lang
stringclasses 2
values | license
stringclasses 13
values | stderr
stringlengths 0
343
| commit
stringlengths 40
40
| returncode
int64 0
128
| repos
stringlengths 6
87.7k
| new_contents
stringlengths 0
6.23M
| new_file
stringlengths 3
311
| old_contents
stringlengths 0
6.23M
| message
stringlengths 6
9.1k
| old_file
stringlengths 3
311
| subject
stringlengths 0
4k
| git_diff
stringlengths 0
6.31M
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
JavaScript
|
mit
|
3cf83e962f4cfcdaac3624a196f5049554d82586
| 0 |
bluetech/ng-annotate-patched
|
// traverse.js
// MIT licensed, see LICENSE file
const walk = require("acorn/dist/walk");
module.exports = function traverse(rootNode, options) {
const ancestors = [];
(function c(node, st, override) {
const parent = ancestors[ancestors.length - 1];
const isNew = node !== parent;
if (options.pre && isNew) options.pre(node, parent);
if (isNew) ancestors.push(node);
walk.base[override || node.type](node, st, c);
if (isNew) ancestors.pop();
if (options.post && isNew) options.post(node, parent);
})(rootNode);
};
|
src/traverse.js
|
// traverse.js
// MIT licensed, see LICENSE file
const walk = require("acorn/dist/walk");
function traverse(rootNode, options) {
const ancestors = [];
(function c(node, st, override) {
const parent = ancestors[ancestors.length - 1];
const isNew = node != parent;
if (options.pre && isNew) options.pre(node, parent);
if (isNew) ancestors.push(node);
walk.base[override || node.type](node, st, c);
if (isNew) ancestors.pop();
if (options.post && isNew) options.post(node, parent);
})(rootNode);
}
module.exports = traverse;
|
Fix != -> !== in traverse.js
|
src/traverse.js
|
Fix != -> !== in traverse.js
|
<ide><path>rc/traverse.js
<ide>
<ide> const walk = require("acorn/dist/walk");
<ide>
<del>function traverse(rootNode, options) {
<add>module.exports = function traverse(rootNode, options) {
<ide> const ancestors = [];
<ide> (function c(node, st, override) {
<ide> const parent = ancestors[ancestors.length - 1];
<del> const isNew = node != parent;
<add> const isNew = node !== parent;
<ide> if (options.pre && isNew) options.pre(node, parent);
<ide> if (isNew) ancestors.push(node);
<ide> walk.base[override || node.type](node, st, c);
<ide> if (isNew) ancestors.pop();
<ide> if (options.post && isNew) options.post(node, parent);
<ide> })(rootNode);
<del>}
<del>
<del>module.exports = traverse;
<add>};
|
|
Java
|
mit
|
8f8e250fcb2c1d987c068bebf9b2cd401a45af45
| 0 |
FRC1458/turtleshell,FRC1458/turtleshell,FRC1458/turtleshell,FRC1458/turtleshell,FRC1458/turtleshell,FRC1458/turtleshell
|
package org.usfirst.frc.team1458.robot.autonomous;
import com.team1458.turtleshell2.core.SampleAutoMode;
import com.team1458.turtleshell2.movement.TankDrive;
import com.team1458.turtleshell2.sensor.TurtleNavX;
import com.team1458.turtleshell2.util.Logger;
import com.team1458.turtleshell2.util.types.Distance;
import com.team1458.turtleshell2.util.types.MotorValue;
import edu.wpi.first.wpilibj.RobotState;
import edu.wpi.first.wpilibj.Timer;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
/**
* This autonomous program will make the robot cross the baseline and nothing else.
* The robot must start against the alliance station wall, facing the airship.
*
* @author asinghani
*/
public class CrossBaseline extends SampleAutoMode {
public CrossBaseline(TankDrive chassis, Logger logger, TurtleNavX navX) {
super(chassis, logger, navX.getYawAxis());
}
// places middle gear
/**
* Runs the autonomous program.
*
* This will drive the robot forward 9.5 feet at 0.8 speed and then 2 feet at 0.3 speed
*/
@Override
public void auto(){
Timer t = new Timer();
t.start();
while (t.get() < 1.0 && RobotState.isAutonomous() && RobotState.isEnabled()) {
chassis.tankDrive(new MotorValue(-.55), new MotorValue(-.55));
System.out.println(t.get() + " " + chassis.getLeftDistance().getInches() + " " +
chassis.getRightDistance().getInches() + " ");
}
while (t.get() < 2.5 && RobotState.isAutonomous() && RobotState.isEnabled()) {
chassis.tankDrive(new MotorValue(-.15),new MotorValue(-.15));
}
chassis.stop();
}
}
|
TurtwigBot/src/org/usfirst/frc/team1458/robot/autonomous/CrossBaseline.java
|
package org.usfirst.frc.team1458.robot.autonomous;
import com.team1458.turtleshell2.core.SampleAutoMode;
import com.team1458.turtleshell2.movement.TankDrive;
import com.team1458.turtleshell2.sensor.TurtleNavX;
import com.team1458.turtleshell2.util.Logger;
import com.team1458.turtleshell2.util.types.Distance;
import com.team1458.turtleshell2.util.types.MotorValue;
import edu.wpi.first.wpilibj.RobotState;
import edu.wpi.first.wpilibj.Timer;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
/**
* This autonomous program will make the robot cross the baseline and nothing else.
* The robot must start against the alliance station wall, facing the airship.
*
* @author asinghani
*/
public class CrossBaseline extends SampleAutoMode {
public CrossBaseline(TankDrive chassis, Logger logger, TurtleNavX navX) {
super(chassis, logger, navX.getYawAxis());
}
// places middle gear
/**
* Runs the autonomous program.
*
* This will drive the robot forward 9.5 feet at 0.8 speed and then 2 feet at 0.3 speed
*/
@Override
public void auto(){
Timer t = new Timer();
t.start();
while (t.get() < 1.0 && RobotState.isAutonomous() && RobotState.isEnabled()) {
chassis.tankDrive(new MotorValue(-.55), new MotorValue(-.55));
System.out.println(t.get() + " " + chassis.getLeftDistance().getInches() + " " +
chassis.getRightDistance().getInches() + " ");
}
while (t.get() < 2.0 && RobotState.isAutonomous() && RobotState.isEnabled()) {
chassis.stop();
}
chassis.stop();
}
}
|
Making go at 15 percent to deal with bounceback
|
TurtwigBot/src/org/usfirst/frc/team1458/robot/autonomous/CrossBaseline.java
|
Making go at 15 percent to deal with bounceback
|
<ide><path>urtwigBot/src/org/usfirst/frc/team1458/robot/autonomous/CrossBaseline.java
<ide> System.out.println(t.get() + " " + chassis.getLeftDistance().getInches() + " " +
<ide> chassis.getRightDistance().getInches() + " ");
<ide> }
<del> while (t.get() < 2.0 && RobotState.isAutonomous() && RobotState.isEnabled()) {
<del> chassis.stop();
<add> while (t.get() < 2.5 && RobotState.isAutonomous() && RobotState.isEnabled()) {
<add> chassis.tankDrive(new MotorValue(-.15),new MotorValue(-.15));
<ide> }
<ide> chassis.stop();
<ide> }
|
|
Java
|
apache-2.0
|
35f67692dfca5a556536cfcef146a05a33956ad5
| 0 |
alexvasilkov/GestureViews
|
package com.alexvasilkov.gestures.sample.adapters;
import android.support.v7.widget.RecyclerView;
import android.view.View;
public abstract class EndlessRecyclerAdapter<VH extends RecyclerView.ViewHolder>
extends RecyclerView.Adapter<VH> {
private final RecyclerView.OnScrollListener scrollListener =
new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
loadNextItemsIfNeeded(recyclerView);
}
};
private boolean isLoading;
private boolean isError;
private LoaderCallbacks callbacks;
private int loadingOffset = 0;
final boolean isLoading() {
return isLoading;
}
final boolean isError() {
return isError;
}
public void setCallbacks(LoaderCallbacks callbacks) {
this.callbacks = callbacks;
}
public void setLoadingOffset(int loadingOffset) {
this.loadingOffset = loadingOffset;
}
private void loadNextItems() {
if (!isLoading && !isError && callbacks != null && callbacks.canLoadNextItems()) {
isLoading = true;
onLoadingStateChanged();
callbacks.loadNextItems();
}
}
void reloadNextItemsIfError() {
if (isError) {
isError = false;
onLoadingStateChanged();
loadNextItems();
}
}
public void onNextItemsLoaded() {
if (isLoading) {
isLoading = false;
isError = false;
onLoadingStateChanged();
}
}
public void onNextItemsError() {
if (isLoading) {
isLoading = false;
isError = true;
onLoadingStateChanged();
}
}
protected void onLoadingStateChanged() {
// No-default-op
}
private void loadNextItemsIfNeeded(RecyclerView recyclerView) {
if (!isLoading && !isError) {
View lastVisibleChild = recyclerView.getChildAt(recyclerView.getChildCount() - 1);
int lastVisiblePos = recyclerView.getChildAdapterPosition(lastVisibleChild);
int total = getItemCount();
if (lastVisiblePos >= total - loadingOffset) {
// We need to use runnable, since recycler view does not like when we are notifying
// about changes during scroll callback.
recyclerView.post(new Runnable() {
@Override
public void run() {
loadNextItems();
}
});
}
}
}
@Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
recyclerView.addOnScrollListener(scrollListener);
loadNextItemsIfNeeded(recyclerView);
}
@Override
public void onDetachedFromRecyclerView(RecyclerView recyclerView) {
super.onDetachedFromRecyclerView(recyclerView);
recyclerView.removeOnScrollListener(scrollListener);
}
public interface LoaderCallbacks {
boolean canLoadNextItems();
void loadNextItems();
}
}
|
sample/src/main/java/com/alexvasilkov/gestures/sample/adapters/EndlessRecyclerAdapter.java
|
package com.alexvasilkov.gestures.sample.adapters;
import android.support.v7.widget.RecyclerView;
import android.view.View;
public abstract class EndlessRecyclerAdapter<VH extends RecyclerView.ViewHolder>
extends RecyclerView.Adapter<VH> {
private final RecyclerView.OnScrollListener scrollListener =
new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
loadNextItemsIfNeeded(recyclerView);
}
};
private boolean isLoading;
private boolean isError;
private LoaderCallbacks callbacks;
private int loadingOffset = 0;
final boolean isLoading() {
return isLoading;
}
final boolean isError() {
return isError;
}
public void setCallbacks(LoaderCallbacks callbacks) {
this.callbacks = callbacks;
}
public void setLoadingOffset(int loadingOffset) {
this.loadingOffset = loadingOffset;
}
private void loadNextItems() {
if (!isLoading && !isError && callbacks != null && callbacks.canLoadNextItems()) {
isLoading = true;
onLoadingStateChanged();
callbacks.loadNextItems();
}
}
void reloadNextItemsIfError() {
if (isError) {
isError = false;
onLoadingStateChanged();
loadNextItems();
}
}
public void onNextItemsLoaded() {
if (isLoading) {
isLoading = false;
isError = false;
onLoadingStateChanged();
}
}
public void onNextItemsError() {
if (isLoading) {
isLoading = false;
isError = true;
onLoadingStateChanged();
}
}
protected void onLoadingStateChanged() {
// No-default-op
}
private void loadNextItemsIfNeeded(RecyclerView recyclerView) {
if (!isLoading && !isError) {
View lastVisibleChild = recyclerView.getChildAt(recyclerView.getChildCount() - 1);
int lastVisiblePos = recyclerView.getChildAdapterPosition(lastVisibleChild);
int total = getItemCount();
if (lastVisiblePos >= total - loadingOffset) {
loadNextItems();
}
}
}
@Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
recyclerView.addOnScrollListener(scrollListener);
loadNextItemsIfNeeded(recyclerView);
}
@Override
public void onDetachedFromRecyclerView(RecyclerView recyclerView) {
super.onDetachedFromRecyclerView(recyclerView);
recyclerView.removeOnScrollListener(scrollListener);
}
public interface LoaderCallbacks {
boolean canLoadNextItems();
void loadNextItems();
}
}
|
Fixed endless list loading
|
sample/src/main/java/com/alexvasilkov/gestures/sample/adapters/EndlessRecyclerAdapter.java
|
Fixed endless list loading
|
<ide><path>ample/src/main/java/com/alexvasilkov/gestures/sample/adapters/EndlessRecyclerAdapter.java
<ide> int total = getItemCount();
<ide>
<ide> if (lastVisiblePos >= total - loadingOffset) {
<del> loadNextItems();
<add> // We need to use runnable, since recycler view does not like when we are notifying
<add> // about changes during scroll callback.
<add> recyclerView.post(new Runnable() {
<add> @Override
<add> public void run() {
<add> loadNextItems();
<add> }
<add> });
<ide> }
<ide> }
<ide> }
|
|
Java
|
apache-2.0
|
d6bc3f0bc6dab555853722614d8638b400df884b
| 0 |
nebhale/spring-boot,ptahchiev/spring-boot,philwebb/spring-boot,tiarebalbi/spring-boot,olivergierke/spring-boot,RichardCSantana/spring-boot,jvz/spring-boot,jvz/spring-boot,wilkinsona/spring-boot,jayarampradhan/spring-boot,royclarkson/spring-boot,vpavic/spring-boot,vpavic/spring-boot,rweisleder/spring-boot,donhuvy/spring-boot,sebastiankirsch/spring-boot,javyzheng/spring-boot,bjornlindstrom/spring-boot,afroje-reshma/spring-boot-sample,ollie314/spring-boot,eddumelendez/spring-boot,lenicliu/spring-boot,SaravananParthasarathy/SPSDemo,afroje-reshma/spring-boot-sample,felipeg48/spring-boot,isopov/spring-boot,Buzzardo/spring-boot,eddumelendez/spring-boot,dreis2211/spring-boot,kamilszymanski/spring-boot,rweisleder/spring-boot,chrylis/spring-boot,xiaoleiPENG/my-project,aahlenst/spring-boot,lexandro/spring-boot,xiaoleiPENG/my-project,isopov/spring-boot,spring-projects/spring-boot,rweisleder/spring-boot,Nowheresly/spring-boot,habuma/spring-boot,akmaharshi/jenkins,zhanhb/spring-boot,kdvolder/spring-boot,yangdd1205/spring-boot,drumonii/spring-boot,royclarkson/spring-boot,philwebb/spring-boot,brettwooldridge/spring-boot,pvorb/spring-boot,donhuvy/spring-boot,tsachev/spring-boot,herau/spring-boot,htynkn/spring-boot,jbovet/spring-boot,brettwooldridge/spring-boot,aahlenst/spring-boot,joshthornhill/spring-boot,zhanhb/spring-boot,kdvolder/spring-boot,kdvolder/spring-boot,cleverjava/jenkins2-course-spring-boot,dreis2211/spring-boot,nebhale/spring-boot,vpavic/spring-boot,donhuvy/spring-boot,aahlenst/spring-boot,jxblum/spring-boot,SaravananParthasarathy/SPSDemo,bbrouwer/spring-boot,minmay/spring-boot,thomasdarimont/spring-boot,tiarebalbi/spring-boot,pvorb/spring-boot,eddumelendez/spring-boot,DeezCashews/spring-boot,bjornlindstrom/spring-boot,jxblum/spring-boot,SaravananParthasarathy/SPSDemo,minmay/spring-boot,ilayaperumalg/spring-boot,rajendra-chola/jenkins2-course-spring-boot,eddumelendez/spring-boot,bbrouwer/spring-boot,qerub/spring-boot,mosoft521/spring-boot,xiaoleiPENG/my-project,bjornlindstrom/spring-boot,mbenson/spring-boot,pvorb/spring-boot,scottfrederick/spring-boot,qerub/spring-boot,philwebb/spring-boot-concourse,htynkn/spring-boot,jmnarloch/spring-boot,shakuzen/spring-boot,minmay/spring-boot,xiaoleiPENG/my-project,michael-simons/spring-boot,i007422/jenkins2-course-spring-boot,brettwooldridge/spring-boot,yhj630520/spring-boot,candrews/spring-boot,joshiste/spring-boot,akmaharshi/jenkins,lenicliu/spring-boot,felipeg48/spring-boot,lburgazzoli/spring-boot,donhuvy/spring-boot,mbenson/spring-boot,hqrt/jenkins2-course-spring-boot,thomasdarimont/spring-boot,isopov/spring-boot,deki/spring-boot,NetoDevel/spring-boot,philwebb/spring-boot,ptahchiev/spring-boot,spring-projects/spring-boot,ilayaperumalg/spring-boot,candrews/spring-boot,mbogoevici/spring-boot,shakuzen/spring-boot,donhuvy/spring-boot,drumonii/spring-boot,lenicliu/spring-boot,chrylis/spring-boot,jmnarloch/spring-boot,linead/spring-boot,tsachev/spring-boot,izeye/spring-boot,philwebb/spring-boot-concourse,linead/spring-boot,habuma/spring-boot,jayarampradhan/spring-boot,Buzzardo/spring-boot,joshthornhill/spring-boot,mbogoevici/spring-boot,drumonii/spring-boot,DeezCashews/spring-boot,herau/spring-boot,javyzheng/spring-boot,DeezCashews/spring-boot,yhj630520/spring-boot,izeye/spring-boot,mbenson/spring-boot,ptahchiev/spring-boot,NetoDevel/spring-boot,linead/spring-boot,zhanhb/spring-boot,rajendra-chola/jenkins2-course-spring-boot,philwebb/spring-boot-concourse,olivergierke/spring-boot,candrews/spring-boot,jbovet/spring-boot,habuma/spring-boot,vakninr/spring-boot,scottfrederick/spring-boot,chrylis/spring-boot,ollie314/spring-boot,bbrouwer/spring-boot,ilayaperumalg/spring-boot,ihoneymon/spring-boot,michael-simons/spring-boot,qerub/spring-boot,RichardCSantana/spring-boot,aahlenst/spring-boot,mosoft521/spring-boot,philwebb/spring-boot-concourse,philwebb/spring-boot-concourse,hello2009chen/spring-boot,minmay/spring-boot,sbcoba/spring-boot,nebhale/spring-boot,ilayaperumalg/spring-boot,habuma/spring-boot,candrews/spring-boot,shangyi0102/spring-boot,wilkinsona/spring-boot,jvz/spring-boot,sbcoba/spring-boot,mbenson/spring-boot,dreis2211/spring-boot,Buzzardo/spring-boot,hello2009chen/spring-boot,Nowheresly/spring-boot,bijukunjummen/spring-boot,htynkn/spring-boot,vpavic/spring-boot,dreis2211/spring-boot,i007422/jenkins2-course-spring-boot,vpavic/spring-boot,drumonii/spring-boot,yhj630520/spring-boot,rajendra-chola/jenkins2-course-spring-boot,joshthornhill/spring-boot,minmay/spring-boot,xiaoleiPENG/my-project,ihoneymon/spring-boot,jayarampradhan/spring-boot,lexandro/spring-boot,mosoft521/spring-boot,lburgazzoli/spring-boot,mosoft521/spring-boot,SaravananParthasarathy/SPSDemo,herau/spring-boot,zhanhb/spring-boot,hello2009chen/spring-boot,rweisleder/spring-boot,bbrouwer/spring-boot,sebastiankirsch/spring-boot,javyzheng/spring-boot,kamilszymanski/spring-boot,thomasdarimont/spring-boot,Buzzardo/spring-boot,i007422/jenkins2-course-spring-boot,bijukunjummen/spring-boot,jbovet/spring-boot,habuma/spring-boot,spring-projects/spring-boot,Nowheresly/spring-boot,spring-projects/spring-boot,joshiste/spring-boot,michael-simons/spring-boot,jayarampradhan/spring-boot,lexandro/spring-boot,jbovet/spring-boot,mdeinum/spring-boot,bclozel/spring-boot,mevasaroj/jenkins2-course-spring-boot,vakninr/spring-boot,sbcoba/spring-boot,jxblum/spring-boot,hqrt/jenkins2-course-spring-boot,pvorb/spring-boot,dreis2211/spring-boot,jayarampradhan/spring-boot,dreis2211/spring-boot,Buzzardo/spring-boot,isopov/spring-boot,nebhale/spring-boot,isopov/spring-boot,NetoDevel/spring-boot,lenicliu/spring-boot,shangyi0102/spring-boot,zhanhb/spring-boot,Buzzardo/spring-boot,bclozel/spring-boot,cleverjava/jenkins2-course-spring-boot,jmnarloch/spring-boot,jvz/spring-boot,lucassaldanha/spring-boot,DeezCashews/spring-boot,kdvolder/spring-boot,cleverjava/jenkins2-course-spring-boot,lburgazzoli/spring-boot,ihoneymon/spring-boot,bclozel/spring-boot,zhanhb/spring-boot,bijukunjummen/spring-boot,felipeg48/spring-boot,jmnarloch/spring-boot,ptahchiev/spring-boot,htynkn/spring-boot,joshthornhill/spring-boot,mdeinum/spring-boot,Nowheresly/spring-boot,bjornlindstrom/spring-boot,lucassaldanha/spring-boot,jxblum/spring-boot,deki/spring-boot,mevasaroj/jenkins2-course-spring-boot,rweisleder/spring-boot,tsachev/spring-boot,rajendra-chola/jenkins2-course-spring-boot,hqrt/jenkins2-course-spring-boot,shakuzen/spring-boot,mdeinum/spring-boot,izeye/spring-boot,jmnarloch/spring-boot,mevasaroj/jenkins2-course-spring-boot,philwebb/spring-boot,ptahchiev/spring-boot,felipeg48/spring-boot,shakuzen/spring-boot,royclarkson/spring-boot,mbogoevici/spring-boot,lucassaldanha/spring-boot,hqrt/jenkins2-course-spring-boot,lexandro/spring-boot,bclozel/spring-boot,tsachev/spring-boot,shakuzen/spring-boot,javyzheng/spring-boot,shakuzen/spring-boot,jbovet/spring-boot,kamilszymanski/spring-boot,chrylis/spring-boot,spring-projects/spring-boot,bijukunjummen/spring-boot,mdeinum/spring-boot,spring-projects/spring-boot,candrews/spring-boot,rweisleder/spring-boot,habuma/spring-boot,bjornlindstrom/spring-boot,jxblum/spring-boot,afroje-reshma/spring-boot-sample,ihoneymon/spring-boot,shangyi0102/spring-boot,mbenson/spring-boot,nebhale/spring-boot,mosoft521/spring-boot,lucassaldanha/spring-boot,vpavic/spring-boot,deki/spring-boot,scottfrederick/spring-boot,olivergierke/spring-boot,ihoneymon/spring-boot,lburgazzoli/spring-boot,izeye/spring-boot,scottfrederick/spring-boot,sebastiankirsch/spring-boot,kamilszymanski/spring-boot,akmaharshi/jenkins,ptahchiev/spring-boot,akmaharshi/jenkins,i007422/jenkins2-course-spring-boot,wilkinsona/spring-boot,felipeg48/spring-boot,yangdd1205/spring-boot,NetoDevel/spring-boot,mdeinum/spring-boot,kdvolder/spring-boot,htynkn/spring-boot,linead/spring-boot,hello2009chen/spring-boot,vakninr/spring-boot,i007422/jenkins2-course-spring-boot,thomasdarimont/spring-boot,mbenson/spring-boot,sebastiankirsch/spring-boot,bclozel/spring-boot,akmaharshi/jenkins,ilayaperumalg/spring-boot,shangyi0102/spring-boot,wilkinsona/spring-boot,ollie314/spring-boot,ollie314/spring-boot,jvz/spring-boot,yhj630520/spring-boot,drumonii/spring-boot,cleverjava/jenkins2-course-spring-boot,tiarebalbi/spring-boot,tsachev/spring-boot,hello2009chen/spring-boot,sebastiankirsch/spring-boot,cleverjava/jenkins2-course-spring-boot,yhj630520/spring-boot,sbcoba/spring-boot,ihoneymon/spring-boot,tiarebalbi/spring-boot,qerub/spring-boot,joshiste/spring-boot,lburgazzoli/spring-boot,shangyi0102/spring-boot,sbcoba/spring-boot,wilkinsona/spring-boot,joshiste/spring-boot,mevasaroj/jenkins2-course-spring-boot,afroje-reshma/spring-boot-sample,michael-simons/spring-boot,scottfrederick/spring-boot,mbogoevici/spring-boot,bbrouwer/spring-boot,mevasaroj/jenkins2-course-spring-boot,thomasdarimont/spring-boot,ilayaperumalg/spring-boot,drumonii/spring-boot,mdeinum/spring-boot,michael-simons/spring-boot,Nowheresly/spring-boot,chrylis/spring-boot,qerub/spring-boot,izeye/spring-boot,htynkn/spring-boot,philwebb/spring-boot,eddumelendez/spring-boot,DeezCashews/spring-boot,royclarkson/spring-boot,SaravananParthasarathy/SPSDemo,jxblum/spring-boot,isopov/spring-boot,afroje-reshma/spring-boot-sample,vakninr/spring-boot,olivergierke/spring-boot,tiarebalbi/spring-boot,herau/spring-boot,aahlenst/spring-boot,philwebb/spring-boot,wilkinsona/spring-boot,lucassaldanha/spring-boot,lexandro/spring-boot,deki/spring-boot,RichardCSantana/spring-boot,javyzheng/spring-boot,mbogoevici/spring-boot,michael-simons/spring-boot,brettwooldridge/spring-boot,rajendra-chola/jenkins2-course-spring-boot,pvorb/spring-boot,bijukunjummen/spring-boot,linead/spring-boot,chrylis/spring-boot,kamilszymanski/spring-boot,RichardCSantana/spring-boot,kdvolder/spring-boot,bclozel/spring-boot,deki/spring-boot,olivergierke/spring-boot,felipeg48/spring-boot,joshiste/spring-boot,brettwooldridge/spring-boot,RichardCSantana/spring-boot,tiarebalbi/spring-boot,hqrt/jenkins2-course-spring-boot,lenicliu/spring-boot,scottfrederick/spring-boot,tsachev/spring-boot,eddumelendez/spring-boot,joshthornhill/spring-boot,yangdd1205/spring-boot,royclarkson/spring-boot,NetoDevel/spring-boot,aahlenst/spring-boot,joshiste/spring-boot,ollie314/spring-boot,herau/spring-boot,vakninr/spring-boot,donhuvy/spring-boot
|
/*
* Copyright 2012-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.autoconfigure.info;
import java.util.Map;
import org.junit.After;
import org.junit.Test;
import org.springframework.boot.autoconfigure.PropertyPlaceholderAutoConfiguration;
import org.springframework.boot.test.EnvironmentTestUtils;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link ProjectInfoAutoConfiguration}.
*
* @author Stephane Nicoll
*/
public class ProjectInfoAutoConfigurationTests {
private AnnotationConfigApplicationContext context;
@After
public void close() {
if (this.context != null) {
this.context.close();
}
}
@Test
public void gitInfoUnavailableIfResourceNotAvailable() {
load();
Map<String, GitInfo> beans = this.context.getBeansOfType(GitInfo.class);
assertThat(beans).hasSize(0);
}
@Test
public void gitLocationTakesPrecedenceOverLegacyKey() {
load("spring.info.git.location=classpath:/org/springframework/boot/autoconfigure/info/git.properties",
"spring.git.properties=classpath:/org/springframework/boot/autoconfigure/info/git-no-data.properties");
GitInfo gitInfo = this.context.getBean(GitInfo.class);
assertThat(gitInfo.getBranch()).isNull();
assertThat(gitInfo.getCommit().getId()).isEqualTo("f95038e");
assertThat(gitInfo.getCommit().getTime().getTime()).isEqualTo(1456995720000L);
}
@Test
public void gitLegacyKeyIsUsedAsFallback() {
load("spring.git.properties=classpath:/org/springframework/boot/autoconfigure/info/git-epoch.properties");
GitInfo gitInfo = this.context.getBean(GitInfo.class);
assertThat(gitInfo.getBranch()).isEqualTo("master");
assertThat(gitInfo.getCommit().getId()).isEqualTo("5009933");
assertThat(gitInfo.getCommit().getTime().getTime()).isEqualTo(1457103850000L);
}
@Test
public void gitInfoWithNoData() {
load("spring.info.git.location=classpath:/org/springframework/boot/autoconfigure/info/git-no-data.properties");
GitInfo gitInfo = this.context.getBean(GitInfo.class);
assertThat(gitInfo.getBranch()).isNull();
}
@Test
public void gitInfoFallbackWithGitInfoBean() {
load(CustomGitInfoConfiguration.class,
"spring.info.git.location=classpath:/org/springframework/boot/autoconfigure/info/git.properties");
GitInfo gitInfo = this.context.getBean(GitInfo.class);
assertThat(gitInfo).isSameAs(this.context.getBean("customGitInfo"));
}
private void load(String... environment) {
load(null, environment);
}
private void load(Class<?> config, String... environment) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
if (config != null) {
context.register(config);
}
context.register(PropertyPlaceholderAutoConfiguration.class,
ProjectInfoAutoConfiguration.class);
EnvironmentTestUtils.addEnvironment(context, environment);
context.refresh();
this.context = context;
}
@Configuration
static class CustomGitInfoConfiguration {
@Bean
public GitInfo customGitInfo() {
return new GitInfo();
}
}
}
|
spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/info/ProjectInfoAutoConfigurationTests.java
|
/*
* Copyright 2012-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.autoconfigure.info;
import java.util.Map;
import org.junit.After;
import org.junit.Test;
import org.springframework.boot.autoconfigure.PropertyPlaceholderAutoConfiguration;
import org.springframework.boot.test.EnvironmentTestUtils;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link ProjectInfoAutoConfiguration}.
*
* @author Stephane Nicoll
*/
public class ProjectInfoAutoConfigurationTests {
private AnnotationConfigApplicationContext context;
@After
public void close() {
if (this.context != null) {
this.context.close();
}
}
@Test
public void gitInfoUnavailableIfResourceNotAvailable() {
load();
Map<String, GitInfo> beans = this.context.getBeansOfType(GitInfo.class);
assertThat(beans).hasSize(0);
}
@Test
public void gitLocationTakesPrecedenceOverLegacyKey() {
load("spring.info.git.location=classpath:/org/springframework/boot/autoconfigure/info/git.properties",
"spring.git.properties=classpath:/org/springframework/boot/autoconfigure/info/git-no-data.properties");
GitInfo gitInfo = this.context.getBean(GitInfo.class);
assertThat(gitInfo.getBranch()).isNull();
assertThat(gitInfo.getCommit().getId()).isEqualTo("f95038e");
assertThat(gitInfo.getCommit().getTime()).isEqualTo("2016-03-03T10:02:00+0100");
}
@Test
public void gitLegacyKeyIsUsedAsFallback() {
load("spring.git.properties=classpath:/org/springframework/boot/autoconfigure/info/git-epoch.properties");
GitInfo gitInfo = this.context.getBean(GitInfo.class);
assertThat(gitInfo.getBranch()).isEqualTo("master");
assertThat(gitInfo.getCommit().getId()).isEqualTo("5009933");
assertThat(gitInfo.getCommit().getTime()).isEqualTo("2016-03-04T16:04:10+0100");
}
@Test
public void gitInfoWithNoData() {
load("spring.info.git.location=classpath:/org/springframework/boot/autoconfigure/info/git-no-data.properties");
GitInfo gitInfo = this.context.getBean(GitInfo.class);
assertThat(gitInfo.getBranch()).isNull();
}
@Test
public void gitInfoFallbackWithGitInfoBean() {
load(CustomGitInfoConfiguration.class,
"spring.info.git.location=classpath:/org/springframework/boot/autoconfigure/info/git.properties");
GitInfo gitInfo = this.context.getBean(GitInfo.class);
assertThat(gitInfo).isSameAs(this.context.getBean("customGitInfo"));
}
private void load(String... environment) {
load(null, environment);
}
private void load(Class<?> config, String... environment) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
if (config != null) {
context.register(config);
}
context.register(PropertyPlaceholderAutoConfiguration.class,
ProjectInfoAutoConfiguration.class);
EnvironmentTestUtils.addEnvironment(context, environment);
context.refresh();
this.context = context;
}
@Configuration
static class CustomGitInfoConfiguration {
@Bean
public GitInfo customGitInfo() {
return new GitInfo();
}
}
}
|
Fix build
Assert using epoch time
|
spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/info/ProjectInfoAutoConfigurationTests.java
|
Fix build
|
<ide><path>pring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/info/ProjectInfoAutoConfigurationTests.java
<ide> GitInfo gitInfo = this.context.getBean(GitInfo.class);
<ide> assertThat(gitInfo.getBranch()).isNull();
<ide> assertThat(gitInfo.getCommit().getId()).isEqualTo("f95038e");
<del> assertThat(gitInfo.getCommit().getTime()).isEqualTo("2016-03-03T10:02:00+0100");
<add> assertThat(gitInfo.getCommit().getTime().getTime()).isEqualTo(1456995720000L);
<ide> }
<ide>
<ide> @Test
<ide> GitInfo gitInfo = this.context.getBean(GitInfo.class);
<ide> assertThat(gitInfo.getBranch()).isEqualTo("master");
<ide> assertThat(gitInfo.getCommit().getId()).isEqualTo("5009933");
<del> assertThat(gitInfo.getCommit().getTime()).isEqualTo("2016-03-04T16:04:10+0100");
<add> assertThat(gitInfo.getCommit().getTime().getTime()).isEqualTo(1457103850000L);
<ide> }
<ide>
<ide> @Test
|
|
Java
|
apache-2.0
|
ebefe4c9bfbfd5d2bb9cc5b5e2645a9082e55ce1
| 0 |
InMobi/elephant-bird,nvoron23/elephant-bird,skinzer/elephant-bird,twitter/elephant-bird,xizhououyang/elephant-bird,twitter/elephant-bird,qubole/elephant-bird,wicknicks/elephant-bird,EugenCepoi/elephant-bird,rubanm/elephant-bird,rangadi/elephant-bird,RainyWang103/elephant-bird,airbnb/elephant-bird,laurentgo/elephant-bird,canojim/elephant-bird,saurfang/elephant-bird,EugenCepoi/elephant-bird,rubanm/elephant-bird
|
package com.twitter.elephantbird.mapred.input;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import com.twitter.elephantbird.mapreduce.input.LzoTextInputFormat;
public class DeprecatedLzoTextInputFormat extends DeprecatedInputFormatWrapper<LongWritable, Text> {
public DeprecatedLzoTextInputFormat() {
super(new LzoTextInputFormat());
}
}
|
src/java/com/twitter/elephantbird/mapred/input/DeprecatedLzoTextInputFormat.java
|
package com.twitter.elephantbird.mapred.input;
import java.io.IOException;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapred.FileSplit;
import org.apache.hadoop.mapred.InputSplit;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapred.RecordReader;
import org.apache.hadoop.mapred.Reporter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A copy of the TextInputFormat class for use with LZO-encoded data. Should be
* identical to TextInputFormat in use.
*
* This class conforms to the old (org.apache.hadoop.mapred.*) hadoop API style
* which is deprecated but still required in places. Streaming, for example,
* does a check that the given input format is a descendant of
* org.apache.hadoop.mapred.InputFormat, which any InputFormat-derived class
* from the new API fails.
*/
@SuppressWarnings("deprecation")
public class DeprecatedLzoTextInputFormat extends DeprecatedLzoInputFormat<LongWritable, Text> {
private static final Logger LOG = LoggerFactory.getLogger(DeprecatedLzoInputFormat.class);
@Override
public RecordReader<LongWritable, Text> getRecordReader(InputSplit split,
JobConf conf, Reporter reporter) throws IOException {
reporter.setStatus(split.toString());
LOG.info(split.toString());
return new DeprecatedLzoLineRecordReader(conf, (FileSplit)split);
}
}
|
DeprecatedLzoTextInputFormat reuses non-deprecated
version using the wrapper.
|
src/java/com/twitter/elephantbird/mapred/input/DeprecatedLzoTextInputFormat.java
|
DeprecatedLzoTextInputFormat reuses non-deprecated version using the wrapper.
|
<ide><path>rc/java/com/twitter/elephantbird/mapred/input/DeprecatedLzoTextInputFormat.java
<ide> package com.twitter.elephantbird.mapred.input;
<del>
<del>import java.io.IOException;
<ide>
<ide> import org.apache.hadoop.io.LongWritable;
<ide> import org.apache.hadoop.io.Text;
<del>import org.apache.hadoop.mapred.FileSplit;
<del>import org.apache.hadoop.mapred.InputSplit;
<del>import org.apache.hadoop.mapred.JobConf;
<del>import org.apache.hadoop.mapred.RecordReader;
<del>import org.apache.hadoop.mapred.Reporter;
<ide>
<del>import org.slf4j.Logger;
<del>import org.slf4j.LoggerFactory;
<add>import com.twitter.elephantbird.mapreduce.input.LzoTextInputFormat;
<ide>
<del>/**
<del> * A copy of the TextInputFormat class for use with LZO-encoded data. Should be
<del> * identical to TextInputFormat in use.
<del> *
<del> * This class conforms to the old (org.apache.hadoop.mapred.*) hadoop API style
<del> * which is deprecated but still required in places. Streaming, for example,
<del> * does a check that the given input format is a descendant of
<del> * org.apache.hadoop.mapred.InputFormat, which any InputFormat-derived class
<del> * from the new API fails.
<del> */
<del>
<del>@SuppressWarnings("deprecation")
<del>public class DeprecatedLzoTextInputFormat extends DeprecatedLzoInputFormat<LongWritable, Text> {
<del> private static final Logger LOG = LoggerFactory.getLogger(DeprecatedLzoInputFormat.class);
<del> @Override
<del> public RecordReader<LongWritable, Text> getRecordReader(InputSplit split,
<del> JobConf conf, Reporter reporter) throws IOException {
<del> reporter.setStatus(split.toString());
<del> LOG.info(split.toString());
<del> return new DeprecatedLzoLineRecordReader(conf, (FileSplit)split);
<add>public class DeprecatedLzoTextInputFormat extends DeprecatedInputFormatWrapper<LongWritable, Text> {
<add> public DeprecatedLzoTextInputFormat() {
<add> super(new LzoTextInputFormat());
<ide> }
<del>
<ide> }
|
|
Java
|
mit
|
143c694260fdd89124f5bfb9a5481562d52dbff6
| 0 |
Simperium/simperium-android,Simperium/simperium-android
|
/**
* For storing and syncing entities with Simperium. To create a bucket you use
* the Simperium.bucket instance method:
*
* // Initialize simperium
* Simperium simperium = new Simperium(...);
* Bucket notesBucket = simperium.bucket("notes", Note.class);
*
* Simperium creates a Bucket instance that is backed by a Channel. The Channel
* takes care of the network operations by communicating with the WebSocketManager.
*
* TODO: A bucket should be able to be queried: "give me all your entities". This
* potentially needs to be flexible to allow storage mechanisms way to extend how
* things can be queried.
*
* Buckets should also provide a way for other objects to listen for when entities
* get added, updated or removed due to operations coming in from the network.
*
* A bucket should also provide an interface that can listen to local changes so
* that the channel can see when entities are changed on the client and push them
* out to Simperium.
*
*/
package com.simperium.client;
import android.database.Cursor;
import android.database.CursorWrapper;
import com.simperium.SimperiumException;
import com.simperium.client.ObjectCacheProvider.ObjectCache;
import com.simperium.storage.StorageProvider.BucketStore;
import com.simperium.util.JSONDiff;
import com.simperium.util.Logger;
import com.simperium.util.Uuid;
import org.json.JSONObject;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.Executor;
public class Bucket<T extends Syncable> {
public interface Channel {
public Change queueLocalChange(Syncable object);
public Change queueLocalDeletion(Syncable object);
public void log(int level, CharSequence message);
public void start();
public void stop();
public void reset();
}
public interface OnSaveObjectListener<T extends Syncable> {
void onSaveObject(Bucket<T> bucket, T object);
}
public interface OnDeleteObjectListener<T extends Syncable> {
void onDeleteObject(Bucket<T> bucket, T object);
}
public interface OnNetworkChangeListener<T extends Syncable> {
void onChange(Bucket<T> bucket, ChangeType type, String key);
}
public interface Listener<T extends Syncable> extends
OnSaveObjectListener<T>, OnDeleteObjectListener<T>,
OnNetworkChangeListener<T> {
// implements all listener methods
}
public enum ChangeType {
REMOVE, MODIFY, INDEX
}
public static final String TAG="Simperium.Bucket";
// The name used for the Simperium namespace
private String name;
// User provides the access token for authentication
private User user;
// The channel that provides networking and change processing.
private Channel channel;
// For storing the bucket listeners
private Set<OnSaveObjectListener<T>> onSaveListeners =
Collections.synchronizedSet(new HashSet<OnSaveObjectListener<T>>());
private Set<OnDeleteObjectListener<T>> onDeleteListeners =
Collections.synchronizedSet(new HashSet<OnDeleteObjectListener<T>>());
private Set<OnNetworkChangeListener<T>> onChangeListeners =
Collections.synchronizedSet(new HashSet<OnNetworkChangeListener<T>>());
private BucketStore<T> storage;
private BucketSchema<T> schema;
private GhostStorageProvider ghostStore;
private ObjectCache<T> cache;
final private Executor executor;
/**
* Represents a Simperium bucket which is a namespace where an app syncs a user's data
* @param name the name to use for the bucket namespace
* @param user provides a way to namespace data if a different user logs in
*/
public Bucket(Executor executor, String name, BucketSchema<T>schema, User user,
BucketStore<T> storage, GhostStorageProvider ghostStore, ObjectCache<T> cache)
throws BucketNameInvalid {
this.executor = executor;
this.name = name;
this.user = user;
this.storage = storage;
this.ghostStore = ghostStore;
this.schema = schema;
this.cache = cache;
validateBucketName(name);
}
public void log(int level, CharSequence message) {
if (channel == null) return;
channel.log(level, message);
}
public void log(CharSequence message) {
log(ChannelProvider.LOG_VERBOSE, message);
}
/**
* Return the instance of this bucket's schema
*/
public BucketSchema<T> getSchema(){
return schema;
}
/**
* Return the user for this bucket
*/
public User getUser(){
return user;
}
/**
* Cursor for bucket data
*/
public interface ObjectCursor<T extends Syncable> extends Cursor {
/**
* Return the current item's siperium key
*/
public String getSimperiumKey();
/**
* Return the object for the current index in the cursor
*/
public T getObject();
}
private class BucketCursor extends CursorWrapper implements ObjectCursor<T> {
private ObjectCursor<T> cursor;
BucketCursor(ObjectCursor<T> cursor){
super(cursor);
this.cursor = cursor;
}
@Override
public String getSimperiumKey(){
return cursor.getSimperiumKey();
}
@Override
public T getObject(){
String key = getSimperiumKey();
T object = cache.get(key);
if (object != null) {
return object;
}
object = cursor.getObject();
try {
Ghost ghost = ghostStore.getGhost(Bucket.this, key);
object.setGhost(ghost);
} catch (GhostMissingException e) {
object.setGhost(new Ghost(key, 0, new JSONObject()));
}
object.setBucket(Bucket.this);
cache.put(key, object);
return object;
}
}
/**
* Tell the bucket to sync changes.
*/
public void sync(final T object){
executor.execute(new Runnable(){
@Override
public void run(){
Boolean modified = object.isModified();
storage.save(object, schema.indexesFor(object));
channel.queueLocalChange(object);
if (modified){
// Notify listeners that an object has been saved, this was
// triggered locally
notifyOnSaveListeners(object);
}
}
});
}
/**
* Delete the object from the bucket.
*
* @param object the Syncable to remove from the bucket
*/
public void remove(T object){
remove(object, true);
}
/**
* Remove the object from the bucket. If isLocal is true, this will queue
* an operation to sync with the Simperium service.
*
* @param object The Syncable to remove from the bucket
* @param isLocal if the operation originates from this client
*/
private void remove(final T object, final boolean isLocal){
cache.remove(object.getSimperiumKey());
executor.execute(new Runnable() {
@Override
public void run() {
if (isLocal)
channel.queueLocalDeletion(object);
storage.delete(object);
notifyOnDeleteListeners(object);
}
});
}
/**
* Given the key for an object in the bucket, remove it if it exists
*/
private void removeObjectWithKey(String key)
throws BucketObjectMissingException {
T object = get(key);
if (object != null) {
// this will call onObjectRemoved on the listener
remove(object, false);
}
}
/**
* Get the bucket's namespace
* @return (String) bucket's namespace
*/
public String getName(){
return name;
}
public String getRemoteName(){
return schema.getRemoteName();
}
public Boolean hasChangeVersion(){
return ghostStore.hasChangeVersion(this);
}
public Boolean hasChangeVersion(String version){
return ghostStore.hasChangeVersion(this, version);
}
public String getChangeVersion(){
String version = ghostStore.getChangeVersion(this);
if (version == null) {
version = "";
}
return version;
}
public void indexComplete(String changeVersion){
setChangeVersion(changeVersion);
notifyOnNetworkChangeListeners(ChangeType.INDEX);
}
public void setChangeVersion(String version){
ghostStore.setChangeVersion(this, version);
}
// starts tracking the object
/**
* Add an object to the bucket so simperium can start syncing it. Must
* conform to the Diffable interface. So simperium can diff/apply patches.
*
*/
public void add(T object){
if (!object.getBucket().equals(this)) {
object.setBucket(this);
}
}
protected T buildObject(String key, JSONObject properties){
return buildObject(new Ghost(key, 0, properties));
}
protected T buildObject(String key){
return buildObject(key, new JSONObject());
}
protected T buildObject(Ghost ghost){
T object = schema.buildWithDefaults(ghost.getSimperiumKey(), JSONDiff.deepCopy(ghost.getDiffableValue()));
object.setGhost(ghost);
object.setBucket(this);
return object;
}
public int count(){
return count(query());
}
public int count(Query<T> query){
return storage.count(query);
}
/**
* Find all objects
*/
public ObjectCursor<T> allObjects(){
return new BucketCursor(storage.all());
}
/**
* Search using a query
*/
public ObjectCursor<T> searchObjects(Query<T> query){
return new BucketCursor(storage.search(query));
}
/**
* Support cancelation
*/
/**
* Build a query for this object
*/
public Query<T> query(){
return new Query<T>(this);
}
/**
* Get a single object object that matches key
*/
public T get(String key) throws BucketObjectMissingException {
// If the cache has it, return the cached object
T object = cache.get(key);
if (object != null) {
return object;
}
// Datastore constructs the object for us
Ghost ghost = null;
try {
ghost = ghostStore.getGhost(this, key);
} catch (GhostMissingException e) {
throw(new BucketObjectMissingException(String.format("Bucket %s does not have object %s", getName(), key)));
}
object = storage.get(key);
if (object == null) {
throw(new BucketObjectMissingException(String.format("Storage provider for bucket:%s did not have object %s", getName(), key)));
}
Logger.log(TAG, String.format("Fetched ghost for %s %s", key, ghost));
object.setBucket(this);
object.setGhost(ghost);
cache.put(key, object);
return object;
}
/**
* Get an object by its key, should we throw an error if the object isn't
* there?
*/
public T getObject(String uuid) throws BucketObjectMissingException {
return get(uuid);
}
/**
* Returns a new objecty tracked by this bucket
*/
public T newObject(){
try {
return newObject(uuid());
} catch (BucketObjectNameInvalid e) {
throw new RuntimeException();
}
}
/**
* Returns a new object with the given uuid
* return null if the uuid exists?
*/
public T newObject(String key)
throws BucketObjectNameInvalid {
return insertObject(key, new JSONObject());
}
/**
*
*/
public T insertObject(String key, JSONObject properties)
throws BucketObjectNameInvalid {
String name = key.trim();
validateObjectName(name);
T object = buildObject(name, properties);
object.setBucket(this);
Ghost ghost = new Ghost(name, 0, new JSONObject());
object.setGhost(ghost);
ghostStore.saveGhost(this, ghost);
cache.put(name, object);
return object;
}
/**
* Add object from new ghost data, no corresponding change version so this
* came from an index request
*/
protected void addObjectWithGhost(final Ghost ghost){
executor.execute(new Runnable() {
@Override
public void run(){
ghostStore.saveGhost(Bucket.this, ghost);
T object = buildObject(ghost);
addObject(object);
}
});
}
/**
* Update the ghost data
*/
protected void updateObjectWithGhost(final Ghost ghost){
ghostStore.saveGhost(Bucket.this, ghost);
T object = buildObject(ghost);
updateObject(object);
}
protected void updateGhost(final Ghost ghost, final Runnable complete){
executor.execute(new Runnable(){
@Override
public void run() {
// find the object
try {
T object = get(ghost.getSimperiumKey());
if (object.isModified()) {
// TODO: we already have the object, how do we handle if we have modifications?
} else {
updateObjectWithGhost(ghost);
}
} catch (BucketObjectMissingException e) {
// The object doesn't exist, insert the new object
updateObjectWithGhost(ghost);
}
if (complete != null) {
complete.run();
}
}
});
}
protected Ghost getGhost(String key) throws GhostMissingException {
return ghostStore.getGhost(this, key);
}
/**
* Add a new object with corresponding change version
*/
protected void addObject(String changeVersion, T object){
addObject(object);
setChangeVersion(changeVersion);
}
/**
* Adds a new object to the bucket
*/
protected void addObject(T object){
if (object.getGhost() == null) {
object.setGhost(new Ghost(object.getSimperiumKey()));
}
// Allows the storage provider to persist the object
Boolean notifyListeners = true;
if (!object.getBucket().equals(this)) {
notifyListeners = true;
}
object.setBucket(this);
storage.save(object, schema.indexesFor(object));
// notify listeners that an object has been added
}
/**
* Updates an existing object
*/
protected void updateObject(T object){
object.setBucket(this);
storage.save(object, schema.indexesFor(object));
}
/**
*
*/
protected void updateObject(String changeVersion, T object){
updateObject(object);
setChangeVersion(changeVersion);
}
public void addListener(Listener<T> listener){
addOnSaveObjectListener(listener);
addOnDeleteObjectListener(listener);
addOnNetworkChangeListener(listener);
}
public void removeListener(Listener<T> listener){
removeOnSaveObjectListener(listener);
removeOnDeleteObjectListener(listener);
removeOnNetworkChangeListener(listener);
}
public void addOnSaveObjectListener(OnSaveObjectListener<T> listener){
onSaveListeners.add(listener);
}
public void removeOnSaveObjectListener(OnSaveObjectListener<T> listener){
onSaveListeners.remove(listener);
}
public void addOnDeleteObjectListener(OnDeleteObjectListener<T> listener){
onDeleteListeners.add(listener);
}
public void removeOnDeleteObjectListener(OnDeleteObjectListener<T> listener){
onDeleteListeners.remove(listener);
}
public void addOnNetworkChangeListener(OnNetworkChangeListener<T> listener){
onChangeListeners.add(listener);
}
public void removeOnNetworkChangeListener(OnNetworkChangeListener<T> listener){
onChangeListeners.remove(listener);
}
public void notifyOnSaveListeners(T object){
Set<OnSaveObjectListener<T>> notify = new HashSet<OnSaveObjectListener<T>>(onSaveListeners);
Iterator<OnSaveObjectListener<T>> iterator = notify.iterator();
while(iterator.hasNext()) {
OnSaveObjectListener<T> listener = iterator.next();
try {
listener.onSaveObject(this, object);
} catch(Exception e) {
Logger.log(TAG, String.format("Listener failed onSaveObject %s", listener), e);
}
}
}
public void notifyOnDeleteListeners(T object){
Set<OnDeleteObjectListener<T>> notify = new HashSet<OnDeleteObjectListener<T>>(onDeleteListeners);
Iterator<OnDeleteObjectListener<T>> iterator = notify.iterator();
while(iterator.hasNext()) {
OnDeleteObjectListener<T> listener = iterator.next();
try {
listener.onDeleteObject(this, object);
} catch(Exception e) {
Logger.log(TAG, String.format("Listener failed onDeleteObject %s", listener), e);
}
}
}
public void notifyOnNetworkChangeListeners(ChangeType type){
notifyOnNetworkChangeListeners(type, null);
}
public void notifyOnNetworkChangeListeners(ChangeType type, String key){
Set<OnNetworkChangeListener> notify =
new HashSet<OnNetworkChangeListener>(onChangeListeners);
Iterator<OnNetworkChangeListener> iterator = notify.iterator();
while(iterator.hasNext()) {
OnNetworkChangeListener listener = iterator.next();
try {
listener.onChange(this, type, key);
} catch(Exception e) {
Logger.log(TAG, String.format("Listener failed onChange %s", listener), e);
}
}
}
public void setChannel(Channel channel){
this.channel = channel;
}
/**
* Initialize the bucket to start tracking changes.
*/
public void start(){
channel.start();
}
public void stop(){
channel.stop();
}
public void reset(){
storage.reset();
ghostStore.resetBucket(this);
channel.reset();
stop();
// Clear the ghost store
}
/**
* Does bucket have at least the requested version?
*/
public Boolean containsKey(String key){
return ghostStore.hasGhost(this, key);
}
/**
* Ask storage if it has at least the requested version or newer
*/
public Boolean hasKeyVersion(String key, Integer version){
try {
Ghost ghost = ghostStore.getGhost(this, key);
return ghost.getVersion().equals(version);
} catch (GhostMissingException e) {
// we don't have the ghost
return false;
}
}
/**
* Which version of the key do we have
*/
public Integer getKeyVersion(String key) throws GhostMissingException {
Ghost ghost = ghostStore.getGhost(this, key);
return ghost.getVersion();
}
/**
* Submit a Runnable to this Bucket's executor
*/
public void executeAsync(Runnable task){
executor.execute(task);
}
public String uuid(){
String key;
do {
key = Uuid.uuid();
} while(containsKey(key));
return key;
}
public Ghost acknowledgeChange(RemoteChange remoteChange, Change change)
throws RemoteChangeInvalidException {
Ghost ghost = null;
if (!remoteChange.isRemoveOperation()) {
try {
T object = get(remoteChange.getKey());
// apply the diff to the underyling object
ghost = remoteChange.apply(object);
ghostStore.saveGhost(this, ghost);
// update the object's ghost
object.setGhost(ghost);
} catch (BucketObjectMissingException e) {
throw(new RemoteChangeInvalidException(e));
}
} else {
ghostStore.deleteGhost(this, remoteChange.getKey());
}
setChangeVersion(remoteChange.getChangeVersion());
remoteChange.setApplied();
// TODO: remove changes don't need ghosts, need to rethink this a bit
return ghost;
}
public Ghost applyRemoteChange(RemoteChange change)
throws RemoteChangeInvalidException {
Ghost ghost = null;
if (change.isRemoveOperation()) {
try {
removeObjectWithKey(change.getKey());
ghostStore.deleteGhost(this, change.getKey());
} catch (BucketObjectMissingException e) {
throw(new RemoteChangeInvalidException(e));
}
} else {
try {
T object = null;
Boolean isNew = false;
if (change.isAddOperation()) {
object = newObject(change.getKey());
isNew = true;
} else {
object = getObject(change.getKey());
isNew = false;
}
// updates the ghost and sets it on the object
ghost = change.apply(object);
// persist the ghost to storage
ghostStore.saveGhost(this, ghost);
// allow the schema to update the object instance with the new
// data
schema.updateWithDefaults(object, JSONDiff.deepCopy(ghost.getDiffableValue()));
if (isNew) {
addObject(object);
} else {
updateObject(object);
}
} catch(SimperiumException e) {
Logger.log(TAG, String.format("Unable to apply remote change %s", change), e);
throw(new RemoteChangeInvalidException(e));
}
}
setChangeVersion(change.getChangeVersion());
change.setApplied();
ChangeType type = change.isRemoveOperation() ? ChangeType.REMOVE : ChangeType.MODIFY;
notifyOnNetworkChangeListeners(type, change.getKey());
return ghost;
}
static public final String BUCKET_OBJECT_NAME_REGEX = "^[a-zA-Z0-9_\\.\\-%@]{1,256}$";
public static void validateObjectName(String name)
throws BucketObjectNameInvalid {
if (!name.matches(BUCKET_OBJECT_NAME_REGEX)) {
throw new BucketObjectNameInvalid(name);
}
}
static public final String BUCKET_NAME_REGEX = "^[a-zA-Z0-9_\\.\\-%]{1,64}$";
public static void validateBucketName(String name)
throws BucketNameInvalid {
if (!name.matches(BUCKET_NAME_REGEX)) {
throw new BucketNameInvalid(name);
}
}
}
|
Simperium/src/main/java/com/simperium/client/Bucket.java
|
/**
* For storing and syncing entities with Simperium. To create a bucket you use
* the Simperium.bucket instance method:
*
* // Initialize simperium
* Simperium simperium = new Simperium(...);
* Bucket notesBucket = simperium.bucket("notes", Note.class);
*
* Simperium creates a Bucket instance that is backed by a Channel. The Channel
* takes care of the network operations by communicating with the WebSocketManager.
*
* TODO: A bucket should be able to be queried: "give me all your entities". This
* potentially needs to be flexible to allow storage mechanisms way to extend how
* things can be queried.
*
* Buckets should also provide a way for other objects to listen for when entities
* get added, updated or removed due to operations coming in from the network.
*
* A bucket should also provide an interface that can listen to local changes so
* that the channel can see when entities are changed on the client and push them
* out to Simperium.
*
*/
package com.simperium.client;
import android.database.Cursor;
import android.database.CursorWrapper;
import com.simperium.SimperiumException;
import com.simperium.client.ObjectCacheProvider.ObjectCache;
import com.simperium.storage.StorageProvider.BucketStore;
import com.simperium.util.JSONDiff;
import com.simperium.util.Logger;
import com.simperium.util.Uuid;
import org.json.JSONObject;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.Executor;
public class Bucket<T extends Syncable> {
public interface Channel {
public Change queueLocalChange(Syncable object);
public Change queueLocalDeletion(Syncable object);
public void log(int level, CharSequence message);
public void start();
public void stop();
public void reset();
}
public interface OnSaveObjectListener<T extends Syncable> {
void onSaveObject(Bucket<T> bucket, T object);
}
public interface OnDeleteObjectListener<T extends Syncable> {
void onDeleteObject(Bucket<T> bucket, T object);
}
public interface OnNetworkChangeListener<T extends Syncable> {
void onChange(Bucket<T> bucket, ChangeType type, String key);
}
public interface Listener<T extends Syncable> extends
OnSaveObjectListener<T>, OnDeleteObjectListener<T>,
OnNetworkChangeListener<T> {
// implements all listener methods
}
public enum ChangeType {
REMOVE, MODIFY, INDEX
}
public static final String TAG="Simperium.Bucket";
// The name used for the Simperium namespace
private String name;
// User provides the access token for authentication
private User user;
// The channel that provides networking and change processing.
private Channel channel;
// For storing the bucket listeners
private Set<OnSaveObjectListener<T>> onSaveListeners =
Collections.synchronizedSet(new HashSet<OnSaveObjectListener<T>>());
private Set<OnDeleteObjectListener<T>> onDeleteListeners =
Collections.synchronizedSet(new HashSet<OnDeleteObjectListener<T>>());
private Set<OnNetworkChangeListener<T>> onChangeListeners =
Collections.synchronizedSet(new HashSet<OnNetworkChangeListener<T>>());
private BucketStore<T> storage;
private BucketSchema<T> schema;
private GhostStorageProvider ghostStore;
private ObjectCache<T> cache;
final private Executor executor;
/**
* Represents a Simperium bucket which is a namespace where an app syncs a user's data
* @param name the name to use for the bucket namespace
* @param user provides a way to namespace data if a different user logs in
*/
public Bucket(Executor executor, String name, BucketSchema<T>schema, User user,
BucketStore<T> storage, GhostStorageProvider ghostStore, ObjectCache<T> cache)
throws BucketNameInvalid {
this.executor = executor;
this.name = name;
this.user = user;
this.storage = storage;
this.ghostStore = ghostStore;
this.schema = schema;
this.cache = cache;
validateBucketName(name);
}
public void log(int level, CharSequence message) {
if (channel == null) return;
channel.log(level, message);
}
public void log(CharSequence message) {
log(ChannelProvider.LOG_VERBOSE, message);
}
/**
* Return the instance of this bucket's schema
*/
public BucketSchema<T> getSchema(){
return schema;
}
/**
* Return the user for this bucket
*/
public User getUser(){
return user;
}
/**
* Cursor for bucket data
*/
public interface ObjectCursor<T extends Syncable> extends Cursor {
/**
* Return the current item's siperium key
*/
public String getSimperiumKey();
/**
* Return the object for the current index in the cursor
*/
public T getObject();
}
private class BucketCursor extends CursorWrapper implements ObjectCursor<T> {
private ObjectCursor<T> cursor;
BucketCursor(ObjectCursor<T> cursor){
super(cursor);
this.cursor = cursor;
}
@Override
public String getSimperiumKey(){
return cursor.getSimperiumKey();
}
@Override
public T getObject(){
String key = getSimperiumKey();
T object = cache.get(key);
if (object != null) {
return object;
}
object = cursor.getObject();
try {
Ghost ghost = ghostStore.getGhost(Bucket.this, key);
object.setGhost(ghost);
} catch (GhostMissingException e) {
object.setGhost(new Ghost(key, 0, new JSONObject()));
}
object.setBucket(Bucket.this);
cache.put(key, object);
return object;
}
}
/**
* Tell the bucket to sync changes.
*/
public void sync(final T object){
executor.execute(new Runnable(){
@Override
public void run(){
Boolean modified = object.isModified();
storage.save(object, schema.indexesFor(object));
channel.queueLocalChange(object);
if (modified){
// Notify listeners that an object has been saved, this was
// triggered locally
notifyOnSaveListeners(object);
}
}
});
}
/**
* Delete the object from the bucket.
*
* @param object the Syncable to remove from the bucket
*/
public void remove(T object){
remove(object, true);
}
/**
* Remove the object from the bucket. If isLocal is true, this will queue
* an operation to sync with the Simperium service.
*
* @param object The Syncable to remove from the bucket
* @param isLocal if the operation originates from this client
*/
private void remove(final T object, final boolean isLocal){
cache.remove(object.getSimperiumKey());
executor.execute(new Runnable() {
@Override
public void run() {
if (isLocal)
channel.queueLocalDeletion(object);
storage.delete(object);
notifyOnDeleteListeners(object);
}
});
}
/**
* Given the key for an object in the bucket, remove it if it exists
*/
private void removeObjectWithKey(String key)
throws BucketObjectMissingException {
T object = get(key);
if (object != null) {
// this will call onObjectRemoved on the listener
remove(object, false);
}
}
/**
* Get the bucket's namespace
* @return (String) bucket's namespace
*/
public String getName(){
return name;
}
public String getRemoteName(){
return schema.getRemoteName();
}
public Boolean hasChangeVersion(){
return ghostStore.hasChangeVersion(this);
}
public Boolean hasChangeVersion(String version){
return ghostStore.hasChangeVersion(this, version);
}
public String getChangeVersion(){
String version = ghostStore.getChangeVersion(this);
if (version == null) {
version = "";
}
return version;
}
public void indexComplete(String changeVersion){
setChangeVersion(changeVersion);
notifyOnNetworkChangeListeners(ChangeType.INDEX);
}
public void setChangeVersion(String version){
ghostStore.setChangeVersion(this, version);
}
// starts tracking the object
/**
* Add an object to the bucket so simperium can start syncing it. Must
* conform to the Diffable interface. So simperium can diff/apply patches.
*
*/
public void add(T object){
if (!object.getBucket().equals(this)) {
object.setBucket(this);
}
}
protected T buildObject(String key, JSONObject properties){
return buildObject(new Ghost(key, 0, properties));
}
protected T buildObject(String key){
return buildObject(key, new JSONObject());
}
protected T buildObject(Ghost ghost){
T object = schema.buildWithDefaults(ghost.getSimperiumKey(), JSONDiff.deepCopy(ghost.getDiffableValue()));
object.setGhost(ghost);
object.setBucket(this);
return object;
}
public int count(){
return count(query());
}
public int count(Query<T> query){
return storage.count(query);
}
/**
* Find all objects
*/
public ObjectCursor<T> allObjects(){
return new BucketCursor(storage.all());
}
/**
* Search using a query
*/
public ObjectCursor<T> searchObjects(Query<T> query){
return new BucketCursor(storage.search(query));
}
/**
* Support cancelation
*/
/**
* Build a query for this object
*/
public Query<T> query(){
return new Query<T>(this);
}
/**
* Get a single object object that matches key
*/
public T get(String key) throws BucketObjectMissingException {
// If the cache has it, return the cached object
T object = cache.get(key);
if (object != null) {
return object;
}
// Datastore constructs the object for us
Ghost ghost = null;
try {
ghost = ghostStore.getGhost(this, key);
} catch (GhostMissingException e) {
throw(new BucketObjectMissingException(String.format("Bucket %s does not have object %s", getName(), key)));
}
object = storage.get(key);
if (object == null) {
throw(new BucketObjectMissingException(String.format("Storage provider for bucket:%s did not have object %s", getName(), key)));
}
Logger.log(TAG, String.format("Fetched ghost for %s %s", key, ghost));
object.setBucket(this);
object.setGhost(ghost);
cache.put(key, object);
return object;
}
/**
* Get an object by its key, should we throw an error if the object isn't
* there?
*/
public T getObject(String uuid) throws BucketObjectMissingException {
return get(uuid);
}
/**
* Returns a new objecty tracked by this bucket
*/
public T newObject(){
try {
return newObject(uuid());
} catch (BucketObjectNameInvalid e) {
throw new RuntimeException();
}
}
/**
* Returns a new object with the given uuid
* return null if the uuid exists?
*/
public T newObject(String key)
throws BucketObjectNameInvalid {
return insertObject(key, new JSONObject());
}
/**
*
*/
public T insertObject(String key, JSONObject properties)
throws BucketObjectNameInvalid {
String name = key.trim();
validateObjectName(name);
T object = buildObject(name, properties);
object.setBucket(this);
Ghost ghost = new Ghost(name, 0, new JSONObject());
object.setGhost(ghost);
ghostStore.saveGhost(this, ghost);
cache.put(name, object);
return object;
}
/**
* Add object from new ghost data, no corresponding change version so this
* came from an index request
*/
protected void addObjectWithGhost(final Ghost ghost){
executor.execute(new Runnable() {
@Override
public void run(){
ghostStore.saveGhost(Bucket.this, ghost);
T object = buildObject(ghost);
addObject(object);
}
});
}
/**
* Update the ghost data
*/
protected void updateObjectWithGhost(final Ghost ghost){
ghostStore.saveGhost(Bucket.this, ghost);
T object = buildObject(ghost);
updateObject(object);
}
protected void updateGhost(final Ghost ghost, final Runnable complete){
executor.execute(new Runnable(){
@Override
public void run() {
// find the object
try {
T object = get(ghost.getSimperiumKey());
if (object.isModified()) {
// TODO: we already have the object, how do we handle if we have modifications?
} else {
updateObjectWithGhost(ghost);
}
} catch (BucketObjectMissingException e) {
// The object doesn't exist, insert the new object
updateObjectWithGhost(ghost);
}
if (complete != null) {
complete.run();
}
}
});
}
protected Ghost getGhost(String key) throws GhostMissingException {
return ghostStore.getGhost(this, key);
}
/**
* Add a new object with corresponding change version
*/
protected void addObject(String changeVersion, T object){
addObject(object);
setChangeVersion(changeVersion);
}
/**
* Adds a new object to the bucket
*/
protected void addObject(T object){
if (object.getGhost() == null) {
object.setGhost(new Ghost(object.getSimperiumKey()));
}
// Allows the storage provider to persist the object
Boolean notifyListeners = true;
if (!object.getBucket().equals(this)) {
notifyListeners = true;
}
object.setBucket(this);
storage.save(object, schema.indexesFor(object));
// notify listeners that an object has been added
}
/**
* Updates an existing object
*/
protected void updateObject(T object){
object.setBucket(this);
storage.save(object, schema.indexesFor(object));
}
/**
*
*/
protected void updateObject(String changeVersion, T object){
updateObject(object);
setChangeVersion(changeVersion);
}
public void addListener(Listener<T> listener){
addOnSaveObjectListener(listener);
addOnDeleteObjectListener(listener);
addOnNetworkChangeListener(listener);
}
public void removeListener(Listener<T> listener){
removeOnSaveObjectListener(listener);
removeOnDeleteObjectListener(listener);
removeOnNetworkChangeListener(listener);
}
public void addOnSaveObjectListener(OnSaveObjectListener<T> listener){
onSaveListeners.add(listener);
}
public void removeOnSaveObjectListener(OnSaveObjectListener<T> listener){
onSaveListeners.remove(listener);
}
public void addOnDeleteObjectListener(OnDeleteObjectListener<T> listener){
onDeleteListeners.add(listener);
}
public void removeOnDeleteObjectListener(OnDeleteObjectListener<T> listener){
onDeleteListeners.remove(listener);
}
public void addOnNetworkChangeListener(OnNetworkChangeListener<T> listener){
onChangeListeners.add(listener);
}
public void removeOnNetworkChangeListener(OnNetworkChangeListener<T> listener){
onChangeListeners.remove(listener);
}
public void notifyOnSaveListeners(T object){
Set<OnSaveObjectListener<T>> notify = new HashSet<OnSaveObjectListener<T>>(onSaveListeners);
Iterator<OnSaveObjectListener<T>> iterator = notify.iterator();
while(iterator.hasNext()) {
OnSaveObjectListener<T> listener = iterator.next();
try {
listener.onSaveObject(this, object);
} catch(Exception e) {
Logger.log(TAG, String.format("Listener failed onSaveObject %s", listener), e);
}
}
}
public void notifyOnDeleteListeners(T object){
Set<OnDeleteObjectListener<T>> notify = new HashSet<OnDeleteObjectListener<T>>(onDeleteListeners);
Iterator<OnDeleteObjectListener<T>> iterator = notify.iterator();
while(iterator.hasNext()) {
OnDeleteObjectListener<T> listener = iterator.next();
try {
listener.onDeleteObject(this, object);
} catch(Exception e) {
Logger.log(TAG, String.format("Listener failed onDeleteObject %s", listener), e);
}
}
}
public void notifyOnNetworkChangeListeners(ChangeType type){
notifyOnNetworkChangeListeners(type, null);
}
public void notifyOnNetworkChangeListeners(ChangeType type, String key){
Set<OnNetworkChangeListener> notify =
new HashSet<OnNetworkChangeListener>(onChangeListeners);
Iterator<OnNetworkChangeListener> iterator = notify.iterator();
while(iterator.hasNext()) {
OnNetworkChangeListener listener = iterator.next();
try {
listener.onChange(this, type, key);
} catch(Exception e) {
Logger.log(TAG, String.format("Listener failed onChange %s", listener), e);
}
}
}
public void setChannel(Channel channel){
this.channel = channel;
}
/**
* Initialize the bucket to start tracking changes.
*/
public void start(){
channel.start();
}
public void stop(){
channel.stop();
}
public void reset(){
storage.reset();
ghostStore.resetBucket(this);
channel.reset();
stop();
// Clear the ghost store
}
/**
* Does bucket have at least the requested version?
*/
public Boolean containsKey(String key){
return ghostStore.hasGhost(this, key);
}
/**
* Ask storage if it has at least the requested version or newer
*/
public Boolean hasKeyVersion(String key, Integer version){
try {
Ghost ghost = ghostStore.getGhost(this, key);
return ghost.getVersion().equals(version);
} catch (GhostMissingException e) {
// we don't have the ghost
return false;
}
}
/**
* Which version of the key do we have
*/
public Integer getKeyVersion(String key) throws GhostMissingException {
Ghost ghost = ghostStore.getGhost(this, key);
return ghost.getVersion();
}
/**
* Submit a Runnable to this Bucket's executor
*/
public void executeAsync(Runnable task){
executor.execute(task);
}
public String uuid(){
String key;
do {
key = Uuid.uuid();
} while(containsKey(key));
return key;
}
public Ghost acknowledgeChange(RemoteChange remoteChange, Change change)
throws RemoteChangeInvalidException {
Ghost ghost = null;
if (!remoteChange.isRemoveOperation()) {
try {
T object = get(remoteChange.getKey());
// apply the diff to the underyling object
ghost = remoteChange.apply(object);
ghostStore.saveGhost(this, ghost);
// update the object's ghost
object.setGhost(ghost);
} catch (BucketObjectMissingException e) {
throw(new RemoteChangeInvalidException(e));
}
} else {
ghostStore.deleteGhost(this, remoteChange.getKey());
}
setChangeVersion(remoteChange.getChangeVersion());
remoteChange.setApplied();
// TODO: remove changes don't need ghosts, need to rethink this a bit
return ghost;
}
public Ghost applyRemoteChange(RemoteChange change)
throws RemoteChangeInvalidException {
Ghost ghost = null;
if (change.isRemoveOperation()) {
try {
removeObjectWithKey(change.getKey());
ghostStore.deleteGhost(this, change.getKey());
} catch (BucketObjectMissingException e) {
throw(new RemoteChangeInvalidException(e));
}
} else {
try {
T object = null;
Boolean isNew = false;
if (change.isAddOperation()) {
object = newObject(change.getKey());
isNew = true;
} else {
object = getObject(change.getKey());
isNew = false;
}
// updates the ghost and sets it on the object
ghost = change.apply(object);
// persist the ghost to storage
ghostStore.saveGhost(this, ghost);
// allow the schema to update the object instance with the new
// data
schema.updateWithDefaults(object, JSONDiff.deepCopy(ghost.getDiffableValue()));
if (isNew) {
addObject(object);
} else {
updateObject(object);
}
} catch(SimperiumException e) {
Logger.log(TAG, String.format("Unable to apply remote change %s", change), e);
throw(new RemoteChangeInvalidException(e));
}
}
setChangeVersion(change.getChangeVersion());
change.setApplied();
ChangeType type = change.isRemoveOperation() ? ChangeType.REMOVE : ChangeType.MODIFY;
notifyOnNetworkChangeListeners(type, change.getKey());
return ghost;
}
static public final String BUCKET_OBJECT_NAME_REGEX = "^[a-zA-Z0-9_\\.\\-%@]{1,256}$";
public static void validateObjectName(String name)
throws BucketObjectNameInvalid {
if (!name.matches(BUCKET_OBJECT_NAME_REGEX)) {
throw new BucketObjectNameInvalid(name);
}
}
static public final String BUCKET_NAME_REGEX = "^[a-zA-Z0-9_\\.\\-%]{1,64}$";
public static void validateBucketName(String name)
throws BucketNameInvalid {
if (!name.matches(BUCKET_NAME_REGEX)) {
throw new BucketNameInvalid(name);
}
}
}
|
Whitespace fixes
|
Simperium/src/main/java/com/simperium/client/Bucket.java
|
Whitespace fixes
|
<ide><path>imperium/src/main/java/com/simperium/client/Bucket.java
<ide> storage.save(object, schema.indexesFor(object));
<ide> // notify listeners that an object has been added
<ide> }
<add>
<ide> /**
<ide> * Updates an existing object
<ide> */
<ide> object.setBucket(this);
<ide> storage.save(object, schema.indexesFor(object));
<ide> }
<add>
<ide> /**
<ide> *
<ide> */
|
|
Java
|
apache-2.0
|
a59f605a494dde23f097c9046540bf6a2a3a27d8
| 0 |
allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community
|
/*
* Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package git4idea.push;
import com.intellij.dvcs.push.PushSpec;
import com.intellij.dvcs.push.Pusher;
import com.intellij.dvcs.push.VcsPushOptionValue;
import com.intellij.notification.NotificationAction;
import com.intellij.notification.NotificationType;
import com.intellij.notification.NotificationsManager;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vcs.ex.ProjectLevelVcsManagerEx;
import com.intellij.openapi.vcs.update.AbstractCommonUpdateAction;
import com.intellij.openapi.vcs.update.UpdateInfoTree;
import com.intellij.openapi.vcs.update.UpdatedFiles;
import com.intellij.vcs.ViewUpdateInfoNotification;
import git4idea.GitUtil;
import git4idea.GitVcs;
import git4idea.config.GitVcsSettings;
import git4idea.repo.GitRepository;
import git4idea.update.GitUpdateInfoAsLog;
import git4idea.update.HashRange;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Map;
import static com.intellij.openapi.util.text.StringUtil.pluralize;
import static com.intellij.openapi.vcs.update.ActionInfo.UPDATE;
import static git4idea.push.GitPushResultNotification.VIEW_FILES_UPDATED_DURING_THE_PUSH;
import static java.util.Collections.singletonList;
class GitPusher extends Pusher<GitRepository, GitPushSource, GitPushTarget> {
@NotNull private final Project myProject;
@NotNull private final GitVcsSettings mySettings;
@NotNull private final GitPushSupport myPushSupport;
GitPusher(@NotNull Project project, @NotNull GitVcsSettings settings, @NotNull GitPushSupport pushSupport) {
myProject = project;
mySettings = settings;
myPushSupport = pushSupport;
}
@Override
public void push(@NotNull Map<GitRepository, PushSpec<GitPushSource, GitPushTarget>> pushSpecs,
@Nullable VcsPushOptionValue optionValue, boolean force) {
expireExistingErrorsAndWarnings();
GitPushTagMode pushTagMode;
boolean skipHook;
if (optionValue instanceof GitVcsPushOptionValue) {
pushTagMode = ((GitVcsPushOptionValue)optionValue).getPushTagMode();
skipHook = ((GitVcsPushOptionValue)optionValue).isSkipHook();
}
else {
pushTagMode = null;
skipHook = false;
}
mySettings.setPushTagMode(pushTagMode);
GitPushOperation pushOperation = new GitPushOperation(myProject, myPushSupport, pushSpecs, pushTagMode, force, skipHook);
pushAndNotify(myProject, pushOperation);
}
public static void pushAndNotify(@NotNull Project project, @NotNull GitPushOperation pushOperation) {
GitPushResult pushResult = pushOperation.execute();
ApplicationManager.getApplication().invokeLater(() -> {
GitPushResultNotification notification = GitPushResultNotification.create(project, pushResult, pushOperation,
GitUtil.getRepositoryManager(project).moreThanOneRoot());
if (AbstractCommonUpdateAction.showsCustomNotification(singletonList(GitVcs.getInstance(project)))) {
Map<GitRepository, HashRange> updatedRanges = pushResult.getUpdatedRanges();
if (updatedRanges.isEmpty()) {
notification.notify(project);
}
else {
new GitUpdateInfoAsLog(project, updatedRanges,
(updatedFilesNumber, updatedCommitsNumber, filteredCommitsNumber, viewCommits) -> {
String commitsNumber;
if (filteredCommitsNumber == null) {
commitsNumber = String.valueOf(updatedCommitsNumber);
}
else {
commitsNumber = filteredCommitsNumber + " of " + updatedCommitsNumber;
}
String actionText = String.format("View %s %s received during the push", commitsNumber,
pluralize("commit", updatedCommitsNumber));
notification.addAction(NotificationAction.createSimple(actionText, viewCommits));
return notification;
}).buildAndShowNotification();
}
}
else {
UpdatedFiles updatedFiles = pushResult.getUpdatedFiles();
if (!updatedFiles.isEmpty()) {
UpdateInfoTree tree = ProjectLevelVcsManagerEx.getInstanceEx(project).showUpdateProjectInfo(updatedFiles, "Update", UPDATE, false);
if (tree != null) {
tree.setBefore(pushResult.getBeforeUpdateLabel());
tree.setAfter(pushResult.getAfterUpdateLabel());
notification.addAction(new ViewUpdateInfoNotification(project, tree, VIEW_FILES_UPDATED_DURING_THE_PUSH, notification));
}
}
notification.notify(project);
}
});
}
protected void expireExistingErrorsAndWarnings() {
GitPushResultNotification[] existingNotifications =
NotificationsManager.getNotificationsManager().getNotificationsOfType(GitPushResultNotification.class, myProject);
for (GitPushResultNotification notification : existingNotifications) {
if (notification.getType() != NotificationType.INFORMATION) {
notification.expire();
}
}
}
}
|
plugins/git4idea/src/git4idea/push/GitPusher.java
|
/*
* Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package git4idea.push;
import com.intellij.dvcs.push.PushSpec;
import com.intellij.dvcs.push.Pusher;
import com.intellij.dvcs.push.VcsPushOptionValue;
import com.intellij.notification.NotificationAction;
import com.intellij.notification.NotificationType;
import com.intellij.notification.NotificationsManager;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vcs.ex.ProjectLevelVcsManagerEx;
import com.intellij.openapi.vcs.update.AbstractCommonUpdateAction;
import com.intellij.openapi.vcs.update.UpdateInfoTree;
import com.intellij.openapi.vcs.update.UpdatedFiles;
import com.intellij.vcs.ViewUpdateInfoNotification;
import git4idea.GitUtil;
import git4idea.GitVcs;
import git4idea.config.GitVcsSettings;
import git4idea.repo.GitRepository;
import git4idea.update.GitUpdateInfoAsLog;
import git4idea.update.HashRange;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Map;
import static com.intellij.openapi.util.text.StringUtil.pluralize;
import static com.intellij.openapi.vcs.update.ActionInfo.UPDATE;
import static git4idea.push.GitPushResultNotification.VIEW_FILES_UPDATED_DURING_THE_PUSH;
import static java.util.Collections.singletonList;
class GitPusher extends Pusher<GitRepository, GitPushSource, GitPushTarget> {
@NotNull private final Project myProject;
@NotNull private final GitVcsSettings mySettings;
@NotNull private final GitPushSupport myPushSupport;
GitPusher(@NotNull Project project, @NotNull GitVcsSettings settings, @NotNull GitPushSupport pushSupport) {
myProject = project;
mySettings = settings;
myPushSupport = pushSupport;
}
@Override
public void push(@NotNull Map<GitRepository, PushSpec<GitPushSource, GitPushTarget>> pushSpecs,
@Nullable VcsPushOptionValue optionValue, boolean force) {
expireExistingErrorsAndWarnings();
GitPushTagMode pushTagMode;
boolean skipHook;
if (optionValue instanceof GitVcsPushOptionValue) {
pushTagMode = ((GitVcsPushOptionValue)optionValue).getPushTagMode();
skipHook = ((GitVcsPushOptionValue)optionValue).isSkipHook();
}
else {
pushTagMode = null;
skipHook = false;
}
mySettings.setPushTagMode(pushTagMode);
GitPushOperation pushOperation = new GitPushOperation(myProject, myPushSupport, pushSpecs, pushTagMode, force, skipHook);
pushAndNotify(myProject, pushOperation);
}
public static void pushAndNotify(@NotNull Project project, @NotNull GitPushOperation pushOperation) {
GitPushResult pushResult = pushOperation.execute();
ApplicationManager.getApplication().invokeLater(() -> {
GitPushResultNotification notification = GitPushResultNotification.create(project, pushResult, pushOperation,
GitUtil.getRepositoryManager(project).moreThanOneRoot());
if (AbstractCommonUpdateAction.showsCustomNotification(singletonList(GitVcs.getInstance(project)))) {
Map<GitRepository, HashRange> updatedRanges = pushResult.getUpdatedRanges();
if (updatedRanges.isEmpty()) {
notification.notify(project);
}
else {
new GitUpdateInfoAsLog(project, updatedRanges,
(updatedFilesNumber, updatedCommitsNumber, filteredCommitsNumber, viewCommits) -> {
String commitsNumber;
if (filteredCommitsNumber == null) {
commitsNumber = String.valueOf(updatedCommitsNumber);
}
else {
commitsNumber = filteredCommitsNumber + " of " + updatedCommitsNumber;
}
String actionText = String.format("View %s %s updated during the push", commitsNumber,
pluralize("commit", updatedCommitsNumber));
notification.addAction(NotificationAction.createSimple(actionText, viewCommits));
return notification;
}).buildAndShowNotification();
}
}
else {
UpdatedFiles updatedFiles = pushResult.getUpdatedFiles();
if (!updatedFiles.isEmpty()) {
UpdateInfoTree tree = ProjectLevelVcsManagerEx.getInstanceEx(project).showUpdateProjectInfo(updatedFiles, "Update", UPDATE, false);
if (tree != null) {
tree.setBefore(pushResult.getBeforeUpdateLabel());
tree.setAfter(pushResult.getAfterUpdateLabel());
notification.addAction(new ViewUpdateInfoNotification(project, tree, VIEW_FILES_UPDATED_DURING_THE_PUSH, notification));
}
}
notification.notify(project);
}
});
}
protected void expireExistingErrorsAndWarnings() {
GitPushResultNotification[] existingNotifications =
NotificationsManager.getNotificationsManager().getNotificationsOfType(GitPushResultNotification.class, myProject);
for (GitPushResultNotification notification : existingNotifications) {
if (notification.getType() != NotificationType.INFORMATION) {
notification.expire();
}
}
}
}
|
git: fix notification text for update after rejected push
Commits were "received", not "updated" (as it was previously for files).
GitOrigin-RevId: 1022518c4a5d582d7782482ba6da345c10bc3458
|
plugins/git4idea/src/git4idea/push/GitPusher.java
|
git: fix notification text for update after rejected push
|
<ide><path>lugins/git4idea/src/git4idea/push/GitPusher.java
<ide> else {
<ide> commitsNumber = filteredCommitsNumber + " of " + updatedCommitsNumber;
<ide> }
<del> String actionText = String.format("View %s %s updated during the push", commitsNumber,
<add> String actionText = String.format("View %s %s received during the push", commitsNumber,
<ide> pluralize("commit", updatedCommitsNumber));
<ide> notification.addAction(NotificationAction.createSimple(actionText, viewCommits));
<ide> return notification;
|
|
JavaScript
|
agpl-3.0
|
ee73865afd3b5fdc919a6fe58dc719f9fbb7e5ec
| 0 |
duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test
|
9ae1bd20-2e63-11e5-9284-b827eb9e62be
|
helloWorld.js
|
9adc1afa-2e63-11e5-9284-b827eb9e62be
|
9ae1bd20-2e63-11e5-9284-b827eb9e62be
|
helloWorld.js
|
9ae1bd20-2e63-11e5-9284-b827eb9e62be
|
<ide><path>elloWorld.js
<del>9adc1afa-2e63-11e5-9284-b827eb9e62be
<add>9ae1bd20-2e63-11e5-9284-b827eb9e62be
|
|
Java
|
apache-2.0
|
b6f6340eb928c6b70e35ad49a5fca61e9aab41c8
| 0 |
jamesagnew/hapi-fhir,Gaduo/hapi-fhir,cementsuf/hapi-fhir,botunge/hapi-fhir,jamesagnew/hapi-fhir,botunge/hapi-fhir,steve1medix/hapi-fhir,shvoidlee/hapi-fhir,cementsuf/hapi-fhir,ismael-sarmento-jr/hapi-fhir,aemay2/hapi-fhir,ismael-sarmento-jr/hapi-fhir,SingingTree/hapi-fhir,jamesagnew/hapi-fhir,cementsuf/hapi-fhir,steve1medix/hapi-fhir,botunge/hapi-fhir,SingingTree/hapi-fhir,eug48/hapi-fhir,eug48/hapi-fhir,shvoidlee/hapi-fhir,shvoidlee/hapi-fhir,cementsuf/hapi-fhir,eug48/hapi-fhir,bjornna/hapi-fhir,jamesagnew/hapi-fhir,SingingTree/hapi-fhir,ismael-sarmento-jr/hapi-fhir,steve1medix/hapi-fhir,Gaduo/hapi-fhir,bjornna/hapi-fhir,Cloudyle/hapi-fhir,ismael-sarmento-jr/hapi-fhir,aemay2/hapi-fhir,botunge/hapi-fhir,aemay2/hapi-fhir,Gaduo/hapi-fhir,SingingTree/hapi-fhir,eug48/hapi-fhir,Cloudyle/hapi-fhir,shvoidlee/hapi-fhir,ismael-sarmento-jr/hapi-fhir,eug48/hapi-fhir,aemay2/hapi-fhir,SingingTree/hapi-fhir,Cloudyle/hapi-fhir,botunge/hapi-fhir,aemay2/hapi-fhir,steve1medix/hapi-fhir,Gaduo/hapi-fhir,steve1medix/hapi-fhir,bjornna/hapi-fhir,bjornna/hapi-fhir,Cloudyle/hapi-fhir,aemay2/hapi-fhir,cementsuf/hapi-fhir,jamesagnew/hapi-fhir,bjornna/hapi-fhir,Gaduo/hapi-fhir,shvoidlee/hapi-fhir,jamesagnew/hapi-fhir,SingingTree/hapi-fhir,Cloudyle/hapi-fhir
|
package ca.uhn.fhir.parser;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.stringContainsInOrder;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.StringReader;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import net.sf.json.JSON;
import net.sf.json.JSONSerializer;
import org.apache.commons.io.IOUtils;
import org.hamcrest.core.IsNot;
import org.hamcrest.core.StringContains;
import org.hamcrest.text.StringContainsInOrder;
import org.hl7.fhir.instance.model.api.IBaseResource;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
import ca.uhn.fhir.context.ConfigurationException;
import ca.uhn.fhir.context.FhirContext;
import ca.uhn.fhir.model.api.Bundle;
import ca.uhn.fhir.model.api.BundleEntry;
import ca.uhn.fhir.model.api.ExtensionDt;
import ca.uhn.fhir.model.api.IResource;
import ca.uhn.fhir.model.api.ResourceMetadataKeyEnum;
import ca.uhn.fhir.model.api.TagList;
import ca.uhn.fhir.model.api.annotation.Child;
import ca.uhn.fhir.model.api.annotation.Extension;
import ca.uhn.fhir.model.api.annotation.ResourceDef;
import ca.uhn.fhir.model.base.composite.BaseNarrativeDt;
import ca.uhn.fhir.model.dstu.composite.AddressDt;
import ca.uhn.fhir.model.dstu.composite.HumanNameDt;
import ca.uhn.fhir.model.dstu.composite.ResourceReferenceDt;
import ca.uhn.fhir.model.dstu.resource.Binary;
import ca.uhn.fhir.model.dstu.resource.Conformance;
import ca.uhn.fhir.model.dstu.resource.Conformance.RestResource;
import ca.uhn.fhir.model.dstu.resource.DiagnosticReport;
import ca.uhn.fhir.model.dstu.resource.ListResource;
import ca.uhn.fhir.model.dstu.resource.Location;
import ca.uhn.fhir.model.dstu.resource.Observation;
import ca.uhn.fhir.model.dstu.resource.Organization;
import ca.uhn.fhir.model.dstu.resource.Patient;
import ca.uhn.fhir.model.dstu.resource.Profile;
import ca.uhn.fhir.model.dstu.resource.Query;
import ca.uhn.fhir.model.dstu.resource.Questionnaire;
import ca.uhn.fhir.model.dstu.resource.Remittance;
import ca.uhn.fhir.model.dstu.resource.Specimen;
import ca.uhn.fhir.model.dstu.resource.ValueSet;
import ca.uhn.fhir.model.dstu.resource.ValueSet.Define;
import ca.uhn.fhir.model.dstu.resource.ValueSet.DefineConcept;
import ca.uhn.fhir.model.dstu.valueset.AddressUseEnum;
import ca.uhn.fhir.model.dstu.valueset.IdentifierUseEnum;
import ca.uhn.fhir.model.dstu.valueset.NarrativeStatusEnum;
import ca.uhn.fhir.model.primitive.DateDt;
import ca.uhn.fhir.model.primitive.DateTimeDt;
import ca.uhn.fhir.model.primitive.DecimalDt;
import ca.uhn.fhir.model.primitive.IdDt;
import ca.uhn.fhir.model.primitive.InstantDt;
import ca.uhn.fhir.model.primitive.StringDt;
import ca.uhn.fhir.model.primitive.XhtmlDt;
import ca.uhn.fhir.narrative.INarrativeGenerator;
public class JsonParserTest {
private static FhirContext ourCtx;
private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(JsonParserTest.class);
private void parseAndEncode(String name) throws IOException {
String msg = IOUtils.toString(XmlParser.class.getResourceAsStream(name));
// ourLog.info(msg);
IParser p = ourCtx.newJsonParser();
Profile res = p.parseResource(Profile.class, msg);
String encoded = ourCtx.newJsonParser().setPrettyPrint(true).encodeResourceToString(res);
// ourLog.info(encoded);
JSON expected = JSONSerializer.toJSON(msg.trim());
JSON actual = JSONSerializer.toJSON(encoded.trim());
String exp = expected.toString().replace("\\r\\n", "\\n"); // .replace("§", "§");
String act = actual.toString().replace("\\r\\n", "\\n");
ourLog.info("Expected: {}", exp);
ourLog.info("Actual : {}", act);
assertEquals(exp, act);
}
@Test
public void testDecimalPrecisionPreserved() {
String number = "52.3779939997090374535378485873776474764643249869328698436986235758587";
Location loc = new Location();
// This is far more precision than is realistic, but let's see if we preserve it
loc.getPosition().setLatitude(new DecimalDt(number));
String encoded = ourCtx.newJsonParser().encodeResourceToString(loc);
Location parsed = ourCtx.newJsonParser().parseResource(Location.class, encoded);
assertEquals(number, parsed.getPosition().getLatitude().getValueAsString());
}
@Test
public void testDecimalPrecisionPreservedInResource() {
Remittance obs = new Remittance();
obs.addService().setRate(new DecimalDt("0.10000"));
String output = ourCtx.newJsonParser().encodeResourceToString(obs);
ourLog.info(output);
assertEquals("{\"resourceType\":\"Remittance\",\"service\":[{\"rate\":0.10000}]}", output);
obs = ourCtx.newJsonParser().parseResource(Remittance.class, output);
assertEquals("0.10000", obs.getService().get(0).getRate().getValueAsString());
}
@Test
public void testParseStringWithNewlineUnencoded() {
Observation obs = new Observation();
obs.setValue(new StringDt("line1\\nline2"));
String output = ourCtx.newJsonParser().encodeResourceToString(obs);
ourLog.info(output);
assertEquals("{\"resourceType\":\"Observation\",\"valueString\":\"line1\\\\nline2\"}", output);
obs = ourCtx.newJsonParser().parseResource(Observation.class, output);
assertEquals("line1\\nline2", ((StringDt)obs.getValue()).getValue());
}
@Test
public void testParseStringWithNewlineEncoded() {
Observation obs = new Observation();
obs.setValue(new StringDt("line1\nline2"));
String output = ourCtx.newJsonParser().encodeResourceToString(obs);
ourLog.info(output);
assertEquals("{\"resourceType\":\"Observation\",\"valueString\":\"line1\\nline2\"}", output);
obs = ourCtx.newJsonParser().parseResource(Observation.class, output);
assertEquals("line1\nline2", ((StringDt)obs.getValue()).getValue());
}
@Test
public void testEncodeAndParseExtensions() throws Exception {
Patient patient = new Patient();
patient.addIdentifier().setUse(IdentifierUseEnum.OFFICIAL).setSystem("urn:example").setValue("7000135");
ExtensionDt ext = new ExtensionDt();
ext.setUrl("http://example.com/extensions#someext");
ext.setValue(new DateTimeDt("2011-01-02T11:13:15"));
patient.addUndeclaredExtension(ext);
ExtensionDt parent = new ExtensionDt().setUrl("http://example.com#parent");
patient.addUndeclaredExtension(parent);
ExtensionDt child1 = new ExtensionDt().setUrl("http://example.com#child").setValue(new StringDt("value1"));
parent.addUndeclaredExtension(child1);
ExtensionDt child2 = new ExtensionDt().setUrl("http://example.com#child").setValue(new StringDt("value2"));
parent.addUndeclaredExtension(child2);
ExtensionDt modExt = new ExtensionDt();
modExt.setUrl("http://example.com/extensions#modext");
modExt.setValue(new DateDt("1995-01-02"));
modExt.setModifier(true);
patient.addUndeclaredExtension(modExt);
HumanNameDt name = patient.addName();
name.addFamily("Blah");
StringDt given = name.addGiven();
given.setValue("Joe");
ExtensionDt ext2 = new ExtensionDt().setUrl("http://examples.com#givenext").setValue(new StringDt("given"));
given.addUndeclaredExtension(ext2);
StringDt given2 = name.addGiven();
given2.setValue("Shmoe");
ExtensionDt given2ext = new ExtensionDt().setUrl("http://examples.com#givenext_parent");
given2.addUndeclaredExtension(given2ext);
given2ext.addUndeclaredExtension(new ExtensionDt().setUrl("http://examples.com#givenext_child").setValue(new StringDt("CHILD")));
String output = ourCtx.newJsonParser().setPrettyPrint(true).encodeResourceToString(patient);
ourLog.info(output);
String enc = ourCtx.newJsonParser().encodeResourceToString(patient);
assertThat(enc, org.hamcrest.Matchers.stringContainsInOrder("{\"resourceType\":\"Patient\",",
"\"extension\":[{\"url\":\"http://example.com/extensions#someext\",\"valueDateTime\":\"2011-01-02T11:13:15\"}",
"{\"url\":\"http://example.com#parent\",\"extension\":[{\"url\":\"http://example.com#child\",\"valueString\":\"value1\"},{\"url\":\"http://example.com#child\",\"valueString\":\"value2\"}]}"));
assertThat(enc, org.hamcrest.Matchers.stringContainsInOrder("\"modifierExtension\":[" + "{" + "\"url\":\"http://example.com/extensions#modext\"," + "\"valueDate\":\"1995-01-02\"" + "}" + "],"));
assertThat(enc,
containsString("\"_given\":[" + "{" + "\"extension\":[" + "{" + "\"url\":\"http://examples.com#givenext\"," + "\"valueString\":\"given\"" + "}" + "]" + "}," + "{" + "\"extension\":[" + "{"
+ "\"url\":\"http://examples.com#givenext_parent\"," + "\"extension\":[" + "{" + "\"url\":\"http://examples.com#givenext_child\"," + "\"valueString\":\"CHILD\"" + "}" + "]" + "}"
+ "]" + "}"));
/*
* Now parse this back
*/
Patient parsed = ourCtx.newJsonParser().parseResource(Patient.class, enc);
ext = parsed.getUndeclaredExtensions().get(0);
assertEquals("http://example.com/extensions#someext", ext.getUrl());
assertEquals("2011-01-02T11:13:15", ((DateTimeDt) ext.getValue()).getValueAsString());
parent = patient.getUndeclaredExtensions().get(1);
assertEquals("http://example.com#parent", parent.getUrl());
assertNull(parent.getValue());
child1 = parent.getExtension().get(0);
assertEquals("http://example.com#child", child1.getUrl());
assertEquals("value1", ((StringDt) child1.getValue()).getValueAsString());
child2 = parent.getExtension().get(1);
assertEquals("http://example.com#child", child2.getUrl());
assertEquals("value2", ((StringDt) child2.getValue()).getValueAsString());
modExt = parsed.getUndeclaredModifierExtensions().get(0);
assertEquals("http://example.com/extensions#modext", modExt.getUrl());
assertEquals("1995-01-02", ((DateDt) modExt.getValue()).getValueAsString());
name = parsed.getName().get(0);
ext2 = name.getGiven().get(0).getUndeclaredExtensions().get(0);
assertEquals("http://examples.com#givenext", ext2.getUrl());
assertEquals("given", ((StringDt) ext2.getValue()).getValueAsString());
given2ext = name.getGiven().get(1).getUndeclaredExtensions().get(0);
assertEquals("http://examples.com#givenext_parent", given2ext.getUrl());
assertNull(given2ext.getValue());
ExtensionDt given2ext2 = given2ext.getExtension().get(0);
assertEquals("http://examples.com#givenext_child", given2ext2.getUrl());
assertEquals("CHILD", ((StringDt) given2ext2.getValue()).getValue());
}
@Test
public void testEncodeBinaryResource() {
Binary patient = new Binary();
patient.setContentType("foo");
patient.setContent(new byte[] { 1, 2, 3, 4 });
String val = ourCtx.newJsonParser().encodeResourceToString(patient);
assertEquals("{\"resourceType\":\"Binary\",\"contentType\":\"foo\",\"content\":\"AQIDBA==\"}", val);
}
@Test
public void testEncodeBundle() throws InterruptedException {
Bundle b = new Bundle();
InstantDt pub = InstantDt.withCurrentTime();
Thread.sleep(2);
Patient p1 = new Patient();
p1.addName().addFamily("Family1");
BundleEntry entry = b.addEntry();
entry.getId().setValue("1");
entry.setResource(p1);
entry.getSummary().setValueAsString("this is the summary");
Patient p2 = new Patient();
p2.addName().addFamily("Family2");
entry = b.addEntry();
entry.getId().setValue("2");
entry.setLinkAlternate(new StringDt("http://foo/bar"));
entry.setResource(p2);
BundleEntry deletedEntry = b.addEntry();
deletedEntry.setId(new IdDt("Patient/3"));
InstantDt nowDt = InstantDt.withCurrentTime();
deletedEntry.setDeleted(nowDt);
String bundleString = ourCtx.newJsonParser().setPrettyPrint(true).encodeBundleToString(b);
ourLog.info(bundleString);
List<String> strings = new ArrayList<String>();
strings.addAll(Arrays.asList("\"id\":\"1\""));
strings.addAll(Arrays.asList("this is the summary"));
strings.addAll(Arrays.asList("\"id\":\"2\"", "\"rel\":\"alternate\"", "\"href\":\"http://foo/bar\""));
strings.addAll(Arrays.asList("\"deleted\":\"" + nowDt.getValueAsString() + "\"", "\"id\":\"Patient/3\""));
assertThat(bundleString, StringContainsInOrder.stringContainsInOrder(strings));
b.getEntries().remove(2);
bundleString = ourCtx.newJsonParser().setPrettyPrint(true).encodeBundleToString(b);
assertThat(bundleString, not(containsString("deleted")));
}
@Test
public void testEncodeBundleCategory() {
Bundle b = new Bundle();
BundleEntry e = b.addEntry();
e.setResource(new Patient());
b.addCategory("scheme", "term", "label");
String val = ourCtx.newJsonParser().setPrettyPrint(false).encodeBundleToString(b);
ourLog.info(val);
assertThat(val, StringContains.containsString("\"category\":[{\"term\":\"term\",\"label\":\"label\",\"scheme\":\"scheme\"}]"));
assertThat(val, not(containsString("text")));
b = ourCtx.newJsonParser().parseBundle(val);
assertEquals(1, b.getEntries().size());
assertEquals(1, b.getCategories().size());
assertEquals("term", b.getCategories().get(0).getTerm());
assertEquals("label", b.getCategories().get(0).getLabel());
assertEquals("scheme", b.getCategories().get(0).getScheme());
assertNull(b.getEntries().get(0).getResource());
}
@Test
public void testEncodeBundleEntryCategory() {
Bundle b = new Bundle();
BundleEntry e = b.addEntry();
e.setResource(new Patient());
e.addCategory("scheme", "term", "label");
String val = ourCtx.newJsonParser().setPrettyPrint(false).encodeBundleToString(b);
ourLog.info(val);
assertThat(val, StringContains.containsString("\"category\":[{\"term\":\"term\",\"label\":\"label\",\"scheme\":\"scheme\"}]"));
b = ourCtx.newJsonParser().parseBundle(val);
assertEquals(1, b.getEntries().size());
assertEquals(1, b.getEntries().get(0).getCategories().size());
assertEquals("term", b.getEntries().get(0).getCategories().get(0).getTerm());
assertEquals("label", b.getEntries().get(0).getCategories().get(0).getLabel());
assertEquals("scheme", b.getEntries().get(0).getCategories().get(0).getScheme());
assertNull(b.getEntries().get(0).getResource());
}
@Test
public void testEncodeContained() {
IParser xmlParser = ourCtx.newJsonParser().setPrettyPrint(true);
// Create an organization, note that the organization does not have an ID
Organization org = new Organization();
org.getName().setValue("Contained Test Organization");
// Create a patient
Patient patient = new Patient();
patient.setId("Patient/1333");
patient.addIdentifier("urn:mrns", "253345");
// Put the organization as a reference in the patient resource
patient.getManagingOrganization().setResource(org);
String encoded = xmlParser.encodeResourceToString(patient);
ourLog.info(encoded);
assertThat(encoded, stringContainsInOrder(Arrays.asList("\"contained\":[", "\"id\":\"1\"", "\"identifier\"", "\"reference\":\"#1\"")));
// Create a bundle with just the patient resource
List<IResource> resources = new ArrayList<IResource>();
resources.add(patient);
Bundle b = Bundle.withResources(resources, ourCtx, "http://example.com/base");
// Encode the bundle
encoded = xmlParser.encodeBundleToString(b);
ourLog.info(encoded);
assertThat(encoded, stringContainsInOrder(Arrays.asList("\"contained\":[", "\"id\":\"1\"", "\"identifier\"", "\"reference\":\"#1\"")));
// Re-parse the bundle
patient = (Patient) xmlParser.parseResource(xmlParser.encodeResourceToString(patient));
assertEquals("#1", patient.getManagingOrganization().getReference().getValue());
assertNotNull(patient.getManagingOrganization().getResource());
org = (Organization) patient.getManagingOrganization().getResource();
assertEquals("#1", org.getId().getValue());
assertEquals("Contained Test Organization", org.getName().getValue());
// And re-encode a second time
encoded = xmlParser.encodeResourceToString(patient);
ourLog.info(encoded);
assertThat(encoded, stringContainsInOrder(Arrays.asList("\"contained\":[", "\"id\":\"1\"", "\"identifier\"", "\"reference\":\"#1\"")));
assertThat(encoded, not(stringContainsInOrder(Arrays.asList("\"contained\":", "[", "\"contained\":"))));
// And re-encode once more, with the references cleared
patient.getContained().getContainedResources().clear();
patient.getManagingOrganization().setReference((IdDt) null);
encoded = xmlParser.encodeResourceToString(patient);
ourLog.info(encoded);
assertThat(encoded, stringContainsInOrder(Arrays.asList("\"contained\":[", "\"id\":\"1\"", "\"identifier\"", "\"reference\":\"#1\"")));
assertThat(encoded, not(stringContainsInOrder(Arrays.asList("\"contained\":", "[", "\"contained\":"))));
// And re-encode once more, with the references cleared and a manually set local ID
patient.getContained().getContainedResources().clear();
patient.getManagingOrganization().setReference((IdDt) null);
patient.getManagingOrganization().getResource().setId(new IdDt("#333"));
encoded = xmlParser.encodeResourceToString(patient);
ourLog.info(encoded);
assertThat(encoded, stringContainsInOrder(Arrays.asList("\"contained\":[", "\"id\":\"333\"", "\"identifier\"", "\"reference\":\"#333\"")));
assertThat(encoded, not(stringContainsInOrder(Arrays.asList("\"contained\":", "[", "\"contained\":"))));
}
@Test
public void testEncodeContained__() {
// Create an organization
Organization org = new Organization();
org.getName().setValue("Contained Test Organization");
// Create a patient
Patient patient = new Patient();
patient.setId("Patient/1333");
patient.addIdentifier("urn:mrns", "253345");
patient.getManagingOrganization().setResource(org);
// Create a bundle with just the patient resource
List<IResource> resources = new ArrayList<IResource>();
resources.add(patient);
Bundle b = Bundle.withResources(resources, ourCtx, "http://example.com/base");
// Encode the buntdle
String encoded = ourCtx.newJsonParser().setPrettyPrint(true).encodeBundleToString(b);
ourLog.info(encoded);
assertThat(encoded, stringContainsInOrder(Arrays.asList("\"contained\"", "resourceType\":\"Organization", "id\":\"1\"")));
assertThat(encoded, containsString("reference\":\"#1\""));
encoded = ourCtx.newJsonParser().setPrettyPrint(true).encodeResourceToString(patient);
ourLog.info(encoded);
assertThat(encoded, stringContainsInOrder(Arrays.asList("\"contained\"", "resourceType\":\"Organization", "id\":\"1\"")));
assertThat(encoded, containsString("reference\":\"#1\""));
}
@Test
public void testEncodeContainedResources() throws IOException {
String msg = IOUtils.toString(XmlParser.class.getResourceAsStream("/contained-diagnosticreport.xml"));
IParser p = ourCtx.newXmlParser();
DiagnosticReport res = p.parseResource(DiagnosticReport.class, msg);
String encoded = ourCtx.newJsonParser().setPrettyPrint(true).encodeResourceToString(res);
ourLog.info(encoded);
}
@Test
public void testEncodeContainedResourcesMore() {
DiagnosticReport rpt = new DiagnosticReport();
Specimen spm = new Specimen();
rpt.getText().setDiv("AAA");
rpt.addSpecimen().setResource(spm);
IParser p = new FhirContext(DiagnosticReport.class).newJsonParser().setPrettyPrint(true);
String str = p.encodeResourceToString(rpt);
ourLog.info(str);
assertThat(str, StringContains.containsString("<div>AAA</div>"));
String substring = "\"reference\":\"#";
assertThat(str, StringContains.containsString(substring));
int idx = str.indexOf(substring) + substring.length();
int idx2 = str.indexOf('"', idx + 1);
String id = str.substring(idx, idx2);
assertThat(str, StringContains.containsString("\"id\":\"" + id + "\""));
assertThat(str, IsNot.not(StringContains.containsString("<?xml version='1.0'?>")));
}
@Test
public void testEncodeContainedWithNarrativeIsSuppresed() {
IParser parser = ourCtx.newJsonParser().setPrettyPrint(true);
// Create an organization, note that the organization does not have an ID
Organization org = new Organization();
org.getName().setValue("Contained Test Organization");
org.getText().setDiv("<div>FOOBAR</div>");
// Create a patient
Patient patient = new Patient();
patient.setId("Patient/1333");
patient.addIdentifier("urn:mrns", "253345");
patient.getText().setDiv("<div>BARFOO</div>");
patient.getManagingOrganization().setResource(org);
String encoded = parser.encodeResourceToString(patient);
ourLog.info(encoded);
assertThat(encoded, not(containsString("FOOBAR")));
assertThat(encoded, (containsString("BARFOO")));
}
@Test
public void testEncodeDeclaredExtensionWithAddressContent() {
IParser parser = ourCtx.newJsonParser();
MyPatientWithOneDeclaredAddressExtension patient = new MyPatientWithOneDeclaredAddressExtension();
patient.addAddress().setUse(AddressUseEnum.HOME);
patient.setFoo(new AddressDt().addLine("line1"));
String val = parser.encodeResourceToString(patient);
ourLog.info(val);
assertThat(val, StringContains.containsString("\"extension\":[{\"url\":\"urn:foo\",\"valueAddress\":{\"line\":[\"line1\"]}}]"));
MyPatientWithOneDeclaredAddressExtension actual = parser.parseResource(MyPatientWithOneDeclaredAddressExtension.class, val);
assertEquals(AddressUseEnum.HOME, patient.getAddressFirstRep().getUse().getValueAsEnum());
AddressDt ref = actual.getFoo();
assertEquals("line1", ref.getLineFirstRep().getValue());
}
@Test
public void testEncodeDeclaredExtensionWithResourceContent() {
IParser parser = ourCtx.newJsonParser();
MyPatientWithOneDeclaredExtension patient = new MyPatientWithOneDeclaredExtension();
patient.addAddress().setUse(AddressUseEnum.HOME);
patient.setFoo(new ResourceReferenceDt("Organization/123"));
String val = parser.encodeResourceToString(patient);
ourLog.info(val);
assertThat(val, StringContains.containsString("\"extension\":[{\"url\":\"urn:foo\",\"valueResource\":{\"reference\":\"Organization/123\"}}]"));
MyPatientWithOneDeclaredExtension actual = parser.parseResource(MyPatientWithOneDeclaredExtension.class, val);
assertEquals(AddressUseEnum.HOME, patient.getAddressFirstRep().getUse().getValueAsEnum());
ResourceReferenceDt ref = actual.getFoo();
assertEquals("Organization/123", ref.getReference().getValue());
}
@Test
public void testEncodeExt() throws Exception {
ValueSet valueSet = new ValueSet();
valueSet.setId("123456");
Define define = valueSet.getDefine();
DefineConcept code = define.addConcept();
code.setCode("someCode");
code.setDisplay("someDisplay");
code.addUndeclaredExtension(false, "urn:alt", new StringDt("alt name"));
String encoded = ourCtx.newJsonParser().encodeResourceToString(valueSet);
ourLog.info(encoded);
assertThat(encoded, not(containsString("123456")));
assertEquals("{\"resourceType\":\"ValueSet\",\"define\":{\"concept\":[{\"extension\":[{\"url\":\"urn:alt\",\"valueString\":\"alt name\"}],\"code\":\"someCode\",\"display\":\"someDisplay\"}]}}",
encoded);
}
@Test
public void testEncodeExtensionInCompositeElement() {
Conformance c = new Conformance();
c.addRest().getSecurity().addUndeclaredExtension(false, "http://foo", new StringDt("AAA"));
String encoded = ourCtx.newJsonParser().setPrettyPrint(true).encodeResourceToString(c);
ourLog.info(encoded);
encoded = ourCtx.newJsonParser().setPrettyPrint(false).encodeResourceToString(c);
ourLog.info(encoded);
assertEquals(encoded, "{\"resourceType\":\"Conformance\",\"rest\":[{\"security\":{\"extension\":[{\"url\":\"http://foo\",\"valueString\":\"AAA\"}]}}]}");
}
@Test
public void testEncodeExtensionInPrimitiveElement() {
Conformance c = new Conformance();
c.getAcceptUnknown().addUndeclaredExtension(false, "http://foo", new StringDt("AAA"));
String encoded = ourCtx.newJsonParser().setPrettyPrint(true).encodeResourceToString(c);
ourLog.info(encoded);
encoded = ourCtx.newJsonParser().setPrettyPrint(false).encodeResourceToString(c);
ourLog.info(encoded);
assertEquals(encoded, "{\"resourceType\":\"Conformance\",\"_acceptUnknown\":{\"extension\":[{\"url\":\"http://foo\",\"valueString\":\"AAA\"}]}}");
// Now with a value
ourLog.info("---------------");
c = new Conformance();
c.getAcceptUnknown().setValue(true);
c.getAcceptUnknown().addUndeclaredExtension(false, "http://foo", new StringDt("AAA"));
encoded = ourCtx.newJsonParser().setPrettyPrint(true).encodeResourceToString(c);
ourLog.info(encoded);
encoded = ourCtx.newJsonParser().setPrettyPrint(false).encodeResourceToString(c);
ourLog.info(encoded);
assertEquals(encoded, "{\"resourceType\":\"Conformance\",\"acceptUnknown\":true,\"_acceptUnknown\":{\"extension\":[{\"url\":\"http://foo\",\"valueString\":\"AAA\"}]}}");
}
@Test
public void testEncodeExtensionInResourceElement() {
Conformance c = new Conformance();
// c.addRest().getSecurity().addUndeclaredExtension(false, "http://foo", new StringDt("AAA"));
c.addUndeclaredExtension(false, "http://foo", new StringDt("AAA"));
String encoded = ourCtx.newJsonParser().setPrettyPrint(true).encodeResourceToString(c);
ourLog.info(encoded);
encoded = ourCtx.newJsonParser().setPrettyPrint(false).encodeResourceToString(c);
ourLog.info(encoded);
assertEquals(encoded, "{\"resourceType\":\"Conformance\",\"extension\":[{\"url\":\"http://foo\",\"valueString\":\"AAA\"}]}");
}
@Test
public void testEncodeExtensionOnEmptyElement() throws Exception {
ValueSet valueSet = new ValueSet();
valueSet.addTelecom().addUndeclaredExtension(false, "http://foo", new StringDt("AAA"));
String encoded = ourCtx.newJsonParser().encodeResourceToString(valueSet);
assertThat(encoded, containsString("\"telecom\":[{\"extension\":[{\"url\":\"http://foo\",\"valueString\":\"AAA\"}]}"));
}
@Test
public void testEncodeExtensionWithResourceContent() {
IParser parser = ourCtx.newJsonParser();
Patient patient = new Patient();
patient.addAddress().setUse(AddressUseEnum.HOME);
patient.addUndeclaredExtension(false, "urn:foo", new ResourceReferenceDt("Organization/123"));
String val = parser.encodeResourceToString(patient);
ourLog.info(val);
assertThat(val, StringContains.containsString("\"extension\":[{\"url\":\"urn:foo\",\"valueResource\":{\"reference\":\"Organization/123\"}}]"));
Patient actual = parser.parseResource(Patient.class, val);
assertEquals(AddressUseEnum.HOME, patient.getAddressFirstRep().getUse().getValueAsEnum());
List<ExtensionDt> ext = actual.getUndeclaredExtensionsByUrl("urn:foo");
assertEquals(1, ext.size());
ResourceReferenceDt ref = (ResourceReferenceDt) ext.get(0).getValue();
assertEquals("Organization/123", ref.getReference().getValue());
}
@Test
public void testEncodeIds() {
Patient pt = new Patient();
pt.addIdentifier("sys", "val");
ListResource list = new ListResource();
list.setId("listId");
list.addEntry().setItem(new ResourceReferenceDt(pt));
String enc = ourCtx.newJsonParser().encodeResourceToString(list);
ourLog.info(enc);
assertThat(enc, containsString("\"id\":\"1\""));
ListResource parsed = ourCtx.newJsonParser().parseResource(ListResource.class, enc);
assertEquals(Patient.class, parsed.getEntryFirstRep().getItem().getResource().getClass());
enc = enc.replace("\"id\"", "\"_id\"");
parsed = ourCtx.newJsonParser().parseResource(ListResource.class, enc);
assertEquals(Patient.class, parsed.getEntryFirstRep().getItem().getResource().getClass());
}
@Test
public void testEncodeInvalidChildGoodException() {
Observation obs = new Observation();
obs.setValue(new DecimalDt(112.22));
IParser p = new FhirContext(Observation.class).newJsonParser();
try {
p.encodeResourceToString(obs);
} catch (DataFormatException e) {
assertThat(e.getMessage(), StringContains.containsString("DecimalDt"));
}
}
@Test
public void testEncodeNarrativeBlockInBundle() {
Patient p = new Patient();
p.addIdentifier("foo", "bar");
p.getText().setStatus(NarrativeStatusEnum.GENERATED);
p.getText().setDiv("<div>hello</div>");
Bundle b = new Bundle();
b.getTotalResults().setValue(123);
b.addEntry().setResource(p);
String out = ourCtx.newJsonParser().setPrettyPrint(true).encodeBundleToString(b);
ourLog.info(out);
assertThat(out, containsString("<div>hello</div>"));
p.getText().setDiv("<xhtml:div xmlns:xhtml=\"http://www.w3.org/1999/xhtml\">hello</xhtml:div>");
out = ourCtx.newJsonParser().setPrettyPrint(true).encodeBundleToString(b);
ourLog.info(out);
// Backslashes need to be escaped because they are in a JSON value
assertThat(out, containsString("<xhtml:div xmlns:xhtml=\\\"http://www.w3.org/1999/xhtml\\\">hello</xhtml:div>"));
}
@Test
public void testEncodeNonContained() {
Organization org = new Organization();
org.setId("Organization/65546");
org.getName().setValue("Contained Test Organization");
Patient patient = new Patient();
patient.setId("Patient/1333");
patient.addIdentifier("urn:mrns", "253345");
patient.getManagingOrganization().setResource(org);
Bundle b = Bundle.withResources(Collections.singletonList((IResource) patient), ourCtx, "http://foo");
String encoded = ourCtx.newJsonParser().setPrettyPrint(true).encodeBundleToString(b);
ourLog.info(encoded);
assertThat(encoded, not(containsString("contained")));
assertThat(encoded, containsString("\"reference\":\"Organization/65546\""));
encoded = ourCtx.newJsonParser().setPrettyPrint(true).encodeResourceToString(patient);
ourLog.info(encoded);
assertThat(encoded, not(containsString("contained")));
assertThat(encoded, containsString("\"reference\":\"Organization/65546\""));
}
@Test
public void testEncodeOmitsVersionAndBase() {
Patient p = new Patient();
p.getManagingOrganization().setReference("http://example.com/base/Patient/1/_history/2");
String enc;
enc = ourCtx.newJsonParser().encodeResourceToString(p);
ourLog.info(enc);
assertThat(enc, containsString("\"http://example.com/base/Patient/1\""));
enc = ourCtx.newJsonParser().setServerBaseUrl("http://example.com/base").encodeResourceToString(p);
ourLog.info(enc);
assertThat(enc, containsString("\"Patient/1\""));
enc = ourCtx.newJsonParser().setServerBaseUrl("http://example.com/base2").encodeResourceToString(p);
ourLog.info(enc);
assertThat(enc, containsString("\"http://example.com/base/Patient/1\""));
}
@Test
public void testEncodeQuery() {
Query q = new Query();
ExtensionDt parameter = q.addParameter();
parameter.setUrl("http://hl7.org/fhir/query#_query").setValue(new StringDt("example"));
String val = ourCtx.newJsonParser().encodeResourceToString(q);
ourLog.info(val);
//@formatter:off
String expected =
"{" +
"\"resourceType\":\"Query\"," +
"\"parameter\":[" +
"{" +
"\"url\":\"http://hl7.org/fhir/query#_query\"," +
"\"valueString\":\"example\"" +
"}" +
"]" +
"}";
//@formatter:on
ourLog.info("Expect: {}", expected);
ourLog.info("Got : {}", val);
assertEquals(expected, val);
}
@Test
public void testEncodeResourceRef() throws DataFormatException {
Patient patient = new Patient();
patient.setManagingOrganization(new ResourceReferenceDt());
IParser p = ourCtx.newJsonParser();
String str = p.encodeResourceToString(patient);
assertThat(str, IsNot.not(StringContains.containsString("managingOrganization")));
patient.setManagingOrganization(new ResourceReferenceDt("Organization/123"));
str = p.encodeResourceToString(patient);
assertThat(str, StringContains.containsString("\"managingOrganization\":{\"reference\":\"Organization/123\"}"));
Organization org = new Organization();
org.addIdentifier().setSystem("foo").setValue("bar");
patient.setManagingOrganization(new ResourceReferenceDt(org));
str = p.encodeResourceToString(patient);
assertThat(str, StringContains.containsString("\"contained\":[{\"resourceType\":\"Organization\""));
}
@Test
public void testEncodeUndeclaredExtensionWithAddressContent() {
IParser parser = ourCtx.newJsonParser();
Patient patient = new Patient();
patient.addAddress().setUse(AddressUseEnum.HOME);
patient.addUndeclaredExtension(false, "urn:foo", new AddressDt().addLine("line1"));
String val = parser.encodeResourceToString(patient);
ourLog.info(val);
assertThat(val, StringContains.containsString("\"extension\":[{\"url\":\"urn:foo\",\"valueAddress\":{\"line\":[\"line1\"]}}]"));
MyPatientWithOneDeclaredAddressExtension actual = parser.parseResource(MyPatientWithOneDeclaredAddressExtension.class, val);
assertEquals(AddressUseEnum.HOME, patient.getAddressFirstRep().getUse().getValueAsEnum());
AddressDt ref = actual.getFoo();
assertEquals("line1", ref.getLineFirstRep().getValue());
}
@Test
public void testEncodingNullExtension() {
Patient p = new Patient();
ExtensionDt extension = new ExtensionDt(false, "http://foo#bar");
p.addUndeclaredExtension(extension);
String str = ourCtx.newJsonParser().encodeResourceToString(p);
assertEquals("{\"resourceType\":\"Patient\"}", str);
extension.setValue(new StringDt());
str = ourCtx.newJsonParser().encodeResourceToString(p);
assertEquals("{\"resourceType\":\"Patient\"}", str);
extension.setValue(new StringDt(""));
str = ourCtx.newJsonParser().encodeResourceToString(p);
assertEquals("{\"resourceType\":\"Patient\"}", str);
}
@Test
public void testExtensionOnComposite() throws Exception {
Patient patient = new Patient();
HumanNameDt name = patient.addName();
name.addFamily().setValue("Shmoe");
HumanNameDt given = name.addGiven("Joe");
ExtensionDt ext2 = new ExtensionDt(false, "http://examples.com#givenext", new StringDt("Hello"));
given.addUndeclaredExtension(ext2);
String enc = ourCtx.newJsonParser().encodeResourceToString(patient);
ourLog.info(enc);
assertEquals("{\"resourceType\":\"Patient\",\"name\":[{\"extension\":[{\"url\":\"http://examples.com#givenext\",\"valueString\":\"Hello\"}],\"family\":[\"Shmoe\"],\"given\":[\"Joe\"]}]}", enc);
IParser newJsonParser = ourCtx.newJsonParser();
StringReader reader = new StringReader(enc);
Patient parsed = newJsonParser.parseResource(Patient.class, reader);
ourLog.info(ourCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(parsed));
assertEquals(1, parsed.getNameFirstRep().getUndeclaredExtensionsByUrl("http://examples.com#givenext").size());
ExtensionDt ext = parsed.getNameFirstRep().getUndeclaredExtensionsByUrl("http://examples.com#givenext").get(0);
assertEquals("Hello", ext.getValueAsPrimitive().getValue());
}
@Test
public void testExtensionOnPrimitive() throws Exception {
Patient patient = new Patient();
HumanNameDt name = patient.addName();
StringDt family = name.addFamily();
family.setValue("Shmoe");
ExtensionDt ext2 = new ExtensionDt(false, "http://examples.com#givenext", new StringDt("Hello"));
family.addUndeclaredExtension(ext2);
String enc = ourCtx.newJsonParser().encodeResourceToString(patient);
ourLog.info(enc);
//@formatter:off
assertThat(enc, containsString(("{\n" +
" \"resourceType\":\"Patient\",\n" +
" \"name\":[\n" +
" {\n" +
" \"family\":[\n" +
" \"Shmoe\"\n" +
" ],\n" +
" \"_family\":[\n" +
" {\n" +
" \"extension\":[\n" +
" {\n" +
" \"url\":\"http://examples.com#givenext\",\n" +
" \"valueString\":\"Hello\"\n" +
" }\n" +
" ]\n" +
" }\n" +
" ]\n" +
" }\n" +
" ]\n" +
"}").replace("\n", "").replaceAll(" +", "")));
//@formatter:on
Patient parsed = ourCtx.newJsonParser().parseResource(Patient.class, new StringReader(enc));
assertEquals(1, parsed.getNameFirstRep().getFamilyFirstRep().getUndeclaredExtensionsByUrl("http://examples.com#givenext").size());
ExtensionDt ext = parsed.getNameFirstRep().getFamilyFirstRep().getUndeclaredExtensionsByUrl("http://examples.com#givenext").get(0);
assertEquals("Hello", ext.getValueAsPrimitive().getValue());
}
/**
* #65
*/
@Test
public void testJsonPrimitiveWithExtensionEncoding() {
String res = "{\"resourceType\":\"Questionnaire\",\"status\":\"draft\",\"authored\":\"2014-10-30T14:15:00\",\"subject\":{\"reference\":\"http://www.hl7.org/fhir/Patient/1\"},\"author\":{\"reference\":\"http://www.hl7.org/fhir/Practitioner/1\"},\"name\":{\"text\":\"WDHB Friends and Family Test\"},\"group\":{\"header\":\"Note: This is an anonymous survey, which means you cannot be identified.\",\"_header\":[{\"extension\":[{\"url\":\"http://hl7.org/fhir/Profile/iso-21090#language\",\"valueCode\":\"en\"},{\"url\":\"http://hl7.org/fhir/Profile/iso-21090#string-translation\",\"valueString\":\"è«\\u008b注æ\\u0084\\u008fï¼\\u009aè¿\\u0099æ\\u0098¯ä¸\\u0080个å\\u008c¿å\\u0090\\u008dè°\\u0083æ\\u009f¥ï¼\\u008c被è°\\u0083æ\\u009f¥äººå°\\u0086ä¸\\u008dä¼\\u009a被è¯\\u0086å\\u0088«å\\u0087ºæ\\u009d¥ã\\u0080\\u0082\"},{\"url\":\"http://hl7.org/fhir/Profile/iso-21090#string-translation\",\"valueString\":\"ì\\u009dµëª\\u0085ì\\u009c¼ë¡\\u009c í\\u0095\\u0098ë\\u008a\\u0094 ì\\u0084¤ë¬¸ì¡°ì\\u0082¬ì\\u009d´ë¯\\u0080ë¡\\u009c ì\\u009e\\u0091ì\\u0084±ì\\u009e\\u0090ê°\\u0080 ë\\u0088\\u0084구ì\\u009d¸ì§\\u0080 ë°\\u009dí\\u0098\\u0080ì§\\u0080ì§\\u0080 ì\\u0095\\u008aì\\u008aµë\\u008b\\u0088ë\\u008b¤.\"}]}],\"question\":[{\"extension\":[{\"url\":\"http://hl7.org/fhir/questionnaire-extensions#answerFormat\",\"valueCode\":\"single-choice\"}],\"text\":\"Are you a patient?\",\"options\":{\"reference\":\"#question1\"}}]}}";
Questionnaire parsed = ourCtx.newJsonParser().parseResource(Questionnaire.class, res);
assertEquals("Note: This is an anonymous survey, which means you cannot be identified.", parsed.getGroup().getHeader().getValue());
assertEquals(1, parsed.getGroup().getHeader().getUndeclaredExtensionsByUrl("http://hl7.org/fhir/Profile/iso-21090#language").size());
String encoded = ourCtx.newJsonParser().setPrettyPrint(true).encodeResourceToString(parsed);
ourLog.info(encoded);
assertThat(encoded, containsString("\"_header\":{"));
}
@Test
public void testNarrativeGeneration() throws DataFormatException, IOException {
Patient patient = new Patient();
patient.addName().addFamily("Smith");
Organization org = new Organization();
patient.getManagingOrganization().setResource(org);
INarrativeGenerator gen = new INarrativeGenerator() {
@Override
public void generateNarrative(IBaseResource theResource, BaseNarrativeDt<?> theNarrative) {
throw new UnsupportedOperationException();
}
@Override
public void generateNarrative(String theProfile, IBaseResource theResource, BaseNarrativeDt<?> theNarrative) throws DataFormatException {
theNarrative.getDiv().setValueAsString("<div>help</div>");
theNarrative.getStatus().setValueAsString("generated");
}
@Override
public String generateTitle(IBaseResource theResource) {
throw new UnsupportedOperationException();
}
@Override
public String generateTitle(String theProfile, IBaseResource theResource) {
throw new UnsupportedOperationException();
}
@Override
public void setFhirContext(FhirContext theFhirContext) {
// nothing
}
};
FhirContext context = ourCtx;
context.setNarrativeGenerator(gen);
IParser p = context.newJsonParser();
p.encodeResourceToWriter(patient, new OutputStreamWriter(System.out));
String str = p.encodeResourceToString(patient);
ourLog.info(str);
assertThat(str, StringContains.containsString(",\"text\":{\"status\":\"generated\",\"div\":\"<div>help</div>\"},"));
}
@Before
public void before() {
ourCtx.setNarrativeGenerator(null);
}
@Test
public void testNestedContainedResources() {
Observation A = new Observation();
A.getName().setText("A");
Observation B = new Observation();
B.getName().setText("B");
A.addRelated().setTarget(new ResourceReferenceDt(B));
Observation C = new Observation();
C.getName().setText("C");
B.addRelated().setTarget(new ResourceReferenceDt(C));
String str = ourCtx.newJsonParser().setPrettyPrint(true).encodeResourceToString(A);
ourLog.info(str);
assertThat(str, stringContainsInOrder(Arrays.asList("\"text\":\"B\"", "\"text\":\"C\"", "\"text\":\"A\"")));
// Only one (outer) contained block
int idx0 = str.indexOf("\"contained\"");
int idx1 = str.indexOf("\"contained\"", idx0 + 1);
assertNotEquals(-1, idx0);
assertEquals(-1, idx1);
Observation obs = ourCtx.newJsonParser().parseResource(Observation.class, str);
assertEquals("A", obs.getName().getText().getValue());
Observation obsB = (Observation) obs.getRelatedFirstRep().getTarget().getResource();
assertEquals("B", obsB.getName().getText().getValue());
Observation obsC = (Observation) obsB.getRelatedFirstRep().getTarget().getResource();
assertEquals("C", obsC.getName().getText().getValue());
}
@Test
public void testParseBinaryResource() {
Binary val = ourCtx.newJsonParser().parseResource(Binary.class, "{\"resourceType\":\"Binary\",\"contentType\":\"foo\",\"content\":\"AQIDBA==\"}");
assertEquals("foo", val.getContentType());
assertArrayEquals(new byte[] { 1, 2, 3, 4 }, val.getContent());
}
@Test
public void testParseBundle() throws DataFormatException, IOException {
String msg = IOUtils.toString(XmlParser.class.getResourceAsStream("/atom-document-large.json"));
IParser p = ourCtx.newJsonParser();
Bundle bundle = p.parseBundle(msg);
assertEquals(1, bundle.getCategories().size());
assertEquals("http://scheme", bundle.getCategories().get(0).getScheme());
assertEquals("http://term", bundle.getCategories().get(0).getTerm());
assertEquals("label", bundle.getCategories().get(0).getLabel());
String encoded = ourCtx.newXmlParser().setPrettyPrint(true).encodeBundleToString(bundle);
ourLog.info(encoded);
assertEquals("http://fhir.healthintersections.com.au/open/DiagnosticReport/_search?_format=application/json+fhir&search-id=46d5f0e7-9240-4d4f-9f51-f8ac975c65&search-sort=_id",
bundle.getLinkSelf().getValue());
assertEquals("urn:uuid:0b754ff9-03cf-4322-a119-15019af8a3", bundle.getBundleId().getValue());
BundleEntry entry = bundle.getEntries().get(0);
assertEquals("http://fhir.healthintersections.com.au/open/DiagnosticReport/101", entry.getId().getValue());
assertEquals("http://fhir.healthintersections.com.au/open/DiagnosticReport/101/_history/1", entry.getLinkSelf().getValue());
assertEquals("2014-03-10T11:55:59Z", entry.getUpdated().getValueAsString());
DiagnosticReport res = (DiagnosticReport) entry.getResource();
assertEquals("Complete Blood Count", res.getName().getText().getValue());
assertThat(entry.getSummary().getValueAsString(), containsString("CBC Report for Wile"));
}
@Ignore
@Test
public void testTotalResultsInJsonBundle() {
String json =
"{" +
" \"resourceType\" : \"Bundle\"," +
" \"title\" : \"FHIR Atom Feed\"," +
" \"id\" : \"cb095f55-afb0-41e8-89d5-155259b2a032\"," +
" \"updated\" : \"2015-09-01T08:52:02.793-04:00\"," +
" \"author\": [" +
" {" +
" \"name\": \"author-name\", " +
" \"uri\": \"uri\" " +
" }" +
" ]," +
" \"link\" : [{" +
" \"rel\" : \"self\"," +
" \"href\" : \"http://fhirtest.uhn.ca/baseDstu1/Patient/_search?family=Perez\"" +
" }, {" +
" \"rel\" : \"next\"," +
" \"href\" : \"http://fhirtest.uhn.ca/baseDstu1?_getpages=c1db1094-cc46-49f1-ae69-4763ba52458b&_getpagesoffset=10&_count=10&_format=json&_pretty=true\"" +
" }, {" +
" \"rel\" : \"fhir-base\"," +
" \"href\" : \"http://fhirtest.uhn.ca/baseDstu1\"" +
" }" +
" ]," +
" \"totalResults\" : \"1\"," +
" \"entry\" : [{" +
" \"title\" : \"GONZALO PEREZ (DNI20425239)\"," +
" \"id\" : \"http://fhirtest.uhn.ca/baseDstu1/Patient/34834\"," +
" \"link\" : [{" +
" \"rel\" : \"self\"," +
" \"href\" : \"http://fhirtest.uhn.ca/baseDstu1/Patient/34834/_history/1\"" +
" }" +
" ]," +
" \"updated\" : \"2015-06-10T10:39:38.712-04:00\"," +
" \"published\" : \"2015-06-10T10:39:38.665-04:00\"," +
" \"content\" : {" +
" \"resourceType\" : \"Patient\"," +
" \"name\" : [{" +
" \"family\" : [" +
" \"PEREZ\"" +
" ]," +
" \"given\" : [" +
" \"GONZALO\"" +
" ]" +
" }" +
" ]" +
" }" +
" }" +
" ]" +
"}";
IParser jsonParser = ourCtx.newJsonParser();
Bundle bundle = jsonParser.parseBundle(json);
}
@Test
public void testParseBundleDeletedEntry() {
//@formatter:off
String bundleString =
"{" +
"\"resourceType\":\"Bundle\"," +
"\"totalResults\":\"1\"," +
"\"entry\":[" +
"{" +
"\"deleted\":\"2012-05-29T23:45:32+00:00\"," +
"\"id\":\"http://fhir.furore.com/fhir/Patient/1\"," +
"\"link\":[" +
"{" +
"\"rel\":\"self\"," +
"\"href\":\"http://fhir.furore.com/fhir/Patient/1/_history/2\"" +
"}" +
"]" +
"}" +
"]" +
"}";
//@formatter:on
Bundle bundle = ourCtx.newJsonParser().parseBundle(bundleString);
BundleEntry entry = bundle.getEntries().get(0);
assertEquals("2012-05-29T23:45:32+00:00", entry.getDeletedAt().getValueAsString());
assertEquals("http://fhir.furore.com/fhir/Patient/1/_history/2", entry.getLinkSelf().getValue());
assertEquals("1", entry.getResource().getId().getIdPart());
assertEquals("2", entry.getResource().getId().getVersionIdPart());
assertEquals(new InstantDt("2012-05-29T23:45:32+00:00"), entry.getResource().getResourceMetadata().get(ResourceMetadataKeyEnum.DELETED_AT));
// Now encode
ourLog.info(ourCtx.newJsonParser().setPrettyPrint(true).encodeBundleToString(bundle));
String encoded = ourCtx.newJsonParser().encodeBundleToString(bundle);
assertEquals(bundleString, encoded);
}
@Test
public void testParseBundleFromHI() throws DataFormatException, IOException {
String msg = IOUtils.toString(XmlParser.class.getResourceAsStream("/bundle.json"));
IParser p = ourCtx.newJsonParser();
Bundle bundle = p.parseBundle(msg);
String encoded = ourCtx.newXmlParser().setPrettyPrint(true).encodeBundleToString(bundle);
ourLog.info(encoded);
BundleEntry entry = bundle.getEntries().get(0);
Patient res = (Patient) entry.getResource();
assertEquals("444111234", res.getIdentifierFirstRep().getValue().getValue());
BundleEntry deletedEntry = bundle.getEntries().get(3);
assertEquals("2014-06-20T20:15:49Z", deletedEntry.getDeletedAt().getValueAsString());
}
@Test
public void testParseEmptyNarrative() throws ConfigurationException, DataFormatException, IOException {
//@formatter:off
String text = "{\n" +
" \"resourceType\" : \"Patient\",\n" +
" \"extension\" : [\n" +
" {\n" +
" \"url\" : \"http://clairol.org/colour\",\n" +
" \"valueCode\" : \"B\"\n" +
" }\n" +
" ],\n" +
" \"text\" : {\n" +
" \"div\" : \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\"\n" +
" }" +
"}";
//@formatter:on
Patient res = (Patient) ourCtx.newJsonParser().parseResource(text);
XhtmlDt div = res.getText().getDiv();
String value = div.getValueAsString();
assertEquals("<?xml version=\"1.0\" encoding=\"UTF-8\"?>", value);
assertEquals(null, div.getValue());
}
/**
* This sample has extra elements in <searchParam> that are not actually a part of the spec any more..
*/
@Test
public void testParseFuroreMetadataWithExtraElements() throws IOException {
String msg = IOUtils.toString(JsonParserTest.class.getResourceAsStream("/furore-conformance.json"));
IParser p = ourCtx.newJsonParser();
Conformance conf = p.parseResource(Conformance.class, msg);
RestResource res = conf.getRestFirstRep().getResourceFirstRep();
assertEquals("_id", res.getSearchParam().get(1).getName().getValue());
}
@Test
public void testParseJsonProfile() throws IOException {
parseAndEncode("/patient.profile.json");
parseAndEncode("/alert.profile.json");
}
@Test
public void testParseQuery() {
String msg = "{\n" + " \"resourceType\": \"Query\",\n" + " \"text\": {\n" + " \"status\": \"generated\",\n" + " \"div\": \"<div>[Put rendering here]</div>\"\n" + " },\n"
+ " \"identifier\": \"urn:uuid:42b253f5-fa17-40d0-8da5-44aeb4230376\",\n" + " \"parameter\": [\n" + " {\n" + " \"url\": \"http://hl7.org/fhir/query#_query\",\n"
+ " \"valueString\": \"example\"\n" + " }\n" + " ]\n" + "}";
Query query = ourCtx.newJsonParser().parseResource(Query.class, msg);
assertEquals("urn:uuid:42b253f5-fa17-40d0-8da5-44aeb4230376", query.getIdentifier().getValueAsString());
assertEquals("http://hl7.org/fhir/query#_query", query.getParameterFirstRep().getUrlAsString());
assertEquals("example", query.getParameterFirstRep().getValueAsPrimitive().getValueAsString());
}
@Test
public void testParseSingleQuotes() {
try {
ourCtx.newJsonParser().parseBundle("{ 'resourceType': 'Bundle' }");
fail();
} catch (DataFormatException e) {
// Should be an error message about how single quotes aren't valid JSON
assertThat(e.getMessage(), containsString("double quote"));
}
}
@Test
public void testParseWithContained() throws DataFormatException, IOException {
String msg = IOUtils.toString(XmlParser.class.getResourceAsStream("/diagnostic-report.json"));
IParser p = ourCtx.newJsonParser();
// ourLog.info("Reading in message: {}", msg);
DiagnosticReport res = p.parseResource(DiagnosticReport.class, msg);
String encoded = ourCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(res);
ourLog.info(encoded);
ResourceReferenceDt reference = res.getResult().get(1);
Observation obs = (Observation) reference.getResource();
assertEquals("789-8", obs.getName().getCoding().get(0).getCode().getValue());
}
/**
* HAPI FHIR < 0.6 incorrectly used "resource" instead of "reference"
*/
@Test
public void testParseWithIncorrectReference() throws IOException {
String jsonString = IOUtils.toString(JsonParser.class.getResourceAsStream("/example-patient-general.json"));
jsonString = jsonString.replace("\"reference\"", "\"resource\"");
Patient parsed = ourCtx.newJsonParser().parseResource(Patient.class, jsonString);
assertEquals("Organization/1", parsed.getManagingOrganization().getReference().getValue());
}
@SuppressWarnings("unused")
@Test
public void testParseWithIncorrectResourceType() {
String input = "{\"resourceType\":\"Patient\"}";
try {
IParser parser = ourCtx.newJsonParser();
Organization o = parser.parseResource(Organization.class, input);
fail();
} catch (DataFormatException e) {
assertThat(e.getMessage(), containsString("expected \"Organization\" but found \"Patient\""));
}
}
@Test
public void testSimpleBundleEncode() throws IOException {
String xmlString = IOUtils.toString(JsonParser.class.getResourceAsStream("/atom-document-large.xml"), Charset.forName("UTF-8"));
Bundle obs = ourCtx.newXmlParser().parseBundle(xmlString);
String encoded = ourCtx.newJsonParser().setPrettyPrint(true).encodeBundleToString(obs);
ourLog.info(encoded);
}
@Test
public void testSimpleParse() throws DataFormatException, IOException {
String msg = IOUtils.toString(XmlParser.class.getResourceAsStream("/example-patient-general.json"));
IParser p = ourCtx.newJsonParser();
// ourLog.info("Reading in message: {}", msg);
Patient res = p.parseResource(Patient.class, msg);
assertEquals(2, res.getUndeclaredExtensions().size());
assertEquals(1, res.getUndeclaredModifierExtensions().size());
String encoded = ourCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(res);
ourLog.info(encoded);
}
@Test
public void testSimpleResourceEncode() throws IOException {
String xmlString = IOUtils.toString(JsonParser.class.getResourceAsStream("/example-patient-general.xml"), Charset.forName("UTF-8"));
Patient obs = ourCtx.newXmlParser().parseResource(Patient.class, xmlString);
List<ExtensionDt> undeclaredExtensions = obs.getContact().get(0).getName().getFamily().get(0).getUndeclaredExtensions();
ExtensionDt undeclaredExtension = undeclaredExtensions.get(0);
assertEquals("http://hl7.org/fhir/Profile/iso-21090#qualifier", undeclaredExtension.getUrl());
ourCtx.newJsonParser().setPrettyPrint(true).encodeResourceToWriter(obs, new OutputStreamWriter(System.out));
IParser jsonParser = ourCtx.newJsonParser();
String encoded = jsonParser.encodeResourceToString(obs);
ourLog.info(encoded);
String jsonString = IOUtils.toString(JsonParser.class.getResourceAsStream("/example-patient-general.json"), Charset.forName("UTF-8"));
JSON expected = JSONSerializer.toJSON(jsonString);
JSON actual = JSONSerializer.toJSON(encoded.trim());
// The encoded escapes quote marks using XML escaping instead of JSON escaping, which is probably nicer anyhow...
String exp = expected.toString().replace("\\\"Jim\\\"", ""Jim"");
String act = actual.toString();
ourLog.info("Expected: {}", exp);
ourLog.info("Actual : {}", act);
assertEquals(exp, act);
}
@Test
public void testSimpleResourceEncodeWithCustomType() throws IOException {
FhirContext fhirCtx = new FhirContext(MyPatientWithExtensions.class);
String xmlString = IOUtils.toString(JsonParser.class.getResourceAsStream("/example-patient-general.xml"), Charset.forName("UTF-8"));
MyPatientWithExtensions obs = fhirCtx.newXmlParser().parseResource(MyPatientWithExtensions.class, xmlString);
assertEquals(0, obs.getAllUndeclaredExtensions().size());
assertEquals("aaaa", obs.getExtAtt().getContentType().getValue());
assertEquals("str1", obs.getMoreExt().getStr1().getValue());
assertEquals("2011-01-02", obs.getModExt().getValueAsString());
List<ExtensionDt> undeclaredExtensions = obs.getContact().get(0).getName().getFamily().get(0).getUndeclaredExtensions();
ExtensionDt undeclaredExtension = undeclaredExtensions.get(0);
assertEquals("http://hl7.org/fhir/Profile/iso-21090#qualifier", undeclaredExtension.getUrl());
IParser jsonParser = fhirCtx.newJsonParser().setPrettyPrint(true);
String encoded = jsonParser.encodeResourceToString(obs);
ourLog.info(encoded);
String jsonString = IOUtils.toString(JsonParser.class.getResourceAsStream("/example-patient-general.json"), Charset.forName("UTF-8"));
JSON expected = JSONSerializer.toJSON(jsonString);
JSON actual = JSONSerializer.toJSON(encoded.trim());
// The encoded escapes quote marks using XML escaping instead of JSON escaping, which is probably nicer anyhow...
String exp = expected.toString().replace("\\\"Jim\\\"", ""Jim"");
String act = actual.toString();
ourLog.info("Expected: {}", exp);
ourLog.info("Actual : {}", act);
assertEquals(exp, act);
}
@Test
public void testTagList() {
//@formatter:off
String tagListStr = "{\n" +
" \"resourceType\" : \"TagList\", " +
" \"category\" : [" +
" { " +
" \"term\" : \"term0\", " +
" \"label\" : \"label0\", " +
" \"scheme\" : \"scheme0\" " +
" }," +
" { " +
" \"term\" : \"term1\", " +
" \"label\" : \"label1\", " +
" \"scheme\" : null " +
" }," +
" { " +
" \"term\" : \"term2\", " +
" \"label\" : \"label2\" " +
" }" +
" ] " +
"}";
//@formatter:on
TagList tagList = ourCtx.newJsonParser().parseTagList(tagListStr);
assertEquals(3, tagList.size());
assertEquals("term0", tagList.get(0).getTerm());
assertEquals("label0", tagList.get(0).getLabel());
assertEquals("scheme0", tagList.get(0).getScheme());
assertEquals("term1", tagList.get(1).getTerm());
assertEquals("label1", tagList.get(1).getLabel());
assertEquals(null, tagList.get(1).getScheme());
assertEquals("term2", tagList.get(2).getTerm());
assertEquals("label2", tagList.get(2).getLabel());
assertEquals(null, tagList.get(2).getScheme());
/*
* Encode
*/
//@formatter:off
String expected = "{" +
"\"resourceType\":\"TagList\"," +
"\"category\":[" +
"{" +
"\"term\":\"term0\"," +
"\"label\":\"label0\"," +
"\"scheme\":\"scheme0\"" +
"}," +
"{" +
"\"term\":\"term1\"," +
"\"label\":\"label1\"" +
"}," +
"{" +
"\"term\":\"term2\"," +
"\"label\":\"label2\"" +
"}" +
"]" +
"}";
//@formatter:on
String encoded = ourCtx.newJsonParser().encodeTagListToString(tagList);
assertEquals(expected, encoded);
}
@BeforeClass
public static void beforeClass() {
ourCtx = FhirContext.forDstu1();
}
@ResourceDef(name = "Patient")
public static class MyPatientWithOneDeclaredAddressExtension extends Patient {
@Child(order = 0, name = "foo")
@Extension(url = "urn:foo", definedLocally = true, isModifier = false)
private AddressDt myFoo;
public AddressDt getFoo() {
return myFoo;
}
public void setFoo(AddressDt theFoo) {
myFoo = theFoo;
}
}
@ResourceDef(name = "Patient")
public static class MyPatientWithOneDeclaredExtension extends Patient {
@Child(order = 0, name = "foo")
@Extension(url = "urn:foo", definedLocally = true, isModifier = false)
private ResourceReferenceDt myFoo;
public ResourceReferenceDt getFoo() {
return myFoo;
}
public void setFoo(ResourceReferenceDt theFoo) {
myFoo = theFoo;
}
}
}
|
hapi-fhir-structures-dstu/src/test/java/ca/uhn/fhir/parser/JsonParserTest.java
|
package ca.uhn.fhir.parser;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.stringContainsInOrder;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.StringReader;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import net.sf.json.JSON;
import net.sf.json.JSONSerializer;
import org.apache.commons.io.IOUtils;
import org.hamcrest.core.IsNot;
import org.hamcrest.core.StringContains;
import org.hamcrest.text.StringContainsInOrder;
import org.hl7.fhir.instance.model.api.IBaseResource;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
import ca.uhn.fhir.context.ConfigurationException;
import ca.uhn.fhir.context.FhirContext;
import ca.uhn.fhir.model.api.Bundle;
import ca.uhn.fhir.model.api.BundleEntry;
import ca.uhn.fhir.model.api.ExtensionDt;
import ca.uhn.fhir.model.api.IResource;
import ca.uhn.fhir.model.api.ResourceMetadataKeyEnum;
import ca.uhn.fhir.model.api.TagList;
import ca.uhn.fhir.model.api.annotation.Child;
import ca.uhn.fhir.model.api.annotation.Extension;
import ca.uhn.fhir.model.api.annotation.ResourceDef;
import ca.uhn.fhir.model.base.composite.BaseNarrativeDt;
import ca.uhn.fhir.model.dstu.composite.AddressDt;
import ca.uhn.fhir.model.dstu.composite.HumanNameDt;
import ca.uhn.fhir.model.dstu.composite.ResourceReferenceDt;
import ca.uhn.fhir.model.dstu.resource.Binary;
import ca.uhn.fhir.model.dstu.resource.Conformance;
import ca.uhn.fhir.model.dstu.resource.Conformance.RestResource;
import ca.uhn.fhir.model.dstu.resource.DiagnosticReport;
import ca.uhn.fhir.model.dstu.resource.ListResource;
import ca.uhn.fhir.model.dstu.resource.Location;
import ca.uhn.fhir.model.dstu.resource.Observation;
import ca.uhn.fhir.model.dstu.resource.Organization;
import ca.uhn.fhir.model.dstu.resource.Patient;
import ca.uhn.fhir.model.dstu.resource.Profile;
import ca.uhn.fhir.model.dstu.resource.Query;
import ca.uhn.fhir.model.dstu.resource.Questionnaire;
import ca.uhn.fhir.model.dstu.resource.Remittance;
import ca.uhn.fhir.model.dstu.resource.Specimen;
import ca.uhn.fhir.model.dstu.resource.ValueSet;
import ca.uhn.fhir.model.dstu.resource.ValueSet.Define;
import ca.uhn.fhir.model.dstu.resource.ValueSet.DefineConcept;
import ca.uhn.fhir.model.dstu.valueset.AddressUseEnum;
import ca.uhn.fhir.model.dstu.valueset.IdentifierUseEnum;
import ca.uhn.fhir.model.dstu.valueset.NarrativeStatusEnum;
import ca.uhn.fhir.model.primitive.DateDt;
import ca.uhn.fhir.model.primitive.DateTimeDt;
import ca.uhn.fhir.model.primitive.DecimalDt;
import ca.uhn.fhir.model.primitive.IdDt;
import ca.uhn.fhir.model.primitive.InstantDt;
import ca.uhn.fhir.model.primitive.StringDt;
import ca.uhn.fhir.model.primitive.XhtmlDt;
import ca.uhn.fhir.narrative.INarrativeGenerator;
public class JsonParserTest {
private static FhirContext ourCtx;
private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(JsonParserTest.class);
private void parseAndEncode(String name) throws IOException {
String msg = IOUtils.toString(XmlParser.class.getResourceAsStream(name));
// ourLog.info(msg);
IParser p = ourCtx.newJsonParser();
Profile res = p.parseResource(Profile.class, msg);
String encoded = ourCtx.newJsonParser().setPrettyPrint(true).encodeResourceToString(res);
// ourLog.info(encoded);
JSON expected = JSONSerializer.toJSON(msg.trim());
JSON actual = JSONSerializer.toJSON(encoded.trim());
String exp = expected.toString().replace("\\r\\n", "\\n"); // .replace("§", "§");
String act = actual.toString().replace("\\r\\n", "\\n");
ourLog.info("Expected: {}", exp);
ourLog.info("Actual : {}", act);
assertEquals(exp, act);
}
@Test
public void testDecimalPrecisionPreserved() {
String number = "52.3779939997090374535378485873776474764643249869328698436986235758587";
Location loc = new Location();
// This is far more precision than is realistic, but let's see if we preserve it
loc.getPosition().setLatitude(new DecimalDt(number));
String encoded = ourCtx.newJsonParser().encodeResourceToString(loc);
Location parsed = ourCtx.newJsonParser().parseResource(Location.class, encoded);
assertEquals(number, parsed.getPosition().getLatitude().getValueAsString());
}
@Test
public void testDecimalPrecisionPreservedInResource() {
Remittance obs = new Remittance();
obs.addService().setRate(new DecimalDt("0.10000"));
String output = ourCtx.newJsonParser().encodeResourceToString(obs);
ourLog.info(output);
assertEquals("{\"resourceType\":\"Remittance\",\"service\":[{\"rate\":0.10000}]}", output);
obs = ourCtx.newJsonParser().parseResource(Remittance.class, output);
assertEquals("0.10000", obs.getService().get(0).getRate().getValueAsString());
}
@Test
public void testParseStringWithNewlineUnencoded() {
Observation obs = new Observation();
obs.setValue(new StringDt("line1\\nline2"));
String output = ourCtx.newJsonParser().encodeResourceToString(obs);
ourLog.info(output);
assertEquals("{\"resourceType\":\"Observation\",\"valueString\":\"line1\\\\nline2\"}", output);
obs = ourCtx.newJsonParser().parseResource(Observation.class, output);
assertEquals("line1\\nline2", ((StringDt)obs.getValue()).getValue());
}
@Test
public void testParseStringWithNewlineEncoded() {
Observation obs = new Observation();
obs.setValue(new StringDt("line1\nline2"));
String output = ourCtx.newJsonParser().encodeResourceToString(obs);
ourLog.info(output);
assertEquals("{\"resourceType\":\"Observation\",\"valueString\":\"line1\\nline2\"}", output);
obs = ourCtx.newJsonParser().parseResource(Observation.class, output);
assertEquals("line1\nline2", ((StringDt)obs.getValue()).getValue());
}
@Test
public void testEncodeAndParseExtensions() throws Exception {
Patient patient = new Patient();
patient.addIdentifier().setUse(IdentifierUseEnum.OFFICIAL).setSystem("urn:example").setValue("7000135");
ExtensionDt ext = new ExtensionDt();
ext.setUrl("http://example.com/extensions#someext");
ext.setValue(new DateTimeDt("2011-01-02T11:13:15"));
patient.addUndeclaredExtension(ext);
ExtensionDt parent = new ExtensionDt().setUrl("http://example.com#parent");
patient.addUndeclaredExtension(parent);
ExtensionDt child1 = new ExtensionDt().setUrl("http://example.com#child").setValue(new StringDt("value1"));
parent.addUndeclaredExtension(child1);
ExtensionDt child2 = new ExtensionDt().setUrl("http://example.com#child").setValue(new StringDt("value2"));
parent.addUndeclaredExtension(child2);
ExtensionDt modExt = new ExtensionDt();
modExt.setUrl("http://example.com/extensions#modext");
modExt.setValue(new DateDt("1995-01-02"));
modExt.setModifier(true);
patient.addUndeclaredExtension(modExt);
HumanNameDt name = patient.addName();
name.addFamily("Blah");
StringDt given = name.addGiven();
given.setValue("Joe");
ExtensionDt ext2 = new ExtensionDt().setUrl("http://examples.com#givenext").setValue(new StringDt("given"));
given.addUndeclaredExtension(ext2);
StringDt given2 = name.addGiven();
given2.setValue("Shmoe");
ExtensionDt given2ext = new ExtensionDt().setUrl("http://examples.com#givenext_parent");
given2.addUndeclaredExtension(given2ext);
given2ext.addUndeclaredExtension(new ExtensionDt().setUrl("http://examples.com#givenext_child").setValue(new StringDt("CHILD")));
String output = ourCtx.newJsonParser().setPrettyPrint(true).encodeResourceToString(patient);
ourLog.info(output);
String enc = ourCtx.newJsonParser().encodeResourceToString(patient);
assertThat(enc, org.hamcrest.Matchers.stringContainsInOrder("{\"resourceType\":\"Patient\",",
"\"extension\":[{\"url\":\"http://example.com/extensions#someext\",\"valueDateTime\":\"2011-01-02T11:13:15\"}",
"{\"url\":\"http://example.com#parent\",\"extension\":[{\"url\":\"http://example.com#child\",\"valueString\":\"value1\"},{\"url\":\"http://example.com#child\",\"valueString\":\"value2\"}]}"));
assertThat(enc, org.hamcrest.Matchers.stringContainsInOrder("\"modifierExtension\":[" + "{" + "\"url\":\"http://example.com/extensions#modext\"," + "\"valueDate\":\"1995-01-02\"" + "}" + "],"));
assertThat(enc,
containsString("\"_given\":[" + "{" + "\"extension\":[" + "{" + "\"url\":\"http://examples.com#givenext\"," + "\"valueString\":\"given\"" + "}" + "]" + "}," + "{" + "\"extension\":[" + "{"
+ "\"url\":\"http://examples.com#givenext_parent\"," + "\"extension\":[" + "{" + "\"url\":\"http://examples.com#givenext_child\"," + "\"valueString\":\"CHILD\"" + "}" + "]" + "}"
+ "]" + "}"));
/*
* Now parse this back
*/
Patient parsed = ourCtx.newJsonParser().parseResource(Patient.class, enc);
ext = parsed.getUndeclaredExtensions().get(0);
assertEquals("http://example.com/extensions#someext", ext.getUrl());
assertEquals("2011-01-02T11:13:15", ((DateTimeDt) ext.getValue()).getValueAsString());
parent = patient.getUndeclaredExtensions().get(1);
assertEquals("http://example.com#parent", parent.getUrl());
assertNull(parent.getValue());
child1 = parent.getExtension().get(0);
assertEquals("http://example.com#child", child1.getUrl());
assertEquals("value1", ((StringDt) child1.getValue()).getValueAsString());
child2 = parent.getExtension().get(1);
assertEquals("http://example.com#child", child2.getUrl());
assertEquals("value2", ((StringDt) child2.getValue()).getValueAsString());
modExt = parsed.getUndeclaredModifierExtensions().get(0);
assertEquals("http://example.com/extensions#modext", modExt.getUrl());
assertEquals("1995-01-02", ((DateDt) modExt.getValue()).getValueAsString());
name = parsed.getName().get(0);
ext2 = name.getGiven().get(0).getUndeclaredExtensions().get(0);
assertEquals("http://examples.com#givenext", ext2.getUrl());
assertEquals("given", ((StringDt) ext2.getValue()).getValueAsString());
given2ext = name.getGiven().get(1).getUndeclaredExtensions().get(0);
assertEquals("http://examples.com#givenext_parent", given2ext.getUrl());
assertNull(given2ext.getValue());
ExtensionDt given2ext2 = given2ext.getExtension().get(0);
assertEquals("http://examples.com#givenext_child", given2ext2.getUrl());
assertEquals("CHILD", ((StringDt) given2ext2.getValue()).getValue());
}
@Test
public void testEncodeBinaryResource() {
Binary patient = new Binary();
patient.setContentType("foo");
patient.setContent(new byte[] { 1, 2, 3, 4 });
String val = ourCtx.newJsonParser().encodeResourceToString(patient);
assertEquals("{\"resourceType\":\"Binary\",\"contentType\":\"foo\",\"content\":\"AQIDBA==\"}", val);
}
@Test
public void testEncodeBundle() throws InterruptedException {
Bundle b = new Bundle();
InstantDt pub = InstantDt.withCurrentTime();
Thread.sleep(2);
Patient p1 = new Patient();
p1.addName().addFamily("Family1");
BundleEntry entry = b.addEntry();
entry.getId().setValue("1");
entry.setResource(p1);
entry.getSummary().setValueAsString("this is the summary");
Patient p2 = new Patient();
p2.addName().addFamily("Family2");
entry = b.addEntry();
entry.getId().setValue("2");
entry.setLinkAlternate(new StringDt("http://foo/bar"));
entry.setResource(p2);
BundleEntry deletedEntry = b.addEntry();
deletedEntry.setId(new IdDt("Patient/3"));
InstantDt nowDt = InstantDt.withCurrentTime();
deletedEntry.setDeleted(nowDt);
String bundleString = ourCtx.newJsonParser().setPrettyPrint(true).encodeBundleToString(b);
ourLog.info(bundleString);
List<String> strings = new ArrayList<String>();
strings.addAll(Arrays.asList("\"id\":\"1\""));
strings.addAll(Arrays.asList("this is the summary"));
strings.addAll(Arrays.asList("\"id\":\"2\"", "\"rel\":\"alternate\"", "\"href\":\"http://foo/bar\""));
strings.addAll(Arrays.asList("\"deleted\":\"" + nowDt.getValueAsString() + "\"", "\"id\":\"Patient/3\""));
assertThat(bundleString, StringContainsInOrder.stringContainsInOrder(strings));
b.getEntries().remove(2);
bundleString = ourCtx.newJsonParser().setPrettyPrint(true).encodeBundleToString(b);
assertThat(bundleString, not(containsString("deleted")));
}
@Test
public void testEncodeBundleCategory() {
Bundle b = new Bundle();
BundleEntry e = b.addEntry();
e.setResource(new Patient());
b.addCategory("scheme", "term", "label");
String val = ourCtx.newJsonParser().setPrettyPrint(false).encodeBundleToString(b);
ourLog.info(val);
assertThat(val, StringContains.containsString("\"category\":[{\"term\":\"term\",\"label\":\"label\",\"scheme\":\"scheme\"}]"));
assertThat(val, not(containsString("text")));
b = ourCtx.newJsonParser().parseBundle(val);
assertEquals(1, b.getEntries().size());
assertEquals(1, b.getCategories().size());
assertEquals("term", b.getCategories().get(0).getTerm());
assertEquals("label", b.getCategories().get(0).getLabel());
assertEquals("scheme", b.getCategories().get(0).getScheme());
assertNull(b.getEntries().get(0).getResource());
}
@Test
public void testEncodeBundleEntryCategory() {
Bundle b = new Bundle();
BundleEntry e = b.addEntry();
e.setResource(new Patient());
e.addCategory("scheme", "term", "label");
String val = ourCtx.newJsonParser().setPrettyPrint(false).encodeBundleToString(b);
ourLog.info(val);
assertThat(val, StringContains.containsString("\"category\":[{\"term\":\"term\",\"label\":\"label\",\"scheme\":\"scheme\"}]"));
b = ourCtx.newJsonParser().parseBundle(val);
assertEquals(1, b.getEntries().size());
assertEquals(1, b.getEntries().get(0).getCategories().size());
assertEquals("term", b.getEntries().get(0).getCategories().get(0).getTerm());
assertEquals("label", b.getEntries().get(0).getCategories().get(0).getLabel());
assertEquals("scheme", b.getEntries().get(0).getCategories().get(0).getScheme());
assertNull(b.getEntries().get(0).getResource());
}
@Test
public void testEncodeContained() {
IParser xmlParser = ourCtx.newJsonParser().setPrettyPrint(true);
// Create an organization, note that the organization does not have an ID
Organization org = new Organization();
org.getName().setValue("Contained Test Organization");
// Create a patient
Patient patient = new Patient();
patient.setId("Patient/1333");
patient.addIdentifier("urn:mrns", "253345");
// Put the organization as a reference in the patient resource
patient.getManagingOrganization().setResource(org);
String encoded = xmlParser.encodeResourceToString(patient);
ourLog.info(encoded);
assertThat(encoded, stringContainsInOrder(Arrays.asList("\"contained\":[", "\"id\":\"1\"", "\"identifier\"", "\"reference\":\"#1\"")));
// Create a bundle with just the patient resource
List<IResource> resources = new ArrayList<IResource>();
resources.add(patient);
Bundle b = Bundle.withResources(resources, ourCtx, "http://example.com/base");
// Encode the bundle
encoded = xmlParser.encodeBundleToString(b);
ourLog.info(encoded);
assertThat(encoded, stringContainsInOrder(Arrays.asList("\"contained\":[", "\"id\":\"1\"", "\"identifier\"", "\"reference\":\"#1\"")));
// Re-parse the bundle
patient = (Patient) xmlParser.parseResource(xmlParser.encodeResourceToString(patient));
assertEquals("#1", patient.getManagingOrganization().getReference().getValue());
assertNotNull(patient.getManagingOrganization().getResource());
org = (Organization) patient.getManagingOrganization().getResource();
assertEquals("#1", org.getId().getValue());
assertEquals("Contained Test Organization", org.getName().getValue());
// And re-encode a second time
encoded = xmlParser.encodeResourceToString(patient);
ourLog.info(encoded);
assertThat(encoded, stringContainsInOrder(Arrays.asList("\"contained\":[", "\"id\":\"1\"", "\"identifier\"", "\"reference\":\"#1\"")));
assertThat(encoded, not(stringContainsInOrder(Arrays.asList("\"contained\":", "[", "\"contained\":"))));
// And re-encode once more, with the references cleared
patient.getContained().getContainedResources().clear();
patient.getManagingOrganization().setReference((IdDt) null);
encoded = xmlParser.encodeResourceToString(patient);
ourLog.info(encoded);
assertThat(encoded, stringContainsInOrder(Arrays.asList("\"contained\":[", "\"id\":\"1\"", "\"identifier\"", "\"reference\":\"#1\"")));
assertThat(encoded, not(stringContainsInOrder(Arrays.asList("\"contained\":", "[", "\"contained\":"))));
// And re-encode once more, with the references cleared and a manually set local ID
patient.getContained().getContainedResources().clear();
patient.getManagingOrganization().setReference((IdDt) null);
patient.getManagingOrganization().getResource().setId(new IdDt("#333"));
encoded = xmlParser.encodeResourceToString(patient);
ourLog.info(encoded);
assertThat(encoded, stringContainsInOrder(Arrays.asList("\"contained\":[", "\"id\":\"333\"", "\"identifier\"", "\"reference\":\"#333\"")));
assertThat(encoded, not(stringContainsInOrder(Arrays.asList("\"contained\":", "[", "\"contained\":"))));
}
@Test
public void testEncodeContained__() {
// Create an organization
Organization org = new Organization();
org.getName().setValue("Contained Test Organization");
// Create a patient
Patient patient = new Patient();
patient.setId("Patient/1333");
patient.addIdentifier("urn:mrns", "253345");
patient.getManagingOrganization().setResource(org);
// Create a bundle with just the patient resource
List<IResource> resources = new ArrayList<IResource>();
resources.add(patient);
Bundle b = Bundle.withResources(resources, ourCtx, "http://example.com/base");
// Encode the buntdle
String encoded = ourCtx.newJsonParser().setPrettyPrint(true).encodeBundleToString(b);
ourLog.info(encoded);
assertThat(encoded, stringContainsInOrder(Arrays.asList("\"contained\"", "resourceType\":\"Organization", "id\":\"1\"")));
assertThat(encoded, containsString("reference\":\"#1\""));
encoded = ourCtx.newJsonParser().setPrettyPrint(true).encodeResourceToString(patient);
ourLog.info(encoded);
assertThat(encoded, stringContainsInOrder(Arrays.asList("\"contained\"", "resourceType\":\"Organization", "id\":\"1\"")));
assertThat(encoded, containsString("reference\":\"#1\""));
}
@Test
public void testEncodeContainedResources() throws IOException {
String msg = IOUtils.toString(XmlParser.class.getResourceAsStream("/contained-diagnosticreport.xml"));
IParser p = ourCtx.newXmlParser();
DiagnosticReport res = p.parseResource(DiagnosticReport.class, msg);
String encoded = ourCtx.newJsonParser().setPrettyPrint(true).encodeResourceToString(res);
ourLog.info(encoded);
}
@Test
public void testEncodeContainedResourcesMore() {
DiagnosticReport rpt = new DiagnosticReport();
Specimen spm = new Specimen();
rpt.getText().setDiv("AAA");
rpt.addSpecimen().setResource(spm);
IParser p = new FhirContext(DiagnosticReport.class).newJsonParser().setPrettyPrint(true);
String str = p.encodeResourceToString(rpt);
ourLog.info(str);
assertThat(str, StringContains.containsString("<div>AAA</div>"));
String substring = "\"reference\":\"#";
assertThat(str, StringContains.containsString(substring));
int idx = str.indexOf(substring) + substring.length();
int idx2 = str.indexOf('"', idx + 1);
String id = str.substring(idx, idx2);
assertThat(str, StringContains.containsString("\"id\":\"" + id + "\""));
assertThat(str, IsNot.not(StringContains.containsString("<?xml version='1.0'?>")));
}
@Test
public void testEncodeContainedWithNarrativeIsSuppresed() {
IParser parser = ourCtx.newJsonParser().setPrettyPrint(true);
// Create an organization, note that the organization does not have an ID
Organization org = new Organization();
org.getName().setValue("Contained Test Organization");
org.getText().setDiv("<div>FOOBAR</div>");
// Create a patient
Patient patient = new Patient();
patient.setId("Patient/1333");
patient.addIdentifier("urn:mrns", "253345");
patient.getText().setDiv("<div>BARFOO</div>");
patient.getManagingOrganization().setResource(org);
String encoded = parser.encodeResourceToString(patient);
ourLog.info(encoded);
assertThat(encoded, not(containsString("FOOBAR")));
assertThat(encoded, (containsString("BARFOO")));
}
@Test
public void testEncodeDeclaredExtensionWithAddressContent() {
IParser parser = ourCtx.newJsonParser();
MyPatientWithOneDeclaredAddressExtension patient = new MyPatientWithOneDeclaredAddressExtension();
patient.addAddress().setUse(AddressUseEnum.HOME);
patient.setFoo(new AddressDt().addLine("line1"));
String val = parser.encodeResourceToString(patient);
ourLog.info(val);
assertThat(val, StringContains.containsString("\"extension\":[{\"url\":\"urn:foo\",\"valueAddress\":{\"line\":[\"line1\"]}}]"));
MyPatientWithOneDeclaredAddressExtension actual = parser.parseResource(MyPatientWithOneDeclaredAddressExtension.class, val);
assertEquals(AddressUseEnum.HOME, patient.getAddressFirstRep().getUse().getValueAsEnum());
AddressDt ref = actual.getFoo();
assertEquals("line1", ref.getLineFirstRep().getValue());
}
@Test
public void testEncodeDeclaredExtensionWithResourceContent() {
IParser parser = ourCtx.newJsonParser();
MyPatientWithOneDeclaredExtension patient = new MyPatientWithOneDeclaredExtension();
patient.addAddress().setUse(AddressUseEnum.HOME);
patient.setFoo(new ResourceReferenceDt("Organization/123"));
String val = parser.encodeResourceToString(patient);
ourLog.info(val);
assertThat(val, StringContains.containsString("\"extension\":[{\"url\":\"urn:foo\",\"valueResource\":{\"reference\":\"Organization/123\"}}]"));
MyPatientWithOneDeclaredExtension actual = parser.parseResource(MyPatientWithOneDeclaredExtension.class, val);
assertEquals(AddressUseEnum.HOME, patient.getAddressFirstRep().getUse().getValueAsEnum());
ResourceReferenceDt ref = actual.getFoo();
assertEquals("Organization/123", ref.getReference().getValue());
}
@Test
public void testEncodeExt() throws Exception {
ValueSet valueSet = new ValueSet();
valueSet.setId("123456");
Define define = valueSet.getDefine();
DefineConcept code = define.addConcept();
code.setCode("someCode");
code.setDisplay("someDisplay");
code.addUndeclaredExtension(false, "urn:alt", new StringDt("alt name"));
String encoded = ourCtx.newJsonParser().encodeResourceToString(valueSet);
ourLog.info(encoded);
assertThat(encoded, not(containsString("123456")));
assertEquals("{\"resourceType\":\"ValueSet\",\"define\":{\"concept\":[{\"extension\":[{\"url\":\"urn:alt\",\"valueString\":\"alt name\"}],\"code\":\"someCode\",\"display\":\"someDisplay\"}]}}",
encoded);
}
@Test
public void testEncodeExtensionInCompositeElement() {
Conformance c = new Conformance();
c.addRest().getSecurity().addUndeclaredExtension(false, "http://foo", new StringDt("AAA"));
String encoded = ourCtx.newJsonParser().setPrettyPrint(true).encodeResourceToString(c);
ourLog.info(encoded);
encoded = ourCtx.newJsonParser().setPrettyPrint(false).encodeResourceToString(c);
ourLog.info(encoded);
assertEquals(encoded, "{\"resourceType\":\"Conformance\",\"rest\":[{\"security\":{\"extension\":[{\"url\":\"http://foo\",\"valueString\":\"AAA\"}]}}]}");
}
@Test
public void testEncodeExtensionInPrimitiveElement() {
Conformance c = new Conformance();
c.getAcceptUnknown().addUndeclaredExtension(false, "http://foo", new StringDt("AAA"));
String encoded = ourCtx.newJsonParser().setPrettyPrint(true).encodeResourceToString(c);
ourLog.info(encoded);
encoded = ourCtx.newJsonParser().setPrettyPrint(false).encodeResourceToString(c);
ourLog.info(encoded);
assertEquals(encoded, "{\"resourceType\":\"Conformance\",\"_acceptUnknown\":{\"extension\":[{\"url\":\"http://foo\",\"valueString\":\"AAA\"}]}}");
// Now with a value
ourLog.info("---------------");
c = new Conformance();
c.getAcceptUnknown().setValue(true);
c.getAcceptUnknown().addUndeclaredExtension(false, "http://foo", new StringDt("AAA"));
encoded = ourCtx.newJsonParser().setPrettyPrint(true).encodeResourceToString(c);
ourLog.info(encoded);
encoded = ourCtx.newJsonParser().setPrettyPrint(false).encodeResourceToString(c);
ourLog.info(encoded);
assertEquals(encoded, "{\"resourceType\":\"Conformance\",\"acceptUnknown\":true,\"_acceptUnknown\":{\"extension\":[{\"url\":\"http://foo\",\"valueString\":\"AAA\"}]}}");
}
@Test
public void testEncodeExtensionInResourceElement() {
Conformance c = new Conformance();
// c.addRest().getSecurity().addUndeclaredExtension(false, "http://foo", new StringDt("AAA"));
c.addUndeclaredExtension(false, "http://foo", new StringDt("AAA"));
String encoded = ourCtx.newJsonParser().setPrettyPrint(true).encodeResourceToString(c);
ourLog.info(encoded);
encoded = ourCtx.newJsonParser().setPrettyPrint(false).encodeResourceToString(c);
ourLog.info(encoded);
assertEquals(encoded, "{\"resourceType\":\"Conformance\",\"extension\":[{\"url\":\"http://foo\",\"valueString\":\"AAA\"}]}");
}
@Test
public void testEncodeExtensionOnEmptyElement() throws Exception {
ValueSet valueSet = new ValueSet();
valueSet.addTelecom().addUndeclaredExtension(false, "http://foo", new StringDt("AAA"));
String encoded = ourCtx.newJsonParser().encodeResourceToString(valueSet);
assertThat(encoded, containsString("\"telecom\":[{\"extension\":[{\"url\":\"http://foo\",\"valueString\":\"AAA\"}]}"));
}
@Test
public void testEncodeExtensionWithResourceContent() {
IParser parser = ourCtx.newJsonParser();
Patient patient = new Patient();
patient.addAddress().setUse(AddressUseEnum.HOME);
patient.addUndeclaredExtension(false, "urn:foo", new ResourceReferenceDt("Organization/123"));
String val = parser.encodeResourceToString(patient);
ourLog.info(val);
assertThat(val, StringContains.containsString("\"extension\":[{\"url\":\"urn:foo\",\"valueResource\":{\"reference\":\"Organization/123\"}}]"));
Patient actual = parser.parseResource(Patient.class, val);
assertEquals(AddressUseEnum.HOME, patient.getAddressFirstRep().getUse().getValueAsEnum());
List<ExtensionDt> ext = actual.getUndeclaredExtensionsByUrl("urn:foo");
assertEquals(1, ext.size());
ResourceReferenceDt ref = (ResourceReferenceDt) ext.get(0).getValue();
assertEquals("Organization/123", ref.getReference().getValue());
}
@Test
public void testEncodeIds() {
Patient pt = new Patient();
pt.addIdentifier("sys", "val");
ListResource list = new ListResource();
list.setId("listId");
list.addEntry().setItem(new ResourceReferenceDt(pt));
String enc = ourCtx.newJsonParser().encodeResourceToString(list);
ourLog.info(enc);
assertThat(enc, containsString("\"id\":\"1\""));
ListResource parsed = ourCtx.newJsonParser().parseResource(ListResource.class, enc);
assertEquals(Patient.class, parsed.getEntryFirstRep().getItem().getResource().getClass());
enc = enc.replace("\"id\"", "\"_id\"");
parsed = ourCtx.newJsonParser().parseResource(ListResource.class, enc);
assertEquals(Patient.class, parsed.getEntryFirstRep().getItem().getResource().getClass());
}
@Test
public void testEncodeInvalidChildGoodException() {
Observation obs = new Observation();
obs.setValue(new DecimalDt(112.22));
IParser p = new FhirContext(Observation.class).newJsonParser();
try {
p.encodeResourceToString(obs);
} catch (DataFormatException e) {
assertThat(e.getMessage(), StringContains.containsString("DecimalDt"));
}
}
@Test
public void testEncodeNarrativeBlockInBundle() {
Patient p = new Patient();
p.addIdentifier("foo", "bar");
p.getText().setStatus(NarrativeStatusEnum.GENERATED);
p.getText().setDiv("<div>hello</div>");
Bundle b = new Bundle();
b.getTotalResults().setValue(123);
b.addEntry().setResource(p);
String out = ourCtx.newJsonParser().setPrettyPrint(true).encodeBundleToString(b);
ourLog.info(out);
assertThat(out, containsString("<div>hello</div>"));
p.getText().setDiv("<xhtml:div xmlns:xhtml=\"http://www.w3.org/1999/xhtml\">hello</xhtml:div>");
out = ourCtx.newJsonParser().setPrettyPrint(true).encodeBundleToString(b);
ourLog.info(out);
// Backslashes need to be escaped because they are in a JSON value
assertThat(out, containsString("<xhtml:div xmlns:xhtml=\\\"http://www.w3.org/1999/xhtml\\\">hello</xhtml:div>"));
}
@Test
public void testEncodeNonContained() {
Organization org = new Organization();
org.setId("Organization/65546");
org.getName().setValue("Contained Test Organization");
Patient patient = new Patient();
patient.setId("Patient/1333");
patient.addIdentifier("urn:mrns", "253345");
patient.getManagingOrganization().setResource(org);
Bundle b = Bundle.withResources(Collections.singletonList((IResource) patient), ourCtx, "http://foo");
String encoded = ourCtx.newJsonParser().setPrettyPrint(true).encodeBundleToString(b);
ourLog.info(encoded);
assertThat(encoded, not(containsString("contained")));
assertThat(encoded, containsString("\"reference\":\"Organization/65546\""));
encoded = ourCtx.newJsonParser().setPrettyPrint(true).encodeResourceToString(patient);
ourLog.info(encoded);
assertThat(encoded, not(containsString("contained")));
assertThat(encoded, containsString("\"reference\":\"Organization/65546\""));
}
@Test
public void testEncodeOmitsVersionAndBase() {
Patient p = new Patient();
p.getManagingOrganization().setReference("http://example.com/base/Patient/1/_history/2");
String enc;
enc = ourCtx.newJsonParser().encodeResourceToString(p);
ourLog.info(enc);
assertThat(enc, containsString("\"http://example.com/base/Patient/1\""));
enc = ourCtx.newJsonParser().setServerBaseUrl("http://example.com/base").encodeResourceToString(p);
ourLog.info(enc);
assertThat(enc, containsString("\"Patient/1\""));
enc = ourCtx.newJsonParser().setServerBaseUrl("http://example.com/base2").encodeResourceToString(p);
ourLog.info(enc);
assertThat(enc, containsString("\"http://example.com/base/Patient/1\""));
}
@Test
public void testEncodeQuery() {
Query q = new Query();
ExtensionDt parameter = q.addParameter();
parameter.setUrl("http://hl7.org/fhir/query#_query").setValue(new StringDt("example"));
String val = ourCtx.newJsonParser().encodeResourceToString(q);
ourLog.info(val);
//@formatter:off
String expected =
"{" +
"\"resourceType\":\"Query\"," +
"\"parameter\":[" +
"{" +
"\"url\":\"http://hl7.org/fhir/query#_query\"," +
"\"valueString\":\"example\"" +
"}" +
"]" +
"}";
//@formatter:on
ourLog.info("Expect: {}", expected);
ourLog.info("Got : {}", val);
assertEquals(expected, val);
}
@Test
public void testEncodeResourceRef() throws DataFormatException {
Patient patient = new Patient();
patient.setManagingOrganization(new ResourceReferenceDt());
IParser p = ourCtx.newJsonParser();
String str = p.encodeResourceToString(patient);
assertThat(str, IsNot.not(StringContains.containsString("managingOrganization")));
patient.setManagingOrganization(new ResourceReferenceDt("Organization/123"));
str = p.encodeResourceToString(patient);
assertThat(str, StringContains.containsString("\"managingOrganization\":{\"reference\":\"Organization/123\"}"));
Organization org = new Organization();
org.addIdentifier().setSystem("foo").setValue("bar");
patient.setManagingOrganization(new ResourceReferenceDt(org));
str = p.encodeResourceToString(patient);
assertThat(str, StringContains.containsString("\"contained\":[{\"resourceType\":\"Organization\""));
}
@Test
public void testEncodeUndeclaredExtensionWithAddressContent() {
IParser parser = ourCtx.newJsonParser();
Patient patient = new Patient();
patient.addAddress().setUse(AddressUseEnum.HOME);
patient.addUndeclaredExtension(false, "urn:foo", new AddressDt().addLine("line1"));
String val = parser.encodeResourceToString(patient);
ourLog.info(val);
assertThat(val, StringContains.containsString("\"extension\":[{\"url\":\"urn:foo\",\"valueAddress\":{\"line\":[\"line1\"]}}]"));
MyPatientWithOneDeclaredAddressExtension actual = parser.parseResource(MyPatientWithOneDeclaredAddressExtension.class, val);
assertEquals(AddressUseEnum.HOME, patient.getAddressFirstRep().getUse().getValueAsEnum());
AddressDt ref = actual.getFoo();
assertEquals("line1", ref.getLineFirstRep().getValue());
}
@Test
public void testEncodingNullExtension() {
Patient p = new Patient();
ExtensionDt extension = new ExtensionDt(false, "http://foo#bar");
p.addUndeclaredExtension(extension);
String str = ourCtx.newJsonParser().encodeResourceToString(p);
assertEquals("{\"resourceType\":\"Patient\"}", str);
extension.setValue(new StringDt());
str = ourCtx.newJsonParser().encodeResourceToString(p);
assertEquals("{\"resourceType\":\"Patient\"}", str);
extension.setValue(new StringDt(""));
str = ourCtx.newJsonParser().encodeResourceToString(p);
assertEquals("{\"resourceType\":\"Patient\"}", str);
}
@Test
public void testExtensionOnComposite() throws Exception {
Patient patient = new Patient();
HumanNameDt name = patient.addName();
name.addFamily().setValue("Shmoe");
HumanNameDt given = name.addGiven("Joe");
ExtensionDt ext2 = new ExtensionDt(false, "http://examples.com#givenext", new StringDt("Hello"));
given.addUndeclaredExtension(ext2);
String enc = ourCtx.newJsonParser().encodeResourceToString(patient);
ourLog.info(enc);
assertEquals("{\"resourceType\":\"Patient\",\"name\":[{\"extension\":[{\"url\":\"http://examples.com#givenext\",\"valueString\":\"Hello\"}],\"family\":[\"Shmoe\"],\"given\":[\"Joe\"]}]}", enc);
IParser newJsonParser = ourCtx.newJsonParser();
StringReader reader = new StringReader(enc);
Patient parsed = newJsonParser.parseResource(Patient.class, reader);
ourLog.info(ourCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(parsed));
assertEquals(1, parsed.getNameFirstRep().getUndeclaredExtensionsByUrl("http://examples.com#givenext").size());
ExtensionDt ext = parsed.getNameFirstRep().getUndeclaredExtensionsByUrl("http://examples.com#givenext").get(0);
assertEquals("Hello", ext.getValueAsPrimitive().getValue());
}
@Test
public void testExtensionOnPrimitive() throws Exception {
Patient patient = new Patient();
HumanNameDt name = patient.addName();
StringDt family = name.addFamily();
family.setValue("Shmoe");
ExtensionDt ext2 = new ExtensionDt(false, "http://examples.com#givenext", new StringDt("Hello"));
family.addUndeclaredExtension(ext2);
String enc = ourCtx.newJsonParser().encodeResourceToString(patient);
ourLog.info(enc);
//@formatter:off
assertThat(enc, containsString(("{\n" +
" \"resourceType\":\"Patient\",\n" +
" \"name\":[\n" +
" {\n" +
" \"family\":[\n" +
" \"Shmoe\"\n" +
" ],\n" +
" \"_family\":[\n" +
" {\n" +
" \"extension\":[\n" +
" {\n" +
" \"url\":\"http://examples.com#givenext\",\n" +
" \"valueString\":\"Hello\"\n" +
" }\n" +
" ]\n" +
" }\n" +
" ]\n" +
" }\n" +
" ]\n" +
"}").replace("\n", "").replaceAll(" +", "")));
//@formatter:on
Patient parsed = ourCtx.newJsonParser().parseResource(Patient.class, new StringReader(enc));
assertEquals(1, parsed.getNameFirstRep().getFamilyFirstRep().getUndeclaredExtensionsByUrl("http://examples.com#givenext").size());
ExtensionDt ext = parsed.getNameFirstRep().getFamilyFirstRep().getUndeclaredExtensionsByUrl("http://examples.com#givenext").get(0);
assertEquals("Hello", ext.getValueAsPrimitive().getValue());
}
/**
* #65
*/
@Test
public void testJsonPrimitiveWithExtensionEncoding() {
String res = "{\"resourceType\":\"Questionnaire\",\"status\":\"draft\",\"authored\":\"2014-10-30T14:15:00\",\"subject\":{\"reference\":\"http://www.hl7.org/fhir/Patient/1\"},\"author\":{\"reference\":\"http://www.hl7.org/fhir/Practitioner/1\"},\"name\":{\"text\":\"WDHB Friends and Family Test\"},\"group\":{\"header\":\"Note: This is an anonymous survey, which means you cannot be identified.\",\"_header\":[{\"extension\":[{\"url\":\"http://hl7.org/fhir/Profile/iso-21090#language\",\"valueCode\":\"en\"},{\"url\":\"http://hl7.org/fhir/Profile/iso-21090#string-translation\",\"valueString\":\"è«\\u008b注æ\\u0084\\u008fï¼\\u009aè¿\\u0099æ\\u0098¯ä¸\\u0080个å\\u008c¿å\\u0090\\u008dè°\\u0083æ\\u009f¥ï¼\\u008c被è°\\u0083æ\\u009f¥äººå°\\u0086ä¸\\u008dä¼\\u009a被è¯\\u0086å\\u0088«å\\u0087ºæ\\u009d¥ã\\u0080\\u0082\"},{\"url\":\"http://hl7.org/fhir/Profile/iso-21090#string-translation\",\"valueString\":\"ì\\u009dµëª\\u0085ì\\u009c¼ë¡\\u009c í\\u0095\\u0098ë\\u008a\\u0094 ì\\u0084¤ë¬¸ì¡°ì\\u0082¬ì\\u009d´ë¯\\u0080ë¡\\u009c ì\\u009e\\u0091ì\\u0084±ì\\u009e\\u0090ê°\\u0080 ë\\u0088\\u0084구ì\\u009d¸ì§\\u0080 ë°\\u009dí\\u0098\\u0080ì§\\u0080ì§\\u0080 ì\\u0095\\u008aì\\u008aµë\\u008b\\u0088ë\\u008b¤.\"}]}],\"question\":[{\"extension\":[{\"url\":\"http://hl7.org/fhir/questionnaire-extensions#answerFormat\",\"valueCode\":\"single-choice\"}],\"text\":\"Are you a patient?\",\"options\":{\"reference\":\"#question1\"}}]}}";
Questionnaire parsed = ourCtx.newJsonParser().parseResource(Questionnaire.class, res);
assertEquals("Note: This is an anonymous survey, which means you cannot be identified.", parsed.getGroup().getHeader().getValue());
assertEquals(1, parsed.getGroup().getHeader().getUndeclaredExtensionsByUrl("http://hl7.org/fhir/Profile/iso-21090#language").size());
String encoded = ourCtx.newJsonParser().setPrettyPrint(true).encodeResourceToString(parsed);
ourLog.info(encoded);
assertThat(encoded, containsString("\"_header\":{"));
}
@Test
public void testNarrativeGeneration() throws DataFormatException, IOException {
Patient patient = new Patient();
patient.addName().addFamily("Smith");
Organization org = new Organization();
patient.getManagingOrganization().setResource(org);
INarrativeGenerator gen = new INarrativeGenerator() {
@Override
public void generateNarrative(IBaseResource theResource, BaseNarrativeDt<?> theNarrative) {
throw new UnsupportedOperationException();
}
@Override
public void generateNarrative(String theProfile, IBaseResource theResource, BaseNarrativeDt<?> theNarrative) throws DataFormatException {
theNarrative.getDiv().setValueAsString("<div>help</div>");
theNarrative.getStatus().setValueAsString("generated");
}
@Override
public String generateTitle(IBaseResource theResource) {
throw new UnsupportedOperationException();
}
@Override
public String generateTitle(String theProfile, IBaseResource theResource) {
throw new UnsupportedOperationException();
}
@Override
public void setFhirContext(FhirContext theFhirContext) {
// nothing
}
};
FhirContext context = ourCtx;
context.setNarrativeGenerator(gen);
IParser p = context.newJsonParser();
p.encodeResourceToWriter(patient, new OutputStreamWriter(System.out));
String str = p.encodeResourceToString(patient);
ourLog.info(str);
assertThat(str, StringContains.containsString(",\"text\":{\"status\":\"generated\",\"div\":\"<div>help</div>\"},"));
}
@Before
public void before() {
ourCtx.setNarrativeGenerator(null);
}
@Test
public void testNestedContainedResources() {
Observation A = new Observation();
A.getName().setText("A");
Observation B = new Observation();
B.getName().setText("B");
A.addRelated().setTarget(new ResourceReferenceDt(B));
Observation C = new Observation();
C.getName().setText("C");
B.addRelated().setTarget(new ResourceReferenceDt(C));
String str = ourCtx.newJsonParser().setPrettyPrint(true).encodeResourceToString(A);
ourLog.info(str);
assertThat(str, stringContainsInOrder(Arrays.asList("\"text\":\"B\"", "\"text\":\"C\"", "\"text\":\"A\"")));
// Only one (outer) contained block
int idx0 = str.indexOf("\"contained\"");
int idx1 = str.indexOf("\"contained\"", idx0 + 1);
assertNotEquals(-1, idx0);
assertEquals(-1, idx1);
Observation obs = ourCtx.newJsonParser().parseResource(Observation.class, str);
assertEquals("A", obs.getName().getText().getValue());
Observation obsB = (Observation) obs.getRelatedFirstRep().getTarget().getResource();
assertEquals("B", obsB.getName().getText().getValue());
Observation obsC = (Observation) obsB.getRelatedFirstRep().getTarget().getResource();
assertEquals("C", obsC.getName().getText().getValue());
}
@Test
public void testParseBinaryResource() {
Binary val = ourCtx.newJsonParser().parseResource(Binary.class, "{\"resourceType\":\"Binary\",\"contentType\":\"foo\",\"content\":\"AQIDBA==\"}");
assertEquals("foo", val.getContentType());
assertArrayEquals(new byte[] { 1, 2, 3, 4 }, val.getContent());
}
@Test
public void testParseBundle() throws DataFormatException, IOException {
String msg = IOUtils.toString(XmlParser.class.getResourceAsStream("/atom-document-large.json"));
IParser p = ourCtx.newJsonParser();
Bundle bundle = p.parseBundle(msg);
assertEquals(1, bundle.getCategories().size());
assertEquals("http://scheme", bundle.getCategories().get(0).getScheme());
assertEquals("http://term", bundle.getCategories().get(0).getTerm());
assertEquals("label", bundle.getCategories().get(0).getLabel());
String encoded = ourCtx.newXmlParser().setPrettyPrint(true).encodeBundleToString(bundle);
ourLog.info(encoded);
assertEquals("http://fhir.healthintersections.com.au/open/DiagnosticReport/_search?_format=application/json+fhir&search-id=46d5f0e7-9240-4d4f-9f51-f8ac975c65&search-sort=_id",
bundle.getLinkSelf().getValue());
assertEquals("urn:uuid:0b754ff9-03cf-4322-a119-15019af8a3", bundle.getBundleId().getValue());
BundleEntry entry = bundle.getEntries().get(0);
assertEquals("http://fhir.healthintersections.com.au/open/DiagnosticReport/101", entry.getId().getValue());
assertEquals("http://fhir.healthintersections.com.au/open/DiagnosticReport/101/_history/1", entry.getLinkSelf().getValue());
assertEquals("2014-03-10T11:55:59Z", entry.getUpdated().getValueAsString());
DiagnosticReport res = (DiagnosticReport) entry.getResource();
assertEquals("Complete Blood Count", res.getName().getText().getValue());
assertThat(entry.getSummary().getValueAsString(), containsString("CBC Report for Wile"));
}
@Test
public void testTotalResultsInJsonBundle() {
String json =
"{" +
" \"resourceType\" : \"Bundle\"," +
" \"id\" : \"cb095f55-afb0-41e8-89d5-155259b2a032\"," +
" \"updated\" : \"2015-09-01T08:52:02.793-04:00\"," +
" \"link\" : [{" +
" \"rel\" : \"self\"," +
" \"href\" : \"http://fhirtest.uhn.ca/baseDstu1/Patient/_search?family=Perez\"" +
" }, {" +
" \"rel\" : \"next\"," +
" \"href\" : \"http://fhirtest.uhn.ca/baseDstu1?_getpages=c1db1094-cc46-49f1-ae69-4763ba52458b&_getpagesoffset=10&_count=10&_format=json&_pretty=true\"" +
" }, {" +
" \"rel\" : \"fhir-base\"," +
" \"href\" : \"http://fhirtest.uhn.ca/baseDstu1\"" +
" }" +
" ]," +
" \"totalResults\" : \"1\"," +
" \"entry\" : [{" +
" \"title\" : \"GONZALO PEREZ (DNI20425239)\"," +
" \"id\" : \"http://fhirtest.uhn.ca/baseDstu1/Patient/34834\"," +
" \"link\" : [{" +
" \"rel\" : \"self\"," +
" \"href\" : \"http://fhirtest.uhn.ca/baseDstu1/Patient/34834/_history/1\"" +
" }" +
" ]," +
" \"updated\" : \"2015-06-10T10:39:38.712-04:00\"," +
" \"published\" : \"2015-06-10T10:39:38.665-04:00\"," +
" \"content\" : {" +
" \"resourceType\" : \"Patient\"," +
" \"name\" : [{" +
" \"family\" : [" +
" \"PEREZ\"" +
" ]," +
" \"given\" : [" +
" \"GONZALO\"" +
" ]" +
" }" +
" ]" +
" }" +
" }" +
" ]" +
"}";
IParser jsonParser = ourCtx.newJsonParser();
Bundle bundle = jsonParser.parseBundle(json);
System.out.println("Done");
}
@Test
public void testParseBundleDeletedEntry() {
//@formatter:off
String bundleString =
"{" +
"\"resourceType\":\"Bundle\"," +
"\"totalResults\":\"1\"," +
"\"entry\":[" +
"{" +
"\"deleted\":\"2012-05-29T23:45:32+00:00\"," +
"\"id\":\"http://fhir.furore.com/fhir/Patient/1\"," +
"\"link\":[" +
"{" +
"\"rel\":\"self\"," +
"\"href\":\"http://fhir.furore.com/fhir/Patient/1/_history/2\"" +
"}" +
"]" +
"}" +
"]" +
"}";
//@formatter:on
Bundle bundle = ourCtx.newJsonParser().parseBundle(bundleString);
BundleEntry entry = bundle.getEntries().get(0);
assertEquals("2012-05-29T23:45:32+00:00", entry.getDeletedAt().getValueAsString());
assertEquals("http://fhir.furore.com/fhir/Patient/1/_history/2", entry.getLinkSelf().getValue());
assertEquals("1", entry.getResource().getId().getIdPart());
assertEquals("2", entry.getResource().getId().getVersionIdPart());
assertEquals(new InstantDt("2012-05-29T23:45:32+00:00"), entry.getResource().getResourceMetadata().get(ResourceMetadataKeyEnum.DELETED_AT));
// Now encode
ourLog.info(ourCtx.newJsonParser().setPrettyPrint(true).encodeBundleToString(bundle));
String encoded = ourCtx.newJsonParser().encodeBundleToString(bundle);
assertEquals(bundleString, encoded);
}
@Test
public void testParseBundleFromHI() throws DataFormatException, IOException {
String msg = IOUtils.toString(XmlParser.class.getResourceAsStream("/bundle.json"));
IParser p = ourCtx.newJsonParser();
Bundle bundle = p.parseBundle(msg);
String encoded = ourCtx.newXmlParser().setPrettyPrint(true).encodeBundleToString(bundle);
ourLog.info(encoded);
BundleEntry entry = bundle.getEntries().get(0);
Patient res = (Patient) entry.getResource();
assertEquals("444111234", res.getIdentifierFirstRep().getValue().getValue());
BundleEntry deletedEntry = bundle.getEntries().get(3);
assertEquals("2014-06-20T20:15:49Z", deletedEntry.getDeletedAt().getValueAsString());
}
@Test
public void testParseEmptyNarrative() throws ConfigurationException, DataFormatException, IOException {
//@formatter:off
String text = "{\n" +
" \"resourceType\" : \"Patient\",\n" +
" \"extension\" : [\n" +
" {\n" +
" \"url\" : \"http://clairol.org/colour\",\n" +
" \"valueCode\" : \"B\"\n" +
" }\n" +
" ],\n" +
" \"text\" : {\n" +
" \"div\" : \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\"\n" +
" }" +
"}";
//@formatter:on
Patient res = (Patient) ourCtx.newJsonParser().parseResource(text);
XhtmlDt div = res.getText().getDiv();
String value = div.getValueAsString();
assertEquals("<?xml version=\"1.0\" encoding=\"UTF-8\"?>", value);
assertEquals(null, div.getValue());
}
/**
* This sample has extra elements in <searchParam> that are not actually a part of the spec any more..
*/
@Test
public void testParseFuroreMetadataWithExtraElements() throws IOException {
String msg = IOUtils.toString(JsonParserTest.class.getResourceAsStream("/furore-conformance.json"));
IParser p = ourCtx.newJsonParser();
Conformance conf = p.parseResource(Conformance.class, msg);
RestResource res = conf.getRestFirstRep().getResourceFirstRep();
assertEquals("_id", res.getSearchParam().get(1).getName().getValue());
}
@Test
public void testParseJsonProfile() throws IOException {
parseAndEncode("/patient.profile.json");
parseAndEncode("/alert.profile.json");
}
@Test
public void testParseQuery() {
String msg = "{\n" + " \"resourceType\": \"Query\",\n" + " \"text\": {\n" + " \"status\": \"generated\",\n" + " \"div\": \"<div>[Put rendering here]</div>\"\n" + " },\n"
+ " \"identifier\": \"urn:uuid:42b253f5-fa17-40d0-8da5-44aeb4230376\",\n" + " \"parameter\": [\n" + " {\n" + " \"url\": \"http://hl7.org/fhir/query#_query\",\n"
+ " \"valueString\": \"example\"\n" + " }\n" + " ]\n" + "}";
Query query = ourCtx.newJsonParser().parseResource(Query.class, msg);
assertEquals("urn:uuid:42b253f5-fa17-40d0-8da5-44aeb4230376", query.getIdentifier().getValueAsString());
assertEquals("http://hl7.org/fhir/query#_query", query.getParameterFirstRep().getUrlAsString());
assertEquals("example", query.getParameterFirstRep().getValueAsPrimitive().getValueAsString());
}
@Test
public void testParseSingleQuotes() {
try {
ourCtx.newJsonParser().parseBundle("{ 'resourceType': 'Bundle' }");
fail();
} catch (DataFormatException e) {
// Should be an error message about how single quotes aren't valid JSON
assertThat(e.getMessage(), containsString("double quote"));
}
}
@Test
public void testParseWithContained() throws DataFormatException, IOException {
String msg = IOUtils.toString(XmlParser.class.getResourceAsStream("/diagnostic-report.json"));
IParser p = ourCtx.newJsonParser();
// ourLog.info("Reading in message: {}", msg);
DiagnosticReport res = p.parseResource(DiagnosticReport.class, msg);
String encoded = ourCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(res);
ourLog.info(encoded);
ResourceReferenceDt reference = res.getResult().get(1);
Observation obs = (Observation) reference.getResource();
assertEquals("789-8", obs.getName().getCoding().get(0).getCode().getValue());
}
/**
* HAPI FHIR < 0.6 incorrectly used "resource" instead of "reference"
*/
@Test
public void testParseWithIncorrectReference() throws IOException {
String jsonString = IOUtils.toString(JsonParser.class.getResourceAsStream("/example-patient-general.json"));
jsonString = jsonString.replace("\"reference\"", "\"resource\"");
Patient parsed = ourCtx.newJsonParser().parseResource(Patient.class, jsonString);
assertEquals("Organization/1", parsed.getManagingOrganization().getReference().getValue());
}
@SuppressWarnings("unused")
@Test
public void testParseWithIncorrectResourceType() {
String input = "{\"resourceType\":\"Patient\"}";
try {
IParser parser = ourCtx.newJsonParser();
Organization o = parser.parseResource(Organization.class, input);
fail();
} catch (DataFormatException e) {
assertThat(e.getMessage(), containsString("expected \"Organization\" but found \"Patient\""));
}
}
@Test
public void testSimpleBundleEncode() throws IOException {
String xmlString = IOUtils.toString(JsonParser.class.getResourceAsStream("/atom-document-large.xml"), Charset.forName("UTF-8"));
Bundle obs = ourCtx.newXmlParser().parseBundle(xmlString);
String encoded = ourCtx.newJsonParser().setPrettyPrint(true).encodeBundleToString(obs);
ourLog.info(encoded);
}
@Test
public void testSimpleParse() throws DataFormatException, IOException {
String msg = IOUtils.toString(XmlParser.class.getResourceAsStream("/example-patient-general.json"));
IParser p = ourCtx.newJsonParser();
// ourLog.info("Reading in message: {}", msg);
Patient res = p.parseResource(Patient.class, msg);
assertEquals(2, res.getUndeclaredExtensions().size());
assertEquals(1, res.getUndeclaredModifierExtensions().size());
String encoded = ourCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(res);
ourLog.info(encoded);
}
@Test
public void testSimpleResourceEncode() throws IOException {
String xmlString = IOUtils.toString(JsonParser.class.getResourceAsStream("/example-patient-general.xml"), Charset.forName("UTF-8"));
Patient obs = ourCtx.newXmlParser().parseResource(Patient.class, xmlString);
List<ExtensionDt> undeclaredExtensions = obs.getContact().get(0).getName().getFamily().get(0).getUndeclaredExtensions();
ExtensionDt undeclaredExtension = undeclaredExtensions.get(0);
assertEquals("http://hl7.org/fhir/Profile/iso-21090#qualifier", undeclaredExtension.getUrl());
ourCtx.newJsonParser().setPrettyPrint(true).encodeResourceToWriter(obs, new OutputStreamWriter(System.out));
IParser jsonParser = ourCtx.newJsonParser();
String encoded = jsonParser.encodeResourceToString(obs);
ourLog.info(encoded);
String jsonString = IOUtils.toString(JsonParser.class.getResourceAsStream("/example-patient-general.json"), Charset.forName("UTF-8"));
JSON expected = JSONSerializer.toJSON(jsonString);
JSON actual = JSONSerializer.toJSON(encoded.trim());
// The encoded escapes quote marks using XML escaping instead of JSON escaping, which is probably nicer anyhow...
String exp = expected.toString().replace("\\\"Jim\\\"", ""Jim"");
String act = actual.toString();
ourLog.info("Expected: {}", exp);
ourLog.info("Actual : {}", act);
assertEquals(exp, act);
}
@Test
public void testSimpleResourceEncodeWithCustomType() throws IOException {
FhirContext fhirCtx = new FhirContext(MyPatientWithExtensions.class);
String xmlString = IOUtils.toString(JsonParser.class.getResourceAsStream("/example-patient-general.xml"), Charset.forName("UTF-8"));
MyPatientWithExtensions obs = fhirCtx.newXmlParser().parseResource(MyPatientWithExtensions.class, xmlString);
assertEquals(0, obs.getAllUndeclaredExtensions().size());
assertEquals("aaaa", obs.getExtAtt().getContentType().getValue());
assertEquals("str1", obs.getMoreExt().getStr1().getValue());
assertEquals("2011-01-02", obs.getModExt().getValueAsString());
List<ExtensionDt> undeclaredExtensions = obs.getContact().get(0).getName().getFamily().get(0).getUndeclaredExtensions();
ExtensionDt undeclaredExtension = undeclaredExtensions.get(0);
assertEquals("http://hl7.org/fhir/Profile/iso-21090#qualifier", undeclaredExtension.getUrl());
IParser jsonParser = fhirCtx.newJsonParser().setPrettyPrint(true);
String encoded = jsonParser.encodeResourceToString(obs);
ourLog.info(encoded);
String jsonString = IOUtils.toString(JsonParser.class.getResourceAsStream("/example-patient-general.json"), Charset.forName("UTF-8"));
JSON expected = JSONSerializer.toJSON(jsonString);
JSON actual = JSONSerializer.toJSON(encoded.trim());
// The encoded escapes quote marks using XML escaping instead of JSON escaping, which is probably nicer anyhow...
String exp = expected.toString().replace("\\\"Jim\\\"", ""Jim"");
String act = actual.toString();
ourLog.info("Expected: {}", exp);
ourLog.info("Actual : {}", act);
assertEquals(exp, act);
}
@Test
public void testTagList() {
//@formatter:off
String tagListStr = "{\n" +
" \"resourceType\" : \"TagList\", " +
" \"category\" : [" +
" { " +
" \"term\" : \"term0\", " +
" \"label\" : \"label0\", " +
" \"scheme\" : \"scheme0\" " +
" }," +
" { " +
" \"term\" : \"term1\", " +
" \"label\" : \"label1\", " +
" \"scheme\" : null " +
" }," +
" { " +
" \"term\" : \"term2\", " +
" \"label\" : \"label2\" " +
" }" +
" ] " +
"}";
//@formatter:on
TagList tagList = ourCtx.newJsonParser().parseTagList(tagListStr);
assertEquals(3, tagList.size());
assertEquals("term0", tagList.get(0).getTerm());
assertEquals("label0", tagList.get(0).getLabel());
assertEquals("scheme0", tagList.get(0).getScheme());
assertEquals("term1", tagList.get(1).getTerm());
assertEquals("label1", tagList.get(1).getLabel());
assertEquals(null, tagList.get(1).getScheme());
assertEquals("term2", tagList.get(2).getTerm());
assertEquals("label2", tagList.get(2).getLabel());
assertEquals(null, tagList.get(2).getScheme());
/*
* Encode
*/
//@formatter:off
String expected = "{" +
"\"resourceType\":\"TagList\"," +
"\"category\":[" +
"{" +
"\"term\":\"term0\"," +
"\"label\":\"label0\"," +
"\"scheme\":\"scheme0\"" +
"}," +
"{" +
"\"term\":\"term1\"," +
"\"label\":\"label1\"" +
"}," +
"{" +
"\"term\":\"term2\"," +
"\"label\":\"label2\"" +
"}" +
"]" +
"}";
//@formatter:on
String encoded = ourCtx.newJsonParser().encodeTagListToString(tagList);
assertEquals(expected, encoded);
}
@BeforeClass
public static void beforeClass() {
ourCtx = FhirContext.forDstu1();
}
@ResourceDef(name = "Patient")
public static class MyPatientWithOneDeclaredAddressExtension extends Patient {
@Child(order = 0, name = "foo")
@Extension(url = "urn:foo", definedLocally = true, isModifier = false)
private AddressDt myFoo;
public AddressDt getFoo() {
return myFoo;
}
public void setFoo(AddressDt theFoo) {
myFoo = theFoo;
}
}
@ResourceDef(name = "Patient")
public static class MyPatientWithOneDeclaredExtension extends Patient {
@Child(order = 0, name = "foo")
@Extension(url = "urn:foo", definedLocally = true, isModifier = false)
private ResourceReferenceDt myFoo;
public ResourceReferenceDt getFoo() {
return myFoo;
}
public void setFoo(ResourceReferenceDt theFoo) {
myFoo = theFoo;
}
}
}
|
Fix #214 - more failing bundle stuff
|
hapi-fhir-structures-dstu/src/test/java/ca/uhn/fhir/parser/JsonParserTest.java
|
Fix #214 - more failing bundle stuff
|
<ide><path>api-fhir-structures-dstu/src/test/java/ca/uhn/fhir/parser/JsonParserTest.java
<ide>
<ide> }
<ide>
<add> @Ignore
<ide> @Test
<ide> public void testTotalResultsInJsonBundle() {
<ide> String json =
<ide> "{" +
<ide> " \"resourceType\" : \"Bundle\"," +
<add> " \"title\" : \"FHIR Atom Feed\"," +
<ide> " \"id\" : \"cb095f55-afb0-41e8-89d5-155259b2a032\"," +
<ide> " \"updated\" : \"2015-09-01T08:52:02.793-04:00\"," +
<add> " \"author\": [" +
<add> " {" +
<add> " \"name\": \"author-name\", " +
<add> " \"uri\": \"uri\" " +
<add> " }" +
<add> " ]," +
<ide> " \"link\" : [{" +
<ide> " \"rel\" : \"self\"," +
<ide> " \"href\" : \"http://fhirtest.uhn.ca/baseDstu1/Patient/_search?family=Perez\"" +
<ide>
<ide> IParser jsonParser = ourCtx.newJsonParser();
<ide> Bundle bundle = jsonParser.parseBundle(json);
<del> System.out.println("Done");
<del>
<ide> }
<ide>
<ide> @Test
|
|
JavaScript
|
apache-2.0
|
ae2e7fde4a7bdd0a322730840c0eb23a1c709e99
| 0 |
CCI-MOC/GUI-Frontend,CCI-MOC/GUI-Frontend,CCI-MOC/GUI-Frontend,CCI-MOC/GUI-Frontend,CCI-MOC/GUI-Frontend
|
define(
[
'dispatchers/AppDispatcher',
'constants/InstanceConstants',
'constants/ProjectInstanceConstants',
'models/Instance',
'models/InstanceState',
'globals',
'context',
'url',
'./modalHelpers/InstanceModalHelpers',
'controllers/NotificationController',
'actions/ProjectInstanceActions'
],
function (AppDispatcher, InstanceConstants, ProjectInstanceConstants, Instance, InstanceState, globals, context, URL, InstanceModalHelpers, NotificationController, ProjectInstanceActions) {
return {
dispatch: function(actionType, payload, options){
options = options || {};
AppDispatcher.handleRouteAction({
actionType: actionType,
payload: payload,
options: options
});
},
// ------------------------
// Standard CRUD Operations
// ------------------------
updateInstanceAttributes: function (instance, newAttributes) {
var that = this;
instance.set(newAttributes);
that.dispatch(InstanceConstants.UPDATE_INSTANCE, {instance: instance});
instance.save({
name: instance.get('name'),
tags: instance.get('tags')
}, {
patch: true
}).done(function () {
//NotificationController.success(null, "Instance name and tags updated");
that.dispatch(InstanceConstants.UPDATE_INSTANCE, {instance: instance});
}).fail(function () {
var message = "Error updating Instance " + instance.get('name') + ".";
NotificationController.error(message);
that.dispatch(InstanceConstants.UPDATE_INSTANCE, {instance: instance});
});
},
addTagToInstance: function(tag, instance){
var that = this;
var instanceTags = instance.get('tags');
instanceTags.push(tag.get('name'));
instance.set({tags: instanceTags});
that.dispatch(InstanceConstants.UPDATE_INSTANCE, {instance: instance});
instance.save({
tags: instanceTags
}, {
patch: true
}).done(function () {
that.dispatch(InstanceConstants.UPDATE_INSTANCE, {instance: instance});
}).fail(function () {
NotificationController.error(null, "Error adding tag to Instance");
that.dispatch(InstanceConstants.UPDATE_INSTANCE, {instance: instance});
});
},
_terminate: function(payload, options){
var instance = payload.instance;
var project = payload.project;
var that = this;
that.dispatch(InstanceConstants.REMOVE_INSTANCE, {instance: instance});
instance.destroy().done(function () {
NotificationController.success(null, 'Instance terminated');
// poll until the instance is actually terminated
//that.dispatch(InstanceConstants.POLL_INSTANCE, {instance: instance});
ProjectInstanceActions.removeInstanceFromProject(instance, project);
}).fail(function (response) {
NotificationController.error(null, 'Instance could not be terminated');
that.dispatch(InstanceConstants.ADD_INSTANCE, {instance: instance});
});
},
terminate: function(payload, options){
var instance = payload.instance;
var redirectUrl = payload.redirectUrl;
var project = payload.project;
var that = this;
InstanceModalHelpers.terminate({
instance: instance
},{
onConfirm: function () {
that._terminate(payload, options);
if(redirectUrl) Backbone.history.navigate(redirectUrl, {trigger: true});
}
});
},
terminate_noModal: function(payload, options){
this._terminate(payload, options);
},
// ----------------
// Instance Actions
// ----------------
suspend: function (instance) {
var that = this;
var instanceState = new InstanceState({status_raw: "active - suspending"});
instance.set({state: instanceState});
that.dispatch(InstanceConstants.UPDATE_INSTANCE, {instance: instance});
InstanceModalHelpers.suspend({
instance: instance
},{
onConfirm: function () {
var instanceState = new InstanceState({status_raw: "active - suspending"});
instance.set({state: instanceState});
that.dispatch(InstanceConstants.UPDATE_INSTANCE, {instance: instance});
instance.suspend({
success: function (model) {
NotificationController.success(null, "Your instance is suspending...");
var instanceState = new InstanceState({status_raw: "active - suspending"});
instance.set({state: instanceState});
that.dispatch(InstanceConstants.UPDATE_INSTANCE, {instance: instance});
that.dispatch(InstanceConstants.POLL_INSTANCE, {instance: instance});
},
error: function (response) {
NotificationController.error(null, "Your instance could not be suspended");
}
});
}
});
},
resume: function(instance){
var that = this;
InstanceModalHelpers.resume({
instance: instance
},{
onConfirm: function () {
var instanceState = new InstanceState({status_raw: "suspended - resuming"});
instance.set({state: instanceState});
that.dispatch(InstanceConstants.UPDATE_INSTANCE, {instance: instance});
instance.resume({
success: function (model) {
NotificationController.success(null, "Your instance is resuming...");
var instanceState = new InstanceState({status_raw: "suspended - resuming"});
instance.set({state: instanceState});
that.dispatch(InstanceConstants.UPDATE_INSTANCE, {instance: instance});
that.dispatch(InstanceConstants.POLL_INSTANCE, {instance: instance});
},
error: function (response) {
NotificationController.error(null, "Your instance could not be resumed");
}
});
}
});
},
stop: function(instance){
var that = this;
InstanceModalHelpers.stop({
instance: instance
},{
onConfirm: function () {
var instanceState = new InstanceState({status_raw: "active - powering-off"});
instance.set({state: instanceState});
that.dispatch(InstanceConstants.UPDATE_INSTANCE, {instance: instance});
instance.stop({
success: function (model) {
NotificationController.success(null, "Your instance is stopping...");
var instanceState = new InstanceState({status_raw: "active - powering-off"});
instance.set({state: instanceState});
that.dispatch(InstanceConstants.UPDATE_INSTANCE, {instance: instance});
that.dispatch(InstanceConstants.POLL_INSTANCE, {instance: instance});
},
error: function (response) {
NotificationController.error(null, "Your instance could not be stopped");
}
});
}
});
},
start: function(instance){
var that = this;
InstanceModalHelpers.start({
instance: instance
},{
onConfirm: function () {
var instanceState = new InstanceState({status_raw: "shutoff - powering-on"});
instance.set({state: instanceState});
that.dispatch(InstanceConstants.UPDATE_INSTANCE, {instance: instance});
instance.start({
success: function (model) {
NotificationController.success(null, "Your instance is starting...");
var instanceState = new InstanceState({status_raw: "shutoff - powering-on"});
instance.set({state: instanceState});
that.dispatch(InstanceConstants.UPDATE_INSTANCE, {instance: instance});
that.dispatch(InstanceConstants.POLL_INSTANCE, {instance: instance});
},
error: function (response) {
NotificationController.error(null, "Your instance could not be started");
}
});
}
});
},
launch: function(application){
var that = this;
InstanceModalHelpers.launch({
application: application
},{
onConfirm: function (identity, machineId, sizeId, instanceName, project) {
var instance = new Instance({
identity: {
id: identity.id,
provider: identity.get('provider_id')
},
status: "build - scheduling"
}, {parse: true});
var params = {
machine_alias: machineId,
size_alias: sizeId,
name: instanceName
};
that.dispatch(InstanceConstants.ADD_INSTANCE, {instance: instance});
that.dispatch(ProjectInstanceConstants.ADD_PENDING_INSTANCE_TO_PROJECT, {
instance: instance,
project: project
});
instance.save(params, {
success: function (model) {
NotificationController.success(null, 'Instance launching...');
that.dispatch(InstanceConstants.UPDATE_INSTANCE, {instance: instance});
that.dispatch(InstanceConstants.POLL_INSTANCE, {instance: instance});
that.dispatch(ProjectInstanceConstants.REMOVE_PENDING_INSTANCE_FROM_PROJECT, {
instance: instance,
project: project
});
ProjectInstanceActions.addInstanceToProject(instance, project);
},
error: function (response) {
NotificationController.error(null, 'Instance could not be launched');
that.dispatch(InstanceConstants.REMOVE_INSTANCE, {instance: instance});
that.dispatch(ProjectInstanceConstants.REMOVE_PENDING_INSTANCE_FROM_PROJECT, {
instance: instance,
project: project
});
}
});
// Since this is triggered from the images page, navigate off
// that page and back to the instance list so the user can see
// their instance being created
var redirectUrl = URL.project(project, {relative: true});
Backbone.history.navigate(redirectUrl, {trigger: true});
}
});
},
requestImage: function(instance, requestData){
var providerId = instance.getCreds().provider_id;
var identityId = instance.getCreds().identity_id;
var requestUrl = globals.API_ROOT + "/provider/" + providerId + "/identity/" + identityId + "/request_image" + globals.slash();
$.ajax({
url: requestUrl,
type: 'POST',
data: JSON.stringify(requestData),
dataType: 'json',
contentType: 'application/json',
success: function (model) {
NotificationController.info(null, "An image of your instance has been requested");
},
error: function (response, status, error) {
console.log(response.responseText);
NotificationController.error(null, "An image of your instance could not be requested");
}
});
},
reportInstance: function(instance, reportInfo){
var reportUrl = globals.API_ROOT + "/email/support" + globals.slash();
var problemText = "";
if(reportInfo.problems){
_.each(reportInfo.problems, function(problem){
problemText = problemText + " -" + problem + "\n";
})
}
var username = context.profile.get('username');
var reportData = {
username: username,
message: "Instance IP: " + instance.get('ip_address') + "\n" +
"Instance ID: " + instance.id + "\n" +
"Provider ID: " + instance.get('identity').provider + "\n" +
"\n" +
"Problems" + "\n" +
problemText + "\n" +
"Message \n" +
reportInfo.message + "\n",
subject: "Atmosphere Instance Report from " + username
};
$.ajax({
url: reportUrl,
type: 'POST',
data: JSON.stringify(reportData),
dataType: 'json',
contentType: 'application/json',
success: function (model) {
NotificationController.info(null, "Your instance report has been sent to support.");
var instanceUrl = URL.instance(instance);
Backbone.history.navigate(instanceUrl, {trigger: true});
},
error: function (response, status, error) {
console.log(response.responseText);
NotificationController.error(null, "Your instance report could not be sent to support");
}
});
}
};
});
|
troposphere/static/js/actions/InstanceActions.js
|
define(
[
'dispatchers/AppDispatcher',
'constants/InstanceConstants',
'constants/ProjectInstanceConstants',
'models/Instance',
'models/InstanceState',
'globals',
'context',
'url',
'./modalHelpers/InstanceModalHelpers',
'controllers/NotificationController',
'actions/ProjectInstanceActions'
],
function (AppDispatcher, InstanceConstants, ProjectInstanceConstants, Instance, InstanceState, globals, context, URL, InstanceModalHelpers, NotificationController, ProjectInstanceActions) {
return {
dispatch: function(actionType, payload, options){
options = options || {};
AppDispatcher.handleRouteAction({
actionType: actionType,
payload: payload,
options: options
});
},
// ------------------------
// Standard CRUD Operations
// ------------------------
updateInstanceAttributes: function (instance, newAttributes) {
var that = this;
instance.set(newAttributes);
that.dispatch(InstanceConstants.UPDATE_INSTANCE, {instance: instance});
instance.save({
name: instance.get('name'),
tags: instance.get('tags')
}, {
patch: true
}).done(function () {
NotificationController.success(null, "Instance name and tags updated");
that.dispatch(InstanceConstants.UPDATE_INSTANCE, {instance: instance});
}).fail(function () {
var message = "Error updating Instance " + instance.get('name') + ".";
NotificationController.error(message);
that.dispatch(InstanceConstants.UPDATE_INSTANCE, {instance: instance});
});
},
addTagToInstance: function(tag, instance){
var that = this;
var instanceTags = instance.get('tags');
instanceTags.push(tag.get('name'));
instance.set({tags: instanceTags});
that.dispatch(InstanceConstants.UPDATE_INSTANCE, {instance: instance});
instance.save({
tags: instanceTags
}, {
patch: true
}).done(function () {
that.dispatch(InstanceConstants.UPDATE_INSTANCE, {instance: instance});
}).fail(function () {
NotificationController.error(null, "Error adding tag to Instance");
that.dispatch(InstanceConstants.UPDATE_INSTANCE, {instance: instance});
});
},
_terminate: function(payload, options){
var instance = payload.instance;
var project = payload.project;
var that = this;
that.dispatch(InstanceConstants.REMOVE_INSTANCE, {instance: instance});
instance.destroy().done(function () {
NotificationController.success(null, 'Instance terminated');
// poll until the instance is actually terminated
//that.dispatch(InstanceConstants.POLL_INSTANCE, {instance: instance});
ProjectInstanceActions.removeInstanceFromProject(instance, project);
}).fail(function (response) {
NotificationController.error(null, 'Instance could not be terminated');
that.dispatch(InstanceConstants.ADD_INSTANCE, {instance: instance});
});
},
terminate: function(payload, options){
var instance = payload.instance;
var redirectUrl = payload.redirectUrl;
var project = payload.project;
var that = this;
InstanceModalHelpers.terminate({
instance: instance
},{
onConfirm: function () {
that._terminate(payload, options);
if(redirectUrl) Backbone.history.navigate(redirectUrl, {trigger: true});
}
});
},
terminate_noModal: function(payload, options){
this._terminate(payload, options);
},
// ----------------
// Instance Actions
// ----------------
suspend: function (instance) {
var that = this;
var instanceState = new InstanceState({status_raw: "active - suspending"});
instance.set({state: instanceState});
that.dispatch(InstanceConstants.UPDATE_INSTANCE, {instance: instance});
InstanceModalHelpers.suspend({
instance: instance
},{
onConfirm: function () {
var instanceState = new InstanceState({status_raw: "active - suspending"});
instance.set({state: instanceState});
that.dispatch(InstanceConstants.UPDATE_INSTANCE, {instance: instance});
instance.suspend({
success: function (model) {
NotificationController.success(null, "Your instance is suspending...");
var instanceState = new InstanceState({status_raw: "active - suspending"});
instance.set({state: instanceState});
that.dispatch(InstanceConstants.UPDATE_INSTANCE, {instance: instance});
that.dispatch(InstanceConstants.POLL_INSTANCE, {instance: instance});
},
error: function (response) {
NotificationController.error(null, "Your instance could not be suspended");
}
});
}
});
},
resume: function(instance){
var that = this;
InstanceModalHelpers.resume({
instance: instance
},{
onConfirm: function () {
var instanceState = new InstanceState({status_raw: "suspended - resuming"});
instance.set({state: instanceState});
that.dispatch(InstanceConstants.UPDATE_INSTANCE, {instance: instance});
instance.resume({
success: function (model) {
NotificationController.success(null, "Your instance is resuming...");
var instanceState = new InstanceState({status_raw: "suspended - resuming"});
instance.set({state: instanceState});
that.dispatch(InstanceConstants.UPDATE_INSTANCE, {instance: instance});
that.dispatch(InstanceConstants.POLL_INSTANCE, {instance: instance});
},
error: function (response) {
NotificationController.error(null, "Your instance could not be resumed");
}
});
}
});
},
stop: function(instance){
var that = this;
InstanceModalHelpers.stop({
instance: instance
},{
onConfirm: function () {
var instanceState = new InstanceState({status_raw: "active - powering-off"});
instance.set({state: instanceState});
that.dispatch(InstanceConstants.UPDATE_INSTANCE, {instance: instance});
instance.stop({
success: function (model) {
NotificationController.success(null, "Your instance is stopping...");
var instanceState = new InstanceState({status_raw: "active - powering-off"});
instance.set({state: instanceState});
that.dispatch(InstanceConstants.UPDATE_INSTANCE, {instance: instance});
that.dispatch(InstanceConstants.POLL_INSTANCE, {instance: instance});
},
error: function (response) {
NotificationController.error(null, "Your instance could not be stopped");
}
});
}
});
},
start: function(instance){
var that = this;
InstanceModalHelpers.start({
instance: instance
},{
onConfirm: function () {
var instanceState = new InstanceState({status_raw: "shutoff - powering-on"});
instance.set({state: instanceState});
that.dispatch(InstanceConstants.UPDATE_INSTANCE, {instance: instance});
instance.start({
success: function (model) {
NotificationController.success(null, "Your instance is starting...");
var instanceState = new InstanceState({status_raw: "shutoff - powering-on"});
instance.set({state: instanceState});
that.dispatch(InstanceConstants.UPDATE_INSTANCE, {instance: instance});
that.dispatch(InstanceConstants.POLL_INSTANCE, {instance: instance});
},
error: function (response) {
NotificationController.error(null, "Your instance could not be started");
}
});
}
});
},
launch: function(application){
var that = this;
InstanceModalHelpers.launch({
application: application
},{
onConfirm: function (identity, machineId, sizeId, instanceName, project) {
var instance = new Instance({
identity: {
id: identity.id,
provider: identity.get('provider_id')
},
status: "build - scheduling"
}, {parse: true});
var params = {
machine_alias: machineId,
size_alias: sizeId,
name: instanceName
};
that.dispatch(InstanceConstants.ADD_INSTANCE, {instance: instance});
that.dispatch(ProjectInstanceConstants.ADD_PENDING_INSTANCE_TO_PROJECT, {
instance: instance,
project: project
});
instance.save(params, {
success: function (model) {
NotificationController.success(null, 'Instance launching...');
that.dispatch(InstanceConstants.UPDATE_INSTANCE, {instance: instance});
that.dispatch(InstanceConstants.POLL_INSTANCE, {instance: instance});
that.dispatch(ProjectInstanceConstants.REMOVE_PENDING_INSTANCE_FROM_PROJECT, {
instance: instance,
project: project
});
ProjectInstanceActions.addInstanceToProject(instance, project);
},
error: function (response) {
NotificationController.error(null, 'Instance could not be launched');
that.dispatch(InstanceConstants.REMOVE_INSTANCE, {instance: instance});
that.dispatch(ProjectInstanceConstants.REMOVE_PENDING_INSTANCE_FROM_PROJECT, {
instance: instance,
project: project
});
}
});
// Since this is triggered from the images page, navigate off
// that page and back to the instance list so the user can see
// their instance being created
var redirectUrl = URL.project(project, {relative: true});
Backbone.history.navigate(redirectUrl, {trigger: true});
}
});
},
requestImage: function(instance, requestData){
var providerId = instance.getCreds().provider_id;
var identityId = instance.getCreds().identity_id;
var requestUrl = globals.API_ROOT + "/provider/" + providerId + "/identity/" + identityId + "/request_image" + globals.slash();
$.ajax({
url: requestUrl,
type: 'POST',
data: JSON.stringify(requestData),
dataType: 'json',
contentType: 'application/json',
success: function (model) {
NotificationController.info(null, "An image of your instance has been requested");
},
error: function (response, status, error) {
console.log(response.responseText);
NotificationController.error(null, "An image of your instance could not be requested");
}
});
},
reportInstance: function(instance, reportInfo){
var reportUrl = globals.API_ROOT + "/email/support" + globals.slash();
var problemText = "";
if(reportInfo.problems){
_.each(reportInfo.problems, function(problem){
problemText = problemText + " -" + problem + "\n";
})
}
var username = context.profile.get('username');
var reportData = {
username: username,
message: "Instance IP: " + instance.get('ip_address') + "\n" +
"Instance ID: " + instance.id + "\n" +
"Provider ID: " + instance.get('identity').provider + "\n" +
"\n" +
"Problems" + "\n" +
problemText + "\n" +
"Message \n" +
reportInfo.message + "\n",
subject: "Atmosphere Instance Report from " + username
};
$.ajax({
url: reportUrl,
type: 'POST',
data: JSON.stringify(reportData),
dataType: 'json',
contentType: 'application/json',
success: function (model) {
NotificationController.info(null, "Your instance report has been sent to support.");
var instanceUrl = URL.instance(instance);
Backbone.history.navigate(instanceUrl, {trigger: true});
},
error: function (response, status, error) {
console.log(response.responseText);
NotificationController.error(null, "Your instance report could not be sent to support");
}
});
}
};
});
|
disable instance update success notification
|
troposphere/static/js/actions/InstanceActions.js
|
disable instance update success notification
|
<ide><path>roposphere/static/js/actions/InstanceActions.js
<ide> }, {
<ide> patch: true
<ide> }).done(function () {
<del> NotificationController.success(null, "Instance name and tags updated");
<add> //NotificationController.success(null, "Instance name and tags updated");
<ide> that.dispatch(InstanceConstants.UPDATE_INSTANCE, {instance: instance});
<ide> }).fail(function () {
<ide> var message = "Error updating Instance " + instance.get('name') + ".";
|
|
Java
|
apache-2.0
|
0356c9d349fd76b43fcd9d4ba164327d387d4934
| 0 |
dblevins/bval,apache/bval
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.bval.jsr.util;
import javax.validation.ValidationException;
import org.apache.commons.lang3.StringEscapeUtils;
import java.io.StringWriter;
import java.text.ParsePosition;
import java.util.logging.Logger;
/**
* Defines a path navigation algorithm and a means of interacting with same.
*
* @version $Rev: 1136233 $ $Date: 2011-06-15 17:49:27 -0500 (Wed, 15 Jun 2011) $
*/
public class PathNavigation {
/**
* Path traversal callback function interface.
*/
public interface Callback<T> {
/**
* Handle a .-delimited property.
*
* @param name
*/
void handleProperty(String name);
/**
* Handle an index or key embedded in [].
*
* @param value
*/
void handleIndexOrKey(String value);
/**
* Handle contiguous [].
*/
void handleGenericInIterable();
/**
* Return a result. Called after navigation is complete.
*
* @return result
*/
T result();
}
/**
* Callback "procedure" that always returns null.
*/
public static abstract class CallbackProcedure implements Callback<Object> {
/**
* {@inheritDoc}
*/
@Override
public final Object result() {
complete();
return null;
}
/**
* Complete this CallbackProcedure. Default implementation is noop.
*/
protected void complete() {
}
}
private static final Logger LOG = Logger.getLogger(PathNavigation.class.getName());
private static final boolean COMMONS_LANG3_AVAILABLE;
static {
boolean b = true;
try {
new StringEscapeUtils();
} catch (Exception e) {
b = false;
LOG.warning("Apache commons-lang3 is not on the classpath; Java escaping in quotes will not be available.");
}
COMMONS_LANG3_AVAILABLE = b;
}
/**
* Create a new PathNavigation instance.
*/
private PathNavigation() {
}
/**
* Navigate a path using the specified callback, returning its result.
*
* @param <T>
* @param propertyPath
* , null is assumed empty/root
* @param callback
* @return T result
*/
public static <T> T navigateAndReturn(CharSequence propertyPath, Callback<? extends T> callback) {
try {
parse(propertyPath == null ? "" : propertyPath, new PathPosition(callback));
} catch (ValidationException ex) {
throw ex;
} catch (Exception ex) {
throw new ValidationException(String.format("invalid property: %s", propertyPath), ex);
}
return callback.result();
}
/**
* Navigate a path using the specified callback.
*
* @param propertyPath
* @param callback
*/
public static void navigate(CharSequence propertyPath, Callback<?> callback) {
navigateAndReturn(propertyPath, callback);
}
private static void parse(CharSequence path, PathPosition pos) throws Exception {
int len = path.length();
boolean sep = true;
while (pos.getIndex() < len) {
int here = pos.getIndex();
char c = path.charAt(here);
switch (c) {
case ']':
throw new IllegalStateException(String.format("Position %s: unexpected '%s'", here, c));
case '[':
handleIndex(path, pos.next());
break;
case '.':
if (sep) {
throw new IllegalStateException(
String.format("Position %s: expected property, index/key, or end of expression", here));
}
sep = true;
pos.next();
// fall through:
default:
if (!sep) {
throw new IllegalStateException(String.format(
"Position %s: expected property path separator, index/key, or end of expression", here));
}
pos.handleProperty(parseProperty(path, pos));
}
sep = false;
}
}
private static String parseProperty(CharSequence path, PathPosition pos) throws Exception {
int len = path.length();
int start = pos.getIndex();
loop: while (pos.getIndex() < len) {
switch (path.charAt(pos.getIndex())) {
case '[':
case ']':
case '.':
break loop;
}
pos.next();
}
if (pos.getIndex() > start) {
return path.subSequence(start, pos.getIndex()).toString();
}
throw new IllegalStateException(String.format("Position %s: expected property", start));
}
/**
* Handles an index/key. If the text contained between [] is surrounded by a pair of " or ', it will be treated as a
* string which may contain Java escape sequences. This function is only available if commons-lang3 is available on the classpath!
*
* @param path
* @param pos
* @throws Exception
*/
private static void handleIndex(CharSequence path, PathPosition pos) throws Exception {
int len = path.length();
int start = pos.getIndex();
if (start < len) {
char first = path.charAt(pos.getIndex());
if (first == '"' || first == '\'') {
String s = parseQuotedString(path, pos);
if (s != null && path.charAt(pos.getIndex()) == ']') {
pos.handleIndexOrKey(s);
pos.next();
return;
}
}
// no quoted string; match ] greedily
while (pos.getIndex() < len) {
int here = pos.getIndex();
try {
if (path.charAt(here) == ']') {
if (here == start) {
pos.handleGenericInIterable();
} else {
pos.handleIndexOrKey(path.subSequence(start, here).toString());
}
return;
}
} finally {
pos.next();
}
}
}
throw new IllegalStateException(String.format("Position %s: unparsable index", start));
}
private static String parseQuotedString(CharSequence path, PathPosition pos) throws Exception {
int len = path.length();
int start = pos.getIndex();
if (start < len) {
char quote = path.charAt(start);
pos.next();
StringWriter w = new StringWriter();
while (pos.getIndex() < len) {
int here = pos.getIndex();
// look for matching quote
if (path.charAt(here) == quote) {
pos.next();
return w.toString();
}
final int codePoints;
if (COMMONS_LANG3_AVAILABLE) {
codePoints = StringEscapeUtils.UNESCAPE_JAVA.translate(path, here, w);
} else {
codePoints = 0;
}
if (codePoints == 0) {
w.write(Character.toChars(Character.codePointAt(path, here)));
pos.next();
} else {
for (int i = 0; i < codePoints; i++) {
pos.plus(Character.charCount(Character.codePointAt(path, pos.getIndex())));
}
}
}
// if reached, reset due to no ending quote found
pos.setIndex(start);
}
return null;
}
/**
* ParsePosition/Callback
*/
private static class PathPosition extends ParsePosition implements Callback<Object> {
final Callback<?> delegate;
/**
* Create a new {@link PathPosition} instance.
*
* @param delegate
*/
private PathPosition(Callback<?> delegate) {
super(0);
this.delegate = delegate;
}
/**
* Increment and return this.
*
* @return this
*/
public PathPosition next() {
return plus(1);
}
/**
* Increase position and return this.
*
* @param addend
* @return this
*/
public PathPosition plus(int addend) {
setIndex(getIndex() + addend);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public void handleProperty(String name) {
delegate.handleProperty(name);
}
/**
* {@inheritDoc}
*/
@Override
public void handleIndexOrKey(String value) {
delegate.handleIndexOrKey(value);
}
/**
* {@inheritDoc}
*/
@Override
public void handleGenericInIterable() {
delegate.handleGenericInIterable();
}
/**
* {@inheritDoc}
*/
@Override
public Object result() {
return null;
}
/**
* {@inheritDoc}
*/
/*
* Override equals to make findbugs happy;
* would simply ignore but doesn't seem to be possible at the inner class level
* without attaching the filter to the containing class.
*/
@Override
public boolean equals(Object obj) {
return super.equals(obj);
}
/**
* {@inheritDoc}
*/
/*
* Override hashCode to make findbugs happy in the presence of overridden #equals :P
*/
@Override
public int hashCode() {
return super.hashCode();
}
}
}
|
bval-jsr/src/main/java/org/apache/bval/jsr/util/PathNavigation.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.bval.jsr.util;
import javax.validation.ValidationException;
import java.io.StringWriter;
import java.text.ParsePosition;
/**
* Defines a path navigation algorithm and a means of interacting with same.
*
* @version $Rev: 1136233 $ $Date: 2011-06-15 17:49:27 -0500 (Wed, 15 Jun 2011) $
*/
public class PathNavigation {
/**
* Path traversal callback function interface.
*/
public interface Callback<T> {
/**
* Handle a .-delimited property.
*
* @param name
*/
void handleProperty(String name);
/**
* Handle an index or key embedded in [].
*
* @param value
*/
void handleIndexOrKey(String value);
/**
* Handle contiguous [].
*/
void handleGenericInIterable();
/**
* Return a result. Called after navigation is complete.
*
* @return result
*/
T result();
}
/**
* Callback "procedure" that always returns null.
*/
public static abstract class CallbackProcedure implements Callback<Object> {
/**
* {@inheritDoc}
*/
@Override
public final Object result() {
complete();
return null;
}
/**
* Complete this CallbackProcedure. Default implementation is noop.
*/
protected void complete() {
}
}
/**
* Create a new PathNavigation instance.
*/
private PathNavigation() {
}
/**
* Navigate a path using the specified callback, returning its result.
*
* @param <T>
* @param propertyPath
* , null is assumed empty/root
* @param callback
* @return T result
*/
public static <T> T navigateAndReturn(CharSequence propertyPath, Callback<? extends T> callback) {
try {
parse(propertyPath == null ? "" : propertyPath, new PathPosition(callback));
} catch (ValidationException ex) {
throw ex;
} catch (Exception ex) {
throw new ValidationException(String.format("invalid property: %s", propertyPath), ex);
}
return callback.result();
}
/**
* Navigate a path using the specified callback.
*
* @param propertyPath
* @param callback
*/
public static void navigate(CharSequence propertyPath, Callback<?> callback) {
navigateAndReturn(propertyPath, callback);
}
private static void parse(CharSequence path, PathPosition pos) throws Exception {
int len = path.length();
boolean sep = true;
while (pos.getIndex() < len) {
int here = pos.getIndex();
char c = path.charAt(here);
switch (c) {
case ']':
throw new IllegalStateException(String.format("Position %s: unexpected '%s'", here, c));
case '[':
handleIndex(path, pos.next());
break;
case '.':
if (sep) {
throw new IllegalStateException(
String.format("Position %s: expected property, index/key, or end of expression", here));
}
sep = true;
pos.next();
// fall through:
default:
if (!sep) {
throw new IllegalStateException(String.format(
"Position %s: expected property path separator, index/key, or end of expression", here));
}
pos.handleProperty(parseProperty(path, pos));
}
sep = false;
}
}
private static String parseProperty(CharSequence path, PathPosition pos) throws Exception {
int len = path.length();
int start = pos.getIndex();
loop: while (pos.getIndex() < len) {
switch (path.charAt(pos.getIndex())) {
case '[':
case ']':
case '.':
break loop;
}
pos.next();
}
if (pos.getIndex() > start) {
return path.subSequence(start, pos.getIndex()).toString();
}
throw new IllegalStateException(String.format("Position %s: expected property", start));
}
/**
* Handles an index/key. If the text contained between [] is surrounded by a pair of " or ', it will be treated as a
* string which may contain Java escape sequences. This function is only available if commons-lang3 is available on the classpath!
*
* @param path
* @param pos
* @throws Exception
*/
private static void handleIndex(CharSequence path, PathPosition pos) throws Exception {
int len = path.length();
int start = pos.getIndex();
if (start < len) {
char first = path.charAt(pos.getIndex());
if (first == '"' || first == '\'') {
String s = parseQuotedString(path, pos);
if (s != null && path.charAt(pos.getIndex()) == ']') {
pos.handleIndexOrKey(s);
pos.next();
return;
}
}
// no quoted string; match ] greedily
while (pos.getIndex() < len) {
int here = pos.getIndex();
try {
if (path.charAt(here) == ']') {
if (here == start) {
pos.handleGenericInIterable();
} else {
pos.handleIndexOrKey(path.subSequence(start, here).toString());
}
return;
}
} finally {
pos.next();
}
}
}
throw new IllegalStateException(String.format("Position %s: unparsable index", start));
}
private static String parseQuotedString(CharSequence path, PathPosition pos) throws Exception {
int len = path.length();
int start = pos.getIndex();
if (start < len) {
char quote = path.charAt(start);
pos.next();
StringWriter w = new StringWriter();
while (pos.getIndex() < len) {
int here = pos.getIndex();
// look for matching quote
if (path.charAt(here) == quote) {
pos.next();
return w.toString();
}
try {
int codePoints = org.apache.commons.lang3.StringEscapeUtils.UNESCAPE_JAVA.translate(path, here, w);
if (codePoints == 0) {
w.write(Character.toChars(Character.codePointAt(path, here)));
pos.next();
} else {
for (int i = 0; i < codePoints; i++) {
pos.plus(Character.charCount(Character.codePointAt(path, pos.getIndex())));
}
}
} catch (Exception e) {
throw new RuntimeException(
"Java escaping in quotes is only supported with Apache commons-lang3 on the classpath!");
}
}
// if reached, reset due to no ending quote found
pos.setIndex(start);
}
return null;
}
/**
* ParsePosition/Callback
*/
private static class PathPosition extends ParsePosition implements Callback<Object> {
final Callback<?> delegate;
/**
* Create a new {@link PathPosition} instance.
*
* @param delegate
*/
private PathPosition(Callback<?> delegate) {
super(0);
this.delegate = delegate;
}
/**
* Increment and return this.
*
* @return this
*/
public PathPosition next() {
return plus(1);
}
/**
* Increase position and return this.
*
* @param addend
* @return this
*/
public PathPosition plus(int addend) {
setIndex(getIndex() + addend);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public void handleProperty(String name) {
delegate.handleProperty(name);
}
/**
* {@inheritDoc}
*/
@Override
public void handleIndexOrKey(String value) {
delegate.handleIndexOrKey(value);
}
/**
* {@inheritDoc}
*/
@Override
public void handleGenericInIterable() {
delegate.handleGenericInIterable();
}
/**
* {@inheritDoc}
*/
@Override
public Object result() {
return null;
}
/**
* {@inheritDoc}
*/
/*
* Override equals to make findbugs happy;
* would simply ignore but doesn't seem to be possible at the inner class level
* without attaching the filter to the containing class.
*/
@Override
public boolean equals(Object obj) {
return super.equals(obj);
}
/**
* {@inheritDoc}
*/
/*
* Override hashCode to make findbugs happy in the presence of overridden #equals :P
*/
@Override
public int hashCode() {
return super.hashCode();
}
}
}
|
permit quoted path keys without commons-lang3; bypass escape translation only
|
bval-jsr/src/main/java/org/apache/bval/jsr/util/PathNavigation.java
|
permit quoted path keys without commons-lang3; bypass escape translation only
|
<ide><path>val-jsr/src/main/java/org/apache/bval/jsr/util/PathNavigation.java
<ide> package org.apache.bval.jsr.util;
<ide>
<ide> import javax.validation.ValidationException;
<add>
<add>import org.apache.commons.lang3.StringEscapeUtils;
<add>
<ide> import java.io.StringWriter;
<ide> import java.text.ParsePosition;
<add>import java.util.logging.Logger;
<ide>
<ide> /**
<ide> * Defines a path navigation algorithm and a means of interacting with same.
<ide> */
<ide> protected void complete() {
<ide> }
<add> }
<add>
<add> private static final Logger LOG = Logger.getLogger(PathNavigation.class.getName());
<add>
<add> private static final boolean COMMONS_LANG3_AVAILABLE;
<add> static {
<add> boolean b = true;
<add> try {
<add> new StringEscapeUtils();
<add> } catch (Exception e) {
<add> b = false;
<add> LOG.warning("Apache commons-lang3 is not on the classpath; Java escaping in quotes will not be available.");
<add> }
<add> COMMONS_LANG3_AVAILABLE = b;
<ide> }
<ide>
<ide> /**
<ide> pos.next();
<ide> return w.toString();
<ide> }
<del> try {
<del> int codePoints = org.apache.commons.lang3.StringEscapeUtils.UNESCAPE_JAVA.translate(path, here, w);
<del> if (codePoints == 0) {
<del> w.write(Character.toChars(Character.codePointAt(path, here)));
<del> pos.next();
<del> } else {
<del> for (int i = 0; i < codePoints; i++) {
<del> pos.plus(Character.charCount(Character.codePointAt(path, pos.getIndex())));
<del> }
<add> final int codePoints;
<add> if (COMMONS_LANG3_AVAILABLE) {
<add> codePoints = StringEscapeUtils.UNESCAPE_JAVA.translate(path, here, w);
<add> } else {
<add> codePoints = 0;
<add> }
<add> if (codePoints == 0) {
<add> w.write(Character.toChars(Character.codePointAt(path, here)));
<add> pos.next();
<add> } else {
<add> for (int i = 0; i < codePoints; i++) {
<add> pos.plus(Character.charCount(Character.codePointAt(path, pos.getIndex())));
<ide> }
<del> } catch (Exception e) {
<del> throw new RuntimeException(
<del> "Java escaping in quotes is only supported with Apache commons-lang3 on the classpath!");
<ide> }
<ide> }
<ide> // if reached, reset due to no ending quote found
|
|
Java
|
apache-2.0
|
b96c6a6fe723120ffeb472e7ad5c3ba3dd25ae42
| 0 |
TracyLu/RxJava,NiteshKant/RxJava,spoon-bot/RxJava,simonbasle/RxJava,eduardotrandafilov/RxJava,sanxieryu/RxJava,nurkiewicz/RxJava,jacek-rzrz/RxJava,Bobjoy/RxJava,onepavel/RxJava,reactivex/rxjava,devagul93/RxJava,akarnokd/RxJava,ashwary/RxJava,kuanghao/RxJava,klemzy/RxJava,Bobjoy/RxJava,kuanghao/RxJava,eduardotrandafilov/RxJava,A-w-K/RxJava,AttwellBrian/RxJava,tilal6991/RxJava,forsail/RxJava,zsxwing/RxJava,ruhkopf/RxJava,duqiao/RxJava,dromato/RxJava,ruhkopf/RxJava,hzysoft/RxJava,KevinTCoughlin/RxJava,A-w-K/RxJava,duqiao/RxJava,southwolf/RxJava,wlrhnh-David/RxJava,nurkiewicz/RxJava,jacek-rzrz/RxJava,tombujok/RxJava,zjrstar/RxJava,vqvu/RxJava,AttwellBrian/RxJava,b-cuts/RxJava,davidmoten/RxJava,hzysoft/RxJava,ashwary/RxJava,ayushnvijay/RxJava,shekarrex/RxJava,cloudbearings/RxJava,KevinTCoughlin/RxJava,xfumihiro/RxJava,pitatensai/RxJava,dromato/RxJava,java02014/RxJava,wlrhnh-David/RxJava,ppiech/RxJava,markrietveld/RxJava,ReactiveX/RxJava,hyleung/RxJava,zhongdj/RxJava,AmberWhiteSky/RxJava,onepavel/RxJava,Ryan800/RxJava,ashwary/RxJava,cloudbearings/RxJava,rabbitcount/RxJava,TracyLu/RxJava,androidyue/RxJava,ChenWenHuan/RxJava,rabbitcount/RxJava,TracyLu/RxJava,simonbasle/RxJava,fjg1989/RxJava,aditya-chaturvedi/RxJava,ruhkopf/RxJava,wrightm/RxJava,nurkiewicz/RxJava,wehjin/RxJava,takecy/RxJava,b-cuts/RxJava,stevegury/RxJava,Godchin1990/RxJava,eduardotrandafilov/RxJava,picnic106/RxJava,davidmoten/RxJava,cgpllx/RxJava,nvoron23/RxJava,markrietveld/RxJava,zsxwing/RxJava,pitatensai/RxJava,devagul93/RxJava,cloudbearings/RxJava,ayushnvijay/RxJava,ppiech/RxJava,artem-zinnatullin/RxJava,wlrhnh-David/RxJava,ronenhamias/RxJava,southwolf/RxJava,sitexa/RxJava,ChenWenHuan/RxJava,zhongdj/RxJava,dromato/RxJava,sanxieryu/RxJava,Ryan800/RxJava,stevegury/RxJava,spoon-bot/RxJava,Eagles2F/RxJava,fjg1989/RxJava,sanxieryu/RxJava,tilal6991/RxJava,hyleung/RxJava,ppiech/RxJava,zhongdj/RxJava,zjrstar/RxJava,Eagles2F/RxJava,Turbo87/RxJava,forsail/RxJava,onepavel/RxJava,tilal6991/RxJava,marcogarcia23/RxJava,b-cuts/RxJava,xfumihiro/RxJava,weikipeng/RxJava,jacek-rzrz/RxJava,vqvu/RxJava,aditya-chaturvedi/RxJava,KevinTCoughlin/RxJava,pitatensai/RxJava,simonbasle/RxJava,ChenWenHuan/RxJava,marcogarcia23/RxJava,takecy/RxJava,nvoron23/RxJava,ReactiveX/RxJava,Godchin1990/RxJava,nvoron23/RxJava,ayushnvijay/RxJava,wehjin/RxJava,picnic106/RxJava,southwolf/RxJava,hyleung/RxJava,java02014/RxJava,wrightm/RxJava,Turbo87/RxJava,aditya-chaturvedi/RxJava,takecy/RxJava,weikipeng/RxJava,duqiao/RxJava,java02014/RxJava,AmberWhiteSky/RxJava,devagul93/RxJava,Eagles2F/RxJava,androidyue/RxJava,reactivex/rxjava,zsxwing/RxJava,wrightm/RxJava,tombujok/RxJava,cgpllx/RxJava,Bobjoy/RxJava,hzysoft/RxJava,stevegury/RxJava,NiteshKant/RxJava,klemzy/RxJava,sitexa/RxJava,ronenhamias/RxJava,shekarrex/RxJava,cgpllx/RxJava,artem-zinnatullin/RxJava,weikipeng/RxJava,klemzy/RxJava,androidyue/RxJava,zjrstar/RxJava,tombujok/RxJava,markrietveld/RxJava,marcogarcia23/RxJava,Ryan800/RxJava,benjchristensen/RxJava,sitexa/RxJava,xfumihiro/RxJava,AmberWhiteSky/RxJava,shekarrex/RxJava,fjg1989/RxJava,forsail/RxJava,wehjin/RxJava,picnic106/RxJava,A-w-K/RxJava,kuanghao/RxJava,vqvu/RxJava,Turbo87/RxJava,davidmoten/RxJava,Godchin1990/RxJava,ronenhamias/RxJava,rabbitcount/RxJava,akarnokd/RxJava
|
/**
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package rx.internal.operators;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicLongFieldUpdater;
/**
* Utility functions for use with backpressure.
*
*/
public final class BackpressureUtils {
/** Utility class, no instances. */
private BackpressureUtils() {
throw new IllegalStateException("No instances!");
}
/**
* Adds {@code n} to {@code requested} field and returns the value prior to
* addition once the addition is successful (uses CAS semantics). If
* overflows then sets {@code requested} field to {@code Long.MAX_VALUE}.
*
* @param requested
* atomic field updater for a request count
* @param object
* contains the field updated by the updater
* @param n
* the number of requests to add to the requested count
* @return requested value just prior to successful addition
*/
public static <T> long getAndAddRequest(AtomicLongFieldUpdater<T> requested, T object, long n) {
// add n to field but check for overflow
while (true) {
long current = requested.get(object);
long next = current + n;
// check for overflow
if (next < 0) {
next = Long.MAX_VALUE;
}
if (requested.compareAndSet(object, current, next)) {
return current;
}
}
}
/**
* Adds {@code n} to {@code requested} and returns the value prior to addition once the
* addition is successful (uses CAS semantics). If overflows then sets
* {@code requested} field to {@code Long.MAX_VALUE}.
*
* @param requested
* atomic long that should be updated
* @param n
* the number of requests to add to the requested count
* @return requested value just prior to successful addition
*/
public static long getAndAddRequest(AtomicLong requested, long n) {
// add n to field but check for overflow
while (true) {
long current = requested.get();
long next = current + n;
// check for overflow
if (next < 0) {
next = Long.MAX_VALUE;
}
if (requested.compareAndSet(current, next)) {
return current;
}
}
}
}
|
src/main/java/rx/internal/operators/BackpressureUtils.java
|
/**
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package rx.internal.operators;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicLongFieldUpdater;
/**
* Utility functions for use with backpressure.
*
*/
public final class BackpressureUtils {
/** Utility class, no instances. */
private BackpressureUtils() {
throw new IllegalStateException("No instances!");
}
/**
* Adds {@code n} to {@code requested} field and returns the value prior to
* addition once the addition is successful (uses CAS semantics). If
* overflows then sets {@code requested} field to {@code Long.MAX_VALUE}.
*
* @param requested
* atomic field updater for a request count
* @param object
* contains the field updated by the updater
* @param n
* the number of requests to add to the requested count
* @return requested value just prior to successful addition
*/
public static <T> long getAndAddRequest(AtomicLongFieldUpdater<T> requested, T object, long n) {
// add n to field but check for overflow
while (true) {
long current = requested.get(object);
long next = current + n;
// check for overflow
if (next < 0) {
next = Long.MAX_VALUE;
}
if (requested.compareAndSet(object, current, next)) {
return current;
}
}
}
/**
* Adds {@code n} to {@code requested} and returns the value prior to addition once the
* addition is successful (uses CAS semantics). If overflows then sets
* {@code requested} field to {@code Long.MAX_VALUE}.
*
* @param requested
* atomic field updater for a request count
* @param object
* contains the field updated by the updater
* @param n
* the number of requests to add to the requested count
* @return requested value just prior to successful addition
*/
public static long getAndAddRequest(AtomicLong requested, long n) {
// add n to field but check for overflow
while (true) {
long current = requested.get();
long next = current + n;
// check for overflow
if (next < 0) {
next = Long.MAX_VALUE;
}
if (requested.compareAndSet(current, next)) {
return current;
}
}
}
}
|
Fix for BackpressureUtils method javadoc
|
src/main/java/rx/internal/operators/BackpressureUtils.java
|
Fix for BackpressureUtils method javadoc
|
<ide><path>rc/main/java/rx/internal/operators/BackpressureUtils.java
<ide> * {@code requested} field to {@code Long.MAX_VALUE}.
<ide> *
<ide> * @param requested
<del> * atomic field updater for a request count
<del> * @param object
<del> * contains the field updated by the updater
<add> * atomic long that should be updated
<ide> * @param n
<ide> * the number of requests to add to the requested count
<ide> * @return requested value just prior to successful addition
|
|
Java
|
apache-2.0
|
640b6e1452a2ae7754654e6f627ab68d863bbb13
| 0 |
danwallacenz/Sunshine-Version-2
|
package com.example.android.sunshine.app;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* A placeholder fragment containing a simple view.
*/
public class ForecastFragment extends Fragment {
private final String LOG_TAG = ForecastFragment.class.getSimpleName();
ArrayAdapter<String> forecastAdapter;
public ForecastFragment() {
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setHasOptionsMenu(true);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.forecastfragment, menu);
super.onCreateOptionsMenu(menu, inflater);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_refresh) {
FetchWeatherTask fetchWeatherTask = new FetchWeatherTask();
// String cityId = "2179538";
// fetchWeatherTask.execute(cityId);
// Log.d(LOG_TAG, "finding weather for city " + cityId);
String postcode = "6021,nz";
fetchWeatherTask.execute(postcode);
Log.d(LOG_TAG, "finding weather for postcode " + postcode);
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String[] data = {"Today - Sunny - 88/63",
"Yesterday - Wet - 80/61",
"Thursday - Overcast - 88/70",
"Wednesday - Overcast - 85/72",
"Tuesday - Wet - 67/70",
"Monday - Overcast - 83/77",
"Sunday - Mild - 78/77",
"Saturday - Warm - 84/78",
"Friday - Wet - 80/78",
"Thursday - Overcast - 88/70",
"Wednesday - Overcast - 85/72",
"Tuesday - Wet - 67/70",
"Monday - Overcast - 83/77"};
List<String> weekForecast = new ArrayList<String>(Arrays.asList(data));
forecastAdapter = new ArrayAdapter<String>(getActivity(), R.layout.list_item_forecast, R.id.list_item_forecast_textview, weekForecast);
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
ListView listView = (ListView)rootView.findViewById(R.id.listview_forecast);
listView.setAdapter(forecastAdapter);
return rootView;
}
public class FetchWeatherTask extends AsyncTask<String, Void, Void> {
private final String LOG_TAG = FetchWeatherTask.class.getSimpleName();
protected void onPostExecute(String s) {
Log.d(LOG_TAG,s);
}
@Override
protected Void doInBackground(String...params) {
// Get weather data.
// These two need to be declared outside the try/catch
// so that they can be closed in the finally block.
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
// Will contain the raw JSON response as a string.
String forecastJsonStr = null;
try {
// Construct the URL for the OpenWeatherMap query
// Possible parameters are avaiable at OWM's forecast API page, at
// http://openweathermap.org/API#forecast
// URL url = new URL("http://api.openweathermap.org/data/2.5/forecast/daily?q=94043,us&mode=json&units=metric&cnt=7");
// http://api.openweathermap.org/data/2.5/forecast?zip=6021,nz&units=metric&cnt=7
// URL url = new URL("http://api.openweathermap.org/data/2.5/forecast?id=2179538&mode=json&units=metric&cnt=7"); // Wellington
// http://api.openweathermap.org/data/2.5/forecast/daily?q=6021,nz&mode=json&units=metric&cnt=7 // Berhampore
// URL url = new URL(params[0]);
// Uri.Builder builder = new Uri.Builder();
// builder.scheme("http")
// .authority("api.openweathermap.org")
// .appendPath("data")
// .appendPath("2.5")
// .appendPath("forecast")
// .appendQueryParameter("id", params[0]) // city id
// .appendQueryParameter("mode", "json")
// .appendQueryParameter("units", "metric")
// .appendQueryParameter("cnt", "7");
// String cityIdWeatherUri = builder.build().toString();
// URL url = new URL(cityIdWeatherUri);
Uri.Builder builder = new Uri.Builder();
builder.scheme("http")
.authority("api.openweathermap.org")
.appendPath("data")
.appendPath("2.5")
.appendPath("forecast")
.appendPath("daily")
.appendQueryParameter("q", params[0]) // postcode
.appendQueryParameter("mode", "json")
.appendQueryParameter("units", "metric")
.appendQueryParameter("cnt", "7");
String cityPostcodeWeatherUri = builder.build().toString();
// http://api.openweathermap.org/data/2.5/forecast/daily?q=6021,nz&mode=json&units=metric&cnt=7
URL url = new URL(cityPostcodeWeatherUri);
// Create the request to OpenWeatherMap, and open the connection
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect(); // Can't do this on the main thread.
// Read the input stream into a String
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
// Nothing to do.
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
// Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
// But it does make debugging a *lot* easier if you print out the completed
// buffer for debugging.
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
return null;
}
forecastJsonStr = buffer.toString();
Log.d(LOG_TAG, forecastJsonStr);
} catch (IOException e) {
Log.e(LOG_TAG, "Error ", e);
// If the code didn't successfully get the weather data, there's no point in attemping
// to parse it.
return null;
} finally{
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e(LOG_TAG, "Error closing stream", e);
}
}
}
return null;
}
}
}
|
app/src/main/java/com/example/android/sunshine/app/ForecastFragment.java
|
package com.example.android.sunshine.app;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* A placeholder fragment containing a simple view.
*/
public class ForecastFragment extends Fragment {
private final String LOG_TAG = ForecastFragment.class.getSimpleName();
ArrayAdapter<String> forecastAdapter;
public ForecastFragment() {
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setHasOptionsMenu(true);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.forecastfragment, menu);
super.onCreateOptionsMenu(menu, inflater);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_refresh) {
// Log.d(LOG_TAG, "action_refresh menu item tapped");
// Uri.Builder builder = new Uri.Builder();
// builder.scheme("http")
// .authority("api.openweathermap.org")
// .appendPath("data")
// .appendPath("2.5")
// .appendPath("forecast")
// .appendQueryParameter("id", "2179538")
// .appendQueryParameter("mode", "json")
// .appendQueryParameter("units", "metric")
// .appendQueryParameter("cnt", "7");
// String weatherUrl = builder.build().toString();
FetchWeatherTask fetchWeatherTask = new FetchWeatherTask();
// fetchWeatherTask.execute("http://api.openweathermap.org/data/2.5/forecast?id=2179538&mode=json&units=metric&cnt=7");
// fetchWeatherTask.execute(weatherUrl);
String cityId = "2179538";
fetchWeatherTask.execute(cityId);
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String[] data = {"Today - Sunny - 88/63",
"Yesterday - Wet - 80/61",
"Thursday - Overcast - 88/70",
"Wednesday - Overcast - 85/72",
"Tuesday - Wet - 67/70",
"Monday - Overcast - 83/77",
"Sunday - Mild - 78/77",
"Saturday - Warm - 84/78",
"Friday - Wet - 80/78",
"Thursday - Overcast - 88/70",
"Wednesday - Overcast - 85/72",
"Tuesday - Wet - 67/70",
"Monday - Overcast - 83/77"};
List<String> weekForecast = new ArrayList<String>(Arrays.asList(data));
forecastAdapter = new ArrayAdapter<String>(getActivity(), R.layout.list_item_forecast, R.id.list_item_forecast_textview, weekForecast);
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
ListView listView = (ListView)rootView.findViewById(R.id.listview_forecast);
listView.setAdapter(forecastAdapter);
// new FetchWeatherTask().execute("http://api.openweathermap.org/data/2.5/forecast/daily?q=94043&mode=json&units=metric&cnt=7");
return rootView;
}
public class FetchWeatherTask extends AsyncTask<String, Void, Void> {
private final String LOG_TAG = FetchWeatherTask.class.getSimpleName();
protected void onPostExecute(String s) {
Log.d(LOG_TAG,s);
}
@Override
protected Void doInBackground(String...params) {
// Get weather data.
// These two need to be declared outside the try/catch
// so that they can be closed in the finally block.
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
// Will contain the raw JSON response as a string.
String forecastJsonStr = null;
try {
// Construct the URL for the OpenWeatherMap query
// Possible parameters are avaiable at OWM's forecast API page, at
// http://openweathermap.org/API#forecast
// URL url = new URL("http://api.openweathermap.org/data/2.5/forecast/daily?q=94043&mode=json&units=metric&cnt=7");
// URL url = new URL("http://api.openweathermap.org/data/2.5/forecast?id=2179538&mode=json&units=metric&cnt=7"); // Wellington
// URL url = new URL(params[0]);
Uri.Builder builder = new Uri.Builder();
builder.scheme("http")
.authority("api.openweathermap.org")
.appendPath("data")
.appendPath("2.5")
.appendPath("forecast")
.appendQueryParameter("id", params[0]) // city id
.appendQueryParameter("mode", "json")
.appendQueryParameter("units", "metric")
.appendQueryParameter("cnt", "7");
String weatherUri = builder.build().toString();
URL url = new URL(weatherUri);
// Create the request to OpenWeatherMap, and open the connection
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect(); // Can't do this on the main thread.
// Read the input stream into a String
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
// Nothing to do.
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
// Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
// But it does make debugging a *lot* easier if you print out the completed
// buffer for debugging.
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
return null;
}
forecastJsonStr = buffer.toString();
Log.d(LOG_TAG, forecastJsonStr);
} catch (IOException e) {
Log.e(LOG_TAG, "Error ", e);
// If the code didn't successfully get the weather data, there's no point in attemping
// to parse it.
return null;
} finally{
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e(LOG_TAG, "Error closing stream", e);
}
}
}
return null;
}
}
}
|
pass in postcode
|
app/src/main/java/com/example/android/sunshine/app/ForecastFragment.java
|
pass in postcode
|
<ide><path>pp/src/main/java/com/example/android/sunshine/app/ForecastFragment.java
<ide> int id = item.getItemId();
<ide>
<ide> if (id == R.id.action_refresh) {
<del>// Log.d(LOG_TAG, "action_refresh menu item tapped");
<del>
<del>// Uri.Builder builder = new Uri.Builder();
<del>// builder.scheme("http")
<del>// .authority("api.openweathermap.org")
<del>// .appendPath("data")
<del>// .appendPath("2.5")
<del>// .appendPath("forecast")
<del>// .appendQueryParameter("id", "2179538")
<del>// .appendQueryParameter("mode", "json")
<del>// .appendQueryParameter("units", "metric")
<del>// .appendQueryParameter("cnt", "7");
<del>// String weatherUrl = builder.build().toString();
<ide>
<ide> FetchWeatherTask fetchWeatherTask = new FetchWeatherTask();
<del>// fetchWeatherTask.execute("http://api.openweathermap.org/data/2.5/forecast?id=2179538&mode=json&units=metric&cnt=7");
<del>// fetchWeatherTask.execute(weatherUrl);
<del> String cityId = "2179538";
<del> fetchWeatherTask.execute(cityId);
<del>
<add>// String cityId = "2179538";
<add>// fetchWeatherTask.execute(cityId);
<add>// Log.d(LOG_TAG, "finding weather for city " + cityId);
<add>
<add> String postcode = "6021,nz";
<add> fetchWeatherTask.execute(postcode);
<add> Log.d(LOG_TAG, "finding weather for postcode " + postcode);
<ide>
<ide> return true;
<ide> }
<ide> ListView listView = (ListView)rootView.findViewById(R.id.listview_forecast);
<ide> listView.setAdapter(forecastAdapter);
<ide>
<del>// new FetchWeatherTask().execute("http://api.openweathermap.org/data/2.5/forecast/daily?q=94043&mode=json&units=metric&cnt=7");
<del>
<ide> return rootView;
<ide> }
<ide>
<ide> // Construct the URL for the OpenWeatherMap query
<ide> // Possible parameters are avaiable at OWM's forecast API page, at
<ide> // http://openweathermap.org/API#forecast
<del>// URL url = new URL("http://api.openweathermap.org/data/2.5/forecast/daily?q=94043&mode=json&units=metric&cnt=7");
<del>
<add>// URL url = new URL("http://api.openweathermap.org/data/2.5/forecast/daily?q=94043,us&mode=json&units=metric&cnt=7");
<add> // http://api.openweathermap.org/data/2.5/forecast?zip=6021,nz&units=metric&cnt=7
<ide> // URL url = new URL("http://api.openweathermap.org/data/2.5/forecast?id=2179538&mode=json&units=metric&cnt=7"); // Wellington
<add>// http://api.openweathermap.org/data/2.5/forecast/daily?q=6021,nz&mode=json&units=metric&cnt=7 // Berhampore
<ide> // URL url = new URL(params[0]);
<add>
<add>// Uri.Builder builder = new Uri.Builder();
<add>// builder.scheme("http")
<add>// .authority("api.openweathermap.org")
<add>// .appendPath("data")
<add>// .appendPath("2.5")
<add>// .appendPath("forecast")
<add>// .appendQueryParameter("id", params[0]) // city id
<add>// .appendQueryParameter("mode", "json")
<add>// .appendQueryParameter("units", "metric")
<add>// .appendQueryParameter("cnt", "7");
<add>// String cityIdWeatherUri = builder.build().toString();
<add>// URL url = new URL(cityIdWeatherUri);
<ide>
<ide> Uri.Builder builder = new Uri.Builder();
<ide> builder.scheme("http")
<ide> .appendPath("data")
<ide> .appendPath("2.5")
<ide> .appendPath("forecast")
<del> .appendQueryParameter("id", params[0]) // city id
<add> .appendPath("daily")
<add> .appendQueryParameter("q", params[0]) // postcode
<ide> .appendQueryParameter("mode", "json")
<ide> .appendQueryParameter("units", "metric")
<ide> .appendQueryParameter("cnt", "7");
<del> String weatherUri = builder.build().toString();
<del> URL url = new URL(weatherUri);
<add> String cityPostcodeWeatherUri = builder.build().toString();
<add>
<add> // http://api.openweathermap.org/data/2.5/forecast/daily?q=6021,nz&mode=json&units=metric&cnt=7
<add> URL url = new URL(cityPostcodeWeatherUri);
<add>
<ide>
<ide> // Create the request to OpenWeatherMap, and open the connection
<ide> urlConnection = (HttpURLConnection) url.openConnection();
|
|
Java
|
apache-2.0
|
520b0293a3f0a98e17c71143d8dc9b69ad7f8d6f
| 0 |
pandreetto/saml2-attribute-authority
|
package it.infn.security.saml.datasource.hibernate;
import it.infn.security.saml.datasource.DataSourceException;
import it.infn.security.saml.datasource.jpa.AttributeEntity;
import it.infn.security.saml.datasource.jpa.AttributeEntityId;
import it.infn.security.saml.datasource.jpa.GroupEntity;
import it.infn.security.saml.datasource.jpa.ResourceEntity;
import it.infn.security.saml.datasource.jpa.ResourceEntity.ResourceType;
import it.infn.security.saml.datasource.jpa.UserEntity;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.hibernate.Query;
import org.hibernate.Session;
import org.wso2.charon.core.attributes.Attribute;
import org.wso2.charon.core.attributes.ComplexAttribute;
import org.wso2.charon.core.attributes.MultiValuedAttribute;
import org.wso2.charon.core.attributes.SimpleAttribute;
import org.wso2.charon.core.exceptions.AbstractCharonException;
import org.wso2.charon.core.exceptions.CharonException;
import org.wso2.charon.core.exceptions.DuplicateResourceException;
import org.wso2.charon.core.exceptions.NotFoundException;
import org.wso2.charon.core.objects.AbstractSCIMObject;
import org.wso2.charon.core.objects.Group;
import org.wso2.charon.core.objects.User;
public class HibernateDataSource
extends HibernateBaseDataSource {
private static final Logger logger = Logger.getLogger(HibernateDataSource.class.getName());
public HibernateDataSource() {
}
public User getUser(String userId)
throws CharonException {
User result = null;
Session session = sessionFactory.getCurrentSession();
try {
session.beginTransaction();
UserEntity usrEnt = (UserEntity) session.get(UserEntity.class, userId);
if (usrEnt == null) {
logger.info("Entity not found " + userId);
return null;
}
result = userFromEntity(session, usrEnt);
session.getTransaction().commit();
} catch (Throwable th) {
logger.log(Level.SEVERE, th.getMessage(), th);
session.getTransaction().rollback();
}
return result;
}
public List<User> listUsers()
throws CharonException {
return listUsers(null, null, null, -1, -1);
}
public List<User> listUsersByAttribute(Attribute attribute) {
return null;
}
public List<User> listUsersByFilter(String filter, String operation, String value)
throws CharonException {
try {
return listUsers(filter + operation + value, null, null, -1, -1);
} catch (CharonException chEx) {
logger.log(Level.SEVERE, chEx.getMessage(), chEx);
return null;
}
}
public List<User> listUsersBySort(String sortBy, String sortOrder) {
try {
return listUsers(null, sortBy, sortOrder, -1, -1);
} catch (CharonException chEx) {
logger.log(Level.SEVERE, chEx.getMessage(), chEx);
return null;
}
}
public List<User> listUsersWithPagination(int startIndex, int count) {
try {
return listUsers(null, null, null, startIndex, count);
} catch (CharonException chEx) {
logger.log(Level.SEVERE, chEx.getMessage(), chEx);
return null;
}
}
public List<User> listUsers(String filter, String sortBy, String sortOrder, int startIndex, int count)
throws CharonException {
count = HibernateUtils.checkQueryRange(count, true);
ArrayList<User> result = new ArrayList<User>(count);
Session session = sessionFactory.getCurrentSession();
try {
session.beginTransaction();
StringBuffer queryStr = new StringBuffer("FROM UserEntity as qUser");
if (sortBy != null) {
sortBy = HibernateUtils.convertSortedParam(sortBy, true);
queryStr.append(" ORDER BY ").append(sortBy);
if (sortOrder != null && sortOrder.equalsIgnoreCase("descending")) {
queryStr.append(" DESC");
} else {
queryStr.append(" ASC");
}
}
Query query = session.createQuery(queryStr.toString());
if (startIndex >= 0)
query.setFirstResult(startIndex);
if (count > 0)
query.setMaxResults(count);
@SuppressWarnings("unchecked")
List<UserEntity> usersFound = query.list();
for (UserEntity usrEnt : usersFound) {
result.add(userFromEntity(session, usrEnt));
}
session.getTransaction().commit();
} catch (Throwable th) {
logger.log(Level.SEVERE, th.getMessage(), th);
session.getTransaction().rollback();
}
return result;
}
public User updateUser(User user)
throws CharonException {
return null;
}
public User updateUser(List<Attribute> updatedAttributes) {
return null;
}
public void deleteUser(String userId)
throws NotFoundException, CharonException {
Session session = sessionFactory.getCurrentSession();
try {
session.beginTransaction();
UserEntity usrEnt = (UserEntity) session.get(UserEntity.class, userId);
if (usrEnt == null) {
logger.info("Entity not found " + userId);
throw new NotFoundException();
}
session.delete(usrEnt);
session.getTransaction().commit();
} catch (AbstractCharonException chEx) {
session.getTransaction().rollback();
throw chEx;
} catch (Throwable th) {
logger.log(Level.SEVERE, th.getMessage(), th);
session.getTransaction().rollback();
throw new CharonException(th.getMessage(), th);
}
}
public User createUser(User user)
throws CharonException, DuplicateResourceException {
return createUser(user, false);
}
public User createUser(User user, boolean isBulkUserAdd)
throws CharonException, DuplicateResourceException {
Session session = sessionFactory.getCurrentSession();
try {
session.beginTransaction();
UserEntity eUser = new UserEntity();
/*
* The uid is auto-generated by the SCIM parser
* ServerSideValidator#validateCreatedSCIMObject(AbstractSCIMObject, SCIMResourceSchema)
*/
eUser.setId(user.getId());
eUser.setType(ResourceType.USER);
eUser.setUserName(user.getUserName());
eUser.setCommonName(user.getGivenName() + " " + user.getFamilyName());
eUser.setAttributes(getExtendedAttributes(session, user));
session.save(eUser);
logger.info("Created user " + user.getUserName() + " with id " + user.getId());
session.getTransaction().commit();
return user;
} catch (Throwable th) {
logger.log(Level.SEVERE, th.getMessage(), th);
session.getTransaction().rollback();
throw new CharonException("Query execution error");
}
}
public Group getGroup(String groupId)
throws CharonException {
Group result = null;
Session session = sessionFactory.getCurrentSession();
try {
session.beginTransaction();
GroupEntity grpEnt = (GroupEntity) session.get(GroupEntity.class, groupId);
if (grpEnt == null) {
logger.info("Entity not found " + groupId);
return null;
}
result = groupFromEntity(session, grpEnt);
session.getTransaction().commit();
} catch (Throwable th) {
logger.log(Level.SEVERE, th.getMessage(), th);
session.getTransaction().rollback();
}
return result;
}
public List<Group> listGroups()
throws CharonException {
return listGroups(null, null, null, -1, -1);
}
public List<Group> listGroupsByAttribute(Attribute attribute)
throws CharonException {
return null;
}
public List<Group> listGroupsByFilter(String filter, String operation, String value)
throws CharonException {
return listGroups(filter + operation + value, null, null, -1, -1);
}
public List<Group> listGroupsBySort(String sortBy, String sortOrder)
throws CharonException {
return listGroups(null, sortBy, sortOrder, -1, -1);
}
public List<Group> listGroupsWithPagination(int startIndex, int count) {
try {
return listGroups(null, null, null, startIndex, count);
} catch (CharonException chEx) {
logger.log(Level.SEVERE, chEx.getMessage(), chEx);
return null;
}
}
public List<Group> listGroups(String filter, String sortBy, String sortOrder, int startIndex, int count)
throws CharonException {
count = HibernateUtils.checkQueryRange(count, false);
ArrayList<Group> result = new ArrayList<Group>(count);
Session session = sessionFactory.getCurrentSession();
try {
session.beginTransaction();
StringBuffer queryStr = new StringBuffer("FROM GroupEntity as qGroup");
if (sortBy != null) {
sortBy = HibernateUtils.convertSortedParam(sortBy, false);
queryStr.append(" ORDER BY ").append(sortBy);
if (sortOrder != null && sortOrder.equalsIgnoreCase("descending")) {
queryStr.append(" DESC");
} else {
queryStr.append(" ASC");
}
}
Query query = session.createQuery(queryStr.toString());
if (startIndex >= 0)
query.setFirstResult(startIndex);
if (count > 0)
query.setMaxResults(count);
@SuppressWarnings("unchecked")
List<GroupEntity> groupsFound = query.list();
for (GroupEntity grpEnt : groupsFound) {
result.add(groupFromEntity(session, grpEnt));
}
session.getTransaction().commit();
} catch (Throwable th) {
logger.log(Level.SEVERE, th.getMessage(), th);
session.getTransaction().rollback();
}
return result;
}
public Group createGroup(Group group)
throws CharonException, DuplicateResourceException {
Session session = sessionFactory.getCurrentSession();
try {
session.beginTransaction();
GroupEntity grpEnt = new GroupEntity();
/*
* The gid is auto-generated by the SCIM parser
* ServerSideValidator#validateCreatedSCIMObject(AbstractSCIMObject, SCIMResourceSchema)
*/
grpEnt.setId(group.getId());
grpEnt.setType(ResourceType.GROUP);
grpEnt.setDisplayName(group.getDisplayName());
grpEnt.setAttributes(getExtendedAttributes(session, group));
session.save(grpEnt);
logger.info("Created group " + grpEnt.getDisplayName() + " with id " + group.getId());
addMembers(session, grpEnt, group.getMembers());
session.getTransaction().commit();
return group;
} catch (Throwable th) {
logger.log(Level.SEVERE, th.getMessage(), th);
session.getTransaction().rollback();
throw new CharonException(th.getMessage());
}
}
public Group updateGroup(Group oldGroup, Group group)
throws CharonException {
return null;
}
public Group patchGroup(Group oldGroup, Group group)
throws CharonException {
return null;
}
public Group updateGroup(List<Attribute> attributes)
throws CharonException {
return null;
}
public void deleteGroup(String groupId)
throws NotFoundException, CharonException {
Session session = sessionFactory.getCurrentSession();
try {
session.beginTransaction();
GroupEntity grpEnt = (GroupEntity) session.get(GroupEntity.class, groupId);
if (grpEnt == null) {
logger.info("Entity not found " + groupId);
throw new NotFoundException();
}
/*
* TODO lots fo queries, missing index on source
*/
StringBuffer queryStr = new StringBuffer("SELECT qRes FROM ResourceEntity as qRes");
queryStr.append(" INNER JOIN qRes.groups as rGroup WHERE rGroup.id=?");
Query query = session.createQuery(queryStr.toString()).setString(0, grpEnt.getId());
@SuppressWarnings("unchecked")
List<ResourceEntity> members = query.list();
for (ResourceEntity resEnt : members) {
resEnt.getGroups().remove(grpEnt);
}
session.delete(grpEnt);
session.getTransaction().commit();
} catch (AbstractCharonException chEx) {
session.getTransaction().rollback();
throw chEx;
} catch (Throwable th) {
logger.log(Level.SEVERE, th.getMessage(), th);
session.getTransaction().rollback();
throw new CharonException(th.getMessage(), th);
}
}
private User userFromEntity(Session session, UserEntity usrEnt)
throws CharonException, DataSourceException {
User result = new User();
result.setId(usrEnt.getId());
result.setUserName(usrEnt.getUserName());
HashSet<String> dGroups = getDirectGroupIds(session, usrEnt.getId());
HashSet<String> iGroups = getIndirectGroupIds(session, dGroups);
result.setDirectGroups(new ArrayList<String>(dGroups));
result.setIndirectGroups(new ArrayList<String>(iGroups));
return result;
}
private Group groupFromEntity(Session session, GroupEntity grpEnt)
throws CharonException {
Group result = new Group();
result.setId(grpEnt.getId());
result.setDisplayName(grpEnt.getDisplayName());
StringBuffer queryStr = new StringBuffer("SELECT resource.id, resource.type");
queryStr.append(" FROM ResourceEntity as resource INNER JOIN resource.groups as rGroups");
queryStr.append(" WHERE rGroups.id=?");
Query query = session.createQuery(queryStr.toString());
@SuppressWarnings("unchecked")
List<Object[]> directMembers = (List<Object[]>) query.setString(0, grpEnt.getId()).list();
for (Object[] tmpObj : directMembers) {
if (tmpObj[1].equals(ResourceEntity.ResourceType.USER)) {
result.setUserMember(tmpObj[0].toString());
} else {
result.setGroupMember(tmpObj[0].toString());
}
}
return result;
}
private void addMembers(Session session, GroupEntity grpEnt, List<String> memberIds) {
StringBuffer queryStr = new StringBuffer("FROM ResourceEntity as qRes");
queryStr.append(" WHERE qRes.id in (:memberIds)");
Query query = session.createQuery(queryStr.toString());
@SuppressWarnings("unchecked")
List<ResourceEntity> mResList = query.setParameterList("memberIds", memberIds).list();
/*
* TODO improve query
*/
for (ResourceEntity tmpEnt : mResList) {
tmpEnt.getGroups().add(grpEnt);
session.flush();
}
}
private void checkForCycle(Session session, String grpId)
throws DataSourceException {
HashSet<String> accSet = new HashSet<String>();
accSet.add(grpId);
HashSet<String> currSet = accSet;
while (currSet.size() > 0) {
StringBuffer queryStr = new StringBuffer("SELECT rGroups.id");
queryStr.append(" FROM ResourceEntity as resource INNER JOIN resource.groups as rGroups");
queryStr.append(" WHERE resource.id IN (:resourceIds)");
Query query = session.createQuery(queryStr.toString());
@SuppressWarnings("unchecked")
List<String> idList = query.setParameterList("resourceIds", currSet).list();
currSet = new HashSet<String>(idList);
if (currSet.contains(grpId)) {
throw new DataSourceException("Detected cycle in the groups graph");
}
currSet.remove(accSet);
accSet.addAll(idList);
}
}
private void removeMembers(Session session, GroupEntity grpEnt, List<String> memberIds) {
StringBuffer queryStr = new StringBuffer("FROM ResourceEntity as qRes");
queryStr.append(" WHERE qRes.id in (:memberIds)");
Query query = session.createQuery(queryStr.toString());
@SuppressWarnings("unchecked")
List<ResourceEntity> members = query.setParameterList("memberIds", memberIds).list();
for (ResourceEntity resEnt : members) {
resEnt.getGroups().remove(grpEnt);
}
}
/*
* TODO move the section below into subclass
*/
protected Set<AttributeEntity> getExtendedAttributes(Session session, AbstractSCIMObject resource)
throws CharonException, NotFoundException {
Set<AttributeEntity> result = new HashSet<AttributeEntity>();
if (!resource.isAttributeExist(SPID_ATTR_NAME)) {
return result;
}
Attribute extAttribute = resource.getAttribute(SPID_ATTR_NAME);
for (Attribute subAttr : ((MultiValuedAttribute) extAttribute).getValuesAsSubAttributes()) {
ComplexAttribute cplxAttr = (ComplexAttribute) subAttr;
SimpleAttribute keyAttr = (SimpleAttribute) cplxAttr.getSubAttribute(KEY_FIELD);
SimpleAttribute cntAttr = (SimpleAttribute) cplxAttr.getSubAttribute(CONTENT_FIELD);
SimpleAttribute descrAttr = (SimpleAttribute) cplxAttr.getSubAttribute(ATTR_DESCR_FIELD);
AttributeEntity attrEnt = new AttributeEntity();
AttributeEntityId attrEntId = new AttributeEntityId();
attrEntId.setKey(keyAttr.getStringValue());
attrEntId.setContent(cntAttr.getStringValue());
attrEnt.setAttributeId(attrEntId);
attrEnt.setDescription(descrAttr.getStringValue());
/*
* TODO check for attribute auto-saving
*/
if (session.get(AttributeEntity.class, attrEntId) == null) {
logger.info("Saving attribute " + attrEnt.getAttributeId().getKey());
session.save(attrEnt);
}
result.add(attrEnt);
}
return result;
}
}
|
src/main/java/it/infn/security/saml/datasource/hibernate/HibernateDataSource.java
|
package it.infn.security.saml.datasource.hibernate;
import it.infn.security.saml.datasource.jpa.AttributeEntity;
import it.infn.security.saml.datasource.jpa.AttributeEntityId;
import it.infn.security.saml.datasource.jpa.GroupEntity;
import it.infn.security.saml.datasource.jpa.ResourceEntity;
import it.infn.security.saml.datasource.jpa.ResourceEntity.ResourceType;
import it.infn.security.saml.datasource.jpa.UserEntity;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.hibernate.Query;
import org.hibernate.Session;
import org.wso2.charon.core.attributes.Attribute;
import org.wso2.charon.core.attributes.ComplexAttribute;
import org.wso2.charon.core.attributes.MultiValuedAttribute;
import org.wso2.charon.core.attributes.SimpleAttribute;
import org.wso2.charon.core.exceptions.AbstractCharonException;
import org.wso2.charon.core.exceptions.CharonException;
import org.wso2.charon.core.exceptions.DuplicateResourceException;
import org.wso2.charon.core.exceptions.NotFoundException;
import org.wso2.charon.core.objects.AbstractSCIMObject;
import org.wso2.charon.core.objects.Group;
import org.wso2.charon.core.objects.User;
public class HibernateDataSource
extends HibernateBaseDataSource {
private static final Logger logger = Logger.getLogger(HibernateDataSource.class.getName());
public HibernateDataSource() {
}
public User getUser(String userId)
throws CharonException {
User result = null;
Session session = sessionFactory.getCurrentSession();
try {
session.beginTransaction();
UserEntity usrEnt = (UserEntity) session.get(UserEntity.class, userId);
if (usrEnt == null) {
logger.info("Entity not found " + userId);
return null;
}
result = userFromEntity(session, usrEnt);
session.getTransaction().commit();
} catch (Throwable th) {
logger.log(Level.SEVERE, th.getMessage(), th);
session.getTransaction().rollback();
}
return result;
}
public List<User> listUsers()
throws CharonException {
return listUsers(null, null, null, -1, -1);
}
public List<User> listUsersByAttribute(Attribute attribute) {
return null;
}
public List<User> listUsersByFilter(String filter, String operation, String value)
throws CharonException {
try {
return listUsers(filter + operation + value, null, null, -1, -1);
} catch (CharonException chEx) {
logger.log(Level.SEVERE, chEx.getMessage(), chEx);
return null;
}
}
public List<User> listUsersBySort(String sortBy, String sortOrder) {
try {
return listUsers(null, sortBy, sortOrder, -1, -1);
} catch (CharonException chEx) {
logger.log(Level.SEVERE, chEx.getMessage(), chEx);
return null;
}
}
public List<User> listUsersWithPagination(int startIndex, int count) {
try {
return listUsers(null, null, null, startIndex, count);
} catch (CharonException chEx) {
logger.log(Level.SEVERE, chEx.getMessage(), chEx);
return null;
}
}
public List<User> listUsers(String filter, String sortBy, String sortOrder, int startIndex, int count)
throws CharonException {
count = HibernateUtils.checkQueryRange(count, true);
ArrayList<User> result = new ArrayList<User>(count);
Session session = sessionFactory.getCurrentSession();
try {
session.beginTransaction();
StringBuffer queryStr = new StringBuffer("FROM UserEntity as qUser");
if (sortBy != null) {
sortBy = HibernateUtils.convertSortedParam(sortBy, true);
queryStr.append(" ORDER BY ").append(sortBy);
if (sortOrder != null && sortOrder.equalsIgnoreCase("descending")) {
queryStr.append(" DESC");
} else {
queryStr.append(" ASC");
}
}
Query query = session.createQuery(queryStr.toString());
if (startIndex >= 0)
query.setFirstResult(startIndex);
if (count > 0)
query.setMaxResults(count);
@SuppressWarnings("unchecked")
List<UserEntity> usersFound = query.list();
for (UserEntity usrEnt : usersFound) {
result.add(userFromEntity(session, usrEnt));
}
session.getTransaction().commit();
} catch (Throwable th) {
logger.log(Level.SEVERE, th.getMessage(), th);
session.getTransaction().rollback();
}
return result;
}
public User updateUser(User user)
throws CharonException {
return null;
}
public User updateUser(List<Attribute> updatedAttributes) {
return null;
}
public void deleteUser(String userId)
throws NotFoundException, CharonException {
Session session = sessionFactory.getCurrentSession();
try {
session.beginTransaction();
UserEntity usrEnt = (UserEntity) session.get(UserEntity.class, userId);
if (usrEnt == null) {
logger.info("Entity not found " + userId);
throw new NotFoundException();
}
session.delete(usrEnt);
session.getTransaction().commit();
} catch (AbstractCharonException chEx) {
session.getTransaction().rollback();
throw chEx;
} catch (Throwable th) {
logger.log(Level.SEVERE, th.getMessage(), th);
session.getTransaction().rollback();
throw new CharonException(th.getMessage(), th);
}
}
public User createUser(User user)
throws CharonException, DuplicateResourceException {
return createUser(user, false);
}
public User createUser(User user, boolean isBulkUserAdd)
throws CharonException, DuplicateResourceException {
Session session = sessionFactory.getCurrentSession();
try {
session.beginTransaction();
UserEntity eUser = new UserEntity();
/*
* The uid is auto-generated by the SCIM parser
* ServerSideValidator#validateCreatedSCIMObject(AbstractSCIMObject, SCIMResourceSchema)
*/
eUser.setId(user.getId());
eUser.setType(ResourceType.USER);
eUser.setUserName(user.getUserName());
eUser.setCommonName(user.getGivenName() + " " + user.getFamilyName());
eUser.setAttributes(getExtendedAttributes(session, user));
session.save(eUser);
logger.info("Created user " + user.getUserName() + " with id " + user.getId());
session.getTransaction().commit();
return user;
} catch (Throwable th) {
logger.log(Level.SEVERE, th.getMessage(), th);
session.getTransaction().rollback();
throw new CharonException("Query execution error");
}
}
public Group getGroup(String groupId)
throws CharonException {
Group result = null;
Session session = sessionFactory.getCurrentSession();
try {
session.beginTransaction();
GroupEntity grpEnt = (GroupEntity) session.get(GroupEntity.class, groupId);
if (grpEnt == null) {
logger.info("Entity not found " + groupId);
return null;
}
result = groupFromEntity(session, grpEnt);
session.getTransaction().commit();
} catch (Throwable th) {
logger.log(Level.SEVERE, th.getMessage(), th);
session.getTransaction().rollback();
}
return result;
}
public List<Group> listGroups()
throws CharonException {
return listGroups(null, null, null, -1, -1);
}
public List<Group> listGroupsByAttribute(Attribute attribute)
throws CharonException {
return null;
}
public List<Group> listGroupsByFilter(String filter, String operation, String value)
throws CharonException {
return listGroups(filter + operation + value, null, null, -1, -1);
}
public List<Group> listGroupsBySort(String sortBy, String sortOrder)
throws CharonException {
return listGroups(null, sortBy, sortOrder, -1, -1);
}
public List<Group> listGroupsWithPagination(int startIndex, int count) {
try {
return listGroups(null, null, null, startIndex, count);
} catch (CharonException chEx) {
logger.log(Level.SEVERE, chEx.getMessage(), chEx);
return null;
}
}
public List<Group> listGroups(String filter, String sortBy, String sortOrder, int startIndex, int count)
throws CharonException {
count = HibernateUtils.checkQueryRange(count, false);
ArrayList<Group> result = new ArrayList<Group>(count);
Session session = sessionFactory.getCurrentSession();
try {
session.beginTransaction();
StringBuffer queryStr = new StringBuffer("FROM GroupEntity as qGroup");
if (sortBy != null) {
sortBy = HibernateUtils.convertSortedParam(sortBy, false);
queryStr.append(" ORDER BY ").append(sortBy);
if (sortOrder != null && sortOrder.equalsIgnoreCase("descending")) {
queryStr.append(" DESC");
} else {
queryStr.append(" ASC");
}
}
Query query = session.createQuery(queryStr.toString());
if (startIndex >= 0)
query.setFirstResult(startIndex);
if (count > 0)
query.setMaxResults(count);
@SuppressWarnings("unchecked")
List<GroupEntity> groupsFound = query.list();
for (GroupEntity grpEnt : groupsFound) {
result.add(groupFromEntity(session, grpEnt));
}
session.getTransaction().commit();
} catch (Throwable th) {
logger.log(Level.SEVERE, th.getMessage(), th);
session.getTransaction().rollback();
}
return result;
}
public Group createGroup(Group group)
throws CharonException, DuplicateResourceException {
Session session = sessionFactory.getCurrentSession();
try {
session.beginTransaction();
GroupEntity grpEnt = new GroupEntity();
/*
* The gid is auto-generated by the SCIM parser
* ServerSideValidator#validateCreatedSCIMObject(AbstractSCIMObject, SCIMResourceSchema)
*/
grpEnt.setId(group.getId());
grpEnt.setType(ResourceType.GROUP);
grpEnt.setDisplayName(group.getDisplayName());
grpEnt.setAttributes(getExtendedAttributes(session, group));
session.save(grpEnt);
logger.info("Created group " + grpEnt.getDisplayName() + " with id " + group.getId());
updateMembers(session, grpEnt, group.getMembers());
session.getTransaction().commit();
return group;
} catch (Throwable th) {
logger.log(Level.SEVERE, th.getMessage(), th);
session.getTransaction().rollback();
throw new CharonException("Query execution error");
}
}
public Group updateGroup(Group oldGroup, Group group)
throws CharonException {
return null;
}
public Group patchGroup(Group oldGroup, Group group)
throws CharonException {
return null;
}
public Group updateGroup(List<Attribute> attributes)
throws CharonException {
return null;
}
public void deleteGroup(String groupId)
throws NotFoundException, CharonException {
Session session = sessionFactory.getCurrentSession();
try {
session.beginTransaction();
GroupEntity grpEnt = (GroupEntity) session.get(GroupEntity.class, groupId);
if (grpEnt == null) {
logger.info("Entity not found " + groupId);
throw new NotFoundException();
}
/*
* TODO lots fo queries, missing index on source
*/
StringBuffer queryStr = new StringBuffer("SELECT qRes FROM ResourceEntity as qRes");
queryStr.append(" INNER JOIN qRes.groups as rGroup WHERE rGroup.id=?");
Query query = session.createQuery(queryStr.toString()).setString(0, grpEnt.getId());
@SuppressWarnings("unchecked")
List<ResourceEntity> members = query.list();
for (ResourceEntity resEnt : members) {
resEnt.getGroups().remove(grpEnt);
}
session.delete(grpEnt);
session.getTransaction().commit();
} catch (AbstractCharonException chEx) {
session.getTransaction().rollback();
throw chEx;
} catch (Throwable th) {
logger.log(Level.SEVERE, th.getMessage(), th);
session.getTransaction().rollback();
throw new CharonException(th.getMessage(), th);
}
}
private User userFromEntity(Session session, UserEntity usrEnt)
throws CharonException {
User result = new User();
result.setId(usrEnt.getId());
result.setUserName(usrEnt.getUserName());
HashSet<String> dGroups = getDirectGroupIds(session, usrEnt.getId());
HashSet<String> iGroups = getIndirectGroupIds(session, dGroups);
result.setDirectGroups(new ArrayList<String>(dGroups));
result.setIndirectGroups(new ArrayList<String>(iGroups));
return result;
}
private Group groupFromEntity(Session session, GroupEntity grpEnt)
throws CharonException {
Group result = new Group();
result.setId(grpEnt.getId());
result.setDisplayName(grpEnt.getDisplayName());
StringBuffer queryStr = new StringBuffer("SELECT resource.id, resource.type");
queryStr.append(" FROM ResourceEntity as resource INNER JOIN resource.groups as rGroups");
queryStr.append(" WHERE rGroups.id=?");
Query query = session.createQuery(queryStr.toString());
@SuppressWarnings("unchecked")
List<Object[]> directMembers = (List<Object[]>) query.setString(0, grpEnt.getId()).list();
for (Object[] tmpObj : directMembers) {
if (tmpObj[1].equals(ResourceEntity.ResourceType.USER)) {
result.setUserMember(tmpObj[0].toString());
} else {
result.setGroupMember(tmpObj[0].toString());
}
}
return result;
}
private void updateMembers(Session session, ResourceEntity resEnt, List<String> memberIds) {
/*
* TODO check for cycles in the DAC
*/
StringBuffer queryStr = new StringBuffer("FROM ResourceEntity as qRes");
queryStr.append(" WHERE qRes.id in (:memberIds)");
Query query = session.createQuery(queryStr.toString());
@SuppressWarnings("unchecked")
List<ResourceEntity> mResList = query.setParameterList("memberIds", memberIds).list();
/*
* TODO improve query
*/
for (ResourceEntity tmpEnt : mResList) {
tmpEnt.getGroups().add(resEnt);
session.flush();
}
}
/*
* TODO move the section below into subclass
*/
protected Set<AttributeEntity> getExtendedAttributes(Session session, AbstractSCIMObject resource)
throws CharonException, NotFoundException {
Set<AttributeEntity> result = new HashSet<AttributeEntity>();
if (!resource.isAttributeExist(SPID_ATTR_NAME)) {
return result;
}
Attribute extAttribute = resource.getAttribute(SPID_ATTR_NAME);
for (Attribute subAttr : ((MultiValuedAttribute) extAttribute).getValuesAsSubAttributes()) {
ComplexAttribute cplxAttr = (ComplexAttribute) subAttr;
SimpleAttribute keyAttr = (SimpleAttribute) cplxAttr.getSubAttribute(KEY_FIELD);
SimpleAttribute cntAttr = (SimpleAttribute) cplxAttr.getSubAttribute(CONTENT_FIELD);
SimpleAttribute descrAttr = (SimpleAttribute) cplxAttr.getSubAttribute(ATTR_DESCR_FIELD);
AttributeEntity attrEnt = new AttributeEntity();
AttributeEntityId attrEntId = new AttributeEntityId();
attrEntId.setKey(keyAttr.getStringValue());
attrEntId.setContent(cntAttr.getStringValue());
attrEnt.setAttributeId(attrEntId);
attrEnt.setDescription(descrAttr.getStringValue());
/*
* TODO check for attribute auto-saving
*/
if (session.get(AttributeEntity.class, attrEntId) == null) {
logger.info("Saving attribute " + attrEnt.getAttributeId().getKey());
session.save(attrEnt);
}
result.add(attrEnt);
}
return result;
}
}
|
New methods for member
|
src/main/java/it/infn/security/saml/datasource/hibernate/HibernateDataSource.java
|
New methods for member
|
<ide><path>rc/main/java/it/infn/security/saml/datasource/hibernate/HibernateDataSource.java
<ide> package it.infn.security.saml.datasource.hibernate;
<ide>
<add>import it.infn.security.saml.datasource.DataSourceException;
<ide> import it.infn.security.saml.datasource.jpa.AttributeEntity;
<ide> import it.infn.security.saml.datasource.jpa.AttributeEntityId;
<ide> import it.infn.security.saml.datasource.jpa.GroupEntity;
<ide> session.save(grpEnt);
<ide> logger.info("Created group " + grpEnt.getDisplayName() + " with id " + group.getId());
<ide>
<del> updateMembers(session, grpEnt, group.getMembers());
<add> addMembers(session, grpEnt, group.getMembers());
<ide>
<ide> session.getTransaction().commit();
<ide>
<ide>
<ide> session.getTransaction().rollback();
<ide>
<del> throw new CharonException("Query execution error");
<add> throw new CharonException(th.getMessage());
<ide> }
<ide>
<ide> }
<ide> }
<ide>
<ide> private User userFromEntity(Session session, UserEntity usrEnt)
<del> throws CharonException {
<add> throws CharonException, DataSourceException {
<ide> User result = new User();
<ide> result.setId(usrEnt.getId());
<ide> result.setUserName(usrEnt.getUserName());
<ide> return result;
<ide> }
<ide>
<del> private void updateMembers(Session session, ResourceEntity resEnt, List<String> memberIds) {
<del>
<del> /*
<del> * TODO check for cycles in the DAC
<del> */
<add> private void addMembers(Session session, GroupEntity grpEnt, List<String> memberIds) {
<add>
<ide> StringBuffer queryStr = new StringBuffer("FROM ResourceEntity as qRes");
<ide> queryStr.append(" WHERE qRes.id in (:memberIds)");
<ide> Query query = session.createQuery(queryStr.toString());
<ide> * TODO improve query
<ide> */
<ide> for (ResourceEntity tmpEnt : mResList) {
<del> tmpEnt.getGroups().add(resEnt);
<add> tmpEnt.getGroups().add(grpEnt);
<ide> session.flush();
<add> }
<add>
<add> }
<add>
<add> private void checkForCycle(Session session, String grpId)
<add> throws DataSourceException {
<add>
<add> HashSet<String> accSet = new HashSet<String>();
<add> accSet.add(grpId);
<add> HashSet<String> currSet = accSet;
<add>
<add> while (currSet.size() > 0) {
<add> StringBuffer queryStr = new StringBuffer("SELECT rGroups.id");
<add> queryStr.append(" FROM ResourceEntity as resource INNER JOIN resource.groups as rGroups");
<add> queryStr.append(" WHERE resource.id IN (:resourceIds)");
<add> Query query = session.createQuery(queryStr.toString());
<add> @SuppressWarnings("unchecked")
<add> List<String> idList = query.setParameterList("resourceIds", currSet).list();
<add> currSet = new HashSet<String>(idList);
<add> if (currSet.contains(grpId)) {
<add> throw new DataSourceException("Detected cycle in the groups graph");
<add> }
<add> currSet.remove(accSet);
<add> accSet.addAll(idList);
<add> }
<add> }
<add>
<add> private void removeMembers(Session session, GroupEntity grpEnt, List<String> memberIds) {
<add>
<add> StringBuffer queryStr = new StringBuffer("FROM ResourceEntity as qRes");
<add> queryStr.append(" WHERE qRes.id in (:memberIds)");
<add> Query query = session.createQuery(queryStr.toString());
<add> @SuppressWarnings("unchecked")
<add> List<ResourceEntity> members = query.setParameterList("memberIds", memberIds).list();
<add>
<add> for (ResourceEntity resEnt : members) {
<add> resEnt.getGroups().remove(grpEnt);
<ide> }
<ide>
<ide> }
|
|
JavaScript
|
mit
|
ede4645ac154cea9b86d076085a047deb92f0133
| 0 |
Kylart/KawAnime,Kylart/KawAnime,Kylart/KawAnime
|
import { alignment } from './utils.js'
const re = {
delimiter: /(\{|\})/g,
newline: /\\N/g,
bold: {
start: {
from: /\\b1/g,
to: '<b>'
},
end: {
from: /\\b0/g,
to: '</b>'
}
},
italic: {
start: {
from: /\\i1/g,
to: '<i>'
},
end: {
from: /\\i0/g,
to: '</i>'
}
},
underline: {
start: {
from: /\\u1/g,
to: '<u>'
},
end: {
from: /\\u0/g,
to: '</u>'
}
},
font: {
name: /(\\fn.+(?=\\)|\\fn.+(?=}))/g,
size: /\\fs[0-9]{1,3}/g
},
color: /\\\d?c&H[0-9A-Za-z]{2,6}&/,
alignment: /\\an?\d{1,2}/g,
karaoke: /\\k(f|o)?\d{1,5}/ig,
notSupported: [
/\\s(0|1)/g, // Strikeout
/\\(bord|shad|be)[0-9]{1,5}/g, // Border, shadow and blur
/\\fsc(x|y)\d{1,3}/g, // Scaling
/\\fsp\d{1,3}/g, // letter-spacing is not supported in cue
/fr(x|y|z)?\d{1,3}/g, // Cannot rotate text in cue
/\\b\d{1,3}/g, // Custom bold is a pain to handle
/\\fe\d{1,3}/g, // Encoding
/\\(\d?a|alpha)&H[0-9A-Za-z]{2}&/g, // Alpha
/\\fad\(\d{1,5},\d{1,5}\)/g // fade animation
]
}
// Need to clean up {}s after
const clean = (string) => {
return string.replace(re.delimiter, '')
}
const handleCommon = (type, string) => {
// Handles bold, italic and underline
const re_ = re[type]
if (re_.start.from.test(string)) {
string = string.replace(re_.start.from, re_.start.to)
re_.end.from.test(string)
? string = string.replace(re_.end.from, re_.end.to)
: string += re_.end.to
}
return string.replace(re_.start.from, '').replace(re_.end.from, '')
}
const handleFont = (type, string, style) => {
const fontType = re.font[type].test(string) && string.match(re.font[type])[0]
if (fontType) {
const font = fontType.slice(3)
const fontClass = 'font_' + font.replace(/\s/g, '_')
const value = font + (type === 'size' ? 'px' : '')
// Check if class is in style. If not, includes it.
let current = style.innerHTML
if (!current.includes(`.${fontClass}`)) {
style.innerHTML += `.video-player > video::cue(.${fontClass}) {
font-${type === 'name' ? 'family' : 'size'}:${value};
${type === 'size' && 'line-height: 1.25 !important'};
}`
}
string = string.replace(re.font[type], `<c.${fontClass}>`) + '</c>'
}
return string.replace(re.font[type], '')
}
const setColorStyle = (type, colorTag, string, style) => {
const color = colorTag.replace(/\\\d?c/g, '').slice(2, 8)
const r = color.slice(4, 6)
const g = color.slice(2, 4)
const b = color.slice(0, 2)
const hexColor = `#${r}${g}${b}`
const colorClass = `.${type}${color}`
const typeToProperty = {
'c': {
property: 'color',
rule: hexColor
},
'b': {
property: 'text-shadow',
rule: `0 0 ${1.8 * 4}px ${hexColor},`.repeat(8).slice(-2)
}
}
// Check if class is in style. If not, includes it.
let current = style.innerHTML
if (!current.includes(`.${colorClass}`)) {
style.innerHTML += `.video-player > ::cue(${colorClass}){${typeToProperty[type].property}:${typeToProperty[type].rule};}`
}
return string.replace(re.color, `<c${colorClass}>`)
}
const handleColor = (string, style) => {
if (re.color.test(string)) {
const globalRe = new RegExp(re.color, ['g'])
for (let i = 0, l = string.match(globalRe).length; i < l; ++i) {
const colorTag = string.match(re.color)[0]
const isPrimary = colorTag[1] === 'c' || colorTag[1] === '1'
if (isPrimary) {
string = setColorStyle('c', colorTag, string, style)
if (re.color.test(string)) {
// Meaning there is another color tag in the string so the closing tag should be
// before the next color tag
const match = string.match(re.color)[0]
const index = string.indexOf(match)
string = string.slice(0, index) + '</c>' + string.slice(index)
} else {
string += '</c>'
}
} else {
// Hopefully temporary
// Support only for border color
if (colorTag[1] === '3') {
string = setColorStyle('b', colorTag, string, style)
}
}
}
}
return string
}
const handleAlignment = (string, cue) => {
const alignmentTag = re.alignment.test(string) && string.match(re.alignment)[0] // Only he first tag matters
if (alignmentTag) {
const isNumpad = alignmentTag[2] === 'n'
const align = isNumpad
? +alignmentTag[3] // tag === '\an<number>, 1 <= number <= 9
: +alignmentTag.slice(2, 4) // tag === '\a<number>, 1 <= number <= 11
cue.position = isNumpad ? alignment.numpad[align][1] : alignment.ssa[align][1]
cue.line = isNumpad ? alignment.numpad[align][0] : alignment.ssa[align][0]
const leftAligned = [1, 4, 7]
const rightAligned = [3, 6, 9]
cue.align = leftAligned.includes(align)
? 'start'
: rightAligned.includes(align)
? 'end'
: 'center'
}
cue.text = string.replace(re.alignment, '')
return cue
}
// const handleKaraoke = (string, cue) => {
// const karaokeTag = re.karaoke.test(string) && string.match(re.karaoke)
// // console.log(cue)
// if (karaokeTag.length) {
// const durations = []
// karaokeTag.forEach((tag) => {
// const tag_ = tag.replace(/f/g, '').replace(/o/g, '')
// const { startTime } = cue // Format is mm:ss.xx
// durations.push(tag_.slice(2))
// const completeDuration = durations.reduce((a, elem) => a + elem)
// const shouldStartAt = startTime + completeDuration
// })
// }
// return string.replace(karaokeTag, '')
// }
const handleNotSupported = (string) => {
re.notSupported.forEach((tag) => { string = string.replace(tag, '') })
return string
}
export default function (string, cue) {
const cssStyle = document.head.children[document.head.childElementCount - 1]
if (/\{/g.test(string)) {
string = handleNotSupported(string)
string = handleCommon('bold', string)
string = handleCommon('italic', string)
string = handleCommon('underline', string)
// string = handleKaraoke(string, cue)
string = handleFont('name', string, cssStyle)
string = handleFont('size', string, cssStyle)
string = handleColor(string, cssStyle)
cue = handleAlignment(string, cue)
string = cue.text
}
string = string.replace(re.newline, '\n')
cue.text = clean(string)
return cue
}
|
assets/subtitle-parser/ass/tags.js
|
import { alignment } from './utils.js'
const re = {
delimiter: /(\{|\})/g,
newline: /\\N/g,
bold: {
start: {
from: /\\b1/g,
to: '<b>'
},
end: {
from: /\\b0/g,
to: '</b>'
}
},
italic: {
start: {
from: /\\i1/g,
to: '<i>'
},
end: {
from: /\\i0/g,
to: '</i>'
}
},
underline: {
start: {
from: /\\u1/g,
to: '<u>'
},
end: {
from: /\\u0/g,
to: '</u>'
}
},
font: {
name: /(\\fn.+(?=\\)|\\fn.+(?=}))/g,
size: /\\fs[0-9]{1,3}/g
},
color: /\\\d?c&H[0-9A-Za-z]{2,6}&/,
alignment: /\\an?\d{1,2}/g,
karaoke: /\\k(f|o)?\d{1,5}/ig,
notSupported: [
/\\s(0|1)/g, // Strikeout
/\\(bord|shad|be)[0-9]{1,5}/g, // Border, shadow and blur
/\\fsc(x|y)\d{1,3}/g, // Scaling
/\\fsp\d{1,3}/g, // letter-spacing is not supported in cue
/fr(x|y|z)?\d{1,3}/g, // Cannot rotate text in cue
/\\b\d{1,3}/g, // Custom bold is a pain to handle
/\\fe\d{1,3}/g, // Encoding
/\\(\d?a|alpha)&H[0-9A-Za-z]{2}&/g, // Alpha
/\\fad\(\d{1,5},\d{1,5}\)/g // fade animation
]
}
// Need to clean up {}s after
const clean = (string) => {
return string.replace(re.delimiter, '')
}
const handleCommon = (type, string) => {
// Handles bold, italic and underline
const re_ = re[type]
if (re_.start.from.test(string)) {
string = string.replace(re_.start.from, re_.start.to)
re_.end.from.test(string)
? string = string.replace(re_.end.from, re_.end.to)
: string += re_.end.to
}
return string.replace(re_.start.from, '').replace(re_.end.from, '')
}
const handleFont = (type, string, style) => {
const fontType = re.font[type].test(string) && string.match(re.font[type])[0]
if (fontType) {
const font = fontType.slice(3)
const fontClass = 'font_' + font.replace(/\s/g, '_')
const value = font + (type === 'size' ? 'px' : '')
// Check if class is in style. If not, includes it.
let current = style.innerHTML
if (!current.includes(`.${fontClass}`)) {
style.innerHTML += `.video-player > video::cue(.${fontClass}) {
font-${type === 'name' ? 'family' : 'size'}:${value};
${type === 'size' && 'line-height: 1.25 !important'};
}`
}
string = string.replace(re.font[type], `<c.${fontClass}>`) + '</c>'
}
return string.replace(re.font[type], '')
}
const setColorStyle = (type, colorTag, string, style) => {
const color = colorTag.replace(/\\\d?c/g, '').slice(2, 8)
const r = color.slice(4, 6)
const g = color.slice(2, 4)
const b = color.slice(0, 2)
const hexColor = `#${r}${g}${b}`
const colorClass = `.${type}${color}`
const typeToProperty = {
'c': {
property: 'color',
rule: hexColor
},
'b': {
property: 'text-shadow',
rule: `0 0 ${1.8 * 4}px ${hexColor},`.repeat(8).slice(-2)
}
}
// Check if class is in style. If not, includes it.
let current = style.innerHTML
if (!current.includes(`.${colorClass}`)) {
style.innerHTML += `.video-player > ::cue(${colorClass}){${typeToProperty[type].property}:${typeToProperty[type].rule};}`
}
return string.replace(re.color, `<c${colorClass}>`)
}
const handleColor = (string, style) => {
const globalRe = new RegExp(re.color, ['g'])
for (let i = 0, l = string.match(globalRe).length; i < l; ++i) {
const colorTag = string.match(re.color)[0]
const isPrimary = colorTag[1] === 'c' || colorTag[1] === '1'
if (isPrimary) {
string = setColorStyle('c', colorTag, string, style)
if (re.color.test(string)) {
// Meaning there is another color tag in the string so the closing tag should be
// before the next color tag
const match = string.match(re.color)[0]
const index = string.indexOf(match)
string = string.slice(0, index) + '</c>' + string.slice(index)
} else {
string += '</c>'
}
} else {
// Hopefully temporary
// Support only for border color
if (colorTag[1] === '3') {
string = setColorStyle('b', colorTag, string, style)
}
}
}
return string
}
const handleAlignment = (string, cue) => {
const alignmentTag = re.alignment.test(string) && string.match(re.alignment)[0] // Only he first tag matters
if (alignmentTag) {
const isNumpad = alignmentTag[2] === 'n'
const align = isNumpad
? +alignmentTag[3] // tag === '\an<number>, 1 <= number <= 9
: +alignmentTag.slice(2, 4) // tag === '\a<number>, 1 <= number <= 11
cue.position = isNumpad ? alignment.numpad[align][1] : alignment.ssa[align][1]
cue.line = isNumpad ? alignment.numpad[align][0] : alignment.ssa[align][0]
const leftAligned = [1, 4, 7]
const rightAligned = [3, 6, 9]
cue.align = leftAligned.includes(align)
? 'start'
: rightAligned.includes(align)
? 'end'
: 'center'
}
cue.text = string.replace(re.alignment, '')
return cue
}
// const handleKaraoke = (string, cue) => {
// const karaokeTag = re.karaoke.test(string) && string.match(re.karaoke)
// // console.log(cue)
// if (karaokeTag.length) {
// const durations = []
// karaokeTag.forEach((tag) => {
// const tag_ = tag.replace(/f/g, '').replace(/o/g, '')
// const { startTime } = cue // Format is mm:ss.xx
// durations.push(tag_.slice(2))
// const completeDuration = durations.reduce((a, elem) => a + elem)
// const shouldStartAt = startTime + completeDuration
// })
// }
// return string.replace(karaokeTag, '')
// }
const handleNotSupported = (string) => {
re.notSupported.forEach((tag) => { string = string.replace(tag, '') })
return string
}
export default function (string, cue) {
const cssStyle = document.head.children[document.head.childElementCount - 1]
if (/\{/g.test(string)) {
string = handleNotSupported(string)
string = handleCommon('bold', string)
string = handleCommon('italic', string)
string = handleCommon('underline', string)
// string = handleKaraoke(string, cue)
string = handleFont('name', string, cssStyle)
string = handleFont('size', string, cssStyle)
string = handleColor(string, cssStyle)
cue = handleAlignment(string, cue)
string = cue.text
}
string = string.replace(re.newline, '\n')
cue.text = clean(string)
return cue
}
|
It's be wise to check beforehand
|
assets/subtitle-parser/ass/tags.js
|
It's be wise to check beforehand
|
<ide><path>ssets/subtitle-parser/ass/tags.js
<ide> }
<ide>
<ide> const handleColor = (string, style) => {
<del> const globalRe = new RegExp(re.color, ['g'])
<del>
<del> for (let i = 0, l = string.match(globalRe).length; i < l; ++i) {
<del> const colorTag = string.match(re.color)[0]
<del> const isPrimary = colorTag[1] === 'c' || colorTag[1] === '1'
<del>
<del> if (isPrimary) {
<del> string = setColorStyle('c', colorTag, string, style)
<del>
<del> if (re.color.test(string)) {
<del> // Meaning there is another color tag in the string so the closing tag should be
<del> // before the next color tag
<del> const match = string.match(re.color)[0]
<del> const index = string.indexOf(match)
<del> string = string.slice(0, index) + '</c>' + string.slice(index)
<add> if (re.color.test(string)) {
<add> const globalRe = new RegExp(re.color, ['g'])
<add>
<add> for (let i = 0, l = string.match(globalRe).length; i < l; ++i) {
<add> const colorTag = string.match(re.color)[0]
<add> const isPrimary = colorTag[1] === 'c' || colorTag[1] === '1'
<add>
<add> if (isPrimary) {
<add> string = setColorStyle('c', colorTag, string, style)
<add>
<add> if (re.color.test(string)) {
<add> // Meaning there is another color tag in the string so the closing tag should be
<add> // before the next color tag
<add> const match = string.match(re.color)[0]
<add> const index = string.indexOf(match)
<add> string = string.slice(0, index) + '</c>' + string.slice(index)
<add> } else {
<add> string += '</c>'
<add> }
<ide> } else {
<del> string += '</c>'
<del> }
<del> } else {
<del> // Hopefully temporary
<del> // Support only for border color
<del> if (colorTag[1] === '3') {
<del> string = setColorStyle('b', colorTag, string, style)
<add> // Hopefully temporary
<add> // Support only for border color
<add> if (colorTag[1] === '3') {
<add> string = setColorStyle('b', colorTag, string, style)
<add> }
<ide> }
<ide> }
<ide> }
|
|
Java
|
mit
|
c95a4bacd356ae718339952687ddbf38984b1459
| 0 |
ThisChessPlayer/GroupScheduleCoordinator
|
package com.example.android.groupschedulecoordinator;
/**
* Created by jeremyfolk on 10/17/16.
* Firebase auth added by tommy 10/27/16
*/
import android.*;
import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.auth.api.signin.GoogleSignInResult;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.SignInButton;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthCredential;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseAuthException;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.GoogleAuthProvider;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.jar.*;
public class LoginScreen extends AppCompatActivity{
//global var
private static final int RC_SIGN_IN = 1;
private static final String TAG = "SignInActivity";
private final int REQUEST_CODE_PERMISSIONS = 123;
private final int REQUEST_CODE_MULTI = 124;
private FirebaseAuth mFirebaseAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private FirebaseUser mFirebaseUser;
private int permissionCode;
private GoogleApiClient mGoogleApiClient;
private SignInButton mGoogleButton;
private String mUser;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
mGoogleButton = (SignInButton) findViewById(R.id.sign_in_button);
mFirebaseAuth = FirebaseAuth.getInstance();
mFirebaseUser = mFirebaseAuth.getCurrentUser();
mAuthListener = new FirebaseAuth.AuthStateListener() {
@Override
public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
if(firebaseAuth.getCurrentUser() != null){
startActivity(new Intent(LoginScreen.this, MainActivity.class));
}
}
};
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();
mGoogleApiClient = new GoogleApiClient.Builder(getApplicationContext())
.enableAutoManage(this, new GoogleApiClient.OnConnectionFailedListener() {
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
Toast.makeText(LoginScreen.this, "Error!", Toast.LENGTH_SHORT).show();
}
})
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
mGoogleButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//dummyPermission();
//signIn();
multiPermission();
}
});
mGoogleButton.setSize(SignInButton.SIZE_WIDE);
}
private void signIn() {
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
startActivityForResult(signInIntent, RC_SIGN_IN);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//TODO remove this log
Log.d("jasonlogs", "server_client_id : " + this.getResources().getString(R.string.server_client_id));
Log.d("jasonlogs", "default_web_client_id: " + getApplicationContext().getString(R.string.default_web_client_id));
Log.d("jasonLogs", "onActivityResult: " + requestCode + " " + resultCode + " " + data);
// Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
if (requestCode == RC_SIGN_IN) {
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
Log.d("jasonlogs", "result: " + result.getStatus());
if (result.isSuccess()) {
//TODO remove this log
Log.d("jasonlogs", "successful google auth!");
// Google Sign In was successful, authenticate with Firebase
GoogleSignInAccount account = result.getSignInAccount();
firebaseAuthWithGoogle(account);
} else {
//TODO remove this log
Log.d("jasonlogs", "failed google auth.");
// Google Sign In failed, update UI appropriately
// ...
//TODO don't actually go forwards until auth is completed
//startActivity(new Intent(LoginScreen.this, MainActivity.class));
//finish();
}
}
}
private void firebaseAuthWithGoogle(GoogleSignInAccount account) {
Log.d(TAG, "firebaseAuthWithGoogle:" + account.getId());
AuthCredential credential = GoogleAuthProvider.getCredential(account.getIdToken(), null);
mFirebaseAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
Log.d(TAG, "signInWithCredential:onComplete:" + task.isSuccessful());
// If sign in fails, display a message to the user. If sign in succeeds
// the auth state listener will be notified and logic to handle the
// signed in user can be handled in the listener.
if (!task.isSuccessful()) {
Log.w(TAG, "signInWithCredential", task.getException());
Toast.makeText(LoginScreen.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
} else{
startActivity(new Intent(LoginScreen.this, MainActivity.class));
finish();
}
}
});
}
@Override
protected void onStart() {
super.onStart();
mFirebaseAuth.addAuthStateListener(mAuthListener);
}
@Override
public void onStop() {
super.onStop();
if (mAuthListener != null) {
mFirebaseAuth.removeAuthStateListener(mAuthListener);
}
}
@Override
public void onBackPressed() {
}
/* Prompts user for access
Popup dialog prompts user that contacts access is needed
@success, user allows contacts, signIn() is called
@failure, user denies, toast text shows
*/
private void dummyPermission(){
int dummyPermission = checkSelfPermission(Manifest.permission.GET_ACCOUNTS);
if (dummyPermission != PackageManager.PERMISSION_GRANTED) {
if(shouldShowRequestPermissionRationale(Manifest.permission.GET_ACCOUNTS)){
needPermissions("You need to allow access to Contacts", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
requestPermissions(new String[] {Manifest.permission.GET_ACCOUNTS}, REQUEST_CODE_PERMISSIONS);
}
});
return;
}
requestPermissions(new String[] {Manifest.permission.GET_ACCOUNTS}, REQUEST_CODE_PERMISSIONS);
return;
}
signIn();
}
/*
Requests permissions to access CONTACTS and CALENDER
case 1: user allows both permissions --> call signIn()
case 2: user denies 1 option --> stays on main screen and prompts user for access
to the permission that was denied
case 3: user denies both options --> prompts for both
*/
private void multiPermission(){
List<String> permissionsNeeded = new ArrayList<>();
final List<String> permissionList = new ArrayList<>();
if(!addPermissions(permissionList, Manifest.permission.GET_ACCOUNTS))
permissionsNeeded.add("ACCOUNTS");
if (!addPermissions(permissionList,Manifest.permission.READ_CALENDAR))
permissionsNeeded.add("READ_CALENDER");
if(!addPermissions(permissionList, Manifest.permission.WRITE_CALENDAR))
permissionsNeeded.add("WRITE_CALENDER");
if (permissionList.size() > 0) {
if (permissionsNeeded.size() > 0) {
String message = "You need to provide access to " + permissionsNeeded.get(0);
for(int i = 1; i < permissionsNeeded.size(); i++)
message = message + ", " + permissionsNeeded.get(i);
needPermissions(message, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
requestPermissions(permissionList.toArray(new String[permissionList.size()]), REQUEST_CODE_MULTI);
}
});
return;
}
requestPermissions(permissionList.toArray(new String[permissionList.size()]), REQUEST_CODE_MULTI);
return;
}
signIn();
}
/*helper for adding permissions*/
private boolean addPermissions(List<String> pList, String permission){
if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) {
pList.add(permission);
if(shouldShowRequestPermissionRationale(permission)){
return false;
}
}
return true;
}
private void needPermissions(String message, DialogInterface.OnClickListener okListener){
new AlertDialog.Builder(LoginScreen.this)
.setMessage(message)
.setPositiveButton("OK", okListener)
.create()
.show();
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
switch (requestCode){
case REQUEST_CODE_PERMISSIONS:
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
signIn();
}else{
Toast.makeText(LoginScreen.this, "Please allow access to contacts", Toast.LENGTH_SHORT).show();
}
break;
case REQUEST_CODE_MULTI:
Map<String,Integer> perms = new HashMap<String,Integer>();
perms.put(Manifest.permission.GET_ACCOUNTS, PackageManager.PERMISSION_GRANTED);
perms.put(Manifest.permission.WRITE_CALENDAR, PackageManager.PERMISSION_GRANTED);
perms.put(Manifest.permission.READ_CALENDAR, PackageManager.PERMISSION_GRANTED);
for(int i = 0; i < permissions.length; i++)
perms.put(permissions[i], grantResults[i]);
if((perms.get(Manifest.permission.GET_ACCOUNTS) == PackageManager.PERMISSION_GRANTED)
&& (perms.get(Manifest.permission.READ_CALENDAR) == PackageManager.PERMISSION_GRANTED)
&& (perms.get(Manifest.permission.WRITE_CALENDAR) == PackageManager.PERMISSION_GRANTED)){
signIn();
}else{
Toast.makeText(LoginScreen.this, "Please provide the necessary permissions", Toast.LENGTH_SHORT).show();
}
break;
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
}
|
app/src/main/java/com/example/android/groupschedulecoordinator/LoginScreen.java
|
package com.example.android.groupschedulecoordinator;
/**
* Created by jeremyfolk on 10/17/16.
* Firebase auth added by tommy 10/27/16
*/
import android.*;
import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.auth.api.signin.GoogleSignInResult;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.SignInButton;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthCredential;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseAuthException;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.GoogleAuthProvider;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;
import java.util.jar.*;
public class LoginScreen extends AppCompatActivity{
//global var
private static final int RC_SIGN_IN = 1;
private static final String TAG = "SignInActivity";
private final int REQUEST_CODE_PERMISSIONS = 123;
private FirebaseAuth mFirebaseAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private FirebaseUser mFirebaseUser;
private int permissionCode;
private GoogleApiClient mGoogleApiClient;
private SignInButton mGoogleButton;
private String mUser;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
mGoogleButton = (SignInButton) findViewById(R.id.sign_in_button);
mFirebaseAuth = FirebaseAuth.getInstance();
mFirebaseUser = mFirebaseAuth.getCurrentUser();
mAuthListener = new FirebaseAuth.AuthStateListener() {
@Override
public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
if(firebaseAuth.getCurrentUser() != null){
startActivity(new Intent(LoginScreen.this, MainActivity.class));
}
}
};
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();
mGoogleApiClient = new GoogleApiClient.Builder(getApplicationContext())
.enableAutoManage(this, new GoogleApiClient.OnConnectionFailedListener() {
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
Toast.makeText(LoginScreen.this, "Error!", Toast.LENGTH_SHORT).show();
}
})
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
mGoogleButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
dummyPermission();
//signIn();
}
});
mGoogleButton.setSize(SignInButton.SIZE_WIDE);
}
private void signIn() {
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
startActivityForResult(signInIntent, RC_SIGN_IN);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//TODO remove this log
Log.d("jasonlogs", "server_client_id : " + this.getResources().getString(R.string.server_client_id));
Log.d("jasonlogs", "default_web_client_id: " + getApplicationContext().getString(R.string.default_web_client_id));
Log.d("jasonLogs", "onActivityResult: " + requestCode + " " + resultCode + " " + data);
// Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
if (requestCode == RC_SIGN_IN) {
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
Log.d("jasonlogs", "result: " + result.getStatus());
if (result.isSuccess()) {
//TODO remove this log
Log.d("jasonlogs", "successful google auth!");
// Google Sign In was successful, authenticate with Firebase
GoogleSignInAccount account = result.getSignInAccount();
firebaseAuthWithGoogle(account);
} else {
//TODO remove this log
Log.d("jasonlogs", "failed google auth.");
// Google Sign In failed, update UI appropriately
// ...
//TODO don't actually go forwards until auth is completed
//startActivity(new Intent(LoginScreen.this, MainActivity.class));
//finish();
}
}
}
private void firebaseAuthWithGoogle(GoogleSignInAccount account) {
Log.d(TAG, "firebaseAuthWithGoogle:" + account.getId());
AuthCredential credential = GoogleAuthProvider.getCredential(account.getIdToken(), null);
mFirebaseAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
Log.d(TAG, "signInWithCredential:onComplete:" + task.isSuccessful());
// If sign in fails, display a message to the user. If sign in succeeds
// the auth state listener will be notified and logic to handle the
// signed in user can be handled in the listener.
if (!task.isSuccessful()) {
Log.w(TAG, "signInWithCredential", task.getException());
Toast.makeText(LoginScreen.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
} else{
startActivity(new Intent(LoginScreen.this, MainActivity.class));
finish();
}
}
});
}
@Override
protected void onStart() {
super.onStart();
mFirebaseAuth.addAuthStateListener(mAuthListener);
}
@Override
public void onStop() {
super.onStop();
if (mAuthListener != null) {
mFirebaseAuth.removeAuthStateListener(mAuthListener);
}
}
@Override
public void onBackPressed() {
}
/* Prompts user for access
Popup dialog prompts user that contacts access is needed
@success, user allows contacts, signIn() is called
@failure, user denies, toast text shows
*/
private void dummyPermission(){
int dummyPermission = checkSelfPermission(Manifest.permission.GET_ACCOUNTS);
if (dummyPermission != PackageManager.PERMISSION_GRANTED) {
if(shouldShowRequestPermissionRationale(Manifest.permission.GET_ACCOUNTS)){
needPermissions("You need to allow access to Contacts", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
requestPermissions(new String[] {Manifest.permission.GET_ACCOUNTS}, REQUEST_CODE_PERMISSIONS);
}
});
return;
}
requestPermissions(new String[] {Manifest.permission.GET_ACCOUNTS}, REQUEST_CODE_PERMISSIONS);
return;
}
signIn();
}
private void needPermissions(String message, DialogInterface.OnClickListener okListener){
new AlertDialog.Builder(LoginScreen.this)
.setMessage(message)
.setPositiveButton("OK", okListener)
.create()
.show();
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
switch (requestCode){
case REQUEST_CODE_PERMISSIONS:
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
signIn();
}else{
Toast.makeText(LoginScreen.this, "Please allow access to contacts", Toast.LENGTH_SHORT).show();
}
break;
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
}
|
Added functionality to request multiple permissions
|
app/src/main/java/com/example/android/groupschedulecoordinator/LoginScreen.java
|
Added functionality to request multiple permissions
|
<ide><path>pp/src/main/java/com/example/android/groupschedulecoordinator/LoginScreen.java
<ide>
<ide> import java.lang.reflect.Array;
<ide> import java.util.ArrayList;
<add>import java.util.HashMap;
<ide> import java.util.List;
<add>import java.util.Map;
<ide> import java.util.jar.*;
<ide>
<ide>
<ide> private static final int RC_SIGN_IN = 1;
<ide> private static final String TAG = "SignInActivity";
<ide> private final int REQUEST_CODE_PERMISSIONS = 123;
<add> private final int REQUEST_CODE_MULTI = 124;
<ide>
<ide>
<ide> private FirebaseAuth mFirebaseAuth;
<ide> mGoogleButton.setOnClickListener(new View.OnClickListener() {
<ide> @Override
<ide> public void onClick(View view) {
<del> dummyPermission();
<add> //dummyPermission();
<ide> //signIn();
<add> multiPermission();
<ide> }
<ide> });
<ide> mGoogleButton.setSize(SignInButton.SIZE_WIDE);
<ide> signIn();
<ide> }
<ide>
<add> /*
<add> Requests permissions to access CONTACTS and CALENDER
<add> case 1: user allows both permissions --> call signIn()
<add> case 2: user denies 1 option --> stays on main screen and prompts user for access
<add> to the permission that was denied
<add> case 3: user denies both options --> prompts for both
<add> */
<add> private void multiPermission(){
<add> List<String> permissionsNeeded = new ArrayList<>();
<add>
<add> final List<String> permissionList = new ArrayList<>();
<add> if(!addPermissions(permissionList, Manifest.permission.GET_ACCOUNTS))
<add> permissionsNeeded.add("ACCOUNTS");
<add> if (!addPermissions(permissionList,Manifest.permission.READ_CALENDAR))
<add> permissionsNeeded.add("READ_CALENDER");
<add> if(!addPermissions(permissionList, Manifest.permission.WRITE_CALENDAR))
<add> permissionsNeeded.add("WRITE_CALENDER");
<add>
<add> if (permissionList.size() > 0) {
<add> if (permissionsNeeded.size() > 0) {
<add> String message = "You need to provide access to " + permissionsNeeded.get(0);
<add> for(int i = 1; i < permissionsNeeded.size(); i++)
<add> message = message + ", " + permissionsNeeded.get(i);
<add> needPermissions(message, new DialogInterface.OnClickListener() {
<add> @Override
<add> public void onClick(DialogInterface dialog, int which) {
<add> requestPermissions(permissionList.toArray(new String[permissionList.size()]), REQUEST_CODE_MULTI);
<add> }
<add> });
<add> return;
<add> }
<add> requestPermissions(permissionList.toArray(new String[permissionList.size()]), REQUEST_CODE_MULTI);
<add> return;
<add> }
<add> signIn();
<add> }
<add>
<add> /*helper for adding permissions*/
<add> private boolean addPermissions(List<String> pList, String permission){
<add> if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) {
<add> pList.add(permission);
<add> if(shouldShowRequestPermissionRationale(permission)){
<add> return false;
<add> }
<add> }
<add> return true;
<add> }
<add>
<ide> private void needPermissions(String message, DialogInterface.OnClickListener okListener){
<ide> new AlertDialog.Builder(LoginScreen.this)
<ide> .setMessage(message)
<ide> Toast.makeText(LoginScreen.this, "Please allow access to contacts", Toast.LENGTH_SHORT).show();
<ide> }
<ide> break;
<add>
<add> case REQUEST_CODE_MULTI:
<add> Map<String,Integer> perms = new HashMap<String,Integer>();
<add> perms.put(Manifest.permission.GET_ACCOUNTS, PackageManager.PERMISSION_GRANTED);
<add> perms.put(Manifest.permission.WRITE_CALENDAR, PackageManager.PERMISSION_GRANTED);
<add> perms.put(Manifest.permission.READ_CALENDAR, PackageManager.PERMISSION_GRANTED);
<add>
<add> for(int i = 0; i < permissions.length; i++)
<add> perms.put(permissions[i], grantResults[i]);
<add> if((perms.get(Manifest.permission.GET_ACCOUNTS) == PackageManager.PERMISSION_GRANTED)
<add> && (perms.get(Manifest.permission.READ_CALENDAR) == PackageManager.PERMISSION_GRANTED)
<add> && (perms.get(Manifest.permission.WRITE_CALENDAR) == PackageManager.PERMISSION_GRANTED)){
<add> signIn();
<add> }else{
<add> Toast.makeText(LoginScreen.this, "Please provide the necessary permissions", Toast.LENGTH_SHORT).show();
<add> }
<add> break;
<ide> default:
<ide> super.onRequestPermissionsResult(requestCode, permissions, grantResults);
<ide> }
|
|
Java
|
apache-2.0
|
8fc8be4583d1b89a3ecfa57e903ba5036e0c3a3e
| 0 |
flomotlik/archiva,olamy/archiva,emsouza/archiva,Altiscale/archiva,apache/archiva,olamy/archiva,apache/archiva,apache/archiva,sadlil/archiva,flomotlik/archiva,sadlil/archiva,ricardojbasilio/archiva,olamy/archiva,flomotlik/archiva,Altiscale/archiva,sadlil/archiva,Altiscale/archiva,Altiscale/archiva,olamy/archiva,flomotlik/archiva,ricardojbasilio/archiva,emsouza/archiva,emsouza/archiva,emsouza/archiva,apache/archiva,sadlil/archiva,ricardojbasilio/archiva,sadlil/archiva,apache/archiva,ricardojbasilio/archiva
|
package org.apache.archiva.web.security;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.archiva.admin.model.RepositoryAdminException;
import org.apache.archiva.admin.model.runtime.RedbackRuntimeConfigurationAdmin;
import org.apache.archiva.redback.components.cache.Cache;
import org.apache.archiva.redback.users.AbstractUserManager;
import org.apache.archiva.redback.users.User;
import org.apache.archiva.redback.users.UserManager;
import org.apache.archiva.redback.users.UserManagerException;
import org.apache.archiva.redback.users.UserManagerListener;
import org.apache.archiva.redback.users.UserNotFoundException;
import org.apache.archiva.redback.users.UserQuery;
import org.apache.archiva.redback.users.configurable.ConfigurableUserManager;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
import javax.inject.Inject;
import javax.inject.Named;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* @author Olivier Lamy
* @since 1.4-M4
*/
@Service( "userManager#archiva" )
public class ArchivaConfigurableUsersManager
extends AbstractUserManager
{
@Inject
private RedbackRuntimeConfigurationAdmin redbackRuntimeConfigurationAdmin;
@Inject
private ApplicationContext applicationContext;
private Map<String, UserManager> userManagerPerId;
@Inject
@Named( value = "cache#users" )
private Cache<String, User> usersCache;
private boolean useUsersCache;
@PostConstruct
public void initialize()
{
try
{
List<String> userManagerImpls =
redbackRuntimeConfigurationAdmin.getRedbackRuntimeConfiguration().getUserManagerImpls();
log.info( "use userManagerImpls: '{}'", userManagerImpls );
userManagerPerId = new LinkedHashMap<String, UserManager>( userManagerImpls.size() );
for ( String id : userManagerImpls )
{
UserManager userManagerImpl = applicationContext.getBean( "userManager#" + id, UserManager.class );
setUserManagerImpl( userManagerImpl );
userManagerPerId.put( id, userManagerImpl );
}
this.useUsersCache = redbackRuntimeConfigurationAdmin.getRedbackRuntimeConfiguration().isUseUsersCache();
}
catch ( RepositoryAdminException e )
{
// revert to a default one ?
log.error( e.getMessage(), e );
throw new RuntimeException( e.getMessage(), e );
}
}
protected boolean useUsersCache()
{
return this.useUsersCache;
}
public User addUser( User user )
throws UserManagerException
{
user = userManagerPerId.get( user.getUserManagerId() ).addUser( user );
if ( useUsersCache() )
{
usersCache.put( user.getUsername(), user );
}
return user;
}
public void addUserUnchecked( User user )
throws UserManagerException
{
userManagerPerId.get( user.getUserManagerId() ).addUserUnchecked( user );
if ( useUsersCache() )
{
usersCache.put( user.getUsername(), user );
}
}
public User createUser( String username, String fullName, String emailAddress )
throws UserManagerException
{
Exception lastException = null;
boolean allFailed = true;
User user = null;
for ( UserManager userManager : userManagerPerId.values() )
{
try
{
if ( !userManager.isReadOnly() )
{
user = userManager.createUser( username, fullName, emailAddress );
allFailed = false;
}
}
catch ( Exception e )
{
lastException = e;
}
}
if ( lastException != null && allFailed )
{
throw new UserManagerException( lastException.getMessage(), lastException );
}
return user;
}
public UserQuery createUserQuery()
{
return userManagerPerId.values().iterator().next().createUserQuery();
}
public void deleteUser( String username )
throws UserNotFoundException, UserManagerException
{
Exception lastException = null;
boolean allFailed = true;
User user = null;
for ( UserManager userManager : userManagerPerId.values() )
{
try
{
if ( !userManager.isReadOnly() )
{
userManager.deleteUser( username );
allFailed = false;
}
}
catch ( Exception e )
{
lastException = e;
}
}
if ( lastException != null && allFailed )
{
throw new UserManagerException( lastException.getMessage(), lastException );
}
}
public void eraseDatabase()
{
for ( UserManager userManager : userManagerPerId.values() )
{
userManager.eraseDatabase();
}
}
public User findUser( String username )
throws UserManagerException
{
User user = null;
if ( useUsersCache() )
{
user = usersCache.get( username );
if ( user != null )
{
return user;
}
}
Exception lastException = null;
for ( UserManager userManager : userManagerPerId.values() )
{
try
{
user = userManager.findUser( username );
if ( user != null )
{
if ( useUsersCache() )
{
usersCache.put( username, user );
}
return user;
}
}
catch ( UserNotFoundException e )
{
lastException = e;
}
catch ( Exception e )
{
lastException = e;
}
}
if ( user == null )
{
if ( lastException != null )
{
throw new UserManagerException( lastException.getMessage(), lastException );
}
}
return user;
}
@Override
public User getGuestUser()
throws UserNotFoundException, UserManagerException
{
return findUser( GUEST_USERNAME );
}
public List<User> findUsersByEmailKey( String emailKey, boolean orderAscending )
throws UserManagerException
{
List<User> users = new ArrayList<User>();
for ( UserManager userManager : userManagerPerId.values() )
{
List<User> found = userManager.findUsersByEmailKey( emailKey, orderAscending );
if ( found != null )
{
users.addAll( found );
}
}
return users;
}
public List<User> findUsersByFullNameKey( String fullNameKey, boolean orderAscending )
throws UserManagerException
{
List<User> users = new ArrayList<User>();
for ( UserManager userManager : userManagerPerId.values() )
{
List<User> found = userManager.findUsersByFullNameKey( fullNameKey, orderAscending );
if ( found != null )
{
users.addAll( found );
}
}
return users;
}
public List<User> findUsersByQuery( UserQuery query )
throws UserManagerException
{
List<User> users = new ArrayList<User>();
for ( UserManager userManager : userManagerPerId.values() )
{
List<User> found = userManager.findUsersByQuery( query );
if ( found != null )
{
users.addAll( found );
}
}
return users;
}
public List<User> findUsersByUsernameKey( String usernameKey, boolean orderAscending )
throws UserManagerException
{
List<User> users = new ArrayList<User>();
for ( UserManager userManager : userManagerPerId.values() )
{
List<User> found = userManager.findUsersByUsernameKey( usernameKey, orderAscending );
if ( found != null )
{
users.addAll( found );
}
}
return users;
}
public String getId()
{
return null;
}
public List<User> getUsers()
throws UserManagerException
{
List<User> users = new ArrayList<User>();
for ( UserManager userManager : userManagerPerId.values() )
{
List<User> found = userManager.getUsers();
if ( found != null )
{
users.addAll( found );
}
}
return users;
}
public List<User> getUsers( boolean orderAscending )
throws UserManagerException
{
List<User> users = new ArrayList<User>();
for ( UserManager userManager : userManagerPerId.values() )
{
List<User> found = userManager.getUsers( orderAscending );
if ( found != null )
{
users.addAll( found );
}
}
return users;
}
public boolean isReadOnly()
{
boolean readOnly = false;
for ( UserManager userManager : userManagerPerId.values() )
{
readOnly = readOnly || userManager.isReadOnly();
}
return readOnly;
}
public User updateUser( User user )
throws UserNotFoundException, UserManagerException
{
user = userManagerPerId.get( user.getUserManagerId() ).updateUser( user );
if ( useUsersCache() )
{
usersCache.put( user.getUsername(), user );
}
return user;
}
public User updateUser( User user, boolean passwordChangeRequired )
throws UserNotFoundException, UserManagerException
{
user = userManagerPerId.get( user.getUserManagerId() ).updateUser( user, passwordChangeRequired );
if ( useUsersCache() )
{
usersCache.put( user.getUsername(), user );
}
return user;
}
public void setUserManagerImpl( UserManager userManagerImpl )
{
// not possible here but we know so no need of log.error
log.debug( "setUserManagerImpl cannot be used in this implementation" );
}
@Override
public User createGuestUser()
throws UserManagerException
{
Exception lastException = null;
boolean allFailed = true;
User user = null;
for ( UserManager userManager : userManagerPerId.values() )
{
try
{
if ( !userManager.isReadOnly() )
{
user = userManager.createGuestUser();
allFailed = false;
}
}
catch ( Exception e )
{
lastException = e;
}
}
if ( lastException != null && allFailed )
{
throw new UserManagerException( lastException.getMessage(), lastException );
}
return user;
}
public boolean userExists( String userName )
throws UserManagerException
{
Exception lastException = null;
boolean allFailed = true;
boolean exists = false;
for ( UserManager userManager : userManagerPerId.values() )
{
try
{
if ( userManager.userExists( userName ) )
{
exists = true;
}
allFailed = false;
}
catch ( Exception e )
{
lastException = e;
}
}
if ( lastException != null && allFailed )
{
throw new UserManagerException( lastException.getMessage(), lastException );
}
return exists;
}
@Override
public boolean isFinalImplementation()
{
return false;
}
public String getDescriptionKey()
{
return "archiva.redback.usermanager.configurable.archiva";
}
}
|
archiva-modules/archiva-web/archiva-web-common/src/main/java/org/apache/archiva/web/security/ArchivaConfigurableUsersManager.java
|
package org.apache.archiva.web.security;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.archiva.admin.model.RepositoryAdminException;
import org.apache.archiva.admin.model.runtime.RedbackRuntimeConfigurationAdmin;
import org.apache.archiva.redback.components.cache.Cache;
import org.apache.archiva.redback.users.User;
import org.apache.archiva.redback.users.UserManager;
import org.apache.archiva.redback.users.UserManagerException;
import org.apache.archiva.redback.users.UserManagerListener;
import org.apache.archiva.redback.users.UserNotFoundException;
import org.apache.archiva.redback.users.UserQuery;
import org.apache.archiva.redback.users.configurable.ConfigurableUserManager;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import javax.inject.Inject;
import javax.inject.Named;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* @author Olivier Lamy
* @since 1.4-M4
*/
@Service( "userManager#archiva" )
public class ArchivaConfigurableUsersManager
extends ConfigurableUserManager
{
@Inject
private RedbackRuntimeConfigurationAdmin redbackRuntimeConfigurationAdmin;
@Inject
private ApplicationContext applicationContext;
private Map<String, UserManager> userManagerPerId;
private List<UserManagerListener> listeners = new ArrayList<UserManagerListener>();
@Inject
@Named( value = "cache#users" )
private Cache<String, User> usersCache;
private boolean useUsersCache;
@Override
public void initialize()
{
try
{
List<String> userManagerImpls =
redbackRuntimeConfigurationAdmin.getRedbackRuntimeConfiguration().getUserManagerImpls();
log.info( "use userManagerImpls: '{}'", userManagerImpls );
userManagerPerId = new LinkedHashMap<String, UserManager>( userManagerImpls.size() );
for ( String id : userManagerImpls )
{
UserManager userManagerImpl = applicationContext.getBean( "userManager#" + id, UserManager.class );
setUserManagerImpl( userManagerImpl );
userManagerPerId.put( id, userManagerImpl );
}
this.useUsersCache = redbackRuntimeConfigurationAdmin.getRedbackRuntimeConfiguration().isUseUsersCache();
}
catch ( RepositoryAdminException e )
{
// revert to a default one ?
log.error( e.getMessage(), e );
throw new RuntimeException( e.getMessage(), e );
}
}
protected boolean useUsersCache()
{
return this.useUsersCache;
}
@Override
public User addUser( User user )
throws UserManagerException
{
user = userManagerPerId.get( user.getUserManagerId() ).addUser( user );
if ( useUsersCache() )
{
usersCache.put( user.getUsername(), user );
}
return user;
}
@Override
public void addUserUnchecked( User user )
throws UserManagerException
{
userManagerPerId.get( user.getUserManagerId() ).addUserUnchecked( user );
if ( useUsersCache() )
{
usersCache.put( user.getUsername(), user );
}
}
@Override
public User createUser( String username, String fullName, String emailAddress )
throws UserManagerException
{
Exception lastException = null;
boolean allFailed = true;
User user = null;
for ( UserManager userManager : userManagerPerId.values() )
{
try
{
if ( !userManager.isReadOnly() )
{
user = userManager.createUser( username, fullName, emailAddress );
allFailed = false;
}
}
catch ( Exception e )
{
lastException = e;
}
}
if ( lastException != null && allFailed )
{
throw new UserManagerException( lastException.getMessage(), lastException );
}
return user;
}
@Override
public UserQuery createUserQuery()
{
return super.createUserQuery();
}
@Override
public void deleteUser( String username )
throws UserNotFoundException, UserManagerException
{
Exception lastException = null;
boolean allFailed = true;
User user = null;
for ( UserManager userManager : userManagerPerId.values() )
{
try
{
if ( !userManager.isReadOnly() )
{
userManager.deleteUser( username );
allFailed = false;
}
}
catch ( Exception e )
{
lastException = e;
}
}
if ( lastException != null && allFailed )
{
throw new UserManagerException( lastException.getMessage(), lastException );
}
}
@Override
public void eraseDatabase()
{
for ( UserManager userManager : userManagerPerId.values() )
{
userManager.eraseDatabase();
}
}
@Override
public User findUser( String username )
throws UserManagerException
{
User user = null;
if ( useUsersCache() )
{
user = usersCache.get( username );
if ( user != null )
{
return user;
}
}
Exception lastException = null;
for ( UserManager userManager : userManagerPerId.values() )
{
try
{
user = userManager.findUser( username );
if ( user != null )
{
if ( useUsersCache() )
{
usersCache.put( username, user );
}
return user;
}
}
catch ( UserNotFoundException e )
{
lastException = e;
}
catch ( Exception e )
{
lastException = e;
}
}
if ( user == null )
{
if ( lastException != null )
{
throw new UserManagerException( lastException.getMessage(), lastException );
}
}
return user;
}
@Override
public User getGuestUser()
throws UserNotFoundException, UserManagerException
{
return findUser( GUEST_USERNAME );
}
@Override
public List<User> findUsersByEmailKey( String emailKey, boolean orderAscending )
throws UserManagerException
{
List<User> users = new ArrayList<User>();
for ( UserManager userManager : userManagerPerId.values() )
{
List<User> found = userManager.findUsersByEmailKey( emailKey, orderAscending );
if ( found != null )
{
users.addAll( found );
}
}
return users;
}
@Override
public List<User> findUsersByFullNameKey( String fullNameKey, boolean orderAscending )
throws UserManagerException
{
List<User> users = new ArrayList<User>();
for ( UserManager userManager : userManagerPerId.values() )
{
List<User> found = userManager.findUsersByFullNameKey( fullNameKey, orderAscending );
if ( found != null )
{
users.addAll( found );
}
}
return users;
}
@Override
public List<User> findUsersByQuery( UserQuery query )
throws UserManagerException
{
List<User> users = new ArrayList<User>();
for ( UserManager userManager : userManagerPerId.values() )
{
List<User> found = userManager.findUsersByQuery( query );
if ( found != null )
{
users.addAll( found );
}
}
return users;
}
@Override
public List<User> findUsersByUsernameKey( String usernameKey, boolean orderAscending )
throws UserManagerException
{
List<User> users = new ArrayList<User>();
for ( UserManager userManager : userManagerPerId.values() )
{
List<User> found = userManager.findUsersByUsernameKey( usernameKey, orderAscending );
if ( found != null )
{
users.addAll( found );
}
}
return users;
}
@Override
public String getId()
{
return null;
}
@Override
public List<User> getUsers()
throws UserManagerException
{
List<User> users = new ArrayList<User>();
for ( UserManager userManager : userManagerPerId.values() )
{
List<User> found = userManager.getUsers();
if ( found != null )
{
users.addAll( found );
}
}
return users;
}
@Override
public List<User> getUsers( boolean orderAscending )
throws UserManagerException
{
List<User> users = new ArrayList<User>();
for ( UserManager userManager : userManagerPerId.values() )
{
List<User> found = userManager.getUsers( orderAscending );
if ( found != null )
{
users.addAll( found );
}
}
return users;
}
@Override
public boolean isReadOnly()
{
boolean readOnly = false;
for ( UserManager userManager : userManagerPerId.values() )
{
readOnly = readOnly || userManager.isReadOnly();
}
return readOnly;
}
@Override
public User updateUser( User user )
throws UserNotFoundException, UserManagerException
{
user = userManagerPerId.get( user.getUserManagerId() ).updateUser( user );
if ( useUsersCache() )
{
usersCache.put( user.getUsername(), user );
}
return user;
}
@Override
public User updateUser( User user, boolean passwordChangeRequired )
throws UserNotFoundException, UserManagerException
{
user = userManagerPerId.get( user.getUserManagerId() ).updateUser( user, passwordChangeRequired );
if ( useUsersCache() )
{
usersCache.put( user.getUsername(), user );
}
return user;
}
@Override
public void setUserManagerImpl( UserManager userManagerImpl )
{
// not possible here but we know so no need of log.error
log.debug( "setUserManagerImpl cannot be used in this implementation" );
}
@Override
public void addUserManagerListener( UserManagerListener listener )
{
this.listeners.add( listener );
}
@Override
public void removeUserManagerListener( UserManagerListener listener )
{
this.listeners.remove( listener );
}
@Override
protected void fireUserManagerInit( boolean freshDatabase )
{
for ( UserManagerListener listener : listeners )
{
listener.userManagerInit( freshDatabase );
}
}
@Override
protected void fireUserManagerUserAdded( User addedUser )
{
for ( UserManagerListener listener : listeners )
{
listener.userManagerUserAdded( addedUser );
}
}
@Override
protected void fireUserManagerUserRemoved( User removedUser )
{
for ( UserManagerListener listener : listeners )
{
listener.userManagerUserRemoved( removedUser );
}
}
@Override
protected void fireUserManagerUserUpdated( User updatedUser )
{
for ( UserManagerListener listener : listeners )
{
listener.userManagerUserUpdated( updatedUser );
}
}
@Override
public User createGuestUser()
throws UserManagerException
{
Exception lastException = null;
boolean allFailed = true;
User user = null;
for ( UserManager userManager : userManagerPerId.values() )
{
try
{
if ( !userManager.isReadOnly() )
{
user = userManager.createGuestUser();
allFailed = false;
}
}
catch ( Exception e )
{
lastException = e;
}
}
if ( lastException != null && allFailed )
{
throw new UserManagerException( lastException.getMessage(), lastException );
}
return user;
}
@Override
public boolean userExists( String userName )
throws UserManagerException
{
Exception lastException = null;
boolean allFailed = true;
boolean exists = false;
for ( UserManager userManager : userManagerPerId.values() )
{
try
{
if ( userManager.userExists( userName ) )
{
exists = true;
}
allFailed = false;
}
catch ( Exception e )
{
lastException = e;
}
}
if ( lastException != null && allFailed )
{
throw new UserManagerException( lastException.getMessage(), lastException );
}
return exists;
}
@Override
public boolean isFinalImplementation()
{
return false;
}
public String getDescriptionKey()
{
return "archiva.redback.usermanager.configurable.archiva";
}
}
|
override AbstractUserManager rather than Configurable.
git-svn-id: 5a9cb29c8d7fce18aac47241089437545778aaf0@1451378 13f79535-47bb-0310-9956-ffa450edef68
|
archiva-modules/archiva-web/archiva-web-common/src/main/java/org/apache/archiva/web/security/ArchivaConfigurableUsersManager.java
|
override AbstractUserManager rather than Configurable.
|
<ide><path>rchiva-modules/archiva-web/archiva-web-common/src/main/java/org/apache/archiva/web/security/ArchivaConfigurableUsersManager.java
<ide> import org.apache.archiva.admin.model.RepositoryAdminException;
<ide> import org.apache.archiva.admin.model.runtime.RedbackRuntimeConfigurationAdmin;
<ide> import org.apache.archiva.redback.components.cache.Cache;
<add>import org.apache.archiva.redback.users.AbstractUserManager;
<ide> import org.apache.archiva.redback.users.User;
<ide> import org.apache.archiva.redback.users.UserManager;
<ide> import org.apache.archiva.redback.users.UserManagerException;
<ide> import org.springframework.context.ApplicationContext;
<ide> import org.springframework.stereotype.Service;
<ide>
<add>import javax.annotation.PostConstruct;
<ide> import javax.inject.Inject;
<ide> import javax.inject.Named;
<ide> import java.util.ArrayList;
<ide> */
<ide> @Service( "userManager#archiva" )
<ide> public class ArchivaConfigurableUsersManager
<del> extends ConfigurableUserManager
<add> extends AbstractUserManager
<ide> {
<ide>
<ide> @Inject
<ide> private ApplicationContext applicationContext;
<ide>
<ide> private Map<String, UserManager> userManagerPerId;
<del>
<del> private List<UserManagerListener> listeners = new ArrayList<UserManagerListener>();
<ide>
<ide> @Inject
<ide> @Named( value = "cache#users" )
<ide>
<ide> private boolean useUsersCache;
<ide>
<del> @Override
<add> @PostConstruct
<ide> public void initialize()
<ide> {
<ide> try
<ide> return this.useUsersCache;
<ide> }
<ide>
<del> @Override
<ide> public User addUser( User user )
<ide> throws UserManagerException
<ide> {
<ide> return user;
<ide> }
<ide>
<del> @Override
<ide> public void addUserUnchecked( User user )
<ide> throws UserManagerException
<ide> {
<ide> }
<ide> }
<ide>
<del> @Override
<ide> public User createUser( String username, String fullName, String emailAddress )
<ide> throws UserManagerException
<ide> {
<ide> return user;
<ide> }
<ide>
<del> @Override
<ide> public UserQuery createUserQuery()
<ide> {
<del> return super.createUserQuery();
<del> }
<del>
<del>
<del> @Override
<add> return userManagerPerId.values().iterator().next().createUserQuery();
<add> }
<add>
<add>
<ide> public void deleteUser( String username )
<ide> throws UserNotFoundException, UserManagerException
<ide> {
<ide> }
<ide> }
<ide>
<del> @Override
<ide> public void eraseDatabase()
<ide> {
<ide> for ( UserManager userManager : userManagerPerId.values() )
<ide> }
<ide> }
<ide>
<del> @Override
<ide> public User findUser( String username )
<ide> throws UserManagerException
<ide> {
<ide> return findUser( GUEST_USERNAME );
<ide> }
<ide>
<del> @Override
<ide> public List<User> findUsersByEmailKey( String emailKey, boolean orderAscending )
<ide> throws UserManagerException
<ide> {
<ide> return users;
<ide> }
<ide>
<del> @Override
<ide> public List<User> findUsersByFullNameKey( String fullNameKey, boolean orderAscending )
<ide> throws UserManagerException
<ide> {
<ide> return users;
<ide> }
<ide>
<del> @Override
<ide> public List<User> findUsersByQuery( UserQuery query )
<ide> throws UserManagerException
<ide> {
<ide> return users;
<ide> }
<ide>
<del> @Override
<ide> public List<User> findUsersByUsernameKey( String usernameKey, boolean orderAscending )
<ide> throws UserManagerException
<ide> {
<ide> return users;
<ide> }
<ide>
<del> @Override
<ide> public String getId()
<ide> {
<ide> return null;
<ide> }
<ide>
<del> @Override
<ide> public List<User> getUsers()
<ide> throws UserManagerException
<ide> {
<ide> return users;
<ide> }
<ide>
<del> @Override
<ide> public List<User> getUsers( boolean orderAscending )
<ide> throws UserManagerException
<ide> {
<ide> return users;
<ide> }
<ide>
<del> @Override
<ide> public boolean isReadOnly()
<ide> {
<ide> boolean readOnly = false;
<ide> return readOnly;
<ide> }
<ide>
<del> @Override
<ide> public User updateUser( User user )
<ide> throws UserNotFoundException, UserManagerException
<ide> {
<ide> return user;
<ide> }
<ide>
<del> @Override
<ide> public User updateUser( User user, boolean passwordChangeRequired )
<ide> throws UserNotFoundException, UserManagerException
<ide> {
<ide> return user;
<ide> }
<ide>
<del> @Override
<ide> public void setUserManagerImpl( UserManager userManagerImpl )
<ide> {
<ide> // not possible here but we know so no need of log.error
<ide> log.debug( "setUserManagerImpl cannot be used in this implementation" );
<del> }
<del>
<del> @Override
<del> public void addUserManagerListener( UserManagerListener listener )
<del> {
<del> this.listeners.add( listener );
<del> }
<del>
<del> @Override
<del> public void removeUserManagerListener( UserManagerListener listener )
<del> {
<del> this.listeners.remove( listener );
<del> }
<del>
<del> @Override
<del> protected void fireUserManagerInit( boolean freshDatabase )
<del> {
<del> for ( UserManagerListener listener : listeners )
<del> {
<del> listener.userManagerInit( freshDatabase );
<del> }
<del> }
<del>
<del> @Override
<del> protected void fireUserManagerUserAdded( User addedUser )
<del> {
<del> for ( UserManagerListener listener : listeners )
<del> {
<del> listener.userManagerUserAdded( addedUser );
<del> }
<del> }
<del>
<del> @Override
<del> protected void fireUserManagerUserRemoved( User removedUser )
<del> {
<del> for ( UserManagerListener listener : listeners )
<del> {
<del> listener.userManagerUserRemoved( removedUser );
<del> }
<del> }
<del>
<del> @Override
<del> protected void fireUserManagerUserUpdated( User updatedUser )
<del> {
<del> for ( UserManagerListener listener : listeners )
<del> {
<del> listener.userManagerUserUpdated( updatedUser );
<del> }
<ide> }
<ide>
<ide> @Override
<ide> }
<ide>
<ide>
<del> @Override
<ide> public boolean userExists( String userName )
<ide> throws UserManagerException
<ide> {
<ide> return exists;
<ide> }
<ide>
<add>
<add>
<ide> @Override
<ide> public boolean isFinalImplementation()
<ide> {
|
|
JavaScript
|
mit
|
bcee395da65aff4ca035cb9ba565aa3487c73dec
| 0 |
bd808/userscripts,bd808/userscripts
|
// ==UserScript==
// @name etherpad personal settings
// @namespace http://bd808.com/userscripts
// @description Don't use this unless you are bd808!
// @match http://etherpad.*/p/*
// @match https://etherpad.*/p/*
// @version 0.3
// @author Bryan Davis
// @license MIT License; http://opensource.org/licenses/MIT
// @downloadURL http://bd808.com/userscripts/etherpad.user.js
// @updateURL http://bd808.com/userscripts/etherpad.user.js
// @grant none
// @run-at document-end
// ==/UserScript==
(function() {
pad.notifyChangeColor('#fdf6e3');
pad.notifyChangeName('bd808');
})();
|
etherpad.user.js
|
// ==UserScript==
// @name etherpad personal settings
// @namespace http://bd808.com/userscripts
// @description Don't use this unless you are bd808!
// @match http://etherpad.*/p/*
// @match https://etherpad.*/p/*
// @version 0.2
// @author Bryan Davis
// @license MIT License; http://opensource.org/licenses/MIT
// @downloadURL http://bd808.com/userscripts/etherpad.user.js
// @updateURL http://bd808.com/userscripts/etherpad.user.js
// ==/UserScript==
(function() {
pad.notifyChangeColor('#fdf6e3');
pad.notifyChangeName('bd808');
})();
|
etherpad: grant and run-at settings
|
etherpad.user.js
|
etherpad: grant and run-at settings
|
<ide><path>therpad.user.js
<ide> // @description Don't use this unless you are bd808!
<ide> // @match http://etherpad.*/p/*
<ide> // @match https://etherpad.*/p/*
<del>// @version 0.2
<add>// @version 0.3
<ide> // @author Bryan Davis
<ide> // @license MIT License; http://opensource.org/licenses/MIT
<ide> // @downloadURL http://bd808.com/userscripts/etherpad.user.js
<ide> // @updateURL http://bd808.com/userscripts/etherpad.user.js
<add>// @grant none
<add>// @run-at document-end
<ide> // ==/UserScript==
<ide> (function() {
<ide> pad.notifyChangeColor('#fdf6e3');
|
|
Java
|
lgpl-2.1
|
765a1af54f26c4f6a6dd46b4e2a8be194b265ee2
| 0 |
ethaneldridge/vassal,ethaneldridge/vassal,ethaneldridge/vassal
|
/*
*
* Copyright (c) 2000-2007 by Rodney Kinney, Joel Uckelman
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License (LGPL) as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, copies are available
* at http://www.opensource.org.
*/
package VASSAL.build.module.map;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Stroke;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import javax.swing.JComponent;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import VASSAL.build.Buildable;
import VASSAL.build.GameModule;
import VASSAL.build.module.Map;
import VASSAL.counters.ColoredBorder;
import VASSAL.counters.Deck;
import VASSAL.counters.DeckVisitor;
import VASSAL.counters.EventFilter;
import VASSAL.counters.GamePiece;
import VASSAL.counters.Immobilized;
import VASSAL.counters.KeyBuffer;
import VASSAL.counters.PieceFinder;
import VASSAL.counters.PieceVisitorDispatcher;
import VASSAL.counters.Properties;
import VASSAL.counters.Stack;
import VASSAL.tools.swing.SwingUtils;
/**
* This component listens for mouse clicks on a map and draws the selection
* rectangle.
*
* If the user clicks on a {@link GamePiece}, that piece is added to the
* {@link KeyBuffer}. {@link #draw(Graphics, Map)} is responsible for
* drawing the mouse selection rectangle, and
* {@link #mouseDragged(MouseEvent)} is responsible for triggering repaint
* events as the selection rectangle is moved.
*
* @see Map#addLocalMouseListener
*/
public class KeyBufferer extends MouseAdapter implements Buildable, MouseMotionListener, Drawable {
protected Map map;
protected Rectangle selection;
protected Point anchor;
protected Color color = Color.black;
protected int thickness = 3;
protected GamePiece bandSelectPiece = null;
private enum BandSelectType {
NONE,
NORMAL,
SPECIAL
}
@Override
public void addTo(Buildable b) {
map = (Map) b;
map.addLocalMouseListenerFirst(this);
map.getView().addMouseMotionListener(this);
map.addDrawComponent(this);
}
@Override
public void add(Buildable b) {
}
@Override
public Element getBuildElement(Document doc) {
return doc.createElement(getClass().getName());
}
@Override
public void build(Element e) {
}
@Override
public void mousePressed(MouseEvent e) {
if (e.isConsumed()) {
return;
}
final KeyBuffer kbuf = KeyBuffer.getBuffer();
GamePiece p = map.findPiece(e.getPoint(), PieceFinder.PIECE_IN_STACK);
// Don't clear the buffer until we find the clicked-on piece
// Because selecting a piece affects its visibility
EventFilter filter = null;
BandSelectType bandSelect = BandSelectType.NONE;
if (p != null) {
filter = (EventFilter) p.getProperty(Properties.SELECT_EVENT_FILTER);
if (SwingUtils.isVanillaLeftButtonDown(e) && Boolean.TRUE.equals(p.getProperty(Properties.NON_MOVABLE))) {
// Don't "eat" band-selects if unit found is non-movable
bandSelect = BandSelectType.SPECIAL;
}
}
boolean ignoreEvent = filter != null && filter.rejectEvent(e);
if (p != null && !ignoreEvent) {
boolean movingStacksPickupUnits = (Boolean) GameModule.getGameModule().getPrefs().getValue(Map.MOVING_STACKS_PICKUP_UNITS);
if (!kbuf.contains(p)) {
if (!e.isShiftDown() && !SwingUtils.isSelectionToggle(e)) {
kbuf.clear();
}
// RFE 1629255 - If the top piece of an unexpanded stack is left-clicked
// while not selected, then select all of the pieces in the stack
if (movingStacksPickupUnits ||
p.getParent() == null ||
p.getParent().isExpanded() ||
SwingUtils.isSelectionToggle(e) ||
Boolean.TRUE.equals(p.getProperty(Properties.SELECTED))) {
kbuf.add(p);
}
else {
Stack s = p.getParent();
s.asList().forEach(gamePiece -> KeyBuffer.getBuffer().add(gamePiece));
}
// End RFE 1629255
}
else {
// RFE 1659481 Ctrl-click deselects clicked units
if (SwingUtils.isSelectionToggle(e) && Boolean.TRUE.equals(p.getProperty(Properties.SELECTED))) {
Stack s = p.getParent();
if (s == null) {
kbuf.remove(p);
}
else if (!s.isExpanded()) {
s.asList().forEach(gamePiece -> KeyBuffer.getBuffer().remove(gamePiece));
}
else {
kbuf.remove(p);
}
}
// End RFE 1659481
}
final GamePiece to_front = p.getParent() != null ? p.getParent() : p;
map.getPieceCollection().moveToFront(to_front);
}
else {
bandSelect = BandSelectType.NORMAL; //BR// Allowed to band-select
}
if (bandSelect != BandSelectType.NONE) {
bandSelectPiece = null;
if (!e.isShiftDown() && !SwingUtils.isSelectionToggle(e)) { // No deselect if shift key down
kbuf.clear();
//BR// This section allows band-select to be attempted from non-moving pieces w/o preventing click-to-select from working
if (bandSelect == BandSelectType.SPECIAL && p != null && !ignoreEvent) {
kbuf.add(p);
bandSelectPiece = p;
}
}
anchor = map.mapToComponent(e.getPoint());
selection = new Rectangle(anchor.x, anchor.y, 0, 0);
if (map.getHighlighter() instanceof ColoredBorder) {
ColoredBorder b = (ColoredBorder) map.getHighlighter();
color = b.getColor();
thickness = b.getThickness();
}
}
}
@Override
public void mouseReleased(MouseEvent e) {
if (selection == null) {
return;
}
PieceVisitorDispatcher d = createDragSelector(
!SwingUtils.isSelectionToggle(e), e.isAltDown(), map.componentToMap(selection)
);
// If it was a legit band-select drag (not just a click), our special case
// only applies if piece is allowed to be band-selected
if (bandSelectPiece != null) {
final EventFilter bandFilter = (EventFilter) bandSelectPiece.getProperty(Properties.BAND_SELECT_EVENT_FILTER);
final boolean pieceAllowedToBeBandSelected = bandFilter != null && !e.isAltDown() && bandFilter instanceof Immobilized.UseAlt;
if (pieceAllowedToBeBandSelected) {
final Point finish = map.mapToComponent(e.getPoint());
// Open to suggestions about a better way to distinguish "click" from
// "lasso" (not that Vassal doesn't already suck immensely at
// click-vs-drag threshhold). FWIW, this "works".
final boolean isLasso = finish.distance(anchor) >= 10;
if (isLasso) {
bandSelectPiece = null;
}
}
}
// RFE 1659481 Don't clear the entire selection buffer if either shift
// or control is down - we select/deselect lassoed counters instead
if (bandSelectPiece == null && !e.isShiftDown() && !SwingUtils.isSelectionToggle(e)) {
KeyBuffer.getBuffer().clear();
}
map.apply(d);
repaintSelectionRect();
selection = null;
}
/**
* This PieceVisitorDispatcher determines what to do with pieces on the
* map when the player finished dragging a rectangle to select pieces
*
* @return
*/
protected PieceVisitorDispatcher createDragSelector(
boolean selecting,
boolean altDown,
Rectangle mapsel) {
return new PieceVisitorDispatcher(
new KBDeckVisitor(selecting, altDown, mapsel)
);
}
public class KBDeckVisitor implements DeckVisitor {
boolean selecting = false;
boolean altDown = false;
Rectangle mapsel;
public KBDeckVisitor(boolean b, boolean c, Rectangle ms) {
selecting = b;
altDown = c;
mapsel = ms;
}
@Override
public Object visitDeck(Deck d) {
return null;
}
@Override
public Object visitStack(Stack s) {
if (s.topPiece() != null) {
final KeyBuffer kbuf = KeyBuffer.getBuffer();
if (s instanceof Deck) {
s.asList().forEach(kbuf::remove); // Clear any deck *members* out of the KeyBuffer.
return null;
}
if (s.isExpanded()) {
Point[] pos = new Point[s.getPieceCount()];
map.getStackMetrics().getContents(s, pos, null, null, s.getPosition().x, s.getPosition().y);
for (int i = 0; i < pos.length; ++i) {
if (mapsel.contains(pos[i])) {
if (selecting) {
kbuf.add(s.getPieceAt(i));
}
else {
kbuf.remove(s.getPieceAt(i));
}
}
}
}
else if (mapsel.contains(s.getPosition())) {
s.asList().forEach(selecting ? kbuf::add : kbuf::remove);
}
}
return null;
}
// Handle non-stacked units, including Does Not Stack units
// Does Not Stack units deselect normally once selected
@Override
public Object visitDefault(GamePiece p) {
Stack s = p.getParent();
if (s != null && s instanceof Deck) {
// Clear any deck *members* out of the KeyBuffer.
// (yes, members of decks can be does-not-stack)
KeyBuffer.getBuffer().remove(p);
return null;
}
if (mapsel.contains(p.getPosition()) && !Boolean.TRUE.equals(p.getProperty(Properties.INVISIBLE_TO_ME))) {
if (selecting) {
final EventFilter filter = (EventFilter) p.getProperty(Properties.SELECT_EVENT_FILTER);
final EventFilter bandFilter = (EventFilter) p.getProperty(Properties.BAND_SELECT_EVENT_FILTER);
final boolean altSelect = (altDown && filter instanceof Immobilized.UseAlt);
final boolean altBand = (altDown && bandFilter instanceof Immobilized.UseAlt);
if ((filter == null || altSelect) && ((bandFilter == null) || altBand)) { //BR// Band-select filtering support
KeyBuffer.getBuffer().add(p);
}
}
else {
KeyBuffer.getBuffer().remove(p);
}
}
return null;
}
}
protected void repaintSelectionRect() {
/*
* Repaint strategy: There is no reason to repaint the interior of
* the selection rectangle, as we didn't paint over it in the first
* place. Instead, we repaint only the four (slender) rectangles
* which the stroke of the selection rectangle filled. We have to
* call a repaint on both the old selection rectangle and the new
* in order to prevent drawing artifacts. The KeyBuffer handles
* repainting pieces which have been (de)selected, so we don't
* worry about those.
*
* Area drawn:
* selection.x
* |
* ___________________
* selection.y __ |__|__|_____|__|__| __
* |__|__|_____|__|__| |
* | | | | | | |
* | | | | | | | selection.height
* |__|__|_____|__|__| |
* ~thickness/2 --{ |__|__|_____|__|__| __|
* ~thickness/2 --{ |__|__|_____|__|__|
*
* |___________|
* selection.width
*/
final int ht = thickness / 2 + thickness % 2;
final int ht2 = 2*ht;
final JComponent view = map.getView();
// left
view.repaint(selection.x - ht,
selection.y - ht,
ht2,
selection.height + ht2);
// right
view.repaint(selection.x + selection.width - ht,
selection.y - ht,
ht2,
selection.height + ht2);
// top
view.repaint(selection.x - ht,
selection.y - ht,
selection.width + ht2,
ht2);
// bottom
view.repaint(selection.x - ht,
selection.y + selection.width - ht,
selection.width + ht2,
ht2);
}
/**
* Sets the new location of the selection rectangle.
*/
@Override
public void mouseDragged(MouseEvent e) {
if (selection == null || !SwingUtils.isVanillaLeftButtonDown(e)) {
return;
}
repaintSelectionRect();
final int ex = e.getX();
final int ey = e.getY();
selection.x = Math.min(ex, anchor.x);
selection.y = Math.min(ey, anchor.y);
selection.width = Math.abs(ex - anchor.x);
selection.height = Math.abs(ey - anchor.y);
repaintSelectionRect();
}
@Override
public void mouseMoved(MouseEvent e) {
}
@Override
public void draw(Graphics g, Map map) {
if (selection == null) {
return;
}
final Graphics2D g2d = (Graphics2D) g;
final double os_scale = g2d.getDeviceConfiguration().getDefaultTransform().getScaleX();
final Stroke str = g2d.getStroke();
g2d.setStroke(new BasicStroke((float)(thickness * os_scale)));
g2d.setColor(color);
g2d.drawRect(
(int)(selection.x * os_scale),
(int)(selection.y * os_scale),
(int)(selection.width * os_scale),
(int)(selection.height * os_scale)
);
g2d.setStroke(str);
}
@Override
public boolean drawAboveCounters() {
return true;
}
}
|
vassal-app/src/main/java/VASSAL/build/module/map/KeyBufferer.java
|
/*
*
* Copyright (c) 2000-2007 by Rodney Kinney, Joel Uckelman
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License (LGPL) as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, copies are available
* at http://www.opensource.org.
*/
package VASSAL.build.module.map;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Stroke;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import javax.swing.JComponent;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import VASSAL.build.Buildable;
import VASSAL.build.GameModule;
import VASSAL.build.module.Map;
import VASSAL.counters.ColoredBorder;
import VASSAL.counters.Deck;
import VASSAL.counters.DeckVisitor;
import VASSAL.counters.EventFilter;
import VASSAL.counters.GamePiece;
import VASSAL.counters.Immobilized;
import VASSAL.counters.KeyBuffer;
import VASSAL.counters.PieceFinder;
import VASSAL.counters.PieceVisitorDispatcher;
import VASSAL.counters.Properties;
import VASSAL.counters.Stack;
import VASSAL.tools.swing.SwingUtils;
/**
* This component listens for mouse clicks on a map and draws the selection
* rectangle.
*
* If the user clicks on a {@link GamePiece}, that piece is added to the
* {@link KeyBuffer}. {@link #draw(Graphics, Map)} is responsible for
* drawing the mouse selection rectangle, and
* {@link #mouseDragged(MouseEvent)} is responsible for triggering repaint
* events as the selection rectangle is moved.
*
* @see Map#addLocalMouseListener
*/
public class KeyBufferer extends MouseAdapter implements Buildable, MouseMotionListener, Drawable {
protected Map map;
protected Rectangle selection;
protected Point anchor;
protected Color color = Color.black;
protected int thickness = 3;
protected GamePiece bandSelectPiece = null;
private enum BandSelectType {
NONE,
NORMAL,
SPECIAL
}
@Override
public void addTo(Buildable b) {
map = (Map) b;
map.addLocalMouseListenerFirst(this);
map.getView().addMouseMotionListener(this);
map.addDrawComponent(this);
}
@Override
public void add(Buildable b) {
}
@Override
public Element getBuildElement(Document doc) {
return doc.createElement(getClass().getName());
}
@Override
public void build(Element e) {
}
@Override
public void mousePressed(MouseEvent e) {
if (e.isConsumed()) {
return;
}
final KeyBuffer kbuf = KeyBuffer.getBuffer();
GamePiece p = map.findPiece(e.getPoint(), PieceFinder.PIECE_IN_STACK);
// Don't clear the buffer until we find the clicked-on piece
// Because selecting a piece affects its visibility
EventFilter filter = null;
BandSelectType bandSelect = BandSelectType.NONE;
if (p != null) {
filter = (EventFilter) p.getProperty(Properties.SELECT_EVENT_FILTER);
if (SwingUtils.isVanillaLeftButtonDown(e) && Boolean.TRUE.equals(p.getProperty(Properties.NON_MOVABLE))) {
// Don't "eat" band-selects if unit found is non-movable
bandSelect = BandSelectType.SPECIAL;
}
}
boolean ignoreEvent = filter != null && filter.rejectEvent(e);
if (p != null && !ignoreEvent) {
boolean movingStacksPickupUnits = (Boolean) GameModule.getGameModule().getPrefs().getValue(Map.MOVING_STACKS_PICKUP_UNITS);
if (!kbuf.contains(p)) {
if (!e.isShiftDown() && !SwingUtils.isSelectionToggle(e)) {
kbuf.clear();
}
// RFE 1629255 - If the top piece of an unexpanded stack is left-clicked
// while not selected, then select all of the pieces in the stack
if (movingStacksPickupUnits ||
p.getParent() == null ||
p.getParent().isExpanded() ||
SwingUtils.isSelectionToggle(e) ||
Boolean.TRUE.equals(p.getProperty(Properties.SELECTED))) {
kbuf.add(p);
}
else {
Stack s = p.getParent();
s.asList().forEach(gamePiece -> KeyBuffer.getBuffer().add(gamePiece));
}
// End RFE 1629255
}
else {
// RFE 1659481 Ctrl-click deselects clicked units
if (SwingUtils.isSelectionToggle(e) && Boolean.TRUE.equals(p.getProperty(Properties.SELECTED))) {
Stack s = p.getParent();
if (s == null) {
kbuf.remove(p);
}
else if (!s.isExpanded()) {
s.asList().forEach(gamePiece -> KeyBuffer.getBuffer().remove(gamePiece));
}
else {
kbuf.remove(p);
}
}
// End RFE 1659481
}
final GamePiece to_front = p.getParent() != null ? p.getParent() : p;
map.getPieceCollection().moveToFront(to_front);
}
else {
bandSelect = BandSelectType.NORMAL; //BR// Allowed to band-select
}
if (bandSelect != BandSelectType.NONE) {
bandSelectPiece = null;
if (!e.isShiftDown() && !SwingUtils.isSelectionToggle(e)) { // No deselect if shift key down
kbuf.clear();
//BR// This section allows band-select to be attempted from non-moving pieces w/o preventing click-to-select from working
if (bandSelect == BandSelectType.SPECIAL && p != null && !ignoreEvent) {
kbuf.add(p);
bandSelectPiece = p;
}
}
anchor = map.mapToComponent(e.getPoint());
selection = new Rectangle(anchor.x, anchor.y, 0, 0);
if (map.getHighlighter() instanceof ColoredBorder) {
ColoredBorder b = (ColoredBorder) map.getHighlighter();
color = b.getColor();
thickness = b.getThickness();
}
}
}
@Override
public void mouseReleased(MouseEvent e) {
if (selection == null) {
return;
}
PieceVisitorDispatcher d = createDragSelector(
!SwingUtils.isSelectionToggle(e), e.isAltDown(), map.componentToMap(selection)
);
// If it was a legit band-select drag (not just a click), our special case
// only applies if piece is allowed to be band-selected
if (bandSelectPiece != null) {
final EventFilter bandFilter = (EventFilter) bandSelectPiece.getProperty(Properties.BAND_SELECT_EVENT_FILTER);
final boolean pieceAllowedToBeBandSelected = bandFilter != null && !e.isAltDown() && bandFilter instanceof Immobilized.UseAlt;
if (pieceAllowedToBeBandSelected) {
final Point finish = map.mapToComponent(e.getPoint());
// Open to suggestions about a better way to distinguish "click" from
// "lasso" (not that Vassal doesn't already suck immensely at
// click-vs-drag threshhold). FWIW, this "works".
final boolean isLasso = finish.distance(anchor) >= 10;
if (isLasso) {
bandSelectPiece = null;
}
}
}
// RFE 1659481 Don't clear the entire selection buffer if either shift
// or control is down - we select/deselect lassoed counters instead
if (bandSelectPiece == null && !e.isShiftDown() && !SwingUtils.isSelectionToggle(e)) {
KeyBuffer.getBuffer().clear();
}
map.apply(d);
repaintSelectionRect();
selection = null;
}
/**
* This PieceVisitorDispatcher determines what to do with pieces on the
* map when the player finished dragging a rectangle to select pieces
*
* @return
*/
protected PieceVisitorDispatcher createDragSelector(
boolean selecting,
boolean altDown,
Rectangle mapsel) {
return new PieceVisitorDispatcher(
new KBDeckVisitor(selecting, altDown, mapsel)
);
}
public class KBDeckVisitor implements DeckVisitor {
boolean selecting = false;
boolean altDown = false;
Rectangle mapsel;
public KBDeckVisitor(boolean b, boolean c, Rectangle ms) {
selecting = b;
altDown = c;
mapsel = ms;
}
@Override
public Object visitDeck(Deck d) {
return null;
}
@Override
public Object visitStack(Stack s) {
if (s.topPiece() != null) {
final KeyBuffer kbuf = KeyBuffer.getBuffer();
if (s instanceof Deck) {
s.asList().forEach(kbuf::remove); // Clear any deck *members* out of the KeyBuffer.
return null;
}
if (s.isExpanded()) {
Point[] pos = new Point[s.getPieceCount()];
map.getStackMetrics().getContents(s, pos, null, null, s.getPosition().x, s.getPosition().y);
for (int i = 0; i < pos.length; ++i) {
if (mapsel.contains(pos[i])) {
if (selecting) {
kbuf.add(s.getPieceAt(i));
}
else {
kbuf.remove(s.getPieceAt(i));
}
}
}
}
else if (mapsel.contains(s.getPosition())) {
s.asList().forEach(selecting ? kbuf::add : kbuf::remove);
}
}
return null;
}
// Handle non-stacked units, including Does Not Stack units
// Does Not Stack units deselect normally once selected
@Override
public Object visitDefault(GamePiece p) {
Stack s = p.getParent();
if (s != null && s instanceof Deck) {
// Clear any deck *members* out of the KeyBuffer.
// (yes, members of decks can be does-not-stack)
KeyBuffer.getBuffer().remove(p);
return null;
}
if (mapsel.contains(p.getPosition()) && !Boolean.TRUE.equals(p.getProperty(Properties.INVISIBLE_TO_ME))) {
if (selecting) {
final EventFilter filter = (EventFilter) p.getProperty(Properties.SELECT_EVENT_FILTER);
final EventFilter bandFilter = (EventFilter) p.getProperty(Properties.BAND_SELECT_EVENT_FILTER);
final boolean altSelect = (altDown && filter instanceof Immobilized.UseAlt);
final boolean altBand = (altDown && bandFilter instanceof Immobilized.UseAlt);
if ((filter == null || altSelect) && ((bandFilter == null) || altBand)) { //BR// Band-select filtering support
KeyBuffer.getBuffer().add(p);
}
}
else {
KeyBuffer.getBuffer().remove(p);
}
}
return null;
}
}
protected void repaintSelectionRect() {
/*
* Repaint strategy: There is no reason to repaint the interior of
* the selection rectangle, as we didn't paint over it in the first
* place. Instead, we repaint only the four (slender) rectangles
* which the stroke of the selection rectangle filled. We have to
* call a repaint on both the old selection rectangle and the new
* in order to prevent drawing artifacts. The KeyBuffer handles
* repainting pieces which have been (de)selected, so we don't
* worry about those.
*
* Area drawn:
* selection.x
* |
* ___________________
* selection.y __ |__|__|_____|__|__| __
* |__|__|_____|__|__| |
* | | | | | | |
* | | | | | | | selection.height
* |__|__|_____|__|__| |
* ~thickness/2 --{ |__|__|_____|__|__| __|
* ~thickness/2 --{ |__|__|_____|__|__|
*
* |___________|
* selection.width
*/
final int ht = thickness / 2 + thickness % 2;
final int ht2 = 2*ht;
final JComponent view = map.getView();
// left
view.repaint(selection.x - ht,
selection.y - ht,
ht2,
selection.height + ht2);
// right
view.repaint(selection.x + selection.width - ht,
selection.y - ht,
ht2,
selection.height + ht2);
// top
view.repaint(selection.x - ht,
selection.y - ht,
selection.width + ht2,
ht2);
// bottom
view.repaint(selection.x - ht,
selection.y + selection.width - ht,
selection.width + ht2,
ht2);
}
/**
* Sets the new location of the selection rectangle.
*/
@Override
public void mouseDragged(MouseEvent e) {
if (selection == null || !SwingUtils.isVanillaLeftButtonDown(e)) {
return;
}
repaintSelectionRect();
final int ex = e.getX();
final int ey = e.getY();
selection.x = Math.min(ex, anchor.x);
selection.y = Math.min(ey, anchor.y);
selection.width = Math.abs(ex - anchor.x);
selection.height = Math.abs(ey - anchor.y);
repaintSelectionRect();
}
@Override
public void mouseMoved(MouseEvent e) {
}
@Override
public void draw(Graphics g, Map map) {
if (selection == null) {
return;
}
final Graphics2D g2d = (Graphics2D) g;
final double os_scale = g2d.getDeviceConfiguration().getDefaultTransform().getScaleX();
final Stroke str = g2d.getStroke();
g2d.setStroke(new BasicStroke((float)(thickness * os_scale)));
g2d.setColor(color);
g2d.drawRect(
(int)(selection.x * os_scale),
(int)(selection.y * os_scale),
(int)(selection.width * os_scale),
(int)(selection.height * os_scale)
);
g2d.setStroke(str);
}
@Override
public boolean drawAboveCounters() {
return true;
}
}
|
Re-save KeyBufferer? Why? We Don't Know
|
vassal-app/src/main/java/VASSAL/build/module/map/KeyBufferer.java
|
Re-save KeyBufferer? Why? We Don't Know
|
<ide><path>assal-app/src/main/java/VASSAL/build/module/map/KeyBufferer.java
<ide> import VASSAL.tools.swing.SwingUtils;
<ide>
<ide> /**
<del> * This component listens for mouse clicks on a map and draws the selection
<add> * This component listens for mouse clicks on a map and draws the selection
<ide> * rectangle.
<ide> *
<ide> * If the user clicks on a {@link GamePiece}, that piece is added to the
|
|
JavaScript
|
mit
|
10064edd680c2033017d9d17b22745ac7b2da254
| 0 |
ferhat-taslicukur/iyzipay-node,iyzico/iyzipay-node
|
'use strict';
var crypto = require('crypto');
var utils = module.exports = {
apiMethod: {
RETRIEVE: 'retrieve',
CREATE: 'create',
DELETE: 'delete',
UPDATE: 'update'
},
generateAuthorizationHeader: function (iyziWsHeaderName, apiKey, separator, secretKey, body, randomString) {
return iyziWsHeaderName + ' ' + apiKey + separator + utils.generateHash(apiKey, randomString, secretKey, body);
},
generateHash: function (apiKey, randomString, secretKey, body) {
var shaSum = crypto.createHash('sha1');
shaSum.update(apiKey + randomString + secretKey + body, 'utf8');
return shaSum.digest('base64');
},
generateRequestString: function (request) {
var isArray = Array.isArray(request);
var requestString = '[';
for (var i in request) {
var val = request[i];
// Eliminate number keys of array elements
if (!isArray) {
requestString += i + '=';
}
if (typeof val === 'object') {
requestString += utils.generateRequestString(val);
} else {
requestString += val;
}
requestString += isArray ? ', ' : ',';
}
requestString = requestString.slice(0, (isArray ? -2 : -1));
requestString += ']';
return requestString;
},
generateRandomString: function (size) {
return process.hrtime()[0] + Math.random().toString(size).slice(2);
},
formatPrice: function (price) {
if (('number' !== typeof price && 'string' !== typeof price) || !isFinite(price)) {
return price;
}
var resultPrice = parseFloat(price).toString();
if (-1 === resultPrice.indexOf('.')) {
return resultPrice + '.0';
}
return resultPrice;
}
};
|
lib/utils.js
|
'use strict';
var crypto = require('crypto');
var utils = module.exports = {
apiMethod: {
RETRIEVE: 'retrieve',
CREATE: 'create',
DELETE: 'delete',
UPDATE: 'update'
},
generateAuthorizationHeader: function (iyziWsHeaderName, apiKey, separator, secretKey, body, randomString) {
return iyziWsHeaderName + ' ' + apiKey + separator + utils.generateHash(apiKey, randomString, secretKey, body);
},
generateHash: function (apiKey, randomString, secretKey, body) {
var shaSum = crypto.createHash('sha1');
shaSum.update(apiKey + randomString + secretKey + body, 'utf8');
return shaSum.digest('base64');
},
generateRequestString: function (request) {
var isArray = Array.isArray(request);
var requestString = '[';
for (var i in request) {
var val = request[i];
// Eliminate number keys of array elements
if (!isArray) {
requestString += i + '=';
}
if (typeof val === 'object') {
requestString += utils.generateRequestString(val);
} else {
requestString += val;
}
requestString += isArray ? ', ' : ',';
}
requestString = requestString.slice(0, (isArray ? -2 : -1));
requestString += ']';
return requestString;
},
generateRandomString: function (size) {
return process.hrtime()[0] + Math.random().toString(size).slice(2);
},
formatPrice: function (price) {
if (('number' !== typeof price && 'string' !== typeof price) || ! isFinite(price)) {
// throw new Error('Given price is not a valid number. (' + price + ')');
return price; // to pass previous written tests.
}
var resultPrice = parseFloat(price).toString();
if (-1 === resultPrice.indexOf('.')) {
return resultPrice + '.0';
}
return resultPrice;
}
};
|
code formatted
|
lib/utils.js
|
code formatted
|
<ide><path>ib/utils.js
<ide> return process.hrtime()[0] + Math.random().toString(size).slice(2);
<ide> },
<ide> formatPrice: function (price) {
<del> if (('number' !== typeof price && 'string' !== typeof price) || ! isFinite(price)) {
<del> // throw new Error('Given price is not a valid number. (' + price + ')');
<del> return price; // to pass previous written tests.
<add> if (('number' !== typeof price && 'string' !== typeof price) || !isFinite(price)) {
<add> return price;
<ide> }
<del>
<ide> var resultPrice = parseFloat(price).toString();
<del>
<ide> if (-1 === resultPrice.indexOf('.')) {
<ide> return resultPrice + '.0';
<ide> }
<del>
<ide> return resultPrice;
<ide> }
<ide> };
|
|
Java
|
apache-2.0
|
d709df68f7b509e3f6a6252e732096387f405d8a
| 0 |
pkdevbox/gerrit,thinkernel/gerrit,bootstraponline-archive/gerrit-mirror,gcoders/gerrit,Saulis/gerrit,GerritCodeReview/gerrit,jackminicloud/test,quyixia/gerrit,anminhsu/gerrit,bpollack/gerrit,qtproject/qtqa-gerrit,anminhsu/gerrit,Distrotech/gerrit,WANdisco/gerrit,MerritCR/merrit,renchaorevee/gerrit,thinkernel/gerrit,netroby/gerrit,bpollack/gerrit,pkdevbox/gerrit,pkdevbox/gerrit,gerrit-review/gerrit,GerritCodeReview/gerrit,anminhsu/gerrit,Overruler/gerrit,midnightradio/gerrit,Seinlin/gerrit,jackminicloud/test,supriyantomaftuh/gerrit,TonyChai24/test,Team-OctOS/host_gerrit,dwhipstock/gerrit,midnightradio/gerrit,dwhipstock/gerrit,gcoders/gerrit,midnightradio/gerrit,joshuawilson/merrit,Overruler/gerrit,renchaorevee/gerrit,Team-OctOS/host_gerrit,gcoders/gerrit,supriyantomaftuh/gerrit,jackminicloud/test,netroby/gerrit,pkdevbox/gerrit,bootstraponline-archive/gerrit-mirror,supriyantomaftuh/gerrit,Saulis/gerrit,Distrotech/gerrit,anminhsu/gerrit,Seinlin/gerrit,MerritCR/merrit,anminhsu/gerrit,Saulis/gerrit,hdost/gerrit,bootstraponline-archive/gerrit-mirror,GerritCodeReview/gerrit,WANdisco/gerrit,Overruler/gerrit,qtproject/qtqa-gerrit,gerrit-review/gerrit,GerritCodeReview/gerrit,thesamet/gerrit,thesamet/gerrit,Team-OctOS/host_gerrit,dwhipstock/gerrit,midnightradio/gerrit,joshuawilson/merrit,qtproject/qtqa-gerrit,thinkernel/gerrit,dwhipstock/gerrit,netroby/gerrit,pkdevbox/gerrit,thinkernel/gerrit,gerrit-review/gerrit,renchaorevee/gerrit,hdost/gerrit,Saulis/gerrit,Saulis/gerrit,bpollack/gerrit,qtproject/qtqa-gerrit,Saulis/gerrit,dwhipstock/gerrit,renchaorevee/gerrit,gcoders/gerrit,Seinlin/gerrit,hdost/gerrit,thesamet/gerrit,quyixia/gerrit,thesamet/gerrit,thinkernel/gerrit,netroby/gerrit,TonyChai24/test,gerrit-review/gerrit,supriyantomaftuh/gerrit,Seinlin/gerrit,Team-OctOS/host_gerrit,WANdisco/gerrit,WANdisco/gerrit,bootstraponline-archive/gerrit-mirror,Distrotech/gerrit,netroby/gerrit,jackminicloud/test,jackminicloud/test,Seinlin/gerrit,renchaorevee/gerrit,hdost/gerrit,GerritCodeReview/gerrit,quyixia/gerrit,dwhipstock/gerrit,GerritCodeReview/gerrit,hdost/gerrit,Overruler/gerrit,Distrotech/gerrit,netroby/gerrit,Seinlin/gerrit,joshuawilson/merrit,GerritCodeReview/gerrit,gerrit-review/gerrit,renchaorevee/gerrit,Distrotech/gerrit,dwhipstock/gerrit,anminhsu/gerrit,MerritCR/merrit,quyixia/gerrit,TonyChai24/test,WANdisco/gerrit,thesamet/gerrit,qtproject/qtqa-gerrit,qtproject/qtqa-gerrit,bootstraponline-archive/gerrit-mirror,supriyantomaftuh/gerrit,midnightradio/gerrit,bpollack/gerrit,supriyantomaftuh/gerrit,Team-OctOS/host_gerrit,gcoders/gerrit,MerritCR/merrit,bpollack/gerrit,quyixia/gerrit,hdost/gerrit,Seinlin/gerrit,thesamet/gerrit,joshuawilson/merrit,TonyChai24/test,pkdevbox/gerrit,MerritCR/merrit,Team-OctOS/host_gerrit,MerritCR/merrit,thinkernel/gerrit,Team-OctOS/host_gerrit,gerrit-review/gerrit,hdost/gerrit,pkdevbox/gerrit,quyixia/gerrit,bpollack/gerrit,gcoders/gerrit,joshuawilson/merrit,GerritCodeReview/gerrit,jackminicloud/test,quyixia/gerrit,midnightradio/gerrit,gerrit-review/gerrit,thesamet/gerrit,thinkernel/gerrit,supriyantomaftuh/gerrit,Overruler/gerrit,MerritCR/merrit,Distrotech/gerrit,WANdisco/gerrit,TonyChai24/test,WANdisco/gerrit,Distrotech/gerrit,bootstraponline-archive/gerrit-mirror,netroby/gerrit,TonyChai24/test,jackminicloud/test,MerritCR/merrit,anminhsu/gerrit,joshuawilson/merrit,renchaorevee/gerrit,joshuawilson/merrit,TonyChai24/test,Overruler/gerrit,gcoders/gerrit,qtproject/qtqa-gerrit,joshuawilson/merrit
|
// Copyright (C) 2012 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.gerrit.server.change;
import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.gerrit.extensions.restapi.AuthException;
import com.google.gerrit.extensions.restapi.ResourceNotFoundException;
import com.google.gerrit.extensions.restapi.Response;
import com.google.gerrit.extensions.restapi.RestModifyView;
import com.google.gerrit.reviewdb.client.Account;
import com.google.gerrit.reviewdb.client.Change;
import com.google.gerrit.reviewdb.client.ChangeMessage;
import com.google.gerrit.reviewdb.client.PatchSetApproval;
import com.google.gerrit.reviewdb.server.ReviewDb;
import com.google.gerrit.server.ChangeUtil;
import com.google.gerrit.server.IdentifiedUser;
import com.google.gerrit.server.change.DeleteReviewer.Input;
import com.google.gerrit.server.index.ChangeIndexer;
import com.google.gerrit.server.project.ChangeControl;
import com.google.gerrit.server.util.TimeUtil;
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
import com.google.inject.Provider;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
public class DeleteReviewer implements RestModifyView<ReviewerResource, Input> {
public static class Input {
}
private final Provider<ReviewDb> dbProvider;
private final ChangeIndexer indexer;
private final IdentifiedUser.GenericFactory userFactory;
@Inject
DeleteReviewer(Provider<ReviewDb> dbProvider, ChangeIndexer indexer,
IdentifiedUser.GenericFactory userFactory) {
this.dbProvider = dbProvider;
this.indexer = indexer;
this.userFactory = userFactory;
}
@Override
public Response<?> apply(ReviewerResource rsrc, Input input)
throws AuthException, ResourceNotFoundException, OrmException,
IOException {
ChangeControl control = rsrc.getControl();
Change.Id changeId = rsrc.getChange().getId();
ReviewDb db = dbProvider.get();
StringBuilder msg = new StringBuilder();
db.changes().beginTransaction(changeId);
try {
List<PatchSetApproval> del = Lists.newArrayList();
for (PatchSetApproval a : approvals(db, rsrc)) {
if (control.canRemoveReviewer(a)) {
del.add(a);
if (a.getValue() != 0) {
if (msg.length() == 0) {
msg.append("Removed the following approvals:\n\n");
}
msg.append("* ")
.append(a.getLabel()).append(formatLabelValue(a.getValue()))
.append(" by ").append(userFactory.create(a.getAccountId()).getNameEmail())
.append("\n");
}
} else {
throw new AuthException("delete not permitted");
}
}
if (del.isEmpty()) {
throw new ResourceNotFoundException();
}
ChangeUtil.bumpRowVersionNotLastUpdatedOn(rsrc.getChange().getId(), db);
db.patchSetApprovals().delete(del);
if (msg.length() > 0) {
ChangeMessage changeMessage =
new ChangeMessage(new ChangeMessage.Key(rsrc.getChange().getId(),
ChangeUtil.messageUUID(db)),
((IdentifiedUser) control.getCurrentUser()).getAccountId(),
TimeUtil.nowTs(), rsrc.getChange().currentPatchSetId());
changeMessage.setMessage(msg.toString());
db.changeMessages().insert(Collections.singleton(changeMessage));
}
db.commit();
} finally {
db.rollback();
}
indexer.index(rsrc.getChange());
return Response.none();
}
private static String formatLabelValue(short value) {
if (value > 0) {
return "+" + value;
} else {
return Short.toString(value);
}
}
private Iterable<PatchSetApproval> approvals(ReviewDb db,
ReviewerResource rsrc) throws OrmException {
final Account.Id user = rsrc.getUser().getAccountId();
return Iterables.filter(
db.patchSetApprovals().byChange(rsrc.getChange().getId()),
new Predicate<PatchSetApproval>() {
@Override
public boolean apply(PatchSetApproval input) {
return user.equals(input.getAccountId());
}
});
}
}
|
gerrit-server/src/main/java/com/google/gerrit/server/change/DeleteReviewer.java
|
// Copyright (C) 2012 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.gerrit.server.change;
import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.gerrit.extensions.restapi.AuthException;
import com.google.gerrit.extensions.restapi.ResourceNotFoundException;
import com.google.gerrit.extensions.restapi.Response;
import com.google.gerrit.extensions.restapi.RestModifyView;
import com.google.gerrit.reviewdb.client.Account;
import com.google.gerrit.reviewdb.client.Change;
import com.google.gerrit.reviewdb.client.PatchSetApproval;
import com.google.gerrit.reviewdb.server.ReviewDb;
import com.google.gerrit.server.ChangeUtil;
import com.google.gerrit.server.change.DeleteReviewer.Input;
import com.google.gerrit.server.index.ChangeIndexer;
import com.google.gerrit.server.project.ChangeControl;
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
import com.google.inject.Provider;
import java.io.IOException;
import java.util.List;
public class DeleteReviewer implements RestModifyView<ReviewerResource, Input> {
public static class Input {
}
private final Provider<ReviewDb> dbProvider;
private final ChangeIndexer indexer;
@Inject
DeleteReviewer(Provider<ReviewDb> dbProvider, ChangeIndexer indexer) {
this.dbProvider = dbProvider;
this.indexer = indexer;
}
@Override
public Response<?> apply(ReviewerResource rsrc, Input input)
throws AuthException, ResourceNotFoundException, OrmException,
IOException {
ChangeControl control = rsrc.getControl();
Change.Id changeId = rsrc.getChange().getId();
ReviewDb db = dbProvider.get();
db.changes().beginTransaction(changeId);
try {
List<PatchSetApproval> del = Lists.newArrayList();
for (PatchSetApproval a : approvals(db, rsrc)) {
if (control.canRemoveReviewer(a)) {
del.add(a);
} else {
throw new AuthException("delete not permitted");
}
}
if (del.isEmpty()) {
throw new ResourceNotFoundException();
}
ChangeUtil.bumpRowVersionNotLastUpdatedOn(rsrc.getChange().getId(), db);
db.patchSetApprovals().delete(del);
db.commit();
} finally {
db.rollback();
}
indexer.index(rsrc.getChange());
return Response.none();
}
private Iterable<PatchSetApproval> approvals(ReviewDb db,
ReviewerResource rsrc) throws OrmException {
final Account.Id user = rsrc.getUser().getAccountId();
return Iterables.filter(
db.patchSetApprovals().byChange(rsrc.getChange().getId()),
new Predicate<PatchSetApproval>() {
@Override
public boolean apply(PatchSetApproval input) {
return user.equals(input.getAccountId());
}
});
}
}
|
Write a change message when approvals are removed
If the approvals of a reviewer are removed (e.g. by the project owner)
this is now recorded as a change message so that it later can be seen
who removed the approvals.
This change only affects removing reviewers on ChangeScreen2. If a
reviewer is removed on the old change screen there is still no
message.
Bug: issue 1300
Change-Id: Ibe95d1835e065d6c142edbf53e2ce483c4dc4889
Signed-off-by: Edwin Kempin <[email protected]>
|
gerrit-server/src/main/java/com/google/gerrit/server/change/DeleteReviewer.java
|
Write a change message when approvals are removed
|
<ide><path>errit-server/src/main/java/com/google/gerrit/server/change/DeleteReviewer.java
<ide> import com.google.gerrit.extensions.restapi.RestModifyView;
<ide> import com.google.gerrit.reviewdb.client.Account;
<ide> import com.google.gerrit.reviewdb.client.Change;
<add>import com.google.gerrit.reviewdb.client.ChangeMessage;
<ide> import com.google.gerrit.reviewdb.client.PatchSetApproval;
<ide> import com.google.gerrit.reviewdb.server.ReviewDb;
<ide> import com.google.gerrit.server.ChangeUtil;
<add>import com.google.gerrit.server.IdentifiedUser;
<ide> import com.google.gerrit.server.change.DeleteReviewer.Input;
<ide> import com.google.gerrit.server.index.ChangeIndexer;
<ide> import com.google.gerrit.server.project.ChangeControl;
<add>import com.google.gerrit.server.util.TimeUtil;
<ide> import com.google.gwtorm.server.OrmException;
<ide> import com.google.inject.Inject;
<ide> import com.google.inject.Provider;
<ide>
<ide> import java.io.IOException;
<add>import java.util.Collections;
<ide> import java.util.List;
<ide>
<ide> public class DeleteReviewer implements RestModifyView<ReviewerResource, Input> {
<ide>
<ide> private final Provider<ReviewDb> dbProvider;
<ide> private final ChangeIndexer indexer;
<add> private final IdentifiedUser.GenericFactory userFactory;
<ide>
<ide> @Inject
<del> DeleteReviewer(Provider<ReviewDb> dbProvider, ChangeIndexer indexer) {
<add> DeleteReviewer(Provider<ReviewDb> dbProvider, ChangeIndexer indexer,
<add> IdentifiedUser.GenericFactory userFactory) {
<ide> this.dbProvider = dbProvider;
<ide> this.indexer = indexer;
<add> this.userFactory = userFactory;
<ide> }
<ide>
<ide> @Override
<ide> ChangeControl control = rsrc.getControl();
<ide> Change.Id changeId = rsrc.getChange().getId();
<ide> ReviewDb db = dbProvider.get();
<add> StringBuilder msg = new StringBuilder();
<ide> db.changes().beginTransaction(changeId);
<ide> try {
<ide> List<PatchSetApproval> del = Lists.newArrayList();
<ide> for (PatchSetApproval a : approvals(db, rsrc)) {
<ide> if (control.canRemoveReviewer(a)) {
<ide> del.add(a);
<add> if (a.getValue() != 0) {
<add> if (msg.length() == 0) {
<add> msg.append("Removed the following approvals:\n\n");
<add> }
<add> msg.append("* ")
<add> .append(a.getLabel()).append(formatLabelValue(a.getValue()))
<add> .append(" by ").append(userFactory.create(a.getAccountId()).getNameEmail())
<add> .append("\n");
<add> }
<ide> } else {
<ide> throw new AuthException("delete not permitted");
<ide> }
<ide> }
<ide> ChangeUtil.bumpRowVersionNotLastUpdatedOn(rsrc.getChange().getId(), db);
<ide> db.patchSetApprovals().delete(del);
<add>
<add> if (msg.length() > 0) {
<add> ChangeMessage changeMessage =
<add> new ChangeMessage(new ChangeMessage.Key(rsrc.getChange().getId(),
<add> ChangeUtil.messageUUID(db)),
<add> ((IdentifiedUser) control.getCurrentUser()).getAccountId(),
<add> TimeUtil.nowTs(), rsrc.getChange().currentPatchSetId());
<add> changeMessage.setMessage(msg.toString());
<add> db.changeMessages().insert(Collections.singleton(changeMessage));
<add> }
<add>
<ide> db.commit();
<ide> } finally {
<ide> db.rollback();
<ide> }
<ide> indexer.index(rsrc.getChange());
<ide> return Response.none();
<add> }
<add>
<add> private static String formatLabelValue(short value) {
<add> if (value > 0) {
<add> return "+" + value;
<add> } else {
<add> return Short.toString(value);
<add> }
<ide> }
<ide>
<ide> private Iterable<PatchSetApproval> approvals(ReviewDb db,
|
|
Java
|
apache-2.0
|
d9b699c81ff17154bbae097ce3255c3792ae0b06
| 0 |
jitsi/jitsi-videobridge,jitsi/jitsi-videobridge,jitsi/jitsi-videobridge,gpolitis/jitsi-videobridge,gpolitis/jitsi-videobridge,jitsi/jitsi-videobridge,gpolitis/jitsi-videobridge,jitsi/jitsi-videobridge,jitsi/jitsi-videobridge,jitsi/jitsi-videobridge
|
/*
* Copyright @ 2018 Atlassian Pty Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jitsi.videobridge;
import kotlin.*;
import net.java.sip.communicator.impl.protocol.jabber.extensions.jingle.*;
import org.ice4j.socket.*;
import org.jetbrains.annotations.*;
import org.jitsi.nlj.*;
import org.jitsi.nlj.dtls.*;
import org.jitsi.nlj.transform.*;
import org.jitsi.nlj.transform.node.*;
import org.jitsi.nlj.transform.node.incoming.*;
import org.jitsi.nlj.transform.node.outgoing.*;
import org.jitsi.nlj.util.*;
import org.jitsi.rtp.*;
import org.jitsi.util.*;
import org.jitsi.videobridge.util.*;
import java.io.*;
import java.net.*;
import java.nio.*;
import java.util.*;
import java.util.function.*;
/**
* @author Brian Baldino
* @author Boris Grozev
*/
public class IceDtlsTransportManager
extends IceUdpTransportManager
{
/**
* The {@link Logger} used by the {@link IceDtlsTransportManager} class to
* print debug information. Note that instances should use {@link #logger}
* instead.
*/
private static final Logger classLogger
= Logger.getLogger(IceDtlsTransportManager.class);
/**
* A predicate which is true for DTLS packets. See
* https://tools.ietf.org/html/rfc7983#section-7
*/
private static final Predicate<Packet> DTLS_PREDICATE
= packet -> {
int b = packet.getBuffer().get(0) & 0xFF;
return (20 <= b && b <= 63);
};
/**
* A predicate which is true for all non-DTLS packets. See
* https://tools.ietf.org/html/rfc7983#section-7
*/
private static final Predicate<Packet> NON_DTLS_PREDICATE
= DTLS_PREDICATE.negate();
private final Logger logger;
private DtlsClientStack dtlsStack = new DtlsClientStack();
private DtlsReceiver dtlsReceiver = new DtlsReceiver(dtlsStack);
private DtlsSender dtlsSender = new DtlsSender(dtlsStack);
private List<Runnable> dtlsConnectedSubscribers = new ArrayList<>();
private final PacketInfoQueue outgoingPacketQueue;
private final Endpoint endpoint;
private SocketSenderNode packetSender = new SocketSenderNode();
private Node incomingPipelineRoot = createIncomingPipeline();
private Node outgoingDtlsPipelineRoot = createOutgoingDtlsPipeline();
private Node outgoingSrtpPipelineRoot = createOutgoingSrtpPipeline();
protected boolean dtlsHandshakeComplete = false;
private boolean iceConnectedProcessed = false;
public IceDtlsTransportManager(Endpoint endpoint)
throws IOException
{
super(endpoint, true);
this.endpoint = endpoint;
this.logger
= Logger.getLogger(
classLogger,
endpoint.getConference().getLogger());
outgoingPacketQueue
= new PacketInfoQueue(
"TM-outgoing-" + endpoint.getID(),
TaskPools.IO_POOL,
this::handleOutgoingPacket);
}
/**
* Reads the DTLS fingerprints from, the transport extension before
* passing it over to the ICE transport manager.
* @param transportPacketExtension
*/
@Override
public void startConnectivityEstablishment(
IceUdpTransportPacketExtension transportPacketExtension)
{
// TODO(boris): read the Setup attribute and support acting like the
// DTLS server.
List<DtlsFingerprintPacketExtension> fingerprintExtensions
= transportPacketExtension.getChildExtensionsOfType(
DtlsFingerprintPacketExtension.class);
Map<String, String> remoteFingerprints = new HashMap<>();
fingerprintExtensions.forEach(fingerprintExtension -> {
if (fingerprintExtension.getHash() != null
&& fingerprintExtension.getFingerprint() != null)
{
remoteFingerprints.put(
fingerprintExtension.getHash(),
fingerprintExtension.getFingerprint());
}
else
{
logger.warn(logPrefix +
"Ignoring empty DtlsFingerprint extension: "
+ transportPacketExtension.toXML());
}
});
// Don't pass an empty list to the stack in order to avoid wiping
// certificates that were contained in a previous request.
if (!remoteFingerprints.isEmpty())
{
dtlsStack.setRemoteFingerprints(remoteFingerprints);
}
super.startConnectivityEstablishment(transportPacketExtension);
}
@Override
public boolean isConnected()
{
// TODO: do we consider this TM connected when ICE completes, or when
// ICE and DTLS both complete?
return super.isConnected();
}
/**
* {@inheritDoc}
*/
@Override
protected void describe(IceUdpTransportPacketExtension pe)
{
super.describe(pe);
// Describe dtls
DtlsFingerprintPacketExtension fingerprintPE
= pe.getFirstChildOfType(DtlsFingerprintPacketExtension.class);
if (fingerprintPE == null)
{
fingerprintPE = new DtlsFingerprintPacketExtension();
pe.addChildExtension(fingerprintPE);
}
fingerprintPE.setFingerprint(dtlsStack.getLocalFingerprint());
fingerprintPE.setHash(dtlsStack.getLocalFingerprintHashFunction());
// TODO: don't we only support ACTIVE right now?
fingerprintPE.setSetup("ACTPASS");
}
public void onDtlsHandshakeComplete(Runnable handler)
{
if (dtlsHandshakeComplete)
{
handler.run();
}
else
{
dtlsConnectedSubscribers.add(handler);
}
}
private Node createIncomingPipeline()
{
// do we need a builder if we're using a single node?
PipelineBuilder builder = new PipelineBuilder();
DemuxerNode dtlsSrtpDemuxer = new ExclusivePathDemuxer("DTLS/SRTP");
// DTLS path
ConditionalPacketPath dtlsPath
= new ConditionalPacketPath("DTLS path");
dtlsPath.setPredicate(DTLS_PREDICATE);
PipelineBuilder dtlsPipelineBuilder = new PipelineBuilder();
dtlsPipelineBuilder.node(dtlsReceiver);
dtlsPipelineBuilder.simpleNode(
"sctp app packet handler",
packets -> {
packets.forEach(endpoint::dtlsAppPacketReceived);
return Collections.emptyList();
});
dtlsPath.setPath(dtlsPipelineBuilder.build());
dtlsSrtpDemuxer.addPacketPath(dtlsPath);
// SRTP path
ConditionalPacketPath srtpPath = new ConditionalPacketPath("SRTP path");
// We pass anything non-DTLS to the SRTP stack. This is fine, as STUN
// packets have already been filtered out in ice4j, and we don't expect
// anything else. It might be nice to log a warning if we see anything
// outside the RTP range (see RFC7983), but adding a separate packet
// path here might be expensive.
srtpPath.setPredicate(NON_DTLS_PREDICATE);
PipelineBuilder srtpPipelineBuilder = new PipelineBuilder();
srtpPipelineBuilder.simpleNode(
"SRTP path",
packets -> {
packets.forEach(endpoint::srtpPacketReceived);
return Collections.emptyList();
});
srtpPath.setPath(srtpPipelineBuilder.build());
dtlsSrtpDemuxer.addPacketPath(srtpPath);
builder.node(dtlsSrtpDemuxer);
return builder.build();
}
private Node createOutgoingDtlsPipeline()
{
PipelineBuilder builder = new PipelineBuilder();
builder.node(dtlsSender);
builder.node(packetSender);
return builder.build();
}
private Node createOutgoingSrtpPipeline()
{
PipelineBuilder builder = new PipelineBuilder();
builder.node(packetSender);
return builder.build();
}
public void sendDtlsData(PacketInfo packet)
{
outgoingDtlsPipelineRoot.processPackets(Collections.singletonList(packet));
}
private boolean handleOutgoingPacket(PacketInfo packetInfo)
{
outgoingSrtpPipelineRoot.processPackets(Collections.singletonList(packetInfo));
return true;
}
/**
* Read packets from the given socket and process them in the incoming pipeline
* @param socket the socket to read from
*/
private void installIncomingPacketReader(DatagramSocket socket)
{
//TODO(brian): this does a bit more than just read from the iceSocket
// (does a bit of processing for each packet) but I think it's little
// enough (it'll only be a bit of the DTLS path) that running it in the
// IO pool is fine
TaskPools.IO_POOL.submit(() -> {
byte[] buf = new byte[1500];
while (!closed)
{
DatagramPacket p = new DatagramPacket(buf, 0, 1500);
try
{
socket.receive(p);
ByteBuffer packetBuf = ByteBuffer.allocate(p.getLength());
packetBuf.put(ByteBuffer.wrap(buf, 0, p.getLength())).flip();
Packet pkt = new UnparsedPacket(packetBuf);
PacketInfo pktInfo = new PacketInfo(pkt);
pktInfo.setReceivedTime(System.currentTimeMillis());
incomingPipelineRoot
.processPackets(Collections.singletonList(pktInfo));
}
catch (SocketClosedException e)
{
logger.info(logPrefix + "Socket closed, stopping reader.");
break;
}
catch (IOException e)
{
logger.warn(logPrefix + "Stopping reader: ", e);
break;
}
}
});
}
@Override
protected void onIceConnected()
{
if (iceConnectedProcessed)
{
return;
}
iceConnectedProcessed = true;
DatagramSocket socket = iceComponent.getSocket();
endpoint.setOutgoingSrtpPacketHandler(
packets -> packets.forEach(outgoingPacketQueue::add));
// Socket reader thread. Read from the underlying iceSocket and pass
// to the incoming module chain.
installIncomingPacketReader(socket);
dtlsStack.onHandshakeComplete((tlsContext) -> {
dtlsHandshakeComplete = true;
logger.info(logPrefix +
"DTLS handshake complete. Got SRTP profile " +
dtlsStack.getChosenSrtpProtectionProfile());
//TODO: emit this as part of the dtls handshake complete event?
endpoint.setSrtpInformation(
dtlsStack.getChosenSrtpProtectionProfile(), tlsContext);
dtlsConnectedSubscribers.forEach(Runnable::run);
return Unit.INSTANCE;
});
packetSender.socket = socket;
logger.info(logPrefix + "Starting DTLS.");
TaskPools.IO_POOL.submit(() -> {
try
{
dtlsStack.connect();
}
catch (Exception e)
{
logger.error(logPrefix +
"Error during DTLS negotiation: " + e.toString() +
", closing this transport manager");
close();
}
});
}
class SocketSenderNode extends Node
{
public DatagramSocket socket = null;
SocketSenderNode()
{
super("Socket sender");
}
@Override
protected void doProcessPackets(@NotNull List<PacketInfo> pkts)
{
if (socket != null)
{
pkts.forEach(pktInfo -> {
try
{
socket.send(
new DatagramPacket(
pktInfo.getPacket().getBuffer().array(),
0,
pktInfo.getPacket().getBuffer().limit()));
}
catch (IOException e)
{
logger.error(logPrefix +
"Error sending packet: " + e.toString());
throw new RuntimeException(e);
}
});
}
}
}
}
|
src/main/java/org/jitsi/videobridge/IceDtlsTransportManager.java
|
/*
* Copyright @ 2018 Atlassian Pty Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jitsi.videobridge;
import kotlin.*;
import net.java.sip.communicator.impl.protocol.jabber.extensions.jingle.*;
import org.ice4j.socket.*;
import org.jetbrains.annotations.*;
import org.jitsi.nlj.*;
import org.jitsi.nlj.dtls.*;
import org.jitsi.nlj.transform.*;
import org.jitsi.nlj.transform.node.*;
import org.jitsi.nlj.transform.node.incoming.*;
import org.jitsi.nlj.transform.node.outgoing.*;
import org.jitsi.nlj.util.*;
import org.jitsi.rtp.*;
import org.jitsi.util.*;
import org.jitsi.videobridge.util.*;
import java.io.*;
import java.net.*;
import java.nio.*;
import java.util.*;
import java.util.function.*;
/**
* @author Brian Baldino
* @author Boris Grozev
*/
public class IceDtlsTransportManager
extends IceUdpTransportManager
{
/**
* The {@link Logger} used by the {@link IceDtlsTransportManager} class to
* print debug information. Note that instances should use {@link #logger}
* instead.
*/
private static final Logger classLogger
= Logger.getLogger(IceDtlsTransportManager.class);
/**
* A predicate which is true for DTLS packets. See
* https://tools.ietf.org/html/rfc7983#section-7
*/
private static final Predicate<Packet> DTLS_PREDICATE
= packet -> {
int b = packet.getBuffer().get(0) & 0xFF;
return (20 <= b && b <= 63);
};
/**
* A predicate which is true for all non-DTLS packets. See
* https://tools.ietf.org/html/rfc7983#section-7
*/
private static final Predicate<Packet> NON_DTLS_PREDICATE
= DTLS_PREDICATE.negate();
private final Logger logger;
private DtlsClientStack dtlsStack = new DtlsClientStack();
private DtlsReceiver dtlsReceiver = new DtlsReceiver(dtlsStack);
private DtlsSender dtlsSender = new DtlsSender(dtlsStack);
private List<Runnable> dtlsConnectedSubscribers = new ArrayList<>();
private final PacketInfoQueue outgoingPacketQueue;
private final Endpoint endpoint;
private SocketSenderNode packetSender = new SocketSenderNode();
private Node incomingPipelineRoot = createIncomingPipeline();
private Node outgoingDtlsPipelineRoot = createOutgoingDtlsPipeline();
private Node outgoingSrtpPipelineRoot = createOutgoingSrtpPipeline();
protected boolean dtlsHandshakeComplete = false;
private boolean iceConnectedProcessed = false;
public IceDtlsTransportManager(Endpoint endpoint)
throws IOException
{
super(endpoint, true);
this.endpoint = endpoint;
this.logger
= Logger.getLogger(
classLogger,
endpoint.getConference().getLogger());
outgoingPacketQueue
= new PacketInfoQueue(
"TM-outgoing-" + endpoint.getID(),
TaskPools.IO_POOL,
this::handleOutgoingPacket);
}
/**
* Reads the DTLS fingerprints from, the transport extension before
* passing it over to the ICE transport manager.
* @param transportPacketExtension
*/
@Override
public void startConnectivityEstablishment(
IceUdpTransportPacketExtension transportPacketExtension)
{
// TODO(boris): read the Setup attribute and support acting like the
// DTLS server.
List<DtlsFingerprintPacketExtension> fingerprintExtensions
= transportPacketExtension.getChildExtensionsOfType(
DtlsFingerprintPacketExtension.class);
Map<String, String> remoteFingerprints = new HashMap<>();
fingerprintExtensions.forEach(fingerprintExtension -> {
if (fingerprintExtension.getHash() != null
&& fingerprintExtension.getFingerprint() != null)
{
remoteFingerprints.put(
fingerprintExtension.getHash(),
fingerprintExtension.getFingerprint());
}
else
{
logger.warn(logPrefix +
"Ignoring empty DtlsFingerprint extension: "
+ transportPacketExtension.toXML());
}
});
// Don't pass an empty list to the stack in order to avoid wiping
// certificates that were contained in a previous request.
if (!remoteFingerprints.isEmpty())
{
dtlsStack.setRemoteFingerprints(remoteFingerprints);
}
super.startConnectivityEstablishment(transportPacketExtension);
}
@Override
public boolean isConnected()
{
// TODO: do we consider this TM connected when ICE completes, or when
// ICE and DTLS both complete?
return super.isConnected();
}
/**
* {@inheritDoc}
*/
@Override
protected void describe(IceUdpTransportPacketExtension pe)
{
super.describe(pe);
// Describe dtls
DtlsFingerprintPacketExtension fingerprintPE
= pe.getFirstChildOfType(DtlsFingerprintPacketExtension.class);
if (fingerprintPE == null)
{
fingerprintPE = new DtlsFingerprintPacketExtension();
pe.addChildExtension(fingerprintPE);
}
fingerprintPE.setFingerprint(dtlsStack.getLocalFingerprint());
fingerprintPE.setHash(dtlsStack.getLocalFingerprintHashFunction());
// TODO: don't we only support ACTIVE right now?
fingerprintPE.setSetup("ACTPASS");
}
public void onDtlsHandshakeComplete(Runnable handler)
{
if (dtlsHandshakeComplete)
{
handler.run();
}
else
{
dtlsConnectedSubscribers.add(handler);
}
}
private Node createIncomingPipeline()
{
// do we need a builder if we're using a single node?
PipelineBuilder builder = new PipelineBuilder();
DemuxerNode dtlsSrtpDemuxer = new DemuxerNode("DTLS/SRTP");
// DTLS path
ConditionalPacketPath dtlsPath
= new ConditionalPacketPath("DTLS path");
dtlsPath.setPredicate(DTLS_PREDICATE);
PipelineBuilder dtlsPipelineBuilder = new PipelineBuilder();
dtlsPipelineBuilder.node(dtlsReceiver);
dtlsPipelineBuilder.simpleNode(
"sctp app packet handler",
packets -> {
packets.forEach(endpoint::dtlsAppPacketReceived);
return Collections.emptyList();
});
dtlsPath.setPath(dtlsPipelineBuilder.build());
dtlsSrtpDemuxer.addPacketPath(dtlsPath);
// SRTP path
ConditionalPacketPath srtpPath = new ConditionalPacketPath("SRTP path");
// We pass anything non-DTLS to the SRTP stack. This is fine, as STUN
// packets have already been filtered out in ice4j, and we don't expect
// anything else. It might be nice to log a warning if we see anything
// outside the RTP range (see RFC7983), but adding a separate packet
// path here might be expensive.
srtpPath.setPredicate(NON_DTLS_PREDICATE);
PipelineBuilder srtpPipelineBuilder = new PipelineBuilder();
srtpPipelineBuilder.simpleNode(
"SRTP path",
packets -> {
packets.forEach(endpoint::srtpPacketReceived);
return Collections.emptyList();
});
srtpPath.setPath(srtpPipelineBuilder.build());
dtlsSrtpDemuxer.addPacketPath(srtpPath);
builder.node(dtlsSrtpDemuxer);
return builder.build();
}
private Node createOutgoingDtlsPipeline()
{
PipelineBuilder builder = new PipelineBuilder();
builder.node(dtlsSender);
builder.node(packetSender);
return builder.build();
}
private Node createOutgoingSrtpPipeline()
{
PipelineBuilder builder = new PipelineBuilder();
builder.node(packetSender);
return builder.build();
}
public void sendDtlsData(PacketInfo packet)
{
outgoingDtlsPipelineRoot.processPackets(Collections.singletonList(packet));
}
private boolean handleOutgoingPacket(PacketInfo packetInfo)
{
outgoingSrtpPipelineRoot.processPackets(Collections.singletonList(packetInfo));
return true;
}
/**
* Read packets from the given socket and process them in the incoming pipeline
* @param socket the socket to read from
*/
private void installIncomingPacketReader(DatagramSocket socket)
{
//TODO(brian): this does a bit more than just read from the iceSocket
// (does a bit of processing for each packet) but I think it's little
// enough (it'll only be a bit of the DTLS path) that running it in the
// IO pool is fine
TaskPools.IO_POOL.submit(() -> {
byte[] buf = new byte[1500];
while (!closed)
{
DatagramPacket p = new DatagramPacket(buf, 0, 1500);
try
{
socket.receive(p);
ByteBuffer packetBuf = ByteBuffer.allocate(p.getLength());
packetBuf.put(ByteBuffer.wrap(buf, 0, p.getLength())).flip();
Packet pkt = new UnparsedPacket(packetBuf);
PacketInfo pktInfo = new PacketInfo(pkt);
pktInfo.setReceivedTime(System.currentTimeMillis());
incomingPipelineRoot
.processPackets(Collections.singletonList(pktInfo));
}
catch (SocketClosedException e)
{
logger.info(logPrefix + "Socket closed, stopping reader.");
break;
}
catch (IOException e)
{
logger.warn(logPrefix + "Stopping reader: ", e);
break;
}
}
});
}
@Override
protected void onIceConnected()
{
if (iceConnectedProcessed)
{
return;
}
iceConnectedProcessed = true;
DatagramSocket socket = iceComponent.getSocket();
endpoint.setOutgoingSrtpPacketHandler(
packets -> packets.forEach(outgoingPacketQueue::add));
// Socket reader thread. Read from the underlying iceSocket and pass
// to the incoming module chain.
installIncomingPacketReader(socket);
dtlsStack.onHandshakeComplete((tlsContext) -> {
dtlsHandshakeComplete = true;
logger.info(logPrefix +
"DTLS handshake complete. Got SRTP profile " +
dtlsStack.getChosenSrtpProtectionProfile());
//TODO: emit this as part of the dtls handshake complete event?
endpoint.setSrtpInformation(
dtlsStack.getChosenSrtpProtectionProfile(), tlsContext);
dtlsConnectedSubscribers.forEach(Runnable::run);
return Unit.INSTANCE;
});
packetSender.socket = socket;
logger.info(logPrefix + "Starting DTLS.");
TaskPools.IO_POOL.submit(() -> {
try
{
dtlsStack.connect();
}
catch (Exception e)
{
logger.error(logPrefix +
"Error during DTLS negotiation: " + e.toString() +
", closing this transport manager");
close();
}
});
}
class SocketSenderNode extends Node
{
public DatagramSocket socket = null;
SocketSenderNode()
{
super("Socket sender");
}
@Override
protected void doProcessPackets(@NotNull List<PacketInfo> pkts)
{
if (socket != null)
{
pkts.forEach(pktInfo -> {
try
{
socket.send(
new DatagramPacket(
pktInfo.getPacket().getBuffer().array(),
0,
pktInfo.getPacket().getBuffer().limit()));
}
catch (IOException e)
{
logger.error(logPrefix +
"Error sending packet: " + e.toString());
throw new RuntimeException(e);
}
});
}
}
}
}
|
use exclusivepathdemuxer
|
src/main/java/org/jitsi/videobridge/IceDtlsTransportManager.java
|
use exclusivepathdemuxer
|
<ide><path>rc/main/java/org/jitsi/videobridge/IceDtlsTransportManager.java
<ide> // do we need a builder if we're using a single node?
<ide> PipelineBuilder builder = new PipelineBuilder();
<ide>
<del> DemuxerNode dtlsSrtpDemuxer = new DemuxerNode("DTLS/SRTP");
<add> DemuxerNode dtlsSrtpDemuxer = new ExclusivePathDemuxer("DTLS/SRTP");
<ide> // DTLS path
<ide> ConditionalPacketPath dtlsPath
<ide> = new ConditionalPacketPath("DTLS path");
|
|
JavaScript
|
bsd-3-clause
|
5f40300fc48f993e588a82f682f81e3b067fa5ea
| 0 |
APIs-guru/raml-to-swagger
|
'use strict';
var assert = require('assert');
var URI = require('urijs');
var _ = require('lodash');
var jsonCompat = require('json-schema-compatibility');
var HttpStatus = require('http-status-codes').getStatusText;
var jp = require('jsonpath');
exports.convert = function (raml) {
//FIXME:
//console.log(raml.documentation);
var swagger = {
swagger: '2.0',
info: {
title: raml.title,
version: raml.version,
},
securityDefinitions: parseSecuritySchemes(raml.securitySchemes),
paths: parseResources(raml.resources),
definitions: parseSchemas(raml.schemas)
};
parseBaseUri(raml, swagger);
jp.apply(swagger.paths, '$..*.schema' , function (schema) {
if (!schema || _.isEmpty(schema))
return;
var result = schema;
_.each(swagger.definitions, function (definition, name) {
if (!_.isEqual(schema, definition))
return;
result = { $ref: '#/definitions/' + name};
});
return result;
});
if ('mediaType' in raml) {
swagger.consumes = [raml.mediaType];
swagger.produces = [raml.mediaType];
}
//TODO: refactor into function
//Fix incorrect arrays in RAML
//TODO: add description
_.each(swagger.definitions, function (schema, name) {
if (!schema || schema.type !== 'array' || !_.isUndefined(schema.items))
return;
if (_.isArray(schema[name]) && _.isPlainObject(schema[name][0])) {
schema.items = schema[name][0];
delete schema[name];
}
});
return swagger;
};
function parseBaseUri(raml, swagger) {
var baseUri = raml.baseUri;
if (!baseUri)
return;
var baseUriParameters = _.omit(raml.baseUriParameters, 'version');
baseUri = baseUri.replace(/{version}/g, raml.version);
baseUri = URI(baseUri);
// Split out part path segments starting from first template param
var match = /^(.*?)(\/[^\/]*?{.*)?$/.exec(baseUri.path());
baseUri.path(match[1]);
var pathPrefix = match[2];
//Don't support other URI templates right now.
assert(baseUri.href().indexOf('{') == -1);
assert(!('uriParameters' in raml));
_.assign(swagger, {
host: baseUri.host(),
basePath: '/' + baseUri.pathname().replace(/^\/|\/$/, ''),
schemes: parseProtocols(raml.protocols) || [baseUri.scheme()]
});
if (!pathPrefix)
return;
pathPrefix = pathPrefix.replace(/\/$/, '');
baseUriParameters = parseParametersList(baseUriParameters);
swagger.paths = _.mapKeys(swagger.paths, function (value, key) {
value.parameters = _.concat(baseUriParameters, value.parameters);
return pathPrefix + key;
});
}
function parseSecuritySchemes(ramlSecuritySchemes) {
var srSecurityDefinitions = {};
_.each(ramlSecuritySchemes, function (ramlSecurityArray) {
_.each(ramlSecurityArray, function (ramlSecurityObj, name) {
assert(ramlSecurityObj.type);
//Swagger 2.0 doesn't support Oauth 1.0 so just skip it.
//FIXME: add warning
if (ramlSecurityObj.type === 'OAuth 1.0')
return;
var srType = {
'OAuth 2.0': 'oauth2',
'Basic Authentication': 'basic',
}[ramlSecurityObj.type];
assert(srType);
var srSecurity = {
type: srType,
description: ramlSecurityObj.description,
};
if (srType !== 'oauth2') {
srSecurityDefinitions[name] = srSecurity;
return;
}
var ramlSettings = ramlSecurityObj.settings;
_.assign(srSecurity, {
authorizationUrl: ramlSettings.authorizationUri,
tokenUrl: ramlSettings.accessTokenUri,
scopes: _.transform(ramlSettings.scopes, function (result, name) {
result[name] = '';
}, {})
});
var ramlFlows = ramlSettings.authorizationGrants;
_.each(ramlFlows, function (ramlFlow) {
var srFlowSecurity = _.clone(srSecurity);
var srFlow = srFlowSecurity.flow = {
'code': 'accessCode',
'token': 'implicit',
'owner': 'password',
'credentials': 'application'
}[ramlFlow];
if (srFlow === 'password' || srFlow === 'application')
delete srFlowSecurity.authorizationUrl;
if (srFlow === 'implicit')
delete srFlowSecurity.tokenUrl;
var fullName = name;
if (_.size(ramlFlows) > 1)
fullName = name + '_' + srFlowSecurity.flow;
srSecurityDefinitions[fullName] = srFlowSecurity;
});
});
});
return srSecurityDefinitions;
}
function parseSchemas(ramlSchemas) {
return _.reduce(ramlSchemas, function (definitions, ramlSchemasMap) {
return _.assignWith(definitions, ramlSchemasMap, function (dummy, ramlSchema) {
return convertSchema(ramlSchema);
});
}, {});
}
function parseProtocols(ramlProtocols) {
return _.map(ramlProtocols, function (str) {
return str.toLowerCase();
});
}
function parseResources(ramlResources, srPathParameters) {
var srPaths = {};
_.each(ramlResources, function (ramlResource) {
//FIXME: convert or create warning
//assert(!('displayName' in ramlResource));
//assert(!('description' in ramlResource && ramlResource.description !== ''));
assert(!('baseUriParameters' in ramlResource));
var resourceName = ramlResource.relativeUri;
assert(resourceName);
var srResourceParameters = (srPathParameters || []).concat(
parseParametersList(ramlResource.uriParameters, 'path'));
var srMethods = parseMethodList(ramlResource.methods, srResourceParameters);
if (!_.isEmpty(srMethods))
srPaths[resourceName] = srMethods;
var srSubPaths = parseResources(ramlResource.resources, srResourceParameters);
_.each(srSubPaths, function (subResource, subResourceName) {
srPaths[resourceName + subResourceName] = subResource;
});
});
return srPaths;
}
function parseMethodList(ramlMethods, srPathParameters) {
var srMethods = {};
_.each(ramlMethods, function (ramlMethod) {
var srMethod = parseMethod(ramlMethod);
if (!_.isEmpty(srPathParameters))
srMethod.parameters = srPathParameters.concat(srMethod.parameters);
srMethods[ramlMethod.method] = srMethod;
});
return srMethods;
}
function parseMethod(ramlMethod) {
//FIXME:
//assert(!('protocols' in data));
//assert(!('securedBy' in data));
var srMethod = {
description: ramlMethod.description,
};
var srParameters = parseParametersList(ramlMethod.queryParameters, 'query');
srParameters = srParameters.concat(
parseParametersList(ramlMethod.headers, 'header'));
if (!_.isEmpty(srParameters))
srMethod.parameters = srParameters;
parseBody(ramlMethod.body, srMethod);
parseResponses(ramlMethod, srMethod);
return srMethod;
}
function parseResponses(ramlMethod, srMethod) {
var ramlResponces = ramlMethod.responses;
if (_.isEmpty(ramlResponces)) {
return {
200: { description: HttpStatus(200) }
};
}
srMethod.responses = {};
_.each(ramlResponces, function (ramlResponce, httpCode) {
var defaultDescription = HttpStatus(parseInt(httpCode));
var srResponse = srMethod.responses[httpCode] = {
description: _.get(ramlResponce, 'description') || defaultDescription
};
if (!_.has(ramlResponce, 'body'))
return;
var jsonMIME = 'application/json';
var produces = _.without(_.keys(ramlResponce.body), jsonMIME);
//TODO: types could have examples.
if (!_.isEmpty(produces))
srMethod.produces = produces;
var jsonSchema = _.get(ramlResponce.body, jsonMIME);
if (!_.isUndefined(jsonSchema)) {
//TODO:
//assert(!_.has(jsonSchema, 'example'));
srResponse.schema = convertSchema(_.get(jsonSchema, 'schema'));
}
});
}
function parseParametersList(params, inValue) {
assert(_.isUndefined(params) || _.isPlainObject(params));
return _.map(params, function (value, key) {
//FIXME:
//assert(!_.has(value, 'example'));
//assert(!_.has(value, 'displayName'));
assert(_.has(value, 'type') &&
['date', 'string', 'number', 'integer', 'boolean'].indexOf(value.type) !== -1);
var srParameter = {
type: value.type,
enum: value.enum,
default: value.default,
maximum: value.maximum,
minimum: value.minimum,
maxLength: value.maxLength,
minLength: value.minLength,
pattern: value.pattern
};
if (srParameter.type === 'date') {
srParameter.type = 'string';
srParameter.format = 'date';
}
if (value.repeat === true) {
assert(['query', 'formData'].indexOf(inValue) !== -1);
srParameter = {
type: 'array',
items: srParameter,
collectionFormat: 'multi'
}
}
_.assign(srParameter, {
name: key,
in: inValue,
description: value.description,
required: value.required
});
return srParameter;
});
}
function parseBody(ramlBody, srMethod) {
if (!ramlBody)
return;
var keys = _.keys(ramlBody)
assert(!_.has(keys, 'application/x-www-form-urlencoded'));
assert(!_.has(keys, 'multipart/form-data'));
//TODO: All parsers of RAML MUST be able to interpret ... and XML Schema
var jsonMIME = 'application/json';
var consumes = _.without(keys, jsonMIME);
//TODO: types could have examples.
if (!_.isEmpty(consumes))
srMethod.consumes = consumes;
if (_.indexOf(keys, jsonMIME) === -1)
return;
if (_.isUndefined(srMethod.parameters))
srMethod.parameters = [];
srMethod.parameters.push({
//FIXME: check if name is used;
name: 'body',
in: 'body',
required: true,
//TODO: copy example
schema: convertSchema(_.get(ramlBody[jsonMIME], 'schema'))
});
}
function convertSchema(schema) {
if (_.isUndefined(schema))
return;
assert(_.isString(schema));
try {
var schema = JSON.parse(schema);
}
catch (e) {
return undefined;
}
delete schema.id;
delete schema.$schema;
delete schema[''];
//Convertion is safe even for Draft4 schemas, so convert everything
schema = jsonCompat.v4(schema);
//Add '#/definitions/' prefix to all internal refs
jp.apply(schema, '$..*["$ref"]' , function (ref) {
return '#/definitions/' + ref;
});
//Fixes for common mistakes in RAML 0.8
// Fix case where 'list' keyword used instead of 'items':
// {
// "type": "array",
// "list": [{
// ...
// ]}
// }
if (schema.type === 'array' && !_.isUndefined(schema.list)) {
assert(_.isUndefined(schema.items));
assert(_.size(schema.list) === 1);
assert(_.isPlainObject(schema.list[0]));
schema.items = schema.list[0];
delete schema.list;
}
// Fix case when instead of 'additionalProperties' schema put in following wrappers:
// {
// "type": "object",
// "": [{
// ...
// }]
// }
// or
// {
// "type": "object",
// "properties": {
// "": [{
// ...
// }]
// }
// }
// Or simular case for arrays, when same wrapper used instead of 'items'.
_.each(jp.nodes(schema, '$..*[""]'), function(result) {
var value = result.value;
var path = result.path;
if (!_.isArray(value) || _.size(value) !== 1 || !_.isPlainObject(value[0]))
return;
path = _.dropRight(path);
var parent = jp.value(schema, jp.stringify(path));
delete parent[''];
if (_.isEmpty(parent) && ['properties', 'items'].indexOf(_.last(path)) !== -1) {
parent = jp.value(schema, jp.stringify(_.dropRight(path)));
delete parent.properties;
}
switch (parent.type) {
case 'object':
parent.additionalProperties = value[0];
break;
case 'array':
parent.items = value[0];
break;
default:
assert(false);
}
});
// Fix case when arrays definition wrapped with array, like that:
// [{
// "type": "array",
// ...
// }]
jp.apply(schema, '$..properties[?(@.length === 1 && @[0].type === "array")]', function(schema) {
return schema[0];
});
// Fix incorrect array properties, like that:
// {
// "properties": {
// "type": array,
// "<name>": [{
// ...
// }]
// }
// }
_.each(jp.nodes(schema, '$..properties[?(@.length === 1)]'), function(result) {
var name = _.last(result.path);
var parent = jp.value(schema, jp.stringify(_.dropRight(result.path)));
if (parent['type'] === 'array') {
parent[name] = {type: 'array', items: result.value[0]}
delete parent['type'];
}
});
// Fix case then 'items' value is empty or single element array.
function unwrapItems(schema) {
if (_.isEmpty(schema.items))
schema.items = {};
else {
assert(_.isPlainObject(schema.items[0]));
schema.items = schema.items[0];
}
return schema;
}
jp.apply(schema, '$..*[?(@.type === "array" && @.items && @.items.length <= 1)]', unwrapItems);
//JSON Path can't apply to root object so do this manually
if (schema.type === 'array' && _.isArray(schema.items) && _.size(schema.items) <= 1)
unwrapItems(schema);
return schema;
}
|
src/index.js
|
'use strict';
var assert = require('assert');
var URI = require('urijs');
var _ = require('lodash');
var jsonCompat = require('json-schema-compatibility');
var HttpStatus = require('http-status-codes').getStatusText;
var jp = require('jsonpath');
exports.convert = function (raml) {
//FIXME:
//console.log(raml.documentation);
var swagger = _.assign({
swagger: '2.0',
info: {
title: raml.title,
version: raml.version,
},
securityDefinitions: parseSecuritySchemes(raml.securitySchemes),
paths: parseResources(raml.resources),
definitions: parseSchemas(raml.schemas)
}, parseBaseUri(raml));
jp.apply(swagger.paths, '$..*.schema' , function (schema) {
if (!schema || _.isEmpty(schema))
return;
var result = schema;
_.each(swagger.definitions, function (definition, name) {
if (!_.isEqual(schema, definition))
return;
result = { $ref: '#/definitions/' + name};
});
return result;
});
if ('mediaType' in raml) {
swagger.consumes = [raml.mediaType];
swagger.produces = [raml.mediaType];
}
//TODO: refactor into function
//Fix incorrect arrays in RAML
//TODO: add description
_.each(swagger.definitions, function (schema, name) {
if (!schema || schema.type !== 'array' || !_.isUndefined(schema.items))
return;
if (_.isArray(schema[name]) && _.isPlainObject(schema[name][0])) {
schema.items = schema[name][0];
delete schema[name];
}
});
return swagger;
};
function parseBaseUri(raml) {
var baseUri = raml.baseUri;
if (!baseUri)
return {};
baseUri = baseUri.replace(/{version}/g, raml.version);
//Don't support other URI templates right now.
assert(baseUri.indexOf('{') == -1);
baseUri = URI(baseUri);
assert(!('baseUriParameters' in raml) ||
_.isEqual(_.keys(raml.baseUriParameters), ['version']));
assert(!('uriParameters' in raml));
return {
host: baseUri.host(),
basePath: '/' + baseUri.pathname().replace(/^\/|\/$/, ''),
schemes: parseProtocols(raml.protocols) || [baseUri.scheme()]
};
}
function parseSecuritySchemes(ramlSecuritySchemes) {
var srSecurityDefinitions = {};
_.each(ramlSecuritySchemes, function (ramlSecurityArray) {
_.each(ramlSecurityArray, function (ramlSecurityObj, name) {
assert(ramlSecurityObj.type);
//Swagger 2.0 doesn't support Oauth 1.0 so just skip it.
//FIXME: add warning
if (ramlSecurityObj.type === 'OAuth 1.0')
return;
var srType = {
'OAuth 2.0': 'oauth2',
'Basic Authentication': 'basic',
}[ramlSecurityObj.type];
assert(srType);
var srSecurity = {
type: srType,
description: ramlSecurityObj.description,
};
if (srType !== 'oauth2') {
srSecurityDefinitions[name] = srSecurity;
return;
}
var ramlSettings = ramlSecurityObj.settings;
_.assign(srSecurity, {
authorizationUrl: ramlSettings.authorizationUri,
tokenUrl: ramlSettings.accessTokenUri,
scopes: _.transform(ramlSettings.scopes, function (result, name) {
result[name] = '';
}, {})
});
var ramlFlows = ramlSettings.authorizationGrants;
_.each(ramlFlows, function (ramlFlow) {
var srFlowSecurity = _.clone(srSecurity);
var srFlow = srFlowSecurity.flow = {
'code': 'accessCode',
'token': 'implicit',
'owner': 'password',
'credentials': 'application'
}[ramlFlow];
if (srFlow === 'password' || srFlow === 'application')
delete srFlowSecurity.authorizationUrl;
if (srFlow === 'implicit')
delete srFlowSecurity.tokenUrl;
var fullName = name;
if (_.size(ramlFlows) > 1)
fullName = name + '_' + srFlowSecurity.flow;
srSecurityDefinitions[fullName] = srFlowSecurity;
});
});
});
return srSecurityDefinitions;
}
function parseSchemas(ramlSchemas) {
return _.reduce(ramlSchemas, function (definitions, ramlSchemasMap) {
return _.assignWith(definitions, ramlSchemasMap, function (dummy, ramlSchema) {
return convertSchema(ramlSchema);
});
}, {});
}
function parseProtocols(ramlProtocols) {
return _.map(ramlProtocols, function (str) {
return str.toLowerCase();
});
}
function parseResources(ramlResources, srPathParameters) {
var srPaths = {};
_.each(ramlResources, function (ramlResource) {
//FIXME: convert or create warning
//assert(!('displayName' in ramlResource));
//assert(!('description' in ramlResource && ramlResource.description !== ''));
assert(!('baseUriParameters' in ramlResource));
var resourceName = ramlResource.relativeUri;
assert(resourceName);
var srResourceParameters = (srPathParameters || []).concat(
parseParametersList(ramlResource.uriParameters, 'path'));
var srMethods = parseMethodList(ramlResource.methods, srResourceParameters);
if (!_.isEmpty(srMethods))
srPaths[resourceName] = srMethods;
var srSubPaths = parseResources(ramlResource.resources, srResourceParameters);
_.each(srSubPaths, function (subResource, subResourceName) {
srPaths[resourceName + subResourceName] = subResource;
});
});
return srPaths;
}
function parseMethodList(ramlMethods, srPathParameters) {
var srMethods = {};
_.each(ramlMethods, function (ramlMethod) {
var srMethod = parseMethod(ramlMethod);
if (!_.isEmpty(srPathParameters))
srMethod.parameters = srPathParameters.concat(srMethod.parameters);
srMethods[ramlMethod.method] = srMethod;
});
return srMethods;
}
function parseMethod(ramlMethod) {
//FIXME:
//assert(!('protocols' in data));
//assert(!('securedBy' in data));
var srMethod = {
description: ramlMethod.description,
};
var srParameters = parseParametersList(ramlMethod.queryParameters, 'query');
srParameters = srParameters.concat(
parseParametersList(ramlMethod.headers, 'header'));
if (!_.isEmpty(srParameters))
srMethod.parameters = srParameters;
parseBody(ramlMethod.body, srMethod);
parseResponses(ramlMethod, srMethod);
return srMethod;
}
function parseResponses(ramlMethod, srMethod) {
var ramlResponces = ramlMethod.responses;
if (_.isEmpty(ramlResponces)) {
return {
200: { description: HttpStatus(200) }
};
}
srMethod.responses = {};
_.each(ramlResponces, function (ramlResponce, httpCode) {
var defaultDescription = HttpStatus(parseInt(httpCode));
var srResponse = srMethod.responses[httpCode] = {
description: _.get(ramlResponce, 'description') || defaultDescription
};
if (!_.has(ramlResponce, 'body'))
return;
var jsonMIME = 'application/json';
var produces = _.without(_.keys(ramlResponce.body), jsonMIME);
//TODO: types could have examples.
if (!_.isEmpty(produces))
srMethod.produces = produces;
var jsonSchema = _.get(ramlResponce.body, jsonMIME);
if (!_.isUndefined(jsonSchema)) {
//TODO:
//assert(!_.has(jsonSchema, 'example'));
srResponse.schema = convertSchema(_.get(jsonSchema, 'schema'));
}
});
}
function parseParametersList(params, inValue) {
assert(_.isUndefined(params) || _.isPlainObject(params));
return _.map(params, function (value, key) {
//FIXME:
//assert(!_.has(value, 'example'));
//assert(!_.has(value, 'displayName'));
assert(_.has(value, 'type') &&
['date', 'string', 'number', 'integer', 'boolean'].indexOf(value.type) !== -1);
var srParameter = {
type: value.type,
enum: value.enum,
default: value.default,
maximum: value.maximum,
minimum: value.minimum,
maxLength: value.maxLength,
minLength: value.minLength,
pattern: value.pattern
};
if (srParameter.type === 'date') {
srParameter.type = 'string';
srParameter.format = 'date';
}
if (value.repeat === true) {
assert(['query', 'formData'].indexOf(inValue) !== -1);
srParameter = {
type: 'array',
items: srParameter,
collectionFormat: 'multi'
}
}
_.assign(srParameter, {
name: key,
in: inValue,
description: value.description,
required: value.required
});
return srParameter;
});
}
function parseBody(ramlBody, srMethod) {
if (!ramlBody)
return;
var keys = _.keys(ramlBody)
assert(!_.has(keys, 'application/x-www-form-urlencoded'));
assert(!_.has(keys, 'multipart/form-data'));
//TODO: All parsers of RAML MUST be able to interpret ... and XML Schema
var jsonMIME = 'application/json';
var consumes = _.without(keys, jsonMIME);
//TODO: types could have examples.
if (!_.isEmpty(consumes))
srMethod.consumes = consumes;
if (_.indexOf(keys, jsonMIME) === -1)
return;
if (_.isUndefined(srMethod.parameters))
srMethod.parameters = [];
srMethod.parameters.push({
//FIXME: check if name is used;
name: 'body',
in: 'body',
required: true,
//TODO: copy example
schema: convertSchema(_.get(ramlBody[jsonMIME], 'schema'))
});
}
function convertSchema(schema) {
if (_.isUndefined(schema))
return;
assert(_.isString(schema));
try {
var schema = JSON.parse(schema);
}
catch (e) {
return undefined;
}
delete schema.id;
delete schema.$schema;
delete schema[''];
//Convertion is safe even for Draft4 schemas, so convert everything
schema = jsonCompat.v4(schema);
//Add '#/definitions/' prefix to all internal refs
jp.apply(schema, '$..*["$ref"]' , function (ref) {
return '#/definitions/' + ref;
});
//Fixes for common mistakes in RAML 0.8
// Fix case where 'list' keyword used instead of 'items':
// {
// "type": "array",
// "list": [{
// ...
// ]}
// }
if (schema.type === 'array' && !_.isUndefined(schema.list)) {
assert(_.isUndefined(schema.items));
assert(_.size(schema.list) === 1);
assert(_.isPlainObject(schema.list[0]));
schema.items = schema.list[0];
delete schema.list;
}
// Fix case when instead of 'additionalProperties' schema put in following wrappers:
// {
// "type": "object",
// "": [{
// ...
// }]
// }
// or
// {
// "type": "object",
// "properties": {
// "": [{
// ...
// }]
// }
// }
// Or simular case for arrays, when same wrapper used instead of 'items'.
_.each(jp.nodes(schema, '$..*[""]'), function(result) {
var value = result.value;
var path = result.path;
if (!_.isArray(value) || _.size(value) !== 1 || !_.isPlainObject(value[0]))
return;
path = _.dropRight(path);
var parent = jp.value(schema, jp.stringify(path));
delete parent[''];
if (_.isEmpty(parent) && ['properties', 'items'].indexOf(_.last(path)) !== -1) {
parent = jp.value(schema, jp.stringify(_.dropRight(path)));
delete parent.properties;
}
switch (parent.type) {
case 'object':
parent.additionalProperties = value[0];
break;
case 'array':
parent.items = value[0];
break;
default:
assert(false);
}
});
// Fix case when arrays definition wrapped with array, like that:
// [{
// "type": "array",
// ...
// }]
jp.apply(schema, '$..properties[?(@.length === 1 && @[0].type === "array")]', function(schema) {
return schema[0];
});
// Fix incorrect array properties, like that:
// {
// "properties": {
// "type": array,
// "<name>": [{
// ...
// }]
// }
// }
_.each(jp.nodes(schema, '$..properties[?(@.length === 1)]'), function(result) {
var name = _.last(result.path);
var parent = jp.value(schema, jp.stringify(_.dropRight(result.path)));
if (parent['type'] === 'array') {
parent[name] = {type: 'array', items: result.value[0]}
delete parent['type'];
}
});
// Fix case then 'items' value is empty or single element array.
function unwrapItems(schema) {
if (_.isEmpty(schema.items))
schema.items = {};
else {
assert(_.isPlainObject(schema.items[0]));
schema.items = schema.items[0];
}
return schema;
}
jp.apply(schema, '$..*[?(@.type === "array" && @.items && @.items.length <= 1)]', unwrapItems);
//JSON Path can't apply to root object so do this manually
if (schema.type === 'array' && _.isArray(schema.items) && _.size(schema.items) <= 1)
unwrapItems(schema);
return schema;
}
|
Support url tempates inside path of baseUri
|
src/index.js
|
Support url tempates inside path of baseUri
|
<ide><path>rc/index.js
<ide> //FIXME:
<ide> //console.log(raml.documentation);
<ide>
<del> var swagger = _.assign({
<add> var swagger = {
<ide> swagger: '2.0',
<ide> info: {
<ide> title: raml.title,
<ide> securityDefinitions: parseSecuritySchemes(raml.securitySchemes),
<ide> paths: parseResources(raml.resources),
<ide> definitions: parseSchemas(raml.schemas)
<del> }, parseBaseUri(raml));
<add> };
<add>
<add> parseBaseUri(raml, swagger);
<ide>
<ide> jp.apply(swagger.paths, '$..*.schema' , function (schema) {
<ide> if (!schema || _.isEmpty(schema))
<ide> return swagger;
<ide> };
<ide>
<del>function parseBaseUri(raml) {
<add>function parseBaseUri(raml, swagger) {
<ide> var baseUri = raml.baseUri;
<ide>
<ide> if (!baseUri)
<del> return {};
<del>
<add> return;
<add>
<add> var baseUriParameters = _.omit(raml.baseUriParameters, 'version');
<ide> baseUri = baseUri.replace(/{version}/g, raml.version);
<add> baseUri = URI(baseUri);
<add>
<add> // Split out part path segments starting from first template param
<add> var match = /^(.*?)(\/[^\/]*?{.*)?$/.exec(baseUri.path());
<add> baseUri.path(match[1]);
<add> var pathPrefix = match[2];
<add>
<ide> //Don't support other URI templates right now.
<del> assert(baseUri.indexOf('{') == -1);
<del>
<del> baseUri = URI(baseUri);
<del>
<del> assert(!('baseUriParameters' in raml) ||
<del> _.isEqual(_.keys(raml.baseUriParameters), ['version']));
<add> assert(baseUri.href().indexOf('{') == -1);
<ide> assert(!('uriParameters' in raml));
<ide>
<del> return {
<add> _.assign(swagger, {
<ide> host: baseUri.host(),
<ide> basePath: '/' + baseUri.pathname().replace(/^\/|\/$/, ''),
<ide> schemes: parseProtocols(raml.protocols) || [baseUri.scheme()]
<del> };
<add> });
<add>
<add> if (!pathPrefix)
<add> return;
<add>
<add> pathPrefix = pathPrefix.replace(/\/$/, '');
<add> baseUriParameters = parseParametersList(baseUriParameters);
<add> swagger.paths = _.mapKeys(swagger.paths, function (value, key) {
<add> value.parameters = _.concat(baseUriParameters, value.parameters);
<add> return pathPrefix + key;
<add> });
<ide> }
<ide>
<ide> function parseSecuritySchemes(ramlSecuritySchemes) {
|
|
Java
|
mit
|
a0660599ffdfcbf07c071532965d1a85223f057f
| 0 |
AlterRS/Deobfuscator,AlterRS/Deobfuscator
|
/**
* Copyright (C) <2012> <Lazaro Brito>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software
* and associated documentation files (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial
* portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
* PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
* FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package alterrs.deob;
import java.io.File;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.zip.ZipFile;
import EDU.purdue.cs.bloat.editor.MethodEditor;
import alterrs.deob.trans.ClassLiteralDeobfuscation;
import alterrs.deob.trans.ControlFlowDeobfuscation;
import alterrs.deob.trans.FieldDeobfuscation;
import alterrs.deob.trans.HandlerDeobfuscation;
import alterrs.deob.trans.MonitorDeobfuscation;
import alterrs.deob.trans.PrivilageDeobfuscation;
import alterrs.deob.trans.SimpleArithmeticDeobfuscation;
import alterrs.deob.trans.TryCatchDeobfuscation;
import alterrs.deob.trans.euclid.EuclideanInverseDeobfuscation;
import alterrs.deob.trans.euclid.EuclideanPairIdentifier;
import alterrs.deob.util.NodeVisitor;
public class Deobfuscator {
private static Application app = null;
public static final NodeVisitor[] MISC_PRE_TRANSFORMERS = new NodeVisitor[] {
new HandlerDeobfuscation(), new PrivilageDeobfuscation()
};
public static final NodeVisitor[][] TREE_TRANSFORMERS = new NodeVisitor[][] {
{ // Phase 1
new EuclideanPairIdentifier(),
new ControlFlowDeobfuscation(),
new TryCatchDeobfuscation(),
new FieldDeobfuscation(),
new ClassLiteralDeobfuscation(),
//new SimpleArithmeticDeobfuscation(),
},
{ // Phase 2
new EuclideanInverseDeobfuscation(),
}
};
public static final NodeVisitor[] MISC_POST_TRANSFORMERS = new NodeVisitor[] {
new MonitorDeobfuscation()
};
static {
MethodEditor.OPT_STACK_2 = true;
}
private static Object lock = new Object();
private static int phase = 0;
private static final int totalPhases = TREE_TRANSFORMERS.length;
public static void main(String[] args) {
try {
System.out.println("Loading application... [" + args[0] + "]");
app = new Application(new ZipFile(args[0]));
//app = new Application("./bin/Test.class");
System.out.println("Loaded " + app.size() + " classes!");
System.out.println();
System.out.print("Applying misc pre-transformers...");
for (NodeVisitor visitor : MISC_PRE_TRANSFORMERS) {
app.accept(visitor);
}
System.out.println(" DONE!");
for (NodeVisitor visitor : MISC_PRE_TRANSFORMERS) {
visitor.onFinish();
}
System.out.println();
Chunk[] chunks = app.split(32 * Runtime.getRuntime()
.availableProcessors());
totalChunks = chunks.length;
System.out.println("Application split into " + chunks.length
+ " chunks!");
System.out.println("Executing a total of " + totalPhases + " phases!");
System.out.print("Applying tree transformers...\n\t0%");
ExecutorService executor = Executors.newFixedThreadPool(Runtime
.getRuntime().availableProcessors());
for(; phase < totalPhases; phase++) {
for (int i = 0; i < chunks.length; i++) {
executor.submit(chunks[i]);
}
synchronized (lock) {
lock.wait();
}
}
System.out.println();
for (NodeVisitor[] visitors : TREE_TRANSFORMERS) {
for(NodeVisitor visitor : visitors) {
visitor.onFinish();
}
}
System.out.println();
System.out.print("Applying misc post-transformers...");
for (NodeVisitor visitor : MISC_POST_TRANSFORMERS) {
app.accept(visitor);
}
System.out.println(" DONE!");
for (NodeVisitor visitor : MISC_POST_TRANSFORMERS) {
visitor.onFinish();
}
System.out.println();
String output = args[1].replace("$t",
new StringBuilder().append(System.currentTimeMillis()));
System.out.println("Saving application... [" + output + "]");
app.save(new File(output));
System.out.println("DONE!");
executor.shutdownNow();
Runtime.getRuntime().exec("java -jar deps/proguard.jar deps/@opt.pro");
} catch (Throwable t) {
System.err.println("Failed to run deobfuscator!");
t.printStackTrace();
}
}
public static int getPhase() {
return phase;
}
private static AtomicInteger percent = new AtomicInteger(0);
private static double finishedChunks = 0;
private static double totalChunks = 0;
private static AtomicInteger prints = new AtomicInteger(0);
public static void onFinish(Chunk chunk) {
int p = percent.get();
finishedChunks++;
int p_ = (int) (((finishedChunks / totalChunks) * 100) / ((double) totalPhases)) + ((100 / totalPhases) * phase);
if (p != p_) {
percent.set(p_);
if (prints.incrementAndGet() == 8) {
System.out.println();
prints.set(0);
}
System.out.print("\t" + p_ + "%");
if (finishedChunks == totalChunks) {
synchronized (lock) {
lock.notifyAll();
}
if(p_ == 100)
System.out.println();
finishedChunks = 0;
}
}
}
public static Application getApp() {
return app;
}
}
|
src/alterrs/deob/Deobfuscator.java
|
/**
* Copyright (C) <2012> <Lazaro Brito>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software
* and associated documentation files (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial
* portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
* PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
* FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package alterrs.deob;
import java.io.File;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.zip.ZipFile;
import EDU.purdue.cs.bloat.editor.MethodEditor;
import alterrs.deob.trans.ClassLiteralDeobfuscation;
import alterrs.deob.trans.ControlFlowDeobfuscation;
import alterrs.deob.trans.FieldDeobfuscation;
import alterrs.deob.trans.HandlerDeobfuscation;
import alterrs.deob.trans.MonitorDeobfuscation;
import alterrs.deob.trans.PrivilageDeobfuscation;
import alterrs.deob.trans.SimpleArithmeticDeobfuscation;
import alterrs.deob.trans.TryCatchDeobfuscation;
import alterrs.deob.trans.euclid.EuclideanInverseDeobfuscation;
import alterrs.deob.trans.euclid.EuclideanPairIdentifier;
import alterrs.deob.util.NodeVisitor;
public class Deobfuscator {
private static Application app = null;
public static final NodeVisitor[] MISC_PRE_TRANSFORMERS = new NodeVisitor[] {
new HandlerDeobfuscation(), new PrivilageDeobfuscation()
};
public static final NodeVisitor[][] TREE_TRANSFORMERS = new NodeVisitor[][] {
{ // Phase 1
new EuclideanPairIdentifier(),
new ControlFlowDeobfuscation(),
new TryCatchDeobfuscation(),
new FieldDeobfuscation(),
new ClassLiteralDeobfuscation(),
new SimpleArithmeticDeobfuscation(),
},
{ // Phase 2
new EuclideanInverseDeobfuscation(),
}
};
public static final NodeVisitor[] MISC_POST_TRANSFORMERS = new NodeVisitor[] {
new MonitorDeobfuscation()
};
static {
MethodEditor.OPT_STACK_2 = true;
}
private static Object lock = new Object();
private static int phase = 0;
private static final int totalPhases = TREE_TRANSFORMERS.length;
public static void main(String[] args) {
try {
System.out.println("Loading application... [" + args[0] + "]");
app = new Application(new ZipFile(args[0]));
//app = new Application("./bin/Test.class");
System.out.println("Loaded " + app.size() + " classes!");
System.out.println();
System.out.print("Applying misc pre-transformers...");
for (NodeVisitor visitor : MISC_PRE_TRANSFORMERS) {
app.accept(visitor);
}
System.out.println(" DONE!");
for (NodeVisitor visitor : MISC_PRE_TRANSFORMERS) {
visitor.onFinish();
}
System.out.println();
Chunk[] chunks = app.split(32 * Runtime.getRuntime()
.availableProcessors());
totalChunks = chunks.length;
System.out.println("Application split into " + chunks.length
+ " chunks!");
System.out.println("Executing a total of " + totalPhases + " phases!");
System.out.print("Applying tree transformers...\n\t0%");
ExecutorService executor = Executors.newFixedThreadPool(Runtime
.getRuntime().availableProcessors());
for(; phase < totalPhases; phase++) {
for (int i = 0; i < chunks.length; i++) {
executor.submit(chunks[i]);
}
synchronized (lock) {
lock.wait();
}
}
System.out.println();
for (NodeVisitor[] visitors : TREE_TRANSFORMERS) {
for(NodeVisitor visitor : visitors) {
visitor.onFinish();
}
}
System.out.println();
System.out.print("Applying misc post-transformers...");
for (NodeVisitor visitor : MISC_POST_TRANSFORMERS) {
app.accept(visitor);
}
System.out.println(" DONE!");
for (NodeVisitor visitor : MISC_POST_TRANSFORMERS) {
visitor.onFinish();
}
System.out.println();
String output = args[1].replace("$t",
new StringBuilder().append(System.currentTimeMillis()));
System.out.println("Saving application... [" + output + "]");
app.save(new File(output));
System.out.println("DONE!");
executor.shutdownNow();
Runtime.getRuntime().exec("java -jar deps/proguard.jar deps/@opt.pro");
} catch (Throwable t) {
System.err.println("Failed to run deobfuscator!");
t.printStackTrace();
}
}
public static int getPhase() {
return phase;
}
private static AtomicInteger percent = new AtomicInteger(0);
private static double finishedChunks = 0;
private static double totalChunks = 0;
private static AtomicInteger prints = new AtomicInteger(0);
public static void onFinish(Chunk chunk) {
int p = percent.get();
finishedChunks++;
int p_ = (int) (((finishedChunks / totalChunks) * 100) / ((double) totalPhases));
if (p != p_) {
percent.set(p_);
if (prints.incrementAndGet() == 8) {
System.out.println();
prints.set(0);
}
System.out.print("\t" + p_ + "%");
if (finishedChunks == totalChunks) {
synchronized (lock) {
lock.notifyAll();
}
if(p_ == 100)
System.out.println();
finishedChunks = 0;
}
}
}
public static Application getApp() {
return app;
}
}
|
Wrote a phase system in the deobfuscator for transformers that require a full iteration of the client before executing.
|
src/alterrs/deob/Deobfuscator.java
|
Wrote a phase system in the deobfuscator for transformers that require a full iteration of the client before executing.
|
<ide><path>rc/alterrs/deob/Deobfuscator.java
<ide> new TryCatchDeobfuscation(),
<ide> new FieldDeobfuscation(),
<ide> new ClassLiteralDeobfuscation(),
<del> new SimpleArithmeticDeobfuscation(),
<add> //new SimpleArithmeticDeobfuscation(),
<ide> },
<ide>
<ide> { // Phase 2
<ide>
<ide> int p = percent.get();
<ide> finishedChunks++;
<del> int p_ = (int) (((finishedChunks / totalChunks) * 100) / ((double) totalPhases));
<add> int p_ = (int) (((finishedChunks / totalChunks) * 100) / ((double) totalPhases)) + ((100 / totalPhases) * phase);
<ide>
<ide> if (p != p_) {
<ide> percent.set(p_);
|
|
Java
|
lgpl-2.1
|
871435861ff3cd253a4280d608e4fd1f337a858f
| 0 |
blue-systems-group/project.maybe.polyglot,xcv58/polyglot,blue-systems-group/project.maybe.polyglot,xcv58/polyglot,liujed/polyglot-eclipse,blue-systems-group/project.maybe.polyglot,blue-systems-group/project.maybe.polyglot,xcv58/polyglot,xcv58/polyglot,liujed/polyglot-eclipse,liujed/polyglot-eclipse,liujed/polyglot-eclipse
|
package polyglot.visit;
import java.util.HashMap;
import java.util.Map;
import polyglot.ast.Node;
import polyglot.ast.NodeFactory;
import polyglot.frontend.Job;
import polyglot.types.*;
import polyglot.util.*;
/** Visitor which checks if exceptions are caught or declared properly. */
public class ExceptionChecker extends ErrorHandlingVisitor
{
protected ExceptionChecker outer;
private SubtypeSet scope = null; // lazily instantiated
protected Map exceptionPositions;
public ExceptionChecker(Job job, TypeSystem ts, NodeFactory nf) {
super(job, ts, nf);
this.outer = null;
this.exceptionPositions = new HashMap();
}
public ExceptionChecker push() {
ExceptionChecker ec = (ExceptionChecker) this.visitChildren();
ec.outer = this;
ec.exceptionPositions = new HashMap();
return ec;
}
public ExceptionChecker pop() {
return outer;
}
/**
* This method is called when we are to perform a "normal" traversal of
* a subtree rooted at <code>n</code>. At every node, we will push a
* stack frame. Each child node will add the exceptions that it throws
* to this stack frame. For most nodes ( excdeption for the try / catch)
* will just aggregate the stack frames.
*
* @param n The root of the subtree to be traversed.
* @return The <code>NodeVisitor</code> which should be used to visit the
* children of <code>n</code>.
*
*/
protected NodeVisitor enterCall(Node n) throws SemanticException {
return n.exceptionCheckEnter(push());
}
protected NodeVisitor enterError(Node n) {
return push();
}
/**
* Here, we pop the stack frame that we pushed in enter and agregate the
* exceptions.
*
* @param old The original state of root of the current subtree.
* @param n The current state of the root of the current subtree.
* @param v The <code>NodeVisitor</code> object used to visit the children.
* @return The final result of the traversal of the tree rooted at
* <code>n</code>.
*/
protected Node leaveCall(Node old, Node n, NodeVisitor v)
throws SemanticException {
ExceptionChecker inner = (ExceptionChecker) v;
if (inner.outer != this) throw new InternalCompilerError("oops!");
// gather exceptions from this node.
n = n.del().exceptionCheck(inner);
// Merge results from the children and free the checker used for the
// children.
SubtypeSet t = inner.throwsSet();
throwsSet().addAll(t);
exceptionPositions.putAll(inner.exceptionPositions);
return n;
}
/**
* The ast nodes will use this callback to notify us that they throw an
* exception of type t. This should only be called by MethodExpr node,
* and throw node, since they are the only node which can generate
* exceptions.
*
* @param t The type of exception that the node throws.
*/
public void throwsException(Type t, Position pos) {
throwsSet().add(t) ;
exceptionPositions.put(t, pos);
}
/**
* Method to allow the throws clause and method body to inspect and
* modify the throwsSet.
*/
public SubtypeSet throwsSet() {
if (scope == null) {
scope = new SubtypeSet(ts.Throwable());
}
return scope;
}
/**
* Method to determine the position at which a particular exception is
* thrown
*/
public Position exceptionPosition(Type t) {
return (Position)exceptionPositions.get(t);
}
}
|
src/polyglot/visit/ExceptionChecker.java
|
package polyglot.visit;
import java.util.HashMap;
import java.util.Map;
import polyglot.ast.Node;
import polyglot.ast.NodeFactory;
import polyglot.frontend.Job;
import polyglot.types.SemanticException;
import polyglot.types.Type;
import polyglot.types.TypeSystem;
import polyglot.util.ErrorQueue;
import polyglot.util.InternalCompilerError;
import polyglot.util.Position;
import polyglot.util.SubtypeSet;
/** Visitor which checks if exceptions are caught or declared properly. */
public class ExceptionChecker extends ErrorHandlingVisitor
{
protected ExceptionChecker outer;
protected SubtypeSet scope;
protected Map exceptionPositions;
public ExceptionChecker(Job job, TypeSystem ts, NodeFactory nf) {
super(job, ts, nf);
this.outer = null;
this.scope = new SubtypeSet(ts.Throwable());
this.exceptionPositions = new HashMap();
}
public ExceptionChecker push() {
ExceptionChecker ec = (ExceptionChecker) this.visitChildren();
ec.outer = this;
ec.scope = new SubtypeSet(ts.Throwable());
ec.exceptionPositions = new HashMap();
return ec;
}
public ExceptionChecker pop() {
return outer;
}
/**
* This method is called when we are to perform a "normal" traversal of
* a subtree rooted at <code>n</code>. At every node, we will push a
* stack frame. Each child node will add the exceptions that it throws
* to this stack frame. For most nodes ( excdeption for the try / catch)
* will just aggregate the stack frames.
*
* @param n The root of the subtree to be traversed.
* @return The <code>NodeVisitor</code> which should be used to visit the
* children of <code>n</code>.
*
*/
protected NodeVisitor enterCall(Node n) throws SemanticException {
return n.exceptionCheckEnter(push());
}
protected NodeVisitor enterError(Node n) {
return push();
}
/**
* Here, we pop the stack frame that we pushed in enter and agregate the
* exceptions.
*
* @param old The original state of root of the current subtree.
* @param n The current state of the root of the current subtree.
* @param v The <code>NodeVisitor</code> object used to visit the children.
* @return The final result of the traversal of the tree rooted at
* <code>n</code>.
*/
protected Node leaveCall(Node old, Node n, NodeVisitor v)
throws SemanticException {
ExceptionChecker inner = (ExceptionChecker) v;
if (inner.outer != this) throw new InternalCompilerError("oops!");
// gather exceptions from this node.
n = n.del().exceptionCheck(inner);
// Merge results from the children and free the checker used for the
// children.
SubtypeSet t = inner.throwsSet();
throwsSet().addAll(t);
exceptionPositions.putAll(inner.exceptionPositions);
return n;
}
/**
* The ast nodes will use this callback to notify us that they throw an
* exception of type t. This should only be called by MethodExpr node,
* and throw node, since they are the only node which can generate
* exceptions.
*
* @param t The type of exception that the node throws.
*/
public void throwsException(Type t, Position pos) {
throwsSet().add(t) ;
exceptionPositions.put(t, pos);
}
/**
* Method to allow the throws clause and method body to inspect and
* modify the throwsSet.
*/
public SubtypeSet throwsSet() {
return (SubtypeSet) scope;
}
/**
* Method to determine the position at which a particular exception is
* thrown
*/
public Position exceptionPosition(Type t) {
return (Position)exceptionPositions.get(t);
}
}
|
Lazily instantiate the SubtypeSet, to prevent Throwable from being loaded too early.
|
src/polyglot/visit/ExceptionChecker.java
|
Lazily instantiate the SubtypeSet, to prevent Throwable from being loaded too early.
|
<ide><path>rc/polyglot/visit/ExceptionChecker.java
<ide> import polyglot.ast.Node;
<ide> import polyglot.ast.NodeFactory;
<ide> import polyglot.frontend.Job;
<del>import polyglot.types.SemanticException;
<del>import polyglot.types.Type;
<del>import polyglot.types.TypeSystem;
<del>import polyglot.util.ErrorQueue;
<del>import polyglot.util.InternalCompilerError;
<del>import polyglot.util.Position;
<del>import polyglot.util.SubtypeSet;
<add>import polyglot.types.*;
<add>import polyglot.util.*;
<ide>
<ide> /** Visitor which checks if exceptions are caught or declared properly. */
<ide> public class ExceptionChecker extends ErrorHandlingVisitor
<ide> {
<ide> protected ExceptionChecker outer;
<del> protected SubtypeSet scope;
<add> private SubtypeSet scope = null; // lazily instantiated
<ide> protected Map exceptionPositions;
<ide>
<ide> public ExceptionChecker(Job job, TypeSystem ts, NodeFactory nf) {
<ide> super(job, ts, nf);
<ide> this.outer = null;
<del> this.scope = new SubtypeSet(ts.Throwable());
<ide> this.exceptionPositions = new HashMap();
<ide> }
<ide>
<ide> public ExceptionChecker push() {
<ide> ExceptionChecker ec = (ExceptionChecker) this.visitChildren();
<ide> ec.outer = this;
<del> ec.scope = new SubtypeSet(ts.Throwable());
<ide> ec.exceptionPositions = new HashMap();
<ide> return ec;
<ide> }
<ide> * modify the throwsSet.
<ide> */
<ide> public SubtypeSet throwsSet() {
<del> return (SubtypeSet) scope;
<add> if (scope == null) {
<add> scope = new SubtypeSet(ts.Throwable());
<add> }
<add> return scope;
<ide> }
<ide>
<ide> /**
|
|
Java
|
cc0-1.0
|
b067d4c631ed200429ca347983a51b0ddda4769b
| 0 |
SleepyTrousers/Structures
|
package crazypants.structures.runtime.condition;
import crazypants.structures.api.gen.IStructure;
import crazypants.structures.api.runtime.ICondition;
import crazypants.structures.api.util.Point3i;
import net.minecraft.world.World;
public class OrCondition extends AndCondition {
public OrCondition() {
super("OrCondition");
}
@Override
public boolean isConditionMet(World world, IStructure structure, Point3i refPoint) {
for(ICondition con : getConditions()) {
if(con.isConditionMet(world, structure, refPoint)) {
return true;
}
}
return false;
}
@Override
protected AndCondition doCreateInstance() {
return new OrCondition();
}
}
|
src/main/java/crazypants/structures/runtime/condition/OrCondition.java
|
package crazypants.structures.runtime.condition;
import crazypants.structures.api.gen.IStructure;
import crazypants.structures.api.runtime.ICondition;
import crazypants.structures.api.util.Point3i;
import net.minecraft.world.World;
public class OrCondition extends AndCondition {
@Override
public boolean isConditionMet(World world, IStructure structure, Point3i refPoint) {
for(ICondition con : getConditions()) {
if(con.isConditionMet(world, structure, refPoint)) {
return true;
}
}
return false;
}
@Override
protected AndCondition doCreateInstance() {
return new OrCondition();
}
}
|
Added missing constructor.
|
src/main/java/crazypants/structures/runtime/condition/OrCondition.java
|
Added missing constructor.
|
<ide><path>rc/main/java/crazypants/structures/runtime/condition/OrCondition.java
<ide>
<ide> public class OrCondition extends AndCondition {
<ide>
<add> public OrCondition() {
<add> super("OrCondition");
<add> }
<add>
<ide> @Override
<ide> public boolean isConditionMet(World world, IStructure structure, Point3i refPoint) {
<ide> for(ICondition con : getConditions()) {
|
|
JavaScript
|
mit
|
80902ce31f17ef1c7a6e3bfa89265e3d46a2f474
| 0 |
kevgathuku/inverted-index,kevgathuku/inverted-index
|
describe('Inverted Index Tests: ', function() {
var index = new Index();
var filter = new Filter();
var results;
beforeEach(function(done) {
index.createIndex('books.json', index.populateIndex).done(function(data) {
results = data;
// Invoke jasmine's done callback
done();
});
});
describe('Reads book data', function() {
it('reads the JSON file successfully', function() {
expect(results).toBeDefined();
expect(results.length).not.toEqual(0);
expect(results.length).toEqual(2);
});
it('Ensures each object property contains a string value', function() {
for (var i = 0, len = results.length; i < len; i++) {
// Iterate over the properties of each object
for(key in results[i]) {
// Ensure the value is a string
expect(typeof results[i][key]).toBe('string');
}
}
});
});
describe('Populates Index', function() {
var index0 = ['alice', 'rabbit', 'imagination', 'world'];
var index1 = ['alliance', 'elf', 'dwarf', 'wizard'];
it('creates the index once JSON file has been read', function() {
expect(index.results).not.toEqual({});
});
it('creates an index containing only lowercase terms', function() {
var keys = Object.keys(index.results);
for (var i = 0, len = keys.length; i < len; i++) {
expect(keys[i]).toBe(keys[i].toLowerCase());
}
});
it('creates index strings without punctuation', function() {
var keys = Object.keys(index.results);
for (var i = 0, len = keys.length; i < len; i++) {
expect(keys[i].indexOf('.')).toBe(-1);
expect(keys[i].indexOf(',')).toBe(-1);
}
});
it('creates index strings without stop words', function() {
var keys = Object.keys(index.results);
for (var i = 0, len = keys.length; i < len; i++) {
expect(filter.stopWords.indexOf(keys[i])).toBe(-1);
}
});
it('creates index containing correct terms', function() {
var keys = Object.keys(index.results);
for (var i = 0, len = index0.length; i < len; i++) {
expect(keys).toContain(index0[i]);
}
for (var i = 0, len = index1.length; i < len; i++) {
expect(keys).toContain(index0[i]);
}
});
it('maps string keys to the correct objects', function() {
var keys = Object.keys(index.results);
// Should return 0 for objects in the first array element
for (var i = 0, len = index0.length; i < len; i++) {
expect(index.results[index0[i]]).toBe(0);
}
// Should return 1 for objects in the second array element
for (var i = 0, len = index0.length; i < len; i++) {
expect(index.results[index1[i]]).toBe(1);
}
});
});
describe('Search Index', function() {
it('returns accurate results when searched', function() {
expect(Array.isArray(index.searchIndex('elf'))).toBe(true);
expect(index.searchIndex('rabbit')).toContain(0);
expect(index.searchIndex('hobbit')).toContain(1);
// The returned array should have a maximum of 2 elements
expect(index.searchIndex(['imagination', 'dwarf', 'hobbit']).length)
.toBe(2);
});
it('returns -1 when none of the terms is found', function() {
expect(index.searchIndex('haha')).toBe(-1);
});
it('handles an array of search terms', function() {
expect(index.searchIndex(['haha', 'impossible'])).toBe(-1);
expect(index.searchIndex(['imagination', 'dwarf'])).toContain(0);
expect(index.searchIndex(['imagination', 'dwarf'])).toContain(1);
});
it('handles varied number of of search terms as arguments', function() {
expect(index.searchIndex()).toBe(-1);
expect(index.searchIndex([])).toBe(-1);
expect(index.searchIndex(['imagination'])).toContain(0);
expect(index.searchIndex('imagination', 'dwarf')).toContain(1);
expect(index.searchIndex('imagination', 'dwarf', 'warrior')).toContain(1);
expect(index.searchIndex('imagination', 'dwarf', 'warrior').length).toBe(2);
});
});
});
|
jasmine/spec/invertedIndexTest.js
|
describe('Inverted Index Tests: ', function() {
var index = new Index();
var filter = new Filter();
var results;
beforeEach(function(done) {
index.createIndex('books.json', index.populateIndex).done(function(data) {
results = data;
// Invoke jasmine's done callback
done();
});
});
describe('Reads book data', function() {
it('reads the JSON file successfully', function() {
expect(results).toBeDefined();
expect(results.length).not.toEqual(0);
expect(results.length).toEqual(2);
});
});
describe('Populates Index', function() {
var index0 = ['alice', 'rabbit', 'imagination', 'world'];
var index1 = ['alliance', 'elf', 'dwarf', 'wizard'];
it('creates the index once JSON file has been read', function() {
expect(index.results).not.toEqual({});
});
it('creates an index containing only lowercase terms', function() {
var keys = Object.keys(index.results);
for (var i = 0, len = keys.length; i < len; i++) {
expect(keys[i]).toBe(keys[i].toLowerCase());
}
});
it('creates index strings without punctuation', function() {
var keys = Object.keys(index.results);
for (var i = 0, len = keys.length; i < len; i++) {
expect(keys[i].indexOf('.')).toBe(-1);
expect(keys[i].indexOf(',')).toBe(-1);
}
});
it('creates index strings without stop words', function() {
var keys = Object.keys(index.results);
for (var i = 0, len = keys.length; i < len; i++) {
expect(filter.stopWords.indexOf(keys[i])).toBe(-1);
}
});
it('creates index containing correct terms', function() {
var keys = Object.keys(index.results);
for (var i = 0, len = index0.length; i < len; i++) {
expect(keys).toContain(index0[i]);
}
for (var i = 0, len = index1.length; i < len; i++) {
expect(keys).toContain(index0[i]);
}
});
it('maps string keys to the correct objects', function() {
var keys = Object.keys(index.results);
// Should return 0 for objects in the first array element
for (var i = 0, len = index0.length; i < len; i++) {
expect(index.results[index0[i]]).toBe(0);
}
// Should return 1 for objects in the second array element
for (var i = 0, len = index0.length; i < len; i++) {
expect(index.results[index1[i]]).toBe(1);
}
});
});
describe('Search Index', function() {
it('returns accurate results when searched', function() {
expect(Array.isArray(index.searchIndex('elf'))).toBe(true);
expect(index.searchIndex('rabbit')).toContain(0);
expect(index.searchIndex('hobbit')).toContain(1);
// The returned array should have a maximum of 2 elements
expect(index.searchIndex(['imagination', 'dwarf', 'hobbit']).length)
.toBe(2);
});
it('returns -1 when none of the terms is found', function() {
expect(index.searchIndex('haha')).toBe(-1);
});
it('handles an array of search terms', function() {
expect(index.searchIndex(['haha', 'impossible'])).toBe(-1);
expect(index.searchIndex(['imagination', 'dwarf'])).toContain(0);
expect(index.searchIndex(['imagination', 'dwarf'])).toContain(1);
});
it('handles varied number of of search terms as arguments', function() {
expect(index.searchIndex()).toBe(-1);
expect(index.searchIndex([])).toBe(-1);
expect(index.searchIndex(['imagination'])).toContain(0);
expect(index.searchIndex('imagination', 'dwarf')).toContain(1);
expect(index.searchIndex('imagination', 'dwarf', 'warrior')).toContain(1);
expect(index.searchIndex('imagination', 'dwarf', 'warrior').length).toBe(2);
});
});
});
|
Add test to ensure each property value is a string
For the input JSON file, ensure each object in JSON array contains a property
whose value is a string.
|
jasmine/spec/invertedIndexTest.js
|
Add test to ensure each property value is a string
|
<ide><path>asmine/spec/invertedIndexTest.js
<ide> expect(results).toBeDefined();
<ide> expect(results.length).not.toEqual(0);
<ide> expect(results.length).toEqual(2);
<add> });
<add>
<add> it('Ensures each object property contains a string value', function() {
<add> for (var i = 0, len = results.length; i < len; i++) {
<add> // Iterate over the properties of each object
<add> for(key in results[i]) {
<add> // Ensure the value is a string
<add> expect(typeof results[i][key]).toBe('string');
<add> }
<add> }
<ide> });
<ide> });
<ide>
|
|
Java
|
apache-2.0
|
86878d16ef30653032d1d3639fea1b4d5bf50816
| 0 |
allotria/intellij-community,allotria/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,da1z/intellij-community,da1z/intellij-community,allotria/intellij-community,da1z/intellij-community,allotria/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,apixandru/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,allotria/intellij-community,da1z/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,apixandru/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,vvv1559/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,da1z/intellij-community,xfournet/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,xfournet/intellij-community,allotria/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,xfournet/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,apixandru/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,allotria/intellij-community,da1z/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,apixandru/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,allotria/intellij-community
|
/*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.xdebugger.impl.ui;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.colors.EditorColorsManager;
import com.intellij.openapi.editor.ex.EditorEx;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.ComboBox;
import com.intellij.ui.EditorComboBoxEditor;
import com.intellij.ui.EditorComboBoxRenderer;
import com.intellij.ui.EditorTextField;
import com.intellij.util.ui.UIUtil;
import com.intellij.xdebugger.XExpression;
import com.intellij.xdebugger.XSourcePosition;
import com.intellij.xdebugger.evaluation.EvaluationMode;
import com.intellij.xdebugger.evaluation.XDebuggerEditorsProvider;
import com.intellij.xdebugger.impl.XDebuggerHistoryManager;
import com.intellij.xdebugger.impl.breakpoints.XExpressionImpl;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.util.function.Function;
/**
* @author nik
*/
public class XDebuggerExpressionComboBox extends XDebuggerEditorBase {
private final JComponent myComponent;
private final ComboBox<XExpression> myComboBox;
private XDebuggerComboBoxEditor myEditor;
private XExpression myExpression;
private Function<Document, Document> myDocumentProcessor = Function.identity();
public XDebuggerExpressionComboBox(@NotNull Project project, @NotNull XDebuggerEditorsProvider debuggerEditorsProvider, @Nullable @NonNls String historyId,
@Nullable XSourcePosition sourcePosition, boolean showEditor) {
super(project, debuggerEditorsProvider, EvaluationMode.EXPRESSION, historyId, sourcePosition);
myComboBox = new ComboBox<>(100);
myComboBox.setFocusCycleRoot(true);
myComboBox.setFocusTraversalPolicyProvider(true);
myComboBox.setFocusTraversalPolicy(new FocusTraversalPolicy() {
@Override
public Component getComponentAfter(Container aContainer, Component aComponent) {
return null;
}
@Override
public Component getComponentBefore(Container aContainer, Component aComponent) {
return null;
}
@Override
public Component getFirstComponent(Container aContainer) {
return null;
}
@Override
public Component getLastComponent(Container aContainer) {
return null;
}
@Override
public Component getDefaultComponent(Container aContainer) {
return null;
}
});
myComboBox.setEditable(true);
myExpression = XExpressionImpl.EMPTY_EXPRESSION;
Dimension minimumSize = new Dimension(myComboBox.getMinimumSize());
minimumSize.width = 100;
myComboBox.setMinimumSize(minimumSize);
initEditor();
fillComboBox();
myComponent = showEditor ? addMultilineButton(myComboBox) : myComboBox;
}
public ComboBox getComboBox() {
return myComboBox;
}
@Override
public JComponent getComponent() {
return myComponent;
}
@Nullable
public Editor getEditor() {
return myEditor.getEditorTextField().getEditor();
}
public JComponent getEditorComponent() {
return myEditor.getEditorTextField();
}
public void setEnabled(boolean enable) {
if (enable == myComboBox.isEnabled()) return;
UIUtil.setEnabled(myComponent, enable, true);
//myComboBox.setEditable(enable);
if (enable) {
//initEditor();
}
else {
myExpression = getExpression();
}
}
private void initEditor() {
myEditor = new XDebuggerComboBoxEditor();
myComboBox.setEditor(myEditor);
//myEditor.setItem(myExpression);
myComboBox.setRenderer(new EditorComboBoxRenderer(myEditor));
myComboBox.setMaximumRowCount(XDebuggerHistoryManager.MAX_RECENT_EXPRESSIONS);
}
@Override
protected void onHistoryChanged() {
fillComboBox();
}
private void fillComboBox() {
myComboBox.removeAllItems();
getRecentExpressions().forEach(myComboBox::addItem);
if (myComboBox.getItemCount() > 0) {
myComboBox.setSelectedIndex(0);
}
}
@Override
protected void doSetText(XExpression text) {
if (myComboBox.getItemCount() > 0) {
myComboBox.setSelectedIndex(0);
}
//if (myComboBox.isEditable()) {
myEditor.setItem(text);
//}
myExpression = text;
}
@Override
public XExpression getExpression() {
XExpression item = myEditor.getItem();
return item != null ? item : myExpression;
}
@Override
protected Document createDocument(XExpression text) {
return myDocumentProcessor.apply(super.createDocument(text));
}
public void setDocumentProcessor(Function<Document, Document> documentProcessor) {
myDocumentProcessor = documentProcessor;
}
@Override
public JComponent getPreferredFocusedComponent() {
return myEditor.getEditorTextField();
}
@Override
public void selectAll() {
myComboBox.getEditor().selectAll();
}
private class XDebuggerComboBoxEditor implements ComboBoxEditor {
private final JComponent myPanel;
private final EditorComboBoxEditor myDelegate;
public XDebuggerComboBoxEditor() {
myDelegate = new EditorComboBoxEditor(getProject(), getEditorsProvider().getFileType()) {
@Override
protected void onEditorCreate(EditorEx editor) {
editor.putUserData(DebuggerCopyPastePreprocessor.REMOVE_NEWLINES_ON_PASTE, true);
editor.getColorsScheme().setEditorFontSize(
Math.min(myComboBox.getFont().getSize(), EditorColorsManager.getInstance().getGlobalScheme().getEditorFontSize()));
}
};
myDelegate.getEditorComponent().setFontInheritedFromLAF(false);
myPanel = addChooser(myDelegate.getEditorComponent());
}
public EditorTextField getEditorTextField() {
return myDelegate.getEditorComponent();
}
@Override
public JComponent getEditorComponent() {
return myPanel;
}
@Override
public void setItem(Object anObject) {
if (anObject == null) {
anObject = XExpressionImpl.EMPTY_EXPRESSION;
}
XExpression expression = (XExpression)anObject;
myDelegate.getEditorComponent().setNewDocumentAndFileType(getFileType(expression), createDocument(expression));
}
@Override
public XExpression getItem() {
Object document = myDelegate.getItem();
if (document instanceof Document) { // sometimes null on Mac
return getEditorsProvider().createExpression(getProject(), (Document)document, myExpression.getLanguage(), myExpression.getMode());
}
return null;
}
@Override
public void selectAll() {
myDelegate.selectAll();
}
@Override
public void addActionListener(ActionListener l) {
myDelegate.addActionListener(l);
}
@Override
public void removeActionListener(ActionListener l) {
myDelegate.removeActionListener(l);
}
}
}
|
platform/xdebugger-impl/src/com/intellij/xdebugger/impl/ui/XDebuggerExpressionComboBox.java
|
/*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.xdebugger.impl.ui;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.ex.EditorEx;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.ComboBox;
import com.intellij.ui.EditorComboBoxEditor;
import com.intellij.ui.EditorComboBoxRenderer;
import com.intellij.ui.EditorTextField;
import com.intellij.util.ui.UIUtil;
import com.intellij.xdebugger.XExpression;
import com.intellij.xdebugger.XSourcePosition;
import com.intellij.xdebugger.evaluation.EvaluationMode;
import com.intellij.xdebugger.evaluation.XDebuggerEditorsProvider;
import com.intellij.xdebugger.impl.XDebuggerHistoryManager;
import com.intellij.xdebugger.impl.breakpoints.XExpressionImpl;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.util.function.Function;
/**
* @author nik
*/
public class XDebuggerExpressionComboBox extends XDebuggerEditorBase {
private final JComponent myComponent;
private final ComboBox<XExpression> myComboBox;
private XDebuggerComboBoxEditor myEditor;
private XExpression myExpression;
private Function<Document, Document> myDocumentProcessor = Function.identity();
public XDebuggerExpressionComboBox(@NotNull Project project, @NotNull XDebuggerEditorsProvider debuggerEditorsProvider, @Nullable @NonNls String historyId,
@Nullable XSourcePosition sourcePosition, boolean showEditor) {
super(project, debuggerEditorsProvider, EvaluationMode.EXPRESSION, historyId, sourcePosition);
myComboBox = new ComboBox<>(100);
myComboBox.setFocusCycleRoot(true);
myComboBox.setFocusTraversalPolicyProvider(true);
myComboBox.setFocusTraversalPolicy(new FocusTraversalPolicy() {
@Override
public Component getComponentAfter(Container aContainer, Component aComponent) {
return null;
}
@Override
public Component getComponentBefore(Container aContainer, Component aComponent) {
return null;
}
@Override
public Component getFirstComponent(Container aContainer) {
return null;
}
@Override
public Component getLastComponent(Container aContainer) {
return null;
}
@Override
public Component getDefaultComponent(Container aContainer) {
return null;
}
});
myComboBox.setEditable(true);
myExpression = XExpressionImpl.EMPTY_EXPRESSION;
Dimension minimumSize = new Dimension(myComboBox.getMinimumSize());
minimumSize.width = 100;
myComboBox.setMinimumSize(minimumSize);
initEditor();
fillComboBox();
myComponent = showEditor ? addMultilineButton(myComboBox) : myComboBox;
}
public ComboBox getComboBox() {
return myComboBox;
}
@Override
public JComponent getComponent() {
return myComponent;
}
@Nullable
public Editor getEditor() {
return myEditor.getEditorTextField().getEditor();
}
public JComponent getEditorComponent() {
return myEditor.getEditorTextField();
}
public void setEnabled(boolean enable) {
if (enable == myComboBox.isEnabled()) return;
UIUtil.setEnabled(myComponent, enable, true);
//myComboBox.setEditable(enable);
if (enable) {
//initEditor();
}
else {
myExpression = getExpression();
}
}
private void initEditor() {
myEditor = new XDebuggerComboBoxEditor();
myComboBox.setEditor(myEditor);
//myEditor.setItem(myExpression);
myComboBox.setRenderer(new EditorComboBoxRenderer(myEditor));
myComboBox.setMaximumRowCount(XDebuggerHistoryManager.MAX_RECENT_EXPRESSIONS);
}
@Override
protected void onHistoryChanged() {
fillComboBox();
}
private void fillComboBox() {
myComboBox.removeAllItems();
getRecentExpressions().forEach(myComboBox::addItem);
if (myComboBox.getItemCount() > 0) {
myComboBox.setSelectedIndex(0);
}
}
@Override
protected void doSetText(XExpression text) {
if (myComboBox.getItemCount() > 0) {
myComboBox.setSelectedIndex(0);
}
//if (myComboBox.isEditable()) {
myEditor.setItem(text);
//}
myExpression = text;
}
@Override
public XExpression getExpression() {
XExpression item = myEditor.getItem();
return item != null ? item : myExpression;
}
@Override
protected Document createDocument(XExpression text) {
return myDocumentProcessor.apply(super.createDocument(text));
}
public void setDocumentProcessor(Function<Document, Document> documentProcessor) {
myDocumentProcessor = documentProcessor;
}
@Override
public JComponent getPreferredFocusedComponent() {
return myEditor.getEditorTextField();
}
@Override
public void selectAll() {
myComboBox.getEditor().selectAll();
}
private class XDebuggerComboBoxEditor implements ComboBoxEditor {
private final JComponent myPanel;
private final EditorComboBoxEditor myDelegate;
public XDebuggerComboBoxEditor() {
myDelegate = new EditorComboBoxEditor(getProject(), getEditorsProvider().getFileType()) {
@Override
protected void onEditorCreate(EditorEx editor) {
editor.putUserData(DebuggerCopyPastePreprocessor.REMOVE_NEWLINES_ON_PASTE, true);
editor.getColorsScheme().setEditorFontSize(myComboBox.getFont().getSize());
}
};
myDelegate.getEditorComponent().setFontInheritedFromLAF(false);
myPanel = addChooser(myDelegate.getEditorComponent());
}
public EditorTextField getEditorTextField() {
return myDelegate.getEditorComponent();
}
@Override
public JComponent getEditorComponent() {
return myPanel;
}
@Override
public void setItem(Object anObject) {
if (anObject == null) {
anObject = XExpressionImpl.EMPTY_EXPRESSION;
}
XExpression expression = (XExpression)anObject;
myDelegate.getEditorComponent().setNewDocumentAndFileType(getFileType(expression), createDocument(expression));
}
@Override
public XExpression getItem() {
Object document = myDelegate.getItem();
if (document instanceof Document) { // sometimes null on Mac
return getEditorsProvider().createExpression(getProject(), (Document)document, myExpression.getLanguage(), myExpression.getMode());
}
return null;
}
@Override
public void selectAll() {
myDelegate.selectAll();
}
@Override
public void addActionListener(ActionListener l) {
myDelegate.addActionListener(l);
}
@Override
public void removeActionListener(ActionListener l) {
myDelegate.removeActionListener(l);
}
}
}
|
IDEA-176922 font in various debugger edit fields (that take code) and code completion popups, when editing is larger than the configured font size
|
platform/xdebugger-impl/src/com/intellij/xdebugger/impl/ui/XDebuggerExpressionComboBox.java
|
IDEA-176922 font in various debugger edit fields (that take code) and code completion popups, when editing is larger than the configured font size
|
<ide><path>latform/xdebugger-impl/src/com/intellij/xdebugger/impl/ui/XDebuggerExpressionComboBox.java
<ide>
<ide> import com.intellij.openapi.editor.Document;
<ide> import com.intellij.openapi.editor.Editor;
<add>import com.intellij.openapi.editor.colors.EditorColorsManager;
<ide> import com.intellij.openapi.editor.ex.EditorEx;
<ide> import com.intellij.openapi.project.Project;
<ide> import com.intellij.openapi.ui.ComboBox;
<ide> @Override
<ide> protected void onEditorCreate(EditorEx editor) {
<ide> editor.putUserData(DebuggerCopyPastePreprocessor.REMOVE_NEWLINES_ON_PASTE, true);
<del> editor.getColorsScheme().setEditorFontSize(myComboBox.getFont().getSize());
<add> editor.getColorsScheme().setEditorFontSize(
<add> Math.min(myComboBox.getFont().getSize(), EditorColorsManager.getInstance().getGlobalScheme().getEditorFontSize()));
<ide> }
<ide> };
<ide> myDelegate.getEditorComponent().setFontInheritedFromLAF(false);
|
|
Java
|
apache-2.0
|
1a502ae88ae87f4e291936c4d6390260166e8701
| 0 |
krosenvold/commons-compress,mohanaraosv/commons-compress,lookout/commons-compress,lookout/commons-compress,lookout/commons-compress,mohanaraosv/commons-compress,krosenvold/commons-compress,krosenvold/commons-compress,apache/commons-compress,apache/commons-compress,mohanaraosv/commons-compress,apache/commons-compress
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.commons.compress.archivers.sevenz;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.LinkedList;
import java.util.TimeZone;
import org.apache.commons.compress.archivers.ArchiveEntry;
/**
* An entry in a 7z archive.
*
* @NotThreadSafe
* @since 1.6
*/
public class SevenZArchiveEntry implements ArchiveEntry {
private String name;
private boolean hasStream;
private boolean isDirectory;
private boolean isAntiItem;
private boolean hasCreationDate;
private boolean hasLastModifiedDate;
private boolean hasAccessDate;
private long creationDate;
private long lastModifiedDate;
private long accessDate;
private boolean hasWindowsAttributes;
private int windowsAttributes;
private boolean hasCrc;
private long crc, compressedCrc;
private long size, compressedSize;
private Iterable<? extends SevenZMethodConfiguration> contentMethods;
public SevenZArchiveEntry() {
}
/**
* Get this entry's name.
*
* @return This entry's name.
*/
public String getName() {
return name;
}
/**
* Set this entry's name.
*
* @param name This entry's new name.
*/
public void setName(String name) {
this.name = name;
}
/**
* Whether there is any content associated with this entry.
* @return whether there is any content associated with this entry.
*/
public boolean hasStream() {
return hasStream;
}
/**
* Sets whether there is any content associated with this entry.
* @param hasStream whether there is any content associated with this entry.
*/
public void setHasStream(boolean hasStream) {
this.hasStream = hasStream;
}
/**
* Return whether or not this entry represents a directory.
*
* @return True if this entry is a directory.
*/
public boolean isDirectory() {
return isDirectory;
}
/**
* Sets whether or not this entry represents a directory.
*
* @param isDirectory True if this entry is a directory.
*/
public void setDirectory(boolean isDirectory) {
this.isDirectory = isDirectory;
}
/**
* Indicates whether this is an "anti-item" used in differential backups,
* meaning it should delete the same file from a previous backup.
* @return true if it is an anti-item, false otherwise
*/
public boolean isAntiItem() {
return isAntiItem;
}
/**
* Sets whether this is an "anti-item" used in differential backups,
* meaning it should delete the same file from a previous backup.
* @param isAntiItem true if it is an ait-item, false otherwise
*/
public void setAntiItem(boolean isAntiItem) {
this.isAntiItem = isAntiItem;
}
/**
* Returns whether this entry has got a creation date at all.
*/
public boolean getHasCreationDate() {
return hasCreationDate;
}
/**
* Sets whether this entry has got a creation date at all.
*/
public void setHasCreationDate(boolean hasCreationDate) {
this.hasCreationDate = hasCreationDate;
}
/**
* Gets the creation date.
* @throws UnsupportedOperationException if the entry hasn't got a
* creation date.
*/
public Date getCreationDate() {
if (hasCreationDate) {
return ntfsTimeToJavaTime(creationDate);
} else {
throw new UnsupportedOperationException(
"The entry doesn't have this timestamp");
}
}
/**
* Sets the creation date using NTFS time (100 nanosecond units
* since 1 January 1601)
*/
public void setCreationDate(long ntfsCreationDate) {
this.creationDate = ntfsCreationDate;
}
/**
* Sets the creation date,
*/
public void setCreationDate(Date creationDate) {
hasCreationDate = creationDate != null;
if (hasCreationDate) {
this.creationDate = javaTimeToNtfsTime(creationDate);
}
}
/**
* Returns whether this entry has got a last modified date at all.
*/
public boolean getHasLastModifiedDate() {
return hasLastModifiedDate;
}
/**
* Sets whether this entry has got a last modified date at all.
*/
public void setHasLastModifiedDate(boolean hasLastModifiedDate) {
this.hasLastModifiedDate = hasLastModifiedDate;
}
/**
* Gets the last modified date.
* @throws UnsupportedOperationException if the entry hasn't got a
* last modified date.
*/
public Date getLastModifiedDate() {
if (hasLastModifiedDate) {
return ntfsTimeToJavaTime(lastModifiedDate);
} else {
throw new UnsupportedOperationException(
"The entry doesn't have this timestamp");
}
}
/**
* Sets the last modified date using NTFS time (100 nanosecond
* units since 1 January 1601)
*/
public void setLastModifiedDate(long ntfsLastModifiedDate) {
this.lastModifiedDate = ntfsLastModifiedDate;
}
/**
* Sets the last modified date,
*/
public void setLastModifiedDate(Date lastModifiedDate) {
hasLastModifiedDate = lastModifiedDate != null;
if (hasLastModifiedDate) {
this.lastModifiedDate = javaTimeToNtfsTime(lastModifiedDate);
}
}
/**
* Returns whether this entry has got an access date at all.
*/
public boolean getHasAccessDate() {
return hasAccessDate;
}
/**
* Sets whether this entry has got an access date at all.
*/
public void setHasAccessDate(boolean hasAcessDate) {
this.hasAccessDate = hasAcessDate;
}
/**
* Gets the access date.
* @throws UnsupportedOperationException if the entry hasn't got a
* access date.
*/
public Date getAccessDate() {
if (hasAccessDate) {
return ntfsTimeToJavaTime(accessDate);
} else {
throw new UnsupportedOperationException(
"The entry doesn't have this timestamp");
}
}
/**
* Sets the access date using NTFS time (100 nanosecond units
* since 1 January 1601)
*/
public void setAccessDate(long ntfsAccessDate) {
this.accessDate = ntfsAccessDate;
}
/**
* Sets the access date,
*/
public void setAccessDate(Date accessDate) {
hasAccessDate = accessDate != null;
if (hasAccessDate) {
this.accessDate = javaTimeToNtfsTime(accessDate);
}
}
/**
* Returns whether this entry has windows attributes.
*/
public boolean getHasWindowsAttributes() {
return hasWindowsAttributes;
}
/**
* Sets whether this entry has windows attributes.
*/
public void setHasWindowsAttributes(boolean hasWindowsAttributes) {
this.hasWindowsAttributes = hasWindowsAttributes;
}
/**
* Gets the windows attributes.
*/
public int getWindowsAttributes() {
return windowsAttributes;
}
/**
* Sets the windows attributes.
*/
public void setWindowsAttributes(int windowsAttributes) {
this.windowsAttributes = windowsAttributes;
}
/**
* Returns whether this entry has got a crc.
*
* In general entries without streams don't have a CRC either.
*/
public boolean getHasCrc() {
return hasCrc;
}
/**
* Sets whether this entry has got a crc.
*/
public void setHasCrc(boolean hasCrc) {
this.hasCrc = hasCrc;
}
/**
* Gets the CRC.
* @deprecated use getCrcValue instead.
*/
@Deprecated
public int getCrc() {
return (int) crc;
}
/**
* Sets the CRC.
* @deprecated use setCrcValue instead.
*/
@Deprecated
public void setCrc(int crc) {
this.crc = crc;
}
/**
* Gets the CRC.
* @since Compress 1.7
*/
public long getCrcValue() {
return crc;
}
/**
* Sets the CRC.
* @since Compress 1.7
*/
public void setCrcValue(long crc) {
this.crc = crc;
}
/**
* Gets the compressed CRC.
* @deprecated use getCompressedCrcValue instead.
*/
@Deprecated
int getCompressedCrc() {
return (int) compressedCrc;
}
/**
* Sets the compressed CRC.
* @deprecated use setCompressedCrcValue instead.
*/
@Deprecated
void setCompressedCrc(int crc) {
this.compressedCrc = crc;
}
/**
* Gets the compressed CRC.
* @since Compress 1.7
*/
long getCompressedCrcValue() {
return compressedCrc;
}
/**
* Sets the compressed CRC.
* @since Compress 1.7
*/
void setCompressedCrcValue(long crc) {
this.compressedCrc = crc;
}
/**
* Get this entry's file size.
*
* @return This entry's file size.
*/
public long getSize() {
return size;
}
/**
* Set this entry's file size.
*
* @param size This entry's new file size.
*/
public void setSize(long size) {
this.size = size;
}
/**
* Get this entry's compressed file size.
*
* @return This entry's compressed file size.
*/
long getCompressedSize() {
return compressedSize;
}
/**
* Set this entry's compressed file size.
*
* @param size This entry's new compressed file size.
*/
void setCompressedSize(long size) {
this.compressedSize = size;
}
/**
* Sets the (compression) methods to use for entry's content - the
* default is LZMA2.
*
* <p>Currently only {@link SevenZMethod#COPY}, {@link
* SevenZMethod#LZMA2}, {@link SevenZMethod#BZIP2} and {@link
* SevenZMethod#DEFLATE} are supported.</p>
*
* <p>The methods will be consulted in iteration order to create
* the final output.</p>
*
* @since 1.8
*/
public void setContentMethods(Iterable<? extends SevenZMethodConfiguration> methods) {
if (methods != null) {
LinkedList<SevenZMethodConfiguration> l = new LinkedList<SevenZMethodConfiguration>();
for (SevenZMethodConfiguration m : methods) {
l.addLast(m);
}
contentMethods = Collections.unmodifiableList(l);
} else {
contentMethods = null;
}
}
/**
* Gets the (compression) methods to use for entry's content - the
* default is LZMA2.
*
* <p>Currently only {@link SevenZMethod#COPY}, {@link
* SevenZMethod#LZMA2}, {@link SevenZMethod#BZIP2} and {@link
* SevenZMethod#DEFLATE} are supported.</p>
*
* <p>The methods will be consulted in iteration order to create
* the final output.</p>
*
* @since 1.8
*/
public Iterable<? extends SevenZMethodConfiguration> getContentMethods() {
return contentMethods;
}
/**
* Converts NTFS time (100 nanosecond units since 1 January 1601)
* to Java time.
* @param ntfsTime the NTFS time in 100 nanosecond units
* @return the Java time
*/
public static Date ntfsTimeToJavaTime(final long ntfsTime) {
final Calendar ntfsEpoch = Calendar.getInstance();
ntfsEpoch.setTimeZone(TimeZone.getTimeZone("GMT+0"));
ntfsEpoch.set(1601, 0, 1, 0, 0, 0);
ntfsEpoch.set(Calendar.MILLISECOND, 0);
final long realTime = ntfsEpoch.getTimeInMillis() + (ntfsTime / (10*1000));
return new Date(realTime);
}
/**
* Converts Java time to NTFS time.
* @param date the Java time
* @return the NTFS time
*/
public static long javaTimeToNtfsTime(final Date date) {
final Calendar ntfsEpoch = Calendar.getInstance();
ntfsEpoch.setTimeZone(TimeZone.getTimeZone("GMT+0"));
ntfsEpoch.set(1601, 0, 1, 0, 0, 0);
ntfsEpoch.set(Calendar.MILLISECOND, 0);
return ((date.getTime() - ntfsEpoch.getTimeInMillis())* 1000 * 10);
}
}
|
src/main/java/org/apache/commons/compress/archivers/sevenz/SevenZArchiveEntry.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.commons.compress.archivers.sevenz;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.LinkedList;
import java.util.TimeZone;
import org.apache.commons.compress.archivers.ArchiveEntry;
/**
* An entry in a 7z archive.
*
* @NotThreadSafe
* @since 1.6
*/
public class SevenZArchiveEntry implements ArchiveEntry {
private String name;
private boolean hasStream;
private boolean isDirectory;
private boolean isAntiItem;
private boolean hasCreationDate;
private boolean hasLastModifiedDate;
private boolean hasAccessDate;
private long creationDate;
private long lastModifiedDate;
private long accessDate;
private boolean hasWindowsAttributes;
private int windowsAttributes;
private boolean hasCrc;
private long crc, compressedCrc;
private long size, compressedSize;
private Iterable<? extends SevenZMethodConfiguration> contentMethods;
public SevenZArchiveEntry() {
}
/**
* Get this entry's name.
*
* @return This entry's name.
*/
public String getName() {
return name;
}
/**
* Set this entry's name.
*
* @param name This entry's new name.
*/
public void setName(String name) {
this.name = name;
}
/**
* Whether there is any content associated with this entry.
* @return whether there is any content associated with this entry.
*/
public boolean hasStream() {
return hasStream;
}
/**
* Sets whether there is any content associated with this entry.
* @param hasStream whether there is any content associated with this entry.
*/
public void setHasStream(boolean hasStream) {
this.hasStream = hasStream;
}
/**
* Return whether or not this entry represents a directory.
*
* @return True if this entry is a directory.
*/
public boolean isDirectory() {
return isDirectory;
}
/**
* Sets whether or not this entry represents a directory.
*
* @param isDirectory True if this entry is a directory.
*/
public void setDirectory(boolean isDirectory) {
this.isDirectory = isDirectory;
}
/**
* Indicates whether this is an "anti-item" used in differential backups,
* meaning it should delete the same file from a previous backup.
* @return true if it is an anti-item, false otherwise
*/
public boolean isAntiItem() {
return isAntiItem;
}
/**
* Sets whether this is an "anti-item" used in differential backups,
* meaning it should delete the same file from a previous backup.
* @param isAntiItem true if it is an ait-item, false otherwise
*/
public void setAntiItem(boolean isAntiItem) {
this.isAntiItem = isAntiItem;
}
/**
* Returns whether this entry has got a creation date at all.
*/
public boolean getHasCreationDate() {
return hasCreationDate;
}
/**
* Sets whether this entry has got a creation date at all.
*/
public void setHasCreationDate(boolean hasCreationDate) {
this.hasCreationDate = hasCreationDate;
}
/**
* Gets the creation date.
* @throws UnsupportedOperationException if the entry hasn't got a
* creation date.
*/
public Date getCreationDate() {
if (hasCreationDate) {
return ntfsTimeToJavaTime(creationDate);
} else {
throw new UnsupportedOperationException(
"The entry doesn't have this timestamp");
}
}
/**
* Sets the creation date using NTFS time (100 nanosecond units
* since 1 January 1601)
*/
public void setCreationDate(long ntfsCreationDate) {
this.creationDate = ntfsCreationDate;
}
/**
* Sets the creation date,
*/
public void setCreationDate(Date creationDate) {
hasCreationDate = creationDate != null;
if (hasCreationDate) {
this.creationDate = javaTimeToNtfsTime(creationDate);
}
}
/**
* Returns whether this entry has got a last modified date at all.
*/
public boolean getHasLastModifiedDate() {
return hasLastModifiedDate;
}
/**
* Sets whether this entry has got a last modified date at all.
*/
public void setHasLastModifiedDate(boolean hasLastModifiedDate) {
this.hasLastModifiedDate = hasLastModifiedDate;
}
/**
* Gets the last modified date.
* @throws UnsupportedOperationException if the entry hasn't got a
* last modified date.
*/
public Date getLastModifiedDate() {
if (hasLastModifiedDate) {
return ntfsTimeToJavaTime(lastModifiedDate);
} else {
throw new UnsupportedOperationException(
"The entry doesn't have this timestamp");
}
}
/**
* Sets the last modified date using NTFS time (100 nanosecond
* units since 1 January 1601)
*/
public void setLastModifiedDate(long ntfsLastModifiedDate) {
this.lastModifiedDate = ntfsLastModifiedDate;
}
/**
* Sets the last modified date,
*/
public void setLastModifiedDate(Date lastModifiedDate) {
hasLastModifiedDate = lastModifiedDate != null;
if (hasLastModifiedDate) {
this.lastModifiedDate = javaTimeToNtfsTime(lastModifiedDate);
}
}
/**
* Returns whether this entry has got an access date at all.
*/
public boolean getHasAccessDate() {
return hasAccessDate;
}
/**
* Sets whether this entry has got an access date at all.
*/
public void setHasAccessDate(boolean hasAcessDate) {
this.hasAccessDate = hasAcessDate;
}
/**
* Gets the access date.
* @throws UnsupportedOperationException if the entry hasn't got a
* access date.
*/
public Date getAccessDate() {
if (hasAccessDate) {
return ntfsTimeToJavaTime(accessDate);
} else {
throw new UnsupportedOperationException(
"The entry doesn't have this timestamp");
}
}
/**
* Sets the access date using NTFS time (100 nanosecond units
* since 1 January 1601)
*/
public void setAccessDate(long ntfsAccessDate) {
this.accessDate = ntfsAccessDate;
}
/**
* Sets the access date,
*/
public void setAccessDate(Date accessDate) {
hasAccessDate = accessDate != null;
if (hasAccessDate) {
this.accessDate = javaTimeToNtfsTime(accessDate);
}
}
/**
* Returns whether this entry has windows attributes.
*/
public boolean getHasWindowsAttributes() {
return hasWindowsAttributes;
}
/**
* Sets whether this entry has windows attributes.
*/
public void setHasWindowsAttributes(boolean hasWindowsAttributes) {
this.hasWindowsAttributes = hasWindowsAttributes;
}
/**
* Gets the windows attributes.
*/
public int getWindowsAttributes() {
return windowsAttributes;
}
/**
* Sets the windows attributes.
*/
public void setWindowsAttributes(int windowsAttributes) {
this.windowsAttributes = windowsAttributes;
}
/**
* Returns whether this entry has got a crc.
*
* In general entries without streams don't have a CRC either.
*/
public boolean getHasCrc() {
return hasCrc;
}
/**
* Sets whether this entry has got a crc.
*/
public void setHasCrc(boolean hasCrc) {
this.hasCrc = hasCrc;
}
/**
* Gets the CRC.
* @deprecated use getCrcValue instead.
*/
@Deprecated
public int getCrc() {
return (int) crc;
}
/**
* Sets the CRC.
* @deprecated use setCrcValue instead.
*/
@Deprecated
public void setCrc(int crc) {
this.crc = crc;
}
/**
* Gets the CRC.
* @since Compress 1.7
*/
public long getCrcValue() {
return crc;
}
/**
* Sets the CRC.
* @since Compress 1.7
*/
public void setCrcValue(long crc) {
this.crc = crc;
}
/**
* Gets the compressed CRC.
* @deprecated use getCompressedCrcValue instead.
*/
@Deprecated
int getCompressedCrc() {
return (int) compressedCrc;
}
/**
* Sets the compressed CRC.
* @deprecated use setCompressedCrcValue instead.
*/
@Deprecated
void setCompressedCrc(int crc) {
this.compressedCrc = crc;
}
/**
* Gets the compressed CRC.
* @since Compress 1.7
*/
long getCompressedCrcValue() {
return compressedCrc;
}
/**
* Sets the compressed CRC.
* @since Compress 1.7
*/
void setCompressedCrcValue(long crc) {
this.compressedCrc = crc;
}
/**
* Get this entry's file size.
*
* @return This entry's file size.
*/
public long getSize() {
return size;
}
/**
* Set this entry's file size.
*
* @param size This entry's new file size.
*/
public void setSize(long size) {
this.size = size;
}
/**
* Get this entry's compressed file size.
*
* @return This entry's compressed file size.
*/
long getCompressedSize() {
return compressedSize;
}
/**
* Set this entry's compressed file size.
*
* @param size This entry's new compressed file size.
*/
void setCompressedSize(long size) {
this.compressedSize = size;
}
/**
* Sets the (compression) methods to use for entry's content - the
* default is LZMA2.
*
* <p>Currently only {@link SevenZMethod#COPY}, {@link
* SevenZMethod#LZMA2}, {@link SevenZMethod#BZIP2} and {@link
* SevenZMethod#DEFLATE} are supported.</p>
*
* <p>The methods will be consulted in iteration order to create
* the final output.</p>
*
* @since 1.8
*/
public void setContentMethods(Iterable<? extends SevenZMethodConfiguration> methods) {
LinkedList<SevenZMethodConfiguration> l = new LinkedList<SevenZMethodConfiguration>();
for (SevenZMethodConfiguration m : methods) {
l.addLast(m);
}
this.contentMethods = Collections.unmodifiableList(l);
}
/**
* Gets the (compression) methods to use for entry's content - the
* default is LZMA2.
*
* <p>Currently only {@link SevenZMethod#COPY}, {@link
* SevenZMethod#LZMA2}, {@link SevenZMethod#BZIP2} and {@link
* SevenZMethod#DEFLATE} are supported.</p>
*
* <p>The methods will be consulted in iteration order to create
* the final output.</p>
*
* @since 1.8
*/
public Iterable<? extends SevenZMethodConfiguration> getContentMethods() {
return contentMethods;
}
/**
* Converts NTFS time (100 nanosecond units since 1 January 1601)
* to Java time.
* @param ntfsTime the NTFS time in 100 nanosecond units
* @return the Java time
*/
public static Date ntfsTimeToJavaTime(final long ntfsTime) {
final Calendar ntfsEpoch = Calendar.getInstance();
ntfsEpoch.setTimeZone(TimeZone.getTimeZone("GMT+0"));
ntfsEpoch.set(1601, 0, 1, 0, 0, 0);
ntfsEpoch.set(Calendar.MILLISECOND, 0);
final long realTime = ntfsEpoch.getTimeInMillis() + (ntfsTime / (10*1000));
return new Date(realTime);
}
/**
* Converts Java time to NTFS time.
* @param date the Java time
* @return the NTFS time
*/
public static long javaTimeToNtfsTime(final Date date) {
final Calendar ntfsEpoch = Calendar.getInstance();
ntfsEpoch.setTimeZone(TimeZone.getTimeZone("GMT+0"));
ntfsEpoch.set(1601, 0, 1, 0, 0, 0);
ntfsEpoch.set(Calendar.MILLISECOND, 0);
return ((date.getTime() - ntfsEpoch.getTimeInMillis())* 1000 * 10);
}
}
|
COMPRESS-261 allow the per-entry methods to be set to null explicitly
git-svn-id: fb13a56e2874bbe7f090676f40e1dce4dcf67111@1571925 13f79535-47bb-0310-9956-ffa450edef68
|
src/main/java/org/apache/commons/compress/archivers/sevenz/SevenZArchiveEntry.java
|
COMPRESS-261 allow the per-entry methods to be set to null explicitly
|
<ide><path>rc/main/java/org/apache/commons/compress/archivers/sevenz/SevenZArchiveEntry.java
<ide> * @since 1.8
<ide> */
<ide> public void setContentMethods(Iterable<? extends SevenZMethodConfiguration> methods) {
<del> LinkedList<SevenZMethodConfiguration> l = new LinkedList<SevenZMethodConfiguration>();
<del> for (SevenZMethodConfiguration m : methods) {
<del> l.addLast(m);
<del> }
<del> this.contentMethods = Collections.unmodifiableList(l);
<add> if (methods != null) {
<add> LinkedList<SevenZMethodConfiguration> l = new LinkedList<SevenZMethodConfiguration>();
<add> for (SevenZMethodConfiguration m : methods) {
<add> l.addLast(m);
<add> }
<add> contentMethods = Collections.unmodifiableList(l);
<add> } else {
<add> contentMethods = null;
<add> }
<ide> }
<ide>
<ide> /**
|
|
Java
|
apache-2.0
|
cb0863b3571bcdd3802db62e8e346fa7b3f2e823
| 0 |
Jonathan727/javarosa,Jonathan727/javarosa,Jonathan727/javarosa
|
/*
* Copyright (C) 2009 JavaRosa-Core Project
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.javarosa.xpath.expr;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;
import org.javarosa.core.model.IFormDataModel;
import org.javarosa.core.model.condition.EvaluationContext;
import org.javarosa.core.model.condition.IFunctionHandler;
import org.javarosa.core.model.instance.TreeReference;
import org.javarosa.core.model.utils.DateUtils;
import org.javarosa.core.util.externalizable.DeserializationException;
import org.javarosa.core.util.externalizable.ExtUtil;
import org.javarosa.core.util.externalizable.ExtWrapListPoly;
import org.javarosa.core.util.externalizable.PrototypeFactory;
import org.javarosa.xpath.IExprDataType;
import org.javarosa.xpath.XPathTypeMismatchException;
import org.javarosa.xpath.XPathUnhandledException;
public class XPathFuncExpr extends XPathExpression {
public XPathQName id;
public XPathExpression[] args;
public XPathFuncExpr () { } //for deserialization
public XPathFuncExpr (XPathQName id, XPathExpression[] args) {
this.id = id;
this.args = args;
}
public String toString () {
StringBuffer sb = new StringBuffer();
sb.append("{func-expr:");
sb.append(id.toString());
sb.append(",{");
for (int i = 0; i < args.length; i++) {
sb.append(args[i].toString());
if (i < args.length - 1)
sb.append(",");
}
sb.append("}}");
return sb.toString();
}
public boolean equals (Object o) {
if (o instanceof XPathFuncExpr) {
XPathFuncExpr x = (XPathFuncExpr)o;
Vector a = new Vector();
for (int i = 0; i < args.length; i++)
a.addElement(args[i]);
Vector b = new Vector();
for (int i = 0; i < x.args.length; i++)
b.addElement(x.args[i]);
return id.equals(x.id) && ExtUtil.vectorEquals(a, b);
} else {
return false;
}
}
public void readExternal(DataInputStream in, PrototypeFactory pf) throws IOException, DeserializationException {
id = (XPathQName)ExtUtil.read(in, XPathQName.class);
Vector v = (Vector)ExtUtil.read(in, new ExtWrapListPoly(), pf);
args = new XPathExpression[v.size()];
for (int i = 0; i < args.length; i++)
args[i] = (XPathExpression)v.elementAt(i);
}
public void writeExternal(DataOutputStream out) throws IOException {
Vector v = new Vector();
for (int i = 0; i < args.length; i++)
v.addElement(args[i]);
ExtUtil.write(out, id);
ExtUtil.write(out, new ExtWrapListPoly(v));
}
public Object eval (IFormDataModel model, EvaluationContext evalContext) {
String name = id.toString();
Object[] argVals = new Object[args.length];
Hashtable funcHandlers = evalContext.getFunctionHandlers();
for (int i = 0; i < args.length; i++) {
argVals[i] = args[i].eval(model, evalContext);
}
if (name.equals("true") && args.length == 0) {
return Boolean.TRUE;
} else if (name.equals("false") && args.length == 0) {
return Boolean.FALSE;
} else if (name.equals("boolean") && args.length == 1) {
return toBoolean(argVals[0]);
} else if (name.equals("number") && args.length == 1) {
return toNumeric(argVals[0]);
} else if (name.equals("string") && args.length == 1) {
return toString(argVals[0]);
} else if (name.equals("date") && args.length == 1) { //non-standard
return toDate(argVals[0]);
} else if (name.equals("not") && args.length == 1) {
return boolNot(argVals[0]);
} else if (name.equals("boolean-from-string") && args.length == 1) {
return boolStr(argVals[0]);
} else if (name.equals("if") && args.length == 3) { //non-standard
return ifThenElse(argVals[0], argVals[1], argVals[2]);
} else if ((name.equals("selected") || name.equals("is-selected")) && args.length == 2) { //non-standard
return multiSelected(argVals[0], argVals[1]);
} else if (name.equals("count-selected") && args.length == 1) { //non-standard
return countSelected(argVals[0]);
} else if (name.equals("count") && args.length == 1) {
return count(argVals[0]);
} else if (name.equals("sum") && args.length == 1) {
return sum(model, argVals[0]);
} else if (name.equals("today") && args.length == 0) {
return DateUtils.roundDate(new Date());
} else if (name.equals("now") && args.length == 0) {
return new Date();
} else if (name.equals("concat")) {
return concat(argVals);
} else if (name.equals("checklist") && args.length >= 2) { //non-standard
return checklist(argVals);
} else if (name.equals("weighted-checklist") && args.length >= 2 && args.length % 2 == 0) { //non-standard
return checklistWeighted(argVals);
} else {
IFunctionHandler handler = (IFunctionHandler)funcHandlers.get(name);
if (handler != null) {
return evalCustomFunction(handler, argVals);
} else {
throw new XPathUnhandledException("function \'" + name + "\'");
}
}
}
private Object evalCustomFunction (IFunctionHandler handler, Object[] args) {
Vector prototypes = handler.getPrototypes();
Enumeration e = prototypes.elements();
Object[] typedArgs = null;
while (typedArgs == null && e.hasMoreElements()) {
typedArgs = matchPrototype(args, (Class[])e.nextElement());
}
if (typedArgs != null) {
return handler.eval(typedArgs);
} else if (handler.rawArgs()) {
return handler.eval(args);
} else {
throw new XPathTypeMismatchException("for function \'" + handler.getName() + "\'");
}
}
private Object[] matchPrototype (Object[] args, Class[] prototype) {
Object[] typed = null;
if (prototype.length == args.length) {
typed = new Object[args.length];
for (int i = 0; i < prototype.length; i++) {
typed[i] = null;
//how to handle type conversions of custom types?
if (prototype[i].isAssignableFrom(args[i].getClass())) {
typed[i] = args[i];
} else {
try {
if (prototype[i] == Boolean.class) {
typed[i] = toBoolean(args[i]);
} else if (prototype[i] == Double.class) {
typed[i] = toNumeric(args[i]);
} else if (prototype[i] == String.class) {
typed[i] = toString(args[i]);
} else if (prototype[i] == Date.class) {
typed[i] = toDate(args[i]);
}
} catch (XPathTypeMismatchException xptme) { /* swallow type mismatch exception */ }
}
if (typed[i] == null)
return null;
}
}
return typed;
}
public static Boolean toBoolean (Object o) {
Boolean val = null;
if (o instanceof Boolean) {
val = (Boolean)o;
} else if (o instanceof Double) {
double d = ((Double)o).doubleValue();
val = new Boolean(Math.abs(d) > 1.0e-12 && !Double.isNaN(d));
} else if (o instanceof String) {
String s = (String)o;
val = new Boolean(s.length() > 0);
} else if (o instanceof Vector) {
return new Boolean(count(o).doubleValue() > 0);
} else if (o instanceof IExprDataType) {
val = ((IExprDataType)o).toBoolean();
}
if (val != null) {
return val;
} else {
throw new XPathTypeMismatchException("converting to boolean");
}
}
//a - b * floor(a / b)
private static long modLongNotSuck (long a, long b) {
return ((a % b) + b) % b;
}
private static long divLongNotSuck (long a, long b) {
return (a - modLongNotSuck(a, b)) / b;
}
public static Double toNumeric (Object o) {
Double val = null;
if (o instanceof Boolean) {
val = new Double(((Boolean)o).booleanValue() ? 1 : 0);
} else if (o instanceof Double) {
val = (Double)o;
} else if (o instanceof String) {
/* annoying, but the xpath spec doesn't recognize scientific notation, or +/-Infinity
* when converting a string to a number
*/
String s = (String)o;
double d;
try {
s = s.trim();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c != '-' && c != '.' && (c < '0' || c > '9'))
throw new NumberFormatException();
}
d = Double.parseDouble(s);
val = new Double(d);
} catch (NumberFormatException nfe) {
val = new Double(Double.NaN);
}
} else if (o instanceof Date) {
val = new Double(divLongNotSuck(
DateUtils.roundDate((Date)o).getTime() - DateUtils.getDate(1970, 1, 1).getTime() + 43200000l,
86400000l)); //43200000 offset (0.5 day in ms) is needed to handle differing DST offsets!
} else if (o instanceof IExprDataType) {
val = ((IExprDataType)o).toNumeric();
}
if (val != null) {
return val;
} else {
throw new XPathTypeMismatchException("converting to numeric");
}
}
public static String toString (Object o) {
String val = null;
if (o instanceof Boolean) {
val = (((Boolean)o).booleanValue() ? "true" : "false");
} else if (o instanceof Double) {
double d = ((Double)o).doubleValue();
if (Double.isNaN(d)) {
val = "NaN";
} else if (Math.abs(d) < 1.0e-12) {
val = "0";
} else if (Double.isInfinite(d)) {
val = (d < 0 ? "-" : "") + "Infinity";
} else if (Math.abs(d - (int)d) < 1.0e-12) {
val = String.valueOf((int)d);
} else {
val = String.valueOf(d);
}
} else if (o instanceof String) {
val = (String)o;
} else if (o instanceof Date) {
val = DateUtils.formatDate((Date)o, DateUtils.FORMAT_ISO8601);
} else if (o instanceof IExprDataType) {
val = ((IExprDataType)o).toString();
}
if (val != null) {
return val;
} else {
throw new XPathTypeMismatchException("converting to string");
}
}
public static Date toDate (Object o) {
if (o instanceof Double) {
double d = ((Double)o).doubleValue();
if (Math.abs(d - (int)d) > 1.0e-12) {
throw new XPathTypeMismatchException("converting non-integer to date");
}
Date dt = DateUtils.getDate(1970, 1, 1);
dt.setTime(dt.getTime() + (long)d * 86400000l + 43200000l); //43200000 offset (0.5 day in ms) is needed to handle differing DST offsets!
return DateUtils.roundDate(dt);
} else if (o instanceof String) {
Date d = DateUtils.parseDate((String)o);
if (d == null) {
throw new XPathTypeMismatchException("converting to date");
} else {
return d;
}
} else if (o instanceof Date) {
return DateUtils.roundDate((Date)o);
} else {
throw new XPathTypeMismatchException("converting to date");
}
}
public static Boolean boolNot (Object o) {
boolean b = toBoolean(o).booleanValue();
return new Boolean(!b);
}
public static Boolean boolStr (Object o) {
String s = toString(o);
if (s.equalsIgnoreCase("true") || s.equals("1"))
return Boolean.TRUE;
else
return Boolean.FALSE;
}
public static Object ifThenElse (Object o1, Object o2, Object o3) {
boolean b = toBoolean(o1).booleanValue();
return (b ? o2 : o3);
}
//return whether a particular choice of a multi-select is selected
//arg1: XML-serialized answer to multi-select question (space-delimited choice values)
//arg2: choice to look for
public static Boolean multiSelected (Object o1, Object o2) {
String s1 = (String)o1;
String s2 = ((String)o2).trim();
return new Boolean((" " + s1 + " ").indexOf(" " + s2 + " ") != -1);
}
public static Double countSelected (Object o) {
String s = (String)o;
return new Double(DateUtils.split(s, " ", true).size());
}
public static Double count (Object o) {
if (o instanceof Vector) {
return new Double(((Vector)o).size());
} else {
throw new XPathTypeMismatchException("not a nodeset");
}
}
public static Double sum (IFormDataModel model, Object o) {
if (o instanceof Vector) {
Vector v = (Vector)o;
double sum = 0.0;
for (int i = 0; i < v.size(); i++) {
TreeReference ref = (TreeReference)v.elementAt(i);
sum += toNumeric(XPathPathExpr.getRefValue(model, ref)).doubleValue();
}
return new Double(sum);
} else {
throw new XPathTypeMismatchException("not a nodeset");
}
}
public static String concat (Object[] argVals) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < argVals.length; i++) {
sb.append(toString(argVals[i]));
}
return sb.toString();
}
/*
* arg_0 = min, negative if no min
* arg_1 = max, negative if no max
* arg_2 .. arg_n = true/false values
*
* returns: true if the number of true values is between min and max
*/
public static Boolean checklist (Object[] argVals) {
int min = toNumeric(argVals[0]).intValue();
int max = toNumeric(argVals[1]).intValue();
int count = 0;
for (int i = 2; i < argVals.length; i++) {
if (toBoolean(argVals[i]).booleanValue())
count++;
}
return new Boolean((min < 0 || count >= min) && (max < 0 || count <= max));
}
/*
* arg_0 = min
* arg_1 = max
* arg_2, arg_4, arg_6, ... arg_(n - 1) = true/false values
* arg_3, arg_5, arg_7, ... arg_n = floating point weights corresponding to arg_(i - 1)
*
* returns: true if the sum of the weights corresponding to the true values is between min and max
*/
public static Boolean checklistWeighted (Object[] argVals) {
double min = toNumeric(argVals[0]).doubleValue();
double max = toNumeric(argVals[1]).doubleValue();
double sum = 0.;
for (int i = 2; i < argVals.length; i += 2) {
boolean flag = toBoolean(argVals[i]).booleanValue();
double weight = toNumeric(argVals[i + 1]).doubleValue();
if (flag)
sum += weight;
}
return new Boolean(sum >= min && sum <= max);
}
}
|
javarosa/org.javarosa.xform/src/org/javarosa/xpath/expr/XPathFuncExpr.java
|
/*
* Copyright (C) 2009 JavaRosa-Core Project
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.javarosa.xpath.expr;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;
import org.javarosa.core.model.IFormDataModel;
import org.javarosa.core.model.condition.EvaluationContext;
import org.javarosa.core.model.condition.IFunctionHandler;
import org.javarosa.core.model.instance.TreeReference;
import org.javarosa.core.model.utils.DateUtils;
import org.javarosa.core.util.externalizable.DeserializationException;
import org.javarosa.core.util.externalizable.ExtUtil;
import org.javarosa.core.util.externalizable.ExtWrapListPoly;
import org.javarosa.core.util.externalizable.PrototypeFactory;
import org.javarosa.xpath.IExprDataType;
import org.javarosa.xpath.XPathTypeMismatchException;
import org.javarosa.xpath.XPathUnhandledException;
public class XPathFuncExpr extends XPathExpression {
public XPathQName id;
public XPathExpression[] args;
public XPathFuncExpr () { } //for deserialization
public XPathFuncExpr (XPathQName id, XPathExpression[] args) {
this.id = id;
this.args = args;
}
public String toString () {
StringBuffer sb = new StringBuffer();
sb.append("{func-expr:");
sb.append(id.toString());
sb.append(",{");
for (int i = 0; i < args.length; i++) {
sb.append(args[i].toString());
if (i < args.length - 1)
sb.append(",");
}
sb.append("}}");
return sb.toString();
}
public boolean equals (Object o) {
if (o instanceof XPathFuncExpr) {
XPathFuncExpr x = (XPathFuncExpr)o;
Vector a = new Vector();
for (int i = 0; i < args.length; i++)
a.addElement(args[i]);
Vector b = new Vector();
for (int i = 0; i < x.args.length; i++)
b.addElement(x.args[i]);
return id.equals(x.id) && ExtUtil.vectorEquals(a, b);
} else {
return false;
}
}
public void readExternal(DataInputStream in, PrototypeFactory pf) throws IOException, DeserializationException {
id = (XPathQName)ExtUtil.read(in, XPathQName.class);
Vector v = (Vector)ExtUtil.read(in, new ExtWrapListPoly(), pf);
args = new XPathExpression[v.size()];
for (int i = 0; i < args.length; i++)
args[i] = (XPathExpression)v.elementAt(i);
}
public void writeExternal(DataOutputStream out) throws IOException {
Vector v = new Vector();
for (int i = 0; i < args.length; i++)
v.addElement(args[i]);
ExtUtil.write(out, id);
ExtUtil.write(out, new ExtWrapListPoly(v));
}
public Object eval (IFormDataModel model, EvaluationContext evalContext) {
String name = id.toString();
Object[] argVals = new Object[args.length];
Hashtable funcHandlers = evalContext.getFunctionHandlers();
for (int i = 0; i < args.length; i++) {
argVals[i] = args[i].eval(model, evalContext);
}
if (name.equals("true") && args.length == 0) {
return Boolean.TRUE;
} else if (name.equals("false") && args.length == 0) {
return Boolean.FALSE;
} else if (name.equals("boolean") && args.length == 1) {
return toBoolean(argVals[0]);
} else if (name.equals("number") && args.length == 1) {
return toNumeric(argVals[0]);
} else if (name.equals("string") && args.length == 1) {
return toString(argVals[0]);
} else if (name.equals("date") && args.length == 1) { //non-standard
return toDate(argVals[0]);
} else if (name.equals("not") && args.length == 1) {
return boolNot(argVals[0]);
} else if (name.equals("boolean-from-string") && args.length == 1) {
return boolStr(argVals[0]);
} else if (name.equals("if") && args.length == 3) { //non-standard
return ifThenElse(argVals[0], argVals[1], argVals[2]);
} else if ((name.equals("selected") || name.equals("is-selected")) && args.length == 2) { //non-standard
return multiSelected(argVals[0], argVals[1]);
} else if (name.equals("count-selected") && args.length == 1) { //non-standard
return countSelected(argVals[0]);
} else if (name.equals("count") && args.length == 1) {
return count(argVals[0]);
} else if (name.equals("sum") && args.length == 1) {
return sum(model, argVals[0]);
} else if (name.equals("today") && args.length == 0) {
return DateUtils.roundDate(new Date());
} else if (name.equals("now") && args.length == 0) {
return new Date();
} else if (name.equals("checklist") && args.length >= 2) { //non-standard
return checklist(argVals);
} else if (name.equals("weighted-checklist") && args.length >= 2 && args.length % 2 == 0) { //non-standard
return checklistWeighted(argVals);
} else {
IFunctionHandler handler = (IFunctionHandler)funcHandlers.get(name);
if (handler != null) {
return evalCustomFunction(handler, argVals);
} else {
throw new XPathUnhandledException("function \'" + name + "\'");
}
}
}
private Object evalCustomFunction (IFunctionHandler handler, Object[] args) {
Vector prototypes = handler.getPrototypes();
Enumeration e = prototypes.elements();
Object[] typedArgs = null;
while (typedArgs == null && e.hasMoreElements()) {
typedArgs = matchPrototype(args, (Class[])e.nextElement());
}
if (typedArgs != null) {
return handler.eval(typedArgs);
} else if (handler.rawArgs()) {
return handler.eval(args);
} else {
throw new XPathTypeMismatchException("for function \'" + handler.getName() + "\'");
}
}
private Object[] matchPrototype (Object[] args, Class[] prototype) {
Object[] typed = null;
if (prototype.length == args.length) {
typed = new Object[args.length];
for (int i = 0; i < prototype.length; i++) {
typed[i] = null;
//how to handle type conversions of custom types?
if (prototype[i].isAssignableFrom(args[i].getClass())) {
typed[i] = args[i];
} else {
try {
if (prototype[i] == Boolean.class) {
typed[i] = toBoolean(args[i]);
} else if (prototype[i] == Double.class) {
typed[i] = toNumeric(args[i]);
} else if (prototype[i] == String.class) {
typed[i] = toString(args[i]);
} else if (prototype[i] == Date.class) {
typed[i] = toDate(args[i]);
}
} catch (XPathTypeMismatchException xptme) { /* swallow type mismatch exception */ }
}
if (typed[i] == null)
return null;
}
}
return typed;
}
public static Boolean toBoolean (Object o) {
Boolean val = null;
if (o instanceof Boolean) {
val = (Boolean)o;
} else if (o instanceof Double) {
double d = ((Double)o).doubleValue();
val = new Boolean(Math.abs(d) > 1.0e-12 && !Double.isNaN(d));
} else if (o instanceof String) {
String s = (String)o;
val = new Boolean(s.length() > 0);
} else if (o instanceof Vector) {
return new Boolean(count(o).doubleValue() > 0);
} else if (o instanceof IExprDataType) {
val = ((IExprDataType)o).toBoolean();
}
if (val != null) {
return val;
} else {
throw new XPathTypeMismatchException("converting to boolean");
}
}
//a - b * floor(a / b)
private static long modLongNotSuck (long a, long b) {
return ((a % b) + b) % b;
}
private static long divLongNotSuck (long a, long b) {
return (a - modLongNotSuck(a, b)) / b;
}
public static Double toNumeric (Object o) {
Double val = null;
if (o instanceof Boolean) {
val = new Double(((Boolean)o).booleanValue() ? 1 : 0);
} else if (o instanceof Double) {
val = (Double)o;
} else if (o instanceof String) {
/* annoying, but the xpath spec doesn't recognize scientific notation, or +/-Infinity
* when converting a string to a number
*/
String s = (String)o;
double d;
try {
s = s.trim();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c != '-' && c != '.' && (c < '0' || c > '9'))
throw new NumberFormatException();
}
d = Double.parseDouble(s);
val = new Double(d);
} catch (NumberFormatException nfe) {
val = new Double(Double.NaN);
}
} else if (o instanceof Date) {
val = new Double(divLongNotSuck(
DateUtils.roundDate((Date)o).getTime() - DateUtils.getDate(1970, 1, 1).getTime() + 43200000l,
86400000l)); //43200000 offset (0.5 day in ms) is needed to handle differing DST offsets!
} else if (o instanceof IExprDataType) {
val = ((IExprDataType)o).toNumeric();
}
if (val != null) {
return val;
} else {
throw new XPathTypeMismatchException("converting to numeric");
}
}
public static String toString (Object o) {
String val = null;
if (o instanceof Boolean) {
val = (((Boolean)o).booleanValue() ? "true" : "false");
} else if (o instanceof Double) {
double d = ((Double)o).doubleValue();
if (Double.isNaN(d)) {
val = "NaN";
} else if (Math.abs(d) < 1.0e-12) {
val = "0";
} else if (Double.isInfinite(d)) {
val = (d < 0 ? "-" : "") + "Infinity";
} else if (Math.abs(d - (int)d) < 1.0e-12) {
val = String.valueOf((int)d);
} else {
val = String.valueOf(d);
}
} else if (o instanceof String) {
val = (String)o;
} else if (o instanceof Date) {
val = DateUtils.formatDate((Date)o, DateUtils.FORMAT_ISO8601);
} else if (o instanceof IExprDataType) {
val = ((IExprDataType)o).toString();
}
if (val != null) {
return val;
} else {
throw new XPathTypeMismatchException("converting to string");
}
}
public static Date toDate (Object o) {
if (o instanceof Double) {
double d = ((Double)o).doubleValue();
if (Math.abs(d - (int)d) > 1.0e-12) {
throw new XPathTypeMismatchException("converting non-integer to date");
}
Date dt = DateUtils.getDate(1970, 1, 1);
dt.setTime(dt.getTime() + (long)d * 86400000l + 43200000l); //43200000 offset (0.5 day in ms) is needed to handle differing DST offsets!
return DateUtils.roundDate(dt);
} else if (o instanceof String) {
Date d = DateUtils.parseDate((String)o);
if (d == null) {
throw new XPathTypeMismatchException("converting to date");
} else {
return d;
}
} else if (o instanceof Date) {
return DateUtils.roundDate((Date)o);
} else {
throw new XPathTypeMismatchException("converting to date");
}
}
public static Boolean boolNot (Object o) {
boolean b = toBoolean(o).booleanValue();
return new Boolean(!b);
}
public static Boolean boolStr (Object o) {
String s = toString(o);
if (s.equalsIgnoreCase("true") || s.equals("1"))
return Boolean.TRUE;
else
return Boolean.FALSE;
}
public static Object ifThenElse (Object o1, Object o2, Object o3) {
boolean b = toBoolean(o1).booleanValue();
return (b ? o2 : o3);
}
//return whether a particular choice of a multi-select is selected
//arg1: XML-serialized answer to multi-select question (space-delimited choice values)
//arg2: choice to look for
public static Boolean multiSelected (Object o1, Object o2) {
String s1 = (String)o1;
String s2 = ((String)o2).trim();
return new Boolean((" " + s1 + " ").indexOf(" " + s2 + " ") != -1);
}
public static Double countSelected (Object o) {
String s = (String)o;
return new Double(DateUtils.split(s, " ", true).size());
}
public static Double count (Object o) {
if (o instanceof Vector) {
return new Double(((Vector)o).size());
} else {
throw new XPathTypeMismatchException("not a nodeset");
}
}
public static Double sum (IFormDataModel model, Object o) {
if (o instanceof Vector) {
Vector v = (Vector)o;
double sum = 0.0;
for (int i = 0; i < v.size(); i++) {
TreeReference ref = (TreeReference)v.elementAt(i);
sum += toNumeric(XPathPathExpr.getRefValue(model, ref)).doubleValue();
}
return new Double(sum);
} else {
throw new XPathTypeMismatchException("not a nodeset");
}
}
/*
* arg_0 = min, negative if no min
* arg_1 = max, negative if no max
* arg_2 .. arg_n = true/false values
*
* returns: true if the number of true values is between min and max
*/
public static Boolean checklist (Object[] argVals) {
int min = toNumeric(argVals[0]).intValue();
int max = toNumeric(argVals[1]).intValue();
int count = 0;
for (int i = 2; i < argVals.length; i++) {
if (toBoolean(argVals[i]).booleanValue())
count++;
}
return new Boolean((min < 0 || count >= min) && (max < 0 || count <= max));
}
/*
* arg_0 = min
* arg_1 = max
* arg_2, arg_4, arg_6, ... arg_(n - 1) = true/false values
* arg_3, arg_5, arg_7, ... arg_n = floating point weights corresponding to arg_(i - 1)
*
* returns: true if the sum of the weights corresponding to the true values is between min and max
*/
public static Boolean checklistWeighted (Object[] argVals) {
double min = toNumeric(argVals[0]).doubleValue();
double max = toNumeric(argVals[1]).doubleValue();
double sum = 0.;
for (int i = 2; i < argVals.length; i += 2) {
boolean flag = toBoolean(argVals[i]).booleanValue();
double weight = toNumeric(argVals[i + 1]).doubleValue();
if (flag)
sum += weight;
}
return new Boolean(sum >= min && sum <= max);
}
}
|
[r2527] add concat xpath function
|
javarosa/org.javarosa.xform/src/org/javarosa/xpath/expr/XPathFuncExpr.java
|
[r2527] add concat xpath function
|
<ide><path>avarosa/org.javarosa.xform/src/org/javarosa/xpath/expr/XPathFuncExpr.java
<ide> return DateUtils.roundDate(new Date());
<ide> } else if (name.equals("now") && args.length == 0) {
<ide> return new Date();
<add> } else if (name.equals("concat")) {
<add> return concat(argVals);
<ide> } else if (name.equals("checklist") && args.length >= 2) { //non-standard
<ide> return checklist(argVals);
<ide> } else if (name.equals("weighted-checklist") && args.length >= 2 && args.length % 2 == 0) { //non-standard
<ide> }
<ide> }
<ide>
<add> public static String concat (Object[] argVals) {
<add> StringBuffer sb = new StringBuffer();
<add>
<add> for (int i = 0; i < argVals.length; i++) {
<add> sb.append(toString(argVals[i]));
<add> }
<add>
<add> return sb.toString();
<add> }
<add>
<ide> /*
<ide> * arg_0 = min, negative if no min
<ide> * arg_1 = max, negative if no max
|
|
Java
|
apache-2.0
|
84193ee4c23b68fc0ba31f0ece98b902a8ee8825
| 0 |
smathieu/librarian_sample_repo_java,qos-ch/reload4j,smathieu/librarian_sample_repo_java,qos-ch/reload4j,qos-ch/reload4j
|
/*
* Copyright 1999-2005 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.log4j;
import java.io.IOException;
import java.io.OutputStream;
import org.apache.log4j.helpers.LogLog;
/**
* ConsoleAppender appends log events to <code>System.out</code> or
* <code>System.err</code> using a layout specified by the user. The
* default target is <code>System.out</code>.
*
* @author Ceki Gülcü
* @author Curt Arnold
* @since 1.1 */
public class ConsoleAppender extends WriterAppender {
public static final String SYSTEM_OUT = "System.out";
public static final String SYSTEM_ERR = "System.err";
protected String target = SYSTEM_OUT;
/**
* Determines if the appender honors reassignments of System.out
* or System.err made after configuration.
*/
private boolean honorReassignment = false;
/**
* Constructs an unconfigured appender.
*/
public ConsoleAppender() {
}
/**
* Creates a configured appender.
*
* @param layout layout, may not be null.
*/
public ConsoleAppender(Layout layout) {
this(layout, SYSTEM_OUT);
}
/**
* Creates a configured appender.
* @param layout layout, may not be null.
* @param targetStr target, either "System.err" or "System.out".
*/
public ConsoleAppender(Layout layout, String target) {
setLayout(layout);
setTarget(target);
activateOptions();
}
/**
* Sets the value of the <b>Target</b> option. Recognized values
* are "System.out" and "System.err". Any other value will be
* ignored.
* */
public
void setTarget(String value) {
String v = value.trim();
if (SYSTEM_OUT.equalsIgnoreCase(v)) {
target = SYSTEM_OUT;
} else if (SYSTEM_ERR.equalsIgnoreCase(v)) {
target = SYSTEM_ERR;
} else {
targetWarn(value);
}
}
/**
* Returns the current value of the <b>Target</b> property. The
* default value of the option is "System.out".
*
* See also {@link #setTarget}.
* */
public
String getTarget() {
return target;
}
/**
* Sets whether the appender honors reassignments of System.out
* or System.err made after configuration.
* @param newValue if true, appender will use value of System.out or
* System.err in force at the time when logging events are appended.
* @since 1.2.13
*/
public final void setHonorReassignment(final boolean newValue) {
honorReassignment = newValue;
}
/**
* Gets whether the appender honors reassignments of System.out
* or System.err made after configuration.
* @return true if appender will use value of System.out or
* System.err in force at the time when logging events are appended.
* @since 1.2.13
*/
public final boolean getHonorReassignment() {
return honorReassignment;
}
void targetWarn(String val) {
LogLog.warn("["+val+"] should be System.out or System.err.");
LogLog.warn("Using previously set target, System.out by default.");
}
/**
* Prepares the appender for use.
*/
public void activateOptions() {
if (honorReassignment) {
if (target.equals(SYSTEM_ERR)) {
setWriter(createWriter(new SystemErrStream()));
} else {
setWriter(createWriter(new SystemOutStream()));
}
} else {
if (target.equals(SYSTEM_ERR)) {
setWriter(createWriter(System.err));
} else {
setWriter(createWriter(System.out));
}
}
super.activateOptions();
}
/**
* {@inheritDoc}
*/
protected
final
void closeWriter() {
if (honorReassignment) {
super.closeWriter();
}
}
/**
* An implementation of OutputStream that redirects to the
* current System.err.
*
*/
private static class SystemErrStream extends OutputStream {
public SystemErrStream() {
}
public void close() {
}
public void flush() {
System.err.flush();
}
public void write(final byte[] b) throws IOException {
System.err.write(b);
}
public void write(final byte[] b, final int off, final int len)
throws IOException {
System.err.write(b, off, len);
}
public void write(final int b) throws IOException {
System.err.write(b);
}
}
/**
* An implementation of OutputStream that redirects to the
* current System.out.
*
*/
private static class SystemOutStream extends OutputStream {
public SystemOutStream() {
}
public void close() {
}
public void flush() {
System.out.flush();
}
public void write(final byte[] b) throws IOException {
System.out.write(b);
}
public void write(final byte[] b, final int off, final int len)
throws IOException {
System.out.write(b, off, len);
}
public void write(final int b) throws IOException {
System.out.write(b);
}
}
}
|
src/java/org/apache/log4j/ConsoleAppender.java
|
/*
* Copyright 1999-2005 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.log4j;
import java.io.IOException;
import java.io.OutputStream;
import org.apache.log4j.helpers.LogLog;
/**
* ConsoleAppender appends log events to <code>System.out</code> or
* <code>System.err</code> using a layout specified by the user. The
* default target is <code>System.out</code>.
*
* @author Ceki Gülcü
* @author Curt Arnold
* @since 1.1 */
public class ConsoleAppender extends WriterAppender {
public static final String SYSTEM_OUT = "System.out";
public static final String SYSTEM_ERR = "System.err";
protected String target = SYSTEM_OUT;
/**
* Constructs an unconfigured appender.
*/
public ConsoleAppender() {
}
/**
* Creates a configured appender.
*
* @param layout layout, may not be null.
*/
public ConsoleAppender(Layout layout) {
this(layout, SYSTEM_OUT);
}
/**
* Creates a configured appender.
* @param layout layout, may not be null.
* @param targetStr target, either "System.err" or "System.out".
*/
public ConsoleAppender(Layout layout, String target) {
setLayout(layout);
setTarget(target);
activateOptions();
}
/**
* Sets the value of the <b>Target</b> option. Recognized values
* are "System.out" and "System.err". Any other value will be
* ignored.
* */
public
void setTarget(String value) {
String v = value.trim();
if (SYSTEM_OUT.equalsIgnoreCase(v)) {
target = SYSTEM_OUT;
} else if (SYSTEM_ERR.equalsIgnoreCase(v)) {
target = SYSTEM_ERR;
} else {
targetWarn(value);
}
}
/**
* Returns the current value of the <b>Target</b> property. The
* default value of the option is "System.out".
*
* See also {@link #setTarget}.
* */
public
String getTarget() {
return target;
}
void targetWarn(String val) {
LogLog.warn("["+val+"] should be System.out or System.err.");
LogLog.warn("Using previously set target, System.out by default.");
}
/**
* Prepares the appender for use.
*/
public void activateOptions() {
if (target.equals(SYSTEM_ERR)) {
setWriter(createWriter(new SystemErrStream()));
} else {
setWriter(createWriter(new SystemOutStream()));
}
super.activateOptions();
}
/**
* {@inheritDoc}
*/
protected
final
void closeWriter() {
super.closeWriter();
}
/**
* An implementation of OutputStream that redirects to the
* current System.err.
*
*/
private static class SystemErrStream extends OutputStream {
public SystemErrStream() {
}
public void close() {
}
public void flush() {
System.err.flush();
}
public void write(final byte[] b) throws IOException {
System.err.write(b);
}
public void write(final byte[] b, final int off, final int len)
throws IOException {
System.err.write(b, off, len);
}
public void write(final int b) throws IOException {
System.err.write(b);
}
}
/**
* An implementation of OutputStream that redirects to the
* current System.out.
*
*/
private static class SystemOutStream extends OutputStream {
public SystemOutStream() {
}
public void close() {
}
public void flush() {
System.out.flush();
}
public void write(final byte[] b) throws IOException {
System.out.write(b);
}
public void write(final byte[] b, final int off, final int len)
throws IOException {
System.out.write(b, off, len);
}
public void write(final int b) throws IOException {
System.out.write(b);
}
}
}
|
Bug 37122: Console redirction in 1.2.12 causes infinite loop in JBoss
git-svn-id: f8ec76806b93013cd47e945cc2def9ed48bbf7ea@326599 13f79535-47bb-0310-9956-ffa450edef68
|
src/java/org/apache/log4j/ConsoleAppender.java
|
Bug 37122: Console redirction in 1.2.12 causes infinite loop in JBoss
|
<ide><path>rc/java/org/apache/log4j/ConsoleAppender.java
<ide> protected String target = SYSTEM_OUT;
<ide>
<ide> /**
<add> * Determines if the appender honors reassignments of System.out
<add> * or System.err made after configuration.
<add> */
<add> private boolean honorReassignment = false;
<add>
<add> /**
<ide> * Constructs an unconfigured appender.
<ide> */
<ide> public ConsoleAppender() {
<ide> String getTarget() {
<ide> return target;
<ide> }
<add>
<add> /**
<add> * Sets whether the appender honors reassignments of System.out
<add> * or System.err made after configuration.
<add> * @param newValue if true, appender will use value of System.out or
<add> * System.err in force at the time when logging events are appended.
<add> * @since 1.2.13
<add> */
<add> public final void setHonorReassignment(final boolean newValue) {
<add> honorReassignment = newValue;
<add> }
<add>
<add> /**
<add> * Gets whether the appender honors reassignments of System.out
<add> * or System.err made after configuration.
<add> * @return true if appender will use value of System.out or
<add> * System.err in force at the time when logging events are appended.
<add> * @since 1.2.13
<add> */
<add> public final boolean getHonorReassignment() {
<add> return honorReassignment;
<add> }
<ide>
<ide> void targetWarn(String val) {
<ide> LogLog.warn("["+val+"] should be System.out or System.err.");
<ide> * Prepares the appender for use.
<ide> */
<ide> public void activateOptions() {
<del> if (target.equals(SYSTEM_ERR)) {
<del> setWriter(createWriter(new SystemErrStream()));
<add> if (honorReassignment) {
<add> if (target.equals(SYSTEM_ERR)) {
<add> setWriter(createWriter(new SystemErrStream()));
<add> } else {
<add> setWriter(createWriter(new SystemOutStream()));
<add> }
<ide> } else {
<del> setWriter(createWriter(new SystemOutStream()));
<add> if (target.equals(SYSTEM_ERR)) {
<add> setWriter(createWriter(System.err));
<add> } else {
<add> setWriter(createWriter(System.out));
<add> }
<ide> }
<ide>
<ide> super.activateOptions();
<ide> protected
<ide> final
<ide> void closeWriter() {
<del> super.closeWriter();
<add> if (honorReassignment) {
<add> super.closeWriter();
<add> }
<ide> }
<ide>
<ide>
|
|
Java
|
mit
|
f5f3c11d4733dfefd3f32f1d2c940a425b639a49
| 0 |
ls1intum/ArTEMiS,ls1intum/ArTEMiS,ls1intum/ArTEMiS,ls1intum/ArTEMiS,ls1intum/ArTEMiS,ls1intum/ArTEMiS
|
package de.tum.in.www1.artemis.service.connectors.gitlab;
import static org.gitlab4j.api.models.AccessLevel.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.*;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import javax.annotation.Nullable;
import org.gitlab4j.api.GitLabApi;
import org.gitlab4j.api.GitLabApiException;
import org.gitlab4j.api.models.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;
import com.fasterxml.jackson.databind.JsonNode;
import de.tum.in.www1.artemis.domain.Commit;
import de.tum.in.www1.artemis.domain.ProgrammingExercise;
import de.tum.in.www1.artemis.domain.User;
import de.tum.in.www1.artemis.domain.VcsRepositoryUrl;
import de.tum.in.www1.artemis.domain.enumeration.InitializationState;
import de.tum.in.www1.artemis.domain.participation.ProgrammingExerciseParticipation;
import de.tum.in.www1.artemis.exception.VersionControlException;
import de.tum.in.www1.artemis.repository.UserRepository;
import de.tum.in.www1.artemis.service.UrlService;
import de.tum.in.www1.artemis.service.connectors.AbstractVersionControlService;
import de.tum.in.www1.artemis.service.connectors.ConnectorHealth;
import de.tum.in.www1.artemis.service.connectors.GitService;
import de.tum.in.www1.artemis.service.connectors.gitlab.dto.GitLabPushNotificationDTO;
import de.tum.in.www1.artemis.service.util.UrlUtils;
@Profile("gitlab")
@Service
public class GitLabService extends AbstractVersionControlService {
private final Logger log = LoggerFactory.getLogger(GitLabService.class);
@Value("${artemis.version-control.url}")
private URL gitlabServerUrl;
@Value("${artemis.version-control.ci-token}")
private String ciToken;
private final UserRepository userRepository;
private final RestTemplate shortTimeoutRestTemplate;
private final GitLabUserManagementService gitLabUserManagementService;
private final GitLabApi gitlab;
private final ScheduledExecutorService scheduler;
public GitLabService(UserRepository userRepository, UrlService urlService, @Qualifier("shortTimeoutGitlabRestTemplate") RestTemplate shortTimeoutRestTemplate, GitLabApi gitlab,
GitLabUserManagementService gitLabUserManagementService, GitService gitService, ApplicationContext applicationContext) {
super(applicationContext, urlService, gitService);
this.userRepository = userRepository;
this.shortTimeoutRestTemplate = shortTimeoutRestTemplate;
this.gitlab = gitlab;
this.gitLabUserManagementService = gitLabUserManagementService;
this.scheduler = Executors.newScheduledThreadPool(Runtime.getRuntime().availableProcessors());
}
@Override
public void configureRepository(ProgrammingExercise exercise, VcsRepositoryUrl repositoryUrl, Set<User> users, boolean allowAccess) {
for (User user : users) {
String username = user.getLogin();
// TODO: does it really make sense to potentially create a user here? Should we not rather create this user when the user is created in the internal Artemis database?
// Automatically created users
if ((userPrefixEdx.isPresent() && username.startsWith(userPrefixEdx.get())) || (userPrefixU4I.isPresent() && username.startsWith((userPrefixU4I.get())))) {
if (!userExists(username)) {
gitLabUserManagementService.importUser(user);
}
}
if (allowAccess && !Boolean.FALSE.equals(exercise.isAllowOfflineIde())) {
// only add access to the repository if the offline IDE usage is NOT explicitly disallowed
// NOTE: null values are interpreted as offline IDE is allowed
addMemberToRepository(repositoryUrl, user);
}
}
protectBranch(repositoryUrl, "master");
}
@Override
public void addMemberToRepository(VcsRepositoryUrl repositoryUrl, User user) {
final var repositoryId = getPathIDFromRepositoryURL(repositoryUrl);
final var userId = gitLabUserManagementService.getUserId(user.getLogin());
try {
// Only add the member to the repository if it doesn't exist. Otherwise
// update the existing member.
var projectApi = gitlab.getProjectApi();
if (projectApi.getOptionalMember(repositoryId, userId).isPresent()) {
updateMemberPermissionInRepository(repositoryUrl, user.getLogin(), DEVELOPER);
}
else {
projectApi.addMember(repositoryId, userId, DEVELOPER);
}
}
catch (GitLabApiException e) {
throw new GitLabException("Error while trying to add user to repository: " + user.getLogin() + " to repo " + repositoryUrl, e);
}
}
@Override
public void removeMemberFromRepository(VcsRepositoryUrl repositoryUrl, User user) {
final var repositoryId = getPathIDFromRepositoryURL(repositoryUrl);
final var userId = gitLabUserManagementService.getUserId(user.getLogin());
try {
gitlab.getProjectApi().removeMember(repositoryId, userId);
}
catch (GitLabApiException e) {
throw new GitLabException("Error while trying to remove user from repository: " + user.getLogin() + " from repo " + repositoryUrl, e);
}
}
/**
* Protects a branch from the repository, so that developers cannot change the history
*
* @param repositoryUrl The repository url of the repository to update. It contains the project key & the repository name.
* @param branch The name of the branch to protect (e.g "master")
* @throws VersionControlException If the communication with the VCS fails.
*/
private void protectBranch(VcsRepositoryUrl repositoryUrl, String branch) {
final var repositoryId = getPathIDFromRepositoryURL(repositoryUrl);
// we have to first unprotect the branch in order to set the correct access level, this is the case, because the master branch is protected for maintainers by default
// Unprotect the branch in 8 seconds first and then protect the branch in 12 seconds.
// We do this to wait on any async calls to Gitlab and make sure that the branch really exists before protecting it.
unprotectBranch(repositoryId, branch, 8L, TimeUnit.SECONDS);
protectBranch(repositoryId, branch, 12L, TimeUnit.SECONDS);
}
/**
* Protects the branch but delays the execution.
*
* @param repositoryId The id of the repository
* @param branch The branch to protect
* @param delayTime Time until the call is executed
* @param delayTimeUnit The unit of the time (e.g seconds, minutes)
*/
private void protectBranch(String repositoryId, String branch, Long delayTime, TimeUnit delayTimeUnit) {
scheduler.schedule(() -> {
try {
log.info("Protecting branch " + branch + "for Gitlab repository " + repositoryId);
gitlab.getProtectedBranchesApi().protectBranch(repositoryId, branch, DEVELOPER, DEVELOPER, MAINTAINER, false);
}
catch (GitLabApiException e) {
throw new GitLabException("Unable to protect branch " + branch + " for repository " + repositoryId, e);
}
}, delayTime, delayTimeUnit);
}
@Override
public void unprotectBranch(VcsRepositoryUrl repositoryUrl, String branch) throws VersionControlException {
final var repositoryId = getPathIDFromRepositoryURL(repositoryUrl);
// Unprotect the branch in 10 seconds. We do this to wait on any async calls to Gitlab and make sure that the branch really exists before unprotecting it.
unprotectBranch(repositoryId, branch, 10L, TimeUnit.SECONDS);
}
/**
* Unprotects the branch but delays the execution.
*
* @param repositoryId The id of the repository
* @param branch The branch to unprotect
* @param delayTime Time until the call is executed
* @param delayTimeUnit The unit of the time (e.g seconds, minutes)
*/
private void unprotectBranch(String repositoryId, String branch, Long delayTime, TimeUnit delayTimeUnit) {
scheduler.schedule(() -> {
try {
log.info("Unprotecting branch " + branch + "for Gitlab repository " + repositoryId);
gitlab.getProtectedBranchesApi().unprotectBranch(repositoryId, branch);
}
catch (GitLabApiException e) {
throw new GitLabException("Could not unprotect branch " + branch + " for repository " + repositoryId, e);
}
}, delayTime, delayTimeUnit);
}
@Override
public void addWebHooksForExercise(ProgrammingExercise exercise) {
super.addWebHooksForExercise(exercise);
final var projectKey = exercise.getProjectKey();
// Optional webhook from the version control system to the continuous integration system
// This allows the continuous integration system to immediately build when new commits are pushed (in contrast to pulling regurlarly)
final var templatePlanNotificationUrl = getContinuousIntegrationService().getWebHookUrl(projectKey, exercise.getTemplateParticipation().getBuildPlanId());
final var solutionPlanNotificationUrl = getContinuousIntegrationService().getWebHookUrl(projectKey, exercise.getSolutionParticipation().getBuildPlanId());
if (templatePlanNotificationUrl.isPresent() && solutionPlanNotificationUrl.isPresent()) {
addAuthenticatedWebHook(exercise.getVcsTemplateRepositoryUrl(), templatePlanNotificationUrl.get(), "Artemis Exercise WebHook", ciToken);
addAuthenticatedWebHook(exercise.getVcsSolutionRepositoryUrl(), solutionPlanNotificationUrl.get(), "Artemis Solution WebHook", ciToken);
addAuthenticatedWebHook(exercise.getVcsTestRepositoryUrl(), solutionPlanNotificationUrl.get(), "Artemis Tests WebHook", ciToken);
}
}
@Override
public void addWebHookForParticipation(ProgrammingExerciseParticipation participation) {
if (!participation.getInitializationState().hasCompletedState(InitializationState.INITIALIZED)) {
super.addWebHookForParticipation(participation);
// Optional webhook from the version control system to the continuous integration system
// This allows the continuous integration system to immediately build when new commits are pushed (in contrast to pulling regurlarly)
getContinuousIntegrationService().getWebHookUrl(participation.getProgrammingExercise().getProjectKey(), participation.getBuildPlanId())
.ifPresent(hookUrl -> addAuthenticatedWebHook(participation.getVcsRepositoryUrl(), hookUrl, "Artemis trigger to CI", ciToken));
}
}
@Override
protected void addWebHook(VcsRepositoryUrl repositoryUrl, String notificationUrl, String webHookName) {
addAuthenticatedWebHook(repositoryUrl, notificationUrl, webHookName, "noSecretNeeded");
}
@Override
protected void addAuthenticatedWebHook(VcsRepositoryUrl repositoryUrl, String notificationUrl, String webHookName, String secretToken) {
final var repositoryId = getPathIDFromRepositoryURL(repositoryUrl);
final var hook = new ProjectHook().withPushEvents(true).withIssuesEvents(false).withMergeRequestsEvents(false).withWikiPageEvents(false);
try {
gitlab.getProjectApi().addHook(repositoryId, notificationUrl, hook, false, secretToken);
}
catch (GitLabApiException e) {
throw new GitLabException("Unable to add webhook for " + repositoryUrl, e);
}
}
@Override
public void deleteProject(String projectKey) {
try {
gitlab.getGroupApi().deleteGroup(projectKey);
}
catch (GitLabApiException e) {
throw new GitLabException("Unable to delete group in GitLab: " + projectKey, e);
}
}
@Override
public void deleteRepository(VcsRepositoryUrl repositoryUrl) {
final var repositoryId = getPathIDFromRepositoryURL(repositoryUrl);
final var repositoryName = urlService.getRepositorySlugFromRepositoryUrl(repositoryUrl);
try {
gitlab.getProjectApi().deleteProject(repositoryId);
}
catch (GitLabApiException e) {
throw new GitLabException("Error trying to delete repository on GitLab: " + repositoryName, e);
}
}
@Override
public VcsRepositoryUrl getCloneRepositoryUrl(String projectKey, String repositorySlug) {
return new GitLabRepositoryUrl(projectKey, repositorySlug);
}
@Override
public Boolean repositoryUrlIsValid(@Nullable VcsRepositoryUrl repositoryUrl) {
if (repositoryUrl == null || repositoryUrl.getURL() == null) {
return false;
}
final var repositoryId = getPathIDFromRepositoryURL(repositoryUrl);
try {
gitlab.getProjectApi().getProject(repositoryId);
}
catch (Exception emAll) {
log.warn("Invalid repository VcsRepositoryUrl " + repositoryUrl);
return false;
}
return true;
}
@Override
public Commit getLastCommitDetails(Object requestBody) throws VersionControlException {
final var details = GitLabPushNotificationDTO.convert(requestBody);
final var commit = new Commit();
// We will notify for every commit, so we can just use the first commit in the notification list
final var gitLabCommit = details.getCommits().get(0);
commit.setMessage(gitLabCommit.getMessage());
commit.setAuthorEmail(gitLabCommit.getAuthor().getEmail());
commit.setAuthorName(gitLabCommit.getAuthor().getName());
final var ref = details.getRef().split("/");
commit.setBranch(ref[ref.length - 1]);
commit.setCommitHash(gitLabCommit.getHash());
return commit;
}
@Override
public void createProjectForExercise(ProgrammingExercise programmingExercise) throws VersionControlException {
final var exercisePath = programmingExercise.getProjectKey();
final var exerciseName = exercisePath + " " + programmingExercise.getTitle();
final var group = new Group().withPath(exercisePath).withName(exerciseName).withVisibility(Visibility.PRIVATE);
try {
gitlab.getGroupApi().addGroup(group);
}
catch (GitLabApiException e) {
if (e.getMessage().contains("has already been taken")) {
// ignore this error, because it is not really a problem
log.warn("Failed to add group " + exerciseName + " due to error: " + e.getMessage());
}
else {
throw new GitLabException("Unable to create new group for course " + exerciseName, e);
}
}
final var instructors = userRepository.getInstructors(programmingExercise.getCourseViaExerciseGroupOrCourseMember());
final var tutors = userRepository.getTutors(programmingExercise.getCourseViaExerciseGroupOrCourseMember());
for (final var instructor : instructors) {
try {
final var userId = gitLabUserManagementService.getUserId(instructor.getLogin());
gitLabUserManagementService.addUserToGroups(userId, List.of(programmingExercise), MAINTAINER);
}
catch (GitLabException ignored) {
// ignore the exception and continue with the next user, one non existing user or issue here should not prevent the creation of the whole programming exercise
}
}
for (final var tutor : tutors) {
try {
final var userId = gitLabUserManagementService.getUserId(tutor.getLogin());
gitLabUserManagementService.addUserToGroups(userId, List.of(programmingExercise), GUEST);
}
catch (GitLabException ignored) {
// ignore the exception and continue with the next user, one non existing user or issue here should not prevent the creation of the whole programming exercise
}
}
}
@Override
public void createRepository(String projectKey, String repoName, String parentProjectKey) throws VersionControlException {
try {
final var groupId = gitlab.getGroupApi().getGroup(projectKey).getId();
final var project = new Project().withName(repoName.toLowerCase()).withNamespaceId(groupId).withVisibility(Visibility.PRIVATE).withJobsEnabled(false)
.withSharedRunnersEnabled(false).withContainerRegistryEnabled(false);
gitlab.getProjectApi().createProject(project);
}
catch (GitLabApiException e) {
if (e.getValidationErrors().containsKey("path") && e.getValidationErrors().get("path").contains("has already been taken")) {
log.info("Repository {} (parent {}) already exists, reusing it...", repoName, projectKey);
return;
}
throw new GitLabException("Error creating new repository " + repoName, e);
}
}
@Override
public boolean checkIfProjectExists(String projectKey, String projectName) {
try {
return !gitlab.getProjectApi().getProjects(projectKey).isEmpty();
}
catch (GitLabApiException e) {
throw new GitLabException("Error trying to search for project " + projectName, e);
}
}
@Override
public void setRepositoryPermissionsToReadOnly(VcsRepositoryUrl repositoryUrl, String projectKey, Set<User> users) {
users.forEach(user -> updateMemberPermissionInRepository(repositoryUrl, user.getLogin(), GUEST));
}
/**
* Updates the acess level of the user if it's a member of the repository.
* @param repositoryUrl The url of the repository
* @param username the username of the gitlab user
* @param accessLevel the new access level for the user
*/
private void updateMemberPermissionInRepository(VcsRepositoryUrl repositoryUrl, String username, AccessLevel accessLevel) {
final var userId = gitLabUserManagementService.getUserId(username);
final var repositoryId = getPathIDFromRepositoryURL(repositoryUrl);
try {
gitlab.getProjectApi().updateMember(repositoryId, userId, accessLevel);
}
catch (GitLabApiException e) {
throw new GitLabException("Unable to set permissions for user " + username + ". Trying to set permission " + accessLevel, e);
}
}
@Override
public ConnectorHealth health() {
try {
final var uri = Endpoints.HEALTH.buildEndpoint(gitlabServerUrl.toString()).build().toUri();
final var healthResponse = shortTimeoutRestTemplate.getForObject(uri, JsonNode.class);
final var status = healthResponse.get("status").asText();
if (!status.equals("ok")) {
return new ConnectorHealth(false, Map.of("status", status, "url", gitlabServerUrl));
}
return new ConnectorHealth(true, Map.of("url", gitlabServerUrl));
}
catch (Exception emAll) {
return new ConnectorHealth(emAll);
}
}
private boolean userExists(String username) {
try {
return gitlab.getUserApi().getUser(username) != null;
}
catch (GitLabApiException e) {
throw new GitLabException("Unable to fetch user ID for " + username, e);
}
}
private String getPathIDFromRepositoryURL(VcsRepositoryUrl repositoryUrl) {
final var namespaces = repositoryUrl.getURL().toString().split("/");
final var last = namespaces.length - 1;
return namespaces[last - 1] + "/" + namespaces[last].replace(".git", "");
}
private enum Endpoints {
ADD_USER("projects", "<projectId>", "members"), USERS("users"), EDIT_EXERCISE_PERMISSION("projects", "<projectId>", "members", "<memberId>"),
PROTECTED_BRANCHES("projects", "<projectId>", "protected_branches"), PROTECTED_BRANCH("projects", "<projectId>", "protected_branches", "<branchName>"),
GET_WEBHOOKS("projects", "<projectId>", "hooks"), ADD_WEBHOOK("projects", "<projectId>", "hooks"), COMMITS("projects", "<projectId>", "repository", "commits"),
GROUPS("groups"), NAMESPACES("namespaces", "<groupId>"), DELETE_GROUP("groups", "<groupId>"), DELETE_PROJECT("projects", "<projectId>"), PROJECTS("projects"),
GET_PROJECT("projects", "<projectId>"), FORK("projects", "<projectId>", "fork"), HEALTH("-", "liveness");
private final List<String> pathSegments;
Endpoints(String... pathSegments) {
this.pathSegments = Arrays.asList(pathSegments);
}
public UriComponentsBuilder buildEndpoint(String baseUrl, Object... args) {
return UrlUtils.buildEndpoint(baseUrl, pathSegments, args);
}
}
public final class GitLabRepositoryUrl extends VcsRepositoryUrl {
public GitLabRepositoryUrl(String projectKey, String repositorySlug) {
final var path = projectKey + "/" + repositorySlug;
final var urlString = gitlabServerUrl + "/" + path + ".git";
stringToURL(urlString);
}
private GitLabRepositoryUrl(String urlString) {
stringToURL(urlString);
}
private void stringToURL(String urlString) {
try {
this.url = new URL(urlString);
}
catch (MalformedURLException e) {
throw new GitLabException("Could not build GitLab URL", e);
}
}
@Override
public VcsRepositoryUrl withUser(String username) {
this.username = username;
return new GitLabRepositoryUrl(url.toString().replaceAll("(https?://)(.*)", "$1" + username + "@$2"));
}
}
}
|
src/main/java/de/tum/in/www1/artemis/service/connectors/gitlab/GitLabService.java
|
package de.tum.in.www1.artemis.service.connectors.gitlab;
import static org.gitlab4j.api.models.AccessLevel.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.*;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import javax.annotation.Nullable;
import org.gitlab4j.api.GitLabApi;
import org.gitlab4j.api.GitLabApiException;
import org.gitlab4j.api.models.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;
import com.fasterxml.jackson.databind.JsonNode;
import de.tum.in.www1.artemis.domain.Commit;
import de.tum.in.www1.artemis.domain.ProgrammingExercise;
import de.tum.in.www1.artemis.domain.User;
import de.tum.in.www1.artemis.domain.VcsRepositoryUrl;
import de.tum.in.www1.artemis.domain.enumeration.InitializationState;
import de.tum.in.www1.artemis.domain.participation.ProgrammingExerciseParticipation;
import de.tum.in.www1.artemis.exception.VersionControlException;
import de.tum.in.www1.artemis.repository.UserRepository;
import de.tum.in.www1.artemis.service.UrlService;
import de.tum.in.www1.artemis.service.connectors.AbstractVersionControlService;
import de.tum.in.www1.artemis.service.connectors.ConnectorHealth;
import de.tum.in.www1.artemis.service.connectors.GitService;
import de.tum.in.www1.artemis.service.connectors.gitlab.dto.GitLabPushNotificationDTO;
import de.tum.in.www1.artemis.service.util.UrlUtils;
@Profile("gitlab")
@Service
public class GitLabService extends AbstractVersionControlService {
private final Logger log = LoggerFactory.getLogger(GitLabService.class);
@Value("${artemis.version-control.url}")
private URL gitlabServerUrl;
@Value("${artemis.version-control.ci-token}")
private String ciToken;
private final UserRepository userRepository;
private final RestTemplate shortTimeoutRestTemplate;
private final GitLabUserManagementService gitLabUserManagementService;
private final GitLabApi gitlab;
private final ScheduledExecutorService scheduler;
public GitLabService(UserRepository userRepository, UrlService urlService, @Qualifier("shortTimeoutGitlabRestTemplate") RestTemplate shortTimeoutRestTemplate, GitLabApi gitlab,
GitLabUserManagementService gitLabUserManagementService, GitService gitService, ApplicationContext applicationContext) {
super(applicationContext, urlService, gitService);
this.userRepository = userRepository;
this.shortTimeoutRestTemplate = shortTimeoutRestTemplate;
this.gitlab = gitlab;
this.gitLabUserManagementService = gitLabUserManagementService;
this.scheduler = Executors.newScheduledThreadPool(Runtime.getRuntime().availableProcessors());
}
@Override
public void configureRepository(ProgrammingExercise exercise, VcsRepositoryUrl repositoryUrl, Set<User> users, boolean allowAccess) {
for (User user : users) {
String username = user.getLogin();
// TODO: does it really make sense to potentially create a user here? Should we not rather create this user when the user is created in the internal Artemis database?
// Automatically created users
if ((userPrefixEdx.isPresent() && username.startsWith(userPrefixEdx.get())) || (userPrefixU4I.isPresent() && username.startsWith((userPrefixU4I.get())))) {
if (!userExists(username)) {
gitLabUserManagementService.importUser(user);
}
}
if (allowAccess && !Boolean.FALSE.equals(exercise.isAllowOfflineIde())) {
// only add access to the repository if the offline IDE usage is NOT explicitly disallowed
// NOTE: null values are interpreted as offline IDE is allowed
addMemberToRepository(repositoryUrl, user);
}
}
protectBranch(repositoryUrl, "master");
}
@Override
public void addMemberToRepository(VcsRepositoryUrl repositoryUrl, User user) {
final var repositoryId = getPathIDFromRepositoryURL(repositoryUrl);
final var userId = gitLabUserManagementService.getUserId(user.getLogin());
try {
gitlab.getProjectApi().addMember(repositoryId, userId, DEVELOPER);
}
catch (GitLabApiException e) {
if (e.getValidationErrors().containsKey("access_level")
&& e.getValidationErrors().get("access_level").stream().anyMatch(s -> s.contains("should be greater than or equal to"))) {
log.warn("Member already has the requested permissions! Permission stays the same");
}
else {
throw new GitLabException("Error while trying to add user to repository: " + user.getLogin() + " to repo " + repositoryUrl, e);
}
}
}
@Override
public void removeMemberFromRepository(VcsRepositoryUrl repositoryUrl, User user) {
final var repositoryId = getPathIDFromRepositoryURL(repositoryUrl);
final var userId = gitLabUserManagementService.getUserId(user.getLogin());
try {
gitlab.getProjectApi().removeMember(repositoryId, userId);
}
catch (GitLabApiException e) {
throw new GitLabException("Error while trying to remove user from repository: " + user.getLogin() + " from repo " + repositoryUrl, e);
}
}
/**
* Protects a branch from the repository, so that developers cannot change the history
*
* @param repositoryUrl The repository url of the repository to update. It contains the project key & the repository name.
* @param branch The name of the branch to protect (e.g "master")
* @throws VersionControlException If the communication with the VCS fails.
*/
private void protectBranch(VcsRepositoryUrl repositoryUrl, String branch) {
final var repositoryId = getPathIDFromRepositoryURL(repositoryUrl);
// we have to first unprotect the branch in order to set the correct access level, this is the case, because the master branch is protected for maintainers by default
// Unprotect the branch in 8 seconds first and then protect the branch in 12 seconds.
// We do this to wait on any async calls to Gitlab and make sure that the branch really exists before protecting it.
unprotectBranch(repositoryId, branch, 8L, TimeUnit.SECONDS);
protectBranch(repositoryId, branch, 12L, TimeUnit.SECONDS);
}
/**
* Protects the branch but delays the execution.
*
* @param repositoryId The id of the repository
* @param branch The branch to protect
* @param delayTime Time until the call is executed
* @param delayTimeUnit The unit of the time (e.g seconds, minutes)
*/
private void protectBranch(String repositoryId, String branch, Long delayTime, TimeUnit delayTimeUnit) {
scheduler.schedule(() -> {
try {
log.info("Protecting branch " + branch + "for Gitlab repository " + repositoryId);
gitlab.getProtectedBranchesApi().protectBranch(repositoryId, branch, DEVELOPER, DEVELOPER, MAINTAINER, false);
}
catch (GitLabApiException e) {
throw new GitLabException("Unable to protect branch " + branch + " for repository " + repositoryId, e);
}
}, delayTime, delayTimeUnit);
}
@Override
public void unprotectBranch(VcsRepositoryUrl repositoryUrl, String branch) throws VersionControlException {
final var repositoryId = getPathIDFromRepositoryURL(repositoryUrl);
// Unprotect the branch in 10 seconds. We do this to wait on any async calls to Gitlab and make sure that the branch really exists before unprotecting it.
unprotectBranch(repositoryId, branch, 10L, TimeUnit.SECONDS);
}
/**
* Unprotects the branch but delays the execution.
*
* @param repositoryId The id of the repository
* @param branch The branch to unprotect
* @param delayTime Time until the call is executed
* @param delayTimeUnit The unit of the time (e.g seconds, minutes)
*/
private void unprotectBranch(String repositoryId, String branch, Long delayTime, TimeUnit delayTimeUnit) {
scheduler.schedule(() -> {
try {
log.info("Unprotecting branch " + branch + "for Gitlab repository " + repositoryId);
gitlab.getProtectedBranchesApi().unprotectBranch(repositoryId, branch);
}
catch (GitLabApiException e) {
throw new GitLabException("Could not unprotect branch " + branch + " for repository " + repositoryId, e);
}
}, delayTime, delayTimeUnit);
}
@Override
public void addWebHooksForExercise(ProgrammingExercise exercise) {
super.addWebHooksForExercise(exercise);
final var projectKey = exercise.getProjectKey();
// Optional webhook from the version control system to the continuous integration system
// This allows the continuous integration system to immediately build when new commits are pushed (in contrast to pulling regurlarly)
final var templatePlanNotificationUrl = getContinuousIntegrationService().getWebHookUrl(projectKey, exercise.getTemplateParticipation().getBuildPlanId());
final var solutionPlanNotificationUrl = getContinuousIntegrationService().getWebHookUrl(projectKey, exercise.getSolutionParticipation().getBuildPlanId());
if (templatePlanNotificationUrl.isPresent() && solutionPlanNotificationUrl.isPresent()) {
addAuthenticatedWebHook(exercise.getVcsTemplateRepositoryUrl(), templatePlanNotificationUrl.get(), "Artemis Exercise WebHook", ciToken);
addAuthenticatedWebHook(exercise.getVcsSolutionRepositoryUrl(), solutionPlanNotificationUrl.get(), "Artemis Solution WebHook", ciToken);
addAuthenticatedWebHook(exercise.getVcsTestRepositoryUrl(), solutionPlanNotificationUrl.get(), "Artemis Tests WebHook", ciToken);
}
}
@Override
public void addWebHookForParticipation(ProgrammingExerciseParticipation participation) {
if (!participation.getInitializationState().hasCompletedState(InitializationState.INITIALIZED)) {
super.addWebHookForParticipation(participation);
// Optional webhook from the version control system to the continuous integration system
// This allows the continuous integration system to immediately build when new commits are pushed (in contrast to pulling regurlarly)
getContinuousIntegrationService().getWebHookUrl(participation.getProgrammingExercise().getProjectKey(), participation.getBuildPlanId())
.ifPresent(hookUrl -> addAuthenticatedWebHook(participation.getVcsRepositoryUrl(), hookUrl, "Artemis trigger to CI", ciToken));
}
}
@Override
protected void addWebHook(VcsRepositoryUrl repositoryUrl, String notificationUrl, String webHookName) {
addAuthenticatedWebHook(repositoryUrl, notificationUrl, webHookName, "noSecretNeeded");
}
@Override
protected void addAuthenticatedWebHook(VcsRepositoryUrl repositoryUrl, String notificationUrl, String webHookName, String secretToken) {
final var repositoryId = getPathIDFromRepositoryURL(repositoryUrl);
final var hook = new ProjectHook().withPushEvents(true).withIssuesEvents(false).withMergeRequestsEvents(false).withWikiPageEvents(false);
try {
gitlab.getProjectApi().addHook(repositoryId, notificationUrl, hook, false, secretToken);
}
catch (GitLabApiException e) {
throw new GitLabException("Unable to add webhook for " + repositoryUrl, e);
}
}
@Override
public void deleteProject(String projectKey) {
try {
gitlab.getGroupApi().deleteGroup(projectKey);
}
catch (GitLabApiException e) {
throw new GitLabException("Unable to delete group in GitLab: " + projectKey, e);
}
}
@Override
public void deleteRepository(VcsRepositoryUrl repositoryUrl) {
final var repositoryId = getPathIDFromRepositoryURL(repositoryUrl);
final var repositoryName = urlService.getRepositorySlugFromRepositoryUrl(repositoryUrl);
try {
gitlab.getProjectApi().deleteProject(repositoryId);
}
catch (GitLabApiException e) {
throw new GitLabException("Error trying to delete repository on GitLab: " + repositoryName, e);
}
}
@Override
public VcsRepositoryUrl getCloneRepositoryUrl(String projectKey, String repositorySlug) {
return new GitLabRepositoryUrl(projectKey, repositorySlug);
}
@Override
public Boolean repositoryUrlIsValid(@Nullable VcsRepositoryUrl repositoryUrl) {
if (repositoryUrl == null || repositoryUrl.getURL() == null) {
return false;
}
final var repositoryId = getPathIDFromRepositoryURL(repositoryUrl);
try {
gitlab.getProjectApi().getProject(repositoryId);
}
catch (Exception emAll) {
log.warn("Invalid repository VcsRepositoryUrl " + repositoryUrl);
return false;
}
return true;
}
@Override
public Commit getLastCommitDetails(Object requestBody) throws VersionControlException {
final var details = GitLabPushNotificationDTO.convert(requestBody);
final var commit = new Commit();
// We will notify for every commit, so we can just use the first commit in the notification list
final var gitLabCommit = details.getCommits().get(0);
commit.setMessage(gitLabCommit.getMessage());
commit.setAuthorEmail(gitLabCommit.getAuthor().getEmail());
commit.setAuthorName(gitLabCommit.getAuthor().getName());
final var ref = details.getRef().split("/");
commit.setBranch(ref[ref.length - 1]);
commit.setCommitHash(gitLabCommit.getHash());
return commit;
}
@Override
public void createProjectForExercise(ProgrammingExercise programmingExercise) throws VersionControlException {
final var exercisePath = programmingExercise.getProjectKey();
final var exerciseName = exercisePath + " " + programmingExercise.getTitle();
final var group = new Group().withPath(exercisePath).withName(exerciseName).withVisibility(Visibility.PRIVATE);
try {
gitlab.getGroupApi().addGroup(group);
}
catch (GitLabApiException e) {
if (e.getMessage().contains("has already been taken")) {
// ignore this error, because it is not really a problem
log.warn("Failed to add group " + exerciseName + " due to error: " + e.getMessage());
}
else {
throw new GitLabException("Unable to create new group for course " + exerciseName, e);
}
}
final var instructors = userRepository.getInstructors(programmingExercise.getCourseViaExerciseGroupOrCourseMember());
final var tutors = userRepository.getTutors(programmingExercise.getCourseViaExerciseGroupOrCourseMember());
for (final var instructor : instructors) {
try {
final var userId = gitLabUserManagementService.getUserId(instructor.getLogin());
gitLabUserManagementService.addUserToGroups(userId, List.of(programmingExercise), MAINTAINER);
}
catch (GitLabException ignored) {
// ignore the exception and continue with the next user, one non existing user or issue here should not prevent the creation of the whole programming exercise
}
}
for (final var tutor : tutors) {
try {
final var userId = gitLabUserManagementService.getUserId(tutor.getLogin());
gitLabUserManagementService.addUserToGroups(userId, List.of(programmingExercise), GUEST);
}
catch (GitLabException ignored) {
// ignore the exception and continue with the next user, one non existing user or issue here should not prevent the creation of the whole programming exercise
}
}
}
@Override
public void createRepository(String projectKey, String repoName, String parentProjectKey) throws VersionControlException {
try {
final var groupId = gitlab.getGroupApi().getGroup(projectKey).getId();
final var project = new Project().withName(repoName.toLowerCase()).withNamespaceId(groupId).withVisibility(Visibility.PRIVATE).withJobsEnabled(false)
.withSharedRunnersEnabled(false).withContainerRegistryEnabled(false);
gitlab.getProjectApi().createProject(project);
}
catch (GitLabApiException e) {
if (e.getValidationErrors().containsKey("path") && e.getValidationErrors().get("path").contains("has already been taken")) {
log.info("Repository {} (parent {}) already exists, reusing it...", repoName, projectKey);
return;
}
throw new GitLabException("Error creating new repository " + repoName, e);
}
}
@Override
public boolean checkIfProjectExists(String projectKey, String projectName) {
try {
return !gitlab.getProjectApi().getProjects(projectKey).isEmpty();
}
catch (GitLabApiException e) {
throw new GitLabException("Error trying to search for project " + projectName, e);
}
}
@Override
public void setRepositoryPermissionsToReadOnly(VcsRepositoryUrl repositoryUrl, String projectKey, Set<User> users) {
users.forEach(user -> setRepositoryPermission(repositoryUrl, user.getLogin(), GUEST));
}
private void setRepositoryPermission(VcsRepositoryUrl repositoryUrl, String username, AccessLevel accessLevel) {
final var userId = gitLabUserManagementService.getUserId(username);
final var repositoryId = getPathIDFromRepositoryURL(repositoryUrl);
try {
gitlab.getProjectApi().updateMember(repositoryId, userId, accessLevel);
}
catch (GitLabApiException e) {
throw new GitLabException("Unable to set permissions for user " + username + ". Trying to set permission " + accessLevel, e);
}
}
@Override
public ConnectorHealth health() {
try {
final var uri = Endpoints.HEALTH.buildEndpoint(gitlabServerUrl.toString()).build().toUri();
final var healthResponse = shortTimeoutRestTemplate.getForObject(uri, JsonNode.class);
final var status = healthResponse.get("status").asText();
if (!status.equals("ok")) {
return new ConnectorHealth(false, Map.of("status", status, "url", gitlabServerUrl));
}
return new ConnectorHealth(true, Map.of("url", gitlabServerUrl));
}
catch (Exception emAll) {
return new ConnectorHealth(emAll);
}
}
private boolean userExists(String username) {
try {
return gitlab.getUserApi().getUser(username) != null;
}
catch (GitLabApiException e) {
throw new GitLabException("Unable to fetch user ID for " + username, e);
}
}
private String getPathIDFromRepositoryURL(VcsRepositoryUrl repositoryUrl) {
final var namespaces = repositoryUrl.getURL().toString().split("/");
final var last = namespaces.length - 1;
return namespaces[last - 1] + "/" + namespaces[last].replace(".git", "");
}
private enum Endpoints {
ADD_USER("projects", "<projectId>", "members"), USERS("users"), EDIT_EXERCISE_PERMISSION("projects", "<projectId>", "members", "<memberId>"),
PROTECTED_BRANCHES("projects", "<projectId>", "protected_branches"), PROTECTED_BRANCH("projects", "<projectId>", "protected_branches", "<branchName>"),
GET_WEBHOOKS("projects", "<projectId>", "hooks"), ADD_WEBHOOK("projects", "<projectId>", "hooks"), COMMITS("projects", "<projectId>", "repository", "commits"),
GROUPS("groups"), NAMESPACES("namespaces", "<groupId>"), DELETE_GROUP("groups", "<groupId>"), DELETE_PROJECT("projects", "<projectId>"), PROJECTS("projects"),
GET_PROJECT("projects", "<projectId>"), FORK("projects", "<projectId>", "fork"), HEALTH("-", "liveness");
private final List<String> pathSegments;
Endpoints(String... pathSegments) {
this.pathSegments = Arrays.asList(pathSegments);
}
public UriComponentsBuilder buildEndpoint(String baseUrl, Object... args) {
return UrlUtils.buildEndpoint(baseUrl, pathSegments, args);
}
}
public final class GitLabRepositoryUrl extends VcsRepositoryUrl {
public GitLabRepositoryUrl(String projectKey, String repositorySlug) {
final var path = projectKey + "/" + repositorySlug;
final var urlString = gitlabServerUrl + "/" + path + ".git";
stringToURL(urlString);
}
private GitLabRepositoryUrl(String urlString) {
stringToURL(urlString);
}
private void stringToURL(String urlString) {
try {
this.url = new URL(urlString);
}
catch (MalformedURLException e) {
throw new GitLabException("Could not build GitLab URL", e);
}
}
@Override
public VcsRepositoryUrl withUser(String username) {
this.username = username;
return new GitLabRepositoryUrl(url.toString().replaceAll("(https?://)(.*)", "$1" + username + "@$2"));
}
}
}
|
Update Gitlab members only if they exist (#2929)
|
src/main/java/de/tum/in/www1/artemis/service/connectors/gitlab/GitLabService.java
|
Update Gitlab members only if they exist (#2929)
|
<ide><path>rc/main/java/de/tum/in/www1/artemis/service/connectors/gitlab/GitLabService.java
<ide> final var userId = gitLabUserManagementService.getUserId(user.getLogin());
<ide>
<ide> try {
<del> gitlab.getProjectApi().addMember(repositoryId, userId, DEVELOPER);
<del> }
<del> catch (GitLabApiException e) {
<del> if (e.getValidationErrors().containsKey("access_level")
<del> && e.getValidationErrors().get("access_level").stream().anyMatch(s -> s.contains("should be greater than or equal to"))) {
<del> log.warn("Member already has the requested permissions! Permission stays the same");
<add> // Only add the member to the repository if it doesn't exist. Otherwise
<add> // update the existing member.
<add> var projectApi = gitlab.getProjectApi();
<add> if (projectApi.getOptionalMember(repositoryId, userId).isPresent()) {
<add> updateMemberPermissionInRepository(repositoryUrl, user.getLogin(), DEVELOPER);
<ide> }
<ide> else {
<del> throw new GitLabException("Error while trying to add user to repository: " + user.getLogin() + " to repo " + repositoryUrl, e);
<del> }
<add> projectApi.addMember(repositoryId, userId, DEVELOPER);
<add> }
<add> }
<add> catch (GitLabApiException e) {
<add> throw new GitLabException("Error while trying to add user to repository: " + user.getLogin() + " to repo " + repositoryUrl, e);
<ide> }
<ide> }
<ide>
<ide>
<ide> @Override
<ide> public void setRepositoryPermissionsToReadOnly(VcsRepositoryUrl repositoryUrl, String projectKey, Set<User> users) {
<del> users.forEach(user -> setRepositoryPermission(repositoryUrl, user.getLogin(), GUEST));
<del> }
<del>
<del> private void setRepositoryPermission(VcsRepositoryUrl repositoryUrl, String username, AccessLevel accessLevel) {
<add> users.forEach(user -> updateMemberPermissionInRepository(repositoryUrl, user.getLogin(), GUEST));
<add> }
<add>
<add> /**
<add> * Updates the acess level of the user if it's a member of the repository.
<add> * @param repositoryUrl The url of the repository
<add> * @param username the username of the gitlab user
<add> * @param accessLevel the new access level for the user
<add> */
<add> private void updateMemberPermissionInRepository(VcsRepositoryUrl repositoryUrl, String username, AccessLevel accessLevel) {
<ide> final var userId = gitLabUserManagementService.getUserId(username);
<ide> final var repositoryId = getPathIDFromRepositoryURL(repositoryUrl);
<ide> try {
|
|
Java
|
bsd-3-clause
|
e3ddc1cbc1feb15ff80034020c5386070759db50
| 0 |
rourke750/CivChat,Civcraft/CivChat
|
package com.untamedears.civchat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Random;
import java.util.Set;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.Player;
import com.untamedears.citadel.Citadel;
import com.untamedears.citadel.entity.Faction;
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.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
/*
* Coded by ibbignerd and Rourke750
*/
public class ChatManager {
private CivChat plugin = null;
public double chatmax;
public boolean garbleEnabled;
private Random random = new Random();
private double chatDist1;
private int garble1;
private double chatDist2;
private int garble2;
private int garblevar;
private boolean greyscale;
private String defaultcolor;
private String color1;
private String color2;
public boolean yvar;
private int ynogarb;
public boolean shout;
public String shoutChar;
public int shoutDist;
public boolean whisper;
public String whisperChar;
public int whisperDist;
private String whisperColor;
private HashMap<String, Faction> groupchat = new HashMap<String, Faction>();
private HashMap<String, String> channels = new HashMap<String, String>();
private String replacement = "abcdefghijklmnopqrstuvwxyz";
private HashMap<Player, Long> shoutList = new HashMap<Player, Long>();
public long shoutCool;
private int shoutHunger;
private String shoutColor;
private HashMap<String, List<String>> ignoreList = new HashMap<String, List<String>>();
public ChatManager(CivChat pluginInstance) {
FileConfiguration config;
plugin = pluginInstance;
config = plugin.getConfig();
chatmax = config.getDouble("chat.maxrange", 1000);
garblevar = config.getInt("chat.garblevariation", 5);
yvar = config.getBoolean("chat.yvariation.enabled", true);
ynogarb = config.getInt("chat.yvariation.noGarbLevel", 70);
shout = config.getBoolean("chat.shout.enabled", true);
shoutChar = config.getString("chat.shout.char", "!");
shoutDist = config.getInt("chat.shout.distanceAdded", 100);
shoutColor = config.getString("chat.shout.color", "WHITE");
shoutHunger = config.getInt("chat.shout.hungerreduced", 4);
shoutCool = config.getLong("chat.shout.cooldown", 10) * 1000;
whisper = config.getBoolean("chat.whisper.enabled", true);
whisperChar = config.getString("chat.whisper.char", "#");
whisperDist = config.getInt("chat.whisper.distance", 50);
whisperColor = config.getString("chat.whisper.color", "ITALIC");
defaultcolor = config.getString("chat.defaultcolor", "WHITE");
greyscale = config.getBoolean("chat.greyscale", true);
garbleEnabled = config.getBoolean("chat.range.garbleEnabled", false);
chatDist1 = chatmax - config.getDouble("chat.range.1.distance", 100);
garble1 = config.getInt("chat.range.1.garble", 0);
color1 = config.getString("chat.range.1.color", "GRAY");
chatDist2 = chatmax - config.getDouble("chat.range.2.distance", 50);
garble2 = config.getInt("chat.range.2.garble", 0);
color2 = config.getString("color.range.2.color", "DARK_GRAY");
}
public void sendPrivateMessage(Player from, Player to, String message) {
if (isIgnoring(to.getName(), from.getName())) {
from.sendMessage(ChatColor.YELLOW + to.getName() + ChatColor.RED + " has muted you.");
return;
}
from.sendMessage(ChatColor.LIGHT_PURPLE + "To " + to.getName() + ": " + message);
to.sendMessage(ChatColor.LIGHT_PURPLE + "From " + from.getName() + ": " + message);
}
public void sendPlayerBroadcast(Player player, String message, Set<Player> receivers) {
SaveChat(player, "Broadcast", message);
Location location = player.getLocation();
int x = location.getBlockX();
int y = location.getBlockY();
int z = location.getBlockZ();
double chatdist = 0;
boolean whispering = false;
double chatrange = chatmax;
double added = 0;
boolean shouting = false;
if (yvar && !message.startsWith(whisperChar) && y > ynogarb) {
added = Math.pow(1.1, (y - ynogarb) / 14) * (y - ynogarb);
chatrange += added;
}
if (shout && message.startsWith(shoutChar)) {
if (shoutList.get(player) != null && System.currentTimeMillis() - shoutList.get(player) >= shoutCool) {
shoutList.remove(player);
}
if (shoutList.get(player) == null) {
Float sat = player.getSaturation();
if (sat > 0) {
sat -= shoutHunger;
if (sat <= 0) {
player.setSaturation(0);
player.setFoodLevel(player.getFoodLevel() - Integer.parseInt(sat + ""));
} else {
player.setSaturation(player.getSaturation() - sat);
}
} else {
int food = player.getFoodLevel() - shoutHunger;
if (food < 0) {
food = 0;
}
player.setFoodLevel(food);
}
chatrange += shoutDist;
shoutList.put(player, System.currentTimeMillis());
shouting = true;
} else {
player.sendMessage(ChatColor.RED + "Shout under cooldown, please wait "
+ ((((shoutList.get(player) - System.currentTimeMillis()) + shoutCool) / 1000) + 1) + " seconds");
}
}
for (Player receiver : receivers) {
if(isIgnoring(receiver.getName(), player.getName())){
continue;
}
else{
double garble = 0;
String chat = message;
double randGarble = 0;
ChatColor color = ChatColor.valueOf(defaultcolor);
int rx = receiver.getLocation().getBlockX();
int ry = receiver.getLocation().getBlockY();
int rz = receiver.getLocation().getBlockZ();
chatdist = Math.sqrt(Math.pow(x - rx, 2) + Math.pow(y - ry, 2) + Math.pow(z - rz, 2));
whispering = whisper && message.startsWith(whisperChar);
if (whispering) {
chatrange = whisperDist;
color = ChatColor.valueOf(whisperColor);
randGarble = 0;
} else if (chatdist <= chatDist2 && chatdist > chatDist1) {
if (garbleEnabled) {
randGarble = random.nextInt(garblevar) + garble1;
}
if (greyscale) {
color = ChatColor.valueOf(color1);
}
} else if (chatdist <= chatrange && chatdist > chatDist2) {
if (garbleEnabled) {
randGarble = random.nextInt(garblevar) + garble2;
}
if (greyscale) {
color = ChatColor.valueOf(color2);
}
}
if (garbleEnabled) {
garble = chat.length() * (randGarble / 100.0F);
chat = shuffle(chat, garble);
} else {
chat = message;
}
if (chatdist <= chatrange) {
if (whispering) {
receiver.sendMessage(color + player.getDisplayName() + " whispered: " + chat.substring(1));
} else if (shouting) {
color = ChatColor.valueOf(shoutColor);
receiver.sendMessage(color + player.getDisplayName() + " shouted: " + chat.substring(1));
} else {
receiver.sendMessage(color + player.getDisplayName() + ": " + chat);
}
}
}}
}
private String shuffle(String input, double a) {
int times = (int) a;
StringBuilder sb = new StringBuilder(input);
for (int i = 0; i < times; i++) {
int rand = random.nextInt(input.length());
int replaceRand = random.nextInt(replacement.length());
switch (sb.charAt(rand)) {
case ' ':
case '.':
case ',':
case '!':
continue;
}
sb.setCharAt(rand, replacement.charAt(replaceRand));
}
String output = new String(sb);
return output;
}
public void addChannel(String player1, String player2) {
if (getChannel(player1) != null) {
channels.put(player1, player2);
} else {
channels.put(player1, player2);
}
}
public String getChannel(String player) {
return channels.get(player);
}
public void removeChannel(String player) {
if (channels.containsKey(player)) {
channels.remove(player);
}
}
public void GroupChat(Faction group, StringBuilder message, String player) {
Player player1 = Bukkit.getPlayer(player);
Collection<Player> players = Citadel.getMemberManager().getOnlinePlayers();
String chat = message.toString();
player1.sendMessage(ChatColor.DARK_AQUA + "To group: " + group.getName() + ": " + chat);
for (Player reciever : players) {
if (!group.isMember(reciever.getName())
&& !group.isFounder(reciever.getName())
&& !group.isModerator(reciever.getName())==true) {
continue;
}
if (isIgnoring(reciever.getName(), player)){
continue;
}
if (reciever.getName().equals(player1.getName())) {
continue;
} else {
reciever.sendMessage(ChatColor.DARK_AQUA + "Group " + group.getName() + ", from " + player + ": " + chat);
}
}
}
public void PrivateGroupChat(Faction group, String message, String player) {
Player player1 = Bukkit.getPlayer(player);
Collection<Player> players = Citadel.getMemberManager().getOnlinePlayers();
String chat = message;
player1.sendMessage(ChatColor.DARK_AQUA + "To group: " + group.getName() + ": " + chat);
for (Player reciever : players) {
if (!group.isMember(reciever.getName())
&& !group.isFounder(reciever.getName())
&& !group.isModerator(reciever.getName())) {
continue;
}
if (isIgnoring(reciever.getName(), player) == true){
continue;
}
if (reciever.getName().equals(player1.getName())) {
continue;
}
reciever.sendMessage(ChatColor.DARK_AQUA + "Group " + group.getName() + ", from " + player + ": " + chat);
}
}
public void addGroupTalk(String player, Faction group) {
if (getGroupTalk(player) != null) {
groupchat.put(player, group);
} else {
groupchat.put(player, group);
}
}
public Faction getGroupTalk(String player) {
return groupchat.get(player);
}
public boolean isGroupTalk(String player) {
if (groupchat.containsKey(player)) {
return true;
}
return false;
}
public void removeGroupTalk(String player) {
if (groupchat.containsKey(player)) {
groupchat.remove(player);
}
}
public void SaveChat(Player sender, String type, String message) {
String date = new SimpleDateFormat("dd-MM HH:mm:ss").format(new Date());
String name = sender.getName();
String loc = (int) sender.getLocation().getX() + ", " + (int) sender.getLocation().getY() + ", " + (int) sender.getLocation().getZ();
String textLine = "[" + date + "] [" + loc + "] [" + type + "] [" + name + "] " + message;
try {
plugin.writer.write(textLine);
plugin.writer.newLine();
plugin.writer.flush();
} catch (IOException ex) {
Logger.getLogger(CivChat.class.getName()).log(Level.SEVERE, null, ex);
}
}
public String playerCheck(String player) {
Player[] onlineList = Bukkit.getOnlinePlayers();
for (Player check : onlineList) {
if (check.getName().startsWith(player)) {
return check.getName();
}
}
return player;
}
public boolean isIgnoring(String muter, String muted) {
List<String> ignorelist;
try {
if (ignoreList.containsKey(muter)) {
ignorelist = ignoreList.get(muter);
if (ignorelist.contains(muted)) {
return true;
}
}
else{
return false;
}
} catch (NullPointerException e) {
return false;
}
return false;
}
public void setIgnoreList(String player, String reciever){
List<String> recievers=new ArrayList<String>();
if (ignoreList.get(player)!=null){
recievers= ignoreList.get(player);
recievers.add(reciever);
ignoreList.put(player, recievers);
}
else{
recievers.add(reciever);
ignoreList.put(player, recievers);
}
}
public List<String> getIgnoreList(String player){
return ignoreList.get(player);
}
public void removeIgnore(String player, String reciever){
List<String> removeplayers= new ArrayList<String>();
for (String x: ignoreList.get(player)){
if (x.equals(reciever)){
continue;
}
else{removeplayers.add(x);
}
}
ignoreList.put(player, removeplayers);
}
public void load(File file) throws IOException{
FileInputStream fis = new FileInputStream(file);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
String line;
while ((line=br.readLine()) != null){
String parts[] =line.split(" ");
String owner= parts[0];
List<String> participants= new ArrayList<>();;
for(int x=1; x<parts.length; x++){
participants.add(parts[x]);
}
ignoreList.put(owner, participants);
}
fis.close();
}
public void save(File file) throws IOException{
FileOutputStream fos = new FileOutputStream(file);
BufferedWriter br = new BufferedWriter(new OutputStreamWriter(fos));
Set<String> main= ignoreList.keySet();
for (String z: main){
br.append(z);
for (String x: ignoreList.get(z)){
br.append(" ");
br.append(x);
}
br.append("\n");
}
br.flush();
fos.close();
}
}
|
src/com/untamedears/civchat/ChatManager.java
|
package com.untamedears.civchat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Random;
import java.util.Set;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.Player;
import com.untamedears.citadel.Citadel;
import com.untamedears.citadel.entity.Faction;
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.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
/*
* Coded by ibbignerd and Rourke750
*/
public class ChatManager {
private CivChat plugin = null;
public double chatmax;
public boolean garbleEnabled;
private Random random = new Random();
private double chatDist1;
private int garble1;
private double chatDist2;
private int garble2;
private int garblevar;
private boolean greyscale;
private String defaultcolor;
private String color1;
private String color2;
public boolean yvar;
private int ynogarb;
public boolean shout;
public String shoutChar;
public int shoutDist;
public boolean whisper;
public String whisperChar;
public int whisperDist;
private String whisperColor;
private HashMap<String, Faction> groupchat = new HashMap<String, Faction>();
private HashMap<String, String> channels = new HashMap<String, String>();
private String replacement = "abcdefghijklmnopqrstuvwxyz";
private HashMap<Player, Long> shoutList = new HashMap<Player, Long>();
public long shoutCool;
private int shoutHunger;
private String shoutColor;
private HashMap<String, List<String>> ignoreList = new HashMap<String, List<String>>();
public ChatManager(CivChat pluginInstance) {
FileConfiguration config;
plugin = pluginInstance;
config = plugin.getConfig();
chatmax = config.getDouble("chat.maxrange", 1000);
garblevar = config.getInt("chat.garblevariation", 5);
yvar = config.getBoolean("chat.yvariation.enabled", true);
ynogarb = config.getInt("chat.yvariation.noGarbLevel", 70);
shout = config.getBoolean("chat.shout.enabled", true);
shoutChar = config.getString("chat.shout.char", "!");
shoutDist = config.getInt("chat.shout.distanceAdded", 100);
shoutColor = config.getString("chat.shout.color", "WHITE");
shoutHunger = config.getInt("chat.shout.hungerreduced", 4);
shoutCool = config.getLong("chat.shout.cooldown", 10) * 1000;
whisper = config.getBoolean("chat.whisper.enabled", true);
whisperChar = config.getString("chat.whisper.char", "#");
whisperDist = config.getInt("chat.whisper.distance", 50);
whisperColor = config.getString("chat.whisper.color", "ITALIC");
defaultcolor = config.getString("chat.defaultcolor", "WHITE");
greyscale = config.getBoolean("chat.greyscale", true);
garbleEnabled = config.getBoolean("chat.range.garbleEnabled", false);
chatDist1 = chatmax - config.getDouble("chat.range.1.distance", 100);
garble1 = config.getInt("chat.range.1.garble", 0);
color1 = config.getString("chat.range.1.color", "GRAY");
chatDist2 = chatmax - config.getDouble("chat.range.2.distance", 50);
garble2 = config.getInt("chat.range.2.garble", 0);
color2 = config.getString("color.range.2.color", "DARK_GRAY");
}
public void sendPrivateMessage(Player from, Player to, String message) {
if (isIgnoring(to.getName(), from.getName())) {
from.sendMessage(ChatColor.YELLOW + to.getName() + ChatColor.RED + " has muted you.");
return;
}
from.sendMessage(ChatColor.LIGHT_PURPLE + "To " + to.getName() + ": " + message);
to.sendMessage(ChatColor.LIGHT_PURPLE + "From " + from.getName() + ": " + message);
}
public void sendPlayerBroadcast(Player player, String message, Set<Player> receivers) {
SaveChat(player, "Broadcast", message);
Location location = player.getLocation();
int x = location.getBlockX();
int y = location.getBlockY();
int z = location.getBlockZ();
double chatdist = 0;
boolean whispering = false;
double chatrange = chatmax;
double added = 0;
boolean shouting = false;
if (yvar && !message.startsWith(whisperChar) && y > ynogarb) {
added = Math.pow(1.1, (y - ynogarb) / 14) * (y - ynogarb);
chatrange += added;
}
if (shout && message.startsWith(shoutChar)) {
if (shoutList.get(player) != null && System.currentTimeMillis() - shoutList.get(player) >= shoutCool) {
shoutList.remove(player);
}
if (shoutList.get(player) == null) {
Float sat = player.getSaturation();
if (sat > 0) {
sat -= shoutHunger;
if (sat <= 0) {
player.setSaturation(0);
player.setFoodLevel(player.getFoodLevel() - Integer.parseInt(sat + ""));
} else {
player.setSaturation(player.getSaturation() - sat);
}
} else {
int food = player.getFoodLevel() - shoutHunger;
if (food < 0) {
food = 0;
}
player.setFoodLevel(food);
}
chatrange += shoutDist;
shoutList.put(player, System.currentTimeMillis());
shouting = true;
} else {
player.sendMessage(ChatColor.RED + "Shout under cooldown, please wait "
+ ((((shoutList.get(player) - System.currentTimeMillis()) + shoutCool) / 1000) + 1) + " seconds");
}
}
for (Player receiver : receivers) {
if(isIgnoring(receiver.getName(), player.getName())){
continue;
}
else{
double garble = 0;
String chat = message;
double randGarble = 0;
ChatColor color = ChatColor.valueOf(defaultcolor);
int rx = receiver.getLocation().getBlockX();
int ry = receiver.getLocation().getBlockY();
int rz = receiver.getLocation().getBlockZ();
chatdist = Math.sqrt(Math.pow(x - rx, 2) + Math.pow(y - ry, 2) + Math.pow(z - rz, 2));
whispering = whisper && message.startsWith(whisperChar);
if (whispering) {
chatrange = whisperDist;
color = ChatColor.valueOf(whisperColor);
randGarble = 0;
} else if (chatdist <= chatDist2 && chatdist > chatDist1) {
if (garbleEnabled) {
randGarble = random.nextInt(garblevar) + garble1;
}
if (greyscale) {
color = ChatColor.valueOf(color1);
}
} else if (chatdist <= chatrange && chatdist > chatDist2) {
if (garbleEnabled) {
randGarble = random.nextInt(garblevar) + garble2;
}
if (greyscale) {
color = ChatColor.valueOf(color2);
}
}
if (garbleEnabled) {
garble = chat.length() * (randGarble / 100.0F);
chat = shuffle(chat, garble);
} else {
chat = message;
}
if (chatdist <= chatrange) {
if (whispering) {
receiver.sendMessage(color + player.getDisplayName() + " whispered: " + chat.substring(1));
} else if (shouting) {
color = ChatColor.valueOf(shoutColor);
receiver.sendMessage(color + player.getDisplayName() + " shouted: " + chat.substring(1));
} else {
receiver.sendMessage(color + player.getDisplayName() + ": " + chat);
}
}
}}
}
private String shuffle(String input, double a) {
int times = (int) a;
StringBuilder sb = new StringBuilder(input);
for (int i = 0; i < times; i++) {
int rand = random.nextInt(input.length());
int replaceRand = random.nextInt(replacement.length());
switch (sb.charAt(rand)) {
case ' ':
case '.':
case ',':
case '!':
continue;
}
sb.setCharAt(rand, replacement.charAt(replaceRand));
}
String output = new String(sb);
return output;
}
public void addChannel(String player1, String player2) {
if (getChannel(player1) != null) {
channels.put(player1, player2);
} else {
channels.put(player1, player2);
}
}
public String getChannel(String player) {
return channels.get(player);
}
public void removeChannel(String player) {
if (channels.containsKey(player)) {
channels.remove(player);
}
}
public void GroupChat(Faction group, StringBuilder message, String player) {
Player player1 = Bukkit.getPlayer(player);
Collection<Player> players = Citadel.getMemberManager().getOnlinePlayers();
String chat = message.toString();
player1.sendMessage(ChatColor.DARK_AQUA + "To group: " + group.getName() + ": " + chat);
for (Player reciever : players) {
if (!group.isMember(reciever.getName())
&& !group.isFounder(reciever.getName())
&& !group.isModerator(reciever.getName())==true) {
continue;
}
if (isIgnoring(reciever.getName(), player)){
continue;
}
if (reciever.getName().equals(player1.getName())) {
continue;
} else {
reciever.sendMessage(ChatColor.DARK_AQUA + "Group " + group.getName() + ", from " + player + ": " + chat);
}
}
}
public void PrivateGroupChat(Faction group, String message, String player) {
Player player1 = Bukkit.getPlayer(player);
Collection<Player> players = Citadel.getMemberManager().getOnlinePlayers();
String chat = message;
player1.sendMessage(ChatColor.DARK_AQUA + "To group: " + group.getName() + ": " + chat);
for (Player reciever : players) {
if (!group.isMember(reciever.getName())
&& !group.isFounder(reciever.getName())
&& !group.isModerator(reciever.getName())) {
continue;
}
if (isIgnoring(reciever.getName(), player) == true){
continue;
}
if (reciever.getName().equals(player1.getName())) {
continue;
}
reciever.sendMessage(ChatColor.DARK_AQUA + "Group " + group.getName() + ", from " + player + ": " + chat);
}
}
public void addGroupTalk(String player, Faction group) {
if (getGroupTalk(player) != null) {
groupchat.put(player, group);
} else {
groupchat.put(player, group);
}
}
public Faction getGroupTalk(String player) {
return groupchat.get(player);
}
public boolean isGroupTalk(String player) {
if (groupchat.containsKey(player)) {
return true;
}
return false;
}
public void removeGroupTalk(String player) {
if (groupchat.containsKey(player)) {
groupchat.remove(player);
}
}
public void SaveChat(Player sender, String type, String message) {
String date = new SimpleDateFormat("dd-MM HH:mm:ss").format(new Date());
String name = sender.getName();
String loc = (int) sender.getLocation().getX() + ", " + (int) sender.getLocation().getY() + ", " + (int) sender.getLocation().getZ();
String textLine = "[" + date + "] [" + loc + "] [" + type + "] [" + name + "] " + message;
try {
plugin.writer.write(textLine);
plugin.writer.newLine();
plugin.writer.flush();
} catch (IOException ex) {
Logger.getLogger(CivChat.class.getName()).log(Level.SEVERE, null, ex);
}
}
public String playerCheck(String player) {
Player[] onlineList = Bukkit.getOnlinePlayers();
for (Player check : onlineList) {
if (check.getName().startsWith(player)) {
return check.getName();
}
}
return player;
}
public boolean isIgnoring(String muter, String muted) {
List<String> ignorelist;
try {
if (ignoreList.containsKey(muter)) {
ignorelist = ignoreList.get(muter);
if (ignorelist.contains(muted)) {
return true;
}
}
else{
return false;
}
} catch (NullPointerException e) {
return false;
}
return false;
}
public void setIgnoreList(String player, String reciever){
List<String> recievers=new ArrayList<String>();
if (ignoreList.get(player)!=null){
recievers= ignoreList.get(player);
recievers.add(reciever);
ignoreList.put(player, recievers);
}
else{
recievers.add(reciever);
ignoreList.put(player, recievers);
}
}
public List<String> getIgnoreList(String player){
return ignoreList.get(player);
}
public void removeIgnore(String player, String reciever){
List<String> removeplayers= new ArrayList<String>();
for (String x: ignoreList.get(player)){
if (x.equals(reciever)){
continue;
}
else{removeplayers.add(x);
}
}
ignoreList.put(player, removeplayers);
}
public void load(File file) throws IOException{
FileInputStream fis = new FileInputStream(file);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
String line;
while ((line=br.readLine()) != null){
String parts[] =line.split(" ");
String owner= parts[0];
List<String> participants= new ArrayList<>();;
for(int x=1; x<=parts.length; x++){
participants.add(parts[x]);
}
ignoreList.put(owner, participants);
}
fis.close();
}
public void save(File file) throws IOException{
FileOutputStream fos = new FileOutputStream(file);
BufferedWriter br = new BufferedWriter(new OutputStreamWriter(fos));
Set<String> main= ignoreList.keySet();
for (String z: main){
br.append(z);
for (String x: ignoreList.get(z)){
br.append(" ");
br.append(x);
}
br.append("\n");
}
br.flush();
fos.close();
}
}
|
shush
|
src/com/untamedears/civchat/ChatManager.java
|
shush
|
<ide><path>rc/com/untamedears/civchat/ChatManager.java
<ide> String parts[] =line.split(" ");
<ide> String owner= parts[0];
<ide> List<String> participants= new ArrayList<>();;
<del> for(int x=1; x<=parts.length; x++){
<add> for(int x=1; x<parts.length; x++){
<ide> participants.add(parts[x]);
<ide> }
<ide> ignoreList.put(owner, participants);
|
|
Java
|
mit
|
c546d4c24a1c693de32630782b1bc057fb3d1464
| 0 |
GluuFederation/oxAuth,madumlao/oxAuth,madumlao/oxAuth,GluuFederation/oxAuth,madumlao/oxAuth,madumlao/oxAuth,GluuFederation/oxAuth,madumlao/oxAuth,GluuFederation/oxAuth,GluuFederation/oxAuth
|
/*
* oxAuth is available under the MIT License (2008). See http://opensource.org/licenses/MIT for full text.
*
* Copyright (c) 2014, Gluu
*/
package org.xdi.oxauth.uma.ws.rs;
import com.wordnik.swagger.annotations.Api;
import com.wordnik.swagger.annotations.ApiOperation;
import com.wordnik.swagger.annotations.ApiResponse;
import com.wordnik.swagger.annotations.ApiResponses;
import org.slf4j.Logger;
import org.xdi.oxauth.uma.authorization.UmaRPT;
import org.xdi.oxauth.model.error.ErrorResponseFactory;
import org.xdi.oxauth.model.uma.RptIntrospectionResponse;
import org.xdi.oxauth.model.uma.UmaConstants;
import org.xdi.oxauth.model.uma.UmaErrorResponseType;
import org.xdi.oxauth.model.uma.persistence.UmaPermission;
import org.xdi.oxauth.uma.service.UmaRptService;
import org.xdi.oxauth.uma.service.UmaScopeService;
import org.xdi.oxauth.uma.service.UmaValidationService;
import org.xdi.oxauth.util.ServerUtil;
import javax.inject.Inject;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.ArrayList;
import java.util.List;
/**
* The endpoint at which the host requests the status of an RPT presented to it by a requester.
* The endpoint is RPT introspection profile implementation defined by
* http://docs.kantarainitiative.org/uma/draft-uma-core.html#uma-bearer-token-profile
*
* @author Yuriy Zabrovarnyy
*/
@Path("/rpt/status")
@Api(value = "/rpt/status", description = "The endpoint at which the host requests the status of an RPT presented to it by a requester." +
" The endpoint is RPT introspection profile implementation defined by UMA specification")
public class UmaRptIntrospectionWS {
@Inject
private Logger log;
@Inject
private ErrorResponseFactory errorResponseFactory;
@Inject
private UmaRptService rptService;
@Inject
private UmaValidationService umaValidationService;
@Inject
private UmaScopeService umaScopeService;
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response introspectGet(@HeaderParam("Authorization") String authorization,
@QueryParam("token") String token,
@QueryParam("token_type_hint") String tokenTypeHint) {
return introspect(authorization, token, tokenTypeHint);
}
@POST
@Produces(MediaType.APPLICATION_JSON)
public Response introspectPost(@HeaderParam("Authorization") String authorization,
@FormParam("token") String token,
@FormParam("token_type_hint") String tokenTypeHint) {
return introspect(authorization, token, tokenTypeHint);
}
private Response introspect(String authorization, String token, String tokenTypeHint) {
try {
umaValidationService.assertHasProtectionScope(authorization);
final UmaRPT rpt = rptService.getRPTByCode(token);
if (!isValid(rpt)) {
return Response.status(Response.Status.OK).
entity(new RptIntrospectionResponse(false)).
cacheControl(ServerUtil.cacheControl(true)).
build();
}
final List<org.xdi.oxauth.model.uma.UmaPermission> permissions = buildStatusResponsePermissions(rpt);
// active status
final RptIntrospectionResponse statusResponse = new RptIntrospectionResponse();
statusResponse.setActive(true);
statusResponse.setExpiresAt(rpt.getExpirationDate());
statusResponse.setIssuedAt(rpt.getCreationDate());
statusResponse.setPermissions(permissions);
statusResponse.setClientId(rpt.getClientId());
statusResponse.setAud(rpt.getClientId());
statusResponse.setSub(rpt.getUserId());
// convert manually to avoid possible conflict between resteasy providers, e.g. jettison, jackson
final String entity = ServerUtil.asJson(statusResponse);
return Response.status(Response.Status.OK).entity(entity).cacheControl(ServerUtil.cacheControl(true)).build();
} catch (Exception ex) {
log.error("Exception happened", ex);
if (ex instanceof WebApplicationException) {
throw (WebApplicationException) ex;
}
throw new WebApplicationException(Response.status(Response.Status.INTERNAL_SERVER_ERROR)
.entity(errorResponseFactory.getUmaJsonErrorResponse(UmaErrorResponseType.SERVER_ERROR)).build());
}
}
private boolean isValid(UmaRPT p_rpt) {
if (p_rpt != null) {
p_rpt.checkExpired();
return p_rpt.isValid();
}
return false;
}
private boolean isValid(UmaPermission permission) {
if (permission != null) {
permission.checkExpired();
return permission.isValid();
}
return false;
}
private List<org.xdi.oxauth.model.uma.UmaPermission> buildStatusResponsePermissions(UmaRPT rpt) {
final List<org.xdi.oxauth.model.uma.UmaPermission> result = new ArrayList<org.xdi.oxauth.model.uma.UmaPermission>();
if (rpt != null) {
final List<UmaPermission> rptPermissions = rptService.getRptPermissions(rpt);
if (rptPermissions != null && !rptPermissions.isEmpty()) {
for (UmaPermission permission : rptPermissions) {
if (isValid(permission)) {
final org.xdi.oxauth.model.uma.UmaPermission toAdd = ServerUtil.convert(permission, umaScopeService);
if (toAdd != null) {
result.add(toAdd);
}
} else {
log.debug("Ignore permission, skip it in response because permission is not valid. Permission dn: {}, rpt dn: {}",
permission.getDn(), rpt.getDn());
}
}
}
}
return result;
}
@GET
@Consumes({UmaConstants.JSON_MEDIA_TYPE})
@Produces({UmaConstants.JSON_MEDIA_TYPE})
@ApiOperation(value = "Not allowed")
@ApiResponses(value = {
@ApiResponse(code = 405, message = "Introspection of RPT is not allowed by GET HTTP method.")
})
public Response requestRptStatusGet(@HeaderParam("Authorization") String authorization,
@FormParam("token") String rpt,
@FormParam("token_type_hint") String tokenTypeHint) {
throw new WebApplicationException(Response.status(405).entity("Introspection of RPT is not allowed by GET HTTP method.").build());
}
}
|
Server/src/main/java/org/xdi/oxauth/uma/ws/rs/UmaRptIntrospectionWS.java
|
/*
* oxAuth is available under the MIT License (2008). See http://opensource.org/licenses/MIT for full text.
*
* Copyright (c) 2014, Gluu
*/
package org.xdi.oxauth.uma.ws.rs;
import com.wordnik.swagger.annotations.Api;
import com.wordnik.swagger.annotations.ApiOperation;
import com.wordnik.swagger.annotations.ApiResponse;
import com.wordnik.swagger.annotations.ApiResponses;
import org.slf4j.Logger;
import org.xdi.oxauth.uma.authorization.UmaRPT;
import org.xdi.oxauth.model.error.ErrorResponseFactory;
import org.xdi.oxauth.model.uma.RptIntrospectionResponse;
import org.xdi.oxauth.model.uma.UmaConstants;
import org.xdi.oxauth.model.uma.UmaErrorResponseType;
import org.xdi.oxauth.model.uma.persistence.UmaPermission;
import org.xdi.oxauth.uma.service.UmaRptService;
import org.xdi.oxauth.uma.service.UmaScopeService;
import org.xdi.oxauth.uma.service.UmaValidationService;
import org.xdi.oxauth.util.ServerUtil;
import javax.inject.Inject;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.ArrayList;
import java.util.List;
/**
* The endpoint at which the host requests the status of an RPT presented to it by a requester.
* The endpoint is RPT introspection profile implementation defined by
* http://docs.kantarainitiative.org/uma/draft-uma-core.html#uma-bearer-token-profile
*
* @author Yuriy Zabrovarnyy
*/
@Path("/rpt/status")
@Api(value = "/rpt/status", description = "The endpoint at which the host requests the status of an RPT presented to it by a requester." +
" The endpoint is RPT introspection profile implementation defined by UMA specification")
public class UmaRptIntrospectionWS {
@Inject
private Logger log;
@Inject
private ErrorResponseFactory errorResponseFactory;
@Inject
private UmaRptService rptService;
@Inject
private UmaValidationService umaValidationService;
@Inject
private UmaScopeService umaScopeService;
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response introspectGet(@HeaderParam("Authorization") String authorization,
@QueryParam("token") String token,
@QueryParam("token_type_hint") String tokenTypeHint) {
return introspect(authorization, token, tokenTypeHint);
}
@POST
@Produces(MediaType.APPLICATION_JSON)
public Response introspectPost(@HeaderParam("Authorization") String authorization,
@FormParam("token") String token,
@FormParam("token_type_hint") String tokenTypeHint) {
return introspect(authorization, token, tokenTypeHint);
}
private Response introspect(String authorization, String token, String tokenTypeHint) {
try {
umaValidationService.assertHasProtectionScope(authorization);
final UmaRPT rpt = rptService.getRPTByCode(token);
if (!isValid(rpt)) {
return Response.status(Response.Status.OK).
entity(new RptIntrospectionResponse(false)).
cacheControl(ServerUtil.cacheControl(true)).
build();
}
final List<org.xdi.oxauth.model.uma.UmaPermission> permissions = buildStatusResponsePermissions(rpt);
// active status
final RptIntrospectionResponse statusResponse = new RptIntrospectionResponse();
statusResponse.setActive(true);
statusResponse.setExpiresAt(rpt.getExpirationDate());
statusResponse.setIssuedAt(rpt.getCreationDate());
statusResponse.setPermissions(permissions);
// convert manually to avoid possible conflict between resteasy providers, e.g. jettison, jackson
final String entity = ServerUtil.asJson(statusResponse);
return Response.status(Response.Status.OK).entity(entity).cacheControl(ServerUtil.cacheControl(true)).build();
} catch (Exception ex) {
log.error("Exception happened", ex);
if (ex instanceof WebApplicationException) {
throw (WebApplicationException) ex;
}
throw new WebApplicationException(Response.status(Response.Status.INTERNAL_SERVER_ERROR)
.entity(errorResponseFactory.getUmaJsonErrorResponse(UmaErrorResponseType.SERVER_ERROR)).build());
}
}
private boolean isValid(UmaRPT p_rpt) {
if (p_rpt != null) {
p_rpt.checkExpired();
return p_rpt.isValid();
}
return false;
}
private boolean isValid(UmaPermission permission) {
if (permission != null) {
permission.checkExpired();
return permission.isValid();
}
return false;
}
private List<org.xdi.oxauth.model.uma.UmaPermission> buildStatusResponsePermissions(UmaRPT rpt) {
final List<org.xdi.oxauth.model.uma.UmaPermission> result = new ArrayList<org.xdi.oxauth.model.uma.UmaPermission>();
if (rpt != null) {
final List<UmaPermission> rptPermissions = rptService.getRptPermissions(rpt);
if (rptPermissions != null && !rptPermissions.isEmpty()) {
for (UmaPermission permission : rptPermissions) {
if (isValid(permission)) {
final org.xdi.oxauth.model.uma.UmaPermission toAdd = ServerUtil.convert(permission, umaScopeService);
if (toAdd != null) {
result.add(toAdd);
}
} else {
log.debug("Ignore permission, skip it in response because permission is not valid. Permission dn: {}, rpt dn: {}",
permission.getDn(), rpt.getDn());
}
}
}
}
return result;
}
@GET
@Consumes({UmaConstants.JSON_MEDIA_TYPE})
@Produces({UmaConstants.JSON_MEDIA_TYPE})
@ApiOperation(value = "Not allowed")
@ApiResponses(value = {
@ApiResponse(code = 405, message = "Introspection of RPT is not allowed by GET HTTP method.")
})
public Response requestRptStatusGet(@HeaderParam("Authorization") String authorization,
@FormParam("token") String rpt,
@FormParam("token_type_hint") String tokenTypeHint) {
throw new WebApplicationException(Response.status(405).entity("Introspection of RPT is not allowed by GET HTTP method.").build());
}
}
|
added client_id to RPT introspection https://github.com/GluuFederation/oxAuth/issues/746
|
Server/src/main/java/org/xdi/oxauth/uma/ws/rs/UmaRptIntrospectionWS.java
|
added client_id to RPT introspection https://github.com/GluuFederation/oxAuth/issues/746
|
<ide><path>erver/src/main/java/org/xdi/oxauth/uma/ws/rs/UmaRptIntrospectionWS.java
<ide> statusResponse.setExpiresAt(rpt.getExpirationDate());
<ide> statusResponse.setIssuedAt(rpt.getCreationDate());
<ide> statusResponse.setPermissions(permissions);
<add> statusResponse.setClientId(rpt.getClientId());
<add> statusResponse.setAud(rpt.getClientId());
<add> statusResponse.setSub(rpt.getUserId());
<ide>
<ide> // convert manually to avoid possible conflict between resteasy providers, e.g. jettison, jackson
<ide> final String entity = ServerUtil.asJson(statusResponse);
|
|
Java
|
apache-2.0
|
6d3312f62bd10bbfdd27a935c5f476b0e2b3b560
| 0 |
MaTriXy/timber,JakeWharton/timber,leixinstar/timber,maxme/timber,jianlei/timber,hejunbinlan/timber,jsibbold/timber,MaTriXy/timber,msdgwzhy6/timber,angcyo/timber,lockerfish/timber,leixinstar/timber,MichaelEvans/timber,vipulshah2010/timber,ab271994/timber,MaTriXy/timber,zhuxiaohao/timber,zhuxiaohao/timber,hejunbinlan/timber,robertschmid/timber,ab271994/timber,jianlei/timber,leixinstar/timber,msdgwzhy6/timber,donnfelker/timber,lockerfish/timber,JakeWharton/timber,robertschmid/timber,angcyo/timber,maxme/timber,MichaelEvans/timber,vipulshah2010/timber,jsibbold/timber,donnfelker/timber
|
package timber.log;
import android.util.Log;
import android.util.SparseBooleanArray;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/** Logging for lazy people. */
public final class Timber {
/** Log a verbose message with optional format args. */
public static void v(String message, Object... args) {
TREE_OF_SOULS.v(message, args);
}
/** Log a verbose exception and a message with optional format args. */
public static void v(Throwable t, String message, Object... args) {
TREE_OF_SOULS.v(t, message, args);
}
/** Log a debug message with optional format args. */
public static void d(String message, Object... args) {
TREE_OF_SOULS.d(message, args);
}
/** Log a debug exception and a message with optional format args. */
public static void d(Throwable t, String message, Object... args) {
TREE_OF_SOULS.d(t, message, args);
}
/** Log an info message with optional format args. */
public static void i(String message, Object... args) {
TREE_OF_SOULS.i(message, args);
}
/** Log an info exception and a message with optional format args. */
public static void i(Throwable t, String message, Object... args) {
TREE_OF_SOULS.i(t, message, args);
}
/** Log a warning message with optional format args. */
public static void w(String message, Object... args) {
TREE_OF_SOULS.w(message, args);
}
/** Log a warning exception and a message with optional format args. */
public static void w(Throwable t, String message, Object... args) {
TREE_OF_SOULS.w(t, message, args);
}
/** Log an error message with optional format args. */
public static void e(String message, Object... args) {
TREE_OF_SOULS.e(message, args);
}
/** Log an error exception and a message with optional format args. */
public static void e(Throwable t, String message, Object... args) {
TREE_OF_SOULS.e(t, message, args);
}
/** Set a one-time tag for use on the next logging call. */
public static Tree tag(String tag) {
for (int index = 0, size = TAGGED_TREES.size(); index < size; index++) {
((TaggedTree) FOREST.get(TAGGED_TREES.keyAt(index))).tag(tag);
}
return TREE_OF_SOULS;
}
/** Add a new logging tree. */
public static void plant(Tree tree) {
if (tree instanceof TaggedTree) {
TAGGED_TREES.append(FOREST.size(), true);
}
FOREST.add(tree);
}
static final List<Tree> FOREST = new CopyOnWriteArrayList<Tree>();
static final SparseBooleanArray TAGGED_TREES = new SparseBooleanArray();
/** A {@link Tree} that delegates to all planted trees in the {@link #FOREST forest}. */
private static final Tree TREE_OF_SOULS = new Tree() {
@Override public void v(String message, Object... args) {
for (Tree tree : FOREST) {
tree.v(message, args);
}
}
@Override public void v(Throwable t, String message, Object... args) {
for (Tree tree : FOREST) {
tree.v(t, message, args);
}
}
@Override public void d(String message, Object... args) {
for (Tree tree : FOREST) {
tree.d(message, args);
}
}
@Override public void d(Throwable t, String message, Object... args) {
for (Tree tree : FOREST) {
tree.d(t, message, args);
}
}
@Override public void i(String message, Object... args) {
for (Tree tree : FOREST) {
tree.i(message, args);
}
}
@Override public void i(Throwable t, String message, Object... args) {
for (Tree tree : FOREST) {
tree.i(t, message, args);
}
}
@Override public void w(String message, Object... args) {
for (Tree tree : FOREST) {
tree.w(message, args);
}
}
@Override public void w(Throwable t, String message, Object... args) {
for (Tree tree : FOREST) {
tree.w(t, message, args);
}
}
@Override public void e(String message, Object... args) {
for (Tree tree : FOREST) {
tree.e(message, args);
}
}
@Override public void e(Throwable t, String message, Object... args) {
for (Tree tree : FOREST) {
tree.e(t, message, args);
}
}
};
private Timber() {
}
/** A facade for handling logging calls. Install instances via {@link #plant}. */
public interface Tree {
/** Log a verbose message with optional format args. */
void v(String message, Object... args);
/** Log a verbose exception and a message with optional format args. */
void v(Throwable t, String message, Object... args);
/** Log a debug message with optional format args. */
void d(String message, Object... args);
/** Log a debug exception and a message with optional format args. */
void d(Throwable t, String message, Object... args);
/** Log an info message with optional format args. */
void i(String message, Object... args);
/** Log an info exception and a message with optional format args. */
void i(Throwable t, String message, Object... args);
/** Log a warning message with optional format args. */
void w(String message, Object... args);
/** Log a warning exception and a message with optional format args. */
void w(Throwable t, String message, Object... args);
/** Log an error message with optional format args. */
void e(String message, Object... args);
/** Log an error exception and a message with optional format args. */
void e(Throwable t, String message, Object... args);
}
/** A facade for attaching tags to logging calls. Install instances via {@link #plant} */
public interface TaggedTree extends Tree {
/** Set a one-time tag for use on the next logging call. */
void tag(String tag);
}
/** A {@link Tree} for debug builds. Automatically infers the tag from the calling class. */
public static class DebugTree implements TaggedTree {
private static final Pattern ANONYMOUS_CLASS = Pattern.compile("\\$\\d+$");
private String nextTag;
private String createTag() {
String tag = nextTag;
if (tag != null) {
nextTag = null;
return tag;
}
tag = new Throwable().getStackTrace()[4].getClassName();
Matcher m = ANONYMOUS_CLASS.matcher(tag);
if (m.find()) {
tag = m.replaceAll("");
}
return tag.substring(tag.lastIndexOf('.') + 1);
}
@Override public void v(String message, Object... args) {
Log.v(createTag(), String.format(message, args));
}
@Override public void v(Throwable t, String message, Object... args) {
Log.v(createTag(), String.format(message, args), t);
}
@Override public void d(String message, Object... args) {
Log.d(createTag(), String.format(message, args));
}
@Override public void d(Throwable t, String message, Object... args) {
Log.d(createTag(), String.format(message, args), t);
}
@Override public void i(String message, Object... args) {
Log.i(createTag(), String.format(message, args));
}
@Override public void i(Throwable t, String message, Object... args) {
Log.i(createTag(), String.format(message, args), t);
}
@Override public void w(String message, Object... args) {
Log.w(createTag(), String.format(message, args));
}
@Override public void w(Throwable t, String message, Object... args) {
Log.w(createTag(), String.format(message, args), t);
}
@Override public void e(String message, Object... args) {
Log.e(createTag(), String.format(message, args));
}
@Override public void e(Throwable t, String message, Object... args) {
Log.e(createTag(), String.format(message, args), t);
}
@Override public void tag(String tag) {
nextTag = tag;
}
}
/** A {@link Tree} which does nothing. Useful for extending. */
public static class HollowTree implements Tree {
@Override public void v(String message, Object... args) {
}
@Override public void v(Throwable t, String message, Object... args) {
}
@Override public void d(String message, Object... args) {
}
@Override public void d(Throwable t, String message, Object... args) {
}
@Override public void i(String message, Object... args) {
}
@Override public void i(Throwable t, String message, Object... args) {
}
@Override public void w(String message, Object... args) {
}
@Override public void w(Throwable t, String message, Object... args) {
}
@Override public void e(String message, Object... args) {
}
@Override public void e(Throwable t, String message, Object... args) {
}
}
}
|
timber/src/main/java/timber/log/Timber.java
|
package timber.log;
import android.util.Log;
import android.util.SparseBooleanArray;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/** Logging for lazy people. */
public final class Timber {
/** Log a debug message with optional format args. */
public static void d(String message, Object... args) {
TREE_OF_SOULS.d(message, args);
}
/** Log a debug exception and a message with optional format args. */
public static void d(Throwable t, String message, Object... args) {
TREE_OF_SOULS.d(t, message, args);
}
/** Log an info message with optional format args. */
public static void i(String message, Object... args) {
TREE_OF_SOULS.i(message, args);
}
/** Log an info exception and a message with optional format args. */
public static void i(Throwable t, String message, Object... args) {
TREE_OF_SOULS.i(t, message, args);
}
/** Log a warning message with optional format args. */
public static void w(String message, Object... args) {
TREE_OF_SOULS.w(message, args);
}
/** Log a warning exception and a message with optional format args. */
public static void w(Throwable t, String message, Object... args) {
TREE_OF_SOULS.w(t, message, args);
}
/** Log an error message with optional format args. */
public static void e(String message, Object... args) {
TREE_OF_SOULS.e(message, args);
}
/** Log an error exception and a message with optional format args. */
public static void e(Throwable t, String message, Object... args) {
TREE_OF_SOULS.e(t, message, args);
}
/** Set a one-time tag for use on the next logging call. */
public static Tree tag(String tag) {
for (int index = 0, size = TAGGED_TREES.size(); index < size; index++) {
((TaggedTree) FOREST.get(TAGGED_TREES.keyAt(index))).tag(tag);
}
return TREE_OF_SOULS;
}
/** Add a new logging tree. */
public static void plant(Tree tree) {
if (tree instanceof TaggedTree) {
TAGGED_TREES.append(FOREST.size(), true);
}
FOREST.add(tree);
}
static final List<Tree> FOREST = new CopyOnWriteArrayList<Tree>();
static final SparseBooleanArray TAGGED_TREES = new SparseBooleanArray();
/** A {@link Tree} that delegates to all planted trees in the {@link #FOREST forest}. */
private static final Tree TREE_OF_SOULS = new Tree() {
@Override public void d(String message, Object... args) {
for (Tree tree : FOREST) {
tree.d(message, args);
}
}
@Override public void d(Throwable t, String message, Object... args) {
for (Tree tree : FOREST) {
tree.d(t, message, args);
}
}
@Override public void i(String message, Object... args) {
for (Tree tree : FOREST) {
tree.i(message, args);
}
}
@Override public void i(Throwable t, String message, Object... args) {
for (Tree tree : FOREST) {
tree.i(t, message, args);
}
}
@Override public void w(String message, Object... args) {
for (Tree tree : FOREST) {
tree.w(message, args);
}
}
@Override public void w(Throwable t, String message, Object... args) {
for (Tree tree : FOREST) {
tree.w(t, message, args);
}
}
@Override public void e(String message, Object... args) {
for (Tree tree : FOREST) {
tree.e(message, args);
}
}
@Override public void e(Throwable t, String message, Object... args) {
for (Tree tree : FOREST) {
tree.e(t, message, args);
}
}
};
private Timber() {
}
/** A facade for handling logging calls. Install instances via {@link #plant}. */
public interface Tree {
/** Log a debug message with optional format args. */
void d(String message, Object... args);
/** Log a debug exception and a message with optional format args. */
void d(Throwable t, String message, Object... args);
/** Log an info message with optional format args. */
void i(String message, Object... args);
/** Log an info exception and a message with optional format args. */
void i(Throwable t, String message, Object... args);
/** Log a warning message with optional format args. */
void w(String message, Object... args);
/** Log a warning exception and a message with optional format args. */
void w(Throwable t, String message, Object... args);
/** Log an error message with optional format args. */
void e(String message, Object... args);
/** Log an error exception and a message with optional format args. */
void e(Throwable t, String message, Object... args);
}
/** A facade for attaching tags to logging calls. Install instances via {@link #plant} */
public interface TaggedTree extends Tree {
/** Set a one-time tag for use on the next logging call. */
void tag(String tag);
}
/** A {@link Tree} for debug builds. Automatically infers the tag from the calling class. */
public static class DebugTree implements TaggedTree {
private static final Pattern ANONYMOUS_CLASS = Pattern.compile("\\$\\d+$");
private String nextTag;
private String createTag() {
String tag = nextTag;
if (tag != null) {
nextTag = null;
return tag;
}
tag = new Throwable().getStackTrace()[4].getClassName();
Matcher m = ANONYMOUS_CLASS.matcher(tag);
if (m.find()) {
tag = m.replaceAll("");
}
return tag.substring(tag.lastIndexOf('.') + 1);
}
@Override public void d(String message, Object... args) {
Log.d(createTag(), String.format(message, args));
}
@Override public void d(Throwable t, String message, Object... args) {
Log.d(createTag(), String.format(message, args), t);
}
@Override public void i(String message, Object... args) {
Log.i(createTag(), String.format(message, args));
}
@Override public void i(Throwable t, String message, Object... args) {
Log.i(createTag(), String.format(message, args), t);
}
@Override public void w(String message, Object... args) {
Log.w(createTag(), String.format(message, args));
}
@Override public void w(Throwable t, String message, Object... args) {
Log.w(createTag(), String.format(message, args), t);
}
@Override public void e(String message, Object... args) {
Log.e(createTag(), String.format(message, args));
}
@Override public void e(Throwable t, String message, Object... args) {
Log.e(createTag(), String.format(message, args), t);
}
@Override public void tag(String tag) {
nextTag = tag;
}
}
/** A {@link Tree} which does nothing. Useful for extending. */
public static class HollowTree implements Tree {
@Override public void d(String message, Object... args) {
}
@Override public void d(Throwable t, String message, Object... args) {
}
@Override public void i(String message, Object... args) {
}
@Override public void i(Throwable t, String message, Object... args) {
}
@Override public void w(String message, Object... args) {
}
@Override public void w(Throwable t, String message, Object... args) {
}
@Override public void e(String message, Object... args) {
}
@Override public void e(Throwable t, String message, Object... args) {
}
}
}
|
Added v() methods
The v() methods were missing from the Tree interface, but in some cases they
can be quite useful.
|
timber/src/main/java/timber/log/Timber.java
|
Added v() methods
|
<ide><path>imber/src/main/java/timber/log/Timber.java
<ide>
<ide> /** Logging for lazy people. */
<ide> public final class Timber {
<add> /** Log a verbose message with optional format args. */
<add> public static void v(String message, Object... args) {
<add> TREE_OF_SOULS.v(message, args);
<add> }
<add>
<add> /** Log a verbose exception and a message with optional format args. */
<add> public static void v(Throwable t, String message, Object... args) {
<add> TREE_OF_SOULS.v(t, message, args);
<add> }
<add>
<ide> /** Log a debug message with optional format args. */
<ide> public static void d(String message, Object... args) {
<ide> TREE_OF_SOULS.d(message, args);
<ide>
<ide> /** A {@link Tree} that delegates to all planted trees in the {@link #FOREST forest}. */
<ide> private static final Tree TREE_OF_SOULS = new Tree() {
<add> @Override public void v(String message, Object... args) {
<add> for (Tree tree : FOREST) {
<add> tree.v(message, args);
<add> }
<add> }
<add>
<add> @Override public void v(Throwable t, String message, Object... args) {
<add> for (Tree tree : FOREST) {
<add> tree.v(t, message, args);
<add> }
<add> }
<add>
<ide> @Override public void d(String message, Object... args) {
<ide> for (Tree tree : FOREST) {
<ide> tree.d(message, args);
<ide>
<ide> /** A facade for handling logging calls. Install instances via {@link #plant}. */
<ide> public interface Tree {
<add> /** Log a verbose message with optional format args. */
<add> void v(String message, Object... args);
<add>
<add> /** Log a verbose exception and a message with optional format args. */
<add> void v(Throwable t, String message, Object... args);
<add>
<ide> /** Log a debug message with optional format args. */
<ide> void d(String message, Object... args);
<ide>
<ide> return tag.substring(tag.lastIndexOf('.') + 1);
<ide> }
<ide>
<add> @Override public void v(String message, Object... args) {
<add> Log.v(createTag(), String.format(message, args));
<add> }
<add>
<add> @Override public void v(Throwable t, String message, Object... args) {
<add> Log.v(createTag(), String.format(message, args), t);
<add> }
<add>
<ide> @Override public void d(String message, Object... args) {
<ide> Log.d(createTag(), String.format(message, args));
<ide> }
<ide>
<ide> /** A {@link Tree} which does nothing. Useful for extending. */
<ide> public static class HollowTree implements Tree {
<add> @Override public void v(String message, Object... args) {
<add> }
<add>
<add> @Override public void v(Throwable t, String message, Object... args) {
<add> }
<add>
<ide> @Override public void d(String message, Object... args) {
<ide> }
<ide>
|
|
Java
|
apache-2.0
|
50b08c670e96e6fdc0a02df2f082b1187fc3fc4b
| 0 |
mizdebsk/java-deptools-native
|
/*-
* Copyright (c) 2016 Red Hat, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.fedoraproject.javadeptools.rpm;
import static org.fedoraproject.javadeptools.rpm.Rpm.RPMDBI_INSTFILENAMES;
import static org.fedoraproject.javadeptools.rpm.Rpm.rpmReadConfigFiles;
import static org.fedoraproject.javadeptools.rpm.Rpm.rpmdbFreeIterator;
import static org.fedoraproject.javadeptools.rpm.Rpm.rpmdbNextIterator;
import static org.fedoraproject.javadeptools.rpm.Rpm.rpmtsCreate;
import static org.fedoraproject.javadeptools.rpm.Rpm.rpmtsFree;
import static org.fedoraproject.javadeptools.rpm.Rpm.rpmtsInitIterator;
import static org.fedoraproject.javadeptools.rpm.Rpm.rpmtsSetRootDir;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import com.sun.jna.Pointer;
/**
* @author Mikolaj Izdebski
*/
public class RpmQuery {
static {
rpmReadConfigFiles(null, null);
}
public static List<NEVRA> byFile(Path path) {
return byFile(path, null);
}
public static List<NEVRA> byFile(Path path, Path root) {
Pointer ts = rpmtsCreate();
try {
if (path != null) {
if (rpmtsSetRootDir(ts, root.toString()) != 0) {
return Collections.emptyList();
}
}
Pointer mi = rpmtsInitIterator(ts, RPMDBI_INSTFILENAMES, path.toAbsolutePath().toString(), 0);
try {
List<NEVRA> providers = new ArrayList<>();
Pointer h;
while ((h = rpmdbNextIterator(mi)) != null) {
providers.add(new NEVRA(h));
}
return Collections.unmodifiableList(providers);
} finally {
rpmdbFreeIterator(mi);
}
} finally {
rpmtsFree(ts);
}
}
}
|
src/main/java/org/fedoraproject/javadeptools/rpm/RpmQuery.java
|
/*-
* Copyright (c) 2016 Red Hat, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.fedoraproject.javadeptools.rpm;
import static org.fedoraproject.javadeptools.rpm.Rpm.RPMDBI_INSTFILENAMES;
import static org.fedoraproject.javadeptools.rpm.Rpm.rpmReadConfigFiles;
import static org.fedoraproject.javadeptools.rpm.Rpm.rpmdbFreeIterator;
import static org.fedoraproject.javadeptools.rpm.Rpm.rpmdbNextIterator;
import static org.fedoraproject.javadeptools.rpm.Rpm.rpmtsCreate;
import static org.fedoraproject.javadeptools.rpm.Rpm.rpmtsFree;
import static org.fedoraproject.javadeptools.rpm.Rpm.rpmtsInitIterator;
import static org.fedoraproject.javadeptools.rpm.Rpm.rpmtsSetRootDir;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import com.sun.jna.Pointer;
/**
* @author Mikolaj Izdebski
*/
public class RpmQuery {
static {
rpmReadConfigFiles(null, null);
}
public static List<NEVRA> byFile(Path path) {
return byFile(path, null);
}
public static List<NEVRA> byFile(Path path, Path root) {
Pointer ts = rpmtsCreate();
try {
if (path != null) {
if (rpmtsSetRootDir(ts, root.toString()) != 0) {
return Collections.emptyList();
}
}
Pointer mi = rpmtsInitIterator(ts, RPMDBI_INSTFILENAMES, path.toAbsolutePath().toString(), 0);
try {
List<NEVRA> providers = new ArrayList<>();
Pointer h;
while ((h = rpmdbNextIterator(mi)) != null) {
providers.add(new NEVRA(h));
}
return Collections.unmodifiableList(providers);
} finally {
rpmdbFreeIterator(mi);
}
} finally {
rpmtsFree(ts);
}
}
public static void main(String[] args) {
List<NEVRA> providers = RpmQuery.byFile(Paths.get("/usr/bin/bash"), Paths.get("/tmp/tr1"));
for (NEVRA prov : providers) {
System.out.println(prov.getName());
}
}
}
|
Remove letfover test code
|
src/main/java/org/fedoraproject/javadeptools/rpm/RpmQuery.java
|
Remove letfover test code
|
<ide><path>rc/main/java/org/fedoraproject/javadeptools/rpm/RpmQuery.java
<ide> import static org.fedoraproject.javadeptools.rpm.Rpm.rpmtsSetRootDir;
<ide>
<ide> import java.nio.file.Path;
<del>import java.nio.file.Paths;
<ide> import java.util.ArrayList;
<ide> import java.util.Collections;
<ide> import java.util.List;
<ide> }
<ide> }
<ide>
<del> public static void main(String[] args) {
<del> List<NEVRA> providers = RpmQuery.byFile(Paths.get("/usr/bin/bash"), Paths.get("/tmp/tr1"));
<del> for (NEVRA prov : providers) {
<del> System.out.println(prov.getName());
<del> }
<del> }
<del>
<ide> }
|
|
JavaScript
|
mit
|
ec460ee1e0b1adc0b03be4d395ab1439226ac984
| 0 |
supnate/rekit-core
|
const app = require('./app');
const feature = require('./feature');
const component = require('./component');
const action = require('./action');
const hooks = require('./hooks');
module.exports = {
name: 'rekit-react-core',
appType: 'rekit-react',
app,
hooks,
elements: {
feature,
component,
action,
},
};
|
plugins/rekit-react-core/index.js
|
const app = require('./app');
const feature = require('./feature');
const component = require('./component');
const action = require('./action');
const hooks = require('./hooks');
module.exports = {
name: 'rekit-react-core',
app,
hooks,
elements: {
feature,
component,
action,
},
};
|
Add appType.
|
plugins/rekit-react-core/index.js
|
Add appType.
|
<ide><path>lugins/rekit-react-core/index.js
<ide>
<ide> module.exports = {
<ide> name: 'rekit-react-core',
<add> appType: 'rekit-react',
<ide> app,
<ide> hooks,
<ide> elements: {
|
|
Java
|
mit
|
a74f504a1e370607004ffc57756ad669b2eed726
| 0 |
shortcutmedia/shortcut-deeplink-sdk-android,shortcutmedia/shortcut-android-sdk
|
package sc.shortcut.sdk.android.deeplinking;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
/**
* Main Singleton class.
*/
public class SCDeepLinking {
private static final String LOG_TAG = SCDeepLinking.class.getSimpleName();
private static final String LINK_ID_KEY= "sc_link_id";
private static SCDeepLinking sSCDeepLinking;
private Context mContext;
private SCActivityLifecyleObserver mActivityLifecyleObserver;
private boolean mActivityLifecyleCallbackRegistred;
private SCPreference mPreference;
private boolean mAutoSessionMode;
private boolean mTestMode;
private Activity mCurrentActivity;
private Uri mDeepLinkAtLaunch;
private Uri mDeepLink;
private SCSession mCurrentSession;
private Map<Activity, SCSession> mSessions;
private boolean mDeviceRotated;
private SCDeepLinking(Context context) {
mContext = context;
mPreference = new SCPreference(context.getApplicationContext());
mSessions = new HashMap<>();
if (context instanceof SCDeepLinkingApp) {
mAutoSessionMode = true;
setActivityLifeCycleObserver((Application) context.getApplicationContext());
}
}
public static SCDeepLinking getInstance(Context context) {
if (sSCDeepLinking == null) {
sSCDeepLinking = new SCDeepLinking(context);
}
return sSCDeepLinking;
}
public static SCDeepLinking getInstance() {
return sSCDeepLinking;
}
public void startSession(Intent intent) {
Activity activity = (Activity) mContext;
startSession(activity, intent);
}
public void startSession(Activity activity, Intent intent) {
mCurrentActivity = activity;
mDeepLinkAtLaunch = getDeepLinkFromIntent(intent);
if (mDeepLinkAtLaunch == null && isFirstLaunch()) {
generateSessionId();
SCSession session = mSessions.get(activity);
// check for deferred deep link
PostTask postTask = new PostTask();
postTask.execute(new SCServerRequestRegisterFirstOpen(session));
try {
SCServerResponse response = postTask.get(5000, TimeUnit.MILLISECONDS);
Uri deferredDeepLink = response.getDeepLink();
if (deferredDeepLink != null) {
handleDeepLink(activity, deferredDeepLink);
mCurrentSession.setDeepLink(deferredDeepLink);
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (TimeoutException e) {
e.printStackTrace();
}
} else if (mDeepLinkAtLaunch != null) {
SCSession session = mSessions.get(activity);
if (session == null) {
if (!mDeviceRotated) {
generateSessionId();
mDeviceRotated = false;
} else {
saveSessionId();
}
}
session = mSessions.get(activity);
if (session != null) {
session.open();
handleDeepLink(activity, mDeepLinkAtLaunch);
PostTask postTask = new PostTask();
postTask.execute(new SCServerRequestRegisterOpen(session));
}
}
// clean up
if (isFirstLaunch()) {
mPreference.setFirstLuanch(false);
}
}
public void stopSession(Activity activity) {
SCSession session = mSessions.get(activity);
if (session != null && !session.isClosed()) {
session.close();
PostTask postTask = new PostTask();
postTask.execute(new SCServerRequestRegisterClose(session));
}
}
public Uri getDeepLink() {
return mDeepLink;
}
public boolean isFirstLaunch() {
return mPreference.isFirstLaunch();
}
private void handleDeepLink(Activity activity, Uri deepLink) {
String linkId = deepLink.getQueryParameter(LINK_ID_KEY);
if (linkId != null) {
mCurrentActivity = activity;
}
// TODO do not strip Deeplink id if prevented by configuration
mDeepLink = SCUtils.uriStripQueryParameter(deepLink, LINK_ID_KEY);
activity.getIntent().setData(mDeepLink);
}
private class PostTask extends AsyncTask<SCServerRequest, Void, SCServerResponse> {
@Override
protected SCServerResponse doInBackground(SCServerRequest... params) {
SCServerRequest request = params[0];
JSONObject json = request.doRequest();
return new SCServerResponse(json);
}
}
private Uri getDeepLinkFromIntent(Intent intent) {
String action = intent.getAction();
Uri data = intent.getData();
return Intent.ACTION_VIEW.equals(action) && data != null ? data : null;
}
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
private void setActivityLifeCycleObserver(Application application) {
try {
mActivityLifecyleObserver = new SCActivityLifecyleObserver();
/* Set an observer for activity life cycle events. */
application.unregisterActivityLifecycleCallbacks(mActivityLifecyleObserver);
application.registerActivityLifecycleCallbacks(mActivityLifecyleObserver);
mActivityLifecyleCallbackRegistred = true;
} catch (NoSuchMethodError Ex) {
mActivityLifecyleCallbackRegistred = false;
// isAutoSessionMode_ = false;
/* LifeCycleEvents are available only from API level 14. */
Log.w(LOG_TAG, SCErrorMessages.SANITIZE_NOT_AVAILABLE_MESSAGE);
} catch (NoClassDefFoundError Ex) {
mActivityLifecyleCallbackRegistred = false;
// isAutoSessionMode_ = false;
/* LifeCycleEvents are available only from API level 14. */
Log.w(LOG_TAG, SCErrorMessages.SANITIZE_NOT_AVAILABLE_MESSAGE);
}
}
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
private class SCActivityLifecyleObserver implements Application.ActivityLifecycleCallbacks {
@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
mDeviceRotated = savedInstanceState != null;
if (!mDeviceRotated) {
SCDeepLinking.getInstance(activity).startSession(activity, activity.getIntent());
}
}
@Override
public void onActivityStarted(Activity activity) {
}
@Override
public void onActivityResumed(Activity activity) {
}
@Override
public void onActivityPaused(Activity activity) {
}
@Override
public void onActivityStopped(Activity activity) {
// SCDeepLinking.getInstance(activity).stopSession(activity);
}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
}
@Override
public void onActivityDestroyed(Activity activity) {
}
}
SCPreference getPreference() {
return mPreference;
}
private void generateSessionId() {
mCurrentSession = new SCSession(mDeepLinkAtLaunch);
saveSessionId();
}
private void saveSessionId() {
mSessions.put(mCurrentActivity, mCurrentSession);
}
}
|
DeepLinkingSDK/src/main/java/sc/shortcut/sdk/android/deeplinking/SCDeepLinking.java
|
package sc.shortcut.sdk.android.deeplinking;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
/**
* Main Singleton class.
*/
public class SCDeepLinking {
private static final String LOG_TAG = SCDeepLinking.class.getSimpleName();
private static final String LINK_ID_KEY= "sc_link_id";
private static SCDeepLinking sSCDeepLinking;
private Context mContext;
private SCActivityLifecyleObserver mActivityLifecyleObserver;
private boolean mActivityLifecyleCallbackRegistred;
private SCPreference mPreference;
private boolean mAutoSessionMode;
private boolean mTestMode;
private Activity mCurrentActivity;
private Uri mDeepLinkAtLaunch;
private Uri mDeepLink;
private SCSession mCurrentSession;
private Map<Activity, SCSession> mSessions;
private boolean mDeviceRotated;
private SCDeepLinking(Context context) {
mContext = context;
mPreference = new SCPreference(context.getApplicationContext());
mSessions = new HashMap<>();
if (context instanceof SCDeepLinkingApp) {
mAutoSessionMode = true;
setActivityLifeCycleObserver((Application) context.getApplicationContext());
}
if (context instanceof Activity) {
Intent intent = ((Activity) context).getIntent();
mDeepLinkAtLaunch = getDeepLinkFromIntent(intent);
// TODO do not strip Deeplink id if prevented by configuration
mDeepLink = SCUtils.uriStripQueryParameter(mDeepLinkAtLaunch, LINK_ID_KEY);
intent.setData(mDeepLink);
}
}
public static SCDeepLinking getInstance(Context context) {
if (sSCDeepLinking == null) {
sSCDeepLinking = new SCDeepLinking(context);
}
return sSCDeepLinking;
}
public static SCDeepLinking getInstance() {
return sSCDeepLinking;
}
public void startSession(Intent intent) {
Activity activity = (Activity) mContext;
startSession(activity, intent);
}
public void startSession(Activity activity, Intent intent) {
mCurrentActivity = activity;
mDeepLinkAtLaunch = getDeepLinkFromIntent(intent);
if (mDeepLinkAtLaunch == null && isFirstLaunch()) {
generateSessionId();
SCSession session = mSessions.get(activity);
// check for deferred deep link
PostTask postTask = new PostTask();
postTask.execute(new SCServerRequestRegisterFirstOpen(session));
try {
SCServerResponse response = postTask.get(5000, TimeUnit.MILLISECONDS);
Uri deferredDeepLink = response.getDeepLink();
if (deferredDeepLink != null) {
handleDeepLink(activity, deferredDeepLink);
mCurrentSession.setDeepLink(deferredDeepLink);
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (TimeoutException e) {
e.printStackTrace();
}
} else if (mDeepLinkAtLaunch != null) {
SCSession session = mSessions.get(activity);
if (session == null) {
if (!mDeviceRotated) {
generateSessionId();
mDeviceRotated = false;
} else {
saveSessionId();
}
}
session = mSessions.get(activity);
if (session != null) {
session.open();
handleDeepLink(activity, mDeepLinkAtLaunch);
PostTask postTask = new PostTask();
postTask.execute(new SCServerRequestRegisterOpen(session));
}
}
// clean up
if (isFirstLaunch()) {
mPreference.setFirstLuanch(false);
}
}
public void stopSession(Activity activity) {
SCSession session = mSessions.get(activity);
if (session != null && !session.isClosed()) {
session.close();
PostTask postTask = new PostTask();
postTask.execute(new SCServerRequestRegisterClose(session));
}
}
public Uri getDeepLink() {
return mDeepLink;
}
public boolean isFirstLaunch() {
return mPreference.isFirstLaunch();
}
private void handleDeepLink(Activity activity, Uri deepLink) {
String linkId = deepLink.getQueryParameter(LINK_ID_KEY);
if (linkId != null) {
mCurrentActivity = activity;
}
// TODO do not strip Deeplink id if prevented by configuration
mDeepLink = SCUtils.uriStripQueryParameter(deepLink, LINK_ID_KEY);
activity.getIntent().setData(mDeepLink);
}
private class PostTask extends AsyncTask<SCServerRequest, Void, SCServerResponse> {
@Override
protected SCServerResponse doInBackground(SCServerRequest... params) {
SCServerRequest request = params[0];
JSONObject json = request.doRequest();
return new SCServerResponse(json);
}
}
private Uri getDeepLinkFromIntent(Intent intent) {
String action = intent.getAction();
Uri data = intent.getData();
return Intent.ACTION_VIEW.equals(action) && data != null ? data : null;
}
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
private void setActivityLifeCycleObserver(Application application) {
try {
mActivityLifecyleObserver = new SCActivityLifecyleObserver();
/* Set an observer for activity life cycle events. */
application.unregisterActivityLifecycleCallbacks(mActivityLifecyleObserver);
application.registerActivityLifecycleCallbacks(mActivityLifecyleObserver);
mActivityLifecyleCallbackRegistred = true;
} catch (NoSuchMethodError Ex) {
mActivityLifecyleCallbackRegistred = false;
// isAutoSessionMode_ = false;
/* LifeCycleEvents are available only from API level 14. */
Log.w(LOG_TAG, SCErrorMessages.SANITIZE_NOT_AVAILABLE_MESSAGE);
} catch (NoClassDefFoundError Ex) {
mActivityLifecyleCallbackRegistred = false;
// isAutoSessionMode_ = false;
/* LifeCycleEvents are available only from API level 14. */
Log.w(LOG_TAG, SCErrorMessages.SANITIZE_NOT_AVAILABLE_MESSAGE);
}
}
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
private class SCActivityLifecyleObserver implements Application.ActivityLifecycleCallbacks {
@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
mDeviceRotated = savedInstanceState != null;
if (!mDeviceRotated) {
SCDeepLinking.getInstance(activity).startSession(activity, activity.getIntent());
}
}
@Override
public void onActivityStarted(Activity activity) {
}
@Override
public void onActivityResumed(Activity activity) {
}
@Override
public void onActivityPaused(Activity activity) {
}
@Override
public void onActivityStopped(Activity activity) {
// SCDeepLinking.getInstance(activity).stopSession(activity);
}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
}
@Override
public void onActivityDestroyed(Activity activity) {
}
}
SCPreference getPreference() {
return mPreference;
}
private void generateSessionId() {
mCurrentSession = new SCSession(mDeepLinkAtLaunch);
saveSessionId();
}
private void saveSessionId() {
mSessions.put(mCurrentActivity, mCurrentSession);
}
}
|
fix: unobserved activity lifecyle method breaks otherwise
|
DeepLinkingSDK/src/main/java/sc/shortcut/sdk/android/deeplinking/SCDeepLinking.java
|
fix: unobserved activity lifecyle method breaks otherwise
|
<ide><path>eepLinkingSDK/src/main/java/sc/shortcut/sdk/android/deeplinking/SCDeepLinking.java
<ide> mAutoSessionMode = true;
<ide> setActivityLifeCycleObserver((Application) context.getApplicationContext());
<ide> }
<del>
<del> if (context instanceof Activity) {
<del> Intent intent = ((Activity) context).getIntent();
<del> mDeepLinkAtLaunch = getDeepLinkFromIntent(intent);
<del>
<del> // TODO do not strip Deeplink id if prevented by configuration
<del> mDeepLink = SCUtils.uriStripQueryParameter(mDeepLinkAtLaunch, LINK_ID_KEY);
<del> intent.setData(mDeepLink);
<del> }
<ide> }
<ide>
<ide> public static SCDeepLinking getInstance(Context context) {
|
|
JavaScript
|
mit
|
6fb32273b6018c2c3c940cd3747ac12c1d2509cc
| 0 |
jlmakes/scrollReveal.js,julianlloyd/scrollReveal.js
|
import delegate from './delegate'
import { each } from '../../utils/generic'
export default function initialize () {
/**
* Let's take stock of which containers and sequences
* our current store of elements is actively using,
* and add each elements initial styles.
*/
const activeContainerIds = []
const activeSequenceIds = []
each(this.store.elements, element => {
if (activeContainerIds.indexOf(element.containerId) === -1) {
activeContainerIds.push(element.containerId)
}
if (activeSequenceIds.indexOf(element.sequence.id) === -1) {
activeSequenceIds.push(element.sequence.id)
}
/**
* Since we may be initializing elements that have
* already been revealed, e.g. invoking sync(),
* discern whether to use initial or final styles.
*/
let styles
if (element.visible) {
styles = [
element.styles.inline.generated,
element.styles.opacity.computed,
element.styles.transform.generated.final,
].join(' ')
} else {
styles = [
element.styles.inline.generated,
element.styles.opacity.generated,
element.styles.transform.generated.initial,
].join(' ')
}
element.node.setAttribute('style', styles)
})
/**
* Remove unused sequences.
*/
each(this.store.sequences, sequence => {
if (activeSequenceIds.indexOf(sequence.id) === -1) {
delete this.store.sequences[sequence.id]
}
})
each(this.store.containers, container => {
/**
* Remove unused containers.
*/
if (activeContainerIds.indexOf(container.id) === -1) {
container.node.removeEventListener('scroll', delegate)
container.node.removeEventListener('resize', delegate)
delete this.store.containers[container.id]
/**
* The default container is the <html> element, and in
* this case we listen for scroll events on the window.
*/
} else if (container.node === document.documentElement) {
window.addEventListener('scroll', delegate.bind(this))
window.addEventListener('resize', delegate.bind(this))
/**
* Otherwise listen for scroll events directly on the container.
*/
} else {
container.node.addEventListener('scroll', delegate.bind(this))
container.node.addEventListener('resize', delegate.bind(this))
}
})
/**
* Manually invoke delegate once to capture
* element and container dimensions, container
* scroll position, and trigger any valid reveals
*/
delegate.call(this)
/**
* And with that, initialization is complete so
* let's update our initialization timeout and state.
*/
this.initTimeout = null
this.initialized = true
}
|
src/instance/functions/initialize.js
|
import delegate from './delegate'
import { each } from '../../utils/generic'
export default function initialize () {
/**
* Let's take stock of which containers and sequences
* our current store of elements is actively using,
* and add each elements initial styles.
*/
const activeContainerIds = []
const activeSequenceIds = []
each(this.store.elements, element => {
if (activeContainerIds.indexOf(element.containerId) === -1) {
activeContainerIds.push(element.containerId)
}
if (activeSequenceIds.indexOf(element.sequence.id) === -1) {
activeSequenceIds.push(element.sequence.id)
}
// check the element status before choosing which
// styles to initialize with; e.g. after a sync() call,
// elements will be visible and will need their
// final styles applied alongwith transition.
let styles
styles = [
element.styles.inline.generated,
element.styles.opacity.generated,
element.styles.transform.generated.initial,
].join(' ')
element.node.setAttribute('style', styles)
})
/**
* Remove unused sequences.
*/
each(this.store.sequences, sequence => {
if (activeSequenceIds.indexOf(sequence.id) === -1) {
delete this.store.sequences[sequence.id]
}
})
each(this.store.containers, container => {
/**
* Remove unused containers.
*/
if (activeContainerIds.indexOf(container.id) === -1) {
container.node.removeEventListener('scroll', delegate)
container.node.removeEventListener('resize', delegate)
delete this.store.containers[container.id]
/**
* The default container is the <html> element, and in
* this case we listen for scroll events on the window.
*/
} else if (container.node === document.documentElement) {
window.addEventListener('scroll', delegate.bind(this))
window.addEventListener('resize', delegate.bind(this))
/**
* Otherwise listen for scroll events directly on the container.
*/
} else {
container.node.addEventListener('scroll', delegate.bind(this))
container.node.addEventListener('resize', delegate.bind(this))
}
})
/**
* Manually invoke delegate once to capture
* element and container dimensions, container
* scroll position, and trigger any valid reveals
*/
delegate.call(this)
/**
* And with that, initialization is complete so
* let's update our initialization timeout and state.
*/
this.initTimeout = null
this.initialized = true
}
|
check if final styles should be applied in initialization
|
src/instance/functions/initialize.js
|
check if final styles should be applied in initialization
|
<ide><path>rc/instance/functions/initialize.js
<ide> activeSequenceIds.push(element.sequence.id)
<ide> }
<ide>
<del> // check the element status before choosing which
<del> // styles to initialize with; e.g. after a sync() call,
<del> // elements will be visible and will need their
<del> // final styles applied alongwith transition.
<add> /**
<add> * Since we may be initializing elements that have
<add> * already been revealed, e.g. invoking sync(),
<add> * discern whether to use initial or final styles.
<add> */
<ide> let styles
<ide>
<del> styles = [
<del> element.styles.inline.generated,
<del> element.styles.opacity.generated,
<del> element.styles.transform.generated.initial,
<del> ].join(' ')
<add> if (element.visible) {
<add> styles = [
<add> element.styles.inline.generated,
<add> element.styles.opacity.computed,
<add> element.styles.transform.generated.final,
<add> ].join(' ')
<add> } else {
<add> styles = [
<add> element.styles.inline.generated,
<add> element.styles.opacity.generated,
<add> element.styles.transform.generated.initial,
<add> ].join(' ')
<add> }
<ide>
<ide> element.node.setAttribute('style', styles)
<ide> })
|
|
Java
|
bsd-3-clause
|
7e559465bdbfb8d21399cb43c32b3b553320d503
| 0 |
hoangpham95/react-native,facebook/react-native,arthuralee/react-native,janicduplessis/react-native,javache/react-native,pandiaraj44/react-native,janicduplessis/react-native,janicduplessis/react-native,hoangpham95/react-native,janicduplessis/react-native,hoangpham95/react-native,pandiaraj44/react-native,facebook/react-native,myntra/react-native,pandiaraj44/react-native,javache/react-native,facebook/react-native,myntra/react-native,facebook/react-native,facebook/react-native,myntra/react-native,myntra/react-native,pandiaraj44/react-native,javache/react-native,myntra/react-native,hoangpham95/react-native,arthuralee/react-native,myntra/react-native,myntra/react-native,myntra/react-native,hoangpham95/react-native,myntra/react-native,arthuralee/react-native,pandiaraj44/react-native,javache/react-native,janicduplessis/react-native,pandiaraj44/react-native,facebook/react-native,javache/react-native,janicduplessis/react-native,javache/react-native,arthuralee/react-native,facebook/react-native,javache/react-native,janicduplessis/react-native,arthuralee/react-native,javache/react-native,hoangpham95/react-native,pandiaraj44/react-native,hoangpham95/react-native,facebook/react-native,hoangpham95/react-native,javache/react-native,janicduplessis/react-native,pandiaraj44/react-native,facebook/react-native
|
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.facebook.react.fabric.mounting;
import static com.facebook.infer.annotation.ThreadConfined.ANY;
import static com.facebook.infer.annotation.ThreadConfined.UI;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import androidx.annotation.AnyThread;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.UiThread;
import com.facebook.common.logging.FLog;
import com.facebook.infer.annotation.Assertions;
import com.facebook.infer.annotation.ThreadConfined;
import com.facebook.react.bridge.ReactSoftException;
import com.facebook.react.bridge.ReadableArray;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.bridge.ReadableNativeMap;
import com.facebook.react.bridge.RetryableMountingLayerException;
import com.facebook.react.bridge.SoftAssertions;
import com.facebook.react.bridge.UiThreadUtil;
import com.facebook.react.fabric.FabricUIManager;
import com.facebook.react.fabric.events.EventEmitterWrapper;
import com.facebook.react.fabric.mounting.mountitems.MountItem;
import com.facebook.react.touch.JSResponderHandler;
import com.facebook.react.uimanager.IllegalViewOperationException;
import com.facebook.react.uimanager.ReactStylesDiffMap;
import com.facebook.react.uimanager.RootView;
import com.facebook.react.uimanager.RootViewManager;
import com.facebook.react.uimanager.StateWrapper;
import com.facebook.react.uimanager.ThemedReactContext;
import com.facebook.react.uimanager.ViewGroupManager;
import com.facebook.react.uimanager.ViewManager;
import com.facebook.react.uimanager.ViewManagerRegistry;
import com.facebook.yoga.YogaMeasureMode;
import java.util.concurrent.ConcurrentHashMap;
/**
* Class responsible for actually dispatching view updates enqueued via {@link
* FabricUIManager#scheduleMountItems(int, MountItem[])} on the UI thread.
*/
public class MountingManager {
public static final String TAG = MountingManager.class.getSimpleName();
@NonNull private final ConcurrentHashMap<Integer, ViewState> mTagToViewState;
@NonNull private final JSResponderHandler mJSResponderHandler = new JSResponderHandler();
@NonNull private final ViewManagerRegistry mViewManagerRegistry;
@NonNull private final RootViewManager mRootViewManager = new RootViewManager();
public MountingManager(@NonNull ViewManagerRegistry viewManagerRegistry) {
mTagToViewState = new ConcurrentHashMap<>();
mViewManagerRegistry = viewManagerRegistry;
}
/**
* This mutates the rootView, which is an Android View, so this should only be called on the UI
* thread.
*
* @param reactRootTag
* @param rootView
*/
@ThreadConfined(UI)
public void addRootView(int reactRootTag, @NonNull View rootView) {
if (rootView.getId() != View.NO_ID) {
throw new IllegalViewOperationException(
"Trying to add a root view with an explicit id already set. React Native uses "
+ "the id field to track react tags and will overwrite this field. If that is fine, "
+ "explicitly overwrite the id field to View.NO_ID before calling addRootView.");
}
mTagToViewState.put(
reactRootTag, new ViewState(reactRootTag, rootView, mRootViewManager, true));
rootView.setId(reactRootTag);
}
/** Releases all references to given native View. */
@UiThread
private void dropView(@NonNull View view) {
UiThreadUtil.assertOnUiThread();
int reactTag = view.getId();
ViewState state = getViewState(reactTag);
ViewManager viewManager = state.mViewManager;
if (!state.mIsRoot && viewManager != null) {
// For non-root views we notify viewmanager with {@link ViewManager#onDropInstance}
viewManager.onDropViewInstance(view);
}
if (view instanceof ViewGroup && viewManager instanceof ViewGroupManager) {
ViewGroup viewGroup = (ViewGroup) view;
ViewGroupManager<ViewGroup> viewGroupManager = getViewGroupManager(state);
for (int i = viewGroupManager.getChildCount(viewGroup) - 1; i >= 0; i--) {
View child = viewGroupManager.getChildAt(viewGroup, i);
if (getNullableViewState(child.getId()) != null) {
dropView(child);
}
viewGroupManager.removeViewAt(viewGroup, i);
}
}
mTagToViewState.remove(reactTag);
}
@UiThread
public void addViewAt(int parentTag, int tag, int index) {
UiThreadUtil.assertOnUiThread();
ViewState parentViewState = getViewState(parentTag);
if (!(parentViewState.mView instanceof ViewGroup)) {
String message =
"Unable to add a view into a view that is not a ViewGroup. ParentTag: "
+ parentTag
+ " - Tag: "
+ tag
+ " - Index: "
+ index;
FLog.e(TAG, message);
throw new IllegalStateException(message);
}
final ViewGroup parentView = (ViewGroup) parentViewState.mView;
ViewState viewState = getViewState(tag);
final View view = viewState.mView;
if (view == null) {
throw new IllegalStateException(
"Unable to find view for viewState " + viewState + " and tag " + tag);
}
getViewGroupManager(parentViewState).addView(parentView, view, index);
}
private @NonNull ViewState getViewState(int tag) {
ViewState viewState = mTagToViewState.get(tag);
if (viewState == null) {
throw new RetryableMountingLayerException("Unable to find viewState view for tag " + tag);
}
return viewState;
}
private @Nullable ViewState getNullableViewState(int tag) {
return mTagToViewState.get(tag);
}
@Deprecated
public void receiveCommand(int reactTag, int commandId, @Nullable ReadableArray commandArgs) {
ViewState viewState = getNullableViewState(reactTag);
// It's not uncommon for JS to send events as/after a component is being removed from the
// view hierarchy. For example, TextInput may send a "blur" command in response to the view
// disappearing. Throw `ReactNoCrashSoftException` so they're logged but don't crash in dev
// for now.
if (viewState == null) {
throw new RetryableMountingLayerException(
"Unable to find viewState for tag: " + reactTag + " for commandId: " + commandId);
}
if (viewState.mViewManager == null) {
throw new RetryableMountingLayerException("Unable to find viewManager for tag " + reactTag);
}
if (viewState.mView == null) {
throw new RetryableMountingLayerException(
"Unable to find viewState view for tag " + reactTag);
}
viewState.mViewManager.receiveCommand(viewState.mView, commandId, commandArgs);
}
public void receiveCommand(
int reactTag, @NonNull String commandId, @Nullable ReadableArray commandArgs) {
ViewState viewState = getNullableViewState(reactTag);
// It's not uncommon for JS to send events as/after a component is being removed from the
// view hierarchy. For example, TextInput may send a "blur" command in response to the view
// disappearing. Throw `ReactNoCrashSoftException` so they're logged but don't crash in dev
// for now.
if (viewState == null) {
throw new RetryableMountingLayerException(
"Unable to find viewState for tag: " + reactTag + " for commandId: " + commandId);
}
if (viewState.mViewManager == null) {
throw new RetryableMountingLayerException(
"Unable to find viewState manager for tag " + reactTag);
}
if (viewState.mView == null) {
throw new RetryableMountingLayerException(
"Unable to find viewState view for tag " + reactTag);
}
viewState.mViewManager.receiveCommand(viewState.mView, commandId, commandArgs);
}
public void sendAccessibilityEvent(int reactTag, int eventType) {
ViewState viewState = getViewState(reactTag);
if (viewState.mViewManager == null) {
throw new RetryableMountingLayerException(
"Unable to find viewState manager for tag " + reactTag);
}
if (viewState.mView == null) {
throw new RetryableMountingLayerException(
"Unable to find viewState view for tag " + reactTag);
}
viewState.mView.sendAccessibilityEvent(eventType);
}
@SuppressWarnings("unchecked") // prevents unchecked conversion warn of the <ViewGroup> type
private static @NonNull ViewGroupManager<ViewGroup> getViewGroupManager(
@NonNull ViewState viewState) {
if (viewState.mViewManager == null) {
throw new IllegalStateException("Unable to find ViewManager for view: " + viewState);
}
return (ViewGroupManager<ViewGroup>) viewState.mViewManager;
}
@UiThread
public void removeViewAt(int parentTag, int index) {
UiThreadUtil.assertOnUiThread();
ViewState viewState = getNullableViewState(parentTag);
if (viewState == null) {
ReactSoftException.logSoftException(
MountingManager.TAG,
new IllegalStateException(
"Unable to find viewState for tag: " + parentTag + " for removeViewAt"));
return;
}
final ViewGroup parentView = (ViewGroup) viewState.mView;
if (parentView == null) {
throw new IllegalStateException("Unable to find view for tag " + parentTag);
}
ViewGroupManager<ViewGroup> viewGroupManager = getViewGroupManager(viewState);
if (viewGroupManager.getChildCount(parentView) <= index) {
throw new IllegalStateException(
"Cannot remove child at index "
+ index
+ " from parent ViewGroup ["
+ parentView.getId()
+ "], only "
+ parentView.getChildCount()
+ " children in parent");
}
viewGroupManager.removeViewAt(parentView, index);
}
@UiThread
public void createView(
@NonNull ThemedReactContext themedReactContext,
@NonNull String componentName,
int reactTag,
@Nullable ReadableMap props,
@Nullable StateWrapper stateWrapper,
boolean isLayoutable) {
if (getNullableViewState(reactTag) != null) {
return;
}
View view = null;
ViewManager viewManager = null;
ReactStylesDiffMap propsDiffMap = null;
if (props != null) {
propsDiffMap = new ReactStylesDiffMap(props);
}
if (isLayoutable) {
viewManager = mViewManagerRegistry.get(componentName);
// View Managers are responsible for dealing with initial state and props.
view =
viewManager.createView(
themedReactContext, propsDiffMap, stateWrapper, mJSResponderHandler);
view.setId(reactTag);
}
ViewState viewState = new ViewState(reactTag, view, viewManager);
viewState.mCurrentProps = propsDiffMap;
viewState.mCurrentState = (stateWrapper != null ? stateWrapper.getState() : null);
mTagToViewState.put(reactTag, viewState);
}
@UiThread
public void updateProps(int reactTag, @Nullable ReadableMap props) {
if (props == null) {
return;
}
UiThreadUtil.assertOnUiThread();
ViewState viewState = getViewState(reactTag);
viewState.mCurrentProps = new ReactStylesDiffMap(props);
View view = viewState.mView;
if (view == null) {
throw new IllegalStateException("Unable to find view for tag " + reactTag);
}
Assertions.assertNotNull(viewState.mViewManager)
.updateProperties(view, viewState.mCurrentProps);
}
@UiThread
public void updateLayout(int reactTag, int x, int y, int width, int height) {
UiThreadUtil.assertOnUiThread();
ViewState viewState = getViewState(reactTag);
// Do not layout Root Views
if (viewState.mIsRoot) {
return;
}
View viewToUpdate = viewState.mView;
if (viewToUpdate == null) {
throw new IllegalStateException("Unable to find View for tag: " + reactTag);
}
viewToUpdate.measure(
View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.EXACTLY),
View.MeasureSpec.makeMeasureSpec(height, View.MeasureSpec.EXACTLY));
ViewParent parent = viewToUpdate.getParent();
if (parent instanceof RootView) {
parent.requestLayout();
}
// TODO: T31905686 Check if the parent of the view has to layout the view, or the child has
// to lay itself out. see NativeViewHierarchyManager.updateLayout
viewToUpdate.layout(x, y, x + width, y + height);
}
@UiThread
public void updatePadding(int reactTag, int left, int top, int right, int bottom) {
UiThreadUtil.assertOnUiThread();
ViewState viewState = getViewState(reactTag);
// Do not layout Root Views
if (viewState.mIsRoot) {
return;
}
View viewToUpdate = viewState.mView;
if (viewToUpdate == null) {
throw new IllegalStateException("Unable to find View for tag: " + reactTag);
}
ViewManager viewManager = viewState.mViewManager;
if (viewManager == null) {
throw new IllegalStateException("Unable to find ViewManager for view: " + viewState);
}
//noinspection unchecked
viewManager.setPadding(viewToUpdate, left, top, right, bottom);
}
@UiThread
public void deleteView(int reactTag) {
UiThreadUtil.assertOnUiThread();
ViewState viewState = getNullableViewState(reactTag);
if (viewState == null) {
ReactSoftException.logSoftException(
MountingManager.TAG,
new IllegalStateException(
"Unable to find viewState for tag: " + reactTag + " for deleteView"));
return;
}
View view = viewState.mView;
if (view != null) {
dropView(view);
} else {
mTagToViewState.remove(reactTag);
}
}
@UiThread
public void updateState(final int reactTag, @Nullable StateWrapper stateWrapper) {
UiThreadUtil.assertOnUiThread();
ViewState viewState = getViewState(reactTag);
@Nullable ReadableNativeMap newState = stateWrapper == null ? null : stateWrapper.getState();
if ((viewState.mCurrentState != null && viewState.mCurrentState.equals(newState))
|| (viewState.mCurrentState == null && stateWrapper == null)) {
return;
}
viewState.mCurrentState = newState;
ViewManager viewManager = viewState.mViewManager;
if (viewManager == null) {
throw new IllegalStateException("Unable to find ViewManager for tag: " + reactTag);
}
Object extraData =
viewManager.updateState(viewState.mView, viewState.mCurrentProps, stateWrapper);
if (extraData != null) {
viewManager.updateExtraData(viewState.mView, extraData);
}
}
@UiThread
public void preallocateView(
@NonNull ThemedReactContext reactContext,
String componentName,
int reactTag,
@Nullable ReadableMap props,
@Nullable StateWrapper stateWrapper,
boolean isLayoutable) {
if (getNullableViewState(reactTag) != null) {
throw new IllegalStateException(
"View for component " + componentName + " with tag " + reactTag + " already exists.");
}
createView(reactContext, componentName, reactTag, props, stateWrapper, isLayoutable);
}
@UiThread
public void updateEventEmitter(int reactTag, @NonNull EventEmitterWrapper eventEmitter) {
UiThreadUtil.assertOnUiThread();
ViewState viewState = mTagToViewState.get(reactTag);
if (viewState == null) {
// TODO T62717437 - Use a flag to determine that these event emitters belong to virtual nodes
// only.
viewState = new ViewState(reactTag, null, null);
mTagToViewState.put(reactTag, viewState);
}
viewState.mEventEmitter = eventEmitter;
}
/**
* Set the JS responder for the view associated with the tags received as a parameter.
*
* <p>The JSResponder coordinates the return values of the onInterceptTouch method in Android
* Views. This allows JS to coordinate when a touch should be handled by JS or by the Android
* native views. See {@link JSResponderHandler} for more details.
*
* <p>This method is going to be executed on the UIThread as soon as it is delivered from JS to
* RN.
*
* <p>Currently, there is no warranty that the view associated with the react tag exists, because
* this method is not handled by the react commit process.
*
* @param reactTag React tag of the first parent of the view that is NOT virtual
* @param initialReactTag React tag of the JS view that initiated the touch operation
* @param blockNativeResponder If native responder should be blocked or not
*/
@UiThread
public synchronized void setJSResponder(
int reactTag, int initialReactTag, boolean blockNativeResponder) {
if (!blockNativeResponder) {
mJSResponderHandler.setJSResponder(initialReactTag, null);
return;
}
ViewState viewState = getViewState(reactTag);
View view = viewState.mView;
if (initialReactTag != reactTag && view instanceof ViewParent) {
// In this case, initialReactTag corresponds to a virtual/layout-only View, and we already
// have a parent of that View in reactTag, so we can use it.
mJSResponderHandler.setJSResponder(initialReactTag, (ViewParent) view);
return;
} else if (view == null) {
SoftAssertions.assertUnreachable("Cannot find view for tag " + reactTag + ".");
return;
}
if (viewState.mIsRoot) {
SoftAssertions.assertUnreachable(
"Cannot block native responder on " + reactTag + " that is a root view");
}
mJSResponderHandler.setJSResponder(initialReactTag, view.getParent());
}
/**
* Clears the JS Responder specified by {@link #setJSResponder(int, int, boolean)}. After this
* method is called, all the touch events are going to be handled by JS.
*/
@UiThread
public void clearJSResponder() {
mJSResponderHandler.clearJSResponder();
}
@AnyThread
public long measure(
@NonNull Context context,
@NonNull String componentName,
@NonNull ReadableMap localData,
@NonNull ReadableMap props,
@NonNull ReadableMap state,
float width,
@NonNull YogaMeasureMode widthMode,
float height,
@NonNull YogaMeasureMode heightMode,
@Nullable float[] attachmentsPositions) {
return mViewManagerRegistry
.get(componentName)
.measure(
context,
localData,
props,
state,
width,
widthMode,
height,
heightMode,
attachmentsPositions);
}
@AnyThread
@ThreadConfined(ANY)
public @Nullable EventEmitterWrapper getEventEmitter(int reactTag) {
ViewState viewState = getNullableViewState(reactTag);
return viewState == null ? null : viewState.mEventEmitter;
}
/**
* This class holds view state for react tags. Objects of this class are stored into the {@link
* #mTagToViewState}, and they should be updated in the same thread.
*/
private static class ViewState {
@Nullable final View mView;
final int mReactTag;
final boolean mIsRoot;
@Nullable final ViewManager mViewManager;
@Nullable public ReactStylesDiffMap mCurrentProps = null;
@Nullable public ReadableMap mCurrentLocalData = null;
@Nullable public ReadableMap mCurrentState = null;
@Nullable public EventEmitterWrapper mEventEmitter = null;
private ViewState(int reactTag, @Nullable View view, @Nullable ViewManager viewManager) {
this(reactTag, view, viewManager, false);
}
private ViewState(int reactTag, @Nullable View view, ViewManager viewManager, boolean isRoot) {
mReactTag = reactTag;
mView = view;
mIsRoot = isRoot;
mViewManager = viewManager;
}
@Override
public String toString() {
boolean isLayoutOnly = mViewManager == null;
return "ViewState ["
+ mReactTag
+ "] - isRoot: "
+ mIsRoot
+ " - props: "
+ mCurrentProps
+ " - localData: "
+ mCurrentLocalData
+ " - viewManager: "
+ mViewManager
+ " - isLayoutOnly: "
+ isLayoutOnly;
}
}
}
|
ReactAndroid/src/main/java/com/facebook/react/fabric/mounting/MountingManager.java
|
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.facebook.react.fabric.mounting;
import static com.facebook.infer.annotation.ThreadConfined.ANY;
import static com.facebook.infer.annotation.ThreadConfined.UI;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import androidx.annotation.AnyThread;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.UiThread;
import com.facebook.common.logging.FLog;
import com.facebook.infer.annotation.Assertions;
import com.facebook.infer.annotation.ThreadConfined;
import com.facebook.react.bridge.ReactSoftException;
import com.facebook.react.bridge.ReadableArray;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.bridge.ReadableNativeMap;
import com.facebook.react.bridge.RetryableMountingLayerException;
import com.facebook.react.bridge.SoftAssertions;
import com.facebook.react.bridge.UiThreadUtil;
import com.facebook.react.fabric.FabricUIManager;
import com.facebook.react.fabric.events.EventEmitterWrapper;
import com.facebook.react.fabric.mounting.mountitems.MountItem;
import com.facebook.react.touch.JSResponderHandler;
import com.facebook.react.uimanager.IllegalViewOperationException;
import com.facebook.react.uimanager.ReactStylesDiffMap;
import com.facebook.react.uimanager.RootView;
import com.facebook.react.uimanager.RootViewManager;
import com.facebook.react.uimanager.StateWrapper;
import com.facebook.react.uimanager.ThemedReactContext;
import com.facebook.react.uimanager.ViewGroupManager;
import com.facebook.react.uimanager.ViewManager;
import com.facebook.react.uimanager.ViewManagerRegistry;
import com.facebook.yoga.YogaMeasureMode;
import java.util.concurrent.ConcurrentHashMap;
/**
* Class responsible for actually dispatching view updates enqueued via {@link
* FabricUIManager#scheduleMountItems(int, MountItem[])} on the UI thread.
*/
public class MountingManager {
public static final String TAG = MountingManager.class.getSimpleName();
@NonNull private final ConcurrentHashMap<Integer, ViewState> mTagToViewState;
@NonNull private final JSResponderHandler mJSResponderHandler = new JSResponderHandler();
@NonNull private final ViewManagerRegistry mViewManagerRegistry;
@NonNull private final RootViewManager mRootViewManager = new RootViewManager();
public MountingManager(@NonNull ViewManagerRegistry viewManagerRegistry) {
mTagToViewState = new ConcurrentHashMap<>();
mViewManagerRegistry = viewManagerRegistry;
}
/**
* This mutates the rootView, which is an Android View, so this should only be called on the UI
* thread.
*
* @param reactRootTag
* @param rootView
*/
@ThreadConfined(UI)
public void addRootView(int reactRootTag, @NonNull View rootView) {
if (rootView.getId() != View.NO_ID) {
throw new IllegalViewOperationException(
"Trying to add a root view with an explicit id already set. React Native uses "
+ "the id field to track react tags and will overwrite this field. If that is fine, "
+ "explicitly overwrite the id field to View.NO_ID before calling addRootView.");
}
mTagToViewState.put(
reactRootTag, new ViewState(reactRootTag, rootView, mRootViewManager, true));
rootView.setId(reactRootTag);
}
/** Releases all references to given native View. */
@UiThread
private void dropView(@NonNull View view) {
UiThreadUtil.assertOnUiThread();
int reactTag = view.getId();
ViewState state = getViewState(reactTag);
ViewManager viewManager = state.mViewManager;
if (!state.mIsRoot && viewManager != null) {
// For non-root views we notify viewmanager with {@link ViewManager#onDropInstance}
viewManager.onDropViewInstance(view);
}
if (view instanceof ViewGroup && viewManager instanceof ViewGroupManager) {
ViewGroup viewGroup = (ViewGroup) view;
ViewGroupManager<ViewGroup> viewGroupManager = getViewGroupManager(state);
for (int i = viewGroupManager.getChildCount(viewGroup) - 1; i >= 0; i--) {
View child = viewGroupManager.getChildAt(viewGroup, i);
if (getNullableViewState(child.getId()) != null) {
dropView(child);
}
viewGroupManager.removeViewAt(viewGroup, i);
}
}
mTagToViewState.remove(reactTag);
}
@UiThread
public void addViewAt(int parentTag, int tag, int index) {
UiThreadUtil.assertOnUiThread();
ViewState parentViewState = getViewState(parentTag);
if (!(parentViewState.mView instanceof ViewGroup)) {
String message =
"Unable to add a view into a view that is not a ViewGroup. ParentTag: "
+ parentTag
+ " - Tag: "
+ tag
+ " - Index: "
+ index;
FLog.e(TAG, message);
throw new IllegalStateException(message);
}
final ViewGroup parentView = (ViewGroup) parentViewState.mView;
ViewState viewState = getViewState(tag);
final View view = viewState.mView;
if (view == null) {
throw new IllegalStateException(
"Unable to find view for viewState " + viewState + " and tag " + tag);
}
getViewGroupManager(parentViewState).addView(parentView, view, index);
}
private @NonNull ViewState getViewState(int tag) {
ViewState viewState = mTagToViewState.get(tag);
if (viewState == null) {
throw new RetryableMountingLayerException("Unable to find viewState view for tag " + tag);
}
return viewState;
}
private @Nullable ViewState getNullableViewState(int tag) {
return mTagToViewState.get(tag);
}
@Deprecated
public void receiveCommand(int reactTag, int commandId, @Nullable ReadableArray commandArgs) {
ViewState viewState = getNullableViewState(reactTag);
// It's not uncommon for JS to send events as/after a component is being removed from the
// view hierarchy. For example, TextInput may send a "blur" command in response to the view
// disappearing. Throw `ReactNoCrashSoftException` so they're logged but don't crash in dev
// for now.
if (viewState == null) {
throw new RetryableMountingLayerException(
"Unable to find viewState for tag: " + reactTag + " for commandId: " + commandId);
}
if (viewState.mViewManager == null) {
throw new RetryableMountingLayerException("Unable to find viewManager for tag " + reactTag);
}
if (viewState.mView == null) {
throw new RetryableMountingLayerException(
"Unable to find viewState view for tag " + reactTag);
}
viewState.mViewManager.receiveCommand(viewState.mView, commandId, commandArgs);
}
public void receiveCommand(
int reactTag, @NonNull String commandId, @Nullable ReadableArray commandArgs) {
ViewState viewState = getNullableViewState(reactTag);
// It's not uncommon for JS to send events as/after a component is being removed from the
// view hierarchy. For example, TextInput may send a "blur" command in response to the view
// disappearing. Throw `ReactNoCrashSoftException` so they're logged but don't crash in dev
// for now.
if (viewState == null) {
throw new RetryableMountingLayerException(
"Unable to find viewState for tag: " + reactTag + " for commandId: " + commandId);
}
if (viewState.mViewManager == null) {
throw new RetryableMountingLayerException(
"Unable to find viewState manager for tag " + reactTag);
}
if (viewState.mView == null) {
throw new RetryableMountingLayerException(
"Unable to find viewState view for tag " + reactTag);
}
viewState.mViewManager.receiveCommand(viewState.mView, commandId, commandArgs);
}
public void sendAccessibilityEvent(int reactTag, int eventType) {
ViewState viewState = getViewState(reactTag);
if (viewState.mViewManager == null) {
throw new RetryableMountingLayerException(
"Unable to find viewState manager for tag " + reactTag);
}
if (viewState.mView == null) {
throw new RetryableMountingLayerException(
"Unable to find viewState view for tag " + reactTag);
}
viewState.mView.sendAccessibilityEvent(eventType);
}
@SuppressWarnings("unchecked") // prevents unchecked conversion warn of the <ViewGroup> type
private static @NonNull ViewGroupManager<ViewGroup> getViewGroupManager(
@NonNull ViewState viewState) {
if (viewState.mViewManager == null) {
throw new IllegalStateException("Unable to find ViewManager for view: " + viewState);
}
return (ViewGroupManager<ViewGroup>) viewState.mViewManager;
}
@UiThread
public void removeViewAt(int parentTag, int index) {
UiThreadUtil.assertOnUiThread();
ViewState viewState = getNullableViewState(parentTag);
if (viewState == null) {
ReactSoftException.logSoftException(
MountingManager.TAG,
new IllegalStateException(
"Unable to find viewState for tag: " + parentTag + " for removeViewAt"));
return;
}
final ViewGroup parentView = (ViewGroup) viewState.mView;
if (parentView == null) {
throw new IllegalStateException("Unable to find view for tag " + parentTag);
}
if (parentView.getChildCount() <= index) {
throw new IllegalStateException(
"Cannot remove child at index "
+ index
+ " from parent ViewGroup ["
+ parentView.getId()
+ "], only "
+ parentView.getChildCount()
+ " children in parent");
}
getViewGroupManager(viewState).removeViewAt(parentView, index);
}
@UiThread
public void createView(
@NonNull ThemedReactContext themedReactContext,
@NonNull String componentName,
int reactTag,
@Nullable ReadableMap props,
@Nullable StateWrapper stateWrapper,
boolean isLayoutable) {
if (getNullableViewState(reactTag) != null) {
return;
}
View view = null;
ViewManager viewManager = null;
ReactStylesDiffMap propsDiffMap = null;
if (props != null) {
propsDiffMap = new ReactStylesDiffMap(props);
}
if (isLayoutable) {
viewManager = mViewManagerRegistry.get(componentName);
// View Managers are responsible for dealing with initial state and props.
view =
viewManager.createView(
themedReactContext, propsDiffMap, stateWrapper, mJSResponderHandler);
view.setId(reactTag);
}
ViewState viewState = new ViewState(reactTag, view, viewManager);
viewState.mCurrentProps = propsDiffMap;
viewState.mCurrentState = (stateWrapper != null ? stateWrapper.getState() : null);
mTagToViewState.put(reactTag, viewState);
}
@UiThread
public void updateProps(int reactTag, @Nullable ReadableMap props) {
if (props == null) {
return;
}
UiThreadUtil.assertOnUiThread();
ViewState viewState = getViewState(reactTag);
viewState.mCurrentProps = new ReactStylesDiffMap(props);
View view = viewState.mView;
if (view == null) {
throw new IllegalStateException("Unable to find view for tag " + reactTag);
}
Assertions.assertNotNull(viewState.mViewManager)
.updateProperties(view, viewState.mCurrentProps);
}
@UiThread
public void updateLayout(int reactTag, int x, int y, int width, int height) {
UiThreadUtil.assertOnUiThread();
ViewState viewState = getViewState(reactTag);
// Do not layout Root Views
if (viewState.mIsRoot) {
return;
}
View viewToUpdate = viewState.mView;
if (viewToUpdate == null) {
throw new IllegalStateException("Unable to find View for tag: " + reactTag);
}
viewToUpdate.measure(
View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.EXACTLY),
View.MeasureSpec.makeMeasureSpec(height, View.MeasureSpec.EXACTLY));
ViewParent parent = viewToUpdate.getParent();
if (parent instanceof RootView) {
parent.requestLayout();
}
// TODO: T31905686 Check if the parent of the view has to layout the view, or the child has
// to lay itself out. see NativeViewHierarchyManager.updateLayout
viewToUpdate.layout(x, y, x + width, y + height);
}
@UiThread
public void updatePadding(int reactTag, int left, int top, int right, int bottom) {
UiThreadUtil.assertOnUiThread();
ViewState viewState = getViewState(reactTag);
// Do not layout Root Views
if (viewState.mIsRoot) {
return;
}
View viewToUpdate = viewState.mView;
if (viewToUpdate == null) {
throw new IllegalStateException("Unable to find View for tag: " + reactTag);
}
ViewManager viewManager = viewState.mViewManager;
if (viewManager == null) {
throw new IllegalStateException("Unable to find ViewManager for view: " + viewState);
}
//noinspection unchecked
viewManager.setPadding(viewToUpdate, left, top, right, bottom);
}
@UiThread
public void deleteView(int reactTag) {
UiThreadUtil.assertOnUiThread();
ViewState viewState = getNullableViewState(reactTag);
if (viewState == null) {
ReactSoftException.logSoftException(
MountingManager.TAG,
new IllegalStateException(
"Unable to find viewState for tag: " + reactTag + " for deleteView"));
return;
}
View view = viewState.mView;
if (view != null) {
dropView(view);
} else {
mTagToViewState.remove(reactTag);
}
}
@UiThread
public void updateState(final int reactTag, @Nullable StateWrapper stateWrapper) {
UiThreadUtil.assertOnUiThread();
ViewState viewState = getViewState(reactTag);
@Nullable ReadableNativeMap newState = stateWrapper == null ? null : stateWrapper.getState();
if ((viewState.mCurrentState != null && viewState.mCurrentState.equals(newState))
|| (viewState.mCurrentState == null && stateWrapper == null)) {
return;
}
viewState.mCurrentState = newState;
ViewManager viewManager = viewState.mViewManager;
if (viewManager == null) {
throw new IllegalStateException("Unable to find ViewManager for tag: " + reactTag);
}
Object extraData =
viewManager.updateState(viewState.mView, viewState.mCurrentProps, stateWrapper);
if (extraData != null) {
viewManager.updateExtraData(viewState.mView, extraData);
}
}
@UiThread
public void preallocateView(
@NonNull ThemedReactContext reactContext,
String componentName,
int reactTag,
@Nullable ReadableMap props,
@Nullable StateWrapper stateWrapper,
boolean isLayoutable) {
if (getNullableViewState(reactTag) != null) {
throw new IllegalStateException(
"View for component " + componentName + " with tag " + reactTag + " already exists.");
}
createView(reactContext, componentName, reactTag, props, stateWrapper, isLayoutable);
}
@UiThread
public void updateEventEmitter(int reactTag, @NonNull EventEmitterWrapper eventEmitter) {
UiThreadUtil.assertOnUiThread();
ViewState viewState = mTagToViewState.get(reactTag);
if (viewState == null) {
// TODO T62717437 - Use a flag to determine that these event emitters belong to virtual nodes
// only.
viewState = new ViewState(reactTag, null, null);
mTagToViewState.put(reactTag, viewState);
}
viewState.mEventEmitter = eventEmitter;
}
/**
* Set the JS responder for the view associated with the tags received as a parameter.
*
* <p>The JSResponder coordinates the return values of the onInterceptTouch method in Android
* Views. This allows JS to coordinate when a touch should be handled by JS or by the Android
* native views. See {@link JSResponderHandler} for more details.
*
* <p>This method is going to be executed on the UIThread as soon as it is delivered from JS to
* RN.
*
* <p>Currently, there is no warranty that the view associated with the react tag exists, because
* this method is not handled by the react commit process.
*
* @param reactTag React tag of the first parent of the view that is NOT virtual
* @param initialReactTag React tag of the JS view that initiated the touch operation
* @param blockNativeResponder If native responder should be blocked or not
*/
@UiThread
public synchronized void setJSResponder(
int reactTag, int initialReactTag, boolean blockNativeResponder) {
if (!blockNativeResponder) {
mJSResponderHandler.setJSResponder(initialReactTag, null);
return;
}
ViewState viewState = getViewState(reactTag);
View view = viewState.mView;
if (initialReactTag != reactTag && view instanceof ViewParent) {
// In this case, initialReactTag corresponds to a virtual/layout-only View, and we already
// have a parent of that View in reactTag, so we can use it.
mJSResponderHandler.setJSResponder(initialReactTag, (ViewParent) view);
return;
} else if (view == null) {
SoftAssertions.assertUnreachable("Cannot find view for tag " + reactTag + ".");
return;
}
if (viewState.mIsRoot) {
SoftAssertions.assertUnreachable(
"Cannot block native responder on " + reactTag + " that is a root view");
}
mJSResponderHandler.setJSResponder(initialReactTag, view.getParent());
}
/**
* Clears the JS Responder specified by {@link #setJSResponder(int, int, boolean)}. After this
* method is called, all the touch events are going to be handled by JS.
*/
@UiThread
public void clearJSResponder() {
mJSResponderHandler.clearJSResponder();
}
@AnyThread
public long measure(
@NonNull Context context,
@NonNull String componentName,
@NonNull ReadableMap localData,
@NonNull ReadableMap props,
@NonNull ReadableMap state,
float width,
@NonNull YogaMeasureMode widthMode,
float height,
@NonNull YogaMeasureMode heightMode,
@Nullable float[] attachmentsPositions) {
return mViewManagerRegistry
.get(componentName)
.measure(
context,
localData,
props,
state,
width,
widthMode,
height,
heightMode,
attachmentsPositions);
}
@AnyThread
@ThreadConfined(ANY)
public @Nullable EventEmitterWrapper getEventEmitter(int reactTag) {
ViewState viewState = getNullableViewState(reactTag);
return viewState == null ? null : viewState.mEventEmitter;
}
/**
* This class holds view state for react tags. Objects of this class are stored into the {@link
* #mTagToViewState}, and they should be updated in the same thread.
*/
private static class ViewState {
@Nullable final View mView;
final int mReactTag;
final boolean mIsRoot;
@Nullable final ViewManager mViewManager;
@Nullable public ReactStylesDiffMap mCurrentProps = null;
@Nullable public ReadableMap mCurrentLocalData = null;
@Nullable public ReadableMap mCurrentState = null;
@Nullable public EventEmitterWrapper mEventEmitter = null;
private ViewState(int reactTag, @Nullable View view, @Nullable ViewManager viewManager) {
this(reactTag, view, viewManager, false);
}
private ViewState(int reactTag, @Nullable View view, ViewManager viewManager, boolean isRoot) {
mReactTag = reactTag;
mView = view;
mIsRoot = isRoot;
mViewManager = viewManager;
}
@Override
public String toString() {
boolean isLayoutOnly = mViewManager == null;
return "ViewState ["
+ mReactTag
+ "] - isRoot: "
+ mIsRoot
+ " - props: "
+ mCurrentProps
+ " - localData: "
+ mCurrentLocalData
+ " - viewManager: "
+ mViewManager
+ " - isLayoutOnly: "
+ isLayoutOnly;
}
}
}
|
Fix crash introduced by D21735940 in T67525923
Summary:
We cannot call `parentView.getChildCount()` directly, we must get the child count through the ViewManager:
A simple `Log.e` call shows:
```
MountingManager: parentView.getChildCount(): 0 // viewGroupManager.getChildCount(parentView): 7
```
This difference does not occur for ALL views, but it occurs for... enough that this will crash on basically ~every screen, at least on navigation when all views are removed.
Theory about why this is happening: some ViewGroup types compute childCount differently, especially if we do some sort of custom child management for some view type? By coercing to `T` which the ViewManager does, we call getChildCount on the correct class type. This is just a hypothesis, though. But the failing views are all `View`s and it does look like `ReactClippingViewManager` has custom `getChildCount` logic, so that's likely the answer.
There's no such thing as an easy diff!
Changelog: [Internal]
Reviewed By: mdvacca
Differential Revision: D21750097
fbshipit-source-id: 3d87d8f629a0c12101658050e57e09242dfc2a8c
|
ReactAndroid/src/main/java/com/facebook/react/fabric/mounting/MountingManager.java
|
Fix crash introduced by D21735940 in T67525923
|
<ide><path>eactAndroid/src/main/java/com/facebook/react/fabric/mounting/MountingManager.java
<ide> throw new IllegalStateException("Unable to find view for tag " + parentTag);
<ide> }
<ide>
<del> if (parentView.getChildCount() <= index) {
<add> ViewGroupManager<ViewGroup> viewGroupManager = getViewGroupManager(viewState);
<add>
<add> if (viewGroupManager.getChildCount(parentView) <= index) {
<ide> throw new IllegalStateException(
<ide> "Cannot remove child at index "
<ide> + index
<ide> + " children in parent");
<ide> }
<ide>
<del> getViewGroupManager(viewState).removeViewAt(parentView, index);
<add> viewGroupManager.removeViewAt(parentView, index);
<ide> }
<ide>
<ide> @UiThread
|
|
JavaScript
|
mit
|
8a0bdc3df823769cbd2a5a351a611649845dcf7c
| 0 |
guptaanoop2005/sitespeed.io,jzoldak/sitespeed.io,andrebellafronte/sitespeed.io,beenanner/sitespeed.io,yesman82/sitespeed.io,pelmered/sitespeed.io,sitespeedio/sitespeed.io,guptaanoop2005/sitespeed.io,jzoldak/sitespeed.io,krishnakanthpps/sitespeed.io,sitespeedio/sitespeed.io,pelmered/sitespeed.io,kendrick-k/sitespeed.io,dieface/sitespeed.io,JeroenVdb/sitespeed.io,mattdcamp/sitespeed.io,yesman82/sitespeed.io,JeroenVdb/sitespeed.io,mattdcamp/sitespeed.io,dieface/sitespeed.io,andrebellafronte/sitespeed.io,jzoldak/sitespeed.io,beenanner/sitespeed.io,iessone/sitespeedio,andrebellafronte/sitespeed.io,laer/sitespeed.io,kendrick-k/sitespeed.io,dieface/sitespeed.io,krishnakanthpps/sitespeed.io,iessone/sitespeedio,JeroenVdb/sitespeed.io,laer/sitespeed.io,laer/sitespeed.io,sitespeedio/sitespeed.io,yesman82/sitespeed.io,sitespeedio/sitespeed.io,beenanner/sitespeed.io,pelmered/sitespeed.io,krishnakanthpps/sitespeed.io,kendrick-k/sitespeed.io
|
/**
* Sitespeed.io - How speedy is your site? (http://www.sitespeed.io)
* Copyright (c) 2014, Peter Hedenskog, Tobias Lidskog
* and other contributors
* Released under the Apache 2.0 License
*/
var crawler = require('./crawler'),
Analyzer = require('./analyze/analyzer'),
HTMLRenderer = require('./htmlRenderer'),
Collector = require('./collector'),
JUnitRenderer = require('./junitRenderer'),
Graphite = require('./graphite'),
logger = require('./log'),
path = require('path'),
dateFormat = require('dateformat'),
fs = require('fs-extra'),
config = require('./conf'),
async = require("async"),
urlParser = require('url'),
os = require('os'),
EOL = os.EOL,
binPath = require('phantomjs').path,
childProcess = require('child_process'),
log = require('winston');
module.exports = Runner;
function Runner() {
this.analyzer = new Analyzer();
this.collector = new Collector();
this.htmlRenderer = new HTMLRenderer();
this.junitRenderer = new JUnitRenderer(this.collector);
this.graphite = new Graphite(config.graphiteHost, config.graphitePort, config
.graphiteNamespace, this.collector);
}
Runner.prototype.run = function(finshedCb) {
finshedCb = finshedCb || function() {};
logVersions();
var self = this;
if (config.sites) {
this.sites = {};
var urls = fs.readFileSync(config.sites).toString().split(EOL);
var queue = async.queue(this._setupSite, 1);
log.log('info', 'Analyze ' + urls.length + ' sites');
urls.forEach(function (url) {
if (url!=="") queue.push({
'url': url,
'runner': self
}, function() {
log.log('info', "Finished with site " + url);
});
});
queue.drain = function() {
async.parallel({
copySiteAssets: function(cb) {
self.htmlRenderer.copyAssets(path.join(config.run.absResultDir,'..'), cb);
},
renderSites: function(cb) {
self.htmlRenderer.renderSites(self.sites, cb);
}
},
function(err, results) {
if (!err)
log.log('info', "Wrote sites result to " + config.run.absResultDir);
finshedCb();
});
};
}
else {
// setup the directories needed
var dataDir = path.join(config.run.absResultDir, config.dataDir);
fs.mkdirs(dataDir, function(err) {
if (err) {
log.log('error', "Couldn't create the data dir:" + dataDir + ' ' + err);
throw err;
} else {
// TODO needs t be stored for sites also
// store the config file, so we can backtrack errors and/or use it again
fs.writeFile(path.join(config.run.absResultDir, 'config.json'), JSON.stringify(
config), function(err) {
if (err) throw err;
});
self._fetchData(finshedCb);
}
});
}
};
Runner.prototype._setupSite = function(args, cb) {
var url = args.url;
config.url= url;
config.urlObject = urlParser.parse(config.url);
config.run.absResultDir = path.join(__dirname, '../',config.resultBaseDir, 'sites', dateFormat(config.run.date, "yyyy-mm-dd-HH-MM-ss"), config.urlObject.hostname );
// setup the directories needed
var dataDir = path.join(config.run.absResultDir, config.dataDir);
fs.mkdirs(dataDir, function (err) {
if (err) {
log.log('error', "Couldn't create the data dir:" + dataDir + ' ' + err);
throw err;
}
else args.runner._fetchData(cb);
});
};
Runner.prototype._fetchData = function(cb) {
var self = this;
/**
This is the main flow of the application and this is what we do:
1. Fetch the URL:s that will be analyzed, either we crawl a site using
a start url or we read the URL:s from a file.
2. Finetune the URL:s = do other thing that's needed, store them to disk etc.
3. Let the analyser take a go at the URL:s, the analyzer
got a lot to do, lets check the analyzer.js file
4. The analyze is finished, lets create output
**/
async.waterfall([
function(cb) {
self._fetchUrls(crawler, cb);
},
function(okUrls, errorUrls, cb) {
self._fineTuneUrls(okUrls, errorUrls, cb);
},
function(urls, downloadErrors, cb) {
self._analyze(urls, downloadErrors, cb);
},
function(downloadErrors, analysisErrors, cb) {
self._createOutput(downloadErrors, analysisErrors, cb);
}
], function(err, result) {
if (err)
log.log('error', err);
cb();
});
};
Runner.prototype._fineTuneUrls = function (okUrls, errorUrls, callback) {
var downloadErrors = {};
Object.keys(errorUrls).forEach(function(url) {
log.log('error', "Failed to download " + url);
downloadErrors[url] = errorUrls[url];
});
// limit
if (config.maxPagesToTest) {
if (okUrls.length > config.maxPagesToTest)
okUrls.length = config.maxPagesToTest;
}
if (okUrls.length === 0) {
log.log('info', "Didn't get any URLs");
throw Error('No URL:s to analyze');
}
saveUrls(okUrls);
callback(null, okUrls, downloadErrors);
};
Runner.prototype._fetchUrls = function (crawler, callback) {
if (config.url) {
log.log('info', "Will crawl from start point " + config.url +
" with crawl depth " + config.deep);
crawler.crawl(config.url, function(okUrls, errorUrls) {
callback(null, okUrls, errorUrls);
});
} else {
var urls = fs.readFileSync(config.file).toString().split(EOL);
urls = urls.filter(function(l) {
return l.length > 0;
});
callback(null, urls, {});
}
};
Runner.prototype._analyze = function (urls, downloadErrors, callback) {
var analysisErrors = {};
var self = this;
log.log('info', "Will analyze " + urls.length + " pages");
this.analyzer.analyze(urls, this.collector, downloadErrors, analysisErrors, function(err, url, pageData) {
if (err) {
log.log('error', 'Could not analyze ' + url + ' (' + JSON.stringify(err) +
')');
analysisErrors[url] = err;
return;
}
if (config.junit)
self.junitRenderer.renderForEachPage(url, pageData);
self.htmlRenderer.renderPage(url, pageData, function() {});
}, callback);
};
function saveUrls(urls) {
fs.writeFile(path.join(config.run.absResultDir, 'data', 'urls.txt'), urls.join(
EOL), function(err) {
if (err) {
throw err;
}
});
}
function logVersions() {
/*
log.log('info', 'OS:' + os.platform() + ' release:' + os.release());
log.log('info', 'sitespeed.io:' + require("../package.json").version);
childProcess.execFile(binPath, ['--version'], {
timeout: 120000
}, function(err, stdout, stderr) {
log.log('info', 'phantomjs:' + stdout);
});
childProcess.exec('java -version', {
timeout: 120000
}, function(err, stdout, stderr) {
log.log('info', 'java:' + stderr);
});
*/
}
Runner.prototype._createOutput = function (downloadErrors, analysisErrors, callBack) {
log.log('info', 'Done analyzing urls');
// fetch all the data we need, and then generate the output
var aggregates = this.collector.createAggregates();
var assets = this.collector.createCollections().assets;
var pages = this.collector.createCollections().pages;
var self = this;
if (this.sites)
this.sites[config.url] = aggregates;
/* We got a lot of things to do, lets generate all results
in parallel and then let us know when we are finished
*/
async.parallel({
renderSummary: function(cb) {
self.htmlRenderer.renderSummary(aggregates, cb);
},
renderAssets: function(cb) {
self.htmlRenderer.renderAssets(assets, cb);
},
renderPages: function(cb) {
self.htmlRenderer.renderPages(pages, cb);
},
renderRules: function(cb) {
// TODO the rules needs to be generated after ...
self.htmlRenderer.renderRules(cb);
},
renderErrors: function(cb) {
self.htmlRenderer.renderErrors(downloadErrors, analysisErrors, cb);
},
copyAssets: function(cb) {
self.htmlRenderer.copyAssets(config.run.absResultDir, cb);
},
renderScreenshots: function(cb) {
if (config.screenshot) {
self.htmlRenderer.renderScreenshots(pages, cb);
} else cb();
},
sendToGraphite: function(cb) {
if (config.graphiteHost)
self.graphite.sendPageData(aggregates, pages, cb);
else cb();
},
renderJUnit: function(cb) {
if (config.junit)
self.junitRenderer.renderAfterFullAnalyse(cb);
else cb();
}
},
function(err, results) {
if (!err)
log.log('info', "Wrote results to " + config.run.absResultDir);
callBack();
});
};
|
lib/runner.js
|
/**
* Sitespeed.io - How speedy is your site? (http://www.sitespeed.io)
* Copyright (c) 2014, Peter Hedenskog, Tobias Lidskog
* and other contributors
* Released under the Apache 2.0 License
*/
var crawler = require('./crawler'),
Analyzer = require('./analyze/analyzer'),
HTMLRenderer = require('./htmlRenderer'),
Collector = require('./collector'),
JUnitRenderer = require('./junitRenderer'),
Graphite = require('./graphite'),
logger = require('./log'),
path = require('path'),
dateFormat = require('dateformat'),
fs = require('fs-extra'),
config = require('./conf'),
async = require("async"),
urlParser = require('url'),
os = require('os'),
EOL = os.EOL,
binPath = require('phantomjs').path,
childProcess = require('child_process'),
log = require('winston');
module.exports = Runner;
function Runner() {
this.analyzer = new Analyzer();
this.collector = new Collector();
this.htmlRenderer = new HTMLRenderer();
this.junitRenderer = new JUnitRenderer(this.collector);
this.graphite = new Graphite(config.graphiteHost, config.graphitePort, config
.graphiteNamespace, this.collector);
}
Runner.prototype.run = function(finshedCb) {
finshedCb = finshedCb || function() {};
logVersions();
var self = this;
if (config.sites) {
this.sites = {};
var urls = fs.readFileSync(config.sites).toString().split(EOL);
var queue = async.queue(this._setupSite, 1);
log.log('info', 'Analyze ' + urls.length + ' sites');
urls.forEach(function (url) {
if (url!=="") queue.push({
'url': url,
'runner': self
}, function() {
log.log('info', "Finished with site " + url);
});
});
queue.drain = function() {
async.parallel({
copySiteAssets: function(cb) {
self.htmlRenderer.copyAssets(path.join(config.run.absResultDir,'..'), cb);
},
renderSites: function(cb) {
self.htmlRenderer.renderSites(self.sites, cb);
}
},
function(err, results) {
if (!err)
log.log('info', "Wrote sites result to " + config.run.absResultDir);
finshedCb();
});
};
}
else {
// setup the directories needed
fs.mkdirsSync(path.join(config.run.absResultDir, config.dataDir));
// TODO needs t be stored for sites also
// store the config file, so we can backtrack errors and/or use it again
fs.writeFile(path.join(config.run.absResultDir, 'config.json'), JSON.stringify(
config), function(err) {
if (err) throw err;
});
this._fetchData(finshedCb);
}
};
Runner.prototype._setupSite = function(args, cb) {
var url = args.url;
config.url= url;
config.urlObject = urlParser.parse(config.url);
config.run.absResultDir = path.join(__dirname, '../',config.resultBaseDir, 'sites', dateFormat(config.run.date, "yyyy-mm-dd-HH-MM-ss"), config.urlObject.hostname );
// setup the directories needed
fs.mkdirsSync(path.join(config.run.absResultDir, config.dataDir));
args.runner._fetchData(cb);
};
Runner.prototype._fetchData = function(cb) {
var self = this;
/**
This is the main flow of the application and this is what we do:
1. Fetch the URL:s that will be analyzed, either we crawl a site using
a start url or we read the URL:s from a file.
2. Finetune the URL:s = do other thing that's needed, store them to disk etc.
3. Let the analyser take a go at the URL:s, the analyzer
got a lot to do, lets check the analyzer.js file
4. The analyze is finished, lets create output
**/
async.waterfall([
function(cb) {
self._fetchUrls(crawler, cb);
},
function(okUrls, errorUrls, cb) {
self._fineTuneUrls(okUrls, errorUrls, cb);
},
function(urls, downloadErrors, cb) {
self._analyze(urls, downloadErrors, cb);
},
function(downloadErrors, analysisErrors, cb) {
self._createOutput(downloadErrors, analysisErrors, cb);
}
], function(err, result) {
if (err)
log.log('error', err);
cb();
});
};
Runner.prototype._fineTuneUrls = function (okUrls, errorUrls, callback) {
var downloadErrors = {};
Object.keys(errorUrls).forEach(function(url) {
log.log('error', "Failed to download " + url);
downloadErrors[url] = errorUrls[url];
});
// limit
if (config.maxPagesToTest) {
if (okUrls.length > config.maxPagesToTest)
okUrls.length = config.maxPagesToTest;
}
if (okUrls.length === 0) {
log.log('info', "Didn't get any URLs");
throw Error('No URL:s to analyze');
}
saveUrls(okUrls);
callback(null, okUrls, downloadErrors);
};
Runner.prototype._fetchUrls = function (crawler, callback) {
if (config.url) {
log.log('info', "Will crawl from start point " + config.url +
" with crawl depth " + config.deep);
crawler.crawl(config.url, function(okUrls, errorUrls) {
callback(null, okUrls, errorUrls);
});
} else {
var urls = fs.readFileSync(config.file).toString().split(EOL);
urls = urls.filter(function(l) {
return l.length > 0;
});
callback(null, urls, {});
}
};
Runner.prototype._analyze = function (urls, downloadErrors, callback) {
var analysisErrors = {};
var self = this;
log.log('info', "Will analyze " + urls.length + " pages");
this.analyzer.analyze(urls, this.collector, downloadErrors, analysisErrors, function(err, url, pageData) {
if (err) {
log.log('error', 'Could not analyze ' + url + ' (' + JSON.stringify(err) +
')');
analysisErrors[url] = err;
return;
}
if (config.junit)
self.junitRenderer.renderForEachPage(url, pageData);
self.htmlRenderer.renderPage(url, pageData, function() {});
}, callback);
};
function saveUrls(urls) {
fs.writeFile(path.join(config.run.absResultDir, 'data', 'urls.txt'), urls.join(
EOL), function(err) {
if (err) {
throw err;
}
});
}
function logVersions() {
/*
log.log('info', 'OS:' + os.platform() + ' release:' + os.release());
log.log('info', 'sitespeed.io:' + require("../package.json").version);
childProcess.execFile(binPath, ['--version'], {
timeout: 120000
}, function(err, stdout, stderr) {
log.log('info', 'phantomjs:' + stdout);
});
childProcess.exec('java -version', {
timeout: 120000
}, function(err, stdout, stderr) {
log.log('info', 'java:' + stderr);
});
*/
}
Runner.prototype._createOutput = function (downloadErrors, analysisErrors, callBack) {
log.log('info', 'Done analyzing urls');
// fetch all the data we need, and then generate the output
var aggregates = this.collector.createAggregates();
var assets = this.collector.createCollections().assets;
var pages = this.collector.createCollections().pages;
var self = this;
if (this.sites)
this.sites[config.url] = aggregates;
/* We got a lot of things to do, lets generate all results
in parallel and then let us know when we are finished
*/
async.parallel({
renderSummary: function(cb) {
self.htmlRenderer.renderSummary(aggregates, cb);
},
renderAssets: function(cb) {
self.htmlRenderer.renderAssets(assets, cb);
},
renderPages: function(cb) {
self.htmlRenderer.renderPages(pages, cb);
},
renderRules: function(cb) {
// TODO the rules needs to be generated after ...
self.htmlRenderer.renderRules(cb);
},
renderErrors: function(cb) {
self.htmlRenderer.renderErrors(downloadErrors, analysisErrors, cb);
},
copyAssets: function(cb) {
self.htmlRenderer.copyAssets(config.run.absResultDir, cb);
},
renderScreenshots: function(cb) {
if (config.screenshot) {
self.htmlRenderer.renderScreenshots(pages, cb);
} else cb();
},
sendToGraphite: function(cb) {
if (config.graphiteHost)
self.graphite.sendPageData(aggregates, pages, cb);
else cb();
},
renderJUnit: function(cb) {
if (config.junit)
self.junitRenderer.renderAfterFullAnalyse(cb);
else cb();
}
},
function(err, results) {
if (!err)
log.log('info', "Wrote results to " + config.run.absResultDir);
callBack();
});
};
|
removed sync making of dirs #445
|
lib/runner.js
|
removed sync making of dirs #445
|
<ide><path>ib/runner.js
<ide> }
<ide> else {
<ide> // setup the directories needed
<del> fs.mkdirsSync(path.join(config.run.absResultDir, config.dataDir));
<del>
<del> // TODO needs t be stored for sites also
<del> // store the config file, so we can backtrack errors and/or use it again
<del> fs.writeFile(path.join(config.run.absResultDir, 'config.json'), JSON.stringify(
<del> config), function(err) {
<del> if (err) throw err;
<del> });
<del>
<del> this._fetchData(finshedCb);
<del> }
<del>};
<add> var dataDir = path.join(config.run.absResultDir, config.dataDir);
<add> fs.mkdirs(dataDir, function(err) {
<add> if (err) {
<add> log.log('error', "Couldn't create the data dir:" + dataDir + ' ' + err);
<add> throw err;
<add> } else {
<add> // TODO needs t be stored for sites also
<add> // store the config file, so we can backtrack errors and/or use it again
<add> fs.writeFile(path.join(config.run.absResultDir, 'config.json'), JSON.stringify(
<add> config), function(err) {
<add> if (err) throw err;
<add> });
<add>
<add> self._fetchData(finshedCb);
<add> }
<add> });
<add> }
<add> };
<ide>
<ide>
<ide> Runner.prototype._setupSite = function(args, cb) {
<ide> config.urlObject = urlParser.parse(config.url);
<ide> config.run.absResultDir = path.join(__dirname, '../',config.resultBaseDir, 'sites', dateFormat(config.run.date, "yyyy-mm-dd-HH-MM-ss"), config.urlObject.hostname );
<ide> // setup the directories needed
<del> fs.mkdirsSync(path.join(config.run.absResultDir, config.dataDir));
<del> args.runner._fetchData(cb);
<add> var dataDir = path.join(config.run.absResultDir, config.dataDir);
<add> fs.mkdirs(dataDir, function (err) {
<add> if (err) {
<add> log.log('error', "Couldn't create the data dir:" + dataDir + ' ' + err);
<add> throw err;
<add> }
<add> else args.runner._fetchData(cb);
<add> });
<add>
<ide> };
<ide>
<ide> Runner.prototype._fetchData = function(cb) {
|
|
Java
|
apache-2.0
|
a99edb3292daf5abee47d29efba5f9a7c4c9fe2e
| 0 |
SpectraLogic/ds3_java_sdk,RachelTucker/ds3_java_sdk,rpmoore/ds3_java_sdk,rpmoore/ds3_java_sdk,SpectraLogic/ds3_java_sdk,RachelTucker/ds3_java_sdk,rpmoore/ds3_java_sdk,RachelTucker/ds3_java_sdk,SpectraLogic/ds3_java_sdk,RachelTucker/ds3_java_sdk,SpectraLogic/ds3_java_sdk,rpmoore/ds3_java_sdk
|
/*
* ******************************************************************************
* Copyright 2014-2017 Spectra Logic Corporation. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use
* this file except in compliance with the License. A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file.
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
* ****************************************************************************
*/
package com.spectralogic.ds3client.helpers;
import java.io.IOException;
import java.nio.file.FileSystemException;
public final class ExceptionClassifier {
private ExceptionClassifier() { }
public static boolean isRecoverableException(final Throwable t) {
if (t instanceof UnrecoverableIOException || t instanceof FileSystemException || t instanceof SecurityException || t instanceof NoSuchMethodException) {
return false;
}
return t instanceof IOException;
}
public static boolean isUnrecoverableException(final Throwable t) {
return ! isRecoverableException(t);
}
}
|
ds3-sdk/src/main/java/com/spectralogic/ds3client/helpers/ExceptionClassifier.java
|
/*
* ******************************************************************************
* Copyright 2014-2017 Spectra Logic Corporation. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use
* this file except in compliance with the License. A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file.
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
* ****************************************************************************
*/
package com.spectralogic.ds3client.helpers;
import java.io.IOException;
import java.nio.file.FileSystemException;
public final class ExceptionClassifier {
private ExceptionClassifier() { }
public static boolean isRecoverableException(final Throwable t) {
if (t instanceof UnrecoverableIOException || t instanceof FileSystemException || t instanceof SecurityException) {
return false;
}
return t instanceof IOException;
}
public static boolean isUnrecoverableException(final Throwable t) {
return ! isRecoverableException(t);
}
}
|
Fix for https://jira.spectralogic.com/browse/BPBROWSER-408
Seems that building on a machine that has both java 8 & 9 JDKs using the java 8 javac causes java 9
jars to get pulled in.
|
ds3-sdk/src/main/java/com/spectralogic/ds3client/helpers/ExceptionClassifier.java
|
Fix for https://jira.spectralogic.com/browse/BPBROWSER-408 Seems that building on a machine that has both java 8 & 9 JDKs using the java 8 javac causes java 9 jars to get pulled in.
|
<ide><path>s3-sdk/src/main/java/com/spectralogic/ds3client/helpers/ExceptionClassifier.java
<ide> private ExceptionClassifier() { }
<ide>
<ide> public static boolean isRecoverableException(final Throwable t) {
<del> if (t instanceof UnrecoverableIOException || t instanceof FileSystemException || t instanceof SecurityException) {
<add> if (t instanceof UnrecoverableIOException || t instanceof FileSystemException || t instanceof SecurityException || t instanceof NoSuchMethodException) {
<ide> return false;
<ide> }
<ide>
|
|
Java
|
agpl-3.0
|
157b110dd9a8294f7c40cf0102bec53ef95e7be0
| 0 |
quikkian-ua-devops/will-financials,UniversityOfHawaii/kfs,ua-eas/kfs,ua-eas/kfs-devops-automation-fork,quikkian-ua-devops/kfs,UniversityOfHawaii/kfs,ua-eas/kfs,quikkian-ua-devops/will-financials,kuali/kfs,bhutchinson/kfs,quikkian-ua-devops/kfs,smith750/kfs,bhutchinson/kfs,kuali/kfs,bhutchinson/kfs,ua-eas/kfs-devops-automation-fork,smith750/kfs,quikkian-ua-devops/will-financials,quikkian-ua-devops/kfs,kuali/kfs,quikkian-ua-devops/will-financials,quikkian-ua-devops/will-financials,quikkian-ua-devops/kfs,kkronenb/kfs,ua-eas/kfs-devops-automation-fork,kkronenb/kfs,smith750/kfs,quikkian-ua-devops/kfs,ua-eas/kfs,quikkian-ua-devops/will-financials,ua-eas/kfs,ua-eas/kfs-devops-automation-fork,quikkian-ua-devops/kfs,ua-eas/kfs,bhutchinson/kfs,kkronenb/kfs,UniversityOfHawaii/kfs,smith750/kfs,kuali/kfs,ua-eas/kfs-devops-automation-fork,kuali/kfs,UniversityOfHawaii/kfs,kkronenb/kfs,UniversityOfHawaii/kfs
|
/*
* Copyright 2006-2007 The Kuali Foundation.
*
* Licensed under the Educational Community License, Version 1.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ecl1.php
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kuali.module.financial.rules;
import static org.kuali.kfs.KFSConstants.ACCOUNTING_LINE_ERRORS;
import static org.kuali.kfs.KFSConstants.AMOUNT_PROPERTY_NAME;
import static org.kuali.kfs.KFSConstants.ZERO;
import static org.kuali.kfs.KFSKeyConstants.ERROR_DOCUMENT_BALANCE_CONSIDERING_SOURCE_AND_TARGET_AMOUNTS;
import static org.kuali.kfs.KFSKeyConstants.ERROR_DOCUMENT_PC_TRANSACTION_TOTAL_ACCTING_LINE_TOTAL_NOT_EQUAL;
import static org.kuali.kfs.KFSKeyConstants.ERROR_ZERO_AMOUNT;
import static org.kuali.module.financial.rules.ProcurementCardDocumentRuleConstants.ACCOUNT_NUMBER_GLOBAL_RESTRICTION_PARM_NM;
import static org.kuali.module.financial.rules.ProcurementCardDocumentRuleConstants.FUNCTION_CODE_GLOBAL_RESTRICTION_PARM_NM;
import static org.kuali.module.financial.rules.ProcurementCardDocumentRuleConstants.GLOBAL_FIELD_RESTRICTIONS_GROUP_NM;
import static org.kuali.module.financial.rules.ProcurementCardDocumentRuleConstants.MCC_OBJECT_CODE_GROUP_NM;
import static org.kuali.module.financial.rules.ProcurementCardDocumentRuleConstants.MCC_OBJECT_SUB_TYPE_GROUP_NM;
import static org.kuali.module.financial.rules.ProcurementCardDocumentRuleConstants.MCC_PARM_PREFIX;
import static org.kuali.module.financial.rules.ProcurementCardDocumentRuleConstants.OBJECT_CONSOLIDATION_GLOBAL_RESTRICTION_PARM_NM;
import static org.kuali.module.financial.rules.ProcurementCardDocumentRuleConstants.OBJECT_LEVEL_GLOBAL_RESTRICTION_PARM_NM;
import static org.kuali.module.financial.rules.ProcurementCardDocumentRuleConstants.OBJECT_SUB_TYPE_GLOBAL_RESTRICTION_PARM_NM;
import static org.kuali.module.financial.rules.ProcurementCardDocumentRuleConstants.OBJECT_TYPE_GLOBAL_RESTRICTION_PARM_NM;
import static org.kuali.module.financial.rules.ProcurementCardDocumentRuleConstants.SUB_FUND_GLOBAL_RESTRICTION_PARM_NM;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.kuali.core.util.ErrorMap;
import org.kuali.core.util.GlobalVariables;
import org.kuali.core.util.KualiDecimal;
import org.kuali.core.util.ObjectUtils;
import org.kuali.core.workflow.service.KualiWorkflowDocument;
import org.kuali.kfs.KFSKeyConstants;
import org.kuali.kfs.KFSPropertyConstants;
import org.kuali.kfs.bo.AccountingLine;
import org.kuali.kfs.bo.TargetAccountingLine;
import org.kuali.kfs.document.AccountingDocument;
import org.kuali.kfs.rules.AccountingDocumentRuleBase;
import org.kuali.module.financial.bo.ProcurementCardTargetAccountingLine;
import org.kuali.module.financial.bo.ProcurementCardTransactionDetail;
import org.kuali.module.financial.document.ProcurementCardDocument;
import org.kuali.workflow.KualiWorkflowUtils.RouteLevelNames;
import edu.iu.uis.eden.exception.WorkflowException;
/**
* Business rule(s) applicable to Procurement Card document.
*/
public class ProcurementCardDocumentRule extends AccountingDocumentRuleBase {
/**
* Inserts proper errorPath, otherwise functions just like super.
*
* @see org.kuali.core.rule.UpdateAccountingLineRule#processUpdateAccountingLineBusinessRules(org.kuali.core.document.FinancialDocument,
* org.kuali.core.bo.AccountingLine, org.kuali.core.bo.AccountingLine)
*/
@Override
public boolean processUpdateAccountingLineBusinessRules(AccountingDocument transactionalDocument, AccountingLine accountingLine, AccountingLine updatedAccountingLine) {
fixErrorPath(transactionalDocument, accountingLine);
return super.processUpdateAccountingLineBusinessRules(transactionalDocument, accountingLine, updatedAccountingLine);
}
/**
* Only target lines can be changed, so we need to only validate them
*
* @see org.kuali.module.financial.rules.FinancialDocumentRuleBase#processCustomAddAccountingLineBusinessRules(org.kuali.core.document.FinancialDocument,
* org.kuali.core.bo.AccountingLine)
*/
@Override
protected boolean processCustomAddAccountingLineBusinessRules(AccountingDocument transactionalDocument, AccountingLine accountingLine) {
boolean allow = true;
if (accountingLine instanceof ProcurementCardTargetAccountingLine) {
LOG.debug("validating accounting line # " + accountingLine.getSequenceNumber());
// Somewhat of an ugly hack... the goal is to have fixErrorPath run for cases where it's _not_ a new accounting line.
// If it is a new accounting line, all is well. But if it isn't then this might be a case where approve is called
// and we need to run validation with proper errorPath for that.
if (accountingLine.getSequenceNumber() != null) {
fixErrorPath(transactionalDocument, accountingLine);
}
LOG.debug("beginning object code validation ");
allow = validateObjectCode(transactionalDocument, accountingLine);
LOG.debug("beginning account number validation ");
allow = allow & validateAccountNumber(transactionalDocument, accountingLine);
LOG.debug("end validating accounting line, has errors: " + allow);
}
return allow;
}
/**
* Only target lines can be changed, so we need to only validate them
*
* @see org.kuali.module.financial.rules.FinancialDocumentRuleBase#processCustomUpdateAccountingLineBusinessRules(org.kuali.core.document.FinancialDocument,
* org.kuali.core.bo.AccountingLine, org.kuali.core.bo.AccountingLine)
*/
@Override
protected boolean processCustomUpdateAccountingLineBusinessRules(AccountingDocument transactionalDocument, AccountingLine accountingLine, AccountingLine updatedAccountingLine) {
return processCustomAddAccountingLineBusinessRules(transactionalDocument, updatedAccountingLine);
}
/**
* Only target lines can be changed, so we need to only validate them
*
* @see org.kuali.module.financial.rules.FinancialDocumentRuleBase#processCustomReviewAccountingLineBusinessRules(org.kuali.core.document.FinancialDocument,
* org.kuali.core.bo.AccountingLine)
*/
@Override
protected boolean processCustomReviewAccountingLineBusinessRules(AccountingDocument transactionalDocument, AccountingLine accountingLine) {
return processCustomAddAccountingLineBusinessRules(transactionalDocument, accountingLine);
}
/**
* Checks object codes restrictions, including restrictions in parameters table.
*
* @param transactionalDocument
* @param accountingLine
* @return boolean
*/
public boolean validateObjectCode(AccountingDocument transactionalDocument, AccountingLine accountingLine) {
ProcurementCardDocument pcDocument = (ProcurementCardDocument) transactionalDocument;
ErrorMap errors = GlobalVariables.getErrorMap();
String errorKey = KFSPropertyConstants.FINANCIAL_OBJECT_CODE;
boolean objectCodeAllowed = true;
/* object code exist done in super, check we have a valid object */
if (ObjectUtils.isNull(accountingLine.getObjectCode())) {
return false;
}
/* make sure object code is active */
if (!accountingLine.getObjectCode().isFinancialObjectActiveCode()) {
errors.putError(errorKey, KFSKeyConstants.ERROR_INACTIVE, "object code");
objectCodeAllowed = false;
}
/* check object type global restrictions */
objectCodeAllowed = objectCodeAllowed && executeApplicationParameterRestriction(GLOBAL_FIELD_RESTRICTIONS_GROUP_NM, OBJECT_TYPE_GLOBAL_RESTRICTION_PARM_NM, accountingLine.getObjectCode().getFinancialObjectTypeCode(), errorKey, "Object type");
/* check object sub type global restrictions */
objectCodeAllowed = objectCodeAllowed && executeApplicationParameterRestriction(GLOBAL_FIELD_RESTRICTIONS_GROUP_NM, OBJECT_SUB_TYPE_GLOBAL_RESTRICTION_PARM_NM, accountingLine.getObjectCode().getFinancialObjectSubTypeCode(), errorKey, "Object sub type");
/* check object level global restrictions */
objectCodeAllowed = objectCodeAllowed && executeApplicationParameterRestriction(GLOBAL_FIELD_RESTRICTIONS_GROUP_NM, OBJECT_LEVEL_GLOBAL_RESTRICTION_PARM_NM, accountingLine.getObjectCode().getFinancialObjectLevelCode(), errorKey, "Object level");
/* check object consolidation global restrictions */
objectCodeAllowed = objectCodeAllowed && executeApplicationParameterRestriction(GLOBAL_FIELD_RESTRICTIONS_GROUP_NM, OBJECT_CONSOLIDATION_GLOBAL_RESTRICTION_PARM_NM, accountingLine.getObjectCode().getFinancialObjectLevel().getFinancialConsolidationObjectCode(), errorKey, "Object consolidation code");
/* get mcc restriction from transaction */
String mccRestriction = "";
ProcurementCardTargetAccountingLine line = (ProcurementCardTargetAccountingLine) accountingLine;
List pcTransactions = pcDocument.getTransactionEntries();
for (Iterator iter = pcTransactions.iterator(); iter.hasNext();) {
ProcurementCardTransactionDetail transactionEntry = (ProcurementCardTransactionDetail) iter.next();
if (transactionEntry.getFinancialDocumentTransactionLineNumber().equals(line.getFinancialDocumentTransactionLineNumber())) {
mccRestriction = transactionEntry.getProcurementCardVendor().getTransactionMerchantCategoryCode();
}
}
if (StringUtils.isBlank(mccRestriction)) {
return objectCodeAllowed;
}
/* check object code is in permitted list for mcc */
objectCodeAllowed = objectCodeAllowed && executeApplicationParameterRestriction(MCC_OBJECT_CODE_GROUP_NM, MCC_PARM_PREFIX + mccRestriction, accountingLine.getFinancialObjectCode(), errorKey, "Object code");
/* check object sub type is in permitted list for mcc */
objectCodeAllowed = objectCodeAllowed && executeApplicationParameterRestriction(MCC_OBJECT_SUB_TYPE_GROUP_NM, MCC_PARM_PREFIX + mccRestriction, accountingLine.getObjectCode().getFinancialObjectSubTypeCode(), errorKey, "Object sub type code");
return objectCodeAllowed;
}
/**
* Checks account number restrictions, including restrictions in parameters table.
*
* @param transactionalDocument
* @param accountingLine
* @return boolean
*/
public boolean validateAccountNumber(AccountingDocument transactionalDocument, AccountingLine accountingLine) {
ProcurementCardDocument pcDocument = (ProcurementCardDocument) transactionalDocument;
ErrorMap errors = GlobalVariables.getErrorMap();
String errorKey = KFSPropertyConstants.ACCOUNT_NUMBER;
boolean accountNumberAllowed = true;
/* account exist and object exist done in super, check we have a valid object */
if (ObjectUtils.isNull(accountingLine.getAccount()) || ObjectUtils.isNull(accountingLine.getObjectCode())) {
return false;
}
/* global account number restrictions */
accountNumberAllowed = accountNumberAllowed && executeApplicationParameterRestriction(GLOBAL_FIELD_RESTRICTIONS_GROUP_NM, ACCOUNT_NUMBER_GLOBAL_RESTRICTION_PARM_NM, accountingLine.getAccountNumber(), errorKey, "Account number");
/* global sub fund restrictions */
accountNumberAllowed = accountNumberAllowed && executeApplicationParameterRestriction(GLOBAL_FIELD_RESTRICTIONS_GROUP_NM, SUB_FUND_GLOBAL_RESTRICTION_PARM_NM, accountingLine.getAccount().getSubFundGroupCode(), errorKey, "Sub fund code");
/* global function code restrictions */
accountNumberAllowed = accountNumberAllowed && executeApplicationParameterRestriction(GLOBAL_FIELD_RESTRICTIONS_GROUP_NM, FUNCTION_CODE_GLOBAL_RESTRICTION_PARM_NM, accountingLine.getAccount().getFinancialHigherEdFunctionCd(), errorKey, "Function code");
return accountNumberAllowed;
}
/**
* Overrides FinancialDocumentRuleBase.isDocumentBalanceValid and changes the default debit/credit comparision to checking
* the target total against the total balance. If they don't balance, and error message is produced that is more appropriate for
* PCDO.
*
* @param transactionalDocument
* @return boolean True if the document is balanced, false otherwise.
*/
@Override
protected boolean isDocumentBalanceValid(AccountingDocument transactionalDocument) {
ProcurementCardDocument pcDocument = (ProcurementCardDocument) transactionalDocument;
KualiDecimal targetTotal = pcDocument.getTargetTotal();
KualiDecimal sourceTotal = pcDocument.getSourceTotal();
boolean isValid = targetTotal.compareTo(sourceTotal) == 0;
if (!isValid) {
GlobalVariables.getErrorMap().putError(ACCOUNTING_LINE_ERRORS, ERROR_DOCUMENT_BALANCE_CONSIDERING_SOURCE_AND_TARGET_AMOUNTS, new String[] { sourceTotal.toString(), targetTotal.toString() });
}
List<ProcurementCardTransactionDetail> pcTransactionEntries = pcDocument.getTransactionEntries();
for(ProcurementCardTransactionDetail pcTransactionDetail : pcTransactionEntries) {
isValid &= isTransactionBalanceValid(pcTransactionDetail);
}
return isValid;
}
/**
*
* This method...
* @param pcTransaction
* @return
*/
protected boolean isTransactionBalanceValid(ProcurementCardTransactionDetail pcTransaction) {
boolean inBalance = true;
KualiDecimal transAmount = pcTransaction.getTransactionTotalAmount();
List<ProcurementCardTargetAccountingLine> targetAcctingLines = pcTransaction.getTargetAccountingLines();
KualiDecimal targetLineTotal = new KualiDecimal(0.00);
for(TargetAccountingLine targetLine : targetAcctingLines) {
targetLineTotal = targetLineTotal.add(targetLine.getAmount());
}
// perform absolute value check because current system has situations where amounts may be opposite in sign
// This will no longer be necessary following completion of KULFDBCK-1290
inBalance = transAmount.abs().equals(targetLineTotal.abs());
if(!inBalance) {
GlobalVariables.getErrorMap().putError(ACCOUNTING_LINE_ERRORS, ERROR_DOCUMENT_PC_TRANSACTION_TOTAL_ACCTING_LINE_TOTAL_NOT_EQUAL, new String[] {transAmount.toString(), targetLineTotal.toString()});
}
return inBalance;
}
/**
* On procurement card, positive source amounts are credits, negative source amounts are debits
*
* @see org.kuali.module.financial.rules.FinancialDocumentRuleBase#isDebit(FinancialDocument,
* org.kuali.core.bo.AccountingLine)
*/
public boolean isDebit(AccountingDocument transactionalDocument, AccountingLine accountingLine) throws IllegalStateException {
// disallow error correction
IsDebitUtils.disallowErrorCorrectionDocumentCheck(this, transactionalDocument);
return IsDebitUtils.isDebitConsideringSection(this, transactionalDocument, accountingLine);
}
/**
* Override for fiscal officer full approve, in which case any account can be used.
*
* @see org.kuali.module.financial.rules.FinancialDocumentRuleBase#accountIsAccessible(org.kuali.core.document.FinancialDocument,
* org.kuali.core.bo.AccountingLine)
*/
@Override
protected boolean accountIsAccessible(AccountingDocument transactionalDocument, AccountingLine accountingLine) {
KualiWorkflowDocument workflowDocument = transactionalDocument.getDocumentHeader().getWorkflowDocument();
List activeNodes = null;
try {
activeNodes = Arrays.asList(workflowDocument.getNodeNames());
}
catch (WorkflowException e) {
LOG.error("Error getting active nodes " + e.getMessage());
throw new RuntimeException("Error getting active nodes " + e.getMessage());
}
if (workflowDocument.stateIsEnroute() && activeNodes.contains(RouteLevelNames.ACCOUNT_REVIEW_FULL_EDIT)) {
return true;
}
return super.accountIsAccessible(transactionalDocument, accountingLine);
}
/**
* For transactions that are credits back from the bank, accounting lines can be negative. It still checks that an amount is not
* zero.
*
* @see org.kuali.module.financial.rules.FinancialDocumentRuleBase#isAmountValid(org.kuali.core.document.FinancialDocument,
* org.kuali.core.bo.AccountingLine)
*/
@Override
public boolean isAmountValid(AccountingDocument document, AccountingLine accountingLine) {
KualiDecimal amount = accountingLine.getAmount();
// Check for zero, negative amounts (non-correction), positive amounts (correction)
String correctsDocumentId = document.getDocumentHeader().getFinancialDocumentInErrorNumber();
if (ZERO.compareTo(amount) == 0) { // amount == 0
GlobalVariables.getErrorMap().putError(AMOUNT_PROPERTY_NAME, ERROR_ZERO_AMOUNT, "an accounting line");
LOG.info("failing isAmountValid - zero check");
return false;
}
return true;
}
/**
* Override to avoid seeing ERROR_DOCUMENT_SINGLE_ACCOUNTING_LINE_SECTION_TOTAL_CHANGED error message on PCDO.
*
* @param propertyName
* @param persistedSourceLineTotal
* @param currentSourceLineTotal
*/
@Override
protected void buildTotalChangeErrorMessage(String propertyName, KualiDecimal persistedSourceLineTotal, KualiDecimal currentSourceLineTotal) {
return;
}
/**
* Fix the GlobalVariables.getErrorMap errorPath for how PCDO needs them in order to properly display errors on the
* interface. This is different from kuali accounting lines because instead PCDO has accounting lines insides of
* transactions. Hence the error path is slighly different.
*
* @param transactionalDocument
* @param accountingLine
*/
private void fixErrorPath(AccountingDocument financialDocument, AccountingLine accountingLine) {
List transactionEntries = ((ProcurementCardDocument) financialDocument).getTransactionEntries();
ProcurementCardTargetAccountingLine targetAccountingLineToBeFound = (ProcurementCardTargetAccountingLine) accountingLine;
String errorPath = KFSPropertyConstants.DOCUMENT;
// originally I used getFinancialDocumentTransactionLineNumber to determine the appropriate transaction, unfortunatly
// this makes it dependent on the order of transactionEntries in FP_PRCRMNT_DOC_T. Hence we have two loops below.
boolean done = false;
int transactionLineIndex = 0;
for (Iterator iterTransactionEntries = transactionEntries.iterator(); !done && iterTransactionEntries.hasNext(); transactionLineIndex++) {
ProcurementCardTransactionDetail transactionEntry = (ProcurementCardTransactionDetail) iterTransactionEntries.next();
// Loop over the transactionEntry to find the accountingLine's location. Keep another counter handy.
int accountingLineCounter = 0;
for (Iterator iterTargetAccountingLines = transactionEntry.getTargetAccountingLines().iterator(); !done && iterTargetAccountingLines.hasNext(); accountingLineCounter++) {
ProcurementCardTargetAccountingLine targetAccountingLine = (ProcurementCardTargetAccountingLine) iterTargetAccountingLines.next();
if(targetAccountingLine.getSequenceNumber().equals(targetAccountingLineToBeFound.getSequenceNumber())) {
// Found the item, capture error path, and set boolean (break isn't enough for 2 loops).
errorPath = errorPath + "." + KFSPropertyConstants.TRANSACTION_ENTRIES + "[" + transactionLineIndex + "]." + KFSPropertyConstants.TARGET_ACCOUNTING_LINES + "[" + accountingLineCounter + "]";
done = true;
}
}
}
if (!done) {
LOG.warn("fixErrorPath failed to locate item accountingLine=" + accountingLine.toString());
}
// Clearing the error path is not a universal solution but should work for PCDO. In this case it's the only choice
// because KualiRuleService.applyRules will miss to remove the previous transaction added error path (only this
// method knows how it is called).
ErrorMap errorMap = GlobalVariables.getErrorMap();
errorMap.clearErrorPath();
errorMap.addToErrorPath(errorPath);
}
}
|
work/src/org/kuali/kfs/fp/document/validation/impl/ProcurementCardDocumentRule.java
|
/*
* Copyright 2006-2007 The Kuali Foundation.
*
* Licensed under the Educational Community License, Version 1.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ecl1.php
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kuali.module.financial.rules;
import static org.kuali.kfs.KFSConstants.ACCOUNTING_LINE_ERRORS;
import static org.kuali.kfs.KFSConstants.AMOUNT_PROPERTY_NAME;
import static org.kuali.kfs.KFSConstants.ZERO;
import static org.kuali.kfs.KFSKeyConstants.ERROR_DOCUMENT_BALANCE_CONSIDERING_SOURCE_AND_TARGET_AMOUNTS;
import static org.kuali.kfs.KFSKeyConstants.ERROR_ZERO_AMOUNT;
import static org.kuali.module.financial.rules.ProcurementCardDocumentRuleConstants.ACCOUNT_NUMBER_GLOBAL_RESTRICTION_PARM_NM;
import static org.kuali.module.financial.rules.ProcurementCardDocumentRuleConstants.FUNCTION_CODE_GLOBAL_RESTRICTION_PARM_NM;
import static org.kuali.module.financial.rules.ProcurementCardDocumentRuleConstants.GLOBAL_FIELD_RESTRICTIONS_GROUP_NM;
import static org.kuali.module.financial.rules.ProcurementCardDocumentRuleConstants.MCC_OBJECT_CODE_GROUP_NM;
import static org.kuali.module.financial.rules.ProcurementCardDocumentRuleConstants.MCC_OBJECT_SUB_TYPE_GROUP_NM;
import static org.kuali.module.financial.rules.ProcurementCardDocumentRuleConstants.MCC_PARM_PREFIX;
import static org.kuali.module.financial.rules.ProcurementCardDocumentRuleConstants.OBJECT_CONSOLIDATION_GLOBAL_RESTRICTION_PARM_NM;
import static org.kuali.module.financial.rules.ProcurementCardDocumentRuleConstants.OBJECT_LEVEL_GLOBAL_RESTRICTION_PARM_NM;
import static org.kuali.module.financial.rules.ProcurementCardDocumentRuleConstants.OBJECT_SUB_TYPE_GLOBAL_RESTRICTION_PARM_NM;
import static org.kuali.module.financial.rules.ProcurementCardDocumentRuleConstants.OBJECT_TYPE_GLOBAL_RESTRICTION_PARM_NM;
import static org.kuali.module.financial.rules.ProcurementCardDocumentRuleConstants.SUB_FUND_GLOBAL_RESTRICTION_PARM_NM;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.kuali.core.util.ErrorMap;
import org.kuali.core.util.GlobalVariables;
import org.kuali.core.util.KualiDecimal;
import org.kuali.core.util.ObjectUtils;
import org.kuali.core.workflow.service.KualiWorkflowDocument;
import org.kuali.kfs.KFSKeyConstants;
import org.kuali.kfs.KFSPropertyConstants;
import org.kuali.kfs.bo.AccountingLine;
import org.kuali.kfs.document.AccountingDocument;
import org.kuali.kfs.rules.AccountingDocumentRuleBase;
import org.kuali.module.financial.bo.ProcurementCardTargetAccountingLine;
import org.kuali.module.financial.bo.ProcurementCardTransactionDetail;
import org.kuali.module.financial.document.ProcurementCardDocument;
import org.kuali.workflow.KualiWorkflowUtils.RouteLevelNames;
import edu.iu.uis.eden.exception.WorkflowException;
/**
* Business rule(s) applicable to Procurement Card document.
*/
public class ProcurementCardDocumentRule extends AccountingDocumentRuleBase {
/**
* Inserts proper errorPath, otherwise functions just like super.
*
* @see org.kuali.core.rule.UpdateAccountingLineRule#processUpdateAccountingLineBusinessRules(org.kuali.core.document.FinancialDocument,
* org.kuali.core.bo.AccountingLine, org.kuali.core.bo.AccountingLine)
*/
@Override
public boolean processUpdateAccountingLineBusinessRules(AccountingDocument transactionalDocument, AccountingLine accountingLine, AccountingLine updatedAccountingLine) {
fixErrorPath(transactionalDocument, accountingLine);
return super.processUpdateAccountingLineBusinessRules(transactionalDocument, accountingLine, updatedAccountingLine);
}
/**
* Only target lines can be changed, so we need to only validate them
*
* @see org.kuali.module.financial.rules.FinancialDocumentRuleBase#processCustomAddAccountingLineBusinessRules(org.kuali.core.document.FinancialDocument,
* org.kuali.core.bo.AccountingLine)
*/
@Override
protected boolean processCustomAddAccountingLineBusinessRules(AccountingDocument transactionalDocument, AccountingLine accountingLine) {
boolean allow = true;
if (accountingLine instanceof ProcurementCardTargetAccountingLine) {
LOG.debug("validating accounting line # " + accountingLine.getSequenceNumber());
// Somewhat of an ugly hack... the goal is to have fixErrorPath run for cases where it's _not_ a new accounting line.
// If it is a new accounting line, all is well. But if it isn't then this might be a case where approve is called
// and we need to run validation with proper errorPath for that.
if (accountingLine.getSequenceNumber() != null) {
fixErrorPath(transactionalDocument, accountingLine);
}
LOG.debug("beginning object code validation ");
allow = validateObjectCode(transactionalDocument, accountingLine);
LOG.debug("beginning account number validation ");
allow = allow & validateAccountNumber(transactionalDocument, accountingLine);
LOG.debug("end validating accounting line, has errors: " + allow);
}
return allow;
}
/**
* Only target lines can be changed, so we need to only validate them
*
* @see org.kuali.module.financial.rules.FinancialDocumentRuleBase#processCustomUpdateAccountingLineBusinessRules(org.kuali.core.document.FinancialDocument,
* org.kuali.core.bo.AccountingLine, org.kuali.core.bo.AccountingLine)
*/
@Override
protected boolean processCustomUpdateAccountingLineBusinessRules(AccountingDocument transactionalDocument, AccountingLine accountingLine, AccountingLine updatedAccountingLine) {
return processCustomAddAccountingLineBusinessRules(transactionalDocument, updatedAccountingLine);
}
/**
* Only target lines can be changed, so we need to only validate them
*
* @see org.kuali.module.financial.rules.FinancialDocumentRuleBase#processCustomReviewAccountingLineBusinessRules(org.kuali.core.document.FinancialDocument,
* org.kuali.core.bo.AccountingLine)
*/
@Override
protected boolean processCustomReviewAccountingLineBusinessRules(AccountingDocument transactionalDocument, AccountingLine accountingLine) {
return processCustomAddAccountingLineBusinessRules(transactionalDocument, accountingLine);
}
/**
* Checks object codes restrictions, including restrictions in parameters table.
*
* @param transactionalDocument
* @param accountingLine
* @return boolean
*/
public boolean validateObjectCode(AccountingDocument transactionalDocument, AccountingLine accountingLine) {
ProcurementCardDocument pcDocument = (ProcurementCardDocument) transactionalDocument;
ErrorMap errors = GlobalVariables.getErrorMap();
String errorKey = KFSPropertyConstants.FINANCIAL_OBJECT_CODE;
boolean objectCodeAllowed = true;
/* object code exist done in super, check we have a valid object */
if (ObjectUtils.isNull(accountingLine.getObjectCode())) {
return false;
}
/* make sure object code is active */
if (!accountingLine.getObjectCode().isFinancialObjectActiveCode()) {
errors.putError(errorKey, KFSKeyConstants.ERROR_INACTIVE, "object code");
objectCodeAllowed = false;
}
/* check object type global restrictions */
objectCodeAllowed = objectCodeAllowed && executeApplicationParameterRestriction(GLOBAL_FIELD_RESTRICTIONS_GROUP_NM, OBJECT_TYPE_GLOBAL_RESTRICTION_PARM_NM, accountingLine.getObjectCode().getFinancialObjectTypeCode(), errorKey, "Object type");
/* check object sub type global restrictions */
objectCodeAllowed = objectCodeAllowed && executeApplicationParameterRestriction(GLOBAL_FIELD_RESTRICTIONS_GROUP_NM, OBJECT_SUB_TYPE_GLOBAL_RESTRICTION_PARM_NM, accountingLine.getObjectCode().getFinancialObjectSubTypeCode(), errorKey, "Object sub type");
/* check object level global restrictions */
objectCodeAllowed = objectCodeAllowed && executeApplicationParameterRestriction(GLOBAL_FIELD_RESTRICTIONS_GROUP_NM, OBJECT_LEVEL_GLOBAL_RESTRICTION_PARM_NM, accountingLine.getObjectCode().getFinancialObjectLevelCode(), errorKey, "Object level");
/* check object consolidation global restrictions */
objectCodeAllowed = objectCodeAllowed && executeApplicationParameterRestriction(GLOBAL_FIELD_RESTRICTIONS_GROUP_NM, OBJECT_CONSOLIDATION_GLOBAL_RESTRICTION_PARM_NM, accountingLine.getObjectCode().getFinancialObjectLevel().getFinancialConsolidationObjectCode(), errorKey, "Object consolidation code");
/* get mcc restriction from transaction */
String mccRestriction = "";
ProcurementCardTargetAccountingLine line = (ProcurementCardTargetAccountingLine) accountingLine;
List pcTransactions = pcDocument.getTransactionEntries();
for (Iterator iter = pcTransactions.iterator(); iter.hasNext();) {
ProcurementCardTransactionDetail transactionEntry = (ProcurementCardTransactionDetail) iter.next();
if (transactionEntry.getFinancialDocumentTransactionLineNumber().equals(line.getFinancialDocumentTransactionLineNumber())) {
mccRestriction = transactionEntry.getProcurementCardVendor().getTransactionMerchantCategoryCode();
}
}
if (StringUtils.isBlank(mccRestriction)) {
return objectCodeAllowed;
}
/* check object code is in permitted list for mcc */
objectCodeAllowed = objectCodeAllowed && executeApplicationParameterRestriction(MCC_OBJECT_CODE_GROUP_NM, MCC_PARM_PREFIX + mccRestriction, accountingLine.getFinancialObjectCode(), errorKey, "Object code");
/* check object sub type is in permitted list for mcc */
objectCodeAllowed = objectCodeAllowed && executeApplicationParameterRestriction(MCC_OBJECT_SUB_TYPE_GROUP_NM, MCC_PARM_PREFIX + mccRestriction, accountingLine.getObjectCode().getFinancialObjectSubTypeCode(), errorKey, "Object sub type code");
return objectCodeAllowed;
}
/**
* Checks account number restrictions, including restrictions in parameters table.
*
* @param transactionalDocument
* @param accountingLine
* @return boolean
*/
public boolean validateAccountNumber(AccountingDocument transactionalDocument, AccountingLine accountingLine) {
ProcurementCardDocument pcDocument = (ProcurementCardDocument) transactionalDocument;
ErrorMap errors = GlobalVariables.getErrorMap();
String errorKey = KFSPropertyConstants.ACCOUNT_NUMBER;
boolean accountNumberAllowed = true;
/* account exist and object exist done in super, check we have a valid object */
if (ObjectUtils.isNull(accountingLine.getAccount()) || ObjectUtils.isNull(accountingLine.getObjectCode())) {
return false;
}
/* global account number restrictions */
accountNumberAllowed = accountNumberAllowed && executeApplicationParameterRestriction(GLOBAL_FIELD_RESTRICTIONS_GROUP_NM, ACCOUNT_NUMBER_GLOBAL_RESTRICTION_PARM_NM, accountingLine.getAccountNumber(), errorKey, "Account number");
/* global sub fund restrictions */
accountNumberAllowed = accountNumberAllowed && executeApplicationParameterRestriction(GLOBAL_FIELD_RESTRICTIONS_GROUP_NM, SUB_FUND_GLOBAL_RESTRICTION_PARM_NM, accountingLine.getAccount().getSubFundGroupCode(), errorKey, "Sub fund code");
/* global function code restrictions */
accountNumberAllowed = accountNumberAllowed && executeApplicationParameterRestriction(GLOBAL_FIELD_RESTRICTIONS_GROUP_NM, FUNCTION_CODE_GLOBAL_RESTRICTION_PARM_NM, accountingLine.getAccount().getFinancialHigherEdFunctionCd(), errorKey, "Function code");
return accountNumberAllowed;
}
/**
* Overrides FinancialDocumentRuleBase.isDocumentBalanceValid and changes the default debit/credit comparision to checking
* the target total against the total balance. If they don't balance, and error message is produced that is more appropriate for
* PCDO.
*
* @param transactionalDocument
* @return boolean True if the document is balanced, false otherwise.
*/
@Override
protected boolean isDocumentBalanceValid(AccountingDocument transactionalDocument) {
ProcurementCardDocument pcDocument = (ProcurementCardDocument) transactionalDocument;
KualiDecimal targetTotal = pcDocument.getTargetTotal();
KualiDecimal sourceTotal = pcDocument.getSourceTotal();
boolean isValid = targetTotal.compareTo(sourceTotal) == 0;
if (!isValid) {
GlobalVariables.getErrorMap().putError(ACCOUNTING_LINE_ERRORS, ERROR_DOCUMENT_BALANCE_CONSIDERING_SOURCE_AND_TARGET_AMOUNTS, new String[] { sourceTotal.toString(), targetTotal.toString() });
}
return isValid;
}
/**
* On procurement card, positive source amounts are credits, negative source amounts are debits
*
* @see org.kuali.module.financial.rules.FinancialDocumentRuleBase#isDebit(FinancialDocument,
* org.kuali.core.bo.AccountingLine)
*/
public boolean isDebit(AccountingDocument transactionalDocument, AccountingLine accountingLine) throws IllegalStateException {
// disallow error correction
IsDebitUtils.disallowErrorCorrectionDocumentCheck(this, transactionalDocument);
return IsDebitUtils.isDebitConsideringSection(this, transactionalDocument, accountingLine);
}
/**
* Override for fiscal officer full approve, in which case any account can be used.
*
* @see org.kuali.module.financial.rules.FinancialDocumentRuleBase#accountIsAccessible(org.kuali.core.document.FinancialDocument,
* org.kuali.core.bo.AccountingLine)
*/
@Override
protected boolean accountIsAccessible(AccountingDocument transactionalDocument, AccountingLine accountingLine) {
KualiWorkflowDocument workflowDocument = transactionalDocument.getDocumentHeader().getWorkflowDocument();
List activeNodes = null;
try {
activeNodes = Arrays.asList(workflowDocument.getNodeNames());
}
catch (WorkflowException e) {
LOG.error("Error getting active nodes " + e.getMessage());
throw new RuntimeException("Error getting active nodes " + e.getMessage());
}
if (workflowDocument.stateIsEnroute() && activeNodes.contains(RouteLevelNames.ACCOUNT_REVIEW_FULL_EDIT)) {
return true;
}
return super.accountIsAccessible(transactionalDocument, accountingLine);
}
/**
* For transactions that are credits back from the bank, accounting lines can be negative. It still checks that an amount is not
* zero.
*
* @see org.kuali.module.financial.rules.FinancialDocumentRuleBase#isAmountValid(org.kuali.core.document.FinancialDocument,
* org.kuali.core.bo.AccountingLine)
*/
@Override
public boolean isAmountValid(AccountingDocument document, AccountingLine accountingLine) {
KualiDecimal amount = accountingLine.getAmount();
// Check for zero, negative amounts (non-correction), positive amounts (correction)
String correctsDocumentId = document.getDocumentHeader().getFinancialDocumentInErrorNumber();
if (ZERO.compareTo(amount) == 0) { // amount == 0
GlobalVariables.getErrorMap().putError(AMOUNT_PROPERTY_NAME, ERROR_ZERO_AMOUNT, "an accounting line");
LOG.info("failing isAmountValid - zero check");
return false;
}
return true;
}
/**
* Override to avoid seeing ERROR_DOCUMENT_SINGLE_ACCOUNTING_LINE_SECTION_TOTAL_CHANGED error message on PCDO.
*
* @param propertyName
* @param persistedSourceLineTotal
* @param currentSourceLineTotal
*/
@Override
protected void buildTotalChangeErrorMessage(String propertyName, KualiDecimal persistedSourceLineTotal, KualiDecimal currentSourceLineTotal) {
return;
}
/**
* Fix the GlobalVariables.getErrorMap errorPath for how PCDO needs them in order to properly display errors on the
* interface. This is different from kuali accounting lines because instead PCDO has accounting lines insides of
* transactions. Hence the error path is slighly different.
*
* @param transactionalDocument
* @param accountingLine
*/
private void fixErrorPath(AccountingDocument financialDocument, AccountingLine accountingLine) {
List transactionEntries = ((ProcurementCardDocument) financialDocument).getTransactionEntries();
ProcurementCardTargetAccountingLine targetAccountingLineToBeFound = (ProcurementCardTargetAccountingLine) accountingLine;
String errorPath = KFSPropertyConstants.DOCUMENT;
// originally I used getFinancialDocumentTransactionLineNumber to determine the appropriate transaction, unfortunatly
// this makes it dependent on the order of transactionEntries in FP_PRCRMNT_DOC_T. Hence we have two loops below.
boolean done = false;
int transactionLineIndex = 0;
for (Iterator iterTransactionEntries = transactionEntries.iterator(); !done && iterTransactionEntries.hasNext(); transactionLineIndex++) {
ProcurementCardTransactionDetail transactionEntry = (ProcurementCardTransactionDetail) iterTransactionEntries.next();
// Loop over the transactionEntry to find the accountingLine's location. Keep another counter handy.
int accountingLineCounter = 0;
for (Iterator iterTargetAccountingLines = transactionEntry.getTargetAccountingLines().iterator(); !done && iterTargetAccountingLines.hasNext(); accountingLineCounter++) {
ProcurementCardTargetAccountingLine targetAccountingLine = (ProcurementCardTargetAccountingLine) iterTargetAccountingLines.next();
if(targetAccountingLine.getSequenceNumber().equals(targetAccountingLineToBeFound.getSequenceNumber())) {
// Found the item, capture error path, and set boolean (break isn't enough for 2 loops).
errorPath = errorPath + "." + KFSPropertyConstants.TRANSACTION_ENTRIES + "[" + transactionLineIndex + "]." + KFSPropertyConstants.TARGET_ACCOUNTING_LINES + "[" + accountingLineCounter + "]";
done = true;
}
}
}
if (!done) {
LOG.warn("fixErrorPath failed to locate item accountingLine=" + accountingLine.toString());
}
// Clearing the error path is not a universal solution but should work for PCDO. In this case it's the only choice
// because KualiRuleService.applyRules will miss to remove the previous transaction added error path (only this
// method knows how it is called).
ErrorMap errorMap = GlobalVariables.getErrorMap();
errorMap.clearErrorPath();
errorMap.addToErrorPath(errorPath);
}
}
|
KULFDBCK-877 : Added a new validation method to check the balance of each PC transaction to make sure it balances against it's associated accounting lines.
|
work/src/org/kuali/kfs/fp/document/validation/impl/ProcurementCardDocumentRule.java
|
KULFDBCK-877 : Added a new validation method to check the balance of each PC transaction to make sure it balances against it's associated accounting lines.
|
<ide><path>ork/src/org/kuali/kfs/fp/document/validation/impl/ProcurementCardDocumentRule.java
<ide> import static org.kuali.kfs.KFSConstants.AMOUNT_PROPERTY_NAME;
<ide> import static org.kuali.kfs.KFSConstants.ZERO;
<ide> import static org.kuali.kfs.KFSKeyConstants.ERROR_DOCUMENT_BALANCE_CONSIDERING_SOURCE_AND_TARGET_AMOUNTS;
<add>import static org.kuali.kfs.KFSKeyConstants.ERROR_DOCUMENT_PC_TRANSACTION_TOTAL_ACCTING_LINE_TOTAL_NOT_EQUAL;
<ide> import static org.kuali.kfs.KFSKeyConstants.ERROR_ZERO_AMOUNT;
<ide> import static org.kuali.module.financial.rules.ProcurementCardDocumentRuleConstants.ACCOUNT_NUMBER_GLOBAL_RESTRICTION_PARM_NM;
<ide> import static org.kuali.module.financial.rules.ProcurementCardDocumentRuleConstants.FUNCTION_CODE_GLOBAL_RESTRICTION_PARM_NM;
<ide> import org.kuali.kfs.KFSKeyConstants;
<ide> import org.kuali.kfs.KFSPropertyConstants;
<ide> import org.kuali.kfs.bo.AccountingLine;
<add>import org.kuali.kfs.bo.TargetAccountingLine;
<ide> import org.kuali.kfs.document.AccountingDocument;
<ide> import org.kuali.kfs.rules.AccountingDocumentRuleBase;
<ide> import org.kuali.module.financial.bo.ProcurementCardTargetAccountingLine;
<ide> GlobalVariables.getErrorMap().putError(ACCOUNTING_LINE_ERRORS, ERROR_DOCUMENT_BALANCE_CONSIDERING_SOURCE_AND_TARGET_AMOUNTS, new String[] { sourceTotal.toString(), targetTotal.toString() });
<ide> }
<ide>
<add> List<ProcurementCardTransactionDetail> pcTransactionEntries = pcDocument.getTransactionEntries();
<add>
<add> for(ProcurementCardTransactionDetail pcTransactionDetail : pcTransactionEntries) {
<add> isValid &= isTransactionBalanceValid(pcTransactionDetail);
<add> }
<add>
<ide> return isValid;
<add> }
<add>
<add> /**
<add> *
<add> * This method...
<add> * @param pcTransaction
<add> * @return
<add> */
<add> protected boolean isTransactionBalanceValid(ProcurementCardTransactionDetail pcTransaction) {
<add> boolean inBalance = true;
<add> KualiDecimal transAmount = pcTransaction.getTransactionTotalAmount();
<add> List<ProcurementCardTargetAccountingLine> targetAcctingLines = pcTransaction.getTargetAccountingLines();
<add>
<add> KualiDecimal targetLineTotal = new KualiDecimal(0.00);
<add>
<add> for(TargetAccountingLine targetLine : targetAcctingLines) {
<add> targetLineTotal = targetLineTotal.add(targetLine.getAmount());
<add> }
<add>
<add> // perform absolute value check because current system has situations where amounts may be opposite in sign
<add> // This will no longer be necessary following completion of KULFDBCK-1290
<add> inBalance = transAmount.abs().equals(targetLineTotal.abs());
<add>
<add> if(!inBalance) {
<add> GlobalVariables.getErrorMap().putError(ACCOUNTING_LINE_ERRORS, ERROR_DOCUMENT_PC_TRANSACTION_TOTAL_ACCTING_LINE_TOTAL_NOT_EQUAL, new String[] {transAmount.toString(), targetLineTotal.toString()});
<add> }
<add>
<add> return inBalance;
<ide> }
<ide>
<ide> /**
|
|
Java
|
apache-2.0
|
14672f0d910f97b18178c5ed5f9c0b0b5bcc9bb8
| 0 |
jamezp/wildfly-arquillian,rhusar/wildfly-arquillian
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2011 Red Hat Inc. and/or its affiliates and other contributors
* as indicated by the @authors tag. All rights reserved.
* See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.as.arquillian.protocol.jmx;
import java.util.concurrent.atomic.AtomicBoolean;
import org.jboss.arquillian.container.spi.Container;
import org.jboss.arquillian.container.spi.client.container.DeployableContainer;
import org.jboss.arquillian.container.spi.context.annotation.ContainerScoped;
import org.jboss.arquillian.container.spi.event.container.BeforeDeploy;
import org.jboss.arquillian.container.spi.event.container.BeforeStop;
import org.jboss.arquillian.core.api.Instance;
import org.jboss.arquillian.core.api.annotation.Inject;
import org.jboss.arquillian.core.api.annotation.Observes;
import org.jboss.arquillian.test.spi.annotation.SuiteScoped;
import org.jboss.as.arquillian.protocol.jmx.JMXProtocolAS7.ServiceArchiveHolder;
import org.jboss.logging.Logger;
import org.jboss.shrinkwrap.api.Archive;
/**
* A deployer for the Arquillian JMXProtocol endpoint.
*
* @see JMXProtocolPackager
*
* @author [email protected]
* @since 31-May-2011
*/
public class ArquillianServiceDeployer {
private static final Logger log = Logger.getLogger(ArquillianServiceDeployer.class);
@Inject
@SuiteScoped
private Instance<ServiceArchiveHolder> archiveHolderInst;
@Inject
@ContainerScoped
private Instance<Container> containerInst;
private AtomicBoolean serviceArchiveDeployed = new AtomicBoolean();
public synchronized void doServiceDeploy(@Observes BeforeDeploy event) {
ServiceArchiveHolder archiveHolder = archiveHolderInst.get();
if (archiveHolder != null && serviceArchiveDeployed.get() == false) {
try {
Archive<?> archive = archiveHolder.getArchive();
log.infof("Deploy arquillian service: %s", archive);
DeployableContainer<?> deployableContainer = containerInst.get().getDeployableContainer();
deployableContainer.deploy(archive);
serviceArchiveDeployed.set(true);
} catch (Throwable th) {
log.error("Cannot deploy arquillian service", th);
}
}
}
public synchronized void undeploy(@Observes BeforeStop event) {
ServiceArchiveHolder archiveHolder = archiveHolderInst.get();
if (archiveHolder != null && serviceArchiveDeployed.get() == true) {
try {
Archive<?> archive = archiveHolder.getArchive();
log.infof("Undeploy arquillian service: %s", archive);
DeployableContainer<?> deployableContainer = containerInst.get().getDeployableContainer();
deployableContainer.undeploy(archive);
serviceArchiveDeployed.set(false);
} catch (Throwable th) {
log.error("Cannot undeploy arquillian service", th);
}
}
}
}
|
protocol-jmx/src/main/java/org/jboss/as/arquillian/protocol/jmx/ArquillianServiceDeployer.java
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2011 Red Hat Inc. and/or its affiliates and other contributors
* as indicated by the @authors tag. All rights reserved.
* See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.as.arquillian.protocol.jmx;
import java.util.concurrent.atomic.AtomicBoolean;
import org.jboss.arquillian.container.spi.Container;
import org.jboss.arquillian.container.spi.client.container.DeployableContainer;
import org.jboss.arquillian.container.spi.context.annotation.ContainerScoped;
import org.jboss.arquillian.container.spi.event.container.BeforeDeploy;
import org.jboss.arquillian.container.spi.event.container.BeforeStop;
import org.jboss.arquillian.core.api.Instance;
import org.jboss.arquillian.core.api.annotation.Inject;
import org.jboss.arquillian.core.api.annotation.Observes;
import org.jboss.arquillian.test.spi.annotation.SuiteScoped;
import org.jboss.as.arquillian.protocol.jmx.JMXProtocolAS7.ServiceArchiveHolder;
import org.jboss.logging.Logger;
/**
* A deployer for the Arquillian JMXProtocol endpoint.
*
* @see JMXProtocolPackager
*
* @author [email protected]
* @since 31-May-2011
*/
public class ArquillianServiceDeployer {
private static final Logger log = Logger.getLogger(ArquillianServiceDeployer.class);
@Inject
@SuiteScoped
private Instance<ServiceArchiveHolder> archiveHolderInst;
@Inject
@ContainerScoped
private Instance<Container> containerInst;
private AtomicBoolean serviceArchiveDeployed = new AtomicBoolean();
public void doServiceDeploy(@Observes BeforeDeploy event) {
ServiceArchiveHolder archiveHolder = archiveHolderInst.get();
if (archiveHolder != null && !serviceArchiveDeployed.get()) {
try {
DeployableContainer<?> deployableContainer = containerInst.get().getDeployableContainer();
deployableContainer.deploy(archiveHolder.getArchive());
serviceArchiveDeployed.set(true);
} catch (Throwable th) {
log.error("Cannot deploy arquillian service", th);
}
}
}
public void undeploy(@Observes BeforeStop event) {
if (serviceArchiveDeployed.get()) {
try {
DeployableContainer<?> deployableContainer = containerInst.get().getDeployableContainer();
ServiceArchiveHolder archiveHolder = archiveHolderInst.get();
deployableContainer.undeploy(archiveHolder.getArchive());
serviceArchiveDeployed.set(false);
} catch (Throwable th) {
log.error("Cannot undeploy arquillian service", th);
}
}
}
}
|
Synchronize arquillian-service deployment/undeployment
|
protocol-jmx/src/main/java/org/jboss/as/arquillian/protocol/jmx/ArquillianServiceDeployer.java
|
Synchronize arquillian-service deployment/undeployment
|
<ide><path>rotocol-jmx/src/main/java/org/jboss/as/arquillian/protocol/jmx/ArquillianServiceDeployer.java
<ide> import org.jboss.arquillian.test.spi.annotation.SuiteScoped;
<ide> import org.jboss.as.arquillian.protocol.jmx.JMXProtocolAS7.ServiceArchiveHolder;
<ide> import org.jboss.logging.Logger;
<add>import org.jboss.shrinkwrap.api.Archive;
<ide>
<ide> /**
<ide> * A deployer for the Arquillian JMXProtocol endpoint.
<ide>
<ide> private AtomicBoolean serviceArchiveDeployed = new AtomicBoolean();
<ide>
<del> public void doServiceDeploy(@Observes BeforeDeploy event) {
<add> public synchronized void doServiceDeploy(@Observes BeforeDeploy event) {
<ide> ServiceArchiveHolder archiveHolder = archiveHolderInst.get();
<del> if (archiveHolder != null && !serviceArchiveDeployed.get()) {
<add> if (archiveHolder != null && serviceArchiveDeployed.get() == false) {
<ide> try {
<add> Archive<?> archive = archiveHolder.getArchive();
<add> log.infof("Deploy arquillian service: %s", archive);
<ide> DeployableContainer<?> deployableContainer = containerInst.get().getDeployableContainer();
<del> deployableContainer.deploy(archiveHolder.getArchive());
<add> deployableContainer.deploy(archive);
<ide> serviceArchiveDeployed.set(true);
<ide> } catch (Throwable th) {
<ide> log.error("Cannot deploy arquillian service", th);
<ide> }
<ide> }
<ide>
<del> public void undeploy(@Observes BeforeStop event) {
<del> if (serviceArchiveDeployed.get()) {
<add> public synchronized void undeploy(@Observes BeforeStop event) {
<add> ServiceArchiveHolder archiveHolder = archiveHolderInst.get();
<add> if (archiveHolder != null && serviceArchiveDeployed.get() == true) {
<ide> try {
<add> Archive<?> archive = archiveHolder.getArchive();
<add> log.infof("Undeploy arquillian service: %s", archive);
<ide> DeployableContainer<?> deployableContainer = containerInst.get().getDeployableContainer();
<del> ServiceArchiveHolder archiveHolder = archiveHolderInst.get();
<del> deployableContainer.undeploy(archiveHolder.getArchive());
<add> deployableContainer.undeploy(archive);
<ide> serviceArchiveDeployed.set(false);
<ide> } catch (Throwable th) {
<ide> log.error("Cannot undeploy arquillian service", th);
|
|
Java
|
apache-2.0
|
c57fa3adb1d488f15069c36ef6721f04c0c0b3f7
| 0 |
lstNull/MaterialDrawer,yongjiliu/MaterialDrawer,Ornolfr/MaterialDrawer,rodnois/MaterialDrawer,mikepenz/MaterialDrawer,hejunbinlan/MaterialDrawer,jiguoling/MaterialDrawer,EnterPrayz/MaterialDrawer,hongnguyenpro/MaterialDrawer,mychaelgo/MaterialDrawer,mikepenz/MaterialDrawer,sandeepnegi/MaterialDrawer,rameshvoltella/MaterialDrawer,irfankhoirul/MaterialDrawer,chenanze/MaterialDrawer,StNekroman/MaterialDrawer,hanhailong/MaterialDrawer,lyxwll/MaterialDrawer,MaTriXy/MaterialDrawer,codenameupik/MaterialDrawer,focus-forked-open-source-license/MaterialDrawer,s8871404/MaterialDrawer,chaoyang805/MaterialDrawer,DrNadson/MaterialDrawer,guffyWave/MaterialDrawer,yunarta/MaterialDrawer,fairyzoro/MaterialDrawer,mmazzarolo/MaterialDrawer,Rowandjj/MaterialDrawer,JohnTsaiAndroid/MaterialDrawer,generalzou/MaterialDrawer,rabyunghwa/MaterialDrawer,yunarta/MaterialDrawer,Papuh/MaterialDrawer,amithub/Material-Drawer-Sample,mikepenz/MaterialDrawer,maitho/MaterialDrawer,idrisfab/MaterialDrawer,nousmotards/MaterialDrawer,webmasteraxe/MaterialDrawer,Ryan---Yang/MaterialDrawer,rayzone107/MaterialDrawer,maxi182/MaterialDrawer,Kondasamy/MaterialDrawer,chteuchteu/MaterialDrawer,Bloody-Badboy/MaterialDrawer,heriproj/MaterialDrawer,democedes/MaterialDrawer,WeRockStar/MaterialDrawer,flystaros/MaterialDrawer,McUsaVsUrss/MaterialDrawer,fxyzj/MaterialDrawer,MaTriXy/MaterialDrawer,honeyflyfish/MaterialDrawer,jgabrielfreitas/MaterialDrawer,liqk2014/MaterialDrawer,FWest98/MaterialDrawer,jaohoang/MaterialDrawer,riezkykenzie/MaterialDrawer
|
package com.mikepenz.materialdrawer;
import android.app.Activity;
import android.content.Context;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.ColorInt;
import android.support.annotation.ColorRes;
import android.support.annotation.DimenRes;
import android.support.annotation.DrawableRes;
import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import com.mikepenz.iconics.IconicsDrawable;
import com.mikepenz.materialdrawer.holder.ImageHolder;
import com.mikepenz.materialdrawer.holder.StringHolder;
import com.mikepenz.materialdrawer.icons.MaterialDrawerFont;
import com.mikepenz.materialdrawer.model.interfaces.IDrawerItem;
import com.mikepenz.materialdrawer.model.interfaces.IProfile;
import com.mikepenz.materialdrawer.util.DrawerImageLoader;
import com.mikepenz.materialdrawer.util.DrawerUIUtils;
import com.mikepenz.materialdrawer.view.BezelImageView;
import com.mikepenz.materialize.util.UIUtils;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Stack;
/**
* Created by mikepenz on 23.05.15.
*/
public class AccountHeaderBuilder {
// global references to views we need later
protected View mAccountHeader;
protected ImageView mAccountHeaderBackground;
protected BezelImageView mCurrentProfileView;
protected View mAccountHeaderTextSection;
protected ImageView mAccountSwitcherArrow;
protected TextView mCurrentProfileName;
protected TextView mCurrentProfileEmail;
protected BezelImageView mProfileFirstView;
protected BezelImageView mProfileSecondView;
protected BezelImageView mProfileThirdView;
// global references to the profiles
protected IProfile mCurrentProfile;
protected IProfile mProfileFirst;
protected IProfile mProfileSecond;
protected IProfile mProfileThird;
// global stuff
protected boolean mSelectionListShown = false;
protected int mAccountHeaderTextSectionBackgroundResource = -1;
// the activity to use
protected Activity mActivity;
/**
* Pass the activity you use the drawer in ;)
*
* @param activity
* @return
*/
public AccountHeaderBuilder withActivity(@NonNull Activity activity) {
this.mActivity = activity;
return this;
}
// defines if we use the compactStyle
protected boolean mCompactStyle = false;
/**
* Defines if we should use the compact style for the header.
*
* @param compactStyle
* @return
*/
public AccountHeaderBuilder withCompactStyle(boolean compactStyle) {
this.mCompactStyle = compactStyle;
return this;
}
// the typeface used for textViews within the AccountHeader
protected Typeface mTypeface;
// the typeface used for name textView only. overrides mTypeface
protected Typeface mNameTypeface;
// the typeface used for email textView only. overrides mTypeface
protected Typeface mEmailTypeface;
/**
* Define the typeface which will be used for all textViews in the AccountHeader
*
* @param typeface
* @return
*/
public AccountHeaderBuilder withTypeface(@NonNull Typeface typeface) {
this.mTypeface = typeface;
return this;
}
/**
* Define the typeface which will be used for name textView in the AccountHeader.
* Overrides typeface supplied to {@link AccountHeaderBuilder#withTypeface(android.graphics.Typeface)}
*
* @param typeface
* @return
* @see #withTypeface(android.graphics.Typeface)
*/
public AccountHeaderBuilder withNameTypeface(@NonNull Typeface typeface) {
this.mNameTypeface = typeface;
return this;
}
/**
* Define the typeface which will be used for email textView in the AccountHeader.
* Overrides typeface supplied to {@link AccountHeaderBuilder#withTypeface(android.graphics.Typeface)}
*
* @param typeface
* @return
* @see #withTypeface(android.graphics.Typeface)
*/
public AccountHeaderBuilder withEmailTypeface(@NonNull Typeface typeface) {
this.mEmailTypeface = typeface;
return this;
}
// set the account header height
protected int mHeightPx = -1;
protected int mHeightDp = -1;
protected int mHeightRes = -1;
/**
* set the height for the header
*
* @param heightPx
* @return
*/
public AccountHeaderBuilder withHeightPx(int heightPx) {
this.mHeightPx = heightPx;
return this;
}
/**
* set the height for the header
*
* @param heightDp
* @return
*/
public AccountHeaderBuilder withHeightDp(int heightDp) {
this.mHeightDp = heightDp;
return this;
}
/**
* set the height for the header by resource
*
* @param heightRes
* @return
*/
public AccountHeaderBuilder withHeightRes(@DimenRes int heightRes) {
this.mHeightRes = heightRes;
return this;
}
//the background color for the slider
protected int mTextColor = 0;
protected int mTextColorRes = -1;
/**
* set the background for the slider as color
*
* @param textColor
* @return
*/
public AccountHeaderBuilder withTextColor(@ColorInt int textColor) {
this.mTextColor = textColor;
return this;
}
/**
* set the background for the slider as resource
*
* @param textColorRes
* @return
*/
public AccountHeaderBuilder withTextColorRes(@ColorRes int textColorRes) {
this.mTextColorRes = textColorRes;
return this;
}
//the current selected profile is visible in the list
protected boolean mCurrentHiddenInList = false;
/**
* hide the current selected profile from the list
*
* @param currentProfileHiddenInList
* @return
*/
public AccountHeaderBuilder withCurrentProfileHiddenInList(boolean currentProfileHiddenInList) {
mCurrentHiddenInList = currentProfileHiddenInList;
return this;
}
//set to hide the first or second line
protected boolean mSelectionFirstLineShown = true;
protected boolean mSelectionSecondLineShown = true;
/**
* set this to false if you want to hide the first line of the selection box in the header (first line would be the name)
*
* @param selectionFirstLineShown
* @return
* @deprecated replaced by {@link #withSelectionFirstLineShown}
*/
@Deprecated
public AccountHeaderBuilder withSelectionFistLineShown(boolean selectionFirstLineShown) {
this.mSelectionFirstLineShown = selectionFirstLineShown;
return this;
}
/**
* set this to false if you want to hide the first line of the selection box in the header (first line would be the name)
*
* @param selectionFirstLineShown
* @return
*/
public AccountHeaderBuilder withSelectionFirstLineShown(boolean selectionFirstLineShown) {
this.mSelectionFirstLineShown = selectionFirstLineShown;
return this;
}
/**
* set this to false if you want to hide the second line of the selection box in the header (second line would be the e-mail)
*
* @param selectionSecondLineShown
* @return
*/
public AccountHeaderBuilder withSelectionSecondLineShown(boolean selectionSecondLineShown) {
this.mSelectionSecondLineShown = selectionSecondLineShown;
return this;
}
//set one of these to define the text in the first or second line with in the account selector
protected String mSelectionFirstLine;
protected String mSelectionSecondLine;
/**
* set this to define the first line in the selection area if there is no profile
* note this will block any values from profiles!
*
* @param selectionFirstLine
* @return
*/
public AccountHeaderBuilder withSelectionFirstLine(String selectionFirstLine) {
this.mSelectionFirstLine = selectionFirstLine;
return this;
}
/**
* set this to define the second line in the selection area if there is no profile
* note this will block any values from profiles!
*
* @param selectionSecondLine
* @return
*/
public AccountHeaderBuilder withSelectionSecondLine(String selectionSecondLine) {
this.mSelectionSecondLine = selectionSecondLine;
return this;
}
// set non translucent statusBar mode
protected boolean mTranslucentStatusBar = true;
/**
* Set or disable this if you use a translucent statusbar
*
* @param translucentStatusBar
* @return
*/
public AccountHeaderBuilder withTranslucentStatusBar(boolean translucentStatusBar) {
this.mTranslucentStatusBar = translucentStatusBar;
return this;
}
//the background for the header
protected Drawable mHeaderBackground = null;
protected int mHeaderBackgroundRes = -1;
/**
* set the background for the slider as color
*
* @param headerBackground
* @return
*/
public AccountHeaderBuilder withHeaderBackground(Drawable headerBackground) {
this.mHeaderBackground = headerBackground;
return this;
}
/**
* set the background for the header as resource
*
* @param headerBackgroundRes
* @return
*/
public AccountHeaderBuilder withHeaderBackground(@DrawableRes int headerBackgroundRes) {
this.mHeaderBackgroundRes = headerBackgroundRes;
return this;
}
//background scale type
protected ImageView.ScaleType mHeaderBackgroundScaleType = null;
/**
* define the ScaleType for the header background
*
* @param headerBackgroundScaleType
* @return
*/
public AccountHeaderBuilder withHeaderBackgroundScaleType(ImageView.ScaleType headerBackgroundScaleType) {
this.mHeaderBackgroundScaleType = headerBackgroundScaleType;
return this;
}
//profile images in the header are shown or not
protected boolean mProfileImagesVisible = true;
/**
* define if the profile images in the header are shown or not
*
* @param profileImagesVisible
* @return
*/
public AccountHeaderBuilder withProfileImagesVisible(boolean profileImagesVisible) {
this.mProfileImagesVisible = profileImagesVisible;
return this;
}
//close the drawer after a profile was clicked in the list
protected boolean mCloseDrawerOnProfileListClick = true;
/**
* define if the drawer should close if the user clicks on a profile item if the selection list is shown
*
* @param closeDrawerOnProfileListClick
* @return
*/
public AccountHeaderBuilder withCloseDrawerOnProfileListClick(boolean closeDrawerOnProfileListClick) {
this.mCloseDrawerOnProfileListClick = closeDrawerOnProfileListClick;
return this;
}
//reset the drawer list to the main drawer list after the profile was clicked in the list
protected boolean mResetDrawerOnProfileListClick = true;
/**
* define if the drawer selection list should be reseted after the user clicks on a profile item if the selection list is shown
*
* @param resetDrawerOnProfileListClick
* @return
*/
public AccountHeaderBuilder withResetDrawerOnProfileListClick(boolean resetDrawerOnProfileListClick) {
this.mResetDrawerOnProfileListClick = resetDrawerOnProfileListClick;
return this;
}
// set the profile images clickable or not
protected boolean mProfileImagesClickable = true;
/**
* enable or disable the profile images to be clickable
*
* @param profileImagesClickable
* @return
*/
public AccountHeaderBuilder withProfileImagesClickable(boolean profileImagesClickable) {
this.mProfileImagesClickable = profileImagesClickable;
return this;
}
// set to use the alternative profile header switching
protected boolean mAlternativeProfileHeaderSwitching = false;
/**
* enable the alternative profile header switching
*
* @param alternativeProfileHeaderSwitching
* @return
*/
public AccountHeaderBuilder withAlternativeProfileHeaderSwitching(boolean alternativeProfileHeaderSwitching) {
this.mAlternativeProfileHeaderSwitching = alternativeProfileHeaderSwitching;
return this;
}
// enable 3 small header previews
protected boolean mThreeSmallProfileImages = false;
/**
* enable the extended profile icon view with 3 small header images instead of two
*
* @param threeSmallProfileImages
* @return
*/
public AccountHeaderBuilder withThreeSmallProfileImages(boolean threeSmallProfileImages) {
this.mThreeSmallProfileImages = threeSmallProfileImages;
return this;
}
// the onAccountHeaderSelectionListener to set
protected AccountHeader.OnAccountHeaderSelectionViewClickListener mOnAccountHeaderSelectionViewClickListener;
/**
* set a onSelection listener for the selection box
*
* @param onAccountHeaderSelectionViewClickListener
* @return
*/
public AccountHeaderBuilder withOnAccountHeaderSelectionViewClickListener(AccountHeader.OnAccountHeaderSelectionViewClickListener onAccountHeaderSelectionViewClickListener) {
this.mOnAccountHeaderSelectionViewClickListener = onAccountHeaderSelectionViewClickListener;
return this;
}
//set the selection list enabled if there is only a single profile
protected boolean mSelectionListEnabledForSingleProfile = true;
/**
* enable or disable the selection list if there is only a single profile
*
* @param selectionListEnabledForSingleProfile
* @return
*/
public AccountHeaderBuilder withSelectionListEnabledForSingleProfile(boolean selectionListEnabledForSingleProfile) {
this.mSelectionListEnabledForSingleProfile = selectionListEnabledForSingleProfile;
return this;
}
//set the selection enabled disabled
protected boolean mSelectionListEnabled = true;
/**
* enable or disable the selection list
*
* @param selectionListEnabled
* @return
*/
public AccountHeaderBuilder withSelectionListEnabled(boolean selectionListEnabled) {
this.mSelectionListEnabled = selectionListEnabled;
return this;
}
// the drawerLayout to use
protected View mAccountHeaderContainer;
/**
* You can pass a custom view for the drawer lib. note this requires the same structure as the drawer.xml
*
* @param accountHeader
* @return
*/
public AccountHeaderBuilder withAccountHeader(@NonNull View accountHeader) {
this.mAccountHeaderContainer = accountHeader;
return this;
}
/**
* You can pass a custom layout for the drawer lib. see the drawer.xml in layouts of this lib on GitHub
*
* @param resLayout
* @return
*/
public AccountHeaderBuilder withAccountHeader(@LayoutRes int resLayout) {
if (mActivity == null) {
throw new RuntimeException("please pass an activity first to use this call");
}
if (resLayout != -1) {
this.mAccountHeaderContainer = mActivity.getLayoutInflater().inflate(resLayout, null, false);
} else {
if (mCompactStyle) {
this.mAccountHeaderContainer = mActivity.getLayoutInflater().inflate(R.layout.material_drawer_compact_header, null, false);
} else {
this.mAccountHeaderContainer = mActivity.getLayoutInflater().inflate(R.layout.material_drawer_header, null, false);
}
}
return this;
}
// the profiles to display
protected ArrayList<IProfile> mProfiles;
/**
* set the arrayList of DrawerItems for the drawer
*
* @param profiles
* @return
*/
public AccountHeaderBuilder withProfiles(@NonNull ArrayList<IProfile> profiles) {
this.mProfiles = profiles;
return this;
}
/**
* add single ore more DrawerItems to the Drawer
*
* @param profiles
* @return
*/
public AccountHeaderBuilder addProfiles(@NonNull IProfile... profiles) {
if (this.mProfiles == null) {
this.mProfiles = new ArrayList<>();
}
if (profiles != null) {
Collections.addAll(this.mProfiles, profiles);
}
return this;
}
// the click listener to be fired on profile or selection click
protected AccountHeader.OnAccountHeaderListener mOnAccountHeaderListener;
/**
* add a listener for the accountHeader
*
* @param onAccountHeaderListener
* @return
*/
public AccountHeaderBuilder withOnAccountHeaderListener(@NonNull AccountHeader.OnAccountHeaderListener onAccountHeaderListener) {
this.mOnAccountHeaderListener = onAccountHeaderListener;
return this;
}
// the drawer to set the AccountSwitcher for
protected Drawer mDrawer;
/**
* @param drawer
* @return
*/
public AccountHeaderBuilder withDrawer(@NonNull Drawer drawer) {
this.mDrawer = drawer;
return this;
}
// savedInstance to restore state
protected Bundle mSavedInstance;
/**
* create the drawer with the values of a savedInstance
*
* @param savedInstance
* @return
*/
public AccountHeaderBuilder withSavedInstance(Bundle savedInstance) {
this.mSavedInstance = savedInstance;
return this;
}
/**
* helper method to set the height for the header!
*
* @param height
*/
private void setHeaderHeight(int height) {
if (mAccountHeaderContainer != null) {
ViewGroup.LayoutParams params = mAccountHeaderContainer.getLayoutParams();
if (params != null) {
params.height = height;
mAccountHeaderContainer.setLayoutParams(params);
}
View accountHeader = mAccountHeaderContainer.findViewById(R.id.account_header_drawer);
if (accountHeader != null) {
params = accountHeader.getLayoutParams();
params.height = height;
accountHeader.setLayoutParams(params);
}
View accountHeaderBackground = mAccountHeaderContainer.findViewById(R.id.account_header_drawer_background);
if (accountHeaderBackground != null) {
params = accountHeaderBackground.getLayoutParams();
params.height = height;
accountHeaderBackground.setLayoutParams(params);
}
}
}
/**
* a small helper to handle the selectionView
*
* @param on
*/
private void handleSelectionView(IProfile profile, boolean on) {
if (on) {
if (Build.VERSION.SDK_INT >= 21) {
((FrameLayout) mAccountHeaderContainer).setForeground(UIUtils.getCompatDrawable(mAccountHeaderContainer.getContext(), mAccountHeaderTextSectionBackgroundResource));
mAccountHeaderContainer.setOnClickListener(onSelectionClickListener);
mAccountHeaderContainer.setTag(R.id.md_profile_header, profile);
} else {
mAccountHeaderTextSection.setBackgroundResource(mAccountHeaderTextSectionBackgroundResource);
mAccountHeaderTextSection.setOnClickListener(onSelectionClickListener);
mAccountHeaderTextSection.setTag(R.id.md_profile_header, profile);
}
} else {
if (Build.VERSION.SDK_INT >= 21) {
((FrameLayout) mAccountHeaderContainer).setForeground(null);
mAccountHeaderContainer.setOnClickListener(null);
} else {
UIUtils.setBackground(mAccountHeaderTextSection, null);
mAccountHeaderTextSection.setOnClickListener(null);
}
}
}
/**
* method to build the header view
*
* @return
*/
public AccountHeader build() {
// if the user has not set a accountHeader use the default one :D
if (mAccountHeaderContainer == null) {
withAccountHeader(-1);
}
// get the header view within the container
mAccountHeader = mAccountHeaderContainer.findViewById(R.id.account_header_drawer);
// handle the height for the header
int height = -1;
if (mHeightPx != -1) {
height = mHeightPx;
} else if (mHeightDp != -1) {
height = (int) UIUtils.convertDpToPixel(mHeightDp, mActivity);
} else if (mHeightRes != -1) {
height = mActivity.getResources().getDimensionPixelSize(mHeightRes);
} else {
if (mCompactStyle) {
height = mActivity.getResources().getDimensionPixelSize(R.dimen.material_drawer_account_header_height_compact);
} else {
//calculate the header height by getting the optimal drawer width and calculating it * 9 / 16
height = (int) (DrawerUIUtils.getOptimalDrawerWidth(mActivity) * AccountHeader.NAVIGATION_DRAWER_ACCOUNT_ASPECT_RATIO);
//if we are lower than api 19 (>= 19 we have a translucentStatusBar) the height should be a bit lower
//probably even if we are non translucent on > 19 devices?
if (Build.VERSION.SDK_INT < 19) {
int tempHeight = height - UIUtils.getStatusBarHeight(mActivity, true);
if (UIUtils.convertPixelsToDp(tempHeight, mActivity) > 140) {
height = tempHeight;
}
}
}
}
// handle everything if we don't have a translucent status bar
if (mTranslucentStatusBar) {
mAccountHeader.setPadding(mAccountHeader.getPaddingLeft(), mAccountHeader.getPaddingTop() + UIUtils.getStatusBarHeight(mActivity), mAccountHeader.getPaddingRight(), mAccountHeader.getPaddingBottom());
//in fact it makes no difference if we have a translucent statusBar or not. we want 9/16 just if we are not compact
if (mCompactStyle) {
height = height + UIUtils.getStatusBarHeight(mActivity);
}
}
//set the height for the header
setHeaderHeight(height);
// get the background view
mAccountHeaderBackground = (ImageView) mAccountHeaderContainer.findViewById(R.id.account_header_drawer_background);
// set the background
if (mHeaderBackground != null) {
mAccountHeaderBackground.setImageDrawable(mHeaderBackground);
} else if (mHeaderBackgroundRes != -1) {
mAccountHeaderBackground.setImageResource(mHeaderBackgroundRes);
}
if (mHeaderBackgroundScaleType != null) {
mAccountHeaderBackground.setScaleType(mHeaderBackgroundScaleType);
}
// get the text color to use for the text section
if (mTextColor == 0 && mTextColorRes != -1) {
mTextColor = mActivity.getResources().getColor(mTextColorRes);
} else if (mTextColor == 0) {
mTextColor = UIUtils.getThemeColorFromAttrOrRes(mActivity, R.attr.material_drawer_header_selection_text, R.color.material_drawer_header_selection_text);
}
// set the background for the section
if (mCompactStyle) {
mAccountHeaderTextSection = mAccountHeader;
} else {
mAccountHeaderTextSection = mAccountHeaderContainer.findViewById(R.id.account_header_drawer_text_section);
}
mAccountHeaderTextSectionBackgroundResource = DrawerUIUtils.getSelectableBackground(mActivity);
handleSelectionView(mCurrentProfile, true);
// set the arrow :D
mAccountSwitcherArrow = (ImageView) mAccountHeaderContainer.findViewById(R.id.account_header_drawer_text_switcher);
mAccountSwitcherArrow.setImageDrawable(new IconicsDrawable(mActivity, MaterialDrawerFont.Icon.mdf_arrow_drop_down).sizeDp(24).paddingDp(6).color(mTextColor));
//get the fields for the name
mCurrentProfileView = (BezelImageView) mAccountHeader.findViewById(R.id.account_header_drawer_current);
mCurrentProfileName = (TextView) mAccountHeader.findViewById(R.id.account_header_drawer_name);
mCurrentProfileEmail = (TextView) mAccountHeader.findViewById(R.id.account_header_drawer_email);
//set the typeface for the AccountHeader
if (mNameTypeface != null) {
mCurrentProfileName.setTypeface(mNameTypeface);
} else if (mTypeface != null) {
mCurrentProfileName.setTypeface(mTypeface);
}
if (mEmailTypeface != null) {
mCurrentProfileEmail.setTypeface(mEmailTypeface);
} else if (mTypeface != null) {
mCurrentProfileEmail.setTypeface(mTypeface);
}
mCurrentProfileName.setTextColor(mTextColor);
mCurrentProfileEmail.setTextColor(mTextColor);
mProfileFirstView = (BezelImageView) mAccountHeader.findViewById(R.id.account_header_drawer_small_first);
mProfileSecondView = (BezelImageView) mAccountHeader.findViewById(R.id.account_header_drawer_small_second);
mProfileThirdView = (BezelImageView) mAccountHeader.findViewById(R.id.account_header_drawer_small_third);
//calculate the profiles to set
calculateProfiles();
//process and build the profiles
buildProfiles();
// try to restore all saved values again
if (mSavedInstance != null) {
int selection = mSavedInstance.getInt(AccountHeader.BUNDLE_SELECTION_HEADER, -1);
if (selection != -1) {
//predefine selection (should be the first element
if (mProfiles != null && (selection) > -1 && selection < mProfiles.size()) {
switchProfiles(mProfiles.get(selection));
}
}
}
//everything created. now set the header
if (mDrawer != null) {
mDrawer.setHeader(mAccountHeaderContainer);
}
//forget the reference to the activity
mActivity = null;
return new AccountHeader(this);
}
/**
* helper method to calculate the order of the profiles
*/
protected void calculateProfiles() {
if (mProfiles == null) {
mProfiles = new ArrayList<>();
}
if (mCurrentProfile == null) {
int setCount = 0;
for (int i = 0; i < mProfiles.size(); i++) {
if (mProfiles.size() > i && mProfiles.get(i).isSelectable()) {
if (setCount == 0 && (mCurrentProfile == null)) {
mCurrentProfile = mProfiles.get(i);
} else if (setCount == 1 && (mProfileFirst == null)) {
mProfileFirst = mProfiles.get(i);
} else if (setCount == 2 && (mProfileSecond == null)) {
mProfileSecond = mProfiles.get(i);
} else if (setCount == 3 && (mProfileThird == null)) {
mProfileThird = mProfiles.get(i);
}
setCount++;
}
}
return;
}
IProfile[] previousActiveProfiles = new IProfile[]{
mCurrentProfile,
mProfileFirst,
mProfileSecond,
mProfileThird
};
IProfile[] newActiveProfiles = new IProfile[4];
Stack<IProfile> unusedProfiles = new Stack<>();
// try to keep existing active profiles in the same positions
for (int i = 0; i < mProfiles.size(); i++) {
IProfile p = mProfiles.get(i);
if (p.isSelectable()) {
boolean used = false;
for (int j = 0; j < 4; j++) {
if (previousActiveProfiles[j] == p) {
newActiveProfiles[j] = p;
used = true;
break;
}
}
if (!used) {
unusedProfiles.push(p);
}
}
}
Stack<IProfile> activeProfiles = new Stack<>();
// try to fill the gaps with new available profiles
for (int i = 0; i < 4; i++) {
if (newActiveProfiles[i] != null) {
activeProfiles.push(newActiveProfiles[i]);
} else if (!unusedProfiles.isEmpty()) {
activeProfiles.push(unusedProfiles.pop());
}
}
Stack<IProfile> reversedActiveProfiles = new Stack<>();
while (!activeProfiles.empty()) {
reversedActiveProfiles.push(activeProfiles.pop());
}
// reassign active profiles
if (reversedActiveProfiles.isEmpty()) {
mCurrentProfile = null;
} else {
mCurrentProfile = reversedActiveProfiles.pop();
}
if (reversedActiveProfiles.isEmpty()) {
mProfileFirst = null;
} else {
mProfileFirst = reversedActiveProfiles.pop();
}
if (reversedActiveProfiles.isEmpty()) {
mProfileSecond = null;
} else {
mProfileSecond = reversedActiveProfiles.pop();
}
if (reversedActiveProfiles.isEmpty()) {
mProfileThird = null;
} else {
mProfileThird = reversedActiveProfiles.pop();
}
}
/**
* helper method to switch the profiles
*
* @param newSelection
* @return true if the new selection was the current profile
*/
protected boolean switchProfiles(IProfile newSelection) {
if (newSelection == null) {
return false;
}
if (mCurrentProfile == newSelection) {
return true;
}
if (mAlternativeProfileHeaderSwitching) {
int prevSelection = -1;
if (mProfileFirst == newSelection) {
prevSelection = 1;
} else if (mProfileSecond == newSelection) {
prevSelection = 2;
} else if (mProfileThird == newSelection) {
prevSelection = 3;
}
IProfile tmp = mCurrentProfile;
mCurrentProfile = newSelection;
if (prevSelection == 1) {
mProfileFirst = tmp;
} else if (prevSelection == 2) {
mProfileSecond = tmp;
} else if (prevSelection == 3) {
mProfileThird = tmp;
}
} else {
if (mProfiles != null) {
ArrayList<IProfile> previousActiveProfiles = new ArrayList<>(Arrays.asList(mCurrentProfile, mProfileFirst, mProfileSecond, mProfileThird));
if (previousActiveProfiles.contains(newSelection)) {
int position = -1;
for (int i = 0; i < 4; i++) {
if (previousActiveProfiles.get(i) == newSelection) {
position = i;
break;
}
}
if (position != -1) {
previousActiveProfiles.remove(position);
previousActiveProfiles.add(0, newSelection);
mCurrentProfile = previousActiveProfiles.get(0);
mProfileFirst = previousActiveProfiles.get(1);
mProfileSecond = previousActiveProfiles.get(2);
mProfileThird = previousActiveProfiles.get(3);
}
} else {
mProfileThird = mProfileSecond;
mProfileSecond = mProfileFirst;
mProfileFirst = mCurrentProfile;
mCurrentProfile = newSelection;
}
}
}
buildProfiles();
return false;
}
/**
* helper method to build the views for the ui
*/
protected void buildProfiles() {
mCurrentProfileView.setVisibility(View.INVISIBLE);
mAccountHeaderTextSection.setVisibility(View.INVISIBLE);
mAccountSwitcherArrow.setVisibility(View.INVISIBLE);
mProfileFirstView.setVisibility(View.INVISIBLE);
mProfileFirstView.setOnClickListener(null);
mProfileSecondView.setVisibility(View.INVISIBLE);
mProfileSecondView.setOnClickListener(null);
mProfileThirdView.setVisibility(View.GONE);
mProfileThirdView.setOnClickListener(null);
handleSelectionView(mCurrentProfile, true);
if (mCurrentProfile != null) {
if (mProfileImagesVisible) {
setImageOrPlaceholder(mCurrentProfileView, mCurrentProfile.getIcon());
if (mProfileImagesClickable) {
mCurrentProfileView.setOnClickListener(onProfileClickListener);
mCurrentProfileView.disableTouchFeedback(false);
} else {
mCurrentProfileView.disableTouchFeedback(true);
}
mCurrentProfileView.setVisibility(View.VISIBLE);
} else if (mCompactStyle) {
mCurrentProfileView.setVisibility(View.GONE);
}
mAccountHeaderTextSection.setVisibility(View.VISIBLE);
handleSelectionView(mCurrentProfile, true);
mAccountSwitcherArrow.setVisibility(View.VISIBLE);
mCurrentProfileView.setTag(R.id.md_profile_header, mCurrentProfile);
StringHolder.applyTo(mCurrentProfile.getName(), mCurrentProfileName);
StringHolder.applyTo(mCurrentProfile.getEmail(), mCurrentProfileEmail);
if (mProfileFirst != null && mProfileImagesVisible) {
setImageOrPlaceholder(mProfileFirstView, mProfileFirst.getIcon());
mProfileFirstView.setTag(R.id.md_profile_header, mProfileFirst);
if (mProfileImagesClickable) {
mProfileFirstView.setOnClickListener(onProfileClickListener);
mProfileFirstView.disableTouchFeedback(false);
} else {
mProfileFirstView.disableTouchFeedback(true);
}
mProfileFirstView.setVisibility(View.VISIBLE);
}
if (mProfileSecond != null && mProfileImagesVisible) {
setImageOrPlaceholder(mProfileSecondView, mProfileSecond.getIcon());
mProfileSecondView.setTag(R.id.md_profile_header, mProfileSecond);
if (mProfileImagesClickable) {
mProfileSecondView.setOnClickListener(onProfileClickListener);
mProfileSecondView.disableTouchFeedback(false);
} else {
mProfileSecondView.disableTouchFeedback(true);
}
mProfileSecondView.setVisibility(View.VISIBLE);
}
if (mProfileThird != null && mThreeSmallProfileImages && mProfileImagesVisible) {
setImageOrPlaceholder(mProfileThirdView, mProfileThird.getIcon());
mProfileThirdView.setTag(R.id.md_profile_header, mProfileThird);
if (mProfileImagesClickable) {
mProfileThirdView.setOnClickListener(onProfileClickListener);
mProfileThirdView.disableTouchFeedback(false);
} else {
mProfileThirdView.disableTouchFeedback(true);
}
mProfileThirdView.setVisibility(View.VISIBLE);
}
} else if (mProfiles != null && mProfiles.size() > 0) {
IProfile profile = mProfiles.get(0);
mAccountHeaderTextSection.setTag(R.id.md_profile_header, profile);
mAccountHeaderTextSection.setVisibility(View.VISIBLE);
handleSelectionView(mCurrentProfile, true);
mAccountSwitcherArrow.setVisibility(View.VISIBLE);
if (mCurrentProfile != null) {
StringHolder.applyTo(mCurrentProfile.getName(), mCurrentProfileName);
StringHolder.applyTo(mCurrentProfile.getEmail(), mCurrentProfileEmail);
}
}
if (!mSelectionFirstLineShown) {
mCurrentProfileName.setVisibility(View.GONE);
}
if (!TextUtils.isEmpty(mSelectionFirstLine)) {
mCurrentProfileName.setText(mSelectionFirstLine);
mAccountHeaderTextSection.setVisibility(View.VISIBLE);
}
if (!mSelectionSecondLineShown) {
mCurrentProfileEmail.setVisibility(View.GONE);
}
if (!TextUtils.isEmpty(mSelectionSecondLine)) {
mCurrentProfileEmail.setText(mSelectionSecondLine);
mAccountHeaderTextSection.setVisibility(View.VISIBLE);
}
//if we disabled the list
if (!mSelectionListEnabled) {
mAccountSwitcherArrow.setVisibility(View.INVISIBLE);
handleSelectionView(null, false);
}
if (!mSelectionListEnabledForSingleProfile && mProfileFirst == null && (mProfiles == null || mProfiles.size() == 1)) {
mAccountSwitcherArrow.setVisibility(View.INVISIBLE);
handleSelectionView(null, false);
}
//if we disabled the list but still have set a custom listener
if (mOnAccountHeaderSelectionViewClickListener != null) {
handleSelectionView(mCurrentProfile, true);
}
}
/**
* small helper method to set an profile image or a placeholder
*
* @param iv
* @param imageHolder
*/
private void setImageOrPlaceholder(ImageView iv, ImageHolder imageHolder) {
//cancel previous started image loading processes
DrawerImageLoader.getInstance().cancelImage(iv);
//set the placeholder
iv.setImageDrawable(DrawerUIUtils.getPlaceHolder(iv.getContext()));
//set the real image (probably also the uri)
ImageHolder.applyTo(imageHolder, iv);
}
/**
* onProfileClickListener to notify onClick on a profile image
*/
private View.OnClickListener onCurrentProfileClickListener = new View.OnClickListener() {
@Override
public void onClick(final View v) {
onProfileClick(v, true);
}
};
/**
* onProfileClickListener to notify onClick on a profile image
*/
private View.OnClickListener onProfileClickListener = new View.OnClickListener() {
@Override
public void onClick(final View v) {
onProfileClick(v, false);
}
};
protected void onProfileClick(View v, boolean current) {
final IProfile profile = (IProfile) v.getTag(R.id.md_profile_header);
switchProfiles(profile);
//reset the drawer content
resetDrawerContent(v.getContext());
boolean consumed = false;
if (mOnAccountHeaderListener != null) {
consumed = mOnAccountHeaderListener.onProfileChanged(v, profile, current);
}
if (!consumed) {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
if (mDrawer != null) {
mDrawer.closeDrawer();
}
}
}, 200);
}
}
/**
* get the current selection
*
* @return
*/
protected int getCurrentSelection() {
if (mCurrentProfile != null && mProfiles != null) {
int i = 0;
for (IProfile profile : mProfiles) {
if (profile == mCurrentProfile) {
return i;
}
i++;
}
}
return -1;
}
/**
* onSelectionClickListener to notify the onClick on the checkbox
*/
private View.OnClickListener onSelectionClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
boolean consumed = false;
if (mOnAccountHeaderSelectionViewClickListener != null) {
consumed = mOnAccountHeaderSelectionViewClickListener.onClick(v, (IProfile) v.getTag(R.id.md_profile_header));
}
if (mAccountSwitcherArrow.getVisibility() == View.VISIBLE && !consumed) {
toggleSelectionList(v.getContext());
}
}
};
/**
* helper method to toggle the collection
*
* @param ctx
*/
protected void toggleSelectionList(Context ctx) {
if (mDrawer != null) {
//if we already show the list. reset everything instead
if (mDrawer.switchedDrawerContent()) {
resetDrawerContent(ctx);
mSelectionListShown = false;
} else {
//build and set the drawer selection list
buildDrawerSelectionList();
// update the arrow image within the drawer
mAccountSwitcherArrow.setImageDrawable(new IconicsDrawable(ctx, MaterialDrawerFont.Icon.mdf_arrow_drop_up).sizeDp(24).paddingDp(6).color(mTextColor));
mSelectionListShown = true;
}
}
}
/**
* helper method to build and set the drawer selection list
*/
protected void buildDrawerSelectionList() {
int selectedPosition = -1;
int position = 0;
ArrayList<IDrawerItem> profileDrawerItems = new ArrayList<>();
if (mProfiles != null) {
for (IProfile profile : mProfiles) {
if (profile == mCurrentProfile) {
if (mCurrentHiddenInList) {
continue;
} else {
selectedPosition = position + mDrawer.getAdapter().getHeaderOffset();
}
}
if (profile instanceof IDrawerItem) {
((IDrawerItem) profile).withSetSelected(false);
profileDrawerItems.add((IDrawerItem) profile);
}
position = position + 1;
}
}
mDrawer.switchDrawerContent(onDrawerItemClickListener, profileDrawerItems, selectedPosition);
}
/**
* onDrawerItemClickListener to catch the selection for the new profile!
*/
private Drawer.OnDrawerItemClickListener onDrawerItemClickListener = new Drawer.OnDrawerItemClickListener() {
@Override
public boolean onItemClick(final View view, int position, final IDrawerItem drawerItem) {
final boolean isCurrentSelectedProfile;
if (drawerItem != null && drawerItem instanceof IProfile && ((IProfile) drawerItem).isSelectable()) {
isCurrentSelectedProfile = switchProfiles((IProfile) drawerItem);
} else {
isCurrentSelectedProfile = false;
}
if (mResetDrawerOnProfileListClick) {
mDrawer.setOnDrawerItemClickListener(null);
}
//wrap the onSelection call and the reset stuff within a handler to prevent lag
if (mResetDrawerOnProfileListClick && mDrawer != null && view != null && view.getContext() != null) {
resetDrawerContent(view.getContext());
}
if (drawerItem != null && drawerItem instanceof IProfile) {
if (mOnAccountHeaderListener != null) {
mOnAccountHeaderListener.onProfileChanged(view, (IProfile) drawerItem, isCurrentSelectedProfile);
}
}
return !mCloseDrawerOnProfileListClick;
}
};
/**
* helper method to reset the drawer content
*/
private void resetDrawerContent(Context ctx) {
if (mDrawer != null) {
mDrawer.resetDrawerContent();
}
mAccountSwitcherArrow.setImageDrawable(new IconicsDrawable(ctx, MaterialDrawerFont.Icon.mdf_arrow_drop_down).sizeDp(24).paddingDp(6).color(mTextColor));
}
/**
* small helper class to update the header and the list
*/
protected void updateHeaderAndList() {
//recalculate the profiles
calculateProfiles();
//update the profiles in the header
buildProfiles();
//if we currently show the list add the new item directly to it
if (mSelectionListShown) {
buildDrawerSelectionList();
}
}
}
|
library/src/main/java/com/mikepenz/materialdrawer/AccountHeaderBuilder.java
|
package com.mikepenz.materialdrawer;
import android.app.Activity;
import android.content.Context;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.ColorInt;
import android.support.annotation.ColorRes;
import android.support.annotation.DimenRes;
import android.support.annotation.DrawableRes;
import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import com.mikepenz.iconics.IconicsDrawable;
import com.mikepenz.materialdrawer.holder.ImageHolder;
import com.mikepenz.materialdrawer.holder.StringHolder;
import com.mikepenz.materialdrawer.icons.MaterialDrawerFont;
import com.mikepenz.materialdrawer.model.interfaces.IDrawerItem;
import com.mikepenz.materialdrawer.model.interfaces.IProfile;
import com.mikepenz.materialdrawer.util.DrawerImageLoader;
import com.mikepenz.materialdrawer.util.DrawerUIUtils;
import com.mikepenz.materialdrawer.view.BezelImageView;
import com.mikepenz.materialize.util.UIUtils;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Stack;
/**
* Created by mikepenz on 23.05.15.
*/
public class AccountHeaderBuilder {
// global references to views we need later
protected View mAccountHeader;
protected ImageView mAccountHeaderBackground;
protected BezelImageView mCurrentProfileView;
protected View mAccountHeaderTextSection;
protected ImageView mAccountSwitcherArrow;
protected TextView mCurrentProfileName;
protected TextView mCurrentProfileEmail;
protected BezelImageView mProfileFirstView;
protected BezelImageView mProfileSecondView;
protected BezelImageView mProfileThirdView;
// global references to the profiles
protected IProfile mCurrentProfile;
protected IProfile mProfileFirst;
protected IProfile mProfileSecond;
protected IProfile mProfileThird;
// global stuff
protected boolean mSelectionListShown = false;
protected int mAccountHeaderTextSectionBackgroundResource = -1;
// the activity to use
protected Activity mActivity;
/**
* Pass the activity you use the drawer in ;)
*
* @param activity
* @return
*/
public AccountHeaderBuilder withActivity(@NonNull Activity activity) {
this.mActivity = activity;
return this;
}
// defines if we use the compactStyle
protected boolean mCompactStyle = false;
/**
* Defines if we should use the compact style for the header.
*
* @param compactStyle
* @return
*/
public AccountHeaderBuilder withCompactStyle(boolean compactStyle) {
this.mCompactStyle = compactStyle;
return this;
}
// the typeface used for textViews within the AccountHeader
protected Typeface mTypeface;
// the typeface used for name textView only. overrides mTypeface
protected Typeface mNameTypeface;
// the typeface used for email textView only. overrides mTypeface
protected Typeface mEmailTypeface;
/**
* Define the typeface which will be used for all textViews in the AccountHeader
*
* @param typeface
* @return
*/
public AccountHeaderBuilder withTypeface(@NonNull Typeface typeface) {
this.mTypeface = typeface;
return this;
}
/**
* Define the typeface which will be used for name textView in the AccountHeader.
* Overrides typeface supplied to {@link AccountHeaderBuilder#withTypeface(android.graphics.Typeface)}
*
* @param typeface
* @return
* @see #withTypeface(android.graphics.Typeface)
*/
public AccountHeaderBuilder withNameTypeface(@NonNull Typeface typeface) {
this.mNameTypeface = typeface;
return this;
}
/**
* Define the typeface which will be used for email textView in the AccountHeader.
* Overrides typeface supplied to {@link AccountHeaderBuilder#withTypeface(android.graphics.Typeface)}
*
* @param typeface
* @return
* @see #withTypeface(android.graphics.Typeface)
*/
public AccountHeaderBuilder withEmailTypeface(@NonNull Typeface typeface) {
this.mEmailTypeface = typeface;
return this;
}
// set the account header height
protected int mHeightPx = -1;
protected int mHeightDp = -1;
protected int mHeightRes = -1;
/**
* set the height for the header
*
* @param heightPx
* @return
*/
public AccountHeaderBuilder withHeightPx(int heightPx) {
this.mHeightPx = heightPx;
return this;
}
/**
* set the height for the header
*
* @param heightDp
* @return
*/
public AccountHeaderBuilder withHeightDp(int heightDp) {
this.mHeightDp = heightDp;
return this;
}
/**
* set the height for the header by resource
*
* @param heightRes
* @return
*/
public AccountHeaderBuilder withHeightRes(@DimenRes int heightRes) {
this.mHeightRes = heightRes;
return this;
}
//the background color for the slider
protected int mTextColor = 0;
protected int mTextColorRes = -1;
/**
* set the background for the slider as color
*
* @param textColor
* @return
*/
public AccountHeaderBuilder withTextColor(@ColorInt int textColor) {
this.mTextColor = textColor;
return this;
}
/**
* set the background for the slider as resource
*
* @param textColorRes
* @return
*/
public AccountHeaderBuilder withTextColorRes(@ColorRes int textColorRes) {
this.mTextColorRes = textColorRes;
return this;
}
//the current selected profile is visible in the list
protected boolean mCurrentHiddenInList = false;
/**
* hide the current selected profile from the list
*
* @param currentProfileHiddenInList
* @return
*/
public AccountHeaderBuilder withCurrentProfileHiddenInList(boolean currentProfileHiddenInList) {
mCurrentHiddenInList = currentProfileHiddenInList;
return this;
}
//set to hide the first or second line
protected boolean mSelectionFirstLineShown = true;
protected boolean mSelectionSecondLineShown = true;
/**
* set this to false if you want to hide the first line of the selection box in the header (first line would be the name)
*
* @param selectionFirstLineShown
* @return
* @deprecated replaced by {@link #withSelectionFirstLineShown}
*/
@Deprecated
public AccountHeaderBuilder withSelectionFistLineShown(boolean selectionFirstLineShown) {
this.mSelectionFirstLineShown = selectionFirstLineShown;
return this;
}
/**
* set this to false if you want to hide the first line of the selection box in the header (first line would be the name)
*
* @param selectionFirstLineShown
* @return
*/
public AccountHeaderBuilder withSelectionFirstLineShown(boolean selectionFirstLineShown) {
this.mSelectionFirstLineShown = selectionFirstLineShown;
return this;
}
/**
* set this to false if you want to hide the second line of the selection box in the header (second line would be the e-mail)
*
* @param selectionSecondLineShown
* @return
*/
public AccountHeaderBuilder withSelectionSecondLineShown(boolean selectionSecondLineShown) {
this.mSelectionSecondLineShown = selectionSecondLineShown;
return this;
}
//set one of these to define the text in the first or second line with in the account selector
protected String mSelectionFirstLine;
protected String mSelectionSecondLine;
/**
* set this to define the first line in the selection area if there is no profile
* note this will block any values from profiles!
*
* @param selectionFirstLine
* @return
*/
public AccountHeaderBuilder withSelectionFirstLine(String selectionFirstLine) {
this.mSelectionFirstLine = selectionFirstLine;
return this;
}
/**
* set this to define the second line in the selection area if there is no profile
* note this will block any values from profiles!
*
* @param selectionSecondLine
* @return
*/
public AccountHeaderBuilder withSelectionSecondLine(String selectionSecondLine) {
this.mSelectionSecondLine = selectionSecondLine;
return this;
}
// set non translucent statusBar mode
protected boolean mTranslucentStatusBar = true;
/**
* Set or disable this if you use a translucent statusbar
*
* @param translucentStatusBar
* @return
*/
public AccountHeaderBuilder withTranslucentStatusBar(boolean translucentStatusBar) {
this.mTranslucentStatusBar = translucentStatusBar;
return this;
}
//the background for the header
protected Drawable mHeaderBackground = null;
protected int mHeaderBackgroundRes = -1;
/**
* set the background for the slider as color
*
* @param headerBackground
* @return
*/
public AccountHeaderBuilder withHeaderBackground(Drawable headerBackground) {
this.mHeaderBackground = headerBackground;
return this;
}
/**
* set the background for the header as resource
*
* @param headerBackgroundRes
* @return
*/
public AccountHeaderBuilder withHeaderBackground(@DrawableRes int headerBackgroundRes) {
this.mHeaderBackgroundRes = headerBackgroundRes;
return this;
}
//background scale type
protected ImageView.ScaleType mHeaderBackgroundScaleType = null;
/**
* define the ScaleType for the header background
*
* @param headerBackgroundScaleType
* @return
*/
public AccountHeaderBuilder withHeaderBackgroundScaleType(ImageView.ScaleType headerBackgroundScaleType) {
this.mHeaderBackgroundScaleType = headerBackgroundScaleType;
return this;
}
//profile images in the header are shown or not
protected boolean mProfileImagesVisible = true;
/**
* define if the profile images in the header are shown or not
*
* @param profileImagesVisible
* @return
*/
public AccountHeaderBuilder withProfileImagesVisible(boolean profileImagesVisible) {
this.mProfileImagesVisible = profileImagesVisible;
return this;
}
//close the drawer after a profile was clicked in the list
protected boolean mCloseDrawerOnProfileListClick = true;
/**
* define if the drawer should close if the user clicks on a profile item if the selection list is shown
*
* @param closeDrawerOnProfileListClick
* @return
*/
public AccountHeaderBuilder withCloseDrawerOnProfileListClick(boolean closeDrawerOnProfileListClick) {
this.mCloseDrawerOnProfileListClick = closeDrawerOnProfileListClick;
return this;
}
//reset the drawer list to the main drawer list after the profile was clicked in the list
protected boolean mResetDrawerOnProfileListClick = true;
/**
* define if the drawer selection list should be reseted after the user clicks on a profile item if the selection list is shown
*
* @param resetDrawerOnProfileListClick
* @return
*/
public AccountHeaderBuilder withResetDrawerOnProfileListClick(boolean resetDrawerOnProfileListClick) {
this.mResetDrawerOnProfileListClick = resetDrawerOnProfileListClick;
return this;
}
// set the profile images clickable or not
protected boolean mProfileImagesClickable = true;
/**
* enable or disable the profile images to be clickable
*
* @param profileImagesClickable
* @return
*/
public AccountHeaderBuilder withProfileImagesClickable(boolean profileImagesClickable) {
this.mProfileImagesClickable = profileImagesClickable;
return this;
}
// set to use the alternative profile header switching
protected boolean mAlternativeProfileHeaderSwitching = false;
/**
* enable the alternative profile header switching
*
* @param alternativeProfileHeaderSwitching
* @return
*/
public AccountHeaderBuilder withAlternativeProfileHeaderSwitching(boolean alternativeProfileHeaderSwitching) {
this.mAlternativeProfileHeaderSwitching = alternativeProfileHeaderSwitching;
return this;
}
// enable 3 small header previews
protected boolean mThreeSmallProfileImages = false;
/**
* enable the extended profile icon view with 3 small header images instead of two
*
* @param threeSmallProfileImages
* @return
*/
public AccountHeaderBuilder withThreeSmallProfileImages(boolean threeSmallProfileImages) {
this.mThreeSmallProfileImages = threeSmallProfileImages;
return this;
}
// the onAccountHeaderSelectionListener to set
protected AccountHeader.OnAccountHeaderSelectionViewClickListener mOnAccountHeaderSelectionViewClickListener;
/**
* set a onSelection listener for the selection box
*
* @param onAccountHeaderSelectionViewClickListener
* @return
*/
public AccountHeaderBuilder withOnAccountHeaderSelectionViewClickListener(AccountHeader.OnAccountHeaderSelectionViewClickListener onAccountHeaderSelectionViewClickListener) {
this.mOnAccountHeaderSelectionViewClickListener = onAccountHeaderSelectionViewClickListener;
return this;
}
//set the selection list enabled if there is only a single profile
protected boolean mSelectionListEnabledForSingleProfile = true;
/**
* enable or disable the selection list if there is only a single profile
*
* @param selectionListEnabledForSingleProfile
* @return
*/
public AccountHeaderBuilder withSelectionListEnabledForSingleProfile(boolean selectionListEnabledForSingleProfile) {
this.mSelectionListEnabledForSingleProfile = selectionListEnabledForSingleProfile;
return this;
}
//set the selection enabled disabled
protected boolean mSelectionListEnabled = true;
/**
* enable or disable the selection list
*
* @param selectionListEnabled
* @return
*/
public AccountHeaderBuilder withSelectionListEnabled(boolean selectionListEnabled) {
this.mSelectionListEnabled = selectionListEnabled;
return this;
}
// the drawerLayout to use
protected View mAccountHeaderContainer;
/**
* You can pass a custom view for the drawer lib. note this requires the same structure as the drawer.xml
*
* @param accountHeader
* @return
*/
public AccountHeaderBuilder withAccountHeader(@NonNull View accountHeader) {
this.mAccountHeaderContainer = accountHeader;
return this;
}
/**
* You can pass a custom layout for the drawer lib. see the drawer.xml in layouts of this lib on GitHub
*
* @param resLayout
* @return
*/
public AccountHeaderBuilder withAccountHeader(@LayoutRes int resLayout) {
if (mActivity == null) {
throw new RuntimeException("please pass an activity first to use this call");
}
if (resLayout != -1) {
this.mAccountHeaderContainer = mActivity.getLayoutInflater().inflate(resLayout, null, false);
} else {
if (mCompactStyle) {
this.mAccountHeaderContainer = mActivity.getLayoutInflater().inflate(R.layout.material_drawer_compact_header, null, false);
} else {
this.mAccountHeaderContainer = mActivity.getLayoutInflater().inflate(R.layout.material_drawer_header, null, false);
}
}
return this;
}
// the profiles to display
protected ArrayList<IProfile> mProfiles;
/**
* set the arrayList of DrawerItems for the drawer
*
* @param profiles
* @return
*/
public AccountHeaderBuilder withProfiles(@NonNull ArrayList<IProfile> profiles) {
this.mProfiles = profiles;
return this;
}
/**
* add single ore more DrawerItems to the Drawer
*
* @param profiles
* @return
*/
public AccountHeaderBuilder addProfiles(@NonNull IProfile... profiles) {
if (this.mProfiles == null) {
this.mProfiles = new ArrayList<>();
}
if (profiles != null) {
Collections.addAll(this.mProfiles, profiles);
}
return this;
}
// the click listener to be fired on profile or selection click
protected AccountHeader.OnAccountHeaderListener mOnAccountHeaderListener;
/**
* add a listener for the accountHeader
*
* @param onAccountHeaderListener
* @return
*/
public AccountHeaderBuilder withOnAccountHeaderListener(@NonNull AccountHeader.OnAccountHeaderListener onAccountHeaderListener) {
this.mOnAccountHeaderListener = onAccountHeaderListener;
return this;
}
// the drawer to set the AccountSwitcher for
protected Drawer mDrawer;
/**
* @param drawer
* @return
*/
public AccountHeaderBuilder withDrawer(@NonNull Drawer drawer) {
this.mDrawer = drawer;
return this;
}
// savedInstance to restore state
protected Bundle mSavedInstance;
/**
* create the drawer with the values of a savedInstance
*
* @param savedInstance
* @return
*/
public AccountHeaderBuilder withSavedInstance(Bundle savedInstance) {
this.mSavedInstance = savedInstance;
return this;
}
/**
* helper method to set the height for the header!
*
* @param height
*/
private void setHeaderHeight(int height) {
if (mAccountHeaderContainer != null) {
ViewGroup.LayoutParams params = mAccountHeaderContainer.getLayoutParams();
if (params != null) {
params.height = height;
mAccountHeaderContainer.setLayoutParams(params);
}
View accountHeader = mAccountHeaderContainer.findViewById(R.id.account_header_drawer);
if (accountHeader != null) {
params = accountHeader.getLayoutParams();
params.height = height;
accountHeader.setLayoutParams(params);
}
View accountHeaderBackground = mAccountHeaderContainer.findViewById(R.id.account_header_drawer_background);
if (accountHeaderBackground != null) {
params = accountHeaderBackground.getLayoutParams();
params.height = height;
accountHeaderBackground.setLayoutParams(params);
}
}
}
/**
* a small helper to handle the selectionView
*
* @param on
*/
private void handleSelectionView(IProfile profile, boolean on) {
if (on) {
if (Build.VERSION.SDK_INT >= 21) {
((FrameLayout) mAccountHeaderContainer).setForeground(UIUtils.getCompatDrawable(mAccountHeaderContainer.getContext(), mAccountHeaderTextSectionBackgroundResource));
mAccountHeaderContainer.setOnClickListener(onSelectionClickListener);
mAccountHeaderContainer.setTag(R.id.md_profile_header, profile);
} else {
mAccountHeaderTextSection.setBackgroundResource(mAccountHeaderTextSectionBackgroundResource);
mAccountHeaderTextSection.setOnClickListener(onSelectionClickListener);
mAccountHeaderTextSection.setTag(R.id.md_profile_header, profile);
}
} else {
if (Build.VERSION.SDK_INT >= 21) {
((FrameLayout) mAccountHeaderContainer).setForeground(null);
mAccountHeaderContainer.setOnClickListener(null);
} else {
UIUtils.setBackground(mAccountHeaderTextSection, null);
mAccountHeaderTextSection.setOnClickListener(null);
}
}
}
/**
* method to build the header view
*
* @return
*/
public AccountHeader build() {
// if the user has not set a accountHeader use the default one :D
if (mAccountHeaderContainer == null) {
withAccountHeader(-1);
}
// get the header view within the container
mAccountHeader = mAccountHeaderContainer.findViewById(R.id.account_header_drawer);
// handle the height for the header
int height = -1;
if (mHeightPx != -1) {
height = mHeightPx;
} else if (mHeightDp != -1) {
height = (int) UIUtils.convertDpToPixel(mHeightDp, mActivity);
} else if (mHeightRes != -1) {
height = mActivity.getResources().getDimensionPixelSize(mHeightRes);
} else {
if (mCompactStyle) {
height = mActivity.getResources().getDimensionPixelSize(R.dimen.material_drawer_account_header_height_compact);
} else {
//calculate the header height by getting the optimal drawer width and calculating it * 9 / 16
height = (int) (DrawerUIUtils.getOptimalDrawerWidth(mActivity) * AccountHeader.NAVIGATION_DRAWER_ACCOUNT_ASPECT_RATIO);
//if we are lower than api 19 (>= 19 we have a translucentStatusBar) the height should be a bit lower
//probably even if we are non translucent on > 19 devices?
if (Build.VERSION.SDK_INT < 19) {
int tempHeight = height - UIUtils.getStatusBarHeight(mActivity, true);
if (UIUtils.convertPixelsToDp(tempHeight, mActivity) > 140) {
height = tempHeight;
}
}
}
}
// handle everything if we don't have a translucent status bar
if (mTranslucentStatusBar) {
mAccountHeader.setPadding(mAccountHeader.getPaddingLeft(), mAccountHeader.getPaddingTop() + UIUtils.getStatusBarHeight(mActivity), mAccountHeader.getPaddingRight(), mAccountHeader.getPaddingBottom());
//in fact it makes no difference if we have a translucent statusBar or not. we want 9/16 just if we are not compact
if (mCompactStyle) {
height = height + UIUtils.getStatusBarHeight(mActivity);
}
}
//set the height for the header
setHeaderHeight(height);
// get the background view
mAccountHeaderBackground = (ImageView) mAccountHeaderContainer.findViewById(R.id.account_header_drawer_background);
// set the background
if (mHeaderBackground != null) {
mAccountHeaderBackground.setImageDrawable(mHeaderBackground);
} else if (mHeaderBackgroundRes != -1) {
mAccountHeaderBackground.setImageResource(mHeaderBackgroundRes);
}
if (mHeaderBackgroundScaleType != null) {
mAccountHeaderBackground.setScaleType(mHeaderBackgroundScaleType);
}
// get the text color to use for the text section
if (mTextColor == 0 && mTextColorRes != -1) {
mTextColor = mActivity.getResources().getColor(mTextColorRes);
} else if (mTextColor == 0) {
mTextColor = UIUtils.getThemeColorFromAttrOrRes(mActivity, R.attr.material_drawer_header_selection_text, R.color.material_drawer_header_selection_text);
}
// set the background for the section
if (mCompactStyle) {
mAccountHeaderTextSection = mAccountHeader;
} else {
mAccountHeaderTextSection = mAccountHeaderContainer.findViewById(R.id.account_header_drawer_text_section);
}
mAccountHeaderTextSectionBackgroundResource = DrawerUIUtils.getSelectableBackground(mActivity);
handleSelectionView(mCurrentProfile, true);
// set the arrow :D
mAccountSwitcherArrow = (ImageView) mAccountHeaderContainer.findViewById(R.id.account_header_drawer_text_switcher);
mAccountSwitcherArrow.setImageDrawable(new IconicsDrawable(mActivity, MaterialDrawerFont.Icon.mdf_arrow_drop_down).sizeDp(24).paddingDp(6).color(mTextColor));
//get the fields for the name
mCurrentProfileView = (BezelImageView) mAccountHeader.findViewById(R.id.account_header_drawer_current);
mCurrentProfileName = (TextView) mAccountHeader.findViewById(R.id.account_header_drawer_name);
mCurrentProfileEmail = (TextView) mAccountHeader.findViewById(R.id.account_header_drawer_email);
//set the typeface for the AccountHeader
if (mNameTypeface != null) {
mCurrentProfileName.setTypeface(mNameTypeface);
} else if (mTypeface != null) {
mCurrentProfileName.setTypeface(mTypeface);
}
if (mEmailTypeface != null) {
mCurrentProfileEmail.setTypeface(mEmailTypeface);
} else if (mTypeface != null) {
mCurrentProfileEmail.setTypeface(mTypeface);
}
mCurrentProfileName.setTextColor(mTextColor);
mCurrentProfileEmail.setTextColor(mTextColor);
mProfileFirstView = (BezelImageView) mAccountHeader.findViewById(R.id.account_header_drawer_small_first);
mProfileSecondView = (BezelImageView) mAccountHeader.findViewById(R.id.account_header_drawer_small_second);
mProfileThirdView = (BezelImageView) mAccountHeader.findViewById(R.id.account_header_drawer_small_third);
//calculate the profiles to set
calculateProfiles();
//process and build the profiles
buildProfiles();
// try to restore all saved values again
if (mSavedInstance != null) {
int selection = mSavedInstance.getInt(AccountHeader.BUNDLE_SELECTION_HEADER, -1);
if (selection != -1) {
//predefine selection (should be the first element
if (mProfiles != null && (selection) > -1 && selection < mProfiles.size()) {
switchProfiles(mProfiles.get(selection));
}
}
}
//everything created. now set the header
if (mDrawer != null) {
mDrawer.setHeader(mAccountHeaderContainer);
}
//forget the reference to the activity
mActivity = null;
return new AccountHeader(this);
}
/**
* helper method to calculate the order of the profiles
*/
protected void calculateProfiles() {
if (mProfiles == null) {
mProfiles = new ArrayList<>();
}
if (mCurrentProfile == null) {
int setCount = 0;
for (int i = 0; i < mProfiles.size(); i++) {
if (mProfiles.size() > i && mProfiles.get(i).isSelectable()) {
if (setCount == 0 && (mCurrentProfile == null)) {
mCurrentProfile = mProfiles.get(i);
} else if (setCount == 1 && (mProfileFirst == null)) {
mProfileFirst = mProfiles.get(i);
} else if (setCount == 2 && (mProfileSecond == null)) {
mProfileSecond = mProfiles.get(i);
} else if (setCount == 3 && (mProfileThird == null)) {
mProfileThird = mProfiles.get(i);
}
setCount++;
}
}
return;
}
IProfile[] previousActiveProfiles = new IProfile[]{
mCurrentProfile,
mProfileFirst,
mProfileSecond,
mProfileThird
};
IProfile[] newActiveProfiles = new IProfile[4];
Stack<IProfile> unusedProfiles = new Stack<>();
// try to keep existing active profiles in the same positions
for (int i = 0; i < mProfiles.size(); i++) {
IProfile p = mProfiles.get(i);
if (p.isSelectable()) {
boolean used = false;
for (int j = 0; j < 4; j++) {
if (previousActiveProfiles[j] == p) {
newActiveProfiles[j] = p;
used = true;
break;
}
}
if (!used) {
unusedProfiles.push(p);
}
}
}
Stack<IProfile> activeProfiles = new Stack<>();
// try to fill the gaps with new available profiles
for (int i = 0; i < 4; i++) {
if (newActiveProfiles[i] != null) {
activeProfiles.push(newActiveProfiles[i]);
} else if (!unusedProfiles.isEmpty()) {
activeProfiles.push(unusedProfiles.pop());
}
}
Stack<IProfile> reversedActiveProfiles = new Stack<>();
while (!activeProfiles.empty()) {
reversedActiveProfiles.push(activeProfiles.pop());
}
// reassign active profiles
if (reversedActiveProfiles.isEmpty()) {
mCurrentProfile = null;
} else {
mCurrentProfile = reversedActiveProfiles.pop();
}
if (reversedActiveProfiles.isEmpty()) {
mProfileFirst = null;
} else {
mProfileFirst = reversedActiveProfiles.pop();
}
if (reversedActiveProfiles.isEmpty()) {
mProfileSecond = null;
} else {
mProfileSecond = reversedActiveProfiles.pop();
}
if (reversedActiveProfiles.isEmpty()) {
mProfileThird = null;
} else {
mProfileThird = reversedActiveProfiles.pop();
}
}
/**
* helper method to switch the profiles
*
* @param newSelection
* @return true if the new selection was the current profile
*/
protected boolean switchProfiles(IProfile newSelection) {
if (newSelection == null) {
return false;
}
if (mCurrentProfile == newSelection) {
return true;
}
if (mAlternativeProfileHeaderSwitching) {
int prevSelection = -1;
if (mProfileFirst == newSelection) {
prevSelection = 1;
} else if (mProfileSecond == newSelection) {
prevSelection = 2;
} else if (mProfileThird == newSelection) {
prevSelection = 3;
}
IProfile tmp = mCurrentProfile;
mCurrentProfile = newSelection;
if (prevSelection == 1) {
mProfileFirst = tmp;
} else if (prevSelection == 2) {
mProfileSecond = tmp;
} else if (prevSelection == 3) {
mProfileThird = tmp;
}
} else {
if (mProfiles != null) {
ArrayList<IProfile> previousActiveProfiles = new ArrayList<>(Arrays.asList(mCurrentProfile, mProfileFirst, mProfileSecond, mProfileThird));
if (previousActiveProfiles.contains(newSelection)) {
int position = -1;
for (int i = 0; i < 4; i++) {
if (previousActiveProfiles.get(i) == newSelection) {
position = i;
break;
}
}
if (position != -1) {
previousActiveProfiles.remove(position);
previousActiveProfiles.add(0, newSelection);
mCurrentProfile = previousActiveProfiles.get(0);
mProfileFirst = previousActiveProfiles.get(1);
mProfileSecond = previousActiveProfiles.get(2);
mProfileThird = previousActiveProfiles.get(3);
}
} else {
mProfileThird = mProfileSecond;
mProfileSecond = mProfileFirst;
mProfileFirst = mCurrentProfile;
mCurrentProfile = newSelection;
}
}
}
buildProfiles();
return false;
}
/**
* helper method to build the views for the ui
*/
protected void buildProfiles() {
mCurrentProfileView.setVisibility(View.INVISIBLE);
mAccountHeaderTextSection.setVisibility(View.INVISIBLE);
mAccountSwitcherArrow.setVisibility(View.INVISIBLE);
mProfileFirstView.setVisibility(View.INVISIBLE);
mProfileFirstView.setOnClickListener(null);
mProfileSecondView.setVisibility(View.INVISIBLE);
mProfileSecondView.setOnClickListener(null);
mProfileThirdView.setVisibility(View.GONE);
mProfileThirdView.setOnClickListener(null);
handleSelectionView(mCurrentProfile, true);
if (mCurrentProfile != null) {
if (mProfileImagesVisible) {
setImageOrPlaceholder(mCurrentProfileView, mCurrentProfile.getIcon());
if (mProfileImagesClickable) {
mCurrentProfileView.setOnClickListener(onProfileClickListener);
mCurrentProfileView.disableTouchFeedback(false);
} else {
mCurrentProfileView.disableTouchFeedback(true);
}
mCurrentProfileView.setVisibility(View.VISIBLE);
} else if (mCompactStyle) {
mCurrentProfileView.setVisibility(View.GONE);
}
mAccountHeaderTextSection.setVisibility(View.VISIBLE);
handleSelectionView(mCurrentProfile, true);
mAccountSwitcherArrow.setVisibility(View.VISIBLE);
mCurrentProfileView.setTag(R.id.md_profile_header, mCurrentProfile);
StringHolder.applyTo(mCurrentProfile.getName(), mCurrentProfileName);
StringHolder.applyTo(mCurrentProfile.getEmail(), mCurrentProfileEmail);
if (mProfileFirst != null && mProfileImagesVisible) {
setImageOrPlaceholder(mProfileFirstView, mProfileFirst.getIcon());
mProfileFirstView.setTag(R.id.md_profile_header, mProfileFirst);
if (mProfileImagesClickable) {
mProfileFirstView.setOnClickListener(onProfileClickListener);
mProfileFirstView.disableTouchFeedback(false);
} else {
mProfileFirstView.disableTouchFeedback(true);
}
mProfileFirstView.setVisibility(View.VISIBLE);
}
if (mProfileSecond != null && mProfileImagesVisible) {
setImageOrPlaceholder(mProfileSecondView, mProfileSecond.getIcon());
mProfileSecondView.setTag(R.id.md_profile_header, mProfileSecond);
if (mProfileImagesClickable) {
mProfileSecondView.setOnClickListener(onProfileClickListener);
mProfileSecondView.disableTouchFeedback(false);
} else {
mProfileSecondView.disableTouchFeedback(true);
}
mProfileSecondView.setVisibility(View.VISIBLE);
}
if (mProfileThird != null && mThreeSmallProfileImages && mProfileImagesVisible) {
setImageOrPlaceholder(mProfileThirdView, mProfileThird.getIcon());
mProfileThirdView.setTag(R.id.md_profile_header, mProfileThird);
if (mProfileImagesClickable) {
mProfileThirdView.setOnClickListener(onProfileClickListener);
mProfileThirdView.disableTouchFeedback(false);
} else {
mProfileThirdView.disableTouchFeedback(true);
}
mProfileThirdView.setVisibility(View.VISIBLE);
}
} else if (mProfiles != null && mProfiles.size() > 0) {
IProfile profile = mProfiles.get(0);
mAccountHeaderTextSection.setTag(R.id.md_profile_header, profile);
mAccountHeaderTextSection.setVisibility(View.VISIBLE);
handleSelectionView(mCurrentProfile, true);
mAccountSwitcherArrow.setVisibility(View.VISIBLE);
StringHolder.applyTo(mCurrentProfile.getName(), mCurrentProfileName);
StringHolder.applyTo(mCurrentProfile.getEmail(), mCurrentProfileEmail);
}
if (!mSelectionFirstLineShown) {
mCurrentProfileName.setVisibility(View.GONE);
}
if (!TextUtils.isEmpty(mSelectionFirstLine)) {
mCurrentProfileName.setText(mSelectionFirstLine);
mAccountHeaderTextSection.setVisibility(View.VISIBLE);
}
if (!mSelectionSecondLineShown) {
mCurrentProfileEmail.setVisibility(View.GONE);
}
if (!TextUtils.isEmpty(mSelectionSecondLine)) {
mCurrentProfileEmail.setText(mSelectionSecondLine);
mAccountHeaderTextSection.setVisibility(View.VISIBLE);
}
//if we disabled the list
if (!mSelectionListEnabled) {
mAccountSwitcherArrow.setVisibility(View.INVISIBLE);
handleSelectionView(null, false);
}
if (!mSelectionListEnabledForSingleProfile && mProfileFirst == null && (mProfiles == null || mProfiles.size() == 1)) {
mAccountSwitcherArrow.setVisibility(View.INVISIBLE);
handleSelectionView(null, false);
}
//if we disabled the list but still have set a custom listener
if (mOnAccountHeaderSelectionViewClickListener != null) {
handleSelectionView(mCurrentProfile, true);
}
}
/**
* small helper method to set an profile image or a placeholder
*
* @param iv
* @param imageHolder
*/
private void setImageOrPlaceholder(ImageView iv, ImageHolder imageHolder) {
//cancel previous started image loading processes
DrawerImageLoader.getInstance().cancelImage(iv);
//set the placeholder
iv.setImageDrawable(DrawerUIUtils.getPlaceHolder(iv.getContext()));
//set the real image (probably also the uri)
ImageHolder.applyTo(imageHolder, iv);
}
/**
* onProfileClickListener to notify onClick on a profile image
*/
private View.OnClickListener onCurrentProfileClickListener = new View.OnClickListener() {
@Override
public void onClick(final View v) {
onProfileClick(v, true);
}
};
/**
* onProfileClickListener to notify onClick on a profile image
*/
private View.OnClickListener onProfileClickListener = new View.OnClickListener() {
@Override
public void onClick(final View v) {
onProfileClick(v, false);
}
};
protected void onProfileClick(View v, boolean current) {
final IProfile profile = (IProfile) v.getTag(R.id.md_profile_header);
switchProfiles(profile);
//reset the drawer content
resetDrawerContent(v.getContext());
boolean consumed = false;
if (mOnAccountHeaderListener != null) {
consumed = mOnAccountHeaderListener.onProfileChanged(v, profile, current);
}
if (!consumed) {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
if (mDrawer != null) {
mDrawer.closeDrawer();
}
}
}, 200);
}
}
/**
* get the current selection
*
* @return
*/
protected int getCurrentSelection() {
if (mCurrentProfile != null && mProfiles != null) {
int i = 0;
for (IProfile profile : mProfiles) {
if (profile == mCurrentProfile) {
return i;
}
i++;
}
}
return -1;
}
/**
* onSelectionClickListener to notify the onClick on the checkbox
*/
private View.OnClickListener onSelectionClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
boolean consumed = false;
if (mOnAccountHeaderSelectionViewClickListener != null) {
consumed = mOnAccountHeaderSelectionViewClickListener.onClick(v, (IProfile) v.getTag(R.id.md_profile_header));
}
if (mAccountSwitcherArrow.getVisibility() == View.VISIBLE && !consumed) {
toggleSelectionList(v.getContext());
}
}
};
/**
* helper method to toggle the collection
*
* @param ctx
*/
protected void toggleSelectionList(Context ctx) {
if (mDrawer != null) {
//if we already show the list. reset everything instead
if (mDrawer.switchedDrawerContent()) {
resetDrawerContent(ctx);
mSelectionListShown = false;
} else {
//build and set the drawer selection list
buildDrawerSelectionList();
// update the arrow image within the drawer
mAccountSwitcherArrow.setImageDrawable(new IconicsDrawable(ctx, MaterialDrawerFont.Icon.mdf_arrow_drop_up).sizeDp(24).paddingDp(6).color(mTextColor));
mSelectionListShown = true;
}
}
}
/**
* helper method to build and set the drawer selection list
*/
protected void buildDrawerSelectionList() {
int selectedPosition = -1;
int position = 0;
ArrayList<IDrawerItem> profileDrawerItems = new ArrayList<>();
if (mProfiles != null) {
for (IProfile profile : mProfiles) {
if (profile == mCurrentProfile) {
if (mCurrentHiddenInList) {
continue;
} else {
selectedPosition = position + mDrawer.getAdapter().getHeaderOffset();
}
}
if (profile instanceof IDrawerItem) {
((IDrawerItem) profile).withSetSelected(false);
profileDrawerItems.add((IDrawerItem) profile);
}
position = position + 1;
}
}
mDrawer.switchDrawerContent(onDrawerItemClickListener, profileDrawerItems, selectedPosition);
}
/**
* onDrawerItemClickListener to catch the selection for the new profile!
*/
private Drawer.OnDrawerItemClickListener onDrawerItemClickListener = new Drawer.OnDrawerItemClickListener() {
@Override
public boolean onItemClick(final View view, int position, final IDrawerItem drawerItem) {
final boolean isCurrentSelectedProfile;
if (drawerItem != null && drawerItem instanceof IProfile && ((IProfile) drawerItem).isSelectable()) {
isCurrentSelectedProfile = switchProfiles((IProfile) drawerItem);
} else {
isCurrentSelectedProfile = false;
}
if (mResetDrawerOnProfileListClick) {
mDrawer.setOnDrawerItemClickListener(null);
}
//wrap the onSelection call and the reset stuff within a handler to prevent lag
if (mResetDrawerOnProfileListClick && mDrawer != null && view != null && view.getContext() != null) {
resetDrawerContent(view.getContext());
}
if (drawerItem != null && drawerItem instanceof IProfile) {
if (mOnAccountHeaderListener != null) {
mOnAccountHeaderListener.onProfileChanged(view, (IProfile) drawerItem, isCurrentSelectedProfile);
}
}
return !mCloseDrawerOnProfileListClick;
}
};
/**
* helper method to reset the drawer content
*/
private void resetDrawerContent(Context ctx) {
if (mDrawer != null) {
mDrawer.resetDrawerContent();
}
mAccountSwitcherArrow.setImageDrawable(new IconicsDrawable(ctx, MaterialDrawerFont.Icon.mdf_arrow_drop_down).sizeDp(24).paddingDp(6).color(mTextColor));
}
/**
* small helper class to update the header and the list
*/
protected void updateHeaderAndList() {
//recalculate the profiles
calculateProfiles();
//update the profiles in the header
buildProfiles();
//if we currently show the list add the new item directly to it
if (mSelectionListShown) {
buildDrawerSelectionList();
}
}
}
|
* fix FC if only ProfileSettingItems are given
thanks @adamgrieger
|
library/src/main/java/com/mikepenz/materialdrawer/AccountHeaderBuilder.java
|
* fix FC if only ProfileSettingItems are given thanks @adamgrieger
|
<ide><path>ibrary/src/main/java/com/mikepenz/materialdrawer/AccountHeaderBuilder.java
<ide> mAccountHeaderTextSection.setVisibility(View.VISIBLE);
<ide> handleSelectionView(mCurrentProfile, true);
<ide> mAccountSwitcherArrow.setVisibility(View.VISIBLE);
<del> StringHolder.applyTo(mCurrentProfile.getName(), mCurrentProfileName);
<del> StringHolder.applyTo(mCurrentProfile.getEmail(), mCurrentProfileEmail);
<add> if (mCurrentProfile != null) {
<add> StringHolder.applyTo(mCurrentProfile.getName(), mCurrentProfileName);
<add> StringHolder.applyTo(mCurrentProfile.getEmail(), mCurrentProfileEmail);
<add> }
<ide> }
<ide>
<ide> if (!mSelectionFirstLineShown) {
|
|
Java
|
apache-2.0
|
d222418e3e58c845e28b265cc19b79935812eb2e
| 0 |
signed/intellij-community,Distrotech/intellij-community,robovm/robovm-studio,dslomov/intellij-community,fnouama/intellij-community,Lekanich/intellij-community,izonder/intellij-community,nicolargo/intellij-community,salguarnieri/intellij-community,ThiagoGarciaAlves/intellij-community,amith01994/intellij-community,MichaelNedzelsky/intellij-community,slisson/intellij-community,petteyg/intellij-community,izonder/intellij-community,retomerz/intellij-community,caot/intellij-community,petteyg/intellij-community,kool79/intellij-community,lucafavatella/intellij-community,signed/intellij-community,samthor/intellij-community,ibinti/intellij-community,lucafavatella/intellij-community,apixandru/intellij-community,salguarnieri/intellij-community,akosyakov/intellij-community,michaelgallacher/intellij-community,apixandru/intellij-community,retomerz/intellij-community,jagguli/intellij-community,kool79/intellij-community,fitermay/intellij-community,michaelgallacher/intellij-community,clumsy/intellij-community,allotria/intellij-community,gnuhub/intellij-community,alphafoobar/intellij-community,ivan-fedorov/intellij-community,fitermay/intellij-community,petteyg/intellij-community,xfournet/intellij-community,ibinti/intellij-community,da1z/intellij-community,ol-loginov/intellij-community,ahb0327/intellij-community,suncycheng/intellij-community,salguarnieri/intellij-community,hurricup/intellij-community,ibinti/intellij-community,ThiagoGarciaAlves/intellij-community,MichaelNedzelsky/intellij-community,diorcety/intellij-community,caot/intellij-community,slisson/intellij-community,kdwink/intellij-community,ahb0327/intellij-community,MER-GROUP/intellij-community,amith01994/intellij-community,tmpgit/intellij-community,FHannes/intellij-community,youdonghai/intellij-community,akosyakov/intellij-community,holmes/intellij-community,suncycheng/intellij-community,vladmm/intellij-community,MER-GROUP/intellij-community,FHannes/intellij-community,FHannes/intellij-community,youdonghai/intellij-community,allotria/intellij-community,ryano144/intellij-community,fnouama/intellij-community,ryano144/intellij-community,robovm/robovm-studio,tmpgit/intellij-community,amith01994/intellij-community,akosyakov/intellij-community,orekyuu/intellij-community,ol-loginov/intellij-community,pwoodworth/intellij-community,TangHao1987/intellij-community,holmes/intellij-community,orekyuu/intellij-community,amith01994/intellij-community,vvv1559/intellij-community,jagguli/intellij-community,hurricup/intellij-community,SerCeMan/intellij-community,fengbaicanhe/intellij-community,suncycheng/intellij-community,izonder/intellij-community,retomerz/intellij-community,pwoodworth/intellij-community,blademainer/intellij-community,ivan-fedorov/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,jagguli/intellij-community,suncycheng/intellij-community,lucafavatella/intellij-community,kool79/intellij-community,semonte/intellij-community,dslomov/intellij-community,fnouama/intellij-community,idea4bsd/idea4bsd,vladmm/intellij-community,ryano144/intellij-community,Lekanich/intellij-community,muntasirsyed/intellij-community,fnouama/intellij-community,muntasirsyed/intellij-community,alphafoobar/intellij-community,ahb0327/intellij-community,orekyuu/intellij-community,supersven/intellij-community,apixandru/intellij-community,kdwink/intellij-community,ryano144/intellij-community,caot/intellij-community,hurricup/intellij-community,kdwink/intellij-community,asedunov/intellij-community,allotria/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,ftomassetti/intellij-community,Lekanich/intellij-community,kdwink/intellij-community,FHannes/intellij-community,ivan-fedorov/intellij-community,ahb0327/intellij-community,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,supersven/intellij-community,fengbaicanhe/intellij-community,signed/intellij-community,diorcety/intellij-community,jagguli/intellij-community,fengbaicanhe/intellij-community,vladmm/intellij-community,hurricup/intellij-community,youdonghai/intellij-community,allotria/intellij-community,dslomov/intellij-community,asedunov/intellij-community,retomerz/intellij-community,robovm/robovm-studio,idea4bsd/idea4bsd,jagguli/intellij-community,tmpgit/intellij-community,ftomassetti/intellij-community,tmpgit/intellij-community,izonder/intellij-community,wreckJ/intellij-community,MER-GROUP/intellij-community,MichaelNedzelsky/intellij-community,suncycheng/intellij-community,signed/intellij-community,idea4bsd/idea4bsd,da1z/intellij-community,supersven/intellij-community,nicolargo/intellij-community,idea4bsd/idea4bsd,hurricup/intellij-community,retomerz/intellij-community,idea4bsd/idea4bsd,fengbaicanhe/intellij-community,xfournet/intellij-community,holmes/intellij-community,blademainer/intellij-community,izonder/intellij-community,vladmm/intellij-community,signed/intellij-community,vladmm/intellij-community,SerCeMan/intellij-community,pwoodworth/intellij-community,kool79/intellij-community,blademainer/intellij-community,MichaelNedzelsky/intellij-community,ryano144/intellij-community,Lekanich/intellij-community,caot/intellij-community,MER-GROUP/intellij-community,salguarnieri/intellij-community,dslomov/intellij-community,TangHao1987/intellij-community,Distrotech/intellij-community,petteyg/intellij-community,ftomassetti/intellij-community,amith01994/intellij-community,hurricup/intellij-community,orekyuu/intellij-community,fnouama/intellij-community,FHannes/intellij-community,TangHao1987/intellij-community,samthor/intellij-community,semonte/intellij-community,nicolargo/intellij-community,da1z/intellij-community,semonte/intellij-community,diorcety/intellij-community,fengbaicanhe/intellij-community,ahb0327/intellij-community,caot/intellij-community,alphafoobar/intellij-community,ivan-fedorov/intellij-community,Distrotech/intellij-community,lucafavatella/intellij-community,orekyuu/intellij-community,kool79/intellij-community,fitermay/intellij-community,allotria/intellij-community,TangHao1987/intellij-community,jagguli/intellij-community,MichaelNedzelsky/intellij-community,idea4bsd/idea4bsd,semonte/intellij-community,da1z/intellij-community,lucafavatella/intellij-community,ahb0327/intellij-community,fitermay/intellij-community,robovm/robovm-studio,semonte/intellij-community,muntasirsyed/intellij-community,MER-GROUP/intellij-community,ol-loginov/intellij-community,diorcety/intellij-community,supersven/intellij-community,wreckJ/intellij-community,orekyuu/intellij-community,kdwink/intellij-community,ol-loginov/intellij-community,kool79/intellij-community,ThiagoGarciaAlves/intellij-community,pwoodworth/intellij-community,dslomov/intellij-community,suncycheng/intellij-community,petteyg/intellij-community,ivan-fedorov/intellij-community,ol-loginov/intellij-community,Lekanich/intellij-community,mglukhikh/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,idea4bsd/idea4bsd,apixandru/intellij-community,dslomov/intellij-community,alphafoobar/intellij-community,samthor/intellij-community,petteyg/intellij-community,amith01994/intellij-community,SerCeMan/intellij-community,ol-loginov/intellij-community,fitermay/intellij-community,wreckJ/intellij-community,ftomassetti/intellij-community,clumsy/intellij-community,adedayo/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,signed/intellij-community,MichaelNedzelsky/intellij-community,Distrotech/intellij-community,apixandru/intellij-community,clumsy/intellij-community,blademainer/intellij-community,alphafoobar/intellij-community,adedayo/intellij-community,kdwink/intellij-community,muntasirsyed/intellij-community,SerCeMan/intellij-community,tmpgit/intellij-community,muntasirsyed/intellij-community,lucafavatella/intellij-community,holmes/intellij-community,holmes/intellij-community,lucafavatella/intellij-community,supersven/intellij-community,adedayo/intellij-community,slisson/intellij-community,blademainer/intellij-community,signed/intellij-community,FHannes/intellij-community,pwoodworth/intellij-community,TangHao1987/intellij-community,fitermay/intellij-community,slisson/intellij-community,Distrotech/intellij-community,alphafoobar/intellij-community,amith01994/intellij-community,Distrotech/intellij-community,ivan-fedorov/intellij-community,robovm/robovm-studio,nicolargo/intellij-community,michaelgallacher/intellij-community,hurricup/intellij-community,michaelgallacher/intellij-community,SerCeMan/intellij-community,pwoodworth/intellij-community,idea4bsd/idea4bsd,suncycheng/intellij-community,nicolargo/intellij-community,idea4bsd/idea4bsd,ftomassetti/intellij-community,caot/intellij-community,gnuhub/intellij-community,MER-GROUP/intellij-community,adedayo/intellij-community,Distrotech/intellij-community,mglukhikh/intellij-community,kool79/intellij-community,SerCeMan/intellij-community,fitermay/intellij-community,michaelgallacher/intellij-community,ThiagoGarciaAlves/intellij-community,FHannes/intellij-community,asedunov/intellij-community,ftomassetti/intellij-community,mglukhikh/intellij-community,MER-GROUP/intellij-community,MichaelNedzelsky/intellij-community,FHannes/intellij-community,salguarnieri/intellij-community,slisson/intellij-community,vvv1559/intellij-community,ahb0327/intellij-community,tmpgit/intellij-community,akosyakov/intellij-community,fitermay/intellij-community,lucafavatella/intellij-community,akosyakov/intellij-community,SerCeMan/intellij-community,ryano144/intellij-community,samthor/intellij-community,SerCeMan/intellij-community,lucafavatella/intellij-community,retomerz/intellij-community,slisson/intellij-community,izonder/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,caot/intellij-community,apixandru/intellij-community,MER-GROUP/intellij-community,retomerz/intellij-community,allotria/intellij-community,wreckJ/intellij-community,supersven/intellij-community,mglukhikh/intellij-community,robovm/robovm-studio,supersven/intellij-community,supersven/intellij-community,salguarnieri/intellij-community,diorcety/intellij-community,slisson/intellij-community,TangHao1987/intellij-community,hurricup/intellij-community,da1z/intellij-community,ftomassetti/intellij-community,da1z/intellij-community,tmpgit/intellij-community,hurricup/intellij-community,adedayo/intellij-community,orekyuu/intellij-community,suncycheng/intellij-community,ThiagoGarciaAlves/intellij-community,ivan-fedorov/intellij-community,izonder/intellij-community,semonte/intellij-community,signed/intellij-community,apixandru/intellij-community,SerCeMan/intellij-community,supersven/intellij-community,ftomassetti/intellij-community,blademainer/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,vvv1559/intellij-community,muntasirsyed/intellij-community,fengbaicanhe/intellij-community,da1z/intellij-community,adedayo/intellij-community,salguarnieri/intellij-community,da1z/intellij-community,kdwink/intellij-community,vvv1559/intellij-community,vladmm/intellij-community,wreckJ/intellij-community,kool79/intellij-community,samthor/intellij-community,alphafoobar/intellij-community,MichaelNedzelsky/intellij-community,SerCeMan/intellij-community,semonte/intellij-community,Lekanich/intellij-community,fengbaicanhe/intellij-community,alphafoobar/intellij-community,akosyakov/intellij-community,petteyg/intellij-community,salguarnieri/intellij-community,retomerz/intellij-community,semonte/intellij-community,petteyg/intellij-community,youdonghai/intellij-community,semonte/intellij-community,michaelgallacher/intellij-community,blademainer/intellij-community,holmes/intellij-community,fengbaicanhe/intellij-community,kdwink/intellij-community,michaelgallacher/intellij-community,izonder/intellij-community,slisson/intellij-community,robovm/robovm-studio,vvv1559/intellij-community,akosyakov/intellij-community,SerCeMan/intellij-community,slisson/intellij-community,muntasirsyed/intellij-community,clumsy/intellij-community,salguarnieri/intellij-community,apixandru/intellij-community,samthor/intellij-community,xfournet/intellij-community,youdonghai/intellij-community,amith01994/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,izonder/intellij-community,muntasirsyed/intellij-community,vvv1559/intellij-community,pwoodworth/intellij-community,allotria/intellij-community,youdonghai/intellij-community,xfournet/intellij-community,kdwink/intellij-community,MER-GROUP/intellij-community,ryano144/intellij-community,ibinti/intellij-community,youdonghai/intellij-community,holmes/intellij-community,salguarnieri/intellij-community,gnuhub/intellij-community,blademainer/intellij-community,adedayo/intellij-community,ibinti/intellij-community,xfournet/intellij-community,clumsy/intellij-community,slisson/intellij-community,asedunov/intellij-community,fnouama/intellij-community,robovm/robovm-studio,wreckJ/intellij-community,lucafavatella/intellij-community,ibinti/intellij-community,supersven/intellij-community,SerCeMan/intellij-community,xfournet/intellij-community,clumsy/intellij-community,wreckJ/intellij-community,FHannes/intellij-community,ryano144/intellij-community,da1z/intellij-community,ivan-fedorov/intellij-community,signed/intellij-community,jagguli/intellij-community,fengbaicanhe/intellij-community,xfournet/intellij-community,dslomov/intellij-community,pwoodworth/intellij-community,muntasirsyed/intellij-community,fnouama/intellij-community,ahb0327/intellij-community,signed/intellij-community,semonte/intellij-community,adedayo/intellij-community,ibinti/intellij-community,gnuhub/intellij-community,lucafavatella/intellij-community,ryano144/intellij-community,idea4bsd/idea4bsd,ol-loginov/intellij-community,Lekanich/intellij-community,fnouama/intellij-community,youdonghai/intellij-community,apixandru/intellij-community,clumsy/intellij-community,slisson/intellij-community,michaelgallacher/intellij-community,Distrotech/intellij-community,clumsy/intellij-community,salguarnieri/intellij-community,idea4bsd/idea4bsd,robovm/robovm-studio,ahb0327/intellij-community,hurricup/intellij-community,izonder/intellij-community,TangHao1987/intellij-community,adedayo/intellij-community,holmes/intellij-community,michaelgallacher/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,ol-loginov/intellij-community,Distrotech/intellij-community,vvv1559/intellij-community,da1z/intellij-community,akosyakov/intellij-community,fnouama/intellij-community,vladmm/intellij-community,nicolargo/intellij-community,gnuhub/intellij-community,lucafavatella/intellij-community,ftomassetti/intellij-community,robovm/robovm-studio,dslomov/intellij-community,wreckJ/intellij-community,slisson/intellij-community,michaelgallacher/intellij-community,allotria/intellij-community,youdonghai/intellij-community,vvv1559/intellij-community,blademainer/intellij-community,MichaelNedzelsky/intellij-community,wreckJ/intellij-community,orekyuu/intellij-community,kool79/intellij-community,allotria/intellij-community,asedunov/intellij-community,tmpgit/intellij-community,ThiagoGarciaAlves/intellij-community,wreckJ/intellij-community,holmes/intellij-community,ThiagoGarciaAlves/intellij-community,vladmm/intellij-community,da1z/intellij-community,ibinti/intellij-community,lucafavatella/intellij-community,petteyg/intellij-community,suncycheng/intellij-community,robovm/robovm-studio,asedunov/intellij-community,jagguli/intellij-community,gnuhub/intellij-community,Lekanich/intellij-community,amith01994/intellij-community,alphafoobar/intellij-community,holmes/intellij-community,petteyg/intellij-community,MichaelNedzelsky/intellij-community,adedayo/intellij-community,blademainer/intellij-community,orekyuu/intellij-community,da1z/intellij-community,supersven/intellij-community,fitermay/intellij-community,petteyg/intellij-community,asedunov/intellij-community,semonte/intellij-community,vladmm/intellij-community,ahb0327/intellij-community,FHannes/intellij-community,dslomov/intellij-community,vladmm/intellij-community,apixandru/intellij-community,youdonghai/intellij-community,ibinti/intellij-community,adedayo/intellij-community,wreckJ/intellij-community,petteyg/intellij-community,diorcety/intellij-community,vvv1559/intellij-community,Lekanich/intellij-community,apixandru/intellij-community,dslomov/intellij-community,hurricup/intellij-community,salguarnieri/intellij-community,FHannes/intellij-community,holmes/intellij-community,fitermay/intellij-community,samthor/intellij-community,samthor/intellij-community,ryano144/intellij-community,asedunov/intellij-community,amith01994/intellij-community,diorcety/intellij-community,kdwink/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,suncycheng/intellij-community,kdwink/intellij-community,MichaelNedzelsky/intellij-community,nicolargo/intellij-community,ryano144/intellij-community,robovm/robovm-studio,ol-loginov/intellij-community,gnuhub/intellij-community,MER-GROUP/intellij-community,orekyuu/intellij-community,nicolargo/intellij-community,FHannes/intellij-community,asedunov/intellij-community,amith01994/intellij-community,youdonghai/intellij-community,akosyakov/intellij-community,idea4bsd/idea4bsd,signed/intellij-community,diorcety/intellij-community,nicolargo/intellij-community,adedayo/intellij-community,akosyakov/intellij-community,ftomassetti/intellij-community,jagguli/intellij-community,supersven/intellij-community,Lekanich/intellij-community,mglukhikh/intellij-community,fengbaicanhe/intellij-community,TangHao1987/intellij-community,MER-GROUP/intellij-community,TangHao1987/intellij-community,tmpgit/intellij-community,fengbaicanhe/intellij-community,Distrotech/intellij-community,pwoodworth/intellij-community,diorcety/intellij-community,pwoodworth/intellij-community,holmes/intellij-community,vvv1559/intellij-community,ahb0327/intellij-community,samthor/intellij-community,akosyakov/intellij-community,kool79/intellij-community,MER-GROUP/intellij-community,samthor/intellij-community,gnuhub/intellij-community,ibinti/intellij-community,retomerz/intellij-community,ahb0327/intellij-community,youdonghai/intellij-community,gnuhub/intellij-community,ol-loginov/intellij-community,xfournet/intellij-community,clumsy/intellij-community,diorcety/intellij-community,mglukhikh/intellij-community,alphafoobar/intellij-community,kool79/intellij-community,ol-loginov/intellij-community,nicolargo/intellij-community,signed/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,retomerz/intellij-community,clumsy/intellij-community,muntasirsyed/intellij-community,kool79/intellij-community,pwoodworth/intellij-community,Lekanich/intellij-community,diorcety/intellij-community,ThiagoGarciaAlves/intellij-community,Distrotech/intellij-community,clumsy/intellij-community,ivan-fedorov/intellij-community,caot/intellij-community,idea4bsd/idea4bsd,gnuhub/intellij-community,gnuhub/intellij-community,samthor/intellij-community,dslomov/intellij-community,blademainer/intellij-community,tmpgit/intellij-community,dslomov/intellij-community,vladmm/intellij-community,nicolargo/intellij-community,youdonghai/intellij-community,fnouama/intellij-community,muntasirsyed/intellij-community,ivan-fedorov/intellij-community,alphafoobar/intellij-community,vladmm/intellij-community,da1z/intellij-community,jagguli/intellij-community,xfournet/intellij-community,caot/intellij-community,TangHao1987/intellij-community,gnuhub/intellij-community,TangHao1987/intellij-community,clumsy/intellij-community,retomerz/intellij-community,hurricup/intellij-community,izonder/intellij-community,tmpgit/intellij-community,semonte/intellij-community,blademainer/intellij-community,jagguli/intellij-community,jagguli/intellij-community,tmpgit/intellij-community,apixandru/intellij-community,caot/intellij-community,Lekanich/intellij-community,fitermay/intellij-community,semonte/intellij-community,michaelgallacher/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,orekyuu/intellij-community,amith01994/intellij-community,ol-loginov/intellij-community,fnouama/intellij-community,fengbaicanhe/intellij-community,hurricup/intellij-community,samthor/intellij-community,muntasirsyed/intellij-community,orekyuu/intellij-community,TangHao1987/intellij-community,asedunov/intellij-community,fitermay/intellij-community,caot/intellij-community,MichaelNedzelsky/intellij-community,fnouama/intellij-community,wreckJ/intellij-community,caot/intellij-community,ivan-fedorov/intellij-community,signed/intellij-community,asedunov/intellij-community,michaelgallacher/intellij-community,apixandru/intellij-community,ftomassetti/intellij-community,diorcety/intellij-community,akosyakov/intellij-community,ftomassetti/intellij-community,izonder/intellij-community,ibinti/intellij-community,ryano144/intellij-community,alphafoobar/intellij-community,nicolargo/intellij-community,fitermay/intellij-community,Distrotech/intellij-community,ibinti/intellij-community,ivan-fedorov/intellij-community,kdwink/intellij-community,pwoodworth/intellij-community,allotria/intellij-community,retomerz/intellij-community,retomerz/intellij-community,suncycheng/intellij-community
|
package com.jetbrains.python.structureView;
import com.intellij.ide.IdeBundle;
import com.intellij.ide.util.FileStructureFilter;
import com.intellij.ide.util.treeView.smartTree.ActionPresentation;
import com.intellij.ide.util.treeView.smartTree.ActionPresentationData;
import com.intellij.ide.util.treeView.smartTree.Filter;
import com.intellij.ide.util.treeView.smartTree.TreeElement;
import com.intellij.openapi.actionSystem.Shortcut;
import com.intellij.openapi.keymap.KeymapManager;
import com.intellij.openapi.util.IconLoader;
import com.jetbrains.python.psi.PyElement;
import org.jetbrains.annotations.NotNull;
/**
* @author vlan
*/
public class PyInheritedMembersFilter implements FileStructureFilter {
private static final String ID = "SHOW_INHERITED";
@Override
public boolean isReverted() {
return true;
}
@Override
public boolean isVisible(TreeElement treeNode) {
if (treeNode instanceof PyStructureViewElement) {
final PyStructureViewElement sve = (PyStructureViewElement)treeNode;
return !sve.isInherited();
}
return true;
}
@NotNull
@Override
public String getName() {
return ID;
}
@Override
public String toString() {
return getName();
}
@NotNull
@Override
public ActionPresentation getPresentation() {
return new ActionPresentationData(IdeBundle.message("action.structureview.show.inherited"),
null,
IconLoader.getIcon("/hierarchy/supertypes.png"));
}
@Override
public String getCheckBoxText() {
return IdeBundle.message("file.structure.toggle.show.inherited");
}
@Override
public Shortcut[] getShortcut() {
return KeymapManager.getInstance().getActiveKeymap().getShortcuts("FileStructurePopup");
}
}
|
python/src/com/jetbrains/python/structureView/PyInheritedMembersFilter.java
|
package com.jetbrains.python.structureView;
import com.intellij.ide.IdeBundle;
import com.intellij.ide.util.treeView.smartTree.ActionPresentation;
import com.intellij.ide.util.treeView.smartTree.ActionPresentationData;
import com.intellij.ide.util.treeView.smartTree.Filter;
import com.intellij.ide.util.treeView.smartTree.TreeElement;
import com.intellij.openapi.util.IconLoader;
import com.jetbrains.python.psi.PyElement;
import org.jetbrains.annotations.NotNull;
/**
* @author vlan
*/
public class PyInheritedMembersFilter implements Filter {
private static final String ID = "SHOW_INHERITED";
@Override
public boolean isReverted() {
return true;
}
@Override
public boolean isVisible(TreeElement treeNode) {
if (treeNode instanceof PyStructureViewElement) {
final PyStructureViewElement sve = (PyStructureViewElement)treeNode;
return !sve.isInherited();
}
return true;
}
@NotNull
@Override
public String getName() {
return ID;
}
@Override
public String toString() {
return getName();
}
@NotNull
@Override
public ActionPresentation getPresentation() {
return new ActionPresentationData(IdeBundle.message("action.structureview.show.inherited"),
null,
IconLoader.getIcon("/hierarchy/supertypes.png"));
}
}
|
Added checkbox to show inherited members in the file structure popup (PY-3936)
|
python/src/com/jetbrains/python/structureView/PyInheritedMembersFilter.java
|
Added checkbox to show inherited members in the file structure popup (PY-3936)
|
<ide><path>ython/src/com/jetbrains/python/structureView/PyInheritedMembersFilter.java
<ide> package com.jetbrains.python.structureView;
<ide>
<ide> import com.intellij.ide.IdeBundle;
<add>import com.intellij.ide.util.FileStructureFilter;
<ide> import com.intellij.ide.util.treeView.smartTree.ActionPresentation;
<ide> import com.intellij.ide.util.treeView.smartTree.ActionPresentationData;
<ide> import com.intellij.ide.util.treeView.smartTree.Filter;
<ide> import com.intellij.ide.util.treeView.smartTree.TreeElement;
<add>import com.intellij.openapi.actionSystem.Shortcut;
<add>import com.intellij.openapi.keymap.KeymapManager;
<ide> import com.intellij.openapi.util.IconLoader;
<ide> import com.jetbrains.python.psi.PyElement;
<ide> import org.jetbrains.annotations.NotNull;
<ide> /**
<ide> * @author vlan
<ide> */
<del>public class PyInheritedMembersFilter implements Filter {
<add>public class PyInheritedMembersFilter implements FileStructureFilter {
<ide> private static final String ID = "SHOW_INHERITED";
<ide>
<ide> @Override
<ide> null,
<ide> IconLoader.getIcon("/hierarchy/supertypes.png"));
<ide> }
<add>
<add> @Override
<add> public String getCheckBoxText() {
<add> return IdeBundle.message("file.structure.toggle.show.inherited");
<add> }
<add>
<add> @Override
<add> public Shortcut[] getShortcut() {
<add> return KeymapManager.getInstance().getActiveKeymap().getShortcuts("FileStructurePopup");
<add> }
<ide> }
|
|
JavaScript
|
lgpl-2.1
|
703c0060d34cc21e2c0f46db8d325269b06787ee
| 0 |
DHTMLGoodies/ludojs,DHTMLGoodies/ludojs,DHTMLGoodies/ludojs
|
/**
* Render a shim
* @namespace view
* @class Shim
*/
ludo.view.Shim = new Class({
txt:'Loading content...',
el:undefined,
shim:undefined,
renderTo:undefined,
initialize:function (config) {
if (config.txt)this.txt = config.txt;
this.renderTo = config.renderTo;
},
getEl:function () {
if (this.el === undefined) {
this.el = ludo.dom.create({
renderTo:this.getRenderTo(),
cls:'ludo-shim-loading',
css:{'display':'none'},
html : this.getText(this.txt)
});
}
return this.el;
},
getShim:function () {
if (this.shim === undefined) {
if(ludo.util.isString(this.renderTo))this.renderTo = ludo.get(this.renderTo).getEl();
this.shim = ludo.dom.create({
renderTo:this.getRenderTo(),
cls:'ludo-loader-shim',
css:{'display':'none'}
});
}
return this.shim;
},
getRenderTo:function(){
if(ludo.util.isString(this.renderTo)){
var view = ludo.get(this.renderTo);
if(!view)return undefined;
this.renderTo = ludo.get(this.renderTo).getEl();
}
return this.renderTo;
},
show:function (txt) {
this.getEl().set('html', this.getText(txt ? txt : this.txt));
this.css('');
this.resizeShim();
},
resizeShim:function(){
var span = document.id(this.el).getElement('span');
var width = (span.offsetWidth + 5);
this.el.style.width = width + 'px';
this.el.style.marginLeft = (Math.round(width/2) * -1) + 'px';
},
getText:function(txt){
return '<span>' + (ludo.util.isFunction(txt) ? txt.call() : txt ? txt : '') + '</span>';
},
hide:function () {
this.css('none');
},
css:function (d) {
this.getShim().style.display = d;
this.getEl().style.display = d === '' && this.txt ? '' : 'none';
}
});
|
src/view/shim.js
|
/**
* Render a shim
* @namespace view
* @class Shim
*/
ludo.view.Shim = new Class({
txt:'Loading content...',
el:undefined,
shim:undefined,
renderTo:undefined,
initialize:function (config) {
if (config.txt)this.txt = config.txt;
this.renderTo = config.renderTo;
},
getEl:function () {
if (this.el === undefined) {
this.el = ludo.dom.create({
renderTo:this.getRenderTo(),
cls:'ludo-shim-loading',
css:{'display':'none'},
html : this.getText(this.txt)
});
}
return this.el;
},
getShim:function () {
if (this.shim === undefined) {
if(ludo.util.isString(this.renderTo))this.renderTo = ludo.get(this.renderTo).getEl();
this.shim = ludo.dom.create({
renderTo:this.getRenderTo(),
cls:'ludo-loader-shim',
css:{'display':'none'}
});
}
return this.shim;
},
getRenderTo:function(){
if(ludo.util.isString(this.renderTo)){
var view = ludo.get(this.renderTo);
if(!view)return undefined;
this.renderTo = ludo.get(this.renderTo).getEl();
}
return this.renderTo;
},
show:function (txt) {
if (txt !== undefined) {
this.getEl().set('html', this.getText(txt));
}else{
this.getEl().set('html', this.getText(this.txt));
}
this.css('');
this.resizeShim();
},
resizeShim:function(){
var span = document.id(this.el).getElement('span');
var width = (span.offsetWidth + 5);
this.el.style.width = width + 'px';
this.el.style.marginLeft = (Math.round(width/2) * -1) + 'px';
},
getText:function(txt){
return '<span>' + (ludo.util.isFunction(txt) ? txt.call() : txt ? txt : '') + '</span>';
},
hide:function () {
this.css('none');
},
css:function (d) {
this.getShim().style.display = d;
this.getEl().style.display = d === '' && this.txt ? '' : 'none';
}
});
|
code refactorign
|
src/view/shim.js
|
code refactorign
|
<ide><path>rc/view/shim.js
<ide> },
<ide>
<ide> show:function (txt) {
<del> if (txt !== undefined) {
<del> this.getEl().set('html', this.getText(txt));
<del> }else{
<del> this.getEl().set('html', this.getText(this.txt));
<del> }
<add> this.getEl().set('html', this.getText(txt ? txt : this.txt));
<ide> this.css('');
<ide> this.resizeShim();
<ide> },
|
|
Java
|
mit
|
d815a2af02f1f4f84e6040be372b9727da4bfddd
| 0 |
jancajthaml/paloi13
|
package pal;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Vector;
public class Main
{
static int BIG_ENOUGHT_LINES = 1000000;
static BufferedReader bi = new BufferedReader(new InputStreamReader(System.in));
static StringBuilder buffer = new StringBuilder();
public static HashMap<String,Node> cache = new HashMap<String,Node>();
static String[] line_map = new String[BIG_ENOUGHT_LINES];
static int LINES_RED = 0;
static HashMap<Integer,String> relation = new HashMap<Integer,String>();
protected static Vector<Edge> edges = new Vector<Edge>();
static String s = "";
static String name = "";
static int current = 0;
//TODO get rid of Node objects
private static int[] visited = new int[BIG_ENOUGHT_LINES];
public static void main(String[] args) throws IOException
{
LINES_RED = 0;
slurp();
Node root = cache.get("all");
if(cycle(root)) System.out.println("ERROR");
else
{
// for(Node n : cache.values()) n.visited=false;
traverse(root);
out();
}
}
private static Node node(String key)
{
key = key.trim();
Node n = cache.get(key);
if(n==null)
{
n = new Node(key);
cache.put(key, n);
}
return n;
}
private static void readLine()
{
line_map[LINES_RED++] = s;
//System.err.print("RED LINE : "+s);
if(s.charAt(0) != 9)
{
try
{
int index = s.indexOf(":");
name = s.substring(0, index);
String[] dependencies = s.substring(index).split(" ");
Node n = node(name);
for(int i=1; i<dependencies.length; i++)
{
if(dependencies[i].isEmpty()) continue;
Node m = node(dependencies[i]);
edges.add(new Edge(n,m));
}
relation.put(LINES_RED-1, name);
}
catch(StringIndexOutOfBoundsException e){}
}
else relation.put(LINES_RED-1, name);
s="";
}
public static String slurp()
{
try
{
while((current = bi.read()) > -1)
{
s+=(char)current;
if(current == '\n')
readLine();
}
//System.err.println("s "+s);
//readLine();
}
catch (UnsupportedEncodingException ex) { System.out.println("ERROR"); }
catch (IOException ex) { System.out.println("ERROR"); }
return s;
}
static void out()
{
buffer.setLength(0);
//FIXME set "#" in NODE and get rid of O(n) here
for(int i=0; i<LINES_RED; i++)
buffer.append((i==0 || cache.get(relation.get(i)).visited)?(line_map[i]):("#"+line_map[i]));
System.out.print(buffer);
}
static boolean cycle(Node n)
{
return false;
}
public static void traverse(Node node)
{
Queue<Node> q = new LinkedList<Node>();
q.add(node);
node.visited = true;
while(!q.isEmpty())
{
Node n = (Node)q.poll();
for(Node adj : getNeighbors(n))
{
if(!adj.visited)
{
adj.visited = true;
q.add(adj);
}
}
}
}
public static Vector<Node> getNeighbors(Node a)
{
Vector<Node> neighbors = new Vector<Node>();
for(int i = 0; i < edges.size(); i++)
{
Edge edge = edges.elementAt(i);
if(edge.a == a)
neighbors.add(edge.b);
}
return neighbors;
}
}
class Node
{
String data;
boolean visited;
public Node(String data)
{ this.data = data; }
public java.lang.String toString()
{ return data.toString()+"["+(visited?" ":"#")+"]"; }
}
class Edge
{
protected Node a, b;
public Edge(Node a, Node b)
{
this.a = a;
this.b = b;
}
}
|
tasks-source/2-refactoring-makefile/Main.java
|
package pal;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Vector;
public class Main
{
static int BIG_ENOUGHT_LINES = 1000000;
static BufferedReader bi = new BufferedReader(new InputStreamReader(System.in));
static StringBuilder buffer = new StringBuilder();
public static HashMap<String,Node> cache = new HashMap<String,Node>();
static String[] line_map = new String[BIG_ENOUGHT_LINES];
static int LINES_RED = 0;
static HashMap<Integer,String> relation = new HashMap<Integer,String>();
protected static Vector<Edge> edges = new Vector<Edge>();
static String s = "";
static int current = 0;
static String name = "";
//TODO get rid of Node objects
private static int[] visited = new int[BIG_ENOUGHT_LINES];
public static void main(String[] args) throws IOException
{
LINES_RED = 0;
slurp();
Node root = cache.get("all");
if(cycle(root)) System.out.println("ERROR");
else
{
for(Node n : cache.values()) n.visited=false;
traverse(root);
out();
}
}
private static Node node(String key)
{
key=key.trim();
Node n ;
if(!cache.containsKey(key))
{
//System.err.print("creating "+key);
n = new Node(key);
cache.put(key, n);
}
else n = cache.get(key);
return n;
}
private static void readLine()
{
line_map[LINES_RED++]=s;
System.err.print("RED LINE : "+s);
if(s.charAt(0) != 9)
{
try
{
int index = s.indexOf(":");
name = s.substring(0, index);
String[] dependencies = s.substring(index).split(" ");
Node n = node(name);
for(int i=1; i<dependencies.length; i++)
{
if(dependencies[i].isEmpty()) continue;
Node m = node(dependencies[i]);
edges.add(new Edge(n,m));
}
relation.put(LINES_RED-1, name);
}
catch(StringIndexOutOfBoundsException e){}
}
else relation.put(LINES_RED-1, name);
s="";
}
private static void printEachLine() throws IOException {
int foo = 0;
char ch = 0;
StringBuilder sb = new StringBuilder();
boolean isEOL = false; //err, need to set this or get rid of it
do {
foo = bi.read();
ch = (char) foo;
sb.append(ch);
if ((ch == 10))
{
System.err.print(sb);
foo = bi.read();
ch = (char) foo;
sb.append(ch);
if (ch != 13)
{
while ((255 > ch) && (ch >= 0))
{
sb = new StringBuilder();
foo = bi.read();
ch = (char) foo;
sb.append(ch);
System.err.print(sb);
}
}
sb.append(ch);
}
} while (!isEOL);
}
public static String slurp()
{
try
{
while((current = bi.read()) > -1)
{
s+=(char)current;
if(current == '\n')
{
readLine();
}
}
System.out.println("");
//System.err.println("s "+s);
//readLine();
}
catch (UnsupportedEncodingException ex) { System.out.println("ERROR");}
catch (IOException ex) { System.out.println("ERROR");}
return s;
}
static void out()
{
buffer.setLength(0);
for(int i=0; i<LINES_RED; i++)
buffer.append((i==0 || cache.get(relation.get(i)).visited)?(line_map[i]):("#"+line_map[i]));
System.out.print(buffer);
}
static boolean cycle(Node n)
{
return false;
}
public static void traverse(Node node)
{
Queue<Node> q = new LinkedList<Node>();
q.add(node);
node.visited=true;
while(!q.isEmpty())
{
Node n = (Node)q.poll();
for(Node adj : getNeighbors(n))
{
if(!adj.visited)
{
adj.visited=true;
q.add(adj);
}
}
}
}
public static Vector<Node> getNeighbors(Node a)
{
Vector<Node> neighbors = new Vector<Node>();
for(int i = 0; i < edges.size(); i++)
{
Edge edge = edges.elementAt(i);
if(edge.a == a)
neighbors.add(edge.b);
}
return neighbors;
}
}
class Node
{
String data;
boolean visited;
public Node(String data)
{ this.data = data; }
public java.lang.String toString()
{ return data.toString()+"["+(visited?"X":" ")+"]"; }
}
class Edge
{
protected Node a, b;
public Edge(Node a, Node b)
{
this.a = a;
this.b = b;
}
}
|
Small clean
|
tasks-source/2-refactoring-makefile/Main.java
|
Small clean
|
<ide><path>asks-source/2-refactoring-makefile/Main.java
<ide> static int LINES_RED = 0;
<ide> static HashMap<Integer,String> relation = new HashMap<Integer,String>();
<ide> protected static Vector<Edge> edges = new Vector<Edge>();
<del>
<ide> static String s = "";
<add> static String name = "";
<ide> static int current = 0;
<del> static String name = "";
<ide>
<ide> //TODO get rid of Node objects
<ide> private static int[] visited = new int[BIG_ENOUGHT_LINES];
<ide> if(cycle(root)) System.out.println("ERROR");
<ide> else
<ide> {
<del> for(Node n : cache.values()) n.visited=false;
<add> // for(Node n : cache.values()) n.visited=false;
<ide> traverse(root);
<ide> out();
<ide> }
<del>
<del>
<ide> }
<ide>
<ide> private static Node node(String key)
<ide> {
<del> key=key.trim();
<del> Node n ;
<del> if(!cache.containsKey(key))
<add> key = key.trim();
<add> Node n = cache.get(key);
<add>
<add> if(n==null)
<ide> {
<del> //System.err.print("creating "+key);
<ide> n = new Node(key);
<ide> cache.put(key, n);
<ide> }
<del> else n = cache.get(key);
<ide>
<ide> return n;
<ide> }
<ide>
<ide> private static void readLine()
<ide> {
<del> line_map[LINES_RED++]=s;
<add> line_map[LINES_RED++] = s;
<ide>
<del> System.err.print("RED LINE : "+s);
<add> //System.err.print("RED LINE : "+s);
<ide> if(s.charAt(0) != 9)
<ide> {
<ide> try
<ide> s="";
<ide> }
<ide>
<del>
<del> private static void printEachLine() throws IOException {
<del> int foo = 0;
<del> char ch = 0;
<del> StringBuilder sb = new StringBuilder();
<del>
<del> boolean isEOL = false; //err, need to set this or get rid of it
<del> do {
<del> foo = bi.read();
<del> ch = (char) foo;
<del> sb.append(ch);
<del>
<del> if ((ch == 10))
<del> {
<del> System.err.print(sb);
<del>
<del> foo = bi.read();
<del> ch = (char) foo;
<del> sb.append(ch);
<del> if (ch != 13)
<del> {
<del> while ((255 > ch) && (ch >= 0))
<del> {
<del> sb = new StringBuilder();
<del> foo = bi.read();
<del> ch = (char) foo;
<del> sb.append(ch);
<del> System.err.print(sb);
<del>
<del> }
<del> }
<del> sb.append(ch);
<del> }
<del>
<del> } while (!isEOL);
<del> }
<del>
<ide> public static String slurp()
<ide> {
<ide>
<ide> s+=(char)current;
<ide>
<ide> if(current == '\n')
<del> {
<ide> readLine();
<del> }
<ide> }
<del> System.out.println("");
<ide> //System.err.println("s "+s);
<ide> //readLine();
<ide> }
<del> catch (UnsupportedEncodingException ex) { System.out.println("ERROR");}
<del> catch (IOException ex) { System.out.println("ERROR");}
<add> catch (UnsupportedEncodingException ex) { System.out.println("ERROR"); }
<add> catch (IOException ex) { System.out.println("ERROR"); }
<ide> return s;
<ide> }
<ide>
<ide> static void out()
<ide> {
<ide> buffer.setLength(0);
<add>
<add> //FIXME set "#" in NODE and get rid of O(n) here
<ide> for(int i=0; i<LINES_RED; i++)
<ide> buffer.append((i==0 || cache.get(relation.get(i)).visited)?(line_map[i]):("#"+line_map[i]));
<add>
<ide> System.out.print(buffer);
<ide> }
<del>
<ide>
<ide> static boolean cycle(Node n)
<ide> {
<ide>
<ide> public static void traverse(Node node)
<ide> {
<del> Queue<Node> q = new LinkedList<Node>();
<add> Queue<Node> q = new LinkedList<Node>();
<ide> q.add(node);
<del> node.visited=true;
<add> node.visited = true;
<ide>
<ide> while(!q.isEmpty())
<ide> {
<ide> {
<ide> if(!adj.visited)
<ide> {
<del> adj.visited=true;
<add> adj.visited = true;
<ide> q.add(adj);
<ide> }
<ide> }
<ide>
<ide> return neighbors;
<ide> }
<del>
<ide> }
<ide>
<ide> class Node
<ide> { this.data = data; }
<ide>
<ide> public java.lang.String toString()
<del> { return data.toString()+"["+(visited?"X":" ")+"]"; }
<add> { return data.toString()+"["+(visited?" ":"#")+"]"; }
<ide>
<ide> }
<ide>
<ide> this.a = a;
<ide> this.b = b;
<ide> }
<del>
<ide> }
|
|
Java
|
apache-2.0
|
6087c7470451e4f913fb00fa08f18f0686632f53
| 0 |
grodin/yacc,grodin/yacc
|
/*
* Copyright 2015 Omricat Software
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.omricat.yacc.debug;
import android.util.Log;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.omricat.yacc.api.CurrenciesService;
import com.omricat.yacc.model.CurrencyDataset;
import java.io.IOException;
import rx.Observable;
/**
* Implementation of CurrenciesService which just returns a static
* CurrencyDataset wrapped in an Observable. This is to be used on the in the
* debug version of the app, as a quick way of getting data into the ui.
*/
public class DebugCurrenciesService implements CurrenciesService {
static final String currencyJson = "{\"currencies\":[{\"code\":\"TMT\"," +
"\"value\":\"3.50\",\"name\":\"Turkmenistani Manat\"}," +
"{\"code\":\"KZT\",\"value\":\"184.285\",\"name\":\"Kazakhstani " +
"Tenge\"},{\"code\":\"BTN\",\"value\":\"61.615\"," +
"\"name\":\"Bhutanese Ngultrum\"},{\"code\":\"CHF\"," +
"\"value\":\"0.8615\",\"name\":\"Swiss Franc\"}," +
"{\"code\":\"MDL\",\"value\":\"17.36\"," +
"\"name\":\"Moldovan Leu\"},{\"code\":\"LVL\"," +
"\"value\":\"0.6064\",\"name\":\"Latvian Lats\"}," +
"{\"code\":\"CDF\",\"value\":\"927.00\",\"name\":\"Congolese " +
"Franc\"},{\"code\":\"XDR\",\"value\":\"0.7038\"," +
"\"name\":\"Special Drawing Rights\"},{\"code\":\"AUD\"," +
"\"value\":\"1.2156\",\"name\":\"Australian Dollar\"}," +
"{\"code\":\"SDG\",\"value\":\"5.6925\"," +
"\"name\":\"Sudanese Pound\"},{\"code\":\"RUB\"," +
"\"value\":\"65.8605\",\"name\":\"Russian Ruble\"}," +
"{\"code\":\"VND\",\"value\":\"21380.00\",\"name\":\"Vietnamese " +
"Dong\"},{\"code\":\"MUR\",\"value\":\"32.45\"," +
"\"name\":\"Mauritian Rupee\"},{\"code\":\"JMD\"," +
"\"value\":\"115.10\",\"name\":\"Jamaican Dollar\"}," +
"{\"code\":\"LBP\",\"value\":\"1510.00\"," +
"\"name\":\"Lebanese Pound\"},{\"code\":\"GBP\"," +
"\"value\":\"0.6613\",\"name\":\"British Pound Sterling\"}," +
"{\"code\":\"CAD\",\"value\":\"1.2069\"," +
"\"name\":\"Canadian Dollar\"},{\"code\":\"MXN\"," +
"\"value\":\"14.6014\",\"name\":\"Mexican Peso\"}," +
"{\"code\":\"HUF\",\"value\":\"271.585\"," +
"\"name\":\"Hungarian Forint\"},{\"code\":\"CNY\"," +
"\"value\":\"6.2101\",\"name\":\"Chinese Yuan\"}," +
"{\"code\":\"COP\",\"value\":\"2376.45\"," +
"\"name\":\"Colombian Peso\"},{\"code\":\"HKD\"," +
"\"value\":\"7.7529\",\"name\":\"Hong Kong Dollar\"}," +
"{\"code\":\"JPY\",\"value\":\"117.367\"," +
"\"name\":\"Japanese Yen\"},{\"code\":\"UZS\"," +
"\"value\":\"2430.1699\",\"name\":\"Uzbekistan Som\"}," +
"{\"code\":\"AZN\",\"value\":\"0.7831\",\"name\":\"Azerbaijani " +
"Manat\"},{\"code\":\"INR\",\"value\":\"61.58\"," +
"\"name\":\"Indian Rupee\"},{\"code\":\"CLF\"," +
"\"value\":\"0.0247\",\"name\":\"Chilean Unit of Account (UF)\"}," +
"{\"code\":\"EUR\",\"value\":\"0.8617\",\"name\":\"Euro\"}," +
"{\"code\":\"IEP\",\"value\":\"0.6795\",\"name\":\"\"}," +
"{\"code\":\"CZK\",\"value\":\"24.078\",\"name\":\"Czech Republic" +
" Koruna\"},{\"code\":\"AMD\",\"value\":\"477.91\"," +
"\"name\":\"Armenian Dram\"},{\"code\":\"XCD\"," +
"\"value\":\"2.70\",\"name\":\"East Caribbean Dollar\"}," +
"{\"code\":\"BYR\",\"value\":\"15090.00\",\"name\":\"Belarusian " +
"Ruble\"},{\"code\":\"XOF\",\"value\":\"565.9925\"," +
"\"name\":\"CFA Franc BCEAO\"},{\"code\":\"TWD\"," +
"\"value\":\"31.492\",\"name\":\"New Taiwan Dollar\"}," +
"{\"code\":\"USD\",\"value\":1,\"name\":\"United States " +
"Dollar\"},{\"code\":\"ZAR\",\"value\":\"11.5518\"," +
"\"name\":\"South African Rand\"},{\"code\":\"NOK\"," +
"\"value\":\"7.6024\",\"name\":\"Norwegian Krone\"}]," +
"\"timestamp\":1421847301}";
final ObjectMapper mapper = new ObjectMapper();
final CurrencyDataset dataset;
public DebugCurrenciesService() {
CurrencyDataset set = null;
try {
set = mapper.readValue(currencyJson,
CurrencyDataset.class);
} catch (IOException e) {
Log.e(this.getClass().getSimpleName(), e.getMessage());
}
if (set == null) {
set = CurrencyDataset.EMPTY;
}
dataset = set;
}
@Override public Observable<CurrencyDataset> getAllCurrencies() {
return Observable.just(dataset);
}
}
|
core/src/main/java/com/omricat/yacc/debug/DebugCurrenciesService.java
|
/*
* Copyright 2015 Omricat Software
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.omricat.yacc.debug;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.omricat.yacc.api.CurrenciesService;
import com.omricat.yacc.model.CurrencyDataset;
import java.io.IOException;
import rx.Observable;
/**
* Implementation of CurrenciesService which just returns a static
* CurrencyDataset wrapped in an Observable. This is to be used on the in the
* debug version of the app, as a quick way of getting data into the ui.
*/
public class DebugCurrenciesService implements CurrenciesService {
static final String currencyJson = "{\"currencies\":[{\"code\":\"TMT\"," +
"\"value\":\"3.50\",\"name\":\"Turkmenistani Manat\"}," +
"{\"code\":\"KZT\",\"value\":\"184.285\",\"name\":\"Kazakhstani " +
"Tenge\"},{\"code\":\"BTN\",\"value\":\"61.615\"," +
"\"name\":\"Bhutanese Ngultrum\"},{\"code\":\"CHF\"," +
"\"value\":\"0.8615\",\"name\":\"Swiss Franc\"}," +
"{\"code\":\"MDL\",\"value\":\"17.36\"," +
"\"name\":\"Moldovan Leu\"},{\"code\":\"LVL\"," +
"\"value\":\"0.6064\",\"name\":\"Latvian Lats\"}," +
"{\"code\":\"CDF\",\"value\":\"927.00\",\"name\":\"Congolese " +
"Franc\"},{\"code\":\"XDR\",\"value\":\"0.7038\"," +
"\"name\":\"Special Drawing Rights\"},{\"code\":\"AUD\"," +
"\"value\":\"1.2156\",\"name\":\"Australian Dollar\"}," +
"{\"code\":\"SDG\",\"value\":\"5.6925\"," +
"\"name\":\"Sudanese Pound\"},{\"code\":\"RUB\"," +
"\"value\":\"65.8605\",\"name\":\"Russian Ruble\"}," +
"{\"code\":\"VND\",\"value\":\"21380.00\",\"name\":\"Vietnamese " +
"Dong\"},{\"code\":\"MUR\",\"value\":\"32.45\"," +
"\"name\":\"Mauritian Rupee\"},{\"code\":\"JMD\"," +
"\"value\":\"115.10\",\"name\":\"Jamaican Dollar\"}," +
"{\"code\":\"LBP\",\"value\":\"1510.00\"," +
"\"name\":\"Lebanese Pound\"},{\"code\":\"GBP\"," +
"\"value\":\"0.6613\",\"name\":\"British Pound Sterling\"}," +
"{\"code\":\"CAD\",\"value\":\"1.2069\"," +
"\"name\":\"Canadian Dollar\"},{\"code\":\"MXN\"," +
"\"value\":\"14.6014\",\"name\":\"Mexican Peso\"}," +
"{\"code\":\"HUF\",\"value\":\"271.585\"," +
"\"name\":\"Hungarian Forint\"},{\"code\":\"CNY\"," +
"\"value\":\"6.2101\",\"name\":\"Chinese Yuan\"}," +
"{\"code\":\"COP\",\"value\":\"2376.45\"," +
"\"name\":\"Colombian Peso\"},{\"code\":\"HKD\"," +
"\"value\":\"7.7529\",\"name\":\"Hong Kong Dollar\"}," +
"{\"code\":\"JPY\",\"value\":\"117.367\"," +
"\"name\":\"Japanese Yen\"},{\"code\":\"UZS\"," +
"\"value\":\"2430.1699\",\"name\":\"Uzbekistan Som\"}," +
"{\"code\":\"AZN\",\"value\":\"0.7831\",\"name\":\"Azerbaijani " +
"Manat\"},{\"code\":\"INR\",\"value\":\"61.58\"," +
"\"name\":\"Indian Rupee\"},{\"code\":\"CLF\"," +
"\"value\":\"0.0247\",\"name\":\"Chilean Unit of Account (UF)\"}," +
"{\"code\":\"EUR\",\"value\":\"0.8617\",\"name\":\"Euro\"}," +
"{\"code\":\"IEP\",\"value\":\"0.6795\",\"name\":\"\"}," +
"{\"code\":\"CZK\",\"value\":\"24.078\",\"name\":\"Czech Republic" +
" Koruna\"},{\"code\":\"AMD\",\"value\":\"477.91\"," +
"\"name\":\"Armenian Dram\"},{\"code\":\"XCD\"," +
"\"value\":\"2.70\",\"name\":\"East Caribbean Dollar\"}," +
"{\"code\":\"BYR\",\"value\":\"15090.00\",\"name\":\"Belarusian " +
"Ruble\"},{\"code\":\"XOF\",\"value\":\"565.9925\"," +
"\"name\":\"CFA Franc BCEAO\"},{\"code\":\"TWD\"," +
"\"value\":\"31.492\",\"name\":\"New Taiwan Dollar\"}," +
"{\"code\":\"USD\",\"value\":1,\"name\":\"United States " +
"Dollar\"},{\"code\":\"ZAR\",\"value\":\"11.5518\"," +
"\"name\":\"South African Rand\"},{\"code\":\"NOK\"," +
"\"value\":\"7.6024\",\"name\":\"Norwegian Krone\"}]," +
"\"timestamp\":1421847301}";
final ObjectMapper mapper = new ObjectMapper();
final CurrencyDataset dataset;
public DebugCurrenciesService() throws IOException {
dataset = mapper.readValue(currencyJson, CurrencyDataset.class);
}
@Override public Observable<CurrencyDataset> getAllCurrencies() {
return Observable.just(dataset);
}
}
|
Modified DebugCurrenciesService so that it catches exceptions and just provides an empty CurrencyDataSet if anything is caught.
|
core/src/main/java/com/omricat/yacc/debug/DebugCurrenciesService.java
|
Modified DebugCurrenciesService so that it catches exceptions and just provides an empty CurrencyDataSet if anything is caught.
|
<ide><path>ore/src/main/java/com/omricat/yacc/debug/DebugCurrenciesService.java
<ide> */
<ide>
<ide> package com.omricat.yacc.debug;
<add>
<add>import android.util.Log;
<ide>
<ide> import com.fasterxml.jackson.databind.ObjectMapper;
<ide> import com.omricat.yacc.api.CurrenciesService;
<ide>
<ide> final CurrencyDataset dataset;
<ide>
<del> public DebugCurrenciesService() throws IOException {
<del> dataset = mapper.readValue(currencyJson, CurrencyDataset.class);
<add> public DebugCurrenciesService() {
<add> CurrencyDataset set = null;
<add> try {
<add> set = mapper.readValue(currencyJson,
<add> CurrencyDataset.class);
<add> } catch (IOException e) {
<add> Log.e(this.getClass().getSimpleName(), e.getMessage());
<add> }
<add> if (set == null) {
<add> set = CurrencyDataset.EMPTY;
<add> }
<add> dataset = set;
<ide> }
<ide>
<ide>
|
|
Java
|
apache-2.0
|
error: pathspec 'visor-sensors/src/main/java/de/uniulm/omi/cloudiator/visor/sensors/cassandra/CassandraSensor.java' did not match any file(s) known to git
|
6a62a557532d39562f5a711e26f96b64d8a11752
| 1 |
cloudiator/visor,cloudiator/visor
|
package de.uniulm.omi.cloudiator.visor.sensors.cassandra;
import com.google.common.collect.ImmutableMap;
import de.uniulm.omi.cloudiator.visor.exceptions.MeasurementNotAvailableException;
import de.uniulm.omi.cloudiator.visor.exceptions.SensorInitializationException;
import de.uniulm.omi.cloudiator.visor.monitoring.*;
import javax.management.*;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.function.Supplier;
/**
* Created by Daniel Seybold on 20.06.2016.
*/
public class CassandraSensor extends AbstractSensor {
private static final String CASSANDRA_IP = "cassandra.ip";
private static final String CASSANDRA_PORT = "cassandra.port";
private final static String CASSANDRA_METRIC = "cassandra.metric";
private Optional<String> cassandraIp;
private Optional<String> cassandraPort;
private JMXServiceURL cassandraMonitoringUrl;
private JMXConnector jmxConnector;
private MBeanServerConnection mBeanServerConnection;
private Measureable metric;
private static class Measurables implements Measureable {
public static Measureable of(String string) {
try {
return RawMetric.valueOf(string);
} catch (IllegalArgumentException ignored) {
}
/*
//currently no composite metrics implemented
try {
return CompositeMetric.valueOf(string);
} catch (IllegalArgumentException ignored) {
}
*/
throw new IllegalArgumentException(
String.format("Could not find metric with name %s", string));
}
@Override public Measurement measure(Map<RawMetric, Measurement> old,
Map<RawMetric, Measurement> current) {
return null;
}
}
private enum RawMetric implements CassandraMetric, Measureable {
TOTAL_DISK_SPACE_USED {
@Override
public String string() {
return "org.apache.cassandra.metrics:type=ColumnFamily,name=TotalDiskSpaceUsed";
}
@Override
public Object toType(String value) {
return Long.valueOf(value);
}
@Override
public String valueType() {
return "Value";
}
};
@Override
public Measurement measure(Map<RawMetric, Measurement> old, Map<RawMetric, Measurement> current) throws MeasurementNotAvailableException {
return current.get(this);
}
}
private interface CassandraMetric{
String string();
Object toType(String value);
String valueType();
}
private interface Measureable {
Measurement measure(Map<RawMetric, Measurement> old, Map<RawMetric, Measurement> current)
throws MeasurementNotAvailableException;
}
@Override protected void initialize(MonitorContext monitorContext,
SensorConfiguration sensorConfiguration) throws SensorInitializationException {
super.initialize(monitorContext, sensorConfiguration);
this.cassandraIp = sensorConfiguration.getValue(CASSANDRA_IP);
this.cassandraPort = sensorConfiguration.getValue(CASSANDRA_PORT);
try {
this.cassandraMonitoringUrl = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://"+this.cassandraIp.get()+":"+this.cassandraPort.get()+"/jmxrmi");
this.jmxConnector = JMXConnectorFactory.connect(this.cassandraMonitoringUrl, null);
this.mBeanServerConnection = this.jmxConnector.getMBeanServerConnection();
} catch (MalformedURLException e) {
throw new SensorInitializationException(
"Url provided for Cassandra stats is malformed", e);
}catch (IOException e){
throw new SensorInitializationException("Unable to create MBean connection", e);
}
try {
this.metric = Measurables.of(sensorConfiguration.getValue(CASSANDRA_METRIC).orElseThrow(
() -> new SensorInitializationException(
"Configuration parameter " + CASSANDRA_METRIC + " is required")));
} catch (IllegalArgumentException e) {
throw new SensorInitializationException(e);
}
}
@Override
protected Measurement measure() throws MeasurementNotAvailableException {
return metric.measure(new RawMetricSupplier(this.mBeanServerConnection).get(),new RawMetricSupplier(this.mBeanServerConnection).get());
}
private interface MetricSupplier<T>{
T get() throws MeasurementNotAvailableException;
}
private static class RawMetricSupplier implements MetricSupplier<Map<RawMetric, Measurement>>{
private final MBeanServerConnection mBeanServerConnection;
private RawMetricSupplier(MBeanServerConnection mBeanServerConnection){
this.mBeanServerConnection = mBeanServerConnection;
}
@Override
public Map<RawMetric, Measurement> get() throws MeasurementNotAvailableException {
Map<RawMetric, Measurement> measurements = new HashMap<>(RawMetric.values().length);
try {
for (RawMetric rawMetric : RawMetric.values()) {
ObjectName mbeanObjectName = new ObjectName(rawMetric.string());
String valueType = rawMetric.valueType();
String mbeanValue = this.mBeanServerConnection.getAttribute(mbeanObjectName, valueType).toString();
measurements.put(rawMetric, MeasurementBuilder.newBuilder().now().value(rawMetric.toType(mbeanValue)).build());
}
} catch (IOException | MalformedObjectNameException | AttributeNotFoundException | InstanceNotFoundException |ReflectionException | MBeanException e) {
throw new MeasurementNotAvailableException(e);
}
return ImmutableMap.copyOf(measurements);
}
}
}
|
visor-sensors/src/main/java/de/uniulm/omi/cloudiator/visor/sensors/cassandra/CassandraSensor.java
|
PS-192 implemented cassandra sensor, total disk space used
|
visor-sensors/src/main/java/de/uniulm/omi/cloudiator/visor/sensors/cassandra/CassandraSensor.java
|
PS-192 implemented cassandra sensor, total disk space used
|
<ide><path>isor-sensors/src/main/java/de/uniulm/omi/cloudiator/visor/sensors/cassandra/CassandraSensor.java
<add>package de.uniulm.omi.cloudiator.visor.sensors.cassandra;
<add>
<add>import com.google.common.collect.ImmutableMap;
<add>import de.uniulm.omi.cloudiator.visor.exceptions.MeasurementNotAvailableException;
<add>import de.uniulm.omi.cloudiator.visor.exceptions.SensorInitializationException;
<add>import de.uniulm.omi.cloudiator.visor.monitoring.*;
<add>
<add>import javax.management.*;
<add>import javax.management.remote.JMXConnector;
<add>import javax.management.remote.JMXConnectorFactory;
<add>import javax.management.remote.JMXServiceURL;
<add>import java.io.IOException;
<add>import java.net.MalformedURLException;
<add>import java.util.HashMap;
<add>import java.util.Map;
<add>import java.util.Optional;
<add>import java.util.function.Supplier;
<add>
<add>/**
<add> * Created by Daniel Seybold on 20.06.2016.
<add> */
<add>public class CassandraSensor extends AbstractSensor {
<add>
<add> private static final String CASSANDRA_IP = "cassandra.ip";
<add> private static final String CASSANDRA_PORT = "cassandra.port";
<add> private final static String CASSANDRA_METRIC = "cassandra.metric";
<add>
<add> private Optional<String> cassandraIp;
<add> private Optional<String> cassandraPort;
<add>
<add> private JMXServiceURL cassandraMonitoringUrl;
<add> private JMXConnector jmxConnector;
<add> private MBeanServerConnection mBeanServerConnection;
<add>
<add> private Measureable metric;
<add>
<add> private static class Measurables implements Measureable {
<add>
<add> public static Measureable of(String string) {
<add> try {
<add> return RawMetric.valueOf(string);
<add> } catch (IllegalArgumentException ignored) {
<add> }
<add>
<add> /*
<add> //currently no composite metrics implemented
<add> try {
<add> return CompositeMetric.valueOf(string);
<add> } catch (IllegalArgumentException ignored) {
<add>
<add> }
<add> */
<add>
<add> throw new IllegalArgumentException(
<add> String.format("Could not find metric with name %s", string));
<add> }
<add>
<add> @Override public Measurement measure(Map<RawMetric, Measurement> old,
<add> Map<RawMetric, Measurement> current) {
<add> return null;
<add> }
<add> }
<add>
<add>
<add> private enum RawMetric implements CassandraMetric, Measureable {
<add> TOTAL_DISK_SPACE_USED {
<add>
<add> @Override
<add> public String string() {
<add> return "org.apache.cassandra.metrics:type=ColumnFamily,name=TotalDiskSpaceUsed";
<add> }
<add>
<add> @Override
<add> public Object toType(String value) {
<add> return Long.valueOf(value);
<add> }
<add>
<add> @Override
<add> public String valueType() {
<add> return "Value";
<add> }
<add>
<add> };
<add>
<add>
<add> @Override
<add> public Measurement measure(Map<RawMetric, Measurement> old, Map<RawMetric, Measurement> current) throws MeasurementNotAvailableException {
<add> return current.get(this);
<add> }
<add> }
<add>
<add> private interface CassandraMetric{
<add> String string();
<add>
<add> Object toType(String value);
<add>
<add> String valueType();
<add>
<add>
<add> }
<add>
<add> private interface Measureable {
<add> Measurement measure(Map<RawMetric, Measurement> old, Map<RawMetric, Measurement> current)
<add> throws MeasurementNotAvailableException;
<add> }
<add>
<add> @Override protected void initialize(MonitorContext monitorContext,
<add> SensorConfiguration sensorConfiguration) throws SensorInitializationException {
<add> super.initialize(monitorContext, sensorConfiguration);
<add>
<add> this.cassandraIp = sensorConfiguration.getValue(CASSANDRA_IP);
<add> this.cassandraPort = sensorConfiguration.getValue(CASSANDRA_PORT);
<add>
<add>
<add> try {
<add> this.cassandraMonitoringUrl = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://"+this.cassandraIp.get()+":"+this.cassandraPort.get()+"/jmxrmi");
<add> this.jmxConnector = JMXConnectorFactory.connect(this.cassandraMonitoringUrl, null);
<add> this.mBeanServerConnection = this.jmxConnector.getMBeanServerConnection();
<add>
<add> } catch (MalformedURLException e) {
<add> throw new SensorInitializationException(
<add> "Url provided for Cassandra stats is malformed", e);
<add> }catch (IOException e){
<add> throw new SensorInitializationException("Unable to create MBean connection", e);
<add> }
<add>
<add> try {
<add> this.metric = Measurables.of(sensorConfiguration.getValue(CASSANDRA_METRIC).orElseThrow(
<add> () -> new SensorInitializationException(
<add> "Configuration parameter " + CASSANDRA_METRIC + " is required")));
<add> } catch (IllegalArgumentException e) {
<add> throw new SensorInitializationException(e);
<add> }
<add>
<add>
<add> }
<add>
<add> @Override
<add> protected Measurement measure() throws MeasurementNotAvailableException {
<add>
<add> return metric.measure(new RawMetricSupplier(this.mBeanServerConnection).get(),new RawMetricSupplier(this.mBeanServerConnection).get());
<add>
<add>
<add> }
<add>
<add> private interface MetricSupplier<T>{
<add>
<add> T get() throws MeasurementNotAvailableException;
<add> }
<add>
<add> private static class RawMetricSupplier implements MetricSupplier<Map<RawMetric, Measurement>>{
<add>
<add> private final MBeanServerConnection mBeanServerConnection;
<add>
<add> private RawMetricSupplier(MBeanServerConnection mBeanServerConnection){
<add> this.mBeanServerConnection = mBeanServerConnection;
<add> }
<add>
<add> @Override
<add> public Map<RawMetric, Measurement> get() throws MeasurementNotAvailableException {
<add> Map<RawMetric, Measurement> measurements = new HashMap<>(RawMetric.values().length);
<add> try {
<add>
<add> for (RawMetric rawMetric : RawMetric.values()) {
<add>
<add> ObjectName mbeanObjectName = new ObjectName(rawMetric.string());
<add> String valueType = rawMetric.valueType();
<add> String mbeanValue = this.mBeanServerConnection.getAttribute(mbeanObjectName, valueType).toString();
<add>
<add> measurements.put(rawMetric, MeasurementBuilder.newBuilder().now().value(rawMetric.toType(mbeanValue)).build());
<add> }
<add>
<add>
<add>
<add> } catch (IOException | MalformedObjectNameException | AttributeNotFoundException | InstanceNotFoundException |ReflectionException | MBeanException e) {
<add>
<add> throw new MeasurementNotAvailableException(e);
<add>
<add> }
<add> return ImmutableMap.copyOf(measurements);
<add>
<add> }
<add> }
<add>}
|
|
Java
|
apache-2.0
|
bab1c6bcd1463a86d6dba7c9b744b1cc2932c9ac
| 0 |
barancev/webdriver-factory
|
/*
* Copyright 2013 Alexei Barantsev
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package ru.st.selenium.wrapper;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.net.URL;
import java.util.HashSet;
import java.util.List;
import java.util.ListIterator;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.*;
import org.openqa.selenium.interactions.internal.Coordinates;
import org.openqa.selenium.internal.Locatable;
import org.openqa.selenium.internal.WrapsDriver;
import org.openqa.selenium.internal.WrapsElement;
import org.openqa.selenium.logging.Logs;
import org.openqa.selenium.security.Credentials;
/**
* This class allows to extend WebDriver by adding new functionality to a wrapper.
* Example of use:
* <code><pre>
* WebDriver driver = WebDriverWrapper.wrapDriver(originalDriver, MyWebDriverWrapper.class);
* </pre></code>
* or
* <code><pre>
* MyWebDriverWrapper wrapper = new MyWebDriverWrapper(originalDriver, otherParameter);
* WebDriver driver = wrapper.getDriver();
* </pre></code>
*/
public class WebDriverWrapper implements WebDriver, WrapsDriver, JavascriptExecutor {
private final WebDriver originalDriver;
private WebDriver enhancedDriver = null;
public WebDriverWrapper(WebDriver driver) {
originalDriver = driver;
}
protected Class<? extends WebElementWrapper> getElementWrapperClass() {
return WebElementWrapper.class;
}
protected WebElement wrapElement(final WebElement element) {
return WebElementWrapper.wrapElement(this, element, getElementWrapperClass());
}
private List<WebElement> wrapElements(final List<WebElement> elements) {
for (ListIterator<WebElement> iterator = elements.listIterator(); iterator.hasNext(); ) {
iterator.set(wrapElement(iterator.next()));
}
return elements;
}
protected Class<? extends TargetLocatorWrapper> getTargetLocatorWrapperClass() {
return TargetLocatorWrapper.class;
}
private TargetLocator wrapTargetLocator(final TargetLocator targetLocator) {
return TargetLocatorWrapper.wrapTargetLocator(this, targetLocator, getTargetLocatorWrapperClass());
}
protected Class<? extends AlertWrapper> getAlertWrapperClass() {
return AlertWrapper.class;
}
private Alert wrapAlert(final Alert alert) {
return AlertWrapper.wrapAlert(this, alert, getAlertWrapperClass());
}
protected Class<? extends NavigationWrapper> getNavigationWrapperClass() {
return NavigationWrapper.class;
}
private Navigation wrapNavigation(final Navigation navigator) {
return NavigationWrapper.wrapNavigation(this, navigator, getNavigationWrapperClass());
}
protected Class<? extends OptionsWrapper> getOptionsWrapperClass() {
return OptionsWrapper.class;
}
private Options wrapOptions(final Options options) {
return OptionsWrapper.wrapOptions(this, options, getOptionsWrapperClass());
}
protected Class<? extends TimeoutsWrapper> getTimeoutsWrapperClass() {
return TimeoutsWrapper.class;
}
private Timeouts wrapTimeouts(final Timeouts timeouts) {
return TimeoutsWrapper.wrapTimeouts(this, timeouts, getTimeoutsWrapperClass());
}
protected Class<? extends WindowWrapper> getWindowWrapperClass() {
return WindowWrapper.class;
}
private Window wrapWindow(final Window window) {
return WindowWrapper.wrapWindow(this, window, getWindowWrapperClass());
}
protected Class<? extends CoordinatesWrapper> getCoordinatesWrapperClass() {
return CoordinatesWrapper.class;
}
private Coordinates wrapCoordinates(final Coordinates coordinates) {
return CoordinatesWrapper.wrapCoordinates(this, coordinates, getCoordinatesWrapperClass());
}
// TODO: implement proper wrapping for arbitrary objects
private Object wrapObject(final Object object) {
if (object instanceof WebElement) {
return wrapElement((WebElement) object);
} else {
return object;
}
}
@Override
public final WebDriver getWrappedDriver() {
return originalDriver;
}
@Override
public void get(String url) {
getWrappedDriver().get(url);
}
@Override
public String getCurrentUrl() {
return getWrappedDriver().getCurrentUrl();
}
@Override
public String getTitle() {
return getWrappedDriver().getTitle();
}
@Override
public WebElement findElement(final By by) {
return wrapElement(getWrappedDriver().findElement(by));
}
@Override
public List<WebElement> findElements(final By by) {
return wrapElements(getWrappedDriver().findElements(by));
}
@Override
public String getPageSource() {
return getWrappedDriver().getPageSource();
}
@Override
public void close() {
getWrappedDriver().close();
}
@Override
public void quit() {
getWrappedDriver().quit();
}
@Override
public Set<String> getWindowHandles() {
return getWrappedDriver().getWindowHandles();
}
@Override
public String getWindowHandle() {
return getWrappedDriver().getWindowHandle();
}
@Override
public TargetLocator switchTo() {
return wrapTargetLocator(getWrappedDriver().switchTo());
}
@Override
public Navigation navigate() {
return wrapNavigation(getWrappedDriver().navigate());
}
@Override
public Options manage() {
return wrapOptions(getWrappedDriver().manage());
}
@Override
public Object executeScript(String script, Object... args) {
WebDriver driver = getWrappedDriver();
if (driver instanceof JavascriptExecutor) {
return wrapObject(((JavascriptExecutor) driver).executeScript(script, args));
} else {
throw new WebDriverException("Wrapped webdriver does not support JavascriptExecutor: " + driver);
}
}
@Override
public Object executeAsyncScript(String script, Object... args) {
WebDriver driver = getWrappedDriver();
if (driver instanceof JavascriptExecutor) {
return wrapObject(((JavascriptExecutor) driver).executeAsyncScript(script, args));
} else {
throw new WebDriverException("Wrapped webdriver does not support JavascriptExecutor: " + driver);
}
}
/**
* Builds a {@link Proxy} implementing all interfaces of original driver. It will delegate calls to
* wrapper when wrapper implements the requested method otherwise to original driver.
*
* @param driver the underlying driver
* @param wrapperClass the class of a wrapper
*/
public final static WebDriver wrapDriver(final WebDriver driver, final Class<? extends WebDriverWrapper> wrapperClass) {
WebDriverWrapper wrapper = null;
try {
wrapper = wrapperClass.getConstructor(WebDriver.class).newInstance(driver);
} catch (NoSuchMethodException e) {
throw new Error("Wrapper class should provide a constructor with a single WebDriver parameter", e);
} catch (Exception e) {
throw new Error("Can't create a new wrapper object", e);
}
return wrapper.getDriver();
}
/**
* Builds a {@link Proxy} implementing all interfaces of original driver. It will delegate calls to
* wrapper when wrapper implements the requested method otherwise to original driver.
*/
public final WebDriver getDriver() {
if (enhancedDriver != null) {
return enhancedDriver;
}
final WebDriver driver = getWrappedDriver();
final Set<Class<?>> wrapperInterfaces = extractInterfaces(this);
final InvocationHandler handler = new InvocationHandler() {
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
try {
if (wrapperInterfaces.contains(method.getDeclaringClass())) {
beforeMethod(method, args);
Object result = callMethod(method, args);
afterMethod(method, result, args);
return result;
}
return method.invoke(driver, args);
} catch (InvocationTargetException e) {
onError(method, e, args);
throw e.getTargetException();
}
}
};
Set<Class<?>> allInterfaces = extractInterfaces(driver);
allInterfaces.addAll(wrapperInterfaces);
Class<?>[] allInterfacesArray = allInterfaces.toArray(new Class<?>[allInterfaces.size()]);
enhancedDriver = (WebDriver) Proxy.newProxyInstance(
this.getClass().getClassLoader(),
allInterfaces.toArray(allInterfacesArray),
handler);
return enhancedDriver;
}
protected void beforeMethod(Method method, Object[] args) {
}
protected Object callMethod(Method method, Object[] args) throws Throwable {
return method.invoke(this, args);
}
protected void afterMethod(Method method, Object res, Object[] args) {
}
protected void onError(Method method, InvocationTargetException e, Object[] args) {
}
/**
* Simple {@link WrapsElement} delegating all calls to the wrapped {@link WebElement}.
* The methods {@link WebDriverWrapper#wrapElement(WebElement)}/{@link WebDriverWrapper#wrapElements(List<WebElement>)} will
* be called on the related {@link WebDriverWrapper} to wrap the elements returned by {@link #findElement(By)}/{@link #findElements(By)}.
*/
public static class WebElementWrapper implements WebElement, WrapsElement {
private final WebElement originalElement;
private final WebDriverWrapper driverWrapper;
public WebElementWrapper(final WebDriverWrapper driverWrapper, final WebElement element) {
originalElement = element;
this.driverWrapper = driverWrapper;
}
@Override
public final WebElement getWrappedElement() {
return originalElement;
}
private WebDriverWrapper getDriverWrapper() {
return driverWrapper;
}
@Override
public void click() {
getWrappedElement().click();
}
@Override
public void submit() {
getWrappedElement().submit();
}
@Override
public void sendKeys(final CharSequence... keysToSend) {
getWrappedElement().sendKeys(keysToSend);
}
@Override
public void clear() {
getWrappedElement().clear();
}
@Override
public String getTagName() {
return getWrappedElement().getTagName();
}
@Override
public String getAttribute(final String name) {
return getWrappedElement().getAttribute(name);
}
@Override
public boolean isSelected() {
return getWrappedElement().isSelected();
}
@Override
public boolean isEnabled() {
return getWrappedElement().isEnabled();
}
@Override
public String getText() {
return getWrappedElement().getText();
}
@Override
public List<WebElement> findElements(final By by) {
return getDriverWrapper().wrapElements(getWrappedElement().findElements(by));
}
@Override
public WebElement findElement(final By by) {
return getDriverWrapper().wrapElement(getWrappedElement().findElement(by));
}
@Override
public boolean isDisplayed() {
return getWrappedElement().isDisplayed();
}
@Override
public Point getLocation() {
return getWrappedElement().getLocation();
}
@Override
public Dimension getSize() {
return getWrappedElement().getSize();
}
@Override
public String getCssValue(final String propertyName) {
return getWrappedElement().getCssValue(propertyName);
}
public Coordinates getCoordinates() {
Locatable locatable = (Locatable) getWrappedElement();
return getDriverWrapper().wrapCoordinates(locatable.getCoordinates());
}
/**
* Builds a {@link Proxy} implementing all interfaces of original element. It will delegate calls to
* wrapper when wrapper implements the requested method otherwise to original element.
*
* @param driverWrapper the underlying driver's wrapper
* @param element the underlying element
* @param wrapperClass the class of a wrapper
*/
public final static WebElement wrapElement(final WebDriverWrapper driverWrapper, final WebElement element, final Class<? extends WebElementWrapper> wrapperClass) {
WebElementWrapper wrapper = null;
Constructor<? extends WebElementWrapper> constructor = null;
if (wrapperClass.getEnclosingClass() != null) {
try {
constructor = wrapperClass.getConstructor(wrapperClass.getEnclosingClass(), WebElement.class);
} catch (Exception e) {
}
}
if (constructor == null) {
try {
constructor = wrapperClass.getConstructor(WebDriverWrapper.class, WebElement.class);
} catch (Exception e) {
}
}
if (constructor == null) {
throw new Error("Element wrapper class " + wrapperClass + " does not provide an appropriate constructor");
}
try {
wrapper = constructor.newInstance(driverWrapper, element);
} catch (Exception e) {
throw new Error("Can't create a new wrapper object", e);
}
return wrapper.getElement();
}
/**
* Builds a {@link Proxy} implementing all interfaces of original element. It will delegate calls to
* wrapper when wrapper implements the requested method otherwise to original element.
*/
public final WebElement getElement() {
final WebElement element = getWrappedElement();
final Set<Class<?>> wrapperInterfaces = extractInterfaces(this);
final InvocationHandler handler = new InvocationHandler() {
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
try {
if (wrapperInterfaces.contains(method.getDeclaringClass())) {
beforeMethod(method, args);
Object result = callMethod(method, args);
afterMethod(method, result, args);
return result;
}
return method.invoke(element, args);
} catch (InvocationTargetException e) {
onError(method, e, args);
throw e.getTargetException();
}
}
};
Set<Class<?>> allInterfaces = extractInterfaces(element);
allInterfaces.addAll(wrapperInterfaces);
Class<?>[] allInterfacesArray = allInterfaces.toArray(new Class<?>[allInterfaces.size()]);
return (WebElement) Proxy.newProxyInstance(
this.getClass().getClassLoader(),
allInterfaces.toArray(allInterfacesArray),
handler);
}
protected void beforeMethod(Method method, Object[] args) {
}
protected Object callMethod(Method method, Object[] args) throws Throwable {
return method.invoke(this, args);
}
protected void afterMethod(Method method, Object res, Object[] args) {
}
protected void onError(Method method, InvocationTargetException e, Object[] args) {
}
}
public static class TargetLocatorWrapper implements TargetLocator {
private final TargetLocator originalTargetLocator;
private final WebDriverWrapper driverWrapper;
public TargetLocatorWrapper(final WebDriverWrapper driverWrapper, final TargetLocator targetLocator) {
originalTargetLocator = targetLocator;
this.driverWrapper = driverWrapper;
}
public final TargetLocator getWrappedTargetLocator() {
return originalTargetLocator;
}
private final WebDriverWrapper getDriverWrapper() {
return driverWrapper;
}
@Override
public WebDriver frame(int frameIndex) {
getWrappedTargetLocator().frame(frameIndex);
return getDriverWrapper().getDriver();
}
@Override
public WebDriver frame(String frameName) {
getWrappedTargetLocator().frame(frameName);
return getDriverWrapper().getDriver();
}
@Override
public WebDriver frame(WebElement frameElement) {
getWrappedTargetLocator().frame(frameElement);
return getDriverWrapper().getDriver();
}
@Override
public WebDriver window(String windowName) {
getWrappedTargetLocator().window(windowName);
return getDriverWrapper().getDriver();
}
@Override
public WebDriver defaultContent() {
getWrappedTargetLocator().defaultContent();
return getDriverWrapper().getDriver();
}
@Override
public WebElement activeElement() {
return getDriverWrapper().wrapElement(getWrappedTargetLocator().activeElement());
}
@Override
public Alert alert() {
return getDriverWrapper().wrapAlert(getWrappedTargetLocator().alert());
}
/**
* Builds a {@link Proxy} implementing all interfaces of original target locator. It will delegate calls to
* wrapper when wrapper implements the requested method otherwise to original target locator.
*
* @param driverWrapper the underlying driver's wrapper
* @param targetLocator the underlying target locator
* @param wrapperClass the class of a wrapper
*/
public final static TargetLocator wrapTargetLocator(final WebDriverWrapper driverWrapper, final TargetLocator targetLocator, final Class<? extends TargetLocatorWrapper> wrapperClass) {
TargetLocatorWrapper wrapper = null;
Constructor<? extends TargetLocatorWrapper> constructor = null;
if (wrapperClass.getEnclosingClass() != null) {
try {
constructor = wrapperClass.getConstructor(wrapperClass.getEnclosingClass(), TargetLocator.class);
} catch (Exception e) {
}
}
if (constructor == null) {
try {
constructor = wrapperClass.getConstructor(WebDriverWrapper.class, TargetLocator.class);
} catch (Exception e) {
}
}
if (constructor == null) {
throw new Error("Element wrapper class " + wrapperClass + " does not provide an appropriate constructor");
}
try {
wrapper = constructor.newInstance(driverWrapper, targetLocator);
} catch (Exception e) {
throw new Error("Can't create a new wrapper object", e);
}
return wrapper.getTargetLocator();
}
/**
* Builds a {@link Proxy} implementing all interfaces of original target locator. It will delegate calls to
* wrapper when wrapper implements the requested method otherwise to original target locator.
*/
public final TargetLocator getTargetLocator() {
final TargetLocator targetLocator = getWrappedTargetLocator();
final Set<Class<?>> wrapperInterfaces = extractInterfaces(this);
final InvocationHandler handler = new InvocationHandler() {
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
try {
if (wrapperInterfaces.contains(method.getDeclaringClass())) {
beforeMethod(method, args);
Object result = callMethod(method, args);
afterMethod(method, result, args);
return result;
}
return method.invoke(targetLocator, args);
} catch (InvocationTargetException e) {
onError(method, e, args);
throw e.getTargetException();
}
}
};
Set<Class<?>> allInterfaces = extractInterfaces(targetLocator);
allInterfaces.addAll(wrapperInterfaces);
Class<?>[] allInterfacesArray = allInterfaces.toArray(new Class<?>[allInterfaces.size()]);
return (TargetLocator) Proxy.newProxyInstance(
this.getClass().getClassLoader(),
allInterfaces.toArray(allInterfacesArray),
handler);
}
protected void beforeMethod(Method method, Object[] args) {
}
protected Object callMethod(Method method, Object[] args) throws Throwable {
return method.invoke(this, args);
}
protected void afterMethod(Method method, Object res, Object[] args) {
}
protected void onError(Method method, InvocationTargetException e, Object[] args) {
}
}
public static class NavigationWrapper implements Navigation {
private final Navigation originalNavigator;
private final WebDriverWrapper driverWrapper;
public NavigationWrapper(final WebDriverWrapper driverWrapper, final Navigation navigator) {
originalNavigator = navigator;
this.driverWrapper = driverWrapper;
}
public final Navigation getWrappedNavigation() {
return originalNavigator;
}
private WebDriverWrapper getDriverWrapper() {
return driverWrapper;
}
@Override
public void to(String url) {
getWrappedNavigation().to(url);
}
@Override
public void to(URL url) {
getWrappedNavigation().to(url);
}
@Override
public void back() {
getWrappedNavigation().back();
}
@Override
public void forward() {
getWrappedNavigation().forward();
}
@Override
public void refresh() {
getWrappedNavigation().refresh();
}
/**
* Builds a {@link Proxy} implementing all interfaces of original navigator. It will delegate calls to
* wrapper when wrapper implements the requested method otherwise to original navigator.
*
* @param driverWrapper the underlying driver's wrapper
* @param navigator the underlying navigator
* @param wrapperClass the class of a wrapper
*/
public final static Navigation wrapNavigation(final WebDriverWrapper driverWrapper, final Navigation navigator, final Class<? extends NavigationWrapper> wrapperClass) {
NavigationWrapper wrapper = null;
Constructor<? extends NavigationWrapper> constructor = null;
if (wrapperClass.getEnclosingClass() != null) {
try {
constructor = wrapperClass.getConstructor(wrapperClass.getEnclosingClass(), Navigation.class);
} catch (Exception e) {
}
}
if (constructor == null) {
try {
constructor = wrapperClass.getConstructor(WebDriverWrapper.class, Navigation.class);
} catch (Exception e) {
}
}
if (constructor == null) {
throw new Error("Element wrapper class " + wrapperClass + " does not provide an appropriate constructor");
}
try {
wrapper = constructor.newInstance(driverWrapper, navigator);
} catch (Exception e) {
throw new Error("Can't create a new wrapper object", e);
}
return wrapper.wrapNavigation();
}
/**
* Builds a {@link Proxy} implementing all interfaces of original navigator. It will delegate calls to
* wrapper when wrapper implements the requested method otherwise to original navigator.
*/
public final Navigation wrapNavigation() {
final Navigation navigator = getWrappedNavigation();
final Set<Class<?>> wrapperInterfaces = extractInterfaces(this);
final InvocationHandler handler = new InvocationHandler() {
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
try {
if (wrapperInterfaces.contains(method.getDeclaringClass())) {
beforeMethod(method, args);
Object result = callMethod(method, args);
afterMethod(method, result, args);
return result;
}
return method.invoke(navigator, args);
} catch (InvocationTargetException e) {
onError(method, e, args);
throw e.getTargetException();
}
}
};
Set<Class<?>> allInterfaces = extractInterfaces(navigator);
allInterfaces.addAll(wrapperInterfaces);
Class<?>[] allInterfacesArray = allInterfaces.toArray(new Class<?>[allInterfaces.size()]);
return (Navigation) Proxy.newProxyInstance(
this.getClass().getClassLoader(),
allInterfaces.toArray(allInterfacesArray),
handler);
}
protected void beforeMethod(Method method, Object[] args) {
}
protected Object callMethod(Method method, Object[] args) throws Throwable {
return method.invoke(this, args);
}
protected void afterMethod(Method method, Object res, Object[] args) {
}
protected void onError(Method method, InvocationTargetException e, Object[] args) {
}
}
public static class AlertWrapper implements Alert {
private final Alert originalAlert;
private final WebDriverWrapper driverWrapper;
public AlertWrapper(final WebDriverWrapper driverWrapper, final Alert alert) {
originalAlert = alert;
this.driverWrapper = driverWrapper;
}
public final Alert getWrappedAlert() {
return originalAlert;
}
private WebDriverWrapper getDriverWrapper() {
return driverWrapper;
}
@Override
public void accept() {
getWrappedAlert().accept();
}
@Override
@Beta
public void authenticateUsing(Credentials creds) {
getWrappedAlert().authenticateUsing(creds);
}
@Override
public void dismiss() {
getWrappedAlert().dismiss();
}
@Override
public String getText() {
return getWrappedAlert().getText();
}
@Override
public void sendKeys(String text) {
getWrappedAlert().sendKeys(text);
}
/**
* Builds a {@link Proxy} implementing all interfaces of original alert. It will delegate calls to
* wrapper when wrapper implements the requested method otherwise to original alert.
*
* @param driverWrapper the underlying driver's wrapper
* @param alert the underlying alert
* @param wrapperClass the class of a wrapper
*/
public final static Alert wrapAlert(final WebDriverWrapper driverWrapper, final Alert alert, final Class<? extends AlertWrapper> wrapperClass) {
AlertWrapper wrapper = null;
Constructor<? extends AlertWrapper> constructor = null;
if (wrapperClass.getEnclosingClass() != null) {
try {
constructor = wrapperClass.getConstructor(wrapperClass.getEnclosingClass(), Alert.class);
} catch (Exception e) {
}
}
if (constructor == null) {
try {
constructor = wrapperClass.getConstructor(WebDriverWrapper.class, Alert.class);
} catch (Exception e) {
}
}
if (constructor == null) {
throw new Error("Element wrapper class " + wrapperClass + " does not provide an appropriate constructor");
}
try {
wrapper = constructor.newInstance(driverWrapper, alert);
} catch (Exception e) {
throw new Error("Can't create a new wrapper object", e);
}
return wrapper.wrapAlert();
}
/**
* Builds a {@link Proxy} implementing all interfaces of original alert. It will delegate calls to
* wrapper when wrapper implements the requested method otherwise to original alert.
*/
public final Alert wrapAlert() {
final Alert alert = getWrappedAlert();
final Set<Class<?>> wrapperInterfaces = extractInterfaces(this);
final InvocationHandler handler = new InvocationHandler() {
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
try {
if (wrapperInterfaces.contains(method.getDeclaringClass())) {
beforeMethod(method, args);
Object result = callMethod(method, args);
afterMethod(method, result, args);
return result;
}
return method.invoke(alert, args);
} catch (InvocationTargetException e) {
onError(method, e, args);
throw e.getTargetException();
}
}
};
Set<Class<?>> allInterfaces = extractInterfaces(alert);
allInterfaces.addAll(wrapperInterfaces);
Class<?>[] allInterfacesArray = allInterfaces.toArray(new Class<?>[allInterfaces.size()]);
return (Alert) Proxy.newProxyInstance(
this.getClass().getClassLoader(),
allInterfaces.toArray(allInterfacesArray),
handler);
}
protected void beforeMethod(Method method, Object[] args) {
}
protected Object callMethod(Method method, Object[] args) throws Throwable {
return method.invoke(this, args);
}
protected void afterMethod(Method method, Object res, Object[] args) {
}
protected void onError(Method method, InvocationTargetException e, Object[] args) {
}
}
public static class OptionsWrapper implements Options {
private final Options originalOptions;
private final WebDriverWrapper driverWrapper;
public OptionsWrapper(final WebDriverWrapper driverWrapper, final Options options) {
originalOptions = options;
this.driverWrapper = driverWrapper;
}
public final Options getWrappedOptions() {
return originalOptions;
}
private WebDriverWrapper getDriverWrapper() {
return driverWrapper;
}
@Override
public void addCookie(Cookie cookie) {
getWrappedOptions().addCookie(cookie);
}
@Override
public void deleteCookieNamed(String name) {
getWrappedOptions().deleteCookieNamed(name);
}
@Override
public void deleteCookie(Cookie cookie) {
getWrappedOptions().deleteCookie(cookie);
}
@Override
public void deleteAllCookies() {
getWrappedOptions().deleteAllCookies();
}
@Override
public Set<Cookie> getCookies() {
return getWrappedOptions().getCookies();
}
@Override
public Cookie getCookieNamed(String name) {
return getWrappedOptions().getCookieNamed(name);
}
@Override
public Timeouts timeouts() {
return getDriverWrapper().wrapTimeouts(getWrappedOptions().timeouts());
}
@Override
public ImeHandler ime() {
return getWrappedOptions().ime();
}
@Override
public Window window() {
return getDriverWrapper().wrapWindow(getWrappedOptions().window());
}
@Override
public Logs logs() {
return getWrappedOptions().logs();
}
/**
* Builds a {@link Proxy} implementing all interfaces of original options. It will delegate calls to
* wrapper when wrapper implements the requested method otherwise to original options.
*
* @param driverWrapper the underlying driver's wrapper
* @param options the underlying options
* @param wrapperClass the class of a wrapper
*/
public final static Options wrapOptions(final WebDriverWrapper driverWrapper, final Options options, final Class<? extends OptionsWrapper> wrapperClass) {
OptionsWrapper wrapper = null;
Constructor<? extends OptionsWrapper> constructor = null;
if (wrapperClass.getEnclosingClass() != null) {
try {
constructor = wrapperClass.getConstructor(wrapperClass.getEnclosingClass(), Options.class);
} catch (Exception e) {
}
}
if (constructor == null) {
try {
constructor = wrapperClass.getConstructor(WebDriverWrapper.class, Options.class);
} catch (Exception e) {
}
}
if (constructor == null) {
throw new Error("Element wrapper class " + wrapperClass + " does not provide an appropriate constructor");
}
try {
wrapper = constructor.newInstance(driverWrapper, options);
} catch (Exception e) {
throw new Error("Can't create a new wrapper object", e);
}
return wrapper.wrapOptions();
}
/**
* Builds a {@link Proxy} implementing all interfaces of original options. It will delegate calls to
* wrapper when wrapper implements the requested method otherwise to original options.
*/
public final Options wrapOptions() {
final Options options = getWrappedOptions();
final Set<Class<?>> wrapperInterfaces = extractInterfaces(this);
final InvocationHandler handler = new InvocationHandler() {
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
try {
if (wrapperInterfaces.contains(method.getDeclaringClass())) {
beforeMethod(method, args);
Object result = callMethod(method, args);
afterMethod(method, result, args);
return result;
}
return method.invoke(options, args);
} catch (InvocationTargetException e) {
onError(method, e, args);
throw e.getTargetException();
}
}
};
Set<Class<?>> allInterfaces = extractInterfaces(options);
allInterfaces.addAll(wrapperInterfaces);
Class<?>[] allInterfacesArray = allInterfaces.toArray(new Class<?>[allInterfaces.size()]);
return (Options) Proxy.newProxyInstance(
this.getClass().getClassLoader(),
allInterfaces.toArray(allInterfacesArray),
handler);
}
protected void beforeMethod(Method method, Object[] args) {
}
protected Object callMethod(Method method, Object[] args) throws Throwable {
return method.invoke(this, args);
}
protected void afterMethod(Method method, Object res, Object[] args) {
}
protected void onError(Method method, InvocationTargetException e, Object[] args) {
}
}
public static class TimeoutsWrapper implements Timeouts {
private final Timeouts originalTimeouts;
private final WebDriverWrapper driverWrapper;
public TimeoutsWrapper(final WebDriverWrapper driverWrapper, final Timeouts timeouts) {
originalTimeouts = timeouts;
this.driverWrapper = driverWrapper;
}
public final Timeouts getWrappedTimeouts() {
return originalTimeouts;
}
private WebDriverWrapper getDriverWrapper() {
return driverWrapper;
}
@Override
public Timeouts implicitlyWait(long timeout, TimeUnit timeUnit) {
getWrappedTimeouts().implicitlyWait(timeout, timeUnit);
return this;
}
@Override
public Timeouts setScriptTimeout(long timeout, TimeUnit timeUnit) {
getWrappedTimeouts().setScriptTimeout(timeout, timeUnit);
return this;
}
@Override
public Timeouts pageLoadTimeout(long timeout, TimeUnit timeUnit) {
getWrappedTimeouts().pageLoadTimeout(timeout, timeUnit);
return this;
}
/**
* Builds a {@link Proxy} implementing all interfaces of original timeouts. It will delegate calls to
* wrapper when wrapper implements the requested method otherwise to original timeouts.
*
* @param driverWrapper the underlying driver's wrapper
* @param timeouts the underlying timeouts
* @param wrapperClass the class of a wrapper
*/
public final static Timeouts wrapTimeouts(final WebDriverWrapper driverWrapper, final Timeouts timeouts, final Class<? extends TimeoutsWrapper> wrapperClass) {
TimeoutsWrapper wrapper = null;
Constructor<? extends TimeoutsWrapper> constructor = null;
if (wrapperClass.getEnclosingClass() != null) {
try {
constructor = wrapperClass.getConstructor(wrapperClass.getEnclosingClass(), Timeouts.class);
} catch (Exception e) {
}
}
if (constructor == null) {
try {
constructor = wrapperClass.getConstructor(WebDriverWrapper.class, Timeouts.class);
} catch (Exception e) {
}
}
if (constructor == null) {
throw new Error("Element wrapper class " + wrapperClass + " does not provide an appropriate constructor");
}
try {
wrapper = constructor.newInstance(driverWrapper, timeouts);
} catch (Exception e) {
throw new Error("Can't create a new wrapper object", e);
}
return wrapper.wrapTimeouts();
}
/**
* Builds a {@link Proxy} implementing all interfaces of original timeouts. It will delegate calls to
* wrapper when wrapper implements the requested method otherwise to original timeouts.
*/
public final Timeouts wrapTimeouts() {
final Timeouts timeouts = getWrappedTimeouts();
final Set<Class<?>> wrapperInterfaces = extractInterfaces(this);
final InvocationHandler handler = new InvocationHandler() {
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
try {
if (wrapperInterfaces.contains(method.getDeclaringClass())) {
beforeMethod(method, args);
Object result = callMethod(method, args);
afterMethod(method, result, args);
return result;
}
return method.invoke(timeouts, args);
} catch (InvocationTargetException e) {
onError(method, e, args);
throw e.getTargetException();
}
}
};
Set<Class<?>> allInterfaces = extractInterfaces(timeouts);
allInterfaces.addAll(wrapperInterfaces);
Class<?>[] allInterfacesArray = allInterfaces.toArray(new Class<?>[allInterfaces.size()]);
return (Timeouts) Proxy.newProxyInstance(
this.getClass().getClassLoader(),
allInterfaces.toArray(allInterfacesArray),
handler);
}
protected void beforeMethod(Method method, Object[] args) {
}
protected Object callMethod(Method method, Object[] args) throws Throwable {
return method.invoke(this, args);
}
protected void afterMethod(Method method, Object res, Object[] args) {
}
protected void onError(Method method, InvocationTargetException e, Object[] args) {
}
}
public static class WindowWrapper implements Window {
private final Window originalWindow;
private final WebDriverWrapper driverWrapper;
public WindowWrapper(final WebDriverWrapper driverWrapper, final Window window) {
originalWindow = window;
this.driverWrapper = driverWrapper;
}
public final Window getWrappedWindow() {
return originalWindow;
}
private WebDriverWrapper getDriverWrapper() {
return driverWrapper;
}
@Override
public void setSize(Dimension size) {
getWrappedWindow().setSize(size);
}
@Override
public void setPosition(Point position) {
getWrappedWindow().setPosition(position);
}
@Override
public Dimension getSize() {
return getWrappedWindow().getSize();
}
@Override
public Point getPosition() {
return getWrappedWindow().getPosition();
}
@Override
public void maximize() {
getWrappedWindow().maximize();
}
/**
* Builds a {@link Proxy} implementing all interfaces of original window. It will delegate calls to
* wrapper when wrapper implements the requested method otherwise to original window.
*
* @param driverWrapper the underlying driver's wrapper
* @param window the underlying window
* @param wrapperClass the class of a wrapper
*/
public final static Window wrapWindow(final WebDriverWrapper driverWrapper, final Window window, final Class<? extends WindowWrapper> wrapperClass) {
WindowWrapper wrapper = null;
Constructor<? extends WindowWrapper> constructor = null;
if (wrapperClass.getEnclosingClass() != null) {
try {
constructor = wrapperClass.getConstructor(wrapperClass.getEnclosingClass(), Window.class);
} catch (Exception e) {
}
}
if (constructor == null) {
try {
constructor = wrapperClass.getConstructor(WebDriverWrapper.class, Window.class);
} catch (Exception e) {
}
}
if (constructor == null) {
throw new Error("Element wrapper class " + wrapperClass + " does not provide an appropriate constructor");
}
try {
wrapper = constructor.newInstance(driverWrapper, window);
} catch (Exception e) {
throw new Error("Can't create a new wrapper object", e);
}
return wrapper.wrapWindow();
}
/**
* Builds a {@link Proxy} implementing all interfaces of original window. It will delegate calls to
* wrapper when wrapper implements the requested method otherwise to original window.
*/
public final Window wrapWindow() {
final Window window = getWrappedWindow();
final Set<Class<?>> wrapperInterfaces = extractInterfaces(this);
final InvocationHandler handler = new InvocationHandler() {
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
try {
if (wrapperInterfaces.contains(method.getDeclaringClass())) {
beforeMethod(method, args);
Object result = callMethod(method, args);
afterMethod(method, result, args);
return result;
}
return method.invoke(window, args);
} catch (InvocationTargetException e) {
onError(method, e, args);
throw e.getTargetException();
}
}
};
Set<Class<?>> allInterfaces = extractInterfaces(window);
allInterfaces.addAll(wrapperInterfaces);
Class<?>[] allInterfacesArray = allInterfaces.toArray(new Class<?>[allInterfaces.size()]);
return (Window) Proxy.newProxyInstance(
this.getClass().getClassLoader(),
allInterfaces.toArray(allInterfacesArray),
handler);
}
protected void beforeMethod(Method method, Object[] args) {
}
protected Object callMethod(Method method, Object[] args) throws Throwable {
return method.invoke(this, args);
}
protected void afterMethod(Method method, Object res, Object[] args) {
}
protected void onError(Method method, InvocationTargetException e, Object[] args) {
}
}
public static class CoordinatesWrapper implements Coordinates {
private final Coordinates originalCoordinates;
private final WebDriverWrapper driverWrapper;
public CoordinatesWrapper(final WebDriverWrapper driverWrapper, final Coordinates coordinates) {
originalCoordinates = coordinates;
this.driverWrapper = driverWrapper;
}
public final Coordinates getWrappedCoordinates() {
return originalCoordinates;
}
private WebDriverWrapper getDriverWrapper() {
return driverWrapper;
}
@Override
public Point onScreen() {
return getWrappedCoordinates().onScreen();
}
@Override
public Point inViewPort() {
return getWrappedCoordinates().inViewPort();
}
@Override
public Point onPage() {
return getWrappedCoordinates().onPage();
}
@Override
public Object getAuxiliary() {
return getDriverWrapper().wrapObject(getWrappedCoordinates().getAuxiliary());
}
/**
* Builds a {@link Proxy} implementing all interfaces of original coordinates. It will delegate calls to
* wrapper when wrapper implements the requested method otherwise to original coordinates.
*
* @param driverWrapper the underlying driver's wrapper
* @param coordinates the underlying coordinates
* @param wrapperClass the class of a wrapper
*/
public final static Coordinates wrapCoordinates(final WebDriverWrapper driverWrapper, final Coordinates coordinates, final Class<? extends CoordinatesWrapper> wrapperClass) {
CoordinatesWrapper wrapper = null;
Constructor<? extends CoordinatesWrapper> constructor = null;
if (wrapperClass.getEnclosingClass() != null) {
try {
constructor = wrapperClass.getConstructor(wrapperClass.getEnclosingClass(), Coordinates.class);
} catch (Exception e) {
}
}
if (constructor == null) {
try {
constructor = wrapperClass.getConstructor(WebDriverWrapper.class, Coordinates.class);
} catch (Exception e) {
}
}
if (constructor == null) {
throw new Error("Element wrapper class " + wrapperClass + " does not provide an appropriate constructor");
}
try {
wrapper = constructor.newInstance(driverWrapper, coordinates);
} catch (Exception e) {
throw new Error("Can't create a new wrapper object", e);
}
return wrapper.wrapCoordinates();
}
/**
* Builds a {@link Proxy} implementing all interfaces of original coordinates. It will delegate calls to
* wrapper when wrapper implements the requested method otherwise to original coordinates.
*/
public final Coordinates wrapCoordinates() {
final Coordinates coordinates = getWrappedCoordinates();
final Set<Class<?>> wrapperInterfaces = extractInterfaces(this);
final InvocationHandler handler = new InvocationHandler() {
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
try {
if (wrapperInterfaces.contains(method.getDeclaringClass())) {
beforeMethod(method, args);
Object result = callMethod(method, args);
afterMethod(method, result, args);
return result;
}
return method.invoke(coordinates, args);
} catch (InvocationTargetException e) {
onError(method, e, args);
throw e.getTargetException();
}
}
};
Set<Class<?>> allInterfaces = extractInterfaces(coordinates);
allInterfaces.addAll(wrapperInterfaces);
Class<?>[] allInterfacesArray = allInterfaces.toArray(new Class<?>[allInterfaces.size()]);
return (Coordinates) Proxy.newProxyInstance(
this.getClass().getClassLoader(),
allInterfaces.toArray(allInterfacesArray),
handler);
}
protected void beforeMethod(Method method, Object[] args) {
}
protected Object callMethod(Method method, Object[] args) throws Throwable {
return method.invoke(this, args);
}
protected void afterMethod(Method method, Object res, Object[] args) {
}
protected void onError(Method method, InvocationTargetException e, Object[] args) {
}
}
private static Set<Class<?>> extractInterfaces(final Object object) {
return extractInterfaces(object.getClass());
}
private static Set<Class<?>> extractInterfaces(final Class<?> clazz) {
Set<Class<?>> allInterfaces = new HashSet<Class<?>>();
extractInterfaces(allInterfaces, clazz);
return allInterfaces;
}
private static void extractInterfaces(final Set<Class<?>> collector, final Class<?> clazz) {
if (clazz == null || Object.class.equals(clazz)) {
return;
}
final Class<?>[] classes = clazz.getInterfaces();
for (Class<?> interfaceClass : classes) {
collector.add(interfaceClass);
for (Class<?> superInterface : interfaceClass.getInterfaces()) {
collector.add(superInterface);
extractInterfaces(collector, superInterface);
}
}
extractInterfaces(collector, clazz.getSuperclass());
}
}
|
src/main/java/ru/st/selenium/wrapper/WebDriverWrapper.java
|
/*
* Copyright 2013 Alexei Barantsev
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package ru.st.selenium.wrapper;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.net.URL;
import java.util.HashSet;
import java.util.List;
import java.util.ListIterator;
import java.util.Set;
import org.openqa.selenium.Alert;
import org.openqa.selenium.Beta;
import org.openqa.selenium.By;
import org.openqa.selenium.Dimension;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.Point;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriverException;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.internal.WrapsDriver;
import org.openqa.selenium.internal.WrapsElement;
import org.openqa.selenium.security.Credentials;
/**
* This class allows to extend WebDriver by adding new functionality to a wrapper.
* Example of use:
* <code><pre>
* WebDriver driver = WebDriverWrapper.wrapDriver(originalDriver, MyWebDriverWrapper.class);
* </pre></code>
* or
* <code><pre>
* MyWebDriverWrapper wrapper = new MyWebDriverWrapper(originalDriver, otherParameter);
* WebDriver driver = wrapper.getDriver();
* </pre></code>
*/
public class WebDriverWrapper implements WebDriver, WrapsDriver, JavascriptExecutor {
private final WebDriver originalDriver;
private WebDriver enhancedDriver = null;
public WebDriverWrapper(WebDriver driver) {
originalDriver = driver;
}
protected Class<? extends WebElementWrapper> getElementWrapperClass() {
return WebElementWrapper.class;
}
protected Class<? extends TargetLocatorWrapper> getTargetLocatorWrapperClass() {
return TargetLocatorWrapper.class;
}
protected Class<? extends NavigationWrapper> getNavigationWrapperClass() {
return NavigationWrapper.class;
}
protected Class<? extends AlertWrapper> geAlertWrapperClass() {
return AlertWrapper.class;
}
@Override
public final WebDriver getWrappedDriver() {
return originalDriver;
}
@Override
public void get(String url) {
getWrappedDriver().get(url);
}
@Override
public String getCurrentUrl() {
return getWrappedDriver().getCurrentUrl();
}
@Override
public String getTitle() {
return getWrappedDriver().getTitle();
}
@Override
public WebElement findElement(final By by) {
return wrapElement(getWrappedDriver().findElement(by));
}
// TODO: make private
protected WebElement wrapElement(final WebElement element) {
return WebElementWrapper.wrapElement(this, element, getElementWrapperClass());
}
@Override
public List<WebElement> findElements(final By by) {
return wrapElements(getWrappedDriver().findElements(by));
}
// TODO: make private
private List<WebElement> wrapElements(final List<WebElement> elements) {
for (ListIterator<WebElement> iterator = elements.listIterator(); iterator.hasNext(); ) {
iterator.set(wrapElement(iterator.next()));
}
return elements;
}
@Override
public String getPageSource() {
return getWrappedDriver().getPageSource();
}
@Override
public void close() {
getWrappedDriver().close();
}
@Override
public void quit() {
getWrappedDriver().quit();
}
@Override
public Set<String> getWindowHandles() {
return getWrappedDriver().getWindowHandles();
}
@Override
public String getWindowHandle() {
return getWrappedDriver().getWindowHandle();
}
@Override
public TargetLocator switchTo() {
return wrapTargetLocator(getWrappedDriver().switchTo());
}
private TargetLocator wrapTargetLocator(final TargetLocator targetLocator) {
return TargetLocatorWrapper.wrapTargetLocator(this, targetLocator, getTargetLocatorWrapperClass());
}
@Override
public Navigation navigate() {
return wrapNavigation(getWrappedDriver().navigate());
}
private Navigation wrapNavigation(final Navigation navigator) {
return NavigationWrapper.wrapNavigation(this, navigator, getNavigationWrapperClass());
}
@Override
public Options manage() {
return getWrappedDriver().manage();
}
@Override
public Object executeScript(String script, Object... args) {
WebDriver driver = getWrappedDriver();
if (driver instanceof JavascriptExecutor) {
return ((JavascriptExecutor) driver).executeScript(script, args);
} else {
throw new WebDriverException("Wrapped webdriver does not support JavascriptExecutor: " + driver);
}
}
@Override
public Object executeAsyncScript(String script, Object... args) {
WebDriver driver = getWrappedDriver();
if (driver instanceof JavascriptExecutor) {
return ((JavascriptExecutor) driver).executeAsyncScript(script, args);
} else {
throw new WebDriverException("Wrapped webdriver does not support JavascriptExecutor: " + driver);
}
}
/**
* Builds a {@link Proxy} implementing all interfaces of original driver. It will delegate calls to
* wrapper when wrapper implements the requested method otherwise to original driver.
*
* @param driver the underlying driver
* @param wrapperClass the class of a wrapper
*/
public final static WebDriver wrapDriver(final WebDriver driver, final Class<? extends WebDriverWrapper> wrapperClass) {
WebDriverWrapper wrapper = null;
try {
wrapper = wrapperClass.getConstructor(WebDriver.class).newInstance(driver);
} catch (NoSuchMethodException e) {
throw new Error("Wrapper class should provide a constructor with a single WebDriver parameter", e);
} catch (Exception e) {
throw new Error("Can't create a new wrapper object", e);
}
return wrapper.getDriver();
}
/**
* Builds a {@link Proxy} implementing all interfaces of original driver. It will delegate calls to
* wrapper when wrapper implements the requested method otherwise to original driver.
*
* @param driver the wrapped driver
* @param wrapper the object wrapping the driver
*/
public final WebDriver getDriver() {
if (enhancedDriver != null) {
return enhancedDriver;
}
final WebDriver driver = getWrappedDriver();
final Set<Class<?>> wrapperInterfaces = extractInterfaces(this);
final InvocationHandler handler = new InvocationHandler() {
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
try {
if (wrapperInterfaces.contains(method.getDeclaringClass())) {
beforeMethod(method, args);
Object result = callMethod(method, args);
afterMethod(method, result, args);
return result;
}
return method.invoke(driver, args);
} catch (InvocationTargetException e) {
onError(method, e, args);
throw e.getTargetException();
}
}
};
Set<Class<?>> allInterfaces = extractInterfaces(driver);
allInterfaces.addAll(wrapperInterfaces);
Class<?>[] allInterfacesArray = allInterfaces.toArray(new Class<?>[allInterfaces.size()]);
enhancedDriver = (WebDriver) Proxy.newProxyInstance(
this.getClass().getClassLoader(),
allInterfaces.toArray(allInterfacesArray),
handler);
return enhancedDriver;
}
protected void beforeMethod(Method method, Object[] args) {
}
protected Object callMethod(Method method, Object[] args) throws Throwable {
return method.invoke(this, args);
}
protected void afterMethod(Method method, Object res, Object[] args) {
}
protected void onError(Method method, InvocationTargetException e, Object[] args) {
}
/**
* Simple {@link WrapsElement} delegating all calls to the wrapped {@link WebElement}.
* The methods {@link WebDriverWrapper#wrapElement(WebElement)}/{@link WebDriverWrapper#wrapElements(List<WebElement>)} will
* be called on the related {@link WebDriverWrapper} to wrap the elements returned by {@link #findElement(By)}/{@link #findElements(By)}.
*/
public static class WebElementWrapper implements WebElement, WrapsElement {
private final WebElement originalElement;
private final WebDriverWrapper driverWrapper;
public WebElementWrapper(final WebDriverWrapper driverWrapper, final WebElement element) {
originalElement = element;
this.driverWrapper = driverWrapper;
}
@Override
public final WebElement getWrappedElement() {
return originalElement;
}
private WebDriverWrapper getDriverWrapper() {
return driverWrapper;
}
@Override
public void click() {
getWrappedElement().click();
}
@Override
public void submit() {
getWrappedElement().submit();
}
@Override
public void sendKeys(final CharSequence... keysToSend) {
getWrappedElement().sendKeys(keysToSend);
}
@Override
public void clear() {
getWrappedElement().clear();
}
@Override
public String getTagName() {
return getWrappedElement().getTagName();
}
@Override
public String getAttribute(final String name) {
return getWrappedElement().getAttribute(name);
}
@Override
public boolean isSelected() {
return getWrappedElement().isSelected();
}
@Override
public boolean isEnabled() {
return getWrappedElement().isEnabled();
}
@Override
public String getText() {
return getWrappedElement().getText();
}
@Override
public List<WebElement> findElements(final By by) {
return getDriverWrapper().wrapElements(getWrappedElement().findElements(by));
}
@Override
public WebElement findElement(final By by) {
return getDriverWrapper().wrapElement(getWrappedElement().findElement(by));
}
@Override
public boolean isDisplayed() {
return getWrappedElement().isDisplayed();
}
@Override
public Point getLocation() {
return getWrappedElement().getLocation();
}
@Override
public Dimension getSize() {
return getWrappedElement().getSize();
}
@Override
public String getCssValue(final String propertyName) {
return getWrappedElement().getCssValue(propertyName);
}
/**
* Builds a {@link Proxy} implementing all interfaces of original element. It will delegate calls to
* wrapper when wrapper implements the requested method otherwise to original element.
*
* @param driverWrapper the underlying driver's wrapper
* @param element the underlying element
* @param wrapperClass the class of a wrapper
*/
public final static WebElement wrapElement(final WebDriverWrapper driverWrapper, final WebElement element, final Class<? extends WebElementWrapper> wrapperClass) {
WebElementWrapper wrapper = null;
Constructor<? extends WebElementWrapper> constructor = null;
if (wrapperClass.getEnclosingClass() != null) {
try {
constructor = wrapperClass.getConstructor(wrapperClass.getEnclosingClass(), WebElement.class);
} catch (Exception e) {
}
}
if (constructor == null) {
try {
constructor = wrapperClass.getConstructor(WebDriverWrapper.class, WebElement.class);
} catch (Exception e) {
}
}
if (constructor == null) {
throw new Error("Element wrapper class " + wrapperClass + " does not provide an appropriate constructor");
}
try {
wrapper = constructor.newInstance(driverWrapper, element);
} catch (Exception e) {
throw new Error("Can't create a new wrapper object", e);
}
return wrapper.getElement();
}
/**
* Builds a {@link Proxy} implementing all interfaces of original element. It will delegate calls to
* wrapper when wrapper implements the requested method otherwise to original element.
*/
public final WebElement getElement() {
final WebElement element = getWrappedElement();
final Set<Class<?>> wrapperInterfaces = extractInterfaces(this);
final InvocationHandler handler = new InvocationHandler() {
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
try {
if (wrapperInterfaces.contains(method.getDeclaringClass())) {
beforeMethod(method, args);
Object result = callMethod(method, args);
afterMethod(method, result, args);
return result;
}
return method.invoke(element, args);
} catch (InvocationTargetException e) {
onError(method, e, args);
throw e.getTargetException();
}
}
};
Set<Class<?>> allInterfaces = extractInterfaces(element);
allInterfaces.addAll(wrapperInterfaces);
Class<?>[] allInterfacesArray = allInterfaces.toArray(new Class<?>[allInterfaces.size()]);
return (WebElement) Proxy.newProxyInstance(
this.getClass().getClassLoader(),
allInterfaces.toArray(allInterfacesArray),
handler);
}
protected void beforeMethod(Method method, Object[] args) {
}
protected Object callMethod(Method method, Object[] args) throws Throwable {
return method.invoke(this, args);
}
protected void afterMethod(Method method, Object res, Object[] args) {
}
protected void onError(Method method, InvocationTargetException e, Object[] args) {
}
}
public static class TargetLocatorWrapper implements TargetLocator {
private final TargetLocator originalTargetLocator;
private final WebDriverWrapper driverWrapper;
public TargetLocatorWrapper(final WebDriverWrapper driverWrapper, final TargetLocator targetLocator) {
originalTargetLocator = targetLocator;
this.driverWrapper = driverWrapper;
}
public final TargetLocator getWrappedTargetLocator() {
return originalTargetLocator;
}
private final WebDriverWrapper getDriverWrapper() {
return driverWrapper;
}
@Override
public WebDriver frame(int frameIndex) {
getWrappedTargetLocator().frame(frameIndex);
return getDriverWrapper().getDriver();
}
@Override
public WebDriver frame(String frameName) {
getWrappedTargetLocator().frame(frameName);
return getDriverWrapper().getDriver();
}
@Override
public WebDriver frame(WebElement frameElement) {
getWrappedTargetLocator().frame(frameElement);
return getDriverWrapper().getDriver();
}
@Override
public WebDriver window(String windowName) {
getWrappedTargetLocator().window(windowName);
return getDriverWrapper().getDriver();
}
@Override
public WebDriver defaultContent() {
getWrappedTargetLocator().defaultContent();
return getDriverWrapper().getDriver();
}
@Override
public WebElement activeElement() {
return getDriverWrapper().wrapElement(getWrappedTargetLocator().activeElement());
}
@Override
public Alert alert() {
return getWrappedTargetLocator().alert();
}
/**
* Builds a {@link Proxy} implementing all interfaces of original target locator. It will delegate calls to
* wrapper when wrapper implements the requested method otherwise to original target locator.
*
* @param driverWrapper the underlying driver's wrapper
* @param targetLocator the underlying target locator
* @param wrapperClass the class of a wrapper
*/
public final static TargetLocator wrapTargetLocator(final WebDriverWrapper driverWrapper, final TargetLocator targetLocator, final Class<? extends TargetLocatorWrapper> wrapperClass) {
TargetLocatorWrapper wrapper = null;
Constructor<? extends TargetLocatorWrapper> constructor = null;
if (wrapperClass.getEnclosingClass() != null) {
try {
constructor = wrapperClass.getConstructor(wrapperClass.getEnclosingClass(), TargetLocator.class);
} catch (Exception e) {
}
}
if (constructor == null) {
try {
constructor = wrapperClass.getConstructor(WebDriverWrapper.class, TargetLocator.class);
} catch (Exception e) {
}
}
if (constructor == null) {
throw new Error("Element wrapper class " + wrapperClass + " does not provide an appropriate constructor");
}
try {
wrapper = constructor.newInstance(driverWrapper, targetLocator);
} catch (Exception e) {
throw new Error("Can't create a new wrapper object", e);
}
return wrapper.getTargetLocator();
}
/**
* Builds a {@link Proxy} implementing all interfaces of original target locator. It will delegate calls to
* wrapper when wrapper implements the requested method otherwise to original target locator.
*/
public final TargetLocator getTargetLocator() {
final TargetLocator targetLocator = getWrappedTargetLocator();
final Set<Class<?>> wrapperInterfaces = extractInterfaces(this);
final InvocationHandler handler = new InvocationHandler() {
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
try {
if (wrapperInterfaces.contains(method.getDeclaringClass())) {
beforeMethod(method, args);
Object result = callMethod(method, args);
afterMethod(method, result, args);
return result;
}
return method.invoke(targetLocator, args);
} catch (InvocationTargetException e) {
onError(method, e, args);
throw e.getTargetException();
}
}
};
Set<Class<?>> allInterfaces = extractInterfaces(targetLocator);
allInterfaces.addAll(wrapperInterfaces);
Class<?>[] allInterfacesArray = allInterfaces.toArray(new Class<?>[allInterfaces.size()]);
return (TargetLocator) Proxy.newProxyInstance(
this.getClass().getClassLoader(),
allInterfaces.toArray(allInterfacesArray),
handler);
}
protected void beforeMethod(Method method, Object[] args) {
}
protected Object callMethod(Method method, Object[] args) throws Throwable {
return method.invoke(this, args);
}
protected void afterMethod(Method method, Object res, Object[] args) {
}
protected void onError(Method method, InvocationTargetException e, Object[] args) {
}
}
public static class NavigationWrapper implements Navigation {
private final Navigation originalNavigator;
private final WebDriverWrapper driverWrapper;
public NavigationWrapper(final WebDriverWrapper driverWrapper, final Navigation navigator) {
originalNavigator = navigator;
this.driverWrapper = driverWrapper;
}
public final Navigation getWrappedNavigation() {
return originalNavigator;
}
private WebDriverWrapper getDriverWrapper() {
return driverWrapper;
}
@Override
public void to(String url) {
getWrappedNavigation().to(url);
}
@Override
public void to(URL url) {
getWrappedNavigation().to(url);
}
@Override
public void back() {
getWrappedNavigation().back();
}
@Override
public void forward() {
getWrappedNavigation().forward();
}
@Override
public void refresh() {
getWrappedNavigation().refresh();
}
/**
* Builds a {@link Proxy} implementing all interfaces of original navigator. It will delegate calls to
* wrapper when wrapper implements the requested method otherwise to original navigator.
*
* @param driverWrapper the underlying driver's wrapper
* @param navigator the underlying navigator
* @param wrapperClass the class of a wrapper
*/
public final static Navigation wrapNavigation(final WebDriverWrapper driverWrapper, final Navigation navigator, final Class<? extends NavigationWrapper> wrapperClass) {
NavigationWrapper wrapper = null;
Constructor<? extends NavigationWrapper> constructor = null;
if (wrapperClass.getEnclosingClass() != null) {
try {
constructor = wrapperClass.getConstructor(wrapperClass.getEnclosingClass(), Navigation.class);
} catch (Exception e) {
}
}
if (constructor == null) {
try {
constructor = wrapperClass.getConstructor(WebDriverWrapper.class, Navigation.class);
} catch (Exception e) {
}
}
if (constructor == null) {
throw new Error("Element wrapper class " + wrapperClass + " does not provide an appropriate constructor");
}
try {
wrapper = constructor.newInstance(driverWrapper, navigator);
} catch (Exception e) {
throw new Error("Can't create a new wrapper object", e);
}
return wrapper.wrapNavigation();
}
/**
* Builds a {@link Proxy} implementing all interfaces of original navigator. It will delegate calls to
* wrapper when wrapper implements the requested method otherwise to original navigator.
*/
public final Navigation wrapNavigation() {
final Navigation navigator = getWrappedNavigation();
final Set<Class<?>> wrapperInterfaces = extractInterfaces(this);
final InvocationHandler handler = new InvocationHandler() {
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
try {
if (wrapperInterfaces.contains(method.getDeclaringClass())) {
beforeMethod(method, args);
Object result = callMethod(method, args);
afterMethod(method, result, args);
return result;
}
return method.invoke(navigator, args);
} catch (InvocationTargetException e) {
onError(method, e, args);
throw e.getTargetException();
}
}
};
Set<Class<?>> allInterfaces = extractInterfaces(navigator);
allInterfaces.addAll(wrapperInterfaces);
Class<?>[] allInterfacesArray = allInterfaces.toArray(new Class<?>[allInterfaces.size()]);
return (Navigation) Proxy.newProxyInstance(
this.getClass().getClassLoader(),
allInterfaces.toArray(allInterfacesArray),
handler);
}
protected void beforeMethod(Method method, Object[] args) {
}
protected Object callMethod(Method method, Object[] args) throws Throwable {
return method.invoke(this, args);
}
protected void afterMethod(Method method, Object res, Object[] args) {
}
protected void onError(Method method, InvocationTargetException e, Object[] args) {
}
}
public static class AlertWrapper implements Alert {
private final Alert originalAlert;
private final WebDriverWrapper driverWrapper;
public AlertWrapper(final WebDriverWrapper driverWrapper, final Alert alert) {
originalAlert = alert;
this.driverWrapper = driverWrapper;
}
public final Alert getWrappedAlert() {
return originalAlert;
}
private WebDriverWrapper getDriverWrapper() {
return driverWrapper;
}
@Override
public void accept() {
getWrappedAlert().accept();
}
@Override
@Beta
public void authenticateUsing(Credentials creds) {
getWrappedAlert().authenticateUsing(creds);
}
@Override
public void dismiss() {
getWrappedAlert().dismiss();
}
@Override
public String getText() {
return getWrappedAlert().getText();
}
@Override
public void sendKeys(String text) {
getWrappedAlert().sendKeys(text);
}
/**
* Builds a {@link Proxy} implementing all interfaces of original alert. It will delegate calls to
* wrapper when wrapper implements the requested method otherwise to original alert.
*
* @param driverWrapper the underlying driver's wrapper
* @param alert the underlying alert
* @param wrapperClass the class of a wrapper
*/
public final static Alert wrapNavigation(final WebDriverWrapper driverWrapper, final Alert alert, final Class<? extends AlertWrapper> wrapperClass) {
AlertWrapper wrapper = null;
Constructor<? extends AlertWrapper> constructor = null;
if (wrapperClass.getEnclosingClass() != null) {
try {
constructor = wrapperClass.getConstructor(wrapperClass.getEnclosingClass(), Alert.class);
} catch (Exception e) {
}
}
if (constructor == null) {
try {
constructor = wrapperClass.getConstructor(WebDriverWrapper.class, Alert.class);
} catch (Exception e) {
}
}
if (constructor == null) {
throw new Error("Element wrapper class " + wrapperClass + " does not provide an appropriate constructor");
}
try {
wrapper = constructor.newInstance(driverWrapper, alert);
} catch (Exception e) {
throw new Error("Can't create a new wrapper object", e);
}
return wrapper.wrapAlert();
}
/**
* Builds a {@link Proxy} implementing all interfaces of original alert. It will delegate calls to
* wrapper when wrapper implements the requested method otherwise to original alert.
*/
public final Alert wrapAlert() {
final Alert alert = getWrappedAlert();
final Set<Class<?>> wrapperInterfaces = extractInterfaces(this);
final InvocationHandler handler = new InvocationHandler() {
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
try {
if (wrapperInterfaces.contains(method.getDeclaringClass())) {
beforeMethod(method, args);
Object result = callMethod(method, args);
afterMethod(method, result, args);
return result;
}
return method.invoke(alert, args);
} catch (InvocationTargetException e) {
onError(method, e, args);
throw e.getTargetException();
}
}
};
Set<Class<?>> allInterfaces = extractInterfaces(alert);
allInterfaces.addAll(wrapperInterfaces);
Class<?>[] allInterfacesArray = allInterfaces.toArray(new Class<?>[allInterfaces.size()]);
return (Alert) Proxy.newProxyInstance(
this.getClass().getClassLoader(),
allInterfaces.toArray(allInterfacesArray),
handler);
}
protected void beforeMethod(Method method, Object[] args) {
}
protected Object callMethod(Method method, Object[] args) throws Throwable {
return method.invoke(this, args);
}
protected void afterMethod(Method method, Object res, Object[] args) {
}
protected void onError(Method method, InvocationTargetException e, Object[] args) {
}
}
private static Set<Class<?>> extractInterfaces(final Object object) {
return extractInterfaces(object.getClass());
}
private static Set<Class<?>> extractInterfaces(final Class<?> clazz) {
Set<Class<?>> allInterfaces = new HashSet<Class<?>>();
extractInterfaces(allInterfaces, clazz);
return allInterfaces;
}
private static void extractInterfaces(final Set<Class<?>> collector, final Class<?> clazz) {
if (clazz == null || Object.class.equals(clazz)) {
return;
}
final Class<?>[] classes = clazz.getInterfaces();
for (Class<?> interfaceClass : classes) {
collector.add(interfaceClass);
for (Class<?> superInterface : interfaceClass.getInterfaces()) {
collector.add(superInterface);
extractInterfaces(collector, superInterface);
}
}
extractInterfaces(collector, clazz.getSuperclass());
}
}
|
Implementing all the remaining wrapper abstract classes
|
src/main/java/ru/st/selenium/wrapper/WebDriverWrapper.java
|
Implementing all the remaining wrapper abstract classes
|
<ide><path>rc/main/java/ru/st/selenium/wrapper/WebDriverWrapper.java
<ide> import java.util.List;
<ide> import java.util.ListIterator;
<ide> import java.util.Set;
<del>
<del>import org.openqa.selenium.Alert;
<del>import org.openqa.selenium.Beta;
<del>import org.openqa.selenium.By;
<del>import org.openqa.selenium.Dimension;
<del>import org.openqa.selenium.JavascriptExecutor;
<del>import org.openqa.selenium.Point;
<del>import org.openqa.selenium.WebDriver;
<del>import org.openqa.selenium.WebDriverException;
<del>import org.openqa.selenium.WebElement;
<add>import java.util.concurrent.TimeUnit;
<add>
<add>import org.openqa.selenium.*;
<add>import org.openqa.selenium.interactions.internal.Coordinates;
<add>import org.openqa.selenium.internal.Locatable;
<ide> import org.openqa.selenium.internal.WrapsDriver;
<ide> import org.openqa.selenium.internal.WrapsElement;
<add>import org.openqa.selenium.logging.Logs;
<ide> import org.openqa.selenium.security.Credentials;
<ide>
<ide> /**
<ide> protected Class<? extends WebElementWrapper> getElementWrapperClass() {
<ide> return WebElementWrapper.class;
<ide> }
<del>
<del> protected Class<? extends TargetLocatorWrapper> getTargetLocatorWrapperClass() {
<del> return TargetLocatorWrapper.class;
<del> }
<del>
<del> protected Class<? extends NavigationWrapper> getNavigationWrapperClass() {
<del> return NavigationWrapper.class;
<del> }
<del>
<del> protected Class<? extends AlertWrapper> geAlertWrapperClass() {
<del> return AlertWrapper.class;
<del> }
<del>
<del> @Override
<del> public final WebDriver getWrappedDriver() {
<del> return originalDriver;
<del> }
<del>
<del> @Override
<del> public void get(String url) {
<del> getWrappedDriver().get(url);
<del> }
<del>
<del> @Override
<del> public String getCurrentUrl() {
<del> return getWrappedDriver().getCurrentUrl();
<del> }
<del>
<del> @Override
<del> public String getTitle() {
<del> return getWrappedDriver().getTitle();
<del> }
<del>
<del> @Override
<del> public WebElement findElement(final By by) {
<del> return wrapElement(getWrappedDriver().findElement(by));
<del> }
<del>
<del> // TODO: make private
<add>
<ide> protected WebElement wrapElement(final WebElement element) {
<ide> return WebElementWrapper.wrapElement(this, element, getElementWrapperClass());
<ide> }
<del>
<del> @Override
<del> public List<WebElement> findElements(final By by) {
<del> return wrapElements(getWrappedDriver().findElements(by));
<del> }
<del>
<del> // TODO: make private
<add>
<ide> private List<WebElement> wrapElements(final List<WebElement> elements) {
<ide> for (ListIterator<WebElement> iterator = elements.listIterator(); iterator.hasNext(); ) {
<ide> iterator.set(wrapElement(iterator.next()));
<ide> return elements;
<ide> }
<ide>
<add> protected Class<? extends TargetLocatorWrapper> getTargetLocatorWrapperClass() {
<add> return TargetLocatorWrapper.class;
<add> }
<add>
<add> private TargetLocator wrapTargetLocator(final TargetLocator targetLocator) {
<add> return TargetLocatorWrapper.wrapTargetLocator(this, targetLocator, getTargetLocatorWrapperClass());
<add> }
<add>
<add> protected Class<? extends AlertWrapper> getAlertWrapperClass() {
<add> return AlertWrapper.class;
<add> }
<add>
<add> private Alert wrapAlert(final Alert alert) {
<add> return AlertWrapper.wrapAlert(this, alert, getAlertWrapperClass());
<add> }
<add>
<add> protected Class<? extends NavigationWrapper> getNavigationWrapperClass() {
<add> return NavigationWrapper.class;
<add> }
<add>
<add> private Navigation wrapNavigation(final Navigation navigator) {
<add> return NavigationWrapper.wrapNavigation(this, navigator, getNavigationWrapperClass());
<add> }
<add>
<add> protected Class<? extends OptionsWrapper> getOptionsWrapperClass() {
<add> return OptionsWrapper.class;
<add> }
<add>
<add> private Options wrapOptions(final Options options) {
<add> return OptionsWrapper.wrapOptions(this, options, getOptionsWrapperClass());
<add> }
<add>
<add> protected Class<? extends TimeoutsWrapper> getTimeoutsWrapperClass() {
<add> return TimeoutsWrapper.class;
<add> }
<add>
<add> private Timeouts wrapTimeouts(final Timeouts timeouts) {
<add> return TimeoutsWrapper.wrapTimeouts(this, timeouts, getTimeoutsWrapperClass());
<add> }
<add>
<add> protected Class<? extends WindowWrapper> getWindowWrapperClass() {
<add> return WindowWrapper.class;
<add> }
<add>
<add> private Window wrapWindow(final Window window) {
<add> return WindowWrapper.wrapWindow(this, window, getWindowWrapperClass());
<add> }
<add>
<add> protected Class<? extends CoordinatesWrapper> getCoordinatesWrapperClass() {
<add> return CoordinatesWrapper.class;
<add> }
<add>
<add> private Coordinates wrapCoordinates(final Coordinates coordinates) {
<add> return CoordinatesWrapper.wrapCoordinates(this, coordinates, getCoordinatesWrapperClass());
<add> }
<add>
<add> // TODO: implement proper wrapping for arbitrary objects
<add> private Object wrapObject(final Object object) {
<add> if (object instanceof WebElement) {
<add> return wrapElement((WebElement) object);
<add> } else {
<add> return object;
<add> }
<add> }
<add>
<add> @Override
<add> public final WebDriver getWrappedDriver() {
<add> return originalDriver;
<add> }
<add>
<add> @Override
<add> public void get(String url) {
<add> getWrappedDriver().get(url);
<add> }
<add>
<add> @Override
<add> public String getCurrentUrl() {
<add> return getWrappedDriver().getCurrentUrl();
<add> }
<add>
<add> @Override
<add> public String getTitle() {
<add> return getWrappedDriver().getTitle();
<add> }
<add>
<add> @Override
<add> public WebElement findElement(final By by) {
<add> return wrapElement(getWrappedDriver().findElement(by));
<add> }
<add>
<add> @Override
<add> public List<WebElement> findElements(final By by) {
<add> return wrapElements(getWrappedDriver().findElements(by));
<add> }
<add>
<ide> @Override
<ide> public String getPageSource() {
<ide> return getWrappedDriver().getPageSource();
<ide> return wrapTargetLocator(getWrappedDriver().switchTo());
<ide> }
<ide>
<del> private TargetLocator wrapTargetLocator(final TargetLocator targetLocator) {
<del> return TargetLocatorWrapper.wrapTargetLocator(this, targetLocator, getTargetLocatorWrapperClass());
<del> }
<del>
<ide> @Override
<ide> public Navigation navigate() {
<ide> return wrapNavigation(getWrappedDriver().navigate());
<ide> }
<ide>
<del> private Navigation wrapNavigation(final Navigation navigator) {
<del> return NavigationWrapper.wrapNavigation(this, navigator, getNavigationWrapperClass());
<del> }
<del>
<ide> @Override
<ide> public Options manage() {
<del> return getWrappedDriver().manage();
<add> return wrapOptions(getWrappedDriver().manage());
<ide> }
<ide>
<ide> @Override
<ide> public Object executeScript(String script, Object... args) {
<ide> WebDriver driver = getWrappedDriver();
<ide> if (driver instanceof JavascriptExecutor) {
<del> return ((JavascriptExecutor) driver).executeScript(script, args);
<add> return wrapObject(((JavascriptExecutor) driver).executeScript(script, args));
<ide> } else {
<ide> throw new WebDriverException("Wrapped webdriver does not support JavascriptExecutor: " + driver);
<ide> }
<ide> public Object executeAsyncScript(String script, Object... args) {
<ide> WebDriver driver = getWrappedDriver();
<ide> if (driver instanceof JavascriptExecutor) {
<del> return ((JavascriptExecutor) driver).executeAsyncScript(script, args);
<add> return wrapObject(((JavascriptExecutor) driver).executeAsyncScript(script, args));
<ide> } else {
<ide> throw new WebDriverException("Wrapped webdriver does not support JavascriptExecutor: " + driver);
<ide> }
<ide> /**
<ide> * Builds a {@link Proxy} implementing all interfaces of original driver. It will delegate calls to
<ide> * wrapper when wrapper implements the requested method otherwise to original driver.
<del> *
<del> * @param driver the wrapped driver
<del> * @param wrapper the object wrapping the driver
<ide> */
<ide> public final WebDriver getDriver() {
<ide> if (enhancedDriver != null) {
<ide> @Override
<ide> public String getCssValue(final String propertyName) {
<ide> return getWrappedElement().getCssValue(propertyName);
<add> }
<add>
<add> public Coordinates getCoordinates() {
<add> Locatable locatable = (Locatable) getWrappedElement();
<add> return getDriverWrapper().wrapCoordinates(locatable.getCoordinates());
<ide> }
<ide>
<ide> /**
<ide>
<ide> @Override
<ide> public Alert alert() {
<del> return getWrappedTargetLocator().alert();
<add> return getDriverWrapper().wrapAlert(getWrappedTargetLocator().alert());
<ide> }
<ide>
<ide> /**
<ide> * @param alert the underlying alert
<ide> * @param wrapperClass the class of a wrapper
<ide> */
<del> public final static Alert wrapNavigation(final WebDriverWrapper driverWrapper, final Alert alert, final Class<? extends AlertWrapper> wrapperClass) {
<add> public final static Alert wrapAlert(final WebDriverWrapper driverWrapper, final Alert alert, final Class<? extends AlertWrapper> wrapperClass) {
<ide> AlertWrapper wrapper = null;
<ide> Constructor<? extends AlertWrapper> constructor = null;
<ide> if (wrapperClass.getEnclosingClass() != null) {
<ide>
<ide> protected void onError(Method method, InvocationTargetException e, Object[] args) {
<ide> }
<del>
<del> }
<del>
<add> }
<add>
<add> public static class OptionsWrapper implements Options {
<add>
<add> private final Options originalOptions;
<add> private final WebDriverWrapper driverWrapper;
<add>
<add> public OptionsWrapper(final WebDriverWrapper driverWrapper, final Options options) {
<add> originalOptions = options;
<add> this.driverWrapper = driverWrapper;
<add> }
<add>
<add> public final Options getWrappedOptions() {
<add> return originalOptions;
<add> }
<add>
<add> private WebDriverWrapper getDriverWrapper() {
<add> return driverWrapper;
<add> }
<add>
<add> @Override
<add> public void addCookie(Cookie cookie) {
<add> getWrappedOptions().addCookie(cookie);
<add> }
<add>
<add> @Override
<add> public void deleteCookieNamed(String name) {
<add> getWrappedOptions().deleteCookieNamed(name);
<add> }
<add>
<add> @Override
<add> public void deleteCookie(Cookie cookie) {
<add> getWrappedOptions().deleteCookie(cookie);
<add> }
<add>
<add> @Override
<add> public void deleteAllCookies() {
<add> getWrappedOptions().deleteAllCookies();
<add> }
<add>
<add> @Override
<add> public Set<Cookie> getCookies() {
<add> return getWrappedOptions().getCookies();
<add> }
<add>
<add> @Override
<add> public Cookie getCookieNamed(String name) {
<add> return getWrappedOptions().getCookieNamed(name);
<add> }
<add>
<add> @Override
<add> public Timeouts timeouts() {
<add> return getDriverWrapper().wrapTimeouts(getWrappedOptions().timeouts());
<add> }
<add>
<add> @Override
<add> public ImeHandler ime() {
<add> return getWrappedOptions().ime();
<add> }
<add>
<add> @Override
<add> public Window window() {
<add> return getDriverWrapper().wrapWindow(getWrappedOptions().window());
<add> }
<add>
<add> @Override
<add> public Logs logs() {
<add> return getWrappedOptions().logs();
<add> }
<add>
<add> /**
<add> * Builds a {@link Proxy} implementing all interfaces of original options. It will delegate calls to
<add> * wrapper when wrapper implements the requested method otherwise to original options.
<add> *
<add> * @param driverWrapper the underlying driver's wrapper
<add> * @param options the underlying options
<add> * @param wrapperClass the class of a wrapper
<add> */
<add> public final static Options wrapOptions(final WebDriverWrapper driverWrapper, final Options options, final Class<? extends OptionsWrapper> wrapperClass) {
<add> OptionsWrapper wrapper = null;
<add> Constructor<? extends OptionsWrapper> constructor = null;
<add> if (wrapperClass.getEnclosingClass() != null) {
<add> try {
<add> constructor = wrapperClass.getConstructor(wrapperClass.getEnclosingClass(), Options.class);
<add> } catch (Exception e) {
<add> }
<add> }
<add> if (constructor == null) {
<add> try {
<add> constructor = wrapperClass.getConstructor(WebDriverWrapper.class, Options.class);
<add> } catch (Exception e) {
<add> }
<add> }
<add> if (constructor == null) {
<add> throw new Error("Element wrapper class " + wrapperClass + " does not provide an appropriate constructor");
<add> }
<add> try {
<add> wrapper = constructor.newInstance(driverWrapper, options);
<add> } catch (Exception e) {
<add> throw new Error("Can't create a new wrapper object", e);
<add> }
<add> return wrapper.wrapOptions();
<add> }
<add>
<add> /**
<add> * Builds a {@link Proxy} implementing all interfaces of original options. It will delegate calls to
<add> * wrapper when wrapper implements the requested method otherwise to original options.
<add> */
<add> public final Options wrapOptions() {
<add> final Options options = getWrappedOptions();
<add> final Set<Class<?>> wrapperInterfaces = extractInterfaces(this);
<add>
<add> final InvocationHandler handler = new InvocationHandler() {
<add> public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
<add> try {
<add> if (wrapperInterfaces.contains(method.getDeclaringClass())) {
<add> beforeMethod(method, args);
<add> Object result = callMethod(method, args);
<add> afterMethod(method, result, args);
<add> return result;
<add> }
<add> return method.invoke(options, args);
<add> } catch (InvocationTargetException e) {
<add> onError(method, e, args);
<add> throw e.getTargetException();
<add> }
<add> }
<add> };
<add>
<add> Set<Class<?>> allInterfaces = extractInterfaces(options);
<add> allInterfaces.addAll(wrapperInterfaces);
<add> Class<?>[] allInterfacesArray = allInterfaces.toArray(new Class<?>[allInterfaces.size()]);
<add>
<add> return (Options) Proxy.newProxyInstance(
<add> this.getClass().getClassLoader(),
<add> allInterfaces.toArray(allInterfacesArray),
<add> handler);
<add> }
<add>
<add> protected void beforeMethod(Method method, Object[] args) {
<add> }
<add>
<add> protected Object callMethod(Method method, Object[] args) throws Throwable {
<add> return method.invoke(this, args);
<add> }
<add>
<add> protected void afterMethod(Method method, Object res, Object[] args) {
<add> }
<add>
<add> protected void onError(Method method, InvocationTargetException e, Object[] args) {
<add> }
<add> }
<add>
<add> public static class TimeoutsWrapper implements Timeouts {
<add>
<add> private final Timeouts originalTimeouts;
<add> private final WebDriverWrapper driverWrapper;
<add>
<add> public TimeoutsWrapper(final WebDriverWrapper driverWrapper, final Timeouts timeouts) {
<add> originalTimeouts = timeouts;
<add> this.driverWrapper = driverWrapper;
<add> }
<add>
<add> public final Timeouts getWrappedTimeouts() {
<add> return originalTimeouts;
<add> }
<add>
<add> private WebDriverWrapper getDriverWrapper() {
<add> return driverWrapper;
<add> }
<add>
<add> @Override
<add> public Timeouts implicitlyWait(long timeout, TimeUnit timeUnit) {
<add> getWrappedTimeouts().implicitlyWait(timeout, timeUnit);
<add> return this;
<add> }
<add>
<add> @Override
<add> public Timeouts setScriptTimeout(long timeout, TimeUnit timeUnit) {
<add> getWrappedTimeouts().setScriptTimeout(timeout, timeUnit);
<add> return this;
<add> }
<add>
<add> @Override
<add> public Timeouts pageLoadTimeout(long timeout, TimeUnit timeUnit) {
<add> getWrappedTimeouts().pageLoadTimeout(timeout, timeUnit);
<add> return this;
<add> }
<add>
<add> /**
<add> * Builds a {@link Proxy} implementing all interfaces of original timeouts. It will delegate calls to
<add> * wrapper when wrapper implements the requested method otherwise to original timeouts.
<add> *
<add> * @param driverWrapper the underlying driver's wrapper
<add> * @param timeouts the underlying timeouts
<add> * @param wrapperClass the class of a wrapper
<add> */
<add> public final static Timeouts wrapTimeouts(final WebDriverWrapper driverWrapper, final Timeouts timeouts, final Class<? extends TimeoutsWrapper> wrapperClass) {
<add> TimeoutsWrapper wrapper = null;
<add> Constructor<? extends TimeoutsWrapper> constructor = null;
<add> if (wrapperClass.getEnclosingClass() != null) {
<add> try {
<add> constructor = wrapperClass.getConstructor(wrapperClass.getEnclosingClass(), Timeouts.class);
<add> } catch (Exception e) {
<add> }
<add> }
<add> if (constructor == null) {
<add> try {
<add> constructor = wrapperClass.getConstructor(WebDriverWrapper.class, Timeouts.class);
<add> } catch (Exception e) {
<add> }
<add> }
<add> if (constructor == null) {
<add> throw new Error("Element wrapper class " + wrapperClass + " does not provide an appropriate constructor");
<add> }
<add> try {
<add> wrapper = constructor.newInstance(driverWrapper, timeouts);
<add> } catch (Exception e) {
<add> throw new Error("Can't create a new wrapper object", e);
<add> }
<add> return wrapper.wrapTimeouts();
<add> }
<add>
<add> /**
<add> * Builds a {@link Proxy} implementing all interfaces of original timeouts. It will delegate calls to
<add> * wrapper when wrapper implements the requested method otherwise to original timeouts.
<add> */
<add> public final Timeouts wrapTimeouts() {
<add> final Timeouts timeouts = getWrappedTimeouts();
<add> final Set<Class<?>> wrapperInterfaces = extractInterfaces(this);
<add>
<add> final InvocationHandler handler = new InvocationHandler() {
<add> public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
<add> try {
<add> if (wrapperInterfaces.contains(method.getDeclaringClass())) {
<add> beforeMethod(method, args);
<add> Object result = callMethod(method, args);
<add> afterMethod(method, result, args);
<add> return result;
<add> }
<add> return method.invoke(timeouts, args);
<add> } catch (InvocationTargetException e) {
<add> onError(method, e, args);
<add> throw e.getTargetException();
<add> }
<add> }
<add> };
<add>
<add> Set<Class<?>> allInterfaces = extractInterfaces(timeouts);
<add> allInterfaces.addAll(wrapperInterfaces);
<add> Class<?>[] allInterfacesArray = allInterfaces.toArray(new Class<?>[allInterfaces.size()]);
<add>
<add> return (Timeouts) Proxy.newProxyInstance(
<add> this.getClass().getClassLoader(),
<add> allInterfaces.toArray(allInterfacesArray),
<add> handler);
<add> }
<add>
<add> protected void beforeMethod(Method method, Object[] args) {
<add> }
<add>
<add> protected Object callMethod(Method method, Object[] args) throws Throwable {
<add> return method.invoke(this, args);
<add> }
<add>
<add> protected void afterMethod(Method method, Object res, Object[] args) {
<add> }
<add>
<add> protected void onError(Method method, InvocationTargetException e, Object[] args) {
<add> }
<add> }
<add>
<add> public static class WindowWrapper implements Window {
<add>
<add> private final Window originalWindow;
<add> private final WebDriverWrapper driverWrapper;
<add>
<add> public WindowWrapper(final WebDriverWrapper driverWrapper, final Window window) {
<add> originalWindow = window;
<add> this.driverWrapper = driverWrapper;
<add> }
<add>
<add> public final Window getWrappedWindow() {
<add> return originalWindow;
<add> }
<add>
<add> private WebDriverWrapper getDriverWrapper() {
<add> return driverWrapper;
<add> }
<add>
<add> @Override
<add> public void setSize(Dimension size) {
<add> getWrappedWindow().setSize(size);
<add> }
<add>
<add> @Override
<add> public void setPosition(Point position) {
<add> getWrappedWindow().setPosition(position);
<add> }
<add>
<add> @Override
<add> public Dimension getSize() {
<add> return getWrappedWindow().getSize();
<add> }
<add>
<add> @Override
<add> public Point getPosition() {
<add> return getWrappedWindow().getPosition();
<add> }
<add>
<add> @Override
<add> public void maximize() {
<add> getWrappedWindow().maximize();
<add> }
<add>
<add> /**
<add> * Builds a {@link Proxy} implementing all interfaces of original window. It will delegate calls to
<add> * wrapper when wrapper implements the requested method otherwise to original window.
<add> *
<add> * @param driverWrapper the underlying driver's wrapper
<add> * @param window the underlying window
<add> * @param wrapperClass the class of a wrapper
<add> */
<add> public final static Window wrapWindow(final WebDriverWrapper driverWrapper, final Window window, final Class<? extends WindowWrapper> wrapperClass) {
<add> WindowWrapper wrapper = null;
<add> Constructor<? extends WindowWrapper> constructor = null;
<add> if (wrapperClass.getEnclosingClass() != null) {
<add> try {
<add> constructor = wrapperClass.getConstructor(wrapperClass.getEnclosingClass(), Window.class);
<add> } catch (Exception e) {
<add> }
<add> }
<add> if (constructor == null) {
<add> try {
<add> constructor = wrapperClass.getConstructor(WebDriverWrapper.class, Window.class);
<add> } catch (Exception e) {
<add> }
<add> }
<add> if (constructor == null) {
<add> throw new Error("Element wrapper class " + wrapperClass + " does not provide an appropriate constructor");
<add> }
<add> try {
<add> wrapper = constructor.newInstance(driverWrapper, window);
<add> } catch (Exception e) {
<add> throw new Error("Can't create a new wrapper object", e);
<add> }
<add> return wrapper.wrapWindow();
<add> }
<add>
<add> /**
<add> * Builds a {@link Proxy} implementing all interfaces of original window. It will delegate calls to
<add> * wrapper when wrapper implements the requested method otherwise to original window.
<add> */
<add> public final Window wrapWindow() {
<add> final Window window = getWrappedWindow();
<add> final Set<Class<?>> wrapperInterfaces = extractInterfaces(this);
<add>
<add> final InvocationHandler handler = new InvocationHandler() {
<add> public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
<add> try {
<add> if (wrapperInterfaces.contains(method.getDeclaringClass())) {
<add> beforeMethod(method, args);
<add> Object result = callMethod(method, args);
<add> afterMethod(method, result, args);
<add> return result;
<add> }
<add> return method.invoke(window, args);
<add> } catch (InvocationTargetException e) {
<add> onError(method, e, args);
<add> throw e.getTargetException();
<add> }
<add> }
<add> };
<add>
<add> Set<Class<?>> allInterfaces = extractInterfaces(window);
<add> allInterfaces.addAll(wrapperInterfaces);
<add> Class<?>[] allInterfacesArray = allInterfaces.toArray(new Class<?>[allInterfaces.size()]);
<add>
<add> return (Window) Proxy.newProxyInstance(
<add> this.getClass().getClassLoader(),
<add> allInterfaces.toArray(allInterfacesArray),
<add> handler);
<add> }
<add>
<add> protected void beforeMethod(Method method, Object[] args) {
<add> }
<add>
<add> protected Object callMethod(Method method, Object[] args) throws Throwable {
<add> return method.invoke(this, args);
<add> }
<add>
<add> protected void afterMethod(Method method, Object res, Object[] args) {
<add> }
<add>
<add> protected void onError(Method method, InvocationTargetException e, Object[] args) {
<add> }
<add> }
<add>
<add> public static class CoordinatesWrapper implements Coordinates {
<add>
<add> private final Coordinates originalCoordinates;
<add> private final WebDriverWrapper driverWrapper;
<add>
<add> public CoordinatesWrapper(final WebDriverWrapper driverWrapper, final Coordinates coordinates) {
<add> originalCoordinates = coordinates;
<add> this.driverWrapper = driverWrapper;
<add> }
<add>
<add> public final Coordinates getWrappedCoordinates() {
<add> return originalCoordinates;
<add> }
<add>
<add> private WebDriverWrapper getDriverWrapper() {
<add> return driverWrapper;
<add> }
<add>
<add> @Override
<add> public Point onScreen() {
<add> return getWrappedCoordinates().onScreen();
<add> }
<add>
<add> @Override
<add> public Point inViewPort() {
<add> return getWrappedCoordinates().inViewPort();
<add> }
<add>
<add> @Override
<add> public Point onPage() {
<add> return getWrappedCoordinates().onPage();
<add> }
<add>
<add> @Override
<add> public Object getAuxiliary() {
<add> return getDriverWrapper().wrapObject(getWrappedCoordinates().getAuxiliary());
<add> }
<add>
<add> /**
<add> * Builds a {@link Proxy} implementing all interfaces of original coordinates. It will delegate calls to
<add> * wrapper when wrapper implements the requested method otherwise to original coordinates.
<add> *
<add> * @param driverWrapper the underlying driver's wrapper
<add> * @param coordinates the underlying coordinates
<add> * @param wrapperClass the class of a wrapper
<add> */
<add> public final static Coordinates wrapCoordinates(final WebDriverWrapper driverWrapper, final Coordinates coordinates, final Class<? extends CoordinatesWrapper> wrapperClass) {
<add> CoordinatesWrapper wrapper = null;
<add> Constructor<? extends CoordinatesWrapper> constructor = null;
<add> if (wrapperClass.getEnclosingClass() != null) {
<add> try {
<add> constructor = wrapperClass.getConstructor(wrapperClass.getEnclosingClass(), Coordinates.class);
<add> } catch (Exception e) {
<add> }
<add> }
<add> if (constructor == null) {
<add> try {
<add> constructor = wrapperClass.getConstructor(WebDriverWrapper.class, Coordinates.class);
<add> } catch (Exception e) {
<add> }
<add> }
<add> if (constructor == null) {
<add> throw new Error("Element wrapper class " + wrapperClass + " does not provide an appropriate constructor");
<add> }
<add> try {
<add> wrapper = constructor.newInstance(driverWrapper, coordinates);
<add> } catch (Exception e) {
<add> throw new Error("Can't create a new wrapper object", e);
<add> }
<add> return wrapper.wrapCoordinates();
<add> }
<add>
<add> /**
<add> * Builds a {@link Proxy} implementing all interfaces of original coordinates. It will delegate calls to
<add> * wrapper when wrapper implements the requested method otherwise to original coordinates.
<add> */
<add> public final Coordinates wrapCoordinates() {
<add> final Coordinates coordinates = getWrappedCoordinates();
<add> final Set<Class<?>> wrapperInterfaces = extractInterfaces(this);
<add>
<add> final InvocationHandler handler = new InvocationHandler() {
<add> public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
<add> try {
<add> if (wrapperInterfaces.contains(method.getDeclaringClass())) {
<add> beforeMethod(method, args);
<add> Object result = callMethod(method, args);
<add> afterMethod(method, result, args);
<add> return result;
<add> }
<add> return method.invoke(coordinates, args);
<add> } catch (InvocationTargetException e) {
<add> onError(method, e, args);
<add> throw e.getTargetException();
<add> }
<add> }
<add> };
<add>
<add> Set<Class<?>> allInterfaces = extractInterfaces(coordinates);
<add> allInterfaces.addAll(wrapperInterfaces);
<add> Class<?>[] allInterfacesArray = allInterfaces.toArray(new Class<?>[allInterfaces.size()]);
<add>
<add> return (Coordinates) Proxy.newProxyInstance(
<add> this.getClass().getClassLoader(),
<add> allInterfaces.toArray(allInterfacesArray),
<add> handler);
<add> }
<add>
<add> protected void beforeMethod(Method method, Object[] args) {
<add> }
<add>
<add> protected Object callMethod(Method method, Object[] args) throws Throwable {
<add> return method.invoke(this, args);
<add> }
<add>
<add> protected void afterMethod(Method method, Object res, Object[] args) {
<add> }
<add>
<add> protected void onError(Method method, InvocationTargetException e, Object[] args) {
<add> }
<add> }
<add>
<ide> private static Set<Class<?>> extractInterfaces(final Object object) {
<ide> return extractInterfaces(object.getClass());
<ide> }
<ide> }
<ide> extractInterfaces(collector, clazz.getSuperclass());
<ide> }
<del>
<ide> }
|
|
JavaScript
|
mit
|
ae7d6db5ef89054f70f54f4225d765e4f97c6f4c
| 0 |
AlexWang1987/promisify-fs
|
/*eslint-disable*/
var Promise = require('bluebird');
var fs = require('fs');
var path = require('path');
var shell = require('shelljs');
var ok = require('assert');
/**
* expose promisified fs
*/
var pfs = module.exports = {};
/**
* The file specified by `file_path` must be exactly file
* @param string file_path file path
* @return promise promise
*/
pfs.fileExists = function (file_path) {
return Promise.fromCallback(function (node_cb) {
fs.stat(file_path, node_cb)
})
.then(function (stat) {
if (stat.isFile()) {
stat['abs_path'] = path.resolve(file_path);
return stat
}
//file is not exactly the `file` type
return null
})
.error(function (e) {
if (e.code == 'ENOENT') {
//file does not exist
return null
}
//other potential erros, needed to be exposed out
throw e.cause
})
}
/**
* The file specified by `folder_path` must be exactly folder
* @param string folder_path file path
* @return promise promise
*/
pfs.folderExists = function (folder_path) {
return Promise.fromCallback(function (node_cb) {
fs.stat(folder_path, node_cb)
})
.then(function (stat) {
if (stat.isDirectory()) {
stat['abs_path'] = path.resolve(folder_path);
return stat
}
//file is not exactly the `folder` type
return null
})
.error(function (e) {
//folder does not exist
if (e.code == 'ENOENT') {
return null
}
//other potential erros, needed to be exposed out
throw e.cause
})
}
/**
* Read file content by `file_path` , warning: the file specified must be a exactly `file` type
* @param string file_path relative / absolute path
* @param {[type]} options more options, please refer to https://nodejs.org/api/fs.html#fs_fs_readfile_file_options_callback
* @return promise
*/
pfs.readFile = function (file_path, options) {
var options = options || {};
options['encoding'] = options['encoding'] || 'utf8';
return Promise.fromCallback(function (node_cb) {
fs.readFile(file_path, options, node_cb)
})
}
/**
* read file as JSON Object
* @param {string} file_path file
* @param {object} options
* @return {promise} json
*/
pfs.readJSON = function (file_path, options) {
var options = options || {};
options['encoding'] = options['encoding'] || 'utf8';
return pfs
.readFile(file_path)
.then(JSON.parse)
}
/**
* Write data with `string` `buffer` `object` type to a file, it will override former file, so be cautious to verify if it exists ahead.
* @param string file_path relative/absolute path
* @param {string/object/buffer} data string or buffer are internally supported, if you pass a object, 'JSON.stringify' method will be applied.
* @param {object} options more options, please refer to https://nodejs.org/api/fs.html#fs_fs_writefile_file_data_options_callback
* @return promise
*/
pfs.writeFile = function (file_path, data, options) {
var options = options || {};
options['encoding'] = options['encoding'] || 'utf8';
return Promise.try(function () {
if (!(file_path && data)) {
throw '<file_path> , <data> are required.'
}
})
.then(function (d) {
return Promise.fromCallback(function (node_cb) {
//try to stringify
if (!~['String', 'Buffer'].indexOf(data.constructor.name)) {
data = JSON.stringify(data, options.replacer || null, options.space || null);
}
fs.writeFile(file_path, data, options, node_cb)
})
})
}
/**
* delete file
* @param {string} file_path
* @return promise return
*/
pfs.delFile = function (file_path) {
return Promise.try(function () {
var result = shell.rm(('-f'), file_path);
if (result.code) {
throw result
}
});
}
/**
* YOU KNOW WHAT YOU ARE DOING !!!!!
* @param {string} folder_path [description]
* @param {boolean} force forcely to delete all files in this folder recursively.
* @return promise
*/
pfs.delFolder = function (folder_path, force) {
return Promise.try(function () {
var result = shell.rm('-r' + (force ? 'f' : ''), folder_path);
if (result.code) {
throw result
}
})
}
/**
* clone Folder
* @param {string} source_folder
* @param {string} dest_folder
* @param {boolen} force it will forcely overide dest-files
* @return {promise}
*/
pfs.cloneFolder = function (source_folder, dest_folder, force) {
return Promise.try(function () {
var result = shell.cp('-r' + (force ? 'f' : 'n'), source_folder, dest_folder);
if (result.code) {
//Throw result
console.log('cp shelljs bug still exists, whereas the task is done.');
}
})
}
/**
* create a folder recursively
* @param {string} folder_path relative or absolute are both supported
* @return promise
*/
pfs.addFolder = function (folder_path) {
return Promise.try(function () {
var result = shell.mkdir('-p', folder_path);
if (result.code) {
throw result
}
})
}
/**
* getModulePackInfo
* @param {string} [module] moudle is optional. default value is require.main module.
* @return {Promise}
*/
pfs.getModulePackInfo = function (module) {
return Promise.try(function () {
//specified module
var node_modules_paths = [];
if (module && module.paths && module.paths.length) {
node_modules_paths = module.paths;
}
//require main module
if (!node_modules_paths.length) node_modules_paths = require.main.paths;
return Promise
.mapSeries(node_modules_paths, function (node_modules_path) {
var pkg_file_path = path.resolve(node_modules_path, '../package.json');
return pfs
.fileExists(pkg_file_path)
.then(function (file_stat) {
if (file_stat) {
throw file_stat; //target package is found. stop iteration.
}
})
})
.then(function () {
throw 'Warning: The main module of process is not distributed by npm ecosystem.';
})
.catch(function (file_stat) {
return pfs.readJSON(file_stat.abs_path);
})
})
}
|
index.js
|
/*eslint-disable*/
var Promise = require('bluebird');
var fs = require('fs');
var path = require('path');
var shell = require('shelljs');
var ok = require('assert');
/**
* expose promisified fs
*/
var pfs = module.exports = {};
/**
* The file specified by `file_path` must be exactly file
* @param string file_path file path
* @return promise promise
*/
pfs.fileExists = function (file_path) {
return Promise.fromCallback(function (node_cb) {
fs.stat(file_path, node_cb)
})
.then(function (stat) {
if (stat.isFile()) {
stat['abs_path'] = path.resolve(file_path);
return stat
}
//file is not exactly the `file` type
return null
})
.error(function (e) {
if (e.code == 'ENOENT') {
//file does not exist
return null
}
//other potential erros, needed to be exposed out
throw e.cause
})
}
/**
* The file specified by `folder_path` must be exactly folder
* @param string folder_path file path
* @return promise promise
*/
pfs.folderExists = function (folder_path) {
return Promise.fromCallback(function (node_cb) {
fs.stat(folder_path, node_cb)
})
.then(function (stat) {
if (stat.isDirectory()) {
stat['abs_path'] = path.resolve(folder_path);
return stat
}
//file is not exactly the `folder` type
return null
})
.error(function (e) {
//folder does not exist
if (e.code == 'ENOENT') {
return null
}
//other potential erros, needed to be exposed out
throw e.cause
})
}
/**
* Read file content by `file_path` , warning: the file specified must be a exactly `file` type
* @param string file_path relative / absolute path
* @param {[type]} options more options, please refer to https://nodejs.org/api/fs.html#fs_fs_readfile_file_options_callback
* @return promise
*/
pfs.readFile = function (file_path, options) {
var options = options || {};
options['encoding'] = options['encoding'] || 'utf8';
return Promise.fromCallback(function (node_cb) {
fs.readFile(file_path, options, node_cb)
})
}
/**
* read file as JSON Object
* @param {string} file_path file
* @param {object} options
* @return {promise} json
*/
pfs.readJSON = function (file_path, options) {
var options = options || {};
options['encoding'] = options['encoding'] || 'utf8';
return pfs
.readFile(file_path)
.then(JSON.parse)
}
/**
* Write data with `string` `buffer` `object` type to a file, it will override former file, so be cautious to verify if it exists ahead.
* @param string file_path relative/absolute path
* @param {string/object/buffer} data string or buffer are internally supported, if you pass a object, 'JSON.stringify' method will be applied.
* @param {object} options more options, please refer to https://nodejs.org/api/fs.html#fs_fs_writefile_file_data_options_callback
* @return promise
*/
pfs.writeFile = function (file_path, data, options) {
var options = options || {};
options['encoding'] = options['encoding'] || 'utf8';
return Promise.try(function () {
if (!(file_path && data)) {
throw '<file_path> , <data> are required.'
}
})
.then(function (d) {
return Promise.fromCallback(function (node_cb) {
//try to stringify
if (!~['String', 'Buffer'].indexOf(data.constructor.name)) {
data = JSON.stringify(data, options.replacer || null, options.space || null);
}
fs.writeFile(file_path, data, options, node_cb)
})
})
}
/**
* delete file
* @param {string} file_path
* @return promise return
*/
pfs.delFile = function (file_path) {
return Promise.try(function () {
var result = shell.rm(('-f'), file_path);
if (result.code) {
throw result
}
});
}
/**
* YOU KNOW WHAT YOU ARE DOING !!!!!
* @param {string} folder_path [description]
* @param {boolean} force forcely to delete all files in this folder recursively.
* @return promise
*/
pfs.delFolder = function (folder_path, force) {
return Promise.try(function () {
var result = shell.rm('-r' + (force ? 'f' : ''), folder_path);
if (result.code) {
throw result
}
})
}
/**
* clone Folder
* @param {string} source_folder
* @param {string} dest_folder
* @param {boolen} force it will forcely overide dest-files
* @return {promise}
*/
pfs.cloneFolder = function (source_folder, dest_folder, force) {
return Promise.try(function () {
var result = shell.cp('-r' + (force ? 'f' : 'n'), source_folder, dest_folder);
if (result.code) {
//Throw result
console.log('This bug still exists, but the task is done.');
}
})
}
/**
* create a folder recursively
* @param {string} folder_path relative or absolute are both supported
* @return promise
*/
pfs.addFolder = function (folder_path) {
return Promise.try(function () {
var result = shell.mkdir('-p', folder_path);
if (result.code) {
throw result
}
})
}
/**
* getModulePackInfo
* @param {string} [module] moudle is optional. default value is require.main module.
* @return {Promise}
*/
pfs.getModulePackInfo = function (module) {
return Promise.try(function () {
//specified module
var node_modules_paths = [];
if (module && module.paths && module.paths.length) {
node_modules_paths = module.paths;
}
//require main module
if (!node_modules_paths.length) node_modules_paths = require.main.paths;
return Promise
.mapSeries(node_modules_paths, function (node_modules_path) {
var pkg_file_path = path.resolve(node_modules_path, '../package.json');
return pfs
.fileExists(pkg_file_path)
.then(function (file_stat) {
if (file_stat) {
throw file_stat; //target package is found. stop iteration.
}
})
})
.then(function () {
throw 'Warning: The main module of process is not distributed by npm ecosystem.';
})
.catch(function (file_stat) {
return pfs.readJSON(file_stat.abs_path);
})
})
}
|
local_dev_commit
|
index.js
|
local_dev_commit
|
<ide><path>ndex.js
<ide> var result = shell.cp('-r' + (force ? 'f' : 'n'), source_folder, dest_folder);
<ide> if (result.code) {
<ide> //Throw result
<del> console.log('This bug still exists, but the task is done.');
<add> console.log('cp shelljs bug still exists, whereas the task is done.');
<ide> }
<ide> })
<ide> }
|
|
Java
|
apache-2.0
|
47dac3d7e9cafb4c3ffef1b834b6df48a9a6c2a1
| 0 |
snurmine/camel,sverkera/camel,acartapanis/camel,mike-kukla/camel,gnodet/camel,FingolfinTEK/camel,chirino/camel,onders86/camel,dpocock/camel,koscejev/camel,apache/camel,mcollovati/camel,YMartsynkevych/camel,pax95/camel,johnpoth/camel,bhaveshdt/camel,CodeSmell/camel,lburgazzoli/camel,pmoerenhout/camel,manuelh9r/camel,isavin/camel,coderczp/camel,neoramon/camel,MohammedHammam/camel,woj-i/camel,partis/camel,mohanaraosv/camel,w4tson/camel,erwelch/camel,stravag/camel,apache/camel,hqstevenson/camel,grgrzybek/camel,trohovsky/camel,JYBESSON/camel,Thopap/camel,satishgummadelli/camel,qst-jdc-labs/camel,ssharma/camel,scranton/camel,tdiesler/camel,brreitme/camel,trohovsky/camel,tarilabs/camel,christophd/camel,woj-i/camel,sabre1041/camel,dpocock/camel,joakibj/camel,yuruki/camel,gautric/camel,adessaigne/camel,pplatek/camel,jameszkw/camel,tkopczynski/camel,apache/camel,Thopap/camel,ssharma/camel,edigrid/camel,skinzer/camel,royopa/camel,MrCoder/camel,Fabryprog/camel,CandleCandle/camel,jonmcewen/camel,logzio/camel,neoramon/camel,bdecoste/camel,bgaudaen/camel,edigrid/camel,prashant2402/camel,drsquidop/camel,objectiser/camel,tdiesler/camel,ge0ffrey/camel,pkletsko/camel,akhettar/camel,yogamaha/camel,zregvart/camel,pplatek/camel,JYBESSON/camel,punkhorn/camel-upstream,davidkarlsen/camel,w4tson/camel,drsquidop/camel,atoulme/camel,chirino/camel,rparree/camel,hqstevenson/camel,NickCis/camel,veithen/camel,pmoerenhout/camel,bhaveshdt/camel,salikjan/camel,dsimansk/camel,igarashitm/camel,tkopczynski/camel,neoramon/camel,pax95/camel,tarilabs/camel,YoshikiHigo/camel,rmarting/camel,qst-jdc-labs/camel,isavin/camel,adessaigne/camel,oalles/camel,bhaveshdt/camel,onders86/camel,iweiss/camel,bfitzpat/camel,snadakuduru/camel,rmarting/camel,qst-jdc-labs/camel,jlpedrosa/camel,edigrid/camel,YMartsynkevych/camel,skinzer/camel,sverkera/camel,punkhorn/camel-upstream,driseley/camel,jollygeorge/camel,lasombra/camel,mike-kukla/camel,yury-vashchyla/camel,ekprayas/camel,scranton/camel,atoulme/camel,jarst/camel,MohammedHammam/camel,tarilabs/camel,acartapanis/camel,duro1/camel,gilfernandes/camel,NetNow/camel,drsquidop/camel,dmvolod/camel,manuelh9r/camel,joakibj/camel,bgaudaen/camel,lasombra/camel,anton-k11/camel,royopa/camel,dvankleef/camel,manuelh9r/camel,hqstevenson/camel,gilfernandes/camel,mzapletal/camel,dkhanolkar/camel,coderczp/camel,tkopczynski/camel,sirlatrom/camel,dvankleef/camel,jpav/camel,anton-k11/camel,yogamaha/camel,jlpedrosa/camel,woj-i/camel,CandleCandle/camel,CandleCandle/camel,gyc567/camel,grange74/camel,josefkarasek/camel,nboukhed/camel,anton-k11/camel,stalet/camel,jkorab/camel,jonmcewen/camel,coderczp/camel,josefkarasek/camel,jollygeorge/camel,jlpedrosa/camel,bgaudaen/camel,mohanaraosv/camel,jameszkw/camel,jkorab/camel,gautric/camel,tarilabs/camel,chirino/camel,RohanHart/camel,YoshikiHigo/camel,satishgummadelli/camel,joakibj/camel,lburgazzoli/apache-camel,iweiss/camel,tdiesler/camel,johnpoth/camel,yury-vashchyla/camel,dsimansk/camel,bfitzpat/camel,nikhilvibhav/camel,rmarting/camel,jarst/camel,edigrid/camel,koscejev/camel,chanakaudaya/camel,atoulme/camel,lburgazzoli/camel,CandleCandle/camel,noelo/camel,dvankleef/camel,trohovsky/camel,logzio/camel,pplatek/camel,FingolfinTEK/camel,joakibj/camel,scranton/camel,RohanHart/camel,davidwilliams1978/camel,driseley/camel,YoshikiHigo/camel,jarst/camel,chanakaudaya/camel,jollygeorge/camel,adessaigne/camel,ge0ffrey/camel,gilfernandes/camel,tlehoux/camel,DariusX/camel,sabre1041/camel,driseley/camel,bgaudaen/camel,anoordover/camel,igarashitm/camel,tlehoux/camel,tkopczynski/camel,erwelch/camel,mnki/camel,tadayosi/camel,ullgren/camel,w4tson/camel,arnaud-deprez/camel,igarashitm/camel,mgyongyosi/camel,partis/camel,nikhilvibhav/camel,ge0ffrey/camel,nboukhed/camel,jpav/camel,maschmid/camel,mohanaraosv/camel,brreitme/camel,dpocock/camel,gyc567/camel,mcollovati/camel,Fabryprog/camel,mcollovati/camel,davidwilliams1978/camel,bfitzpat/camel,skinzer/camel,mike-kukla/camel,manuelh9r/camel,lburgazzoli/apache-camel,rparree/camel,manuelh9r/camel,askannon/camel,hqstevenson/camel,isururanawaka/camel,ge0ffrey/camel,apache/camel,yury-vashchyla/camel,stravag/camel,pax95/camel,acartapanis/camel,w4tson/camel,jameszkw/camel,erwelch/camel,grgrzybek/camel,jpav/camel,grange74/camel,kevinearls/camel,josefkarasek/camel,veithen/camel,askannon/camel,oscerd/camel,isururanawaka/camel,bdecoste/camel,borcsokj/camel,rmarting/camel,sirlatrom/camel,pmoerenhout/camel,josefkarasek/camel,prashant2402/camel,pkletsko/camel,sebi-hgdata/camel,sirlatrom/camel,logzio/camel,logzio/camel,Fabryprog/camel,RohanHart/camel,edigrid/camel,pplatek/camel,tkopczynski/camel,kevinearls/camel,lowwool/camel,veithen/camel,sebi-hgdata/camel,snadakuduru/camel,borcsokj/camel,satishgummadelli/camel,isavin/camel,haku/camel,sabre1041/camel,jonmcewen/camel,gyc567/camel,eformat/camel,koscejev/camel,sabre1041/camel,lburgazzoli/camel,gyc567/camel,YoshikiHigo/camel,nikhilvibhav/camel,ssharma/camel,royopa/camel,brreitme/camel,jmandawg/camel,satishgummadelli/camel,curso007/camel,christophd/camel,ekprayas/camel,pmoerenhout/camel,driseley/camel,gnodet/camel,jkorab/camel,anoordover/camel,askannon/camel,scranton/camel,mzapletal/camel,RohanHart/camel,jameszkw/camel,salikjan/camel,johnpoth/camel,joakibj/camel,YoshikiHigo/camel,gilfernandes/camel,yury-vashchyla/camel,jmandawg/camel,edigrid/camel,qst-jdc-labs/camel,objectiser/camel,nicolaferraro/camel,JYBESSON/camel,pmoerenhout/camel,pplatek/camel,jarst/camel,ramonmaruko/camel,partis/camel,pkletsko/camel,tlehoux/camel,chirino/camel,FingolfinTEK/camel,ullgren/camel,chanakaudaya/camel,tdiesler/camel,haku/camel,dkhanolkar/camel,erwelch/camel,duro1/camel,mnki/camel,noelo/camel,yogamaha/camel,oalles/camel,jameszkw/camel,lasombra/camel,w4tson/camel,acartapanis/camel,rparree/camel,maschmid/camel,gyc567/camel,davidwilliams1978/camel,onders86/camel,kevinearls/camel,tlehoux/camel,lburgazzoli/camel,lowwool/camel,veithen/camel,lowwool/camel,skinzer/camel,dvankleef/camel,driseley/camel,tdiesler/camel,cunningt/camel,allancth/camel,eformat/camel,bhaveshdt/camel,lburgazzoli/apache-camel,atoulme/camel,coderczp/camel,snurmine/camel,dkhanolkar/camel,isururanawaka/camel,borcsokj/camel,yuruki/camel,mohanaraosv/camel,mgyongyosi/camel,mnki/camel,sebi-hgdata/camel,Thopap/camel,snurmine/camel,partis/camel,ekprayas/camel,punkhorn/camel-upstream,cunningt/camel,brreitme/camel,snurmine/camel,MrCoder/camel,DariusX/camel,davidwilliams1978/camel,dmvolod/camel,ullgren/camel,rparree/camel,nboukhed/camel,nikvaessen/camel,bdecoste/camel,erwelch/camel,ramonmaruko/camel,yogamaha/camel,eformat/camel,haku/camel,CandleCandle/camel,CodeSmell/camel,jollygeorge/camel,jpav/camel,scranton/camel,dpocock/camel,FingolfinTEK/camel,NickCis/camel,Thopap/camel,oalles/camel,tadayosi/camel,neoramon/camel,akhettar/camel,driseley/camel,johnpoth/camel,curso007/camel,yury-vashchyla/camel,igarashitm/camel,partis/camel,davidkarlsen/camel,NetNow/camel,RohanHart/camel,tarilabs/camel,coderczp/camel,drsquidop/camel,bdecoste/camel,jmandawg/camel,lburgazzoli/apache-camel,onders86/camel,christophd/camel,isavin/camel,dkhanolkar/camel,tadayosi/camel,iweiss/camel,pkletsko/camel,logzio/camel,jmandawg/camel,bfitzpat/camel,chanakaudaya/camel,dpocock/camel,grgrzybek/camel,tadayosi/camel,mnki/camel,cunningt/camel,pplatek/camel,curso007/camel,bdecoste/camel,borcsokj/camel,tarilabs/camel,grgrzybek/camel,gautric/camel,oalles/camel,cunningt/camel,akhettar/camel,anoordover/camel,johnpoth/camel,bdecoste/camel,MrCoder/camel,johnpoth/camel,NickCis/camel,igarashitm/camel,lowwool/camel,grgrzybek/camel,logzio/camel,dvankleef/camel,NetNow/camel,royopa/camel,jkorab/camel,dmvolod/camel,cunningt/camel,jlpedrosa/camel,dmvolod/camel,gautric/camel,mgyongyosi/camel,sverkera/camel,woj-i/camel,YMartsynkevych/camel,anoordover/camel,stalet/camel,noelo/camel,kevinearls/camel,maschmid/camel,cunningt/camel,pkletsko/camel,ge0ffrey/camel,ullgren/camel,mzapletal/camel,neoramon/camel,lburgazzoli/camel,yuruki/camel,objectiser/camel,christophd/camel,pplatek/camel,oscerd/camel,yogamaha/camel,sebi-hgdata/camel,maschmid/camel,prashant2402/camel,arnaud-deprez/camel,ssharma/camel,jlpedrosa/camel,alvinkwekel/camel,RohanHart/camel,mgyongyosi/camel,nikvaessen/camel,duro1/camel,woj-i/camel,YMartsynkevych/camel,jamesnetherton/camel,yogamaha/camel,allancth/camel,sverkera/camel,josefkarasek/camel,akhettar/camel,davidkarlsen/camel,rmarting/camel,NetNow/camel,eformat/camel,ekprayas/camel,yuruki/camel,stravag/camel,MohammedHammam/camel,stalet/camel,anton-k11/camel,acartapanis/camel,nikvaessen/camel,NetNow/camel,nboukhed/camel,jkorab/camel,sebi-hgdata/camel,anoordover/camel,akhettar/camel,oscerd/camel,nboukhed/camel,punkhorn/camel-upstream,Thopap/camel,anton-k11/camel,haku/camel,prashant2402/camel,jamesnetherton/camel,jpav/camel,yury-vashchyla/camel,isururanawaka/camel,ssharma/camel,MrCoder/camel,sabre1041/camel,gnodet/camel,mohanaraosv/camel,kevinearls/camel,dmvolod/camel,hqstevenson/camel,MrCoder/camel,chanakaudaya/camel,dpocock/camel,YMartsynkevych/camel,ekprayas/camel,drsquidop/camel,stravag/camel,oalles/camel,snurmine/camel,DariusX/camel,sverkera/camel,CodeSmell/camel,jonmcewen/camel,pkletsko/camel,snurmine/camel,grange74/camel,scranton/camel,lasombra/camel,ssharma/camel,isavin/camel,koscejev/camel,drsquidop/camel,allancth/camel,adessaigne/camel,rparree/camel,MohammedHammam/camel,stravag/camel,qst-jdc-labs/camel,gnodet/camel,iweiss/camel,mnki/camel,duro1/camel,NickCis/camel,anton-k11/camel,sirlatrom/camel,hqstevenson/camel,satishgummadelli/camel,NickCis/camel,mcollovati/camel,jlpedrosa/camel,lburgazzoli/apache-camel,ramonmaruko/camel,snadakuduru/camel,alvinkwekel/camel,jmandawg/camel,koscejev/camel,dvankleef/camel,tlehoux/camel,tdiesler/camel,gautric/camel,jamesnetherton/camel,arnaud-deprez/camel,bhaveshdt/camel,FingolfinTEK/camel,NetNow/camel,prashant2402/camel,gilfernandes/camel,isururanawaka/camel,chirino/camel,sirlatrom/camel,apache/camel,borcsokj/camel,noelo/camel,prashant2402/camel,mzapletal/camel,anoordover/camel,noelo/camel,oscerd/camel,tadayosi/camel,tkopczynski/camel,duro1/camel,nikhilvibhav/camel,mike-kukla/camel,chirino/camel,askannon/camel,mnki/camel,oscerd/camel,MohammedHammam/camel,jamesnetherton/camel,jonmcewen/camel,dsimansk/camel,stalet/camel,isururanawaka/camel,joakibj/camel,mzapletal/camel,borcsokj/camel,skinzer/camel,grange74/camel,ramonmaruko/camel,duro1/camel,zregvart/camel,lowwool/camel,maschmid/camel,jamesnetherton/camel,veithen/camel,lasombra/camel,MohammedHammam/camel,arnaud-deprez/camel,pmoerenhout/camel,jamesnetherton/camel,bhaveshdt/camel,dkhanolkar/camel,igarashitm/camel,dsimansk/camel,dmvolod/camel,jkorab/camel,pax95/camel,atoulme/camel,askannon/camel,noelo/camel,brreitme/camel,trohovsky/camel,bgaudaen/camel,eformat/camel,objectiser/camel,bfitzpat/camel,FingolfinTEK/camel,partis/camel,CodeSmell/camel,christophd/camel,CandleCandle/camel,grange74/camel,curso007/camel,curso007/camel,snadakuduru/camel,trohovsky/camel,oscerd/camel,stalet/camel,sirlatrom/camel,allancth/camel,w4tson/camel,jarst/camel,royopa/camel,skinzer/camel,onders86/camel,mohanaraosv/camel,lowwool/camel,zregvart/camel,iweiss/camel,chanakaudaya/camel,atoulme/camel,josefkarasek/camel,jollygeorge/camel,veithen/camel,lasombra/camel,ramonmaruko/camel,snadakuduru/camel,oalles/camel,stravag/camel,lburgazzoli/apache-camel,snadakuduru/camel,satishgummadelli/camel,arnaud-deprez/camel,mike-kukla/camel,davidwilliams1978/camel,Thopap/camel,gyc567/camel,haku/camel,zregvart/camel,MrCoder/camel,bgaudaen/camel,sebi-hgdata/camel,akhettar/camel,haku/camel,gautric/camel,JYBESSON/camel,ge0ffrey/camel,stalet/camel,jonmcewen/camel,iweiss/camel,dkhanolkar/camel,woj-i/camel,JYBESSON/camel,dsimansk/camel,Fabryprog/camel,acartapanis/camel,allancth/camel,curso007/camel,lburgazzoli/camel,JYBESSON/camel,logzio/camel,YoshikiHigo/camel,jarst/camel,adessaigne/camel,ramonmaruko/camel,brreitme/camel,dsimansk/camel,jpav/camel,alvinkwekel/camel,davidkarlsen/camel,maschmid/camel,nicolaferraro/camel,pax95/camel,YMartsynkevych/camel,mgyongyosi/camel,allancth/camel,royopa/camel,onders86/camel,tadayosi/camel,koscejev/camel,mzapletal/camel,davidwilliams1978/camel,ekprayas/camel,yuruki/camel,apache/camel,sabre1041/camel,jollygeorge/camel,manuelh9r/camel,isavin/camel,christophd/camel,grange74/camel,NickCis/camel,gnodet/camel,coderczp/camel,arnaud-deprez/camel,erwelch/camel,DariusX/camel,nicolaferraro/camel,nboukhed/camel,mike-kukla/camel,sverkera/camel,pax95/camel,mgyongyosi/camel,jameszkw/camel,adessaigne/camel,qst-jdc-labs/camel,neoramon/camel,jmandawg/camel,grgrzybek/camel,nikvaessen/camel,kevinearls/camel,tlehoux/camel,nikvaessen/camel,trohovsky/camel,eformat/camel,askannon/camel,nikvaessen/camel,bfitzpat/camel,rmarting/camel,yuruki/camel,rparree/camel,nicolaferraro/camel,gilfernandes/camel,alvinkwekel/camel
|
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultEndpoint;
import org.apache.camel.impl.DefaultExchange;
import org.apache.camel.support.SynchronizationAdapter;
/**
*
*/
public class UnitOfWorkSyncProcessTest extends ContextTestSupport {
private static String consumerThread;
private static String afterThread;
private static String taskThread;
private static String doneThread;
private ExecutorService executorService = Executors.newSingleThreadExecutor();
@Override
protected void tearDown() throws Exception {
executorService.shutdownNow();
super.tearDown();
}
public void testUnitOfWorkSync() throws Exception {
// skip test on AIX
if (isPlatform("aix")) {
return;
}
getMockEndpoint("mock:result").expectedMessageCount(1);
assertMockEndpointsSatisfied();
// should be same thread
assertEquals(taskThread, afterThread);
// should not be same
assertNotSame(doneThread, afterThread);
assertNotSame(doneThread, consumerThread);
// should be same thread
assertEquals(consumerThread, doneThread);
}
@Override
protected RouteBuilder createRouteBuilder() throws Exception {
return new RouteBuilder() {
@Override
public void configure() throws Exception {
from(new MyEndpoint())
.process(new AsyncProcessor() {
@Override
public boolean process(final Exchange exchange, final AsyncCallback callback) {
executorService.submit(new Runnable() {
@Override
public void run() {
taskThread = Thread.currentThread().getName();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// ignore
}
exchange.getIn().setHeader("foo", 123);
callback.done(false);
}
});
return false;
}
@Override
public void process(Exchange exchange) throws Exception {
// noop
}
})
.process(new Processor() {
@Override
public void process(Exchange exchange) throws Exception {
afterThread = Thread.currentThread().getName();
}
})
.to("mock:result");
}
};
}
private final class MyEndpoint extends DefaultEndpoint {
@Override
public Producer createProducer() throws Exception {
// not supported
return null;
}
@Override
public Consumer createConsumer(Processor processor) throws Exception {
return new MyConsumer(this, processor);
}
@Override
protected String createEndpointUri() {
return "myEndpoint://foo";
}
@Override
public boolean isSingleton() {
return true;
}
}
private final class MyConsumer implements Consumer {
private Processor processor;
private Endpoint endpoint;
private MyConsumer(Endpoint endpoint, Processor processor) {
this.endpoint = endpoint;
this.processor = processor;
}
@Override
public Endpoint getEndpoint() {
return endpoint;
}
@Override
public void start() throws Exception {
consumerThread = Thread.currentThread().getName();
Exchange exchange = new DefaultExchange(context);
exchange.setProperty(Exchange.UNIT_OF_WORK_PROCESS_SYNC, true);
exchange.addOnCompletion(new SynchronizationAdapter() {
@Override
public void onDone(Exchange exchange) {
doneThread = Thread.currentThread().getName();
}
});
// just fire the exchange when started
processor.process(exchange);
}
@Override
public void stop() throws Exception {
// noop
}
}
}
|
camel-core/src/test/java/org/apache/camel/UnitOfWorkSyncProcessTest.java
|
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultEndpoint;
import org.apache.camel.impl.DefaultExchange;
import org.apache.camel.support.SynchronizationAdapter;
/**
*
*/
public class UnitOfWorkSyncProcessTest extends ContextTestSupport {
private static String consumerThread;
private static String afterThread;
private static String taskThread;
private static String doneThread;
private ExecutorService executorService;
public void testUnitOfWorkSync() throws Exception {
// skip test on AIX
if (isPlatform("aix")) {
return;
}
executorService = Executors.newSingleThreadExecutor();
getMockEndpoint("mock:result").expectedMessageCount(1);
assertMockEndpointsSatisfied();
// should be same thread
assertEquals(taskThread, afterThread);
// should not be same
assertNotSame(doneThread, afterThread);
assertNotSame(doneThread, consumerThread);
// should be same thread
assertEquals(consumerThread, doneThread);
executorService.shutdownNow();
}
@Override
protected RouteBuilder createRouteBuilder() throws Exception {
return new RouteBuilder() {
@Override
public void configure() throws Exception {
from(new MyEndpoint())
.process(new AsyncProcessor() {
@Override
public boolean process(final Exchange exchange, final AsyncCallback callback) {
executorService.submit(new Runnable() {
@Override
public void run() {
taskThread = Thread.currentThread().getName();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// ignore
}
exchange.getIn().setHeader("foo", 123);
callback.done(false);
}
});
return false;
}
@Override
public void process(Exchange exchange) throws Exception {
// noop
}
})
.process(new Processor() {
@Override
public void process(Exchange exchange) throws Exception {
afterThread = Thread.currentThread().getName();
}
})
.to("mock:result");
}
};
}
private final class MyEndpoint extends DefaultEndpoint {
@Override
public Producer createProducer() throws Exception {
// not supported
return null;
}
@Override
public Consumer createConsumer(Processor processor) throws Exception {
return new MyConsumer(this, processor);
}
@Override
protected String createEndpointUri() {
return "myEndpoint://foo";
}
@Override
public boolean isSingleton() {
return true;
}
}
private final class MyConsumer implements Consumer {
private Processor processor;
private Endpoint endpoint;
private MyConsumer(Endpoint endpoint, Processor processor) {
this.endpoint = endpoint;
this.processor = processor;
}
@Override
public Endpoint getEndpoint() {
return endpoint;
}
@Override
public void start() throws Exception {
consumerThread = Thread.currentThread().getName();
Exchange exchange = new DefaultExchange(context);
exchange.setProperty(Exchange.UNIT_OF_WORK_PROCESS_SYNC, true);
exchange.addOnCompletion(new SynchronizationAdapter() {
@Override
public void onDone(Exchange exchange) {
doneThread = Thread.currentThread().getName();
}
});
// just fire the exchange when started
processor.process(exchange);
}
@Override
public void stop() throws Exception {
// noop
}
}
}
|
Skip test failing on aix
git-svn-id: 11f3c9e1d08a13a4be44fe98a6d63a9c00f6ab23@1404519 13f79535-47bb-0310-9956-ffa450edef68
|
camel-core/src/test/java/org/apache/camel/UnitOfWorkSyncProcessTest.java
|
Skip test failing on aix
|
<ide><path>amel-core/src/test/java/org/apache/camel/UnitOfWorkSyncProcessTest.java
<ide> private static String afterThread;
<ide> private static String taskThread;
<ide> private static String doneThread;
<del> private ExecutorService executorService;
<add> private ExecutorService executorService = Executors.newSingleThreadExecutor();
<add>
<add> @Override
<add> protected void tearDown() throws Exception {
<add> executorService.shutdownNow();
<add> super.tearDown();
<add> }
<ide>
<ide> public void testUnitOfWorkSync() throws Exception {
<ide> // skip test on AIX
<ide> if (isPlatform("aix")) {
<ide> return;
<ide> }
<del>
<del> executorService = Executors.newSingleThreadExecutor();
<ide>
<ide> getMockEndpoint("mock:result").expectedMessageCount(1);
<ide>
<ide> assertNotSame(doneThread, consumerThread);
<ide> // should be same thread
<ide> assertEquals(consumerThread, doneThread);
<del>
<del> executorService.shutdownNow();
<ide> }
<ide>
<ide> @Override
|
|
Java
|
mit
|
01fe60d1915870889389460f0190520158038f27
| 0 |
cdai/interview
|
package miscellaneous.bitmanipulation.lc342_poweroffour;
/**
* Given an integer (signed 32 bits), write a function to check whether it is a power of 4.
* Example: Given num = 16, return true. Given num = 5, return false.
* Follow up: Could you solve it without loops/recursion?
*/
public class Solution {
// only 1 one-bit on odd bit.
// A=1010, we have 8 * A (it's ok we set sign)
public boolean isPowerOfFour(int num) {
return num > 0 && ((num - 1) & num) == 0 && (num & 0xAAAAAAAA) == 0;
}
public boolean isPowerOfFour_recursive(int num) {
if (num <= 0) return false;
if (num == 1) return true;
return num % 4 == 0 && isPowerOfFour(num / 4);
}
public boolean isPowerOfFour_loop(int num) {
if (num <= 0) return false;
while(num % 4 == 0) num /= 4; // remove all factors
return num == 1;
}
// My 2AC: check even bit instead, same effect.
public boolean isPowerOfFour2(int num) {
// 0x55555555 = 01010101010101010101010101010101
// 0xAAAAAAAA = 10101010101010101010101010101010
return (num > 0) && ((num & (num - 1)) == 0) && ((num & 0xAAAAAAAA) == 0);
}
public boolean isPowerOfFour1(int num) {
// Use 0x5555555555555555l to check if 1 is on odd bit:
// 010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101
return (num > 0) && ((num & (num - 1)) == 0)
&& ((num & 0x5555555555555555l) == num);
}
public boolean isPowerOfFour12(int num) {
// Determine if it's power of two at first
if (num <= 0 || (num & (num - 1)) != 0) { // error: !=0 not ==1
return false;
}
// Check if there're even zeroes: 4(100), 16(10000)...
int i = 0;
while (num > 1) {
num >>= 1;
i++;
}
return i % 2 == 0;
}
}
|
1-algorithm/13-leetcode/java/src/miscellaneous/bitmanipulation/lc342_poweroffour/Solution.java
|
package miscellaneous.bitmanipulation.lc342_poweroffour;
/**
* Given an integer (signed 32 bits), write a function to check whether it is a power of 4.
* Example: Given num = 16, return true. Given num = 5, return false.
* Follow up: Could you solve it without loops/recursion?
*/
public class Solution {
// only 1 one-bit on odd bit.
// A=1010, we have 8 * A (it's ok we set sign)
public boolean isPowerOfFour(int num) {
return num > 0 && ((num - 1) & num) == 0 && (num & 0xAAAAAAAA) == 0;
}
public boolean isPowerOfFour_loop(int num) {
if (num <= 0) return false;
while(num % 4 == 0) num /= 4; // remove all factors
return num == 1;
}
// My 2AC: check even bit instead, same effect.
public boolean isPowerOfFour2(int num) {
// 0x55555555 = 01010101010101010101010101010101
// 0xAAAAAAAA = 10101010101010101010101010101010
return (num > 0) && ((num & (num - 1)) == 0) && ((num & 0xAAAAAAAA) == 0);
}
public boolean isPowerOfFour1(int num) {
// Use 0x5555555555555555l to check if 1 is on odd bit:
// 010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101
return (num > 0) && ((num & (num - 1)) == 0)
&& ((num & 0x5555555555555555l) == num);
}
public boolean isPowerOfFour12(int num) {
// Determine if it's power of two at first
if (num <= 0 || (num & (num - 1)) != 0) { // error: !=0 not ==1
return false;
}
// Check if there're even zeroes: 4(100), 16(10000)...
int i = 0;
while (num > 1) {
num >>= 1;
i++;
}
return i % 2 == 0;
}
}
|
leetcode-342: power of four
|
1-algorithm/13-leetcode/java/src/miscellaneous/bitmanipulation/lc342_poweroffour/Solution.java
|
leetcode-342: power of four
|
<ide><path>-algorithm/13-leetcode/java/src/miscellaneous/bitmanipulation/lc342_poweroffour/Solution.java
<ide> // A=1010, we have 8 * A (it's ok we set sign)
<ide> public boolean isPowerOfFour(int num) {
<ide> return num > 0 && ((num - 1) & num) == 0 && (num & 0xAAAAAAAA) == 0;
<add> }
<add>
<add> public boolean isPowerOfFour_recursive(int num) {
<add> if (num <= 0) return false;
<add> if (num == 1) return true;
<add> return num % 4 == 0 && isPowerOfFour(num / 4);
<ide> }
<ide>
<ide> public boolean isPowerOfFour_loop(int num) {
|
|
Java
|
apache-2.0
|
a7c26662a50abef24ae4aacbb98706e78b9cce32
| 0 |
avarabyeu/restendpoint
|
/*
* Copyright (C) 2014 Andrei Varabyeu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.avarabyeu.restendpoint.http;
import com.github.avarabyeu.restendpoint.async.Will;
import com.github.avarabyeu.restendpoint.http.exception.RestEndpointIOException;
import com.github.avarabyeu.restendpoint.http.exception.SerializerException;
import com.github.avarabyeu.restendpoint.serializer.ByteArraySerializer;
import com.github.avarabyeu.restendpoint.serializer.StringSerializer;
import com.google.common.collect.ImmutableMap;
import com.google.common.net.HttpHeaders;
import com.google.mockwebserver.MockWebServer;
import org.apache.commons.codec.binary.Base64;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import java.io.IOException;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.notNullValue;
/**
* {@link com.github.avarabyeu.restendpoint.http.RestEndpoints} tests
*
* @author avarabyeu
*/
public class RestEndpointsTest extends BaseRestEndointTest {
public static final String HTTP_TEST_URK = "http://localhost:" + GuiceTestModule.MOCK_PORT;
public static final String ECHO_STRING = "Hello world!";
public static final String RESOURCE = "/";
private static MockWebServer server = Injector.getInstance().getBean(MockWebServer.class);
@BeforeClass
public static void before() throws IOException {
server.play(GuiceTestModule.MOCK_PORT);
}
@AfterClass
public static void after() throws IOException {
server.shutdown();
}
@Test
public void testDefault() throws RestEndpointIOException {
RestEndpoint endpoint = RestEndpoints.createDefault(HTTP_TEST_URK);
Assert.assertThat(endpoint, notNullValue());
server.enqueue(prepareResponse(ECHO_STRING));
Will<String> helloRS = endpoint.post(RESOURCE, ECHO_STRING, String.class);
Assert.assertThat(helloRS.obtain(), is(ECHO_STRING));
}
/**
* Put wrong serializer into non-default configuration
*
* @throws RestEndpointIOException
*/
@Test(expected = SerializerException.class)
public void testNoSerializer() throws RestEndpointIOException {
RestEndpoint endpoint = RestEndpoints.create().withBaseUrl(HTTP_TEST_URK)
.withSerializer(new ByteArraySerializer())
.build();
Assert.assertThat(endpoint, notNullValue());
server.enqueue(prepareResponse(ECHO_STRING));
Will<String> helloRS = endpoint.post(RESOURCE, ECHO_STRING, String.class);
Assert.assertThat(helloRS.obtain(), is(ECHO_STRING));
}
@Test
public void testBuilderHappy() throws RestEndpointIOException {
RestEndpoint endpoint = RestEndpoints.create().withBaseUrl(HTTP_TEST_URK)
.withSerializer(new StringSerializer())
.build();
Assert.assertThat(endpoint, notNullValue());
server.enqueue(prepareResponse(ECHO_STRING));
Will<String> helloRS = endpoint.post(RESOURCE, ECHO_STRING, String.class);
Assert.assertThat(helloRS.obtain(), is(ECHO_STRING));
}
@Test
public void testBuilderBasicAuth() throws RestEndpointIOException, InterruptedException {
RestEndpoint endpoint = RestEndpoints.create().withBaseUrl(HTTP_TEST_URK)
.withSerializer(new StringSerializer()).withBasicAuth("login", "password")
.build();
Assert.assertThat(endpoint, notNullValue());
server.enqueue(prepareResponse(ECHO_STRING));
endpoint.post(RESOURCE, ECHO_STRING, String.class).obtain();
String basicAuthHeader = server.takeRequest().getHeader(HttpHeaders.AUTHORIZATION);
Assert.assertThat(basicAuthHeader, is("Basic " + Base64.encodeBase64String("login:password".getBytes())));
}
//TODO add test for SSL
}
|
src/test/java/com/github/avarabyeu/restendpoint/http/RestEndpointsTest.java
|
/*
* Copyright (C) 2014 Andrei Varabyeu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.avarabyeu.restendpoint.http;
import com.github.avarabyeu.restendpoint.async.Will;
import com.github.avarabyeu.restendpoint.http.exception.RestEndpointIOException;
import com.github.avarabyeu.restendpoint.http.exception.SerializerException;
import com.github.avarabyeu.restendpoint.serializer.ByteArraySerializer;
import com.github.avarabyeu.restendpoint.serializer.StringSerializer;
import com.google.common.net.HttpHeaders;
import com.google.mockwebserver.MockWebServer;
import org.apache.commons.codec.binary.Base64;
import org.hamcrest.CoreMatchers;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import java.io.IOException;
import static org.hamcrest.CoreMatchers.*;
import static org.hamcrest.CoreMatchers.notNullValue;
/**
* {@link com.github.avarabyeu.restendpoint.http.RestEndpoints} tests
*
* @author avarabyeu
*/
public class RestEndpointsTest extends BaseRestEndointTest {
public static final String HTTP_TEST_URK = "http://localhost:" + GuiceTestModule.MOCK_PORT;
public static final String ECHO_STRING = "Hello world!";
public static final String RESOURCE = "/";
private static MockWebServer server = Injector.getInstance().getBean(MockWebServer.class);
@BeforeClass
public static void before() throws IOException {
server.play(GuiceTestModule.MOCK_PORT);
}
@AfterClass
public static void after() throws IOException {
server.shutdown();
}
@Test
public void testDefault() throws RestEndpointIOException {
RestEndpoint endpoint = RestEndpoints.createDefault(HTTP_TEST_URK);
Assert.assertThat(endpoint, notNullValue());
server.enqueue(prepareResponse(ECHO_STRING));
Will<String> helloRS = endpoint.post(RESOURCE, ECHO_STRING, String.class);
Assert.assertThat(helloRS.obtain(), is(ECHO_STRING));
}
/**
* Put wrong serializer into non-default configuration
*
* @throws RestEndpointIOException
*/
@Test(expected = SerializerException.class)
public void testNoSerializer() throws RestEndpointIOException {
RestEndpoint endpoint = RestEndpoints.create().withBaseUrl(HTTP_TEST_URK)
.withSerializer(new ByteArraySerializer())
.build();
Assert.assertThat(endpoint, notNullValue());
server.enqueue(prepareResponse(ECHO_STRING));
Will<String> helloRS = endpoint.post(RESOURCE, ECHO_STRING, String.class);
Assert.assertThat(helloRS.obtain(), is(ECHO_STRING));
}
@Test
public void testBuilderHappy() throws RestEndpointIOException {
RestEndpoint endpoint = RestEndpoints.create().withBaseUrl(HTTP_TEST_URK)
.withSerializer(new StringSerializer())
.build();
Assert.assertThat(endpoint, notNullValue());
server.enqueue(prepareResponse(ECHO_STRING));
Will<String> helloRS = endpoint.post(RESOURCE, ECHO_STRING, String.class);
Assert.assertThat(helloRS.obtain(), is(ECHO_STRING));
}
@Test
public void testBuilderBasicAuth() throws RestEndpointIOException, InterruptedException {
RestEndpoint endpoint = RestEndpoints.create().withBaseUrl(HTTP_TEST_URK)
.withSerializer(new StringSerializer()).withBasicAuth("login", "password")
.build();
Assert.assertThat(endpoint, notNullValue());
server.enqueue(prepareResponse(ECHO_STRING));
endpoint.post(RESOURCE, ECHO_STRING, String.class).obtain();
String basicAuthHeader = server.takeRequest().getHeader(HttpHeaders.AUTHORIZATION);
Assert.assertThat(basicAuthHeader, is("Basic " + Base64.encodeBase64String("login:password".getBytes())));
}
//TODO add test for SSL
}
|
update unit test
|
src/test/java/com/github/avarabyeu/restendpoint/http/RestEndpointsTest.java
|
update unit test
|
<ide><path>rc/test/java/com/github/avarabyeu/restendpoint/http/RestEndpointsTest.java
<ide> import com.github.avarabyeu.restendpoint.http.exception.SerializerException;
<ide> import com.github.avarabyeu.restendpoint.serializer.ByteArraySerializer;
<ide> import com.github.avarabyeu.restendpoint.serializer.StringSerializer;
<add>import com.google.common.collect.ImmutableMap;
<ide> import com.google.common.net.HttpHeaders;
<ide> import com.google.mockwebserver.MockWebServer;
<ide> import org.apache.commons.codec.binary.Base64;
<del>import org.hamcrest.CoreMatchers;
<ide> import org.junit.AfterClass;
<ide> import org.junit.Assert;
<ide> import org.junit.BeforeClass;
<ide>
<ide> import java.io.IOException;
<ide>
<del>import static org.hamcrest.CoreMatchers.*;
<add>import static org.hamcrest.CoreMatchers.is;
<ide> import static org.hamcrest.CoreMatchers.notNullValue;
<ide>
<ide> /**
|
|
Java
|
apache-2.0
|
9d17349aaf1adff899e99e9225b2f95f9b5cdb2d
| 0 |
estatio/estatio,estatio/estatio,estatio/estatio,estatio/estatio
|
/*
* Copyright 2012-2014 Eurocommercial Properties NV
*
*
* Licensed under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.estatio.dom.lease.invoicing.viewmodel;
import java.math.BigDecimal;
import java.util.List;
import javax.inject.Inject;
import javax.jdo.annotations.Extension;
import javax.jdo.annotations.IdentityType;
import javax.jdo.annotations.InheritanceStrategy;
import org.joda.time.LocalDate;
import org.apache.isis.applib.annotation.BookmarkPolicy;
import org.apache.isis.applib.annotation.CollectionLayout;
import org.apache.isis.applib.annotation.DomainObject;
import org.apache.isis.applib.annotation.DomainObjectLayout;
import org.apache.isis.applib.annotation.Editing;
import org.apache.isis.applib.annotation.ViewModel;
import org.apache.isis.applib.annotation.Where;
import org.isisaddons.module.security.dom.tenancy.ApplicationTenancy;
import org.incode.module.base.dom.utils.TitleBuilder;
import org.estatio.dom.asset.PropertyRepository;
import org.estatio.dom.invoice.InvoiceStatus;
import org.estatio.dom.lease.invoicing.InvoiceForLease;
import org.estatio.dom.party.Party;
import org.estatio.dom.party.PartyRepository;
import lombok.Getter;
import lombok.Setter;
@javax.jdo.annotations.PersistenceCapable(
identityType = IdentityType.NONDURABLE,
table = "InvoiceSummaryForPropertyDueDateStatus",
schema = "dbo",
extensions = {
@Extension(vendorName = "datanucleus", key = "view-definition",
value = "CREATE VIEW \"dbo\".\"InvoiceSummaryForPropertyDueDateStatus\" " +
"( " +
" {this.atPath}, " +
" {this.sellerReference}, " +
" {this.dueDate}, " +
" {this.status}, " +
" {this.total}, " +
" {this.netAmount}, " +
" {this.vatAmount}, " +
" {this.grossAmount} " +
") AS " +
"SELECT " +
" i.\"atPath\", " +
" p.\"reference\" , " +
" i.\"dueDate\", " +
" i.\"status\", " +
" COUNT(DISTINCT(i.\"id\")) AS \"total\", " +
" SUM(ii.\"netAmount\") AS \"netAmount\", " +
" SUM(ii.\"vatAmount\") AS \"vatAmount\", " +
" SUM(ii.\"grossAmount\") AS \"grossAmount\" " +
"FROM \"dbo\".\"Invoice\" i " +
" INNER JOIN \"dbo\".\"InvoiceItem\" ii " +
" ON ii.\"invoiceId\" = i.\"id\" " +
" INNER JOIN \"dbo\".\"Party\" p " +
" ON p.\"id\" = i.\"sellerPartyId\" " +
"GROUP BY " +
" i.\"atPath\", " +
" p.\"reference\", " +
" i.\"dueDate\", " +
" i.\"status\"")
})
@javax.jdo.annotations.Queries({
@javax.jdo.annotations.Query(
name = "findByStatus", language = "JDOQL",
value = "SELECT " +
"FROM org.estatio.dom.lease.invoicing.viewmodel.InvoiceSummaryForPropertyDueDateStatus " +
"WHERE status == :status "),
@javax.jdo.annotations.Query(
name = "findByAtPathAndSellerReferenceAndStatus", language = "JDOQL",
value = "SELECT " +
"FROM org.estatio.dom.lease.invoicing.viewmodel.InvoiceSummaryForPropertyDueDateStatus " +
"WHERE atPath == :atPath " +
" && sellerReference == :sellerReference " +
" && status == :status "
),
@javax.jdo.annotations.Query(
name = "findByAtPathAndSellerReferenceAndStatusAndDueDate", language = "JDOQL",
value = "SELECT " +
"FROM org.estatio.dom.lease.invoicing.viewmodel.InvoiceSummaryForPropertyDueDateStatus " +
"WHERE atPath == :atPath " +
" && sellerReference == :sellerReference " +
" && status == :status " +
" && dueDate == :dueDate "
)
})
@javax.jdo.annotations.Inheritance(strategy = InheritanceStrategy.NEW_TABLE)
@ViewModel
@DomainObject(editing = Editing.DISABLED)
@DomainObjectLayout(bookmarking = BookmarkPolicy.AS_ROOT)
public class InvoiceSummaryForPropertyDueDateStatus extends InvoiceSummaryAbstract {
public String iconName() {
return "InvoiceSummary";
}
public String title() {
return TitleBuilder.start()
.withName(getAtPath())
.withName(getSellerReference())
.withName(getDueDate())
.toString();
}
@org.apache.isis.applib.annotation.Property(hidden = Where.EVERYWHERE)
@Getter @Setter
private String atPath;
public ApplicationTenancy getApplicationTenancy(){
return applicationTenancyRepository.findByPath(getAtPath());
}
@Getter @Setter
@org.apache.isis.applib.annotation.Property(hidden = Where.EVERYWHERE)
private String sellerReference;
/**
* Annotated as {@link javax.jdo.annotations.NotPersistent not persistent}
* because not mapped in the <tt>view-definition</tt>.
*/
@javax.jdo.annotations.NotPersistent
private Party seller;
public Party getSeller() {
if (seller == null) {
seller = partyRepository.findPartyByReference(getSellerReference());
}
return seller;
}
@Getter @Setter
private InvoiceStatus status;
@Getter @Setter
private LocalDate dueDate;
@Getter @Setter
private int total;
@Getter @Setter
@org.apache.isis.applib.annotation.Property(hidden = Where.EVERYWHERE)
private BigDecimal vatAmount;
@Getter @Setter
private BigDecimal netAmount;
@Getter @Setter
private BigDecimal grossAmount;
@CollectionLayout(defaultView = "table")
public List<InvoiceForLease> getInvoices() {
return invoiceForLeaseRepository
.findByApplicationTenancyPathAndSellerAndDueDateAndStatus(getAtPath(), getSeller(), getDueDate(), getStatus());
}
@Inject
PropertyRepository propertyRepository;
@Inject
PartyRepository partyRepository;
}
|
estatioapp/module/lease/dom/src/main/java/org/estatio/dom/lease/invoicing/viewmodel/InvoiceSummaryForPropertyDueDateStatus.java
|
/*
* Copyright 2012-2014 Eurocommercial Properties NV
*
*
* Licensed under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.estatio.dom.lease.invoicing.viewmodel;
import java.math.BigDecimal;
import java.util.List;
import javax.inject.Inject;
import javax.jdo.annotations.Extension;
import javax.jdo.annotations.IdentityType;
import javax.jdo.annotations.InheritanceStrategy;
import org.joda.time.LocalDate;
import org.apache.isis.applib.annotation.CollectionLayout;
import org.apache.isis.applib.annotation.DomainObject;
import org.apache.isis.applib.annotation.Editing;
import org.apache.isis.applib.annotation.ViewModel;
import org.apache.isis.applib.annotation.Where;
import org.isisaddons.module.security.dom.tenancy.ApplicationTenancy;
import org.incode.module.base.dom.utils.TitleBuilder;
import org.estatio.dom.asset.PropertyRepository;
import org.estatio.dom.invoice.InvoiceStatus;
import org.estatio.dom.lease.invoicing.InvoiceForLease;
import org.estatio.dom.party.Party;
import org.estatio.dom.party.PartyRepository;
import lombok.Getter;
import lombok.Setter;
@javax.jdo.annotations.PersistenceCapable(
identityType = IdentityType.NONDURABLE,
table = "InvoiceSummaryForPropertyDueDateStatus",
schema = "dbo",
extensions = {
@Extension(vendorName = "datanucleus", key = "view-definition",
value = "CREATE VIEW \"dbo\".\"InvoiceSummaryForPropertyDueDateStatus\" " +
"( " +
" {this.atPath}, " +
" {this.sellerReference}, " +
" {this.dueDate}, " +
" {this.status}, " +
" {this.total}, " +
" {this.netAmount}, " +
" {this.vatAmount}, " +
" {this.grossAmount} " +
") AS " +
"SELECT " +
" i.\"atPath\", " +
" p.\"reference\" , " +
" i.\"dueDate\", " +
" i.\"status\", " +
" COUNT(DISTINCT(i.\"id\")) AS \"total\", " +
" SUM(ii.\"netAmount\") AS \"netAmount\", " +
" SUM(ii.\"vatAmount\") AS \"vatAmount\", " +
" SUM(ii.\"grossAmount\") AS \"grossAmount\" " +
"FROM \"dbo\".\"Invoice\" i " +
" INNER JOIN \"dbo\".\"InvoiceItem\" ii " +
" ON ii.\"invoiceId\" = i.\"id\" " +
" INNER JOIN \"dbo\".\"Party\" p " +
" ON p.\"id\" = i.\"sellerPartyId\" " +
"GROUP BY " +
" i.\"atPath\", " +
" p.\"reference\", " +
" i.\"dueDate\", " +
" i.\"status\"")
})
@javax.jdo.annotations.Queries({
@javax.jdo.annotations.Query(
name = "findByStatus", language = "JDOQL",
value = "SELECT " +
"FROM org.estatio.dom.lease.invoicing.viewmodel.InvoiceSummaryForPropertyDueDateStatus " +
"WHERE status == :status "),
@javax.jdo.annotations.Query(
name = "findByAtPathAndSellerReferenceAndStatus", language = "JDOQL",
value = "SELECT " +
"FROM org.estatio.dom.lease.invoicing.viewmodel.InvoiceSummaryForPropertyDueDateStatus " +
"WHERE atPath == :atPath " +
" && sellerReference == :sellerReference " +
" && status == :status "
),
@javax.jdo.annotations.Query(
name = "findByAtPathAndSellerReferenceAndStatusAndDueDate", language = "JDOQL",
value = "SELECT " +
"FROM org.estatio.dom.lease.invoicing.viewmodel.InvoiceSummaryForPropertyDueDateStatus " +
"WHERE atPath == :atPath " +
" && sellerReference == :sellerReference " +
" && status == :status " +
" && dueDate == :dueDate "
)
})
@javax.jdo.annotations.Inheritance(strategy = InheritanceStrategy.NEW_TABLE)
@ViewModel
@DomainObject(editing = Editing.DISABLED)
public class InvoiceSummaryForPropertyDueDateStatus extends InvoiceSummaryAbstract {
public String iconName() {
return "InvoiceSummary";
}
public String title() {
return TitleBuilder.start()
.withName(getAtPath())
.withName(getSellerReference())
.withName(getDueDate())
.toString();
}
@org.apache.isis.applib.annotation.Property(hidden = Where.EVERYWHERE)
@Getter @Setter
private String atPath;
public ApplicationTenancy getApplicationTenancy(){
return applicationTenancyRepository.findByPath(getAtPath());
}
@Getter @Setter
@org.apache.isis.applib.annotation.Property(hidden = Where.EVERYWHERE)
private String sellerReference;
/**
* Annotated as {@link javax.jdo.annotations.NotPersistent not persistent}
* because not mapped in the <tt>view-definition</tt>.
*/
@javax.jdo.annotations.NotPersistent
private Party seller;
public Party getSeller() {
if (seller == null) {
seller = partyRepository.findPartyByReference(getSellerReference());
}
return seller;
}
@Getter @Setter
private InvoiceStatus status;
@Getter @Setter
private LocalDate dueDate;
@Getter @Setter
private int total;
@Getter @Setter
@org.apache.isis.applib.annotation.Property(hidden = Where.EVERYWHERE)
private BigDecimal vatAmount;
@Getter @Setter
private BigDecimal netAmount;
@Getter @Setter
private BigDecimal grossAmount;
@CollectionLayout(defaultView = "table")
public List<InvoiceForLease> getInvoices() {
return invoiceForLeaseRepository
.findByApplicationTenancyPathAndSellerAndDueDateAndStatus(getAtPath(), getSeller(), getDueDate(), getStatus());
}
@Inject
PropertyRepository propertyRepository;
@Inject
PartyRepository partyRepository;
}
|
EST-1186: makes the invoice summary bookmarkable, easier to navigate back towards during testing
|
estatioapp/module/lease/dom/src/main/java/org/estatio/dom/lease/invoicing/viewmodel/InvoiceSummaryForPropertyDueDateStatus.java
|
EST-1186: makes the invoice summary bookmarkable, easier to navigate back towards during testing
|
<ide><path>statioapp/module/lease/dom/src/main/java/org/estatio/dom/lease/invoicing/viewmodel/InvoiceSummaryForPropertyDueDateStatus.java
<ide>
<ide> import org.joda.time.LocalDate;
<ide>
<add>import org.apache.isis.applib.annotation.BookmarkPolicy;
<ide> import org.apache.isis.applib.annotation.CollectionLayout;
<ide> import org.apache.isis.applib.annotation.DomainObject;
<add>import org.apache.isis.applib.annotation.DomainObjectLayout;
<ide> import org.apache.isis.applib.annotation.Editing;
<ide> import org.apache.isis.applib.annotation.ViewModel;
<ide> import org.apache.isis.applib.annotation.Where;
<ide> @javax.jdo.annotations.Inheritance(strategy = InheritanceStrategy.NEW_TABLE)
<ide> @ViewModel
<ide> @DomainObject(editing = Editing.DISABLED)
<add>@DomainObjectLayout(bookmarking = BookmarkPolicy.AS_ROOT)
<ide> public class InvoiceSummaryForPropertyDueDateStatus extends InvoiceSummaryAbstract {
<ide>
<ide> public String iconName() {
|
|
Java
|
apache-2.0
|
391b5cbc634eb03436e697097a55f6c3b76fb95e
| 0 |
flyway/flyway,flyway/flyway
|
/*
* Copyright 2010-2019 Boxfuse GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.flywaydb.core.internal.database.cockroachdb;
import org.flywaydb.core.api.MigrationVersion;
import org.flywaydb.core.api.configuration.Configuration;
import org.flywaydb.core.internal.database.base.Database;
import org.flywaydb.core.internal.database.base.Table;
import org.flywaydb.core.internal.exception.FlywaySqlException;
import org.flywaydb.core.internal.jdbc.JdbcConnectionFactory;
import org.flywaydb.core.internal.util.StringUtils;
import java.sql.Connection;
import java.sql.SQLException;
/**
* CockroachDB database.
*/
public class CockroachDBDatabase extends Database<CockroachDBConnection> {
/**
* Creates a new instance.
*
* @param configuration The Flyway configuration.
*/
public CockroachDBDatabase(Configuration configuration, JdbcConnectionFactory jdbcConnectionFactory
) {
super(configuration, jdbcConnectionFactory
);
}
@Override
protected CockroachDBConnection doGetConnection(Connection connection) {
return new CockroachDBConnection(this, connection);
}
@Override
public final void ensureSupported() {
ensureDatabaseIsRecentEnough("1.1");
recommendFlywayUpgradeIfNecessary("19.1");
}
@Override
public String getRawCreateScript(Table table, boolean baseline) {
return "CREATE TABLE " + table + " (\n" +
" \"installed_rank\" INT NOT NULL PRIMARY KEY,\n" +
" \"version\" VARCHAR(50),\n" +
" \"description\" VARCHAR(200) NOT NULL,\n" +
" \"type\" VARCHAR(20) NOT NULL,\n" +
" \"script\" VARCHAR(1000) NOT NULL,\n" +
" \"checksum\" INTEGER,\n" +
" \"installed_by\" VARCHAR(100) NOT NULL,\n" +
" \"installed_on\" TIMESTAMP NOT NULL DEFAULT now(),\n" +
" \"execution_time\" INTEGER NOT NULL,\n" +
" \"success\" BOOLEAN NOT NULL\n" +
");\n" +
(baseline ? getBaselineStatement(table) + ";\n" : "") +
"CREATE INDEX \"" + table.getName() + "_s_idx\" ON " + table + " (\"success\");";
}
@Override
protected MigrationVersion determineVersion() {
String version;
try {
version = getMainConnection().getJdbcTemplate().queryForString("SELECT value FROM crdb_internal.node_build_info where field='Version'");
if (version == null) {
version = getMainConnection().getJdbcTemplate().queryForString("SELECT value FROM crdb_internal.node_build_info where field='Tag'");
}
} catch (SQLException e) {
throw new FlywaySqlException("Unable to determine CockroachDB version", e);
}
int firstDot = version.indexOf(".");
int majorVersion = Integer.parseInt(version.substring(1, firstDot));
String minorPatch = version.substring(firstDot + 1);
int minorVersion = Integer.parseInt(minorPatch.substring(0, minorPatch.indexOf(".")));
return MigrationVersion.fromVersion(majorVersion + "." + minorVersion);
}
public String getDbName() {
return "cockroachdb";
}
@Override
protected String doGetCurrentUser() throws SQLException {
return getMainConnection().getJdbcTemplate().queryForString("(SELECT * FROM [SHOW SESSION_USER])");
}
public boolean supportsDdlTransactions() {
return false;
}
@Override
public boolean supportsChangingCurrentSchema() {
return true;
}
public String getBooleanTrue() {
return "TRUE";
}
public String getBooleanFalse() {
return "FALSE";
}
@Override
public String doQuote(String identifier) {
return "\"" + StringUtils.replaceAll(identifier, "\"", "\"\"") + "\"";
}
@Override
public boolean catalogIsSchema() {
return false;
}
@Override
public boolean useSingleConnection() {
return false;
}
}
|
flyway-core/src/main/java/org/flywaydb/core/internal/database/cockroachdb/CockroachDBDatabase.java
|
/*
* Copyright 2010-2019 Boxfuse GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.flywaydb.core.internal.database.cockroachdb;
import org.flywaydb.core.api.MigrationVersion;
import org.flywaydb.core.api.configuration.Configuration;
import org.flywaydb.core.internal.database.base.Database;
import org.flywaydb.core.internal.database.base.Table;
import org.flywaydb.core.internal.exception.FlywaySqlException;
import org.flywaydb.core.internal.jdbc.JdbcConnectionFactory;
import org.flywaydb.core.internal.util.StringUtils;
import java.sql.Connection;
import java.sql.SQLException;
/**
* CockroachDB database.
*/
public class CockroachDBDatabase extends Database<CockroachDBConnection> {
/**
* Creates a new instance.
*
* @param configuration The Flyway configuration.
*/
public CockroachDBDatabase(Configuration configuration, JdbcConnectionFactory jdbcConnectionFactory
) {
super(configuration, jdbcConnectionFactory
);
}
@Override
protected CockroachDBConnection doGetConnection(Connection connection) {
return new CockroachDBConnection(this, connection);
}
@Override
public final void ensureSupported() {
ensureDatabaseIsRecentEnough("1.1");
recommendFlywayUpgradeIfNecessary("2.1");
}
@Override
public String getRawCreateScript(Table table, boolean baseline) {
return "CREATE TABLE " + table + " (\n" +
" \"installed_rank\" INT NOT NULL PRIMARY KEY,\n" +
" \"version\" VARCHAR(50),\n" +
" \"description\" VARCHAR(200) NOT NULL,\n" +
" \"type\" VARCHAR(20) NOT NULL,\n" +
" \"script\" VARCHAR(1000) NOT NULL,\n" +
" \"checksum\" INTEGER,\n" +
" \"installed_by\" VARCHAR(100) NOT NULL,\n" +
" \"installed_on\" TIMESTAMP NOT NULL DEFAULT now(),\n" +
" \"execution_time\" INTEGER NOT NULL,\n" +
" \"success\" BOOLEAN NOT NULL\n" +
");\n" +
(baseline ? getBaselineStatement(table) + ";\n" : "") +
"CREATE INDEX \"" + table.getName() + "_s_idx\" ON " + table + " (\"success\");";
}
@Override
protected MigrationVersion determineVersion() {
String version;
try {
version = getMainConnection().getJdbcTemplate().queryForString("SELECT value FROM crdb_internal.node_build_info where field='Version'");
if (version == null) {
version = getMainConnection().getJdbcTemplate().queryForString("SELECT value FROM crdb_internal.node_build_info where field='Tag'");
}
} catch (SQLException e) {
throw new FlywaySqlException("Unable to determine CockroachDB version", e);
}
int firstDot = version.indexOf(".");
int majorVersion = Integer.parseInt(version.substring(1, firstDot));
String minorPatch = version.substring(firstDot + 1);
int minorVersion = Integer.parseInt(minorPatch.substring(0, minorPatch.indexOf(".")));
return MigrationVersion.fromVersion(majorVersion + "." + minorVersion);
}
public String getDbName() {
return "cockroachdb";
}
@Override
protected String doGetCurrentUser() throws SQLException {
return getMainConnection().getJdbcTemplate().queryForString("(SELECT * FROM [SHOW SESSION_USER])");
}
public boolean supportsDdlTransactions() {
return false;
}
@Override
public boolean supportsChangingCurrentSchema() {
return true;
}
public String getBooleanTrue() {
return "TRUE";
}
public String getBooleanFalse() {
return "FALSE";
}
@Override
public String doQuote(String identifier) {
return "\"" + StringUtils.replaceAll(identifier, "\"", "\"\"") + "\"";
}
@Override
public boolean catalogIsSchema() {
return false;
}
@Override
public boolean useSingleConnection() {
return false;
}
}
|
Bump supported Cockroach version
|
flyway-core/src/main/java/org/flywaydb/core/internal/database/cockroachdb/CockroachDBDatabase.java
|
Bump supported Cockroach version
|
<ide><path>lyway-core/src/main/java/org/flywaydb/core/internal/database/cockroachdb/CockroachDBDatabase.java
<ide> @Override
<ide> public final void ensureSupported() {
<ide> ensureDatabaseIsRecentEnough("1.1");
<del> recommendFlywayUpgradeIfNecessary("2.1");
<add> recommendFlywayUpgradeIfNecessary("19.1");
<ide> }
<ide>
<ide> @Override
|
|
Java
|
apache-2.0
|
03d1bebc95814cb200fcc01b99cad5937b2a7914
| 0 |
SynBioDex/SBOLDesigner,SynBioDex/SBOLDesigner
|
package edu.utah.ece.async.sboldesigner.sbol.editor.dialog;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.DefaultListCellRenderer;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JCheckBox;
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.JScrollPane;
import javax.swing.KeyStroke;
import javax.swing.ListModel;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import org.sbolstandard.core2.SBOLConversionException;
import org.sbolstandard.core2.SBOLDocument;
import org.synbiohub.frontend.IdentifiedMetadata;
import org.synbiohub.frontend.SearchCriteria;
import org.synbiohub.frontend.SearchQuery;
import org.synbiohub.frontend.SynBioHubException;
import org.synbiohub.frontend.SynBioHubFrontend;
import edu.utah.ece.async.sboldesigner.sbol.CharSequenceUtil;
import edu.utah.ece.async.sboldesigner.sbol.editor.Registry;
import edu.utah.ece.async.sboldesigner.sbol.editor.SynBioHubFrontends;
public class UploadExistingDialog extends JDialog implements ActionListener, ListSelectionListener {
private static final String TITLE = "Upload Design: ";
private static String title(Registry registry) {
String title = "";
if (registry.getName() != null) {
title = title + registry.getName();
} else if (registry.getLocation() != null) {
title = title + registry.getLocation();
}
return CharSequenceUtil.shorten(title, 20).toString();
}
private Component parent;
private Registry registry;
private SBOLDocument toBeUploaded;
private final JLabel info = new JLabel(
"Select an existing collection(s) to upload the design into. If Overwrite is selected, the uploaded part will overwrite any parts that have the same URI in the selected collection.");
private final JButton uploadButton = new JButton("Upload");
private final JButton cancelButton = new JButton("Cancel");
private final JCheckBox overwrite = new JCheckBox("");
private JList<IdentifiedMetadata> collections = null;
public UploadExistingDialog(final Component parent, Registry registry, SBOLDocument uploadDoc) {
super(JOptionPane.getFrameForComponent(parent), TITLE + title(registry), true);
this.parent = parent;
this.registry = registry;
this.toBeUploaded = uploadDoc;
cancelButton.registerKeyboardAction(this, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0),
JComponent.WHEN_IN_FOCUSED_WINDOW);
cancelButton.addActionListener(this);
uploadButton.addActionListener(this);
uploadButton.setEnabled(false);
getRootPane().setDefaultButton(uploadButton);
JPanel buttonPane = new JPanel();
buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.LINE_AXIS));
buttonPane.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
buttonPane.add(Box.createHorizontalStrut(100));
buttonPane.add(Box.createHorizontalGlue());
buttonPane.add(cancelButton);
buttonPane.add(uploadButton);
// setup collections
collections = new JList<IdentifiedMetadata>(setupListModel());
collections.addListSelectionListener(this);
collections.setCellRenderer(new MyListCellRenderer());
collections.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
collections.setLayoutOrientation(JList.VERTICAL);
collections.setVisibleRowCount(5);
JScrollPane collectionsScroller = new JScrollPane(collections);
collectionsScroller.setPreferredSize(new Dimension(50, 200));
collectionsScroller.setAlignmentX(LEFT_ALIGNMENT);
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.PAGE_AXIS));
mainPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
mainPanel.add(new JLabel("Collections"));
mainPanel.add(collectionsScroller);
mainPanel.add(new JLabel("Overwrite"));
mainPanel.add(overwrite);
Container contentPane = getContentPane();
contentPane.add(info, BorderLayout.PAGE_START);
contentPane.add(mainPanel, BorderLayout.CENTER);
contentPane.add(buttonPane, BorderLayout.PAGE_END);
((JComponent) contentPane).setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
pack();
setLocationRelativeTo(parent);
setVisible(true);
}
private class MyListCellRenderer extends DefaultListCellRenderer {
@Override
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected,
boolean cellHasFocus) {
JLabel label = (JLabel) super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
label.setOpaque(isSelected); // Highlight only when selected
label.setText(((IdentifiedMetadata) value).getName());
return label;
}
}
private ListModel<IdentifiedMetadata> setupListModel() {
SynBioHubFrontends frontends = new SynBioHubFrontends();
SynBioHubFrontend frontend = null;
if (frontends.hasFrontend(registry.getLocation())) {
frontend = frontends.getFrontend(registry.getLocation());
} else {
frontend = toBeUploaded.addRegistry(registry.getLocation(), registry.getUriPrefix());
}
SearchQuery query = new SearchQuery();
SearchCriteria crit = new SearchCriteria();
crit.setKey("objectType");
crit.setValue("Collection");
query.addCriteria(crit);
query.setLimit(10000);
query.setOffset(0);
List<IdentifiedMetadata> results;
DefaultListModel<IdentifiedMetadata> model = new DefaultListModel<IdentifiedMetadata>();
try {
results = frontend.search(query);
} catch (SynBioHubException e) {
return model;
}
if (results.size() == 0) {
return model;
}
for (IdentifiedMetadata collection : results) {
// don't add collections that have "/public" in the URI.
if (!collection.getUri().contains("/public/")) {
model.addElement(collection);
}
}
return model;
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == cancelButton) {
setVisible(false);
return;
}
if (e.getSource() == uploadButton) {
try {
uploadDesign();
setVisible(false);
return;
} catch (SynBioHubException e1) {
MessageDialog.showMessage(parent, "Uploading failed", Arrays.asList(e1.getMessage().split("\"|,")));
toBeUploaded.clearRegistries();
}
}
}
private void uploadDesign() throws SynBioHubException {
SynBioHubFrontends frontends = new SynBioHubFrontends();
if (!frontends.hasFrontend(registry.getLocation())) {
JOptionPane.showMessageDialog(parent,
"Please login to " + registry.getLocation() + " in the Registry preferences menu.");
return;
}
SynBioHubFrontend frontend = frontends.getFrontend(registry.getLocation());
IdentifiedMetadata selectedCollection = collections.getSelectedValue();
//String option = overwrite.isSelected() ? "3" : "2";
frontend.submit(selectedCollection.getDisplayId().replace("_collection", ""), selectedCollection.getVersion(),
overwrite.isSelected(), toBeUploaded);
JOptionPane.showMessageDialog(parent, "Upload successful!");
}
@Override
public void valueChanged(ListSelectionEvent e) {
uploadButton.setEnabled(!collections.isSelectionEmpty());
}
}
|
src/main/java/edu/utah/ece/async/sboldesigner/sbol/editor/dialog/UploadExistingDialog.java
|
package edu.utah.ece.async.sboldesigner.sbol.editor.dialog;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.DefaultListCellRenderer;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JCheckBox;
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.JScrollPane;
import javax.swing.KeyStroke;
import javax.swing.ListModel;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import org.sbolstandard.core2.SBOLConversionException;
import org.sbolstandard.core2.SBOLDocument;
import org.synbiohub.frontend.IdentifiedMetadata;
import org.synbiohub.frontend.SearchCriteria;
import org.synbiohub.frontend.SearchQuery;
import org.synbiohub.frontend.SynBioHubException;
import org.synbiohub.frontend.SynBioHubFrontend;
import edu.utah.ece.async.sboldesigner.sbol.CharSequenceUtil;
import edu.utah.ece.async.sboldesigner.sbol.editor.Registry;
import edu.utah.ece.async.sboldesigner.sbol.editor.SynBioHubFrontends;
public class UploadExistingDialog extends JDialog implements ActionListener, ListSelectionListener {
private static final String TITLE = "Upload Design: ";
private static String title(Registry registry) {
String title = "";
if (registry.getName() != null) {
title = title + registry.getName();
} else if (registry.getLocation() != null) {
title = title + registry.getLocation();
}
return CharSequenceUtil.shorten(title, 20).toString();
}
private Component parent;
private Registry registry;
private SBOLDocument toBeUploaded;
private final JLabel info = new JLabel(
"Select an existing collection(s) to upload the design into. If Overwrite is selected, the uploaded part will overwrite any parts that have the same URI in the selected collection.");
private final JButton uploadButton = new JButton("Upload");
private final JButton cancelButton = new JButton("Cancel");
private final JCheckBox overwrite = new JCheckBox("");
private JList<IdentifiedMetadata> collections = null;
public UploadExistingDialog(final Component parent, Registry registry, SBOLDocument uploadDoc) {
super(JOptionPane.getFrameForComponent(parent), TITLE + title(registry), true);
this.parent = parent;
this.registry = registry;
this.toBeUploaded = uploadDoc;
cancelButton.registerKeyboardAction(this, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0),
JComponent.WHEN_IN_FOCUSED_WINDOW);
cancelButton.addActionListener(this);
uploadButton.addActionListener(this);
uploadButton.setEnabled(false);
getRootPane().setDefaultButton(uploadButton);
JPanel buttonPane = new JPanel();
buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.LINE_AXIS));
buttonPane.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
buttonPane.add(Box.createHorizontalStrut(100));
buttonPane.add(Box.createHorizontalGlue());
buttonPane.add(cancelButton);
buttonPane.add(uploadButton);
// setup collections
collections = new JList<IdentifiedMetadata>(setupListModel());
collections.addListSelectionListener(this);
collections.setCellRenderer(new MyListCellRenderer());
collections.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
collections.setLayoutOrientation(JList.VERTICAL);
collections.setVisibleRowCount(5);
JScrollPane collectionsScroller = new JScrollPane(collections);
collectionsScroller.setPreferredSize(new Dimension(50, 200));
collectionsScroller.setAlignmentX(LEFT_ALIGNMENT);
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.PAGE_AXIS));
mainPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
mainPanel.add(new JLabel("Collections"));
mainPanel.add(collectionsScroller);
mainPanel.add(new JLabel("Overwrite"));
mainPanel.add(overwrite);
Container contentPane = getContentPane();
contentPane.add(info, BorderLayout.PAGE_START);
contentPane.add(mainPanel, BorderLayout.CENTER);
contentPane.add(buttonPane, BorderLayout.PAGE_END);
((JComponent) contentPane).setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
pack();
setLocationRelativeTo(parent);
setVisible(true);
}
private class MyListCellRenderer extends DefaultListCellRenderer {
@Override
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected,
boolean cellHasFocus) {
JLabel label = (JLabel) super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
label.setOpaque(isSelected); // Highlight only when selected
label.setText(((IdentifiedMetadata) value).getName());
return label;
}
}
private ListModel<IdentifiedMetadata> setupListModel() {
SynBioHubFrontends frontends = new SynBioHubFrontends();
SynBioHubFrontend frontend = null;
if (frontends.hasFrontend(registry.getLocation())) {
frontend = frontends.getFrontend(registry.getLocation());
} else {
frontend = toBeUploaded.addRegistry(registry.getLocation(), registry.getUriPrefix());
}
SearchQuery query = new SearchQuery();
SearchCriteria crit = new SearchCriteria();
crit.setKey("objectType");
crit.setValue("Collection");
query.addCriteria(crit);
query.setLimit(10000);
query.setOffset(0);
List<IdentifiedMetadata> results;
DefaultListModel<IdentifiedMetadata> model = new DefaultListModel<IdentifiedMetadata>();
try {
results = frontend.search(query);
} catch (SynBioHubException e) {
return model;
}
if (results.size() == 0) {
return model;
}
for (IdentifiedMetadata collection : results) {
// don't add collections that have "/public" in the URI.
if (!collection.getUri().contains("/public/")) {
model.addElement(collection);
}
}
return model;
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == cancelButton) {
setVisible(false);
return;
}
if (e.getSource() == uploadButton) {
try {
uploadDesign();
setVisible(false);
return;
} catch (SynBioHubException e1) {
MessageDialog.showMessage(parent, "Uploading failed", Arrays.asList(e1.getMessage().split("\"|,")));
toBeUploaded.clearRegistries();
}
}
}
private void uploadDesign() throws SynBioHubException {
SynBioHubFrontends frontends = new SynBioHubFrontends();
if (!frontends.hasFrontend(registry.getLocation())) {
JOptionPane.showMessageDialog(parent,
"Please login to " + registry.getLocation() + " in the Registry preferences menu.");
return;
}
SynBioHubFrontend frontend = frontends.getFrontend(registry.getLocation());
IdentifiedMetadata selectedCollection = collections.getSelectedValue();
//String option = overwrite.isSelected() ? "3" : "2";
frontend.submit(selectedCollection.getDisplayId().replace("_collection", ""), selectedCollection.getVersion(),
selectedCollection.getName(), selectedCollection.getDescription(), "", overwrite.isSelected(), toBeUploaded);
JOptionPane.showMessageDialog(parent, "Upload successful!");
}
@Override
public void valueChanged(ListSelectionEvent e) {
uploadButton.setEnabled(!collections.isSelectionEmpty());
}
}
|
Fixes issue with submit to existing collection
|
src/main/java/edu/utah/ece/async/sboldesigner/sbol/editor/dialog/UploadExistingDialog.java
|
Fixes issue with submit to existing collection
|
<ide><path>rc/main/java/edu/utah/ece/async/sboldesigner/sbol/editor/dialog/UploadExistingDialog.java
<ide> //String option = overwrite.isSelected() ? "3" : "2";
<ide>
<ide> frontend.submit(selectedCollection.getDisplayId().replace("_collection", ""), selectedCollection.getVersion(),
<del> selectedCollection.getName(), selectedCollection.getDescription(), "", overwrite.isSelected(), toBeUploaded);
<add> overwrite.isSelected(), toBeUploaded);
<ide>
<ide> JOptionPane.showMessageDialog(parent, "Upload successful!");
<ide> }
|
|
Java
|
bsd-3-clause
|
20e1bf702faea7694dd751094bbf94bcec019d49
| 0 |
hypery2k/tracee,SvenBunge/tracee,tracee/tracee,danielwegener/tracee,Hippoom/tracee
|
package de.holisticon.util.tracee.backend.log4j;
import de.holisticon.util.tracee.TraceeLogger;
import org.apache.log4j.Logger;
/**
* TraceeLogger Abstraction for Log4J.
*
* @author Tobias Gindler, holisticon AG
*/
public final class Log4JTraceeLogger implements TraceeLogger {
private final Logger logger;
public Log4JTraceeLogger(final Class<?> clazz) {
this.logger = Logger.getLogger(clazz);
}
public void debug(final Object message) {
this.logger.debug(message);
}
public void debug(final Object message, final Throwable t) {
this.logger.debug(message, t);
}
public void error(final Object message) {
this.logger.error(message);
}
public void error(final Object message, final Throwable t) {
this.logger.error(message, t);
}
public void info(final Object message) {
this.logger.info(message);
}
public void info(final Object message, final Throwable t) {
this.logger.info(message, t);
}
public void warn(final Object message) {
this.logger.warn(message);
}
public void warn(final Object message, final Throwable t) {
this.logger.warn(message, t);
}
}
|
log4j/src/main/java/de/holisticon/util/tracee/backend/log4j/Log4JTraceeLogger.java
|
package de.holisticon.util.tracee.backend.log4j;
import de.holisticon.util.tracee.TraceeLogger;
import org.apache.log4j.Logger;
/**
* TraceeLogger Abstraction for Log4J.
*
* @author Tobias Gindler, holisticon AG
*/
public final class Log4JTraceeLogger implements TraceeLogger {
private final Logger logger;
public Log4JTraceeLogger(final Class<?> clazz) {
this.logger = Logger.getLogger(clazz);
}
public void debug(final Object message) {
this.logger.debug(message);
}
public void debug(final Object message, final Throwable t) {
this.logger.debug(message, t);
}
public void error(final Object message) {
this.logger.error(message);
}
public void error(final Object message, final Throwable t) {
this.logger.debug(message, t);
}
public void info(final Object message) {
this.logger.info(message);
}
public void info(final Object message, final Throwable t) {
this.logger.info(message, t);
}
public void warn(final Object message) {
this.logger.warn(message);
}
public void warn(final Object message, final Throwable t) {
this.logger.warn(message, t);
}
}
|
Resolve #17
|
log4j/src/main/java/de/holisticon/util/tracee/backend/log4j/Log4JTraceeLogger.java
|
Resolve #17
|
<ide><path>og4j/src/main/java/de/holisticon/util/tracee/backend/log4j/Log4JTraceeLogger.java
<ide> }
<ide>
<ide> public void error(final Object message, final Throwable t) {
<del> this.logger.debug(message, t);
<add> this.logger.error(message, t);
<ide> }
<ide>
<ide> public void info(final Object message) {
<ide> public void warn(final Object message, final Throwable t) {
<ide> this.logger.warn(message, t);
<ide> }
<del>
<del>
<ide> }
|
|
Java
|
apache-2.0
|
8b4dece55dbf24b50a1ccf26e821340c416f3b40
| 0 |
RWTH-i5-IDSG/BikeMan,RWTH-i5-IDSG/BikeMan,RWTH-i5-IDSG/BikeMan
|
package de.rwth.idsg.bikeman.ixsi.processor.query.user;
import com.google.common.base.Optional;
import de.rwth.idsg.bikeman.domain.Booking;
import de.rwth.idsg.bikeman.ixsi.ErrorFactory;
import de.rwth.idsg.bikeman.ixsi.IxsiProcessingException;
import de.rwth.idsg.bikeman.ixsi.processor.api.UserRequestProcessor;
import de.rwth.idsg.bikeman.ixsi.service.AvailabilityPushService;
import de.rwth.idsg.bikeman.ixsi.service.BookingService;
import de.rwth.idsg.bikeman.web.rest.exception.DatabaseException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import xjc.schema.ixsi.BookingType;
import xjc.schema.ixsi.ChangeBookingRequestType;
import xjc.schema.ixsi.ChangeBookingResponseType;
import xjc.schema.ixsi.ErrorType;
import xjc.schema.ixsi.Language;
import xjc.schema.ixsi.TimePeriodType;
import xjc.schema.ixsi.UserInfoType;
/**
* @author Sevket Goekay <[email protected]>
* @since 26.09.2014
*/
@Component
public class ChangeBookingRequestProcessor implements
UserRequestProcessor<ChangeBookingRequestType, ChangeBookingResponseType> {
@Autowired private BookingService bookingService;
@Autowired private AvailabilityPushService availabilityPushService;
@Override
public ChangeBookingResponseType processAnonymously(ChangeBookingRequestType request, Optional<Language> lan) {
return buildError(ErrorFactory.Auth.notAnonym("Anonymous change booking request not allowed", null));
}
@Override
public ChangeBookingResponseType processForUser(ChangeBookingRequestType request, Optional<Language> lan,
UserInfoType userInfo) {
try {
if (request.isSetCancel() && request.isCancel()) {
return proceedCancel(request);
} else {
return proceedChange(request);
}
} catch (DatabaseException e) {
return buildError(ErrorFactory.Booking.idUnknown(e.getMessage(), null));
} catch (IxsiProcessingException e) {
return buildError(ErrorFactory.Booking.changeNotPossible(e.getMessage(), e.getMessage()));
}
}
@Transactional
private ChangeBookingResponseType proceedChange(ChangeBookingRequestType request) {
Booking oldBooking = bookingService.get(request.getBookingID());
TimePeriodType oldTimePeriod = buildTimePeriod(oldBooking);
Booking newBooking = bookingService.update(oldBooking, request.getNewTimePeriodProposal());
TimePeriodType newTimePeriod = buildTimePeriod(newBooking);
BookingType responseBooking = new BookingType()
.withID(newBooking.getIxsiBookingId())
.withTimePeriod(newTimePeriod);
String placeId = newBooking.getReservation()
.getPedelec()
.getStationSlot()
.getStation()
.getManufacturerId();
availabilityPushService.changedBooking(request.getBookingID(), placeId, oldTimePeriod, newTimePeriod);
return new ChangeBookingResponseType().withBooking(responseBooking);
}
@Transactional
private ChangeBookingResponseType proceedCancel(ChangeBookingRequestType request) {
Booking booking = bookingService.get(request.getBookingID());
bookingService.cancel(booking);
TimePeriodType timePeriod = buildTimePeriod(booking);
String placeId = booking.getReservation()
.getPedelec()
.getStationSlot()
.getStation()
.getManufacturerId();
availabilityPushService.cancelledBooking(request.getBookingID(), placeId, timePeriod);
return new ChangeBookingResponseType();
}
private TimePeriodType buildTimePeriod(Booking booking) {
return new TimePeriodType()
.withBegin(booking.getReservation().getStartDateTime().toDateTime())
.withEnd(booking.getReservation().getEndDateTime().toDateTime());
}
// -------------------------------------------------------------------------
// Error handling
// -------------------------------------------------------------------------
@Override
public ChangeBookingResponseType buildError(ErrorType e) {
return new ChangeBookingResponseType().withError(e);
}
}
|
src/main/java/de/rwth/idsg/bikeman/ixsi/processor/query/user/ChangeBookingRequestProcessor.java
|
package de.rwth.idsg.bikeman.ixsi.processor.query.user;
import com.google.common.base.Optional;
import de.rwth.idsg.bikeman.domain.Booking;
import de.rwth.idsg.bikeman.ixsi.ErrorFactory;
import de.rwth.idsg.bikeman.ixsi.IxsiProcessingException;
import de.rwth.idsg.bikeman.ixsi.processor.api.UserRequestProcessor;
import de.rwth.idsg.bikeman.ixsi.service.AvailabilityPushService;
import de.rwth.idsg.bikeman.ixsi.service.BookingService;
import de.rwth.idsg.bikeman.web.rest.exception.DatabaseException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import xjc.schema.ixsi.BookingType;
import xjc.schema.ixsi.ChangeBookingRequestType;
import xjc.schema.ixsi.ChangeBookingResponseType;
import xjc.schema.ixsi.ErrorType;
import xjc.schema.ixsi.Language;
import xjc.schema.ixsi.TimePeriodType;
import xjc.schema.ixsi.UserInfoType;
/**
* @author Sevket Goekay <[email protected]>
* @since 26.09.2014
*/
@Component
public class ChangeBookingRequestProcessor implements
UserRequestProcessor<ChangeBookingRequestType, ChangeBookingResponseType> {
@Autowired private BookingService bookingService;
@Autowired private AvailabilityPushService availabilityPushService;
@Override
public ChangeBookingResponseType processAnonymously(ChangeBookingRequestType request, Optional<Language> lan) {
return buildError(ErrorFactory.Auth.notAnonym("Anonymous change booking request not allowed", null));
}
@Override
public ChangeBookingResponseType processForUser(ChangeBookingRequestType request, Optional<Language> lan,
UserInfoType userInfo) {
try {
if (request.isSetCancel() && request.isCancel()) {
return proceedCancel(request);
} else {
return proceedChange(request);
}
} catch (DatabaseException e) {
return buildError(ErrorFactory.Booking.idUnknown(e.getMessage(), null));
} catch (IxsiProcessingException e) {
return buildError(ErrorFactory.Booking.changeNotPossible(e.getMessage(), e.getMessage()));
}
}
private ChangeBookingResponseType proceedChange(ChangeBookingRequestType request) {
Booking oldBooking = bookingService.get(request.getBookingID());
TimePeriodType oldTimePeriod = buildTimePeriod(oldBooking);
Booking newBooking = bookingService.update(oldBooking, request.getNewTimePeriodProposal());
TimePeriodType newTimePeriod = buildTimePeriod(newBooking);
BookingType responseBooking = new BookingType()
.withID(newBooking.getIxsiBookingId())
.withTimePeriod(newTimePeriod);
String placeId = newBooking.getReservation()
.getPedelec()
.getStationSlot()
.getStation()
.getManufacturerId();
availabilityPushService.changedBooking(request.getBookingID(), placeId, oldTimePeriod, newTimePeriod);
return new ChangeBookingResponseType().withBooking(responseBooking);
}
private ChangeBookingResponseType proceedCancel(ChangeBookingRequestType request) {
Booking booking = bookingService.get(request.getBookingID());
bookingService.cancel(booking);
TimePeriodType timePeriod = buildTimePeriod(booking);
String placeId = booking.getReservation()
.getPedelec()
.getStationSlot()
.getStation()
.getManufacturerId();
availabilityPushService.cancelledBooking(request.getBookingID(), placeId, timePeriod);
return new ChangeBookingResponseType();
}
private TimePeriodType buildTimePeriod(Booking booking) {
return new TimePeriodType()
.withBegin(booking.getReservation().getStartDateTime().toDateTime())
.withEnd(booking.getReservation().getEndDateTime().toDateTime());
}
// -------------------------------------------------------------------------
// Error handling
// -------------------------------------------------------------------------
@Override
public ChangeBookingResponseType buildError(ErrorType e) {
return new ChangeBookingResponseType().withError(e);
}
}
|
change/cancel are transactional executions
|
src/main/java/de/rwth/idsg/bikeman/ixsi/processor/query/user/ChangeBookingRequestProcessor.java
|
change/cancel are transactional executions
|
<ide><path>rc/main/java/de/rwth/idsg/bikeman/ixsi/processor/query/user/ChangeBookingRequestProcessor.java
<ide> import de.rwth.idsg.bikeman.web.rest.exception.DatabaseException;
<ide> import org.springframework.beans.factory.annotation.Autowired;
<ide> import org.springframework.stereotype.Component;
<add>import org.springframework.transaction.annotation.Transactional;
<ide> import xjc.schema.ixsi.BookingType;
<ide> import xjc.schema.ixsi.ChangeBookingRequestType;
<ide> import xjc.schema.ixsi.ChangeBookingResponseType;
<ide> }
<ide> }
<ide>
<add> @Transactional
<ide> private ChangeBookingResponseType proceedChange(ChangeBookingRequestType request) {
<ide> Booking oldBooking = bookingService.get(request.getBookingID());
<ide> TimePeriodType oldTimePeriod = buildTimePeriod(oldBooking);
<ide> return new ChangeBookingResponseType().withBooking(responseBooking);
<ide> }
<ide>
<add> @Transactional
<ide> private ChangeBookingResponseType proceedCancel(ChangeBookingRequestType request) {
<ide> Booking booking = bookingService.get(request.getBookingID());
<ide> bookingService.cancel(booking);
|
|
Java
|
mit
|
a90d0751ec452c27bf018754baee7696f861674a
| 0 |
meandor/vs2017,meandor/vs2017
|
package de.haw.vs.neptr.parser;
import de.haw.vs.neptr.idlmodel.IDLClass;
import de.haw.vs.neptr.idlmodel.IDLModule;
import de.haw.vs.neptr.idlmodel.MethodData;
import de.haw.vs.neptr.idlmodel.SupportedDataTypes;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class Parser {
private final String BEGIN_REGEX = "\\{";
private final String END = "};";
private final String MODULE = "module";
private final String CLASS = "class";
private final String PARENTHESES = "[(|)]";
private final String PARAM_SEPARATOR = ",";
private final String IDL_KEYWORD_INT = "int";
private final String IDL_KEYWORD_DOUBLE = "double";
private final String IDL_KEYWORD_STRING = "string";
private final Logger logger = LoggerFactory.getLogger(Parser.class);
/**
* For printing compilation errors
*/
private void printError(int lineNo, String text) {
logger.warn("Line " + lineNo + ": " + text);
}
/**
* Parses IDLFile at the given location and returns it as a module
*
* @param file String file location
* @return IDLModule of parsed content of file
* @throws IOException Throws if files were not found
*/
public IDLModule parse(String file) throws IOException {
IDLFileReader in = new IDLFileReader(new FileReader(file));
return this.parseModule(in);
}
/**
* Parse IDL Module in given file.
*/
private IDLModule parseModule(IDLFileReader in) throws IOException {
String line = in.readLine();
String tokens[] = (line.split(BEGIN_REGEX)[0]).trim().split(" ");
IDLClass newClass;
if (tokens != null && tokens.length > 1 && tokens[0].equals(MODULE) && tokens[1] != null && tokens[1].length() > 0) {
IDLModule currentModule = new IDLModule(tokens[1]);
do {
// parse containing classes
newClass = parseClass(in, currentModule.getModuleName());
if (newClass != null) currentModule.addClass(newClass);
} while (newClass != null);
return currentModule;
} else {
printError(in.getLineNo(), "Error parsing module. '" + line + "'");
return null;
}
}
/**
* Parse (next) class in a file/module.
*
* @param in file reader
* @param currentModuleName name of the module currently being parsed.
* @return the class parsed or null if there is no class left in the file
* @throws IOException thrown when file reader can not read anymore
*/
private IDLClass parseClass(IDLFileReader in, String currentModuleName) throws IOException {
List<MethodData> methodList = new ArrayList<>();
String line = in.readLine();
if (line != null) {
String tokens[] = (line.split(BEGIN_REGEX)[0]).trim().split(" ");
if (tokens != null && tokens.length > 1 && tokens[0].equals(CLASS) && tokens[1] != null && tokens[1].length() > 0) {
// name of this class
String className = tokens[1];
// read methods
line = in.readLine();
while (line != null && !line.contains(END)) {
String[] tokens2 = line.trim().split(PARENTHESES);
String[] tokens3 = tokens2[0].split(" ");
String rTypeString = tokens3[0]; // return value
String methodName = tokens3[1]; // method name
SupportedDataTypes paramTypes[] = parseParams(in.getLineNo(), tokens2[1]);
// into data container
methodList.add(new MethodData(methodName, getSupportedTypeForKeyword(rTypeString), paramTypes));
line = in.readLine();
}
// read class end
if (line == null || !line.contains(END)) {
printError(in.getLineNo(), "Error parsing class " + className + ": no end mark '" + line + "'");
}
// method data -> array
MethodData methodArray[] = new MethodData[methodList.size()];
//return IDL class
return new IDLClass(className, currentModuleName, methodList.toArray(methodArray));
} else {
if (line.contains(END)) {
return null;
} else {
printError(in.getLineNo(), "Error parsing class.'" + line + "'");
return null;
}
}
} else {
printError(in.getLineNo(), "Attempt to read beyond end of file.");
return null;
}
}
/**
* Evaluate parameter list. (No reading done here!)
*/
private SupportedDataTypes[] parseParams(int lineNo, String paramList) {
if (paramList != null && paramList.length() > 0) {
String[] paramEntries = paramList.trim().split(PARAM_SEPARATOR);
// param data container
SupportedDataTypes paramTypes[] = new SupportedDataTypes[paramEntries.length];
for (int i = 0; i < paramEntries.length; i++) {
String[] typeAndParamName = paramEntries[i].trim().split(" ");
// 0: type, 1: name
paramTypes[i] = getSupportedTypeForKeyword(typeAndParamName[0]);
if (paramTypes[i] == null) {
printError(lineNo, "Error parsing param list");
return null;
}
}
return paramTypes;
} else {
return new SupportedDataTypes[0]; // empty list
}
}
/**
* Get supported data type for given keyword.
*/
private SupportedDataTypes getSupportedTypeForKeyword(String keyword) {
switch (keyword) {
case IDL_KEYWORD_DOUBLE:
return SupportedDataTypes.DOUBLE;
case IDL_KEYWORD_INT:
return SupportedDataTypes.INT;
case IDL_KEYWORD_STRING:
return SupportedDataTypes.STRING;
default:
return null;
}
}
}
|
exercise4/idl-compiler/src/main/java/de/haw/vs/neptr/parser/Parser.java
|
package de.haw.vs.neptr.parser;
import de.haw.vs.neptr.idlmodel.IDLClass;
import de.haw.vs.neptr.idlmodel.IDLModule;
import de.haw.vs.neptr.idlmodel.MethodData;
import de.haw.vs.neptr.idlmodel.SupportedDataTypes;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class Parser {
private final String BEGIN_REGEX = "\\{";
private final String END = "};";
private final String MODULE = "module";
private final String CLASS = "class";
private final String PARENTHESES = "[(|)]";
private final String PARAM_SEPARATOR = ",";
private final String IDL_KEYWORD_INT = "int";
private final String IDL_KEYWORD_DOUBLE = "double";
private final String IDL_KEYWORD_STRING = "string";
private final String JAVA_INT = "int";
private final String JAVA_DOUBLE = "double";
private final String JAVA_STRING = "String";
private final Logger logger = LoggerFactory.getLogger(Parser.class);
/**
* For printing compilation errors
*/
private void printError(int lineNo, String text) {
logger.warn("Line " + lineNo + ": " + text);
}
/**
* Parses IDLFile at the given location and returns it as a module
*
* @param file String file location
* @return IDLModule of parsed content of file
* @throws IOException Throws if files were not found
*/
public IDLModule parse(String file) throws IOException {
IDLFileReader in = new IDLFileReader(new FileReader(file));
return this.parseModule(in);
}
/**
* Parse IDL Module in given file.
*/
private IDLModule parseModule(IDLFileReader in) throws IOException {
String line = in.readLine();
String tokens[] = (line.split(BEGIN_REGEX)[0]).trim().split(" ");
IDLClass newClass;
if (tokens != null && tokens.length > 1 && tokens[0].equals(MODULE) && tokens[1] != null && tokens[1].length() > 0) {
IDLModule currentModule = new IDLModule(tokens[1]);
do {
// parse containing classes
newClass = parseClass(in, currentModule.getModuleName());
if (newClass != null) currentModule.addClass(newClass);
} while (newClass != null);
return currentModule;
} else {
printError(in.getLineNo(), "Error parsing module. '" + line + "'");
return null;
}
}
/**
* Parse (next) class in a file/module.
*
* @param in file reader
* @param currentModuleName name of the module currently being parsed.
* @return the class parsed or null if there is no class left in the file
* @throws IOException thrown when file reader can not read anymore
*/
private IDLClass parseClass(IDLFileReader in, String currentModuleName) throws IOException {
List<MethodData> methodList = new ArrayList<>();
String line = in.readLine();
if (line != null) {
String tokens[] = (line.split(BEGIN_REGEX)[0]).trim().split(" ");
if (tokens != null && tokens.length > 1 && tokens[0].equals(CLASS) && tokens[1] != null && tokens[1].length() > 0) {
// name of this class
String className = tokens[1];
// read methods
line = in.readLine();
while (line != null && !line.contains(END)) {
String[] tokens2 = line.trim().split(PARENTHESES);
String[] tokens3 = tokens2[0].split(" ");
String rTypeString = tokens3[0]; // return value
String methodName = tokens3[1]; // method name
SupportedDataTypes paramTypes[] = parseParams(in.getLineNo(), tokens2[1]);
// into data container
methodList.add(new MethodData(methodName, getSupportedTypeForKeyword(rTypeString), paramTypes));
line = in.readLine();
}
// read class end
if (line == null || !line.contains(END)) {
printError(in.getLineNo(), "Error parsing class " + className + ": no end mark '" + line + "'");
}
// method data -> array
MethodData methodArray[] = new MethodData[methodList.size()];
//return IDL class
return new IDLClass(className, currentModuleName, methodList.toArray(methodArray));
} else {
if (line.contains(END)) {
return null;
} else {
printError(in.getLineNo(), "Error parsing class.'" + line + "'");
return null;
}
}
} else {
printError(in.getLineNo(), "Attempt to read beyond end of file.");
return null;
}
}
/**
* Evaluate parameter list. (No reading done here!)
*/
private SupportedDataTypes[] parseParams(int lineNo, String paramList) {
if (paramList != null && paramList.length() > 0) {
String[] paramEntries = paramList.trim().split(PARAM_SEPARATOR);
// param data container
SupportedDataTypes paramTypes[] = new SupportedDataTypes[paramEntries.length];
for (int i = 0; i < paramEntries.length; i++) {
String[] typeAndParamName = paramEntries[i].trim().split(" ");
// 0: type, 1: name
paramTypes[i] = getSupportedTypeForKeyword(typeAndParamName[0]);
if (paramTypes[i] == null) {
printError(lineNo, "Error parsing param list");
return null;
}
}
return paramTypes;
} else {
return new SupportedDataTypes[0]; // empty list
}
}
/**
* Get supported data type for given keyword.
*/
private SupportedDataTypes getSupportedTypeForKeyword(String keyword) {
switch (keyword) {
case IDL_KEYWORD_DOUBLE:
return SupportedDataTypes.DOUBLE;
case IDL_KEYWORD_INT:
return SupportedDataTypes.INT;
case IDL_KEYWORD_STRING:
return SupportedDataTypes.STRING;
default:
return null;
}
}
}
|
remove deprecated fields
|
exercise4/idl-compiler/src/main/java/de/haw/vs/neptr/parser/Parser.java
|
remove deprecated fields
|
<ide><path>xercise4/idl-compiler/src/main/java/de/haw/vs/neptr/parser/Parser.java
<ide> private final String IDL_KEYWORD_INT = "int";
<ide> private final String IDL_KEYWORD_DOUBLE = "double";
<ide> private final String IDL_KEYWORD_STRING = "string";
<del> private final String JAVA_INT = "int";
<del> private final String JAVA_DOUBLE = "double";
<del> private final String JAVA_STRING = "String";
<ide> private final Logger logger = LoggerFactory.getLogger(Parser.class);
<ide>
<ide> /**
|
|
Java
|
apache-2.0
|
66f86d6ab5f09023ce86985402c0b3295653b03d
| 0 |
utgenome/utgb,utgenome/utgb,utgenome/utgb,utgenome/utgb,utgenome/utgb
|
/*--------------------------------------------------------------------------
* Copyright 2009 utgenome.org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*--------------------------------------------------------------------------*/
//--------------------------------------
// utgb-core Project
//
// GWTGraphCanvas.java
// Since: 2010/05/28
//
// $URL$
// $Author$
//--------------------------------------
package org.utgenome.gwt.utgb.client.canvas;
import java.util.ArrayList;
import java.util.List;
import org.utgenome.gwt.utgb.client.bio.CompactWIGData;
import org.utgenome.gwt.utgb.client.canvas.GWTGenomeCanvas.DragPoint;
import org.utgenome.gwt.utgb.client.track.TrackGroup;
import org.utgenome.gwt.utgb.client.track.TrackWindow;
import org.utgenome.gwt.utgb.client.util.Optional;
import org.utgenome.gwt.widget.client.Style;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.AbsolutePanel;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.widgetideas.graphics.client.Color;
import com.google.gwt.widgetideas.graphics.client.GWTCanvas;
/**
* Canvas for drawing bar graph, heat map etc.
*
* @author yoshimura
* @author leo
*
*/
public class GWTGraphCanvas extends Composite {
// widget
private int windowHeight = 100;
private GWTCanvas canvas = new GWTCanvas();
private GWTCanvas frameCanvas = new GWTCanvas();
private AbsolutePanel panel = new AbsolutePanel();
private TrackWindow trackWindow;
private int indentHeight = 0;
private float maxValue = 20.0f;
private float minValue = 0.0f;
private boolean isLog = false;
private boolean drawZeroValue = false;
private TrackGroup trackGroup;
public GWTGraphCanvas() {
init();
}
public void setTrackGroup(TrackGroup trackGroup) {
this.trackGroup = trackGroup;
}
private void init() {
//canvas.setBackgroundColor(new Color(255, 255, 255, 0f));
Style.padding(panel, 0);
Style.margin(panel, 0);
panel.add(frameCanvas, 0, 0);
panel.add(canvas, 0, 0);
initWidget(panel);
sinkEvents(Event.ONMOUSEMOVE | Event.ONMOUSEOVER | Event.ONMOUSEOUT | Event.ONMOUSEDOWN | Event.ONMOUSEUP);
}
private Optional<DragPoint> dragStartPoint = new Optional<DragPoint>();
@Override
public void onBrowserEvent(Event event) {
super.onBrowserEvent(event);
int type = DOM.eventGetType(event);
switch (type) {
case Event.ONMOUSEOVER:
break;
case Event.ONMOUSEMOVE: {
// show readLabels
if (dragStartPoint.isDefined()) {
// scroll the canvas
int clientX = DOM.eventGetClientX(event) + Window.getScrollLeft();
//int clientY = DOM.eventGetClientY(event) + Window.getScrollTop();
DragPoint p = dragStartPoint.get();
int xDiff = clientX - p.x;
//int yDiff = clientY - p.y;
panel.setWidgetPosition(canvas, xDiff, 0);
}
else {
Style.cursor(canvas, Style.CURSOR_AUTO);
}
break;
}
case Event.ONMOUSEOUT: {
resetDrag(event);
break;
}
case Event.ONMOUSEDOWN: {
// invoke a click event
int clientX = DOM.eventGetClientX(event) + Window.getScrollLeft();
int clientY = DOM.eventGetClientY(event) + Window.getScrollTop();
if (dragStartPoint.isUndefined()) {
dragStartPoint.set(new DragPoint(clientX, clientY));
Style.cursor(canvas, Style.CURSOR_RESIZE_E);
event.preventDefault();
}
break;
}
case Event.ONMOUSEUP: {
resetDrag(event);
break;
}
}
}
private void resetDrag(Event event) {
int clientX = DOM.eventGetClientX(event) + Window.getScrollLeft();
int clientY = DOM.eventGetClientY(event) + Window.getScrollTop();
if (dragStartPoint.isDefined() && trackWindow != null) {
DragPoint p = dragStartPoint.get();
int startDiff = trackWindow.calcGenomePosition(clientX) - trackWindow.calcGenomePosition(p.x);
if (startDiff != 0) {
int newStart = trackWindow.getStartOnGenome() - startDiff;
if (newStart < 1)
newStart = 1;
int newEnd = newStart + trackWindow.getWidth();
TrackWindow newWindow = trackWindow.newWindow(newStart, newEnd);
if (trackGroup != null)
trackGroup.setTrackWindow(newWindow);
}
}
dragStartPoint.reset();
event.preventDefault();
Style.cursor(canvas, Style.CURSOR_AUTO);
}
public void clear() {
canvas.clear();
frameCanvas.clear();
panel.setWidgetPosition(canvas, 0, 0);
for (Label each : graphLabels) {
each.removeFromParent();
}
graphLabels.clear();
}
public void drawWigGraph(CompactWIGData data, Color color) {
canvas.saveContext();
canvas.setLineWidth(1.0f);
canvas.setStrokeStyle(color);
float y2 = getYPosition(0.0f);
// draw data graph
for (int i = 0; i < trackWindow.getPixelWidth(); ++i) {
float value = data.getData()[i];
float y1;
if (value == 0.0f) {
if (!drawZeroValue)
continue;
else {
y1 = y2 + ((minValue < maxValue) ? -0.5f : 0.5f);
}
}
else {
y1 = getYPosition(value);
}
int x = i;
if (trackWindow.isReverseStrand()) {
x = trackWindow.getPixelWidth() - x - 1;
}
canvas.saveContext();
canvas.beginPath();
canvas.translate(x + 0.5f, 0);
canvas.moveTo(0, y1);
canvas.lineTo(0, y2);
canvas.stroke();
canvas.restoreContext();
}
canvas.restoreContext();
}
private List<Label> graphLabels = new ArrayList<Label>();
public void drawFrame() {
// draw frame
frameCanvas.saveContext();
frameCanvas.setStrokeStyle(new Color(0, 0, 0, 0.5f));
frameCanvas.setLineWidth(1.0f);
frameCanvas.beginPath();
frameCanvas.rect(0, 0, trackWindow.getPixelWidth(), windowHeight);
frameCanvas.stroke();
frameCanvas.restoreContext();
// draw indent line & label
Indent indent = new Indent(minValue, maxValue);
{
frameCanvas.saveContext();
frameCanvas.setStrokeStyle(Color.BLACK);
frameCanvas.setGlobalAlpha(0.2f);
frameCanvas.setLineWidth(0.5f);
for (int i = 0; i <= indent.nSteps; i++) {
float value = indent.getIndentValue(i);
// draw indent line
frameCanvas.saveContext();
frameCanvas.beginPath();
frameCanvas.translate(0, getYPosition(value) + 0.5d);
frameCanvas.moveTo(0d, 0d);
frameCanvas.lineTo(trackWindow.getPixelWidth(), 0);
frameCanvas.stroke();
frameCanvas.restoreContext();
}
{
// draw zero line
frameCanvas.saveContext();
frameCanvas.beginPath();
frameCanvas.translate(0, getYPosition(0f));
frameCanvas.moveTo(0, 0);
frameCanvas.lineTo(trackWindow.getPixelWidth(), 0);
frameCanvas.stroke();
frameCanvas.restoreContext();
}
frameCanvas.restoreContext();
}
}
public void drawScaleLabel() {
Indent indent = new Indent(minValue, maxValue);
int fontHeight = 10;
for (int i = 0; i <= indent.nSteps; i++) {
float value = indent.getIndentValue(i);
Label label = new Label(indent.getIndentString(i));
Style.fontSize(label, fontHeight);
Style.textAlign(label, "left");
Style.fontColor(label, "#003366");
int labelX = 1;
int labelY = (int) (getYPosition(value) - fontHeight);
if (labelY > windowHeight)
continue;
graphLabels.add(label);
panel.add(label, labelX, labelY);
// if (label[i].getOffsetWidth() < leftMargin)
// labelPosition = leftMargin - label[i].getOffsetWidth();
//panel.setWidgetPosition(label[i], labelX,
// if (getYPosition(value) < 0.0f || getYPosition(value) > windowHeight) {
// panel.remove(label[i]);
// continue;
// }
}
}
public class Indent {
public int exponent = 0;
public long fraction = 0;
public int nSteps = 0;
public float min = 0.0f;
public float max = 0.0f;
public Indent(float minValue, float maxValue) {
if (indentHeight == 0)
indentHeight = 10;
min = minValue < maxValue ? minValue : maxValue;
max = minValue > maxValue ? minValue : maxValue;
if (isLog) {
min = getLogValue(min);
max = getLogValue(max);
}
double tempIndentValue = (max - min) / windowHeight * indentHeight;
if (isLog && tempIndentValue < 1.0)
tempIndentValue = 1.0;
fraction = (long) Math.floor(Math.log10(tempIndentValue));
exponent = (int) Math.ceil(Math.round(tempIndentValue / Math.pow(10, fraction - 3)) / 1000.0);
if (exponent <= 5)
;
// else if(exponent <= 7)
// exponent = 5;
else {
exponent = 1;
fraction++;
}
double stepSize = exponent * Math.pow(10, fraction);
max = (float) (Math.floor(max / stepSize) * stepSize);
min = (float) (Math.ceil(min / stepSize) * stepSize);
nSteps = (int) Math.abs((max - min) / stepSize);
}
public float getIndentValue(int step) {
double indentValue = min + (step * exponent * Math.pow(10, fraction));
if (!isLog)
return (float) indentValue;
else if (indentValue == 0.0f)
return 0.0f;
else if (indentValue >= 0.0f)
return (float) Math.pow(2, indentValue - 1);
else
return (float) -Math.pow(2, -indentValue - 1);
}
public String getIndentString(int step) {
float indentValue = getIndentValue(step);
if (indentValue == (int) indentValue)
return String.valueOf((int) indentValue);
else {
int exponent_tmp = (int) Math.ceil(Math.round(indentValue / Math.pow(10, fraction - 3)) / 1000.0);
int endIndex = String.valueOf(exponent_tmp).length() + 1;
if (fraction < 0)
endIndex -= fraction;
endIndex = Math.min(String.valueOf(indentValue).length(), endIndex);
return String.valueOf(indentValue).substring(0, endIndex);
}
}
}
public float getYPosition(float value) {
if (maxValue == minValue)
return 0.0f;
float tempMin = maxValue < minValue ? maxValue : minValue;
float tempMax = maxValue > minValue ? maxValue : minValue;
if (isLog) {
value = getLogValue(value);
tempMax = getLogValue(tempMax);
tempMin = getLogValue(tempMin);
}
float valueHeight = (value - tempMin) / (tempMax - tempMin) * windowHeight;
if (maxValue < minValue)
return valueHeight;
else
return windowHeight - valueHeight;
}
private float logBase = 2.0f;
public float getLogBase() {
return logBase;
}
public void setLogBase(float logBase) {
this.logBase = logBase;
}
public float getLogValue(float value) {
if (Math.log(logBase) == 0.0)
return value;
float temp = 0.0f;
if (value > 0.0f) {
temp = (float) (Math.log(value) / Math.log(logBase) + 1.0);
if (temp < 0.0f)
temp = 0.0f;
}
else if (value < 0.0f) {
temp = (float) (Math.log(-value) / Math.log(logBase) + 1.0);
if (temp < 0.0f)
temp = 0.0f;
temp *= -1.0f;
}
return temp;
}
public void setTrackWindow(TrackWindow w) {
trackWindow = w;
}
public void setWindowHeight(int windowHeight) {
this.windowHeight = windowHeight;
setPixelSize(trackWindow.getPixelWidth(), windowHeight);
}
@Override
public void setPixelSize(int width, int height) {
canvas.setCoordSize(width, height);
canvas.setPixelWidth(width);
canvas.setPixelHeight(height);
frameCanvas.setCoordSize(width, height);
frameCanvas.setPixelWidth(width);
frameCanvas.setPixelHeight(height);
panel.setPixelSize(width, height);
}
public int getWindowHeight() {
return windowHeight;
}
public float getMaxValue() {
return maxValue;
}
public void setMaxValue(float maxValue) {
this.maxValue = maxValue;
}
public float getMinValue() {
return minValue;
}
public void setMinValue(float minValue) {
this.minValue = minValue;
}
public boolean getIsLog() {
return isLog;
}
public void setIsLog(boolean isLog) {
this.isLog = isLog;
}
public int getIndentHeight() {
return indentHeight;
}
public void setIndentHeight(int indentHeight) {
this.indentHeight = indentHeight;
}
public void setShowZeroValue(boolean showZeroValue) {
this.drawZeroValue = showZeroValue;
}
}
|
utgb-core/src/main/java/org/utgenome/gwt/utgb/client/canvas/GWTGraphCanvas.java
|
/*--------------------------------------------------------------------------
* Copyright 2009 utgenome.org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*--------------------------------------------------------------------------*/
//--------------------------------------
// utgb-core Project
//
// GWTGraphCanvas.java
// Since: 2010/05/28
//
// $URL$
// $Author$
//--------------------------------------
package org.utgenome.gwt.utgb.client.canvas;
import java.util.ArrayList;
import java.util.List;
import org.utgenome.gwt.utgb.client.bio.CompactWIGData;
import org.utgenome.gwt.utgb.client.canvas.GWTGenomeCanvas.DragPoint;
import org.utgenome.gwt.utgb.client.track.TrackGroup;
import org.utgenome.gwt.utgb.client.track.TrackWindow;
import org.utgenome.gwt.utgb.client.util.Optional;
import org.utgenome.gwt.widget.client.Style;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.AbsolutePanel;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.widgetideas.graphics.client.Color;
import com.google.gwt.widgetideas.graphics.client.GWTCanvas;
/**
* Canvas for drawing bar graph, heat map etc.
*
* @author yoshimura
* @author leo
*
*/
public class GWTGraphCanvas extends Composite {
// widget
private int windowHeight = 100;
private GWTCanvas canvas = new GWTCanvas();
private GWTCanvas frameCanvas = new GWTCanvas();
private AbsolutePanel panel = new AbsolutePanel();
private TrackWindow trackWindow;
private int indentHeight = 0;
private float maxValue = 20.0f;
private float minValue = 0.0f;
private boolean isLog = false;
private boolean drawZeroValue = false;
private TrackGroup trackGroup;
public GWTGraphCanvas() {
init();
}
public void setTrackGroup(TrackGroup trackGroup) {
this.trackGroup = trackGroup;
}
private void init() {
//canvas.setBackgroundColor(new Color(255, 255, 255, 0f));
Style.padding(panel, 0);
Style.margin(panel, 0);
panel.add(frameCanvas, 0, 0);
panel.add(canvas, 0, 0);
initWidget(panel);
sinkEvents(Event.ONMOUSEMOVE | Event.ONMOUSEOVER | Event.ONMOUSEOUT | Event.ONMOUSEDOWN | Event.ONMOUSEUP);
}
private Optional<DragPoint> dragStartPoint = new Optional<DragPoint>();
@Override
public void onBrowserEvent(Event event) {
super.onBrowserEvent(event);
int type = DOM.eventGetType(event);
switch (type) {
case Event.ONMOUSEOVER:
break;
case Event.ONMOUSEMOVE: {
// show readLabels
if (dragStartPoint.isDefined()) {
// scroll the canvas
int clientX = DOM.eventGetClientX(event) + Window.getScrollLeft();
//int clientY = DOM.eventGetClientY(event) + Window.getScrollTop();
DragPoint p = dragStartPoint.get();
int xDiff = clientX - p.x;
//int yDiff = clientY - p.y;
panel.setWidgetPosition(canvas, xDiff, 0);
}
else {
Style.cursor(canvas, Style.CURSOR_AUTO);
}
break;
}
case Event.ONMOUSEOUT: {
resetDrag(event);
break;
}
case Event.ONMOUSEDOWN: {
// invoke a click event
int clientX = DOM.eventGetClientX(event) + Window.getScrollLeft();
int clientY = DOM.eventGetClientY(event) + Window.getScrollTop();
if (dragStartPoint.isUndefined()) {
dragStartPoint.set(new DragPoint(clientX, clientY));
Style.cursor(canvas, Style.CURSOR_RESIZE_E);
event.preventDefault();
}
break;
}
case Event.ONMOUSEUP: {
resetDrag(event);
break;
}
}
}
private void resetDrag(Event event) {
int clientX = DOM.eventGetClientX(event) + Window.getScrollLeft();
int clientY = DOM.eventGetClientY(event) + Window.getScrollTop();
if (dragStartPoint.isDefined() && trackWindow != null) {
DragPoint p = dragStartPoint.get();
int startDiff = trackWindow.calcGenomePosition(clientX) - trackWindow.calcGenomePosition(p.x);
if (startDiff != 0) {
int newStart = trackWindow.getStartOnGenome() - startDiff;
if (newStart < 1)
newStart = 1;
int newEnd = newStart + trackWindow.getWidth();
TrackWindow newWindow = trackWindow.newWindow(newStart, newEnd);
if (trackGroup != null)
trackGroup.setTrackWindow(newWindow);
}
}
dragStartPoint.reset();
event.preventDefault();
Style.cursor(canvas, Style.CURSOR_AUTO);
}
public void clear() {
canvas.clear();
frameCanvas.clear();
for (Label each : graphLabels) {
each.removeFromParent();
}
graphLabels.clear();
}
public void drawWigGraph(CompactWIGData data, Color color) {
canvas.saveContext();
canvas.setLineWidth(1.0f);
canvas.setStrokeStyle(color);
float y2 = getYPosition(0.0f);
// draw data graph
for (int i = 0; i < trackWindow.getPixelWidth(); ++i) {
float value = data.getData()[i];
float y1;
if (value == 0.0f) {
if (!drawZeroValue)
continue;
else {
y1 = y2 + ((minValue < maxValue) ? -0.5f : 0.5f);
}
}
else {
y1 = getYPosition(value);
}
int x = i;
if (trackWindow.isReverseStrand()) {
x = trackWindow.getPixelWidth() - x - 1;
}
canvas.saveContext();
canvas.beginPath();
canvas.translate(x + 0.5f, 0);
canvas.moveTo(0, y1);
canvas.lineTo(0, y2);
canvas.stroke();
canvas.restoreContext();
}
canvas.restoreContext();
}
private List<Label> graphLabels = new ArrayList<Label>();
public void drawFrame() {
// draw frame
frameCanvas.saveContext();
frameCanvas.setStrokeStyle(new Color(0, 0, 0, 0.5f));
frameCanvas.setLineWidth(1.0f);
frameCanvas.beginPath();
frameCanvas.rect(0, 0, trackWindow.getPixelWidth(), windowHeight);
frameCanvas.stroke();
frameCanvas.restoreContext();
// draw indent line & label
Indent indent = new Indent(minValue, maxValue);
{
frameCanvas.saveContext();
frameCanvas.setStrokeStyle(Color.BLACK);
frameCanvas.setGlobalAlpha(0.2f);
frameCanvas.setLineWidth(0.5f);
for (int i = 0; i <= indent.nSteps; i++) {
float value = indent.getIndentValue(i);
// draw indent line
frameCanvas.saveContext();
frameCanvas.beginPath();
frameCanvas.translate(0, getYPosition(value) + 0.5d);
frameCanvas.moveTo(0d, 0d);
frameCanvas.lineTo(trackWindow.getPixelWidth(), 0);
frameCanvas.stroke();
frameCanvas.restoreContext();
}
{
// draw zero line
frameCanvas.saveContext();
frameCanvas.beginPath();
frameCanvas.translate(0, getYPosition(0f));
frameCanvas.moveTo(0, 0);
frameCanvas.lineTo(trackWindow.getPixelWidth(), 0);
frameCanvas.stroke();
frameCanvas.restoreContext();
}
frameCanvas.restoreContext();
}
}
public void drawScaleLabel() {
Indent indent = new Indent(minValue, maxValue);
int fontHeight = 10;
for (int i = 0; i <= indent.nSteps; i++) {
float value = indent.getIndentValue(i);
Label label = new Label(indent.getIndentString(i));
Style.fontSize(label, fontHeight);
Style.textAlign(label, "left");
Style.fontColor(label, "#003366");
int labelX = 1;
int labelY = (int) (getYPosition(value) - fontHeight);
if (labelY > windowHeight)
continue;
graphLabels.add(label);
panel.add(label, labelX, labelY);
// if (label[i].getOffsetWidth() < leftMargin)
// labelPosition = leftMargin - label[i].getOffsetWidth();
//panel.setWidgetPosition(label[i], labelX,
// if (getYPosition(value) < 0.0f || getYPosition(value) > windowHeight) {
// panel.remove(label[i]);
// continue;
// }
}
}
public class Indent {
public int exponent = 0;
public long fraction = 0;
public int nSteps = 0;
public float min = 0.0f;
public float max = 0.0f;
public Indent(float minValue, float maxValue) {
if (indentHeight == 0)
indentHeight = 10;
min = minValue < maxValue ? minValue : maxValue;
max = minValue > maxValue ? minValue : maxValue;
if (isLog) {
min = getLogValue(min);
max = getLogValue(max);
}
double tempIndentValue = (max - min) / windowHeight * indentHeight;
if (isLog && tempIndentValue < 1.0)
tempIndentValue = 1.0;
fraction = (long) Math.floor(Math.log10(tempIndentValue));
exponent = (int) Math.ceil(Math.round(tempIndentValue / Math.pow(10, fraction - 3)) / 1000.0);
if (exponent <= 5)
;
// else if(exponent <= 7)
// exponent = 5;
else {
exponent = 1;
fraction++;
}
double stepSize = exponent * Math.pow(10, fraction);
max = (float) (Math.floor(max / stepSize) * stepSize);
min = (float) (Math.ceil(min / stepSize) * stepSize);
nSteps = (int) Math.abs((max - min) / stepSize);
}
public float getIndentValue(int step) {
double indentValue = min + (step * exponent * Math.pow(10, fraction));
if (!isLog)
return (float) indentValue;
else if (indentValue == 0.0f)
return 0.0f;
else if (indentValue >= 0.0f)
return (float) Math.pow(2, indentValue - 1);
else
return (float) -Math.pow(2, -indentValue - 1);
}
public String getIndentString(int step) {
float indentValue = getIndentValue(step);
if (indentValue == (int) indentValue)
return String.valueOf((int) indentValue);
else {
int exponent_tmp = (int) Math.ceil(Math.round(indentValue / Math.pow(10, fraction - 3)) / 1000.0);
int endIndex = String.valueOf(exponent_tmp).length() + 1;
if (fraction < 0)
endIndex -= fraction;
endIndex = Math.min(String.valueOf(indentValue).length(), endIndex);
return String.valueOf(indentValue).substring(0, endIndex);
}
}
}
public float getYPosition(float value) {
if (maxValue == minValue)
return 0.0f;
float tempMin = maxValue < minValue ? maxValue : minValue;
float tempMax = maxValue > minValue ? maxValue : minValue;
if (isLog) {
value = getLogValue(value);
tempMax = getLogValue(tempMax);
tempMin = getLogValue(tempMin);
}
float valueHeight = (value - tempMin) / (tempMax - tempMin) * windowHeight;
if (maxValue < minValue)
return valueHeight;
else
return windowHeight - valueHeight;
}
private float logBase = 2.0f;
public float getLogBase() {
return logBase;
}
public void setLogBase(float logBase) {
this.logBase = logBase;
}
public float getLogValue(float value) {
if (Math.log(logBase) == 0.0)
return value;
float temp = 0.0f;
if (value > 0.0f) {
temp = (float) (Math.log(value) / Math.log(logBase) + 1.0);
if (temp < 0.0f)
temp = 0.0f;
}
else if (value < 0.0f) {
temp = (float) (Math.log(-value) / Math.log(logBase) + 1.0);
if (temp < 0.0f)
temp = 0.0f;
temp *= -1.0f;
}
return temp;
}
public void setTrackWindow(TrackWindow w) {
trackWindow = w;
}
public void setWindowHeight(int windowHeight) {
this.windowHeight = windowHeight;
setPixelSize(trackWindow.getPixelWidth(), windowHeight);
}
@Override
public void setPixelSize(int width, int height) {
canvas.setCoordSize(width, height);
canvas.setPixelWidth(width);
canvas.setPixelHeight(height);
frameCanvas.setCoordSize(width, height);
frameCanvas.setPixelWidth(width);
frameCanvas.setPixelHeight(height);
panel.setPixelSize(width, height);
}
public int getWindowHeight() {
return windowHeight;
}
public float getMaxValue() {
return maxValue;
}
public void setMaxValue(float maxValue) {
this.maxValue = maxValue;
}
public float getMinValue() {
return minValue;
}
public void setMinValue(float minValue) {
this.minValue = minValue;
}
public boolean getIsLog() {
return isLog;
}
public void setIsLog(boolean isLog) {
this.isLog = isLog;
}
public int getIndentHeight() {
return indentHeight;
}
public void setIndentHeight(int indentHeight) {
this.indentHeight = indentHeight;
}
public void setShowZeroValue(boolean showZeroValue) {
this.drawZeroValue = showZeroValue;
}
}
|
reset canvas position
|
utgb-core/src/main/java/org/utgenome/gwt/utgb/client/canvas/GWTGraphCanvas.java
|
reset canvas position
|
<ide><path>tgb-core/src/main/java/org/utgenome/gwt/utgb/client/canvas/GWTGraphCanvas.java
<ide> public void clear() {
<ide> canvas.clear();
<ide> frameCanvas.clear();
<add>
<add> panel.setWidgetPosition(canvas, 0, 0);
<add>
<ide> for (Label each : graphLabels) {
<ide> each.removeFromParent();
<ide> }
|
|
JavaScript
|
mit
|
27eb3de9cbe2255c5f1c8401eb145618db98953f
| 0 |
ArnaudBuchholz/gpf-js,ArnaudBuchholz/gpf-js
|
/**
* @file Host detection, non-UMD loader
* @since 0.1.5
*/
/*#ifndef(UMD)*/
"use strict";
/*exported _GPF_HOST*/ // Host types
/*exported _gpfBootImplByHost*/ // Boot host specific implementation per host
/*exported _gpfDosPath*/ // DOS-like path
/*exported _gpfEmptyFunc*/ // An empty function
/*exported _gpfExit*/ // Exit function
/*exported _gpfHost*/ // Host type
/*exported _gpfIgnore*/ // Helper to remove unused parameter warning
/*exported _gpfMainContext*/ // Main context object
/*exported _gpfMsFSO*/ // Scripting.FileSystemObject activeX
/*exported _gpfNodeFs*/ // Node/PhantomJS require("fs")
/*exported _gpfNodePath*/ // Node require("path")
/*exported _gpfSyncReadSourceJSON*/ // Reads a source json file (only in source mode)
/*exported _gpfVersion*/ // GPF version
/*exported _gpfWebDocument*/ // Browser document object
/*exported _gpfWebWindow*/ // Browser window object
/*eslint-disable no-unused-vars*/
/*#endif*/
/*jshint browser: true, node: true, phantom: true, rhino: true, wsh: true*/
/*eslint-env browser, node, phantomjs, rhino, wsh*/
// An empty function
function _gpfEmptyFunc () {}
var
/**
* GPF Version
* @since 0.1.5
*/
_gpfVersion = "0.2.3-alpha",
/**
* Host constants
* @since 0.1.5
*/
_GPF_HOST = {
BROWSER: "browser",
NODEJS: "nodejs",
PHANTOMJS: "phantomjs",
RHINO: "rhino",
UNKNOWN: "unknown",
WSCRIPT: "wscript"
},
/**
* Current host type
*
* @type {_GPF_HOST}
* @since 0.1.5
*/
_gpfHost = _GPF_HOST.UNKNOWN,
/**
* Indicates that paths are DOS-like (i.e. case insensitive with /)
* @since 0.1.5
*/
_gpfDosPath = false,
/*jshint -W040*/ // This is the common way to get the global context
/**
* Main context object
*
* @type {Object}
* @since 0.1.5
*/
_gpfMainContext = this, //eslint-disable-line no-invalid-this, consistent-this
/*jshint +W040*/
/**
* Helper to ignore unused parameter
*
* @param {*} param
* @since 0.1.5
*/
/*gpf:nop*/ _gpfIgnore = _gpfEmptyFunc,
/**
* Exit function
*
* @param {Number} code
* @since 0.1.5
*/
_gpfExit = _gpfEmptyFunc,
/**
* Browser window object
*
* @type {Object}
* @since 0.1.5
*/
_gpfWebWindow,
/**
* Browser [document](https://developer.mozilla.org/en-US/docs/Web/API/Document) object
*
* @type {Object}
* @since 0.1.5
*/
_gpfWebDocument,
/**
* [Scripting.FileSystemObject](https://msdn.microsoft.com/en-us/library/aa711216(v=vs.71).aspx) Object
*
* @type {Object}
* @since 0.1.5
*/
_gpfMsFSO,
/**
* Node [require("fs")](https://nodejs.org/api/fs.html)
*
* @type {Object}
* @since 0.1.5
*/
_gpfNodeFs,
/**
* Node [require("path")](https://nodejs.org/api/path.html)
*
* @type {Object}
* @since 0.1.5
*/
_gpfNodePath,
/**
* Boot host specific implementation per host
*
* @type {Object}
* @since 0.2.1
*/
_gpfBootImplByHost = {};
/*#ifdef(DEBUG)*/
_gpfVersion += "-debug";
/*#endif*/
/*#ifndef(UMD)*/
_gpfVersion += "-source";
/**
* Synchronous read function
*
* @param {String} srcFileName
* @return {String} content of the srcFileName
* @since 0.1.5
*/
var _gpfSyncReadForBoot;
/*#endif*/
/* Host detection */
// Microsoft cscript / wscript
if ("undefined" !== typeof WScript) {
_gpfHost = _GPF_HOST.WSCRIPT;
_gpfDosPath = true;
/*#ifndef(UMD)*/
/*eslint-disable new-cap*/
_gpfMsFSO = new ActiveXObject("Scripting.FileSystemObject");
_gpfSyncReadForBoot = function (srcFileName) {
var srcFile = _gpfMsFSO.OpenTextFile(srcFileName, 1),
srcContent = srcFile.ReadAll();
srcFile.Close();
return srcContent;
};
/*eslint-enable new-cap*/
/*#endif*/
} else if ("undefined" !== typeof print && "undefined" !== typeof java) {
_gpfHost = _GPF_HOST.RHINO;
_gpfDosPath = false;
/*#ifndef(UMD)*/
_gpfSyncReadForBoot = readFile;
/*#endif*/
// PhantomJS - When used as a command line (otherwise considered as a browser)
} else if ("undefined" !== typeof phantom && phantom.version && !document.currentScript) {
_gpfHost = _GPF_HOST.PHANTOMJS;
_gpfDosPath = require("fs").separator === "\\";
_gpfMainContext = window;
/*#ifndef(UMD)*/
_gpfNodeFs = require("fs");
_gpfSyncReadForBoot = function (srcFileName) {
return _gpfNodeFs.read(srcFileName);
};
/*#endif*/
// Nodejs
} else if ("undefined" !== typeof module && module.exports) {
_gpfHost = _GPF_HOST.NODEJS;
_gpfNodePath = require("path");
_gpfDosPath = _gpfNodePath.sep === "\\";
_gpfMainContext = global;
/*#ifndef(UMD)*/
/*eslint-disable no-sync*/ // Simpler this way
_gpfNodeFs = require("fs");
_gpfSyncReadForBoot = function (srcFileName) {
return _gpfNodeFs.readFileSync(srcFileName).toString();
};
/*#endif*/
// Browser
/* istanbul ignore else */ // unknown.1
} else if ("undefined" !== typeof window) {
_gpfHost = _GPF_HOST.BROWSER;
_gpfMainContext = window;
/*#ifndef(UMD)*/
_gpfSyncReadForBoot = function (srcFileName) {
var xhr = new XMLHttpRequest();
xhr.open("GET", srcFileName, false);
xhr.send();
return xhr.responseText;
};
/*#endif*/
}
/*#ifndef(UMD)*/
/**
* Loading sources occurs here for the non UMD version.
* UMD versions (debug / release) will have everything concatenated.
* @since 0.1.5
*/
// Need to create the gpf name 'manually'
_gpfMainContext.gpf = {
internals: {} // To support testable internals
};
/**
* Contains the root path of GPF sources
*
* @name gpfSourcesPath
* @type {String}
* @private
* @since 0.0.1
*/
/**
* Reads a source file (only in source mode)
*
* NOTE this method is available only when running the source version
*
* @param {String} sourceFileName Source file name (relative to src folder)
* @return {String} Source content
* @since 0.1.7
*/
function _gpfSyncReadSourceJSON (sourceFileName) {
/*jslint evil: true*/
var result;
eval("result = " + _gpfSyncReadForBoot(gpfSourcesPath + sourceFileName) + ";"); //eslint-disable-line no-eval
return result;
}
/**
* Load content of all sources
*
* @return {String} Consolidated sources
* @since 0.1.9
*/
function _gpfLoadSources () { //jshint ignore:line
/*jslint evil: true*/
var sourceListContent = _gpfSyncReadForBoot(gpfSourcesPath + "sources.json"),
_gpfSources,
allContent = [],
idx = 0,
source;
eval("_gpfSources = " + sourceListContent + ";"); //eslint-disable-line no-eval
for (; idx < _gpfSources.length; ++idx) {
source = _gpfSources[idx];
if (source.load !== false) {
allContent.push(_gpfSyncReadForBoot(gpfSourcesPath + source.name + ".js"));
}
}
return allContent.join("\r\n");
}
/*jshint ignore:start*/ // Best way I found
eval(_gpfLoadSources()); //eslint-disable-line no-eval
/*jshint ignore:end*/
/*#endif*/
/**
* Host type enumeration
*
* @enum {String}
* @readonly
* @since 0.1.5
*/
gpf.hosts = {
/**
* Any browser (phantomjs is recognized separately)
* @since 0.1.5
*/
browser: _GPF_HOST.BROWSER,
/**
* [NodeJs](http://nodejs.org/)
* @since 0.1.5
*/
nodejs: _GPF_HOST.NODEJS,
/**
* [PhantomJS](http://phantomjs.org/)
* @since 0.1.5
*/
phantomjs: _GPF_HOST.PHANTOMJS,
/**
* [Rhino](http://developer.mozilla.org/en/docs/Rhino)
* @since 0.1.5
*/
rhino: _GPF_HOST.RHINO,
/**
* Unknown (detection failed or the host is unknown)
* @since 0.1.5
*/
unknown: _GPF_HOST.UNKNOWN,
/**
* [cscript/wscript](http://technet.microsoft.com/en-us/library/bb490887.aspx)
* @since 0.1.5
*/
wscript: _GPF_HOST.WSCRIPT
};
/**
* Returns the detected host type
*
* @return {gpf.hosts} Host type
* @since 0.1.5
*/
gpf.host = function () {
return _gpfHost;
};
/**
* Returns the current version
*
* @return {String} Version
* @since 0.1.5
*/
gpf.version = function () {
return _gpfVersion;
};
|
src/boot.js
|
/**
* @file Host detection, non-UMD loader
* @since 0.1.5
*/
/*#ifndef(UMD)*/
"use strict";
/*exported _GPF_HOST*/ // Host types
/*exported _gpfBootImplByHost*/ // Boot host specific implementation per host
/*exported _gpfDosPath*/ // DOS-like path
/*exported _gpfEmptyFunc*/ // An empty function
/*exported _gpfExit*/ // Exit function
/*exported _gpfHost*/ // Host type
/*exported _gpfIgnore*/ // Helper to remove unused parameter warning
/*exported _gpfMainContext*/ // Main context object
/*exported _gpfMsFSO*/ // Scripting.FileSystemObject activeX
/*exported _gpfNodeFs*/ // Node/PhantomJS require("fs")
/*exported _gpfNodePath*/ // Node require("path")
/*exported _gpfSyncReadSourceJSON*/ // Reads a source json file (only in source mode)
/*exported _gpfVersion*/ // GPF version
/*exported _gpfWebDocument*/ // Browser document object
/*exported _gpfWebWindow*/ // Browser window object
/*eslint-disable no-unused-vars*/
/*#endif*/
/*jshint browser: true, node: true, phantom: true, rhino: true, wsh: true*/
/*eslint-env browser, node, phantomjs, rhino, wsh*/
// An empty function
function _gpfEmptyFunc () {}
var
/**
* GPF Version
* @since 0.1.5
*/
_gpfVersion = "0.2.2",
/**
* Host constants
* @since 0.1.5
*/
_GPF_HOST = {
BROWSER: "browser",
NODEJS: "nodejs",
PHANTOMJS: "phantomjs",
RHINO: "rhino",
UNKNOWN: "unknown",
WSCRIPT: "wscript"
},
/**
* Current host type
*
* @type {_GPF_HOST}
* @since 0.1.5
*/
_gpfHost = _GPF_HOST.UNKNOWN,
/**
* Indicates that paths are DOS-like (i.e. case insensitive with /)
* @since 0.1.5
*/
_gpfDosPath = false,
/*jshint -W040*/ // This is the common way to get the global context
/**
* Main context object
*
* @type {Object}
* @since 0.1.5
*/
_gpfMainContext = this, //eslint-disable-line no-invalid-this, consistent-this
/*jshint +W040*/
/**
* Helper to ignore unused parameter
*
* @param {*} param
* @since 0.1.5
*/
/*gpf:nop*/ _gpfIgnore = _gpfEmptyFunc,
/**
* Exit function
*
* @param {Number} code
* @since 0.1.5
*/
_gpfExit = _gpfEmptyFunc,
/**
* Browser window object
*
* @type {Object}
* @since 0.1.5
*/
_gpfWebWindow,
/**
* Browser [document](https://developer.mozilla.org/en-US/docs/Web/API/Document) object
*
* @type {Object}
* @since 0.1.5
*/
_gpfWebDocument,
/**
* [Scripting.FileSystemObject](https://msdn.microsoft.com/en-us/library/aa711216(v=vs.71).aspx) Object
*
* @type {Object}
* @since 0.1.5
*/
_gpfMsFSO,
/**
* Node [require("fs")](https://nodejs.org/api/fs.html)
*
* @type {Object}
* @since 0.1.5
*/
_gpfNodeFs,
/**
* Node [require("path")](https://nodejs.org/api/path.html)
*
* @type {Object}
* @since 0.1.5
*/
_gpfNodePath,
/**
* Boot host specific implementation per host
*
* @type {Object}
* @since 0.2.1
*/
_gpfBootImplByHost = {};
/*#ifdef(DEBUG)*/
_gpfVersion += "-debug";
/*#endif*/
/*#ifndef(UMD)*/
_gpfVersion += "-source";
/**
* Synchronous read function
*
* @param {String} srcFileName
* @return {String} content of the srcFileName
* @since 0.1.5
*/
var _gpfSyncReadForBoot;
/*#endif*/
/* Host detection */
// Microsoft cscript / wscript
if ("undefined" !== typeof WScript) {
_gpfHost = _GPF_HOST.WSCRIPT;
_gpfDosPath = true;
/*#ifndef(UMD)*/
/*eslint-disable new-cap*/
_gpfMsFSO = new ActiveXObject("Scripting.FileSystemObject");
_gpfSyncReadForBoot = function (srcFileName) {
var srcFile = _gpfMsFSO.OpenTextFile(srcFileName, 1),
srcContent = srcFile.ReadAll();
srcFile.Close();
return srcContent;
};
/*eslint-enable new-cap*/
/*#endif*/
} else if ("undefined" !== typeof print && "undefined" !== typeof java) {
_gpfHost = _GPF_HOST.RHINO;
_gpfDosPath = false;
/*#ifndef(UMD)*/
_gpfSyncReadForBoot = readFile;
/*#endif*/
// PhantomJS - When used as a command line (otherwise considered as a browser)
} else if ("undefined" !== typeof phantom && phantom.version && !document.currentScript) {
_gpfHost = _GPF_HOST.PHANTOMJS;
_gpfDosPath = require("fs").separator === "\\";
_gpfMainContext = window;
/*#ifndef(UMD)*/
_gpfNodeFs = require("fs");
_gpfSyncReadForBoot = function (srcFileName) {
return _gpfNodeFs.read(srcFileName);
};
/*#endif*/
// Nodejs
} else if ("undefined" !== typeof module && module.exports) {
_gpfHost = _GPF_HOST.NODEJS;
_gpfNodePath = require("path");
_gpfDosPath = _gpfNodePath.sep === "\\";
_gpfMainContext = global;
/*#ifndef(UMD)*/
/*eslint-disable no-sync*/ // Simpler this way
_gpfNodeFs = require("fs");
_gpfSyncReadForBoot = function (srcFileName) {
return _gpfNodeFs.readFileSync(srcFileName).toString();
};
/*#endif*/
// Browser
/* istanbul ignore else */ // unknown.1
} else if ("undefined" !== typeof window) {
_gpfHost = _GPF_HOST.BROWSER;
_gpfMainContext = window;
/*#ifndef(UMD)*/
_gpfSyncReadForBoot = function (srcFileName) {
var xhr = new XMLHttpRequest();
xhr.open("GET", srcFileName, false);
xhr.send();
return xhr.responseText;
};
/*#endif*/
}
/*#ifndef(UMD)*/
/**
* Loading sources occurs here for the non UMD version.
* UMD versions (debug / release) will have everything concatenated.
* @since 0.1.5
*/
// Need to create the gpf name 'manually'
_gpfMainContext.gpf = {
internals: {} // To support testable internals
};
/**
* Contains the root path of GPF sources
*
* @name gpfSourcesPath
* @type {String}
* @private
* @since 0.0.1
*/
/**
* Reads a source file (only in source mode)
*
* NOTE this method is available only when running the source version
*
* @param {String} sourceFileName Source file name (relative to src folder)
* @return {String} Source content
* @since 0.1.7
*/
function _gpfSyncReadSourceJSON (sourceFileName) {
/*jslint evil: true*/
var result;
eval("result = " + _gpfSyncReadForBoot(gpfSourcesPath + sourceFileName) + ";"); //eslint-disable-line no-eval
return result;
}
/**
* Load content of all sources
*
* @return {String} Consolidated sources
* @since 0.1.9
*/
function _gpfLoadSources () { //jshint ignore:line
/*jslint evil: true*/
var sourceListContent = _gpfSyncReadForBoot(gpfSourcesPath + "sources.json"),
_gpfSources,
allContent = [],
idx = 0,
source;
eval("_gpfSources = " + sourceListContent + ";"); //eslint-disable-line no-eval
for (; idx < _gpfSources.length; ++idx) {
source = _gpfSources[idx];
if (source.load !== false) {
allContent.push(_gpfSyncReadForBoot(gpfSourcesPath + source.name + ".js"));
}
}
return allContent.join("\r\n");
}
/*jshint ignore:start*/ // Best way I found
eval(_gpfLoadSources()); //eslint-disable-line no-eval
/*jshint ignore:end*/
/*#endif*/
/**
* Host type enumeration
*
* @enum {String}
* @readonly
* @since 0.1.5
*/
gpf.hosts = {
/**
* Any browser (phantomjs is recognized separately)
* @since 0.1.5
*/
browser: _GPF_HOST.BROWSER,
/**
* [NodeJs](http://nodejs.org/)
* @since 0.1.5
*/
nodejs: _GPF_HOST.NODEJS,
/**
* [PhantomJS](http://phantomjs.org/)
* @since 0.1.5
*/
phantomjs: _GPF_HOST.PHANTOMJS,
/**
* [Rhino](http://developer.mozilla.org/en/docs/Rhino)
* @since 0.1.5
*/
rhino: _GPF_HOST.RHINO,
/**
* Unknown (detection failed or the host is unknown)
* @since 0.1.5
*/
unknown: _GPF_HOST.UNKNOWN,
/**
* [cscript/wscript](http://technet.microsoft.com/en-us/library/bb490887.aspx)
* @since 0.1.5
*/
wscript: _GPF_HOST.WSCRIPT
};
/**
* Returns the detected host type
*
* @return {gpf.hosts} Host type
* @since 0.1.5
*/
gpf.host = function () {
return _gpfHost;
};
/**
* Returns the current version
*
* @return {String} Version
* @since 0.1.5
*/
gpf.version = function () {
return _gpfVersion;
};
|
New version (#202)
|
src/boot.js
|
New version (#202)
|
<ide><path>rc/boot.js
<ide> * GPF Version
<ide> * @since 0.1.5
<ide> */
<del> _gpfVersion = "0.2.2",
<add> _gpfVersion = "0.2.3-alpha",
<ide>
<ide> /**
<ide> * Host constants
|
|
Java
|
mit
|
1486b20a288b0c632e3228bc89cd5f2aee2611a2
| 0 |
conveyal/r5,conveyal/r5,conveyal/r5,conveyal/r5,conveyal/r5
|
package org.opentripplanner.profile;
import gnu.trove.iterator.TObjectIntIterator;
import gnu.trove.map.TObjectIntMap;
import gnu.trove.map.TObjectLongMap;
import gnu.trove.map.hash.TObjectIntHashMap;
import gnu.trove.map.hash.TObjectLongHashMap;
import org.onebusaway.gtfs.model.Route;
import org.opentripplanner.analyst.TimeSurface;
import org.opentripplanner.api.parameter.QualifiedModeSet;
import org.opentripplanner.common.model.GenericLocation;
import org.opentripplanner.routing.algorithm.AStar;
import org.opentripplanner.routing.algorithm.PathDiscardingRaptorStateStore;
import org.opentripplanner.routing.algorithm.Raptor;
import org.opentripplanner.routing.core.RoutingRequest;
import org.opentripplanner.routing.core.State;
import org.opentripplanner.routing.core.TraverseMode;
import org.opentripplanner.routing.edgetype.TripPattern;
import org.opentripplanner.routing.graph.Graph;
import org.opentripplanner.routing.graph.Vertex;
import org.opentripplanner.routing.spt.DominanceFunction;
import org.opentripplanner.routing.spt.ShortestPathTree;
import org.opentripplanner.routing.trippattern.TripTimeSubset;
import org.opentripplanner.routing.vertextype.TransitStop;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Map;
/**
* Perform profile routing using repeated RAPTOR searches.
*
* This is conceptually very similar to the work of the Minnesota Accessibility Observatory
* (http://www.its.umn.edu/Publications/ResearchReports/pdfdownloadl.pl?id=2504)
* They run repeated searches. We take advantage of the fact that the street network is static
* (for the most part, assuming time-dependent turn restrictions and traffic are consistent across the time window)
* and only run a fast transit search for each minute in the window.
*/
public class RepeatedRaptorProfileRouter {
private Logger LOG = LoggerFactory.getLogger(RepeatedRaptorProfileRouter.class);
public static final int MAX_DURATION = 60 * 60 * 2; // seconds
private static final int MAX_TRANSFERS = 20;
public ProfileRequest request;
public Graph graph;
// The spacing in minutes between RAPTOR calls within the time window
public int stepMinutes = 2;
/** Three time surfaces for min, max, and average travel time over the given time window. */
public TimeSurface.RangeSet timeSurfaceRangeSet;
/** If not null, completely skip this agency during the calculations. */
public String banAgency = null;
/** The sum of all earliest-arrival travel times to a given transit stop. Will be divided to create an average. */
TObjectLongMap<TransitStop> accumulator = new TObjectLongHashMap<TransitStop>();
/** The number of travel time observations added into the accumulator. The divisor when calculating an average. */
TObjectIntMap<TransitStop> counts = new TObjectIntHashMap<TransitStop>();
public RepeatedRaptorProfileRouter (Graph graph, ProfileRequest request) {
this.request = request;
this.graph = graph;
}
public void route () {
long computationStartTime = System.currentTimeMillis();
LOG.info("Begin profile request");
LOG.info("Finding initial stops");
TObjectIntMap<TransitStop> accessTimes = findInitialStops(false);
LOG.info("Found {} initial transit stops", accessTimes.size());
/** THIN WORKERS */
LOG.info("Make data...");
TimeWindow window = new TimeWindow(request.fromTime, request.toTime, graph.index.servicesRunning(request.date));
RaptorWorkerData raptorWorkerData = new RaptorWorkerData(graph, window);
LOG.info("Done.");
RaptorWorker worker = new RaptorWorker(raptorWorkerData);
PropagatedTimesStore propagatedTimesStore = worker.runRaptor(graph, accessTimes);
propagatedTimesStore.makeSurfaces(timeSurfaceRangeSet);
if (true) {
return;
}
/** A compacted tabular representation of all the patterns that are running on this date in this time window. */
Map<TripPattern, TripTimeSubset> timetables =
TripTimeSubset.indexGraph(graph, request.date, request.fromTime, request.toTime + MAX_DURATION);
/** If a route is banned, remove all patterns belonging to that route from the timetable. */
if (banAgency != null) {
for (Route route : graph.index.routeForId.values()) {
if (route.getAgency().getId().equals(banAgency)) {
LOG.info("Banning route {}", route);
int n = 0;
for (TripPattern pattern : graph.index.patternsForRoute.get(route)) {
timetables.remove(pattern);
n++;
}
LOG.info("Removed {} patterns.", n);
}
}
}
// Create a state store which will be reused calling RAPTOR with each departure time in reverse order.
// This causes portions of the solution that do not change to be reused and should provide some speedup
// over naively creating a new, empty state store for each minute.
PathDiscardingRaptorStateStore rss = new PathDiscardingRaptorStateStore(MAX_TRANSFERS * 2 + 1);
// Summary stats across all minutes of the time window
PropagatedTimesStore windowSummary = new PropagatedTimesStore(graph);
// PropagatedHistogramsStore windowHistograms = new PropagatedHistogramsStore(90);
/** Iterate over all minutes in the time window, running a RAPTOR search at each minute. */
for (int i = 0, departureTime = request.toTime - 60 * stepMinutes;
departureTime >= request.fromTime;
departureTime -= 60 * stepMinutes) {
// Log progress every N iterations
if (++i % 5 == 0) {
LOG.info("Completed {} RAPTOR searches", i);
}
// The departure time has changed; adjust the maximum clock time that the state store will retain
rss.maxTime = departureTime + MAX_DURATION;
// Reset the counter. This is important if reusing the state store from one call to the next.
rss.restart();
// Find the arrival times at the initial transit stops
for (TObjectIntIterator<TransitStop> it = accessTimes.iterator(); it.hasNext();) {
it.advance();
rss.put(it.key(), departureTime + it.value(), true); // store walk times for reachable transit stops
}
// Call the RAPTOR algorithm for this particular departure time
Raptor raptor = new Raptor(graph, MAX_TRANSFERS, request.walkSpeed, rss, departureTime, request.date, timetables);
raptor.run();
// Propagate minimum travel times out to vertices in the street network
StopTreeCache stopTreeCache = graph.index.getStopTreeCache();
TObjectIntIterator<TransitStop> resultIterator = raptor.iterator();
int[] minsPerVertex = new int[Vertex.getMaxIndex()];
while (resultIterator.hasNext()) {
resultIterator.advance();
TransitStop transitStop = resultIterator.key();
int arrivalTime = resultIterator.value();
if (arrivalTime == Integer.MAX_VALUE) continue; // stop was not reached in this round (why was it included in map?)
int elapsedTime = arrivalTime - departureTime;
stopTreeCache.propagateStop(transitStop, elapsedTime, request.walkSpeed, minsPerVertex);
}
// We now have the minimum travel times to reach each street vertex for this departure minute.
// Accumulate them into the summary statistics for the entire time window.
windowSummary.mergeIn(minsPerVertex);
// The Holy Grail: histograms per street vertex. It actually seems as fast or faster than summary stats.
// windowHistograms.mergeIn(minsPerVertex);
}
LOG.info("Profile request complete, creating time surfaces.");
windowSummary.makeSurfaces(timeSurfaceRangeSet);
LOG.info("Profile request finished in {} seconds", (System.currentTimeMillis() - computationStartTime) / 1000.0);
}
/** find the boarding stops */
private TObjectIntMap<TransitStop> findInitialStops(boolean dest) {
double lat = dest ? request.toLat : request.fromLat;
double lon = dest ? request.toLon : request.fromLon;
QualifiedModeSet modes = dest ? request.accessModes : request.egressModes;
RoutingRequest rr = new RoutingRequest(TraverseMode.WALK);
rr.dominanceFunction = new DominanceFunction.EarliestArrival();
rr.batch = true;
rr.from = new GenericLocation(lat, lon);
rr.walkSpeed = request.walkSpeed;
rr.to = rr.from;
rr.setRoutingContext(graph);
// RoutingRequest dateTime defaults to currentTime.
// If elapsed time is not capped, searches are very slow.
rr.worstTime = (rr.dateTime + request.maxWalkTime * 60);
AStar astar = new AStar();
rr.longDistance = true;
rr.setNumItineraries(1);
// Set a path parser to avoid strange edge sequences.
// TODO choose a path parser that actually works here, or reuse nearbyStopFinder!
//rr.rctx.pathParsers = new PathParser[] { new BasicPathParser() };
ShortestPathTree spt = astar.getShortestPathTree(rr, 5); // timeout in seconds
TObjectIntMap<TransitStop> accessTimes = new TObjectIntHashMap<TransitStop>();
for (TransitStop tstop : graph.index.stopVertexForStop.values()) {
State s = spt.getState(tstop);
if (s != null) {
accessTimes.put(tstop, (int) s.getElapsedTimeSeconds());
}
}
// Initialize time surfaces (which will hold the final results) using the on-street search parameters
timeSurfaceRangeSet = new TimeSurface.RangeSet();
timeSurfaceRangeSet.min = new TimeSurface(spt, false);
timeSurfaceRangeSet.max = new TimeSurface(spt, false);
timeSurfaceRangeSet.avg = new TimeSurface(spt, false);
rr.cleanup();
return accessTimes;
}
}
|
src/main/java/org/opentripplanner/profile/RepeatedRaptorProfileRouter.java
|
package org.opentripplanner.profile;
import gnu.trove.iterator.TObjectIntIterator;
import gnu.trove.map.TObjectIntMap;
import gnu.trove.map.TObjectLongMap;
import gnu.trove.map.hash.TObjectIntHashMap;
import gnu.trove.map.hash.TObjectLongHashMap;
import org.onebusaway.gtfs.model.Route;
import org.opentripplanner.analyst.TimeSurface;
import org.opentripplanner.api.parameter.QualifiedModeSet;
import org.opentripplanner.common.model.GenericLocation;
import org.opentripplanner.routing.algorithm.AStar;
import org.opentripplanner.routing.algorithm.PathDiscardingRaptorStateStore;
import org.opentripplanner.routing.algorithm.Raptor;
import org.opentripplanner.routing.core.RoutingRequest;
import org.opentripplanner.routing.core.State;
import org.opentripplanner.routing.core.TraverseMode;
import org.opentripplanner.routing.edgetype.TripPattern;
import org.opentripplanner.routing.graph.Graph;
import org.opentripplanner.routing.graph.Vertex;
import org.opentripplanner.routing.spt.DominanceFunction;
import org.opentripplanner.routing.spt.ShortestPathTree;
import org.opentripplanner.routing.trippattern.TripTimeSubset;
import org.opentripplanner.routing.vertextype.TransitStop;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Map;
/**
* Perform profile routing using repeated RAPTOR searches.
*
* This is conceptually very similar to the work of the Minnesota Accessibility Observatory
* (http://www.its.umn.edu/Publications/ResearchReports/pdfdownloadl.pl?id=2504)
* They run repeated searches. We take advantage of the fact that the street network is static
* (for the most part, assuming time-dependent turn restrictions and traffic are consistent across the time window)
* and only run a fast transit search for each minute in the window.
*/
public class RepeatedRaptorProfileRouter {
private Logger LOG = LoggerFactory.getLogger(RepeatedRaptorProfileRouter.class);
public static final int MAX_DURATION = 60 * 60 * 2; // seconds
private static final int MAX_TRANSFERS = 20;
public ProfileRequest request;
public Graph graph;
// The spacing in minutes between RAPTOR calls within the time window
public int stepMinutes = 2;
/** Three time surfaces for min, max, and average travel time over the given time window. */
public TimeSurface.RangeSet timeSurfaceRangeSet;
/** If not null, completely skip this agency during the calculations. */
public String banAgency = null;
/** The sum of all earliest-arrival travel times to a given transit stop. Will be divided to create an average. */
TObjectLongMap<TransitStop> accumulator = new TObjectLongHashMap<TransitStop>();
/** The number of travel time observations added into the accumulator. The divisor when calculating an average. */
TObjectIntMap<TransitStop> counts = new TObjectIntHashMap<TransitStop>();
public RepeatedRaptorProfileRouter (Graph graph, ProfileRequest request) {
this.request = request;
this.graph = graph;
}
public void route () {
long computationStartTime = System.currentTimeMillis();
LOG.info("Begin profile request");
LOG.info("Finding initial stops");
TObjectIntMap<TransitStop> accessTimes = findInitialStops(false);
LOG.info("Found {} initial transit stops", accessTimes.size());
/** THIN WORKERS */
LOG.info("Make data...", accessTimes.size());
TimeWindow window = new TimeWindow(request.fromTime, request.toTime, graph.index.servicesRunning(request.date));
RaptorWorkerData raptorWorkerData = new RaptorWorkerData(graph, window);
try {
LOG.info("begin write");
FileOutputStream fileOut = new FileOutputStream("/Users/abyrd/worker.obj");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(raptorWorkerData);
out.close();
fileOut.close();
LOG.info("begin read");
FileInputStream fileIn = new FileInputStream("/Users/abyrd/worker.obj");
ObjectInputStream oin = new ObjectInputStream(fileIn);
RaptorWorkerData dummy = (RaptorWorkerData) oin.readObject();
oin.close();
fileIn.close();
LOG.info("end read.");
} catch (Exception ex) {
ex.printStackTrace();
}
LOG.info("Done.", accessTimes.size());
RaptorWorker worker = new RaptorWorker(raptorWorkerData);
PropagatedTimesStore propagatedTimesStore = worker.runRaptor(graph, accessTimes);
propagatedTimesStore.makeSurfaces(timeSurfaceRangeSet);
if (true) {
return;
}
/** A compacted tabular representation of all the patterns that are running on this date in this time window. */
Map<TripPattern, TripTimeSubset> timetables =
TripTimeSubset.indexGraph(graph, request.date, request.fromTime, request.toTime + MAX_DURATION);
/** If a route is banned, remove all patterns belonging to that route from the timetable. */
if (banAgency != null) {
for (Route route : graph.index.routeForId.values()) {
if (route.getAgency().getId().equals(banAgency)) {
LOG.info("Banning route {}", route);
int n = 0;
for (TripPattern pattern : graph.index.patternsForRoute.get(route)) {
timetables.remove(pattern);
n++;
}
LOG.info("Removed {} patterns.", n);
}
}
}
// Create a state store which will be reused calling RAPTOR with each departure time in reverse order.
// This causes portions of the solution that do not change to be reused and should provide some speedup
// over naively creating a new, empty state store for each minute.
PathDiscardingRaptorStateStore rss = new PathDiscardingRaptorStateStore(MAX_TRANSFERS * 2 + 1);
// Summary stats across all minutes of the time window
PropagatedTimesStore windowSummary = new PropagatedTimesStore(graph);
// PropagatedHistogramsStore windowHistograms = new PropagatedHistogramsStore(90);
/** Iterate over all minutes in the time window, running a RAPTOR search at each minute. */
for (int i = 0, departureTime = request.toTime - 60 * stepMinutes;
departureTime >= request.fromTime;
departureTime -= 60 * stepMinutes) {
// Log progress every N iterations
if (++i % 5 == 0) {
LOG.info("Completed {} RAPTOR searches", i);
}
// The departure time has changed; adjust the maximum clock time that the state store will retain
rss.maxTime = departureTime + MAX_DURATION;
// Reset the counter. This is important if reusing the state store from one call to the next.
rss.restart();
// Find the arrival times at the initial transit stops
for (TObjectIntIterator<TransitStop> it = accessTimes.iterator(); it.hasNext();) {
it.advance();
rss.put(it.key(), departureTime + it.value(), true); // store walk times for reachable transit stops
}
// Call the RAPTOR algorithm for this particular departure time
Raptor raptor = new Raptor(graph, MAX_TRANSFERS, request.walkSpeed, rss, departureTime, request.date, timetables);
raptor.run();
// Propagate minimum travel times out to vertices in the street network
StopTreeCache stopTreeCache = graph.index.getStopTreeCache();
TObjectIntIterator<TransitStop> resultIterator = raptor.iterator();
int[] minsPerVertex = new int[Vertex.getMaxIndex()];
while (resultIterator.hasNext()) {
resultIterator.advance();
TransitStop transitStop = resultIterator.key();
int arrivalTime = resultIterator.value();
if (arrivalTime == Integer.MAX_VALUE) continue; // stop was not reached in this round (why was it included in map?)
int elapsedTime = arrivalTime - departureTime;
stopTreeCache.propagateStop(transitStop, elapsedTime, request.walkSpeed, minsPerVertex);
}
// We now have the minimum travel times to reach each street vertex for this departure minute.
// Accumulate them into the summary statistics for the entire time window.
windowSummary.mergeIn(minsPerVertex);
// The Holy Grail: histograms per street vertex. It actually seems as fast or faster than summary stats.
// windowHistograms.mergeIn(minsPerVertex);
}
LOG.info("Profile request complete, creating time surfaces.");
windowSummary.makeSurfaces(timeSurfaceRangeSet);
LOG.info("Profile request finished in {} seconds", (System.currentTimeMillis() - computationStartTime) / 1000.0);
}
/** find the boarding stops */
private TObjectIntMap<TransitStop> findInitialStops(boolean dest) {
double lat = dest ? request.toLat : request.fromLat;
double lon = dest ? request.toLon : request.fromLon;
QualifiedModeSet modes = dest ? request.accessModes : request.egressModes;
RoutingRequest rr = new RoutingRequest(TraverseMode.WALK);
rr.dominanceFunction = new DominanceFunction.EarliestArrival();
rr.batch = true;
rr.from = new GenericLocation(lat, lon);
rr.walkSpeed = request.walkSpeed;
rr.to = rr.from;
rr.setRoutingContext(graph);
// RoutingRequest dateTime defaults to currentTime.
// If elapsed time is not capped, searches are very slow.
rr.worstTime = (rr.dateTime + request.maxWalkTime * 60);
AStar astar = new AStar();
rr.longDistance = true;
rr.setNumItineraries(1);
// Set a path parser to avoid strange edge sequences.
// TODO choose a path parser that actually works here, or reuse nearbyStopFinder!
//rr.rctx.pathParsers = new PathParser[] { new BasicPathParser() };
ShortestPathTree spt = astar.getShortestPathTree(rr, 5); // timeout in seconds
TObjectIntMap<TransitStop> accessTimes = new TObjectIntHashMap<TransitStop>();
for (TransitStop tstop : graph.index.stopVertexForStop.values()) {
State s = spt.getState(tstop);
if (s != null) {
accessTimes.put(tstop, (int) s.getElapsedTimeSeconds());
}
}
// Initialize time surfaces (which will hold the final results) using the on-street search parameters
timeSurfaceRangeSet = new TimeSurface.RangeSet();
timeSurfaceRangeSet.min = new TimeSurface(spt, false);
timeSurfaceRangeSet.max = new TimeSurface(spt, false);
timeSurfaceRangeSet.avg = new TimeSurface(spt, false);
rr.cleanup();
return accessTimes;
}
}
|
fix logging
Former-commit-id: b86776e742fa549a370cc71ef4907935c1e3c208
|
src/main/java/org/opentripplanner/profile/RepeatedRaptorProfileRouter.java
|
fix logging
|
<ide><path>rc/main/java/org/opentripplanner/profile/RepeatedRaptorProfileRouter.java
<ide> import org.slf4j.Logger;
<ide> import org.slf4j.LoggerFactory;
<ide>
<del>import java.io.FileInputStream;
<del>import java.io.FileOutputStream;
<del>import java.io.ObjectInputStream;
<del>import java.io.ObjectOutputStream;
<ide> import java.util.Map;
<ide>
<ide> /**
<ide> LOG.info("Found {} initial transit stops", accessTimes.size());
<ide>
<ide> /** THIN WORKERS */
<del> LOG.info("Make data...", accessTimes.size());
<add> LOG.info("Make data...");
<ide> TimeWindow window = new TimeWindow(request.fromTime, request.toTime, graph.index.servicesRunning(request.date));
<ide> RaptorWorkerData raptorWorkerData = new RaptorWorkerData(graph, window);
<del> try {
<del> LOG.info("begin write");
<del> FileOutputStream fileOut = new FileOutputStream("/Users/abyrd/worker.obj");
<del> ObjectOutputStream out = new ObjectOutputStream(fileOut);
<del> out.writeObject(raptorWorkerData);
<del> out.close();
<del> fileOut.close();
<del> LOG.info("begin read");
<del> FileInputStream fileIn = new FileInputStream("/Users/abyrd/worker.obj");
<del> ObjectInputStream oin = new ObjectInputStream(fileIn);
<del> RaptorWorkerData dummy = (RaptorWorkerData) oin.readObject();
<del> oin.close();
<del> fileIn.close();
<del> LOG.info("end read.");
<del> } catch (Exception ex) {
<del> ex.printStackTrace();
<del> }
<del> LOG.info("Done.", accessTimes.size());
<add> LOG.info("Done.");
<ide>
<ide> RaptorWorker worker = new RaptorWorker(raptorWorkerData);
<ide> PropagatedTimesStore propagatedTimesStore = worker.runRaptor(graph, accessTimes);
|
|
Java
|
apache-2.0
|
c029b6edeb92a96ed6bc2725744dac267907b79d
| 0 |
jahlborn/sqlbuilder,jahlborn/sqlbuilder
|
/*
Copyright (c) 2008 Health Market Science, Inc.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
USA
You can contact Health Market Science at [email protected]
or at the following address:
Health Market Science
2700 Horizon Drive
Suite 200
King of Prussia, PA 19406
*/
package com.healthmarketscience.sqlbuilder;
import java.io.IOException;
import com.healthmarketscience.common.util.AppendableExt;
/**
* Outputs the given query surrounded by parentheses
* <code>"(<query>)"</code>, useful for embedding one query within
* another.
*
* @author James Ahlborn
*/
public class Subquery extends Expression
{
private SqlObject _query;
/**
* {@code Object} -> {@code SqlObject} conversions handled by
* {@link Converter#toCustomSqlObject(Object)}.
*/
public Subquery(Object query) {
_query = ((query != null) ? Converter.toCustomSqlObject(query) :
null);
}
@Override
public boolean isEmpty() {
return _query == null;
}
@Override
protected void collectSchemaObjects(ValidationContext vContext) {
// we do not collect into the subquery if this a "local only" collection
if((_query != null) && (!vContext.isLocalOnly())) {
// subqueries need a nested validation context because their schema
// objects *do not* affect the outer query, but the outer query's
// schema objects *do* affect their query
_query.collectSchemaObjects(new ValidationContext(vContext));
}
}
@Override
public void appendTo(AppendableExt app) throws IOException {
appendCustomIfNotNull(app, _query);
}
}
|
src/main/java/com/healthmarketscience/sqlbuilder/Subquery.java
|
/*
Copyright (c) 2008 Health Market Science, Inc.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
USA
You can contact Health Market Science at [email protected]
or at the following address:
Health Market Science
2700 Horizon Drive
Suite 200
King of Prussia, PA 19406
*/
package com.healthmarketscience.sqlbuilder;
import java.io.IOException;
import com.healthmarketscience.common.util.AppendableExt;
/**
* Outputs the given query surrounded by parentheses
* <code>"(<query>)"</code>, useful for embedding one query within
* another.
*
* @author James Ahlborn
*/
public class Subquery extends Expression
{
private SqlObject _query;
/**
* {@code Object} -> {@code SqlObject} conversions handled by
* {@link Converter#toCustomSqlObject(Object)}.
*/
public Subquery(Object query) {
_query = ((query != null) ? Converter.toCustomSqlObject(query) :
null);
}
@Override
public boolean isEmpty() {
return _query != null;
}
@Override
protected void collectSchemaObjects(ValidationContext vContext) {
// we do not collect into the subquery if this a "local only" collection
if((_query != null) && (!vContext.isLocalOnly())) {
// subqueries need a nested validation context because their schema
// objects *do not* affect the outer query, but the outer query's
// schema objects *do* affect their query
_query.collectSchemaObjects(new ValidationContext(vContext));
}
}
@Override
public void appendTo(AppendableExt app) throws IOException {
appendCustomIfNotNull(app, _query);
}
}
|
fix isEmpty for SubQuery
git-svn-id: d7f6d3fc66399c4a8ff072a18ddf9297da8786ca@242 f9ba57bc-9804-47c6-9de9-2f2ff8aac994
|
src/main/java/com/healthmarketscience/sqlbuilder/Subquery.java
|
fix isEmpty for SubQuery
|
<ide><path>rc/main/java/com/healthmarketscience/sqlbuilder/Subquery.java
<ide>
<ide> @Override
<ide> public boolean isEmpty() {
<del> return _query != null;
<add> return _query == null;
<ide> }
<ide>
<ide> @Override
|
|
Java
|
lgpl-2.1
|
75a57d79ea14e570290aa10f774372855eb7bb68
| 0 |
juanmjacobs/kettle,cwarden/kettle,juanmjacobs/kettle,juanmjacobs/kettle,cwarden/kettle,cwarden/kettle
|
/* Copyright (c) 2007 Pentaho Corporation. All rights reserved.
* This software was developed by Pentaho Corporation and is provided under the terms
* of the GNU Lesser General Public License, Version 2.1. You may not use
* this file except in compliance with the license. If you need a copy of the license,
* please go to http://www.gnu.org/licenses/lgpl-2.1.txt. The Original Code is Pentaho
* Data Integration. The Initial Developer is Pentaho Corporation.
*
* Software distributed under the GNU Lesser Public License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. Please refer to
* the license for the specific language governing your rights and limitations.*/
/*
* Created on 18-mei-2003
*
*/
package org.pentaho.di.ui.trans.steps.mapping;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.vfs.FileObject;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CTabFolder;
import org.eclipse.swt.custom.CTabFolder2Adapter;
import org.eclipse.swt.custom.CTabFolderEvent;
import org.eclipse.swt.custom.CTabItem;
import org.eclipse.swt.events.FocusAdapter;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.ShellAdapter;
import org.eclipse.swt.events.ShellEvent;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.Props;
import org.pentaho.di.core.SourceToTargetMapping;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.gui.SpoonFactory;
import org.pentaho.di.core.gui.SpoonInterface;
import org.pentaho.di.core.row.RowMetaInterface;
import org.pentaho.di.core.vfs.KettleVFS;
import org.pentaho.di.repository.RepositoryDirectory;
import org.pentaho.di.trans.TransMeta;
import org.pentaho.di.trans.step.BaseStepMeta;
import org.pentaho.di.trans.step.StepDialogInterface;
import org.pentaho.di.trans.step.StepMeta;
import org.pentaho.di.trans.steps.mapping.MappingIODefinition;
import org.pentaho.di.trans.steps.mapping.MappingMeta;
import org.pentaho.di.trans.steps.mapping.MappingParameters;
import org.pentaho.di.trans.steps.mapping.MappingValueRename;
import org.pentaho.di.trans.steps.mapping.Messages;
import org.pentaho.di.ui.core.dialog.EnterMappingDialog;
import org.pentaho.di.ui.core.dialog.EnterSelectionDialog;
import org.pentaho.di.ui.core.dialog.ErrorDialog;
import org.pentaho.di.ui.core.widget.ColumnInfo;
import org.pentaho.di.ui.core.widget.TableView;
import org.pentaho.di.ui.core.widget.TextVar;
import org.pentaho.di.ui.repository.dialog.SelectObjectDialog;
import org.pentaho.di.ui.trans.step.BaseStepDialog;
import org.pentaho.vfs.ui.VfsFileChooserDialog;
public class MappingDialog extends BaseStepDialog implements StepDialogInterface
{
private MappingMeta mappingMeta;
private Group gTransGroup;
// File
private Button wFileRadio;
private Button wbbFilename; // Browse: add file or directory
private TextVar wFilename;
// Repository
private Button wRepRadio;
private TextVar wTransName, wTransDir;
private Button wbTrans;
private Button wEditTrans;
private CTabFolder wTabFolder;
TransMeta mappingTransMeta = null;
protected boolean transModified;
private ModifyListener lsMod;
private int middle;
private int margin;
private MappingParameters mappingParameters;
private List<MappingIODefinition> inputMappings;
private List<MappingIODefinition> outputMappings;
private Button wAddInput;
private Button wAddOutput;
private interface ApplyChanges
{
public void applyChanges();
}
private class MappingParametersTab implements ApplyChanges
{
private TableView wMappingParameters;
private MappingParameters parameters;
public MappingParametersTab(TableView wMappingParameters, MappingParameters parameters)
{
this.wMappingParameters = wMappingParameters;
this.parameters = parameters;
}
public void applyChanges()
{
int nrLines = wMappingParameters.nrNonEmpty();
String variables[] = new String[nrLines];
String inputFields[] = new String[nrLines];
parameters.setVariable(variables);
parameters.setInputField(inputFields);
for (int i = 0; i < nrLines; i++)
{
TableItem item = wMappingParameters.getNonEmpty(i);
parameters.getVariable()[i] = item.getText(1);
parameters.getInputField()[i] = item.getText(2);
}
}
}
private class MappingDefinitionTab implements ApplyChanges
{
private MappingIODefinition definition;
private Text wInputStep;
private Text wOutputStep;
private Button wMainPath;
private Text wDescription;
private TableView wFieldMappings;
public MappingDefinitionTab(MappingIODefinition definition, Text inputStep, Text outputStep,
Button mainPath, Text description, TableView fieldMappings)
{
super();
this.definition = definition;
wInputStep = inputStep;
wOutputStep = outputStep;
wMainPath = mainPath;
wDescription = description;
wFieldMappings = fieldMappings;
}
public void applyChanges()
{
// The input step
definition.setInputStepname(wInputStep.getText());
// The output step
definition.setOutputStepname(wOutputStep.getText());
// The description
definition.setDescription(wDescription.getText());
// The main path flag
definition.setMainDataPath(wMainPath.getSelection());
// The grid
//
int nrLines = wFieldMappings.nrNonEmpty();
definition.getValueRenames().clear();
for (int i = 0; i < nrLines; i++)
{
TableItem item = wFieldMappings.getNonEmpty(i);
definition.getValueRenames().add(new MappingValueRename(item.getText(1), item.getText(2)));
}
}
}
private List<ApplyChanges> changeList;
public MappingDialog(Shell parent, Object in, TransMeta tr, String sname)
{
super(parent, (BaseStepMeta) in, tr, sname);
mappingMeta = (MappingMeta) in;
transModified = false;
// Make a copy for our own purposes...
// This allows us to change everything directly in the classes with
// listeners.
// Later we need to copy it to the input class on ok()
//
mappingParameters = (MappingParameters) mappingMeta.getMappingParameters().clone();
inputMappings = new ArrayList<MappingIODefinition>();
outputMappings = new ArrayList<MappingIODefinition>();
for (int i = 0; i < mappingMeta.getInputMappings().size(); i++)
inputMappings.add((MappingIODefinition) mappingMeta.getInputMappings().get(i).clone());
for (int i = 0; i < mappingMeta.getOutputMappings().size(); i++)
outputMappings.add((MappingIODefinition) mappingMeta.getOutputMappings().get(i).clone());
changeList = new ArrayList<ApplyChanges>();
}
public String open()
{
Shell parent = getParent();
Display display = parent.getDisplay();
shell = new Shell(parent, SWT.DIALOG_TRIM | SWT.RESIZE | SWT.MIN | SWT.MAX);
props.setLook(shell);
setShellImage(shell, mappingMeta);
lsMod = new ModifyListener()
{
public void modifyText(ModifyEvent e)
{
mappingMeta.setChanged();
}
};
changed = mappingMeta.hasChanged();
FormLayout formLayout = new FormLayout();
formLayout.marginWidth = Const.FORM_MARGIN;
formLayout.marginHeight = Const.FORM_MARGIN;
shell.setLayout(formLayout);
shell.setText(Messages.getString("MappingDialog.Shell.Title")); //$NON-NLS-1$
middle = props.getMiddlePct();
margin = Const.MARGIN;
// Stepname line
wlStepname = new Label(shell, SWT.RIGHT);
wlStepname.setText(Messages.getString("MappingDialog.Stepname.Label")); //$NON-NLS-1$
props.setLook(wlStepname);
fdlStepname = new FormData();
fdlStepname.left = new FormAttachment(0, 0);
fdlStepname.right = new FormAttachment(middle, -margin);
fdlStepname.top = new FormAttachment(0, margin);
wlStepname.setLayoutData(fdlStepname);
wStepname = new Text(shell, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
wStepname.setText(stepname);
props.setLook(wStepname);
wStepname.addModifyListener(lsMod);
fdStepname = new FormData();
fdStepname.left = new FormAttachment(middle, 0);
fdStepname.top = new FormAttachment(0, margin);
fdStepname.right = new FormAttachment(100, 0);
wStepname.setLayoutData(fdStepname);
// Show a group with 2 main options: a transformation in the repository
// or on file
//
// //////////////////////////////////////////////////
// The key creation box
// //////////////////////////////////////////////////
//
gTransGroup = new Group(shell, SWT.SHADOW_ETCHED_IN);
gTransGroup.setText(Messages.getString("MappingDialog.TransGroup.Label")); //$NON-NLS-1$;
gTransGroup.setBackground(shell.getBackground()); // the default looks
// ugly
FormLayout transGroupLayout = new FormLayout();
transGroupLayout.marginLeft = margin * 2;
transGroupLayout.marginTop = margin * 2;
transGroupLayout.marginRight = margin * 2;
transGroupLayout.marginBottom = margin * 2;
gTransGroup.setLayout(transGroupLayout);
// Radio button: The mapping is in a file
//
wFileRadio = new Button(gTransGroup, SWT.RADIO);
props.setLook(wFileRadio);
wFileRadio.setSelection(false);
wFileRadio.setText(Messages.getString("MappingDialog.RadioFile.Label")); //$NON-NLS-1$
wFileRadio.setToolTipText(Messages.getString("MappingDialog.RadioFile.Tooltip", Const.CR)); //$NON-NLS-1$ //$NON-NLS-2$
FormData fdFileRadio = new FormData();
fdFileRadio.left = new FormAttachment(0, 0);
fdFileRadio.right = new FormAttachment(100, 0);
fdFileRadio.top = new FormAttachment(0, 0);
wFileRadio.setLayoutData(fdFileRadio);
wbbFilename = new Button(gTransGroup, SWT.PUSH | SWT.CENTER); // Browse
props.setLook(wbbFilename);
wbbFilename.setText(Messages.getString("System.Button.Browse"));
wbbFilename.setToolTipText(Messages.getString("System.Tooltip.BrowseForFileOrDirAndAdd"));
FormData fdbFilename = new FormData();
fdbFilename.right = new FormAttachment(100, 0);
fdbFilename.top = new FormAttachment(wFileRadio, margin);
wbbFilename.setLayoutData(fdbFilename);
wbbFilename.addSelectionListener(new SelectionAdapter()
{
public void widgetSelected(SelectionEvent e)
{
selectFileTrans();
}
});
wFilename = new TextVar(transMeta, gTransGroup, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wFilename);
wFilename.addModifyListener(lsMod);
FormData fdFilename = new FormData();
fdFilename.left = new FormAttachment(0, 25);
fdFilename.right = new FormAttachment(wbbFilename, -margin);
fdFilename.top = new FormAttachment(wbbFilename, 0, SWT.CENTER);
wFilename.setLayoutData(fdFilename);
wFilename.addModifyListener(new ModifyListener()
{
public void modifyText(ModifyEvent e)
{
wFileRadio.setSelection(true);
wRepRadio.setSelection(false);
}
});
// Radio button: The mapping is in the repository
//
wRepRadio = new Button(gTransGroup, SWT.RADIO);
props.setLook(wRepRadio);
wRepRadio.setSelection(false);
wRepRadio.setText(Messages.getString("MappingDialog.RadioRep.Label")); //$NON-NLS-1$
wRepRadio.setToolTipText(Messages.getString("MappingDialog.RadioRep.Tooltip", Const.CR)); //$NON-NLS-1$ //$NON-NLS-2$
FormData fdRepRadio = new FormData();
fdRepRadio.left = new FormAttachment(0, 0);
fdRepRadio.right = new FormAttachment(100, 0);
fdRepRadio.top = new FormAttachment(wbbFilename, 2 * margin);
wRepRadio.setLayoutData(fdRepRadio);
wbTrans = new Button(gTransGroup, SWT.PUSH | SWT.CENTER); // Browse
props.setLook(wbTrans);
wbTrans.setText(Messages.getString("MappingDialog.Select.Button"));
wbTrans.setToolTipText(Messages.getString("System.Tooltip.BrowseForFileOrDirAndAdd"));
FormData fdbTrans = new FormData();
fdbTrans.right = new FormAttachment(100, 0);
fdbTrans.top = new FormAttachment(wRepRadio, 2 * margin);
wbTrans.setLayoutData(fdbTrans);
wbTrans.addSelectionListener(new SelectionAdapter()
{
public void widgetSelected(SelectionEvent e)
{
selectRepositoryTrans();
}
});
wTransDir = new TextVar(transMeta, gTransGroup, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wTransDir);
wTransDir.addModifyListener(lsMod);
FormData fdTransDir = new FormData();
fdTransDir.left = new FormAttachment(middle + (100 - middle) / 2, 0);
fdTransDir.right = new FormAttachment(wbTrans, -margin);
fdTransDir.top = new FormAttachment(wbTrans, 0, SWT.CENTER);
wTransDir.setLayoutData(fdTransDir);
wTransName = new TextVar(transMeta, gTransGroup, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wTransName);
wTransName.addModifyListener(lsMod);
FormData fdTransName = new FormData();
fdTransName.left = new FormAttachment(0, 25);
fdTransName.right = new FormAttachment(wTransDir, -margin);
fdTransName.top = new FormAttachment(wbTrans, 0, SWT.CENTER);
wTransName.setLayoutData(fdTransName);
wEditTrans = new Button(gTransGroup, SWT.PUSH | SWT.CENTER); // Browse
props.setLook(wEditTrans);
wEditTrans.setText(Messages.getString("MappingDialog.Edit.Button"));
wEditTrans.setToolTipText(Messages.getString("System.Tooltip.BrowseForFileOrDirAndAdd"));
FormData fdEditTrans = new FormData();
fdEditTrans.left = new FormAttachment(0, 0);
fdEditTrans.right = new FormAttachment(100, 0);
fdEditTrans.top = new FormAttachment(wTransName, 3 * margin);
wEditTrans.setLayoutData(fdEditTrans);
wEditTrans.addSelectionListener(new SelectionAdapter()
{
public void widgetSelected(SelectionEvent e)
{
editTrans();
}
});
FormData fdTransGroup = new FormData();
fdTransGroup.left = new FormAttachment(0, 0);
fdTransGroup.top = new FormAttachment(wStepname, 2 * margin);
fdTransGroup.right = new FormAttachment(100, 0);
// fdTransGroup.bottom = new FormAttachment(wStepname, 350);
gTransGroup.setLayoutData(fdTransGroup);
//
// Add a tab folder for the parameters and various input and output
// streams
//
wTabFolder = new CTabFolder(shell, SWT.BORDER);
props.setLook(wTabFolder, Props.WIDGET_STYLE_TAB);
wTabFolder.setSimple(false);
wTabFolder.setUnselectedCloseVisible(true);
FormData fdTabFolder = new FormData();
fdTabFolder.left = new FormAttachment(0, 0);
fdTabFolder.right = new FormAttachment(100, 0);
fdTabFolder.top = new FormAttachment(gTransGroup, margin * 2);
fdTabFolder.bottom = new FormAttachment(100, -75);
wTabFolder.setLayoutData(fdTabFolder);
// Now add buttons that will allow us to add or remove input or output
// tabs...
wAddInput = new Button(shell, SWT.PUSH);
props.setLook(wAddInput);
wAddInput.setText(Messages.getString("MappingDialog.button.AddInput"));
wAddInput.addSelectionListener(new SelectionAdapter()
{
@Override
public void widgetSelected(SelectionEvent event)
{
// Simply add a new MappingIODefinition object to the
// inputMappings
MappingIODefinition definition = new MappingIODefinition();
inputMappings.add(definition);
int index = inputMappings.size() - 1;
addInputMappingDefinitionTab(definition, index);
}
});
wAddOutput = new Button(shell, SWT.PUSH);
props.setLook(wAddOutput);
wAddOutput.setText(Messages.getString("MappingDialog.button.AddOutput"));
wAddOutput.addSelectionListener(new SelectionAdapter()
{
@Override
public void widgetSelected(SelectionEvent event)
{
// Simply add a new MappingIODefinition object to the
// inputMappings
MappingIODefinition definition = new MappingIODefinition();
outputMappings.add(definition);
int index = outputMappings.size() - 1;
addOutputMappingDefinitionTab(definition, index);
}
});
setButtonPositions(new Button[] { wAddInput, wAddOutput }, margin, wTabFolder);
// Some buttons
wOK = new Button(shell, SWT.PUSH);
wOK.setText(Messages.getString("System.Button.OK")); //$NON-NLS-1$
wCancel = new Button(shell, SWT.PUSH);
wCancel.setText(Messages.getString("System.Button.Cancel")); //$NON-NLS-1$
setButtonPositions(new Button[] { wOK, wCancel }, margin, null);
// Add listeners
lsCancel = new Listener()
{
public void handleEvent(Event e)
{
cancel();
}
};
lsOK = new Listener()
{
public void handleEvent(Event e)
{
ok();
}
};
wCancel.addListener(SWT.Selection, lsCancel);
wOK.addListener(SWT.Selection, lsOK);
lsDef = new SelectionAdapter()
{
public void widgetDefaultSelected(SelectionEvent e)
{
ok();
}
};
wStepname.addSelectionListener(lsDef);
// Detect X or ALT-F4 or something that kills this window...
shell.addShellListener(new ShellAdapter()
{
public void shellClosed(ShellEvent e)
{
cancel();
}
});
// Set the shell size, based upon previous time...
setSize();
getData();
mappingMeta.setChanged(changed);
wTabFolder.setSelection(0);
shell.open();
while (!shell.isDisposed())
{
if (!display.readAndDispatch())
display.sleep();
}
return stepname;
}
private void selectRepositoryTrans()
{
try
{
SelectObjectDialog sod = new SelectObjectDialog(shell, repository);
String transName = sod.open();
RepositoryDirectory repdir = sod.getDirectory();
if (transName != null && repdir != null)
{
loadRepositoryTrans(transName, repdir);
wTransName.setText(mappingTransMeta.getName());
wTransDir.setText(mappingTransMeta.getDirectory().getPath());
wFilename.setText("");
wRepRadio.setSelection(true);
wFileRadio.setSelection(false);
}
} catch (KettleException ke)
{
new ErrorDialog(
shell,
Messages.getString("MappingDialog.ErrorSelectingObject.DialogTitle"), Messages.getString("MappingDialog.ErrorSelectingObject.DialogMessage"), ke); //$NON-NLS-1$ //$NON-NLS-2$
}
}
private void loadRepositoryTrans(String transName, RepositoryDirectory repdir) throws KettleException
{
// Read the transformation...
//
mappingTransMeta = new TransMeta(repository, transMeta.environmentSubstitute(transName), repdir);
mappingTransMeta.clearChanged();
}
private void selectFileTrans()
{
String curFile = wFilename.getText();
FileObject root = null;
try
{
root = KettleVFS.getFileObject(curFile != null ? curFile : Const.USER_HOME_DIRECTORY);
VfsFileChooserDialog vfsFileChooser = new VfsFileChooserDialog(root.getParent(), root);
FileObject file = vfsFileChooser.open(shell, null, Const.STRING_TRANS_FILTER_EXT, Const
.getTransformationFilterNames(), VfsFileChooserDialog.VFS_DIALOG_OPEN_FILE);
if (file == null) {
return;
}
String fname = null;
fname = file.getURL().getFile();
if (fname != null)
{
loadFileTrans(fname);
wFilename.setText(mappingTransMeta.getFilename());
wTransName.setText(Const.NVL(mappingTransMeta.getName(), ""));
wTransDir.setText("");
wFileRadio.setSelection(true);
wRepRadio.setSelection(false);
}
} catch (IOException e)
{
new ErrorDialog(
shell,
Messages.getString("MappingDialog.ErrorLoadingTransformation.DialogTitle"), Messages.getString("MappingDialog.ErrorLoadingTransformation.DialogMessage"), e); //$NON-NLS-1$ //$NON-NLS-2$
} catch (KettleException e)
{
new ErrorDialog(
shell,
Messages.getString("MappingDialog.ErrorLoadingTransformation.DialogTitle"), Messages.getString("MappingDialog.ErrorLoadingTransformation.DialogMessage"), e); //$NON-NLS-1$ //$NON-NLS-2$
}
}
private void loadFileTrans(String fname) throws KettleException
{
mappingTransMeta = new TransMeta(transMeta.environmentSubstitute(fname));
mappingTransMeta.clearChanged();
}
private void editTrans()
{
// Load the transformation again to make sure it's still there and
// refreshed
// It's an extra check to make sure it's still OK...
try
{
loadTransformation();
// If we're still here, mappingTransMeta is valid.
SpoonInterface spoon = SpoonFactory.getInstance();
if (spoon != null)
{
spoon.addTransGraph(mappingTransMeta);
}
} catch (KettleException e)
{
new ErrorDialog(shell, Messages.getString("MappingDialog.ErrorShowingTransformation.Title"),
Messages.getString("MappingDialog.ErrorShowingTransformation.Message"), e);
}
}
private void loadTransformation() throws KettleException
{
if (wFileRadio.getSelection() && !Const.isEmpty(wFilename.getText())) // Read
// from
// file...
{
loadFileTrans(wFilename.getText());
} else
{
if (wRepRadio.getSelection() && repository != null && !Const.isEmpty(wTransName.getText())
&& !Const.isEmpty(wTransDir.getText()))
{
RepositoryDirectory repdir = repository.getDirectoryTree().findDirectory(wTransDir.getText());
if (repdir == null)
{
throw new KettleException(Messages.getString("MappingDialog.Exception.UnableToFindRepositoryDirectory)"));
}
loadRepositoryTrans(wTransName.getText(), repdir);
} else
{
throw new KettleException(Messages.getString("MappingDialog.Exception.NoValidMappingDetailsFound"));
}
}
}
/**
* Copy information from the meta-data input to the dialog fields.
*/
public void getData()
{
wStepname.selectAll();
wFilename.setText(Const.NVL(mappingMeta.getFileName(), ""));
wTransName.setText(Const.NVL(mappingMeta.getTransName(), ""));
wTransDir.setText(Const.NVL(mappingMeta.getDirectoryPath(), ""));
// if we have a filename, then we use the filename, otherwise we go with
// the repository...
wFileRadio.setSelection(false);
wRepRadio.setSelection(false);
if (!Const.isEmpty(mappingMeta.getFileName()))
{
wFileRadio.setSelection(true);
} else
{
if (repository != null && !Const.isEmpty(mappingMeta.getTransName())
&& !Const.isEmpty(mappingMeta.getDirectoryPath()))
{
wRepRadio.setSelection(true);
}
}
setFlags();
// Add the parameters tab
addParametersTab(mappingParameters);
wTabFolder.setSelection(0);
// Now add the input stream tabs: where is our data coming from?
for (int i = 0; i < inputMappings.size(); i++)
{
addInputMappingDefinitionTab(inputMappings.get(i), i);
}
// Now add the output stream tabs: where is our data going to?
for (int i = 0; i < outputMappings.size(); i++)
{
addOutputMappingDefinitionTab(outputMappings.get(i), i);
}
try
{
loadTransformation();
} catch (Throwable t)
{
}
}
private void addOutputMappingDefinitionTab(MappingIODefinition definition, int index)
{
addMappingDefinitionTab(outputMappings.get(index), index + 1 + inputMappings.size(),
Messages.getString("MappingDialog.OutputTab.Title"),
Messages.getString("MappingDialog.InputTab.Tooltip"),
Messages.getString("MappingDialog.OutputTab.label.InputSourceStepName"),
Messages.getString("MappingDialog.OutputTab.label.OutputTargetStepName"),
Messages.getString("MappingDialog.OutputTab.label.Description"),
Messages.getString("MappingDialog.OutputTab.column.SourceField"),
Messages.getString("MappingDialog.OutputTab.column.TargetField"), false);
}
private void addInputMappingDefinitionTab(MappingIODefinition definition, int index)
{
addMappingDefinitionTab(definition, index + 1, Messages.getString("MappingDialog.InputTab.Title"),
Messages.getString("MappingDialog.InputTab.Tooltip"),
Messages.getString("MappingDialog.InputTab.label.InputSourceStepName"),
Messages.getString("MappingDialog.InputTab.label.OutputTargetStepName"),
Messages.getString("MappingDialog.InputTab.label.Description"),
Messages.getString("MappingDialog.InputTab.column.SourceField"),
Messages.getString("MappingDialog.InputTab.column.TargetField"), true);
}
private void addParametersTab(final MappingParameters parameters)
{
CTabItem wParametersTab = new CTabItem(wTabFolder, SWT.NONE);
wParametersTab.setText(Messages.getString("MappingDialog.Parameters.Title")); //$NON-NLS-1$
wParametersTab.setToolTipText(Messages.getString("MappingDialog.Parameters.Tooltip")); //$NON-NLS-1$
Composite wParametersComposite = new Composite(wTabFolder, SWT.NONE);
props.setLook(wParametersComposite);
FormLayout parameterTabLayout = new FormLayout();
parameterTabLayout.marginWidth = Const.FORM_MARGIN;
parameterTabLayout.marginHeight = Const.FORM_MARGIN;
wParametersComposite.setLayout(parameterTabLayout);
// Now add a tableview with the 2 columns to specify: input and output
// fields for the source and target steps.
//
ColumnInfo[] colinfo = new ColumnInfo[] {
new ColumnInfo(
Messages.getString("MappingDialog.Parameters.column.Variable"), ColumnInfo.COLUMN_TYPE_TEXT, false, false), //$NON-NLS-1$
new ColumnInfo(
Messages.getString("MappingDialog.Parameters.column.ValueOrField"), ColumnInfo.COLUMN_TYPE_TEXT, false, false), //$NON-NLS-1$
};
colinfo[1].setUsingVariables(true);
final TableView wMappingParameters = new TableView(transMeta, wParametersComposite,
SWT.FULL_SELECTION | SWT.SINGLE | SWT.BORDER, colinfo, parameters.getVariable().length,
lsMod, props);
props.setLook(wMappingParameters);
FormData fdMappings = new FormData();
fdMappings.left = new FormAttachment(0, 0);
fdMappings.right = new FormAttachment(100, 0);
fdMappings.top = new FormAttachment(0, 0);
fdMappings.bottom = new FormAttachment(100, -30);
wMappingParameters.setLayoutData(fdMappings);
for (int i = 0; i < parameters.getVariable().length; i++)
{
TableItem tableItem = wMappingParameters.table.getItem(i);
tableItem.setText(1, parameters.getVariable()[i]);
tableItem.setText(2, parameters.getInputField()[i]);
}
wMappingParameters.setRowNums();
wMappingParameters.optWidth(true);
FormData fdParametersComposite = new FormData();
fdParametersComposite.left = new FormAttachment(0, 0);
fdParametersComposite.top = new FormAttachment(0, 0);
fdParametersComposite.right = new FormAttachment(100, 0);
fdParametersComposite.bottom = new FormAttachment(100, 0);
wParametersComposite.setLayoutData(fdParametersComposite);
wParametersComposite.layout();
wParametersTab.setControl(wParametersComposite);
changeList.add(new MappingParametersTab(wMappingParameters, parameters));
}
protected String selectTransformationStepname(boolean getTransformationStep, boolean mappingInput)
{
String dialogTitle = Messages.getString("MappingDialog.SelectTransStep.Title");
String dialogMessage = Messages.getString("MappingDialog.SelectTransStep.Message");
if (getTransformationStep)
{
dialogTitle = Messages.getString("MappingDialog.SelectTransStep.Title");
dialogMessage = Messages.getString("MappingDialog.SelectTransStep.Message");
String[] stepnames;
if (mappingInput)
{
stepnames = transMeta.getPrevStepNames(stepMeta);
} else
{
stepnames = transMeta.getNextStepNames(stepMeta);
}
EnterSelectionDialog dialog = new EnterSelectionDialog(shell, stepnames, dialogTitle,
dialogMessage);
return dialog.open();
} else
{
dialogTitle = Messages.getString("MappingDialog.SelectMappingStep.Title");
dialogMessage = Messages.getString("MappingDialog.SelectMappingStep.Message");
String[] stepnames = getMappingSteps(mappingTransMeta, mappingInput);
EnterSelectionDialog dialog = new EnterSelectionDialog(shell, stepnames, dialogTitle,
dialogMessage);
return dialog.open();
}
}
public static String[] getMappingSteps(TransMeta mappingTransMeta, boolean mappingInput)
{
List<StepMeta> steps = new ArrayList<StepMeta>();
for (StepMeta stepMeta : mappingTransMeta.getSteps())
{
if (mappingInput && stepMeta.getStepID().equals("MappingInput"))
{
steps.add(stepMeta);
}
if (!mappingInput && stepMeta.getStepID().equals("MappingOutput"))
{
steps.add(stepMeta);
}
}
String[] stepnames = new String[steps.size()];
for (int i = 0; i < stepnames.length; i++)
stepnames[i] = steps.get(i).getName();
return stepnames;
}
public RowMetaInterface getFieldsFromStep(String stepname, boolean getTransformationStep,
boolean mappingInput) throws KettleException
{
if (!(mappingInput ^ getTransformationStep))
{
if (Const.isEmpty(stepname))
{
// If we don't have a specified stepname we return the input row
// metadata
//
return transMeta.getPrevStepFields(this.stepname);
} else
{
// OK, a fieldname is specified...
// See if we can find it...
StepMeta stepMeta = transMeta.findStep(stepname);
if (stepMeta == null)
{
throw new KettleException(Messages.getString("MappingDialog.Exception.SpecifiedStepWasNotFound", stepname));
}
return transMeta.getStepFields(stepMeta);
}
}
else
{
if (Const.isEmpty(stepname))
{
// If we don't have a specified stepname we select the one and
// only "mapping input" step.
//
String[] stepnames = getMappingSteps(mappingTransMeta, mappingInput);
if (stepnames.length > 1)
{
throw new KettleException(Messages.getString("MappingDialog.Exception.OnlyOneMappingInputStepAllowed", "" + stepnames.length));
}
if (stepnames.length == 0)
{
throw new KettleException(Messages.getString("MappingDialog.Exception.OneMappingInputStepRequired", "" + stepnames.length));
}
return mappingTransMeta.getStepFields(stepnames[0]);
}
else
{
// OK, a fieldname is specified...
// See if we can find it...
StepMeta stepMeta = mappingTransMeta.findStep(stepname);
if (stepMeta == null)
{
throw new KettleException(Messages.getString("MappingDialog.Exception.SpecifiedStepWasNotFound", stepname));
}
return mappingTransMeta.getStepFields(stepMeta);
}
}
}
private void addMappingDefinitionTab(final MappingIODefinition definition, int index,
final String tabTitle, final String tabTooltip, String inputStepLabel, String outputStepLabel,
String descriptionLabel, String sourceColumnLabel, String targetColumnLabel, final boolean input)
{
final CTabItem wTab;
if (index >= wTabFolder.getItemCount())
{
wTab = new CTabItem(wTabFolder, SWT.CLOSE);
} else
{
wTab = new CTabItem(wTabFolder, SWT.CLOSE, index);
}
setMappingDefinitionTabNameAndToolTip(wTab, tabTitle, tabTooltip, definition, input);
Composite wInputComposite = new Composite(wTabFolder, SWT.NONE);
props.setLook(wInputComposite);
FormLayout tabLayout = new FormLayout();
tabLayout.marginWidth = Const.FORM_MARGIN;
tabLayout.marginHeight = Const.FORM_MARGIN;
wInputComposite.setLayout(tabLayout);
// What's the stepname to read from? (empty is OK too)
//
Button wbInputStep = new Button(wInputComposite, SWT.PUSH);
props.setLook(wbInputStep);
wbInputStep.setText(Messages.getString("MappingDialog.button.SourceStepName"));
FormData fdbInputStep = new FormData();
fdbInputStep.top = new FormAttachment(0, 0);
fdbInputStep.right = new FormAttachment(100, 0); // First one in the
// left top corner
wbInputStep.setLayoutData(fdbInputStep);
Label wlInputStep = new Label(wInputComposite, SWT.RIGHT);
props.setLook(wlInputStep);
wlInputStep.setText(inputStepLabel); //$NON-NLS-1$
FormData fdlInputStep = new FormData();
fdlInputStep.top = new FormAttachment(wbInputStep, 0, SWT.CENTER);
fdlInputStep.left = new FormAttachment(0, 0); // First one in the left
// top corner
fdlInputStep.right = new FormAttachment(middle, -margin);
wlInputStep.setLayoutData(fdlInputStep);
final Text wInputStep = new Text(wInputComposite, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wInputStep);
wInputStep.setText(Const.NVL(definition.getInputStepname(), ""));
wInputStep.addModifyListener(lsMod);
FormData fdInputStep = new FormData();
fdInputStep.top = new FormAttachment(wbInputStep, 0, SWT.CENTER);
fdInputStep.left = new FormAttachment(middle, 0); // To the right of
// the label
fdInputStep.right = new FormAttachment(wbInputStep, -margin);
wInputStep.setLayoutData(fdInputStep);
wInputStep.addFocusListener(new FocusAdapter()
{
@Override
public void focusLost(FocusEvent event)
{
definition.setInputStepname(wInputStep.getText());
setMappingDefinitionTabNameAndToolTip(wTab, tabTitle, tabTooltip, definition, input);
}
});
wbInputStep.addSelectionListener(new SelectionAdapter()
{
@Override
public void widgetSelected(SelectionEvent event)
{
String stepName = selectTransformationStepname(input, input);
if (stepName != null)
{
wInputStep.setText(stepName);
definition.setInputStepname(stepName);
setMappingDefinitionTabNameAndToolTip(wTab, tabTitle, tabTooltip, definition, input);
}
}
});
// What's the step name to read from? (empty is OK too)
//
Button wbOutputStep = new Button(wInputComposite, SWT.PUSH);
props.setLook(wbOutputStep);
wbOutputStep.setText(Messages.getString("MappingDialog.button.SourceStepName"));
FormData fdbOutputStep = new FormData();
fdbOutputStep.top = new FormAttachment(wbInputStep, margin);
fdbOutputStep.right = new FormAttachment(100, 0);
wbOutputStep.setLayoutData(fdbOutputStep);
Label wlOutputStep = new Label(wInputComposite, SWT.RIGHT);
props.setLook(wlOutputStep);
wlOutputStep.setText(outputStepLabel); //$NON-NLS-1$
FormData fdlOutputStep = new FormData();
fdlOutputStep.top = new FormAttachment(wbOutputStep, 0, SWT.CENTER);
fdlOutputStep.left = new FormAttachment(0, 0);
fdlOutputStep.right = new FormAttachment(middle, -margin);
wlOutputStep.setLayoutData(fdlOutputStep);
final Text wOutputStep = new Text(wInputComposite, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wOutputStep);
wOutputStep.setText(Const.NVL(definition.getOutputStepname(), ""));
wOutputStep.addModifyListener(lsMod);
FormData fdOutputStep = new FormData();
fdOutputStep.top = new FormAttachment(wbOutputStep, 0, SWT.CENTER);
fdOutputStep.left = new FormAttachment(middle, 0); // To the right of
// the label
fdOutputStep.right = new FormAttachment(wbOutputStep, -margin);
wOutputStep.setLayoutData(fdOutputStep);
// Add a checkbox to indicate the main step to read from, the main data
// path...
//
Label wlMainPath = new Label(wInputComposite, SWT.RIGHT);
props.setLook(wlMainPath);
wlMainPath.setText(Messages.getString("MappingDialog.input.MainDataPath")); //$NON-NLS-1$
FormData fdlMainPath = new FormData();
fdlMainPath.top = new FormAttachment(wbOutputStep, margin);
fdlMainPath.left = new FormAttachment(0, 0);
fdlMainPath.right = new FormAttachment(middle, -margin);
wlMainPath.setLayoutData(fdlMainPath);
Button wMainPath = new Button(wInputComposite, SWT.CHECK);
props.setLook(wMainPath);
FormData fdMainPath = new FormData();
fdMainPath.top = new FormAttachment(wbOutputStep, margin);
fdMainPath.left = new FormAttachment(middle, 0);
// fdMainPath.right = new FormAttachment(100, 0); // who cares, it's a
// checkbox
wMainPath.setLayoutData(fdMainPath);
wMainPath.setSelection(definition.isMainDataPath());
wMainPath.addSelectionListener(new SelectionAdapter()
{
@Override
public void widgetSelected(SelectionEvent event)
{
definition.setMainDataPath(!definition.isMainDataPath()); // flip
// the
// switch
}
});
// Add a checkbox to indicate that all output mappings need to rename
// the values back...
//
Label wlRenameOutput = new Label(wInputComposite, SWT.RIGHT);
props.setLook(wlRenameOutput);
wlRenameOutput.setText(Messages.getString("MappingDialog.input.RenamingOnOutput")); //$NON-NLS-1$
FormData fdlRenameOutput = new FormData();
fdlRenameOutput.top = new FormAttachment(wMainPath, margin);
fdlRenameOutput.left = new FormAttachment(0, 0);
fdlRenameOutput.right = new FormAttachment(middle, -margin);
wlRenameOutput.setLayoutData(fdlRenameOutput);
Button wRenameOutput = new Button(wInputComposite, SWT.CHECK);
props.setLook(wRenameOutput);
FormData fdRenameOutput = new FormData();
fdRenameOutput.top = new FormAttachment(wMainPath, margin);
fdRenameOutput.left = new FormAttachment(middle, 0);
// fdRenameOutput.right = new FormAttachment(100, 0); // who cares, it's
// a check box
wRenameOutput.setLayoutData(fdRenameOutput);
wRenameOutput.setSelection(definition.isRenamingOnOutput());
wRenameOutput.addSelectionListener(new SelectionAdapter()
{
@Override
public void widgetSelected(SelectionEvent event)
{
definition.setRenamingOnOutput(!definition.isRenamingOnOutput()); // flip
// the
// switch
}
});
// Allow for a small description
//
Label wlDescription = new Label(wInputComposite, SWT.RIGHT);
props.setLook(wlDescription);
wlDescription.setText(descriptionLabel); //$NON-NLS-1$
FormData fdlDescription = new FormData();
fdlDescription.top = new FormAttachment(wRenameOutput, margin);
fdlDescription.left = new FormAttachment(0, 0); // First one in the left
// top corner
fdlDescription.right = new FormAttachment(middle, -margin);
wlDescription.setLayoutData(fdlDescription);
final Text wDescription = new Text(wInputComposite, SWT.MULTI | SWT.LEFT | SWT.BORDER | SWT.V_SCROLL
| SWT.H_SCROLL);
props.setLook(wDescription);
wDescription.setText(Const.NVL(definition.getDescription(), ""));
wDescription.addModifyListener(lsMod);
FormData fdDescription = new FormData();
fdDescription.top = new FormAttachment(wRenameOutput, margin);
fdDescription.bottom = new FormAttachment(wRenameOutput, 100 + margin);
fdDescription.left = new FormAttachment(middle, 0); // To the right of
// the label
fdDescription.right = new FormAttachment(wbOutputStep, -margin);
wDescription.setLayoutData(fdDescription);
wDescription.addFocusListener(new FocusAdapter()
{
@Override
public void focusLost(FocusEvent event)
{
definition.setDescription(wDescription.getText());
}
});
// Now add a table view with the 2 columns to specify: input and output
// fields for the source and target steps.
//
final Button wbEnterMapping = new Button(wInputComposite, SWT.PUSH);
props.setLook(wbEnterMapping);
wbEnterMapping.setText(Messages.getString("MappingDialog.button.EnterMapping"));
FormData fdbEnterMapping = new FormData();
fdbEnterMapping.top = new FormAttachment(wDescription, margin * 2);
fdbEnterMapping.right = new FormAttachment(100, 0); // First one in the
// left top corner
wbEnterMapping.setLayoutData(fdbEnterMapping);
ColumnInfo[] colinfo = new ColumnInfo[] {
new ColumnInfo(sourceColumnLabel, ColumnInfo.COLUMN_TYPE_TEXT, false, false), //$NON-NLS-1$
new ColumnInfo(targetColumnLabel, ColumnInfo.COLUMN_TYPE_TEXT, false, false), //$NON-NLS-1$
};
final TableView wFieldMappings = new TableView(transMeta, wInputComposite, SWT.FULL_SELECTION
| SWT.SINGLE | SWT.BORDER, colinfo, 1, lsMod, props);
props.setLook(wFieldMappings);
FormData fdMappings = new FormData();
fdMappings.left = new FormAttachment(0, 0);
fdMappings.right = new FormAttachment(wbEnterMapping, -margin);
fdMappings.top = new FormAttachment(wDescription, margin * 2);
fdMappings.bottom = new FormAttachment(100, -20);
wFieldMappings.setLayoutData(fdMappings);
for (MappingValueRename valueRename : definition.getValueRenames())
{
TableItem tableItem = new TableItem(wFieldMappings.table, SWT.NONE);
tableItem.setText(1, valueRename.getSourceValueName());
tableItem.setText(2, valueRename.getTargetValueName());
}
wFieldMappings.removeEmptyRows();
wFieldMappings.setRowNums();
wFieldMappings.optWidth(true);
wbEnterMapping.addSelectionListener(new SelectionAdapter()
{
@Override
public void widgetSelected(SelectionEvent arg0)
{
try
{
loadTransformation();
RowMetaInterface sourceRowMeta = getFieldsFromStep(wInputStep.getText(), true, input);
RowMetaInterface targetRowMeta = getFieldsFromStep(wOutputStep.getText(), false, input);
String sourceFields[] = sourceRowMeta.getFieldNames();
String targetFields[] = targetRowMeta.getFieldNames();
EnterMappingDialog dialog = new EnterMappingDialog(shell, sourceFields, targetFields);
List<SourceToTargetMapping> mappings = dialog.open();
if (mappings != null)
{
// first clear the dialog...
wFieldMappings.clearAll(false);
//
definition.getValueRenames().clear();
// Now add the new values...
for (int i = 0; i < mappings.size(); i++)
{
SourceToTargetMapping mapping = mappings.get(i);
TableItem item = new TableItem(wFieldMappings.table, SWT.NONE);
item.setText(1, mapping.getSourceString(sourceFields));
item.setText(2, mapping.getTargetString(targetFields));
String source = input ? item.getText(1) : item.getText(2);
String target = input ? item.getText(2) : item.getText(1);
definition.getValueRenames().add(new MappingValueRename(source, target));
}
wFieldMappings.removeEmptyRows();
wFieldMappings.setRowNums();
wFieldMappings.optWidth(true);
}
} catch (KettleException e)
{
new ErrorDialog(shell, Messages.getString("System.Dialog.Error.Title"), Messages.getString("MappingDialog.Exception.ErrorGettingMappingSourceAndTargetFields", e.toString()), e);
}
}
});
wOutputStep.addFocusListener(new FocusAdapter()
{
@Override
public void focusLost(FocusEvent event)
{
definition.setOutputStepname(wOutputStep.getText());
try
{
enableMappingButton(wbEnterMapping, input, wInputStep.getText(), wOutputStep.getText());
} catch (KettleException e)
{
// Show the missing/wrong step name error
//
new ErrorDialog(shell, "Error", "Unexpected error", e);
}
}
});
wbOutputStep.addSelectionListener(new SelectionAdapter()
{
@Override
public void widgetSelected(SelectionEvent event)
{
String stepName = selectTransformationStepname(!input, input);
if (stepName != null)
{
wOutputStep.setText(stepName);
definition.setOutputStepname(stepName);
try
{
enableMappingButton(wbEnterMapping, input, wInputStep.getText(), wOutputStep
.getText());
} catch (KettleException e)
{
// Show the missing/wrong stepname error
new ErrorDialog(shell, "Error", "Unexpected error", e);
}
}
}
});
FormData fdParametersComposite = new FormData();
fdParametersComposite.left = new FormAttachment(0, 0);
fdParametersComposite.top = new FormAttachment(0, 0);
fdParametersComposite.right = new FormAttachment(100, 0);
fdParametersComposite.bottom = new FormAttachment(100, 0);
wInputComposite.setLayoutData(fdParametersComposite);
wInputComposite.layout();
wTab.setControl(wInputComposite);
final ApplyChanges applyChanges = new MappingDefinitionTab(definition, wInputStep, wOutputStep,
wMainPath, wDescription, wFieldMappings);
changeList.add(applyChanges);
// OK, suppose for some weird reason the user wants to remove an input
// or output tab...
wTabFolder.addCTabFolder2Listener(new CTabFolder2Adapter()
{
@Override
public void close(CTabFolderEvent event)
{
if (event.item.equals(wTab))
{
// The user has the audacity to try and close this mapping
// definition tab.
// We really should warn him that this is a bad idea...
MessageBox box = new MessageBox(shell, SWT.YES | SWT.NO);
box.setText(Messages.getString("MappingDialog.CloseDefinitionTabAreYouSure.Title"));
box.setMessage(Messages.getString("MappingDialog.CloseDefinitionTabAreYouSure.Message"));
int answer = box.open();
if (answer != SWT.YES)
{
event.doit = false;
} else
{
// Remove it from our list to make sure it's gone...
if (input)
inputMappings.remove(definition);
else
outputMappings.remove(definition);
// remove it from the changeList too...
// Otherwise the dialog leaks memory.
//
changeList.remove(applyChanges);
}
}
}
});
wTabFolder.setSelection(wTab);
}
/**
* Enables or disables the mapping button. We can only enable it if the
* target steps allows a mapping to be made against it.
*
* @param button
* The button to disable or enable
* @param input
* input or output. If it's true, we keep the button enabled all
* the time.
* @param sourceStepname
* The mapping output step
* @param targetStepname
* The target step to verify
* @throws KettleException
*/
private void enableMappingButton(final Button button, boolean input, String sourceStepname,
String targetStepname) throws KettleException
{
if (input)
return; // nothing to do
boolean enabled = false;
if (mappingTransMeta != null)
{
StepMeta mappingInputStep = mappingTransMeta.findMappingInputStep(sourceStepname);
if (mappingInputStep != null)
{
StepMeta mappingOutputStep = transMeta.findMappingOutputStep(targetStepname);
RowMetaInterface requiredFields = mappingOutputStep.getStepMetaInterface()
.getRequiredFields();
if (requiredFields != null && requiredFields.size() > 0)
{
enabled = true;
}
}
}
button.setEnabled(enabled);
}
private void setMappingDefinitionTabNameAndToolTip(CTabItem wTab, String tabTitle, String tabTooltip,
MappingIODefinition definition, boolean input)
{
String stepname;
if (input)
{
stepname = definition.getInputStepname();
} else
{
stepname = definition.getOutputStepname();
}
String description = definition.getDescription();
if (Const.isEmpty(stepname))
{
wTab.setText(tabTitle); //$NON-NLS-1$
} else
{
wTab.setText(tabTitle + " : " + stepname); //$NON-NLS-1$ $NON-NLS-2$
}
String tooltip = tabTooltip; //$NON-NLS-1$
if (!Const.isEmpty(stepname))
{
tooltip += Const.CR + Const.CR + stepname;
}
if (!Const.isEmpty(description))
{
tooltip += Const.CR + Const.CR + description;
}
wTab.setToolTipText(tooltip); //$NON-NLS-1$
}
private void setFlags()
{
if (repository == null)
{
wRepRadio.setEnabled(false);
wbTrans.setEnabled(false);
wTransName.setEnabled(false);
wTransDir.setEnabled(false);
}
}
private void cancel()
{
stepname = null;
mappingMeta.setChanged(changed);
dispose();
}
private void ok()
{
if (Const.isEmpty(wStepname.getText())) return;
try
{
stepname = wStepname.getText(); // return value
loadTransformation();
mappingMeta.setFileName(wFilename.getText());
mappingMeta.setTransName(wTransName.getText());
mappingMeta.setDirectoryPath(wTransDir.getText());
// Load the information on the tabs, optionally do some
// verifications...
//
collectInformation();
mappingMeta.setMappingParameters(mappingParameters);
mappingMeta.setInputMappings(inputMappings);
mappingMeta.setOutputMappings(outputMappings);
mappingMeta.setChanged(true);
dispose();
} catch (KettleException e)
{
new ErrorDialog(shell, Messages.getString("MappingDialog.ErrorLoadingSpecifiedTransformation.Title"), Messages.getString("MappingDialog.ErrorLoadingSpecifiedTransformation.Message"), e);
}
}
private void collectInformation()
{
for (ApplyChanges applyChanges : changeList)
{
applyChanges.applyChanges(); // collect information from all
// tabs...
}
}
}
|
src-ui/org/pentaho/di/ui/trans/steps/mapping/MappingDialog.java
|
/* Copyright (c) 2007 Pentaho Corporation. All rights reserved.
* This software was developed by Pentaho Corporation and is provided under the terms
* of the GNU Lesser General Public License, Version 2.1. You may not use
* this file except in compliance with the license. If you need a copy of the license,
* please go to http://www.gnu.org/licenses/lgpl-2.1.txt. The Original Code is Pentaho
* Data Integration. The Initial Developer is Pentaho Corporation.
*
* Software distributed under the GNU Lesser Public License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. Please refer to
* the license for the specific language governing your rights and limitations.*/
/*
* Created on 18-mei-2003
*
*/
package org.pentaho.di.ui.trans.steps.mapping;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.vfs.FileObject;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CTabFolder;
import org.eclipse.swt.custom.CTabFolder2Adapter;
import org.eclipse.swt.custom.CTabFolderEvent;
import org.eclipse.swt.custom.CTabItem;
import org.eclipse.swt.events.FocusAdapter;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.ShellAdapter;
import org.eclipse.swt.events.ShellEvent;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.Props;
import org.pentaho.di.core.SourceToTargetMapping;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.gui.SpoonFactory;
import org.pentaho.di.core.gui.SpoonInterface;
import org.pentaho.di.core.row.RowMetaInterface;
import org.pentaho.di.core.vfs.KettleVFS;
import org.pentaho.di.repository.RepositoryDirectory;
import org.pentaho.di.trans.TransMeta;
import org.pentaho.di.trans.step.BaseStepMeta;
import org.pentaho.di.trans.step.StepDialogInterface;
import org.pentaho.di.trans.step.StepMeta;
import org.pentaho.di.trans.steps.mapping.MappingIODefinition;
import org.pentaho.di.trans.steps.mapping.MappingMeta;
import org.pentaho.di.trans.steps.mapping.MappingParameters;
import org.pentaho.di.trans.steps.mapping.MappingValueRename;
import org.pentaho.di.trans.steps.mapping.Messages;
import org.pentaho.di.ui.core.dialog.EnterMappingDialog;
import org.pentaho.di.ui.core.dialog.EnterSelectionDialog;
import org.pentaho.di.ui.core.dialog.ErrorDialog;
import org.pentaho.di.ui.core.widget.ColumnInfo;
import org.pentaho.di.ui.core.widget.TableView;
import org.pentaho.di.ui.core.widget.TextVar;
import org.pentaho.di.ui.repository.dialog.SelectObjectDialog;
import org.pentaho.di.ui.trans.step.BaseStepDialog;
import org.pentaho.vfs.ui.VfsFileChooserDialog;
public class MappingDialog extends BaseStepDialog implements StepDialogInterface
{
private MappingMeta mappingMeta;
private Group gTransGroup;
// File
private Button wFileRadio;
private Button wbbFilename; // Browse: add file or directory
private TextVar wFilename;
// Repository
private Button wRepRadio;
private TextVar wTransName, wTransDir;
private Button wbTrans;
private Button wEditTrans;
private CTabFolder wTabFolder;
TransMeta mappingTransMeta = null;
protected boolean transModified;
private ModifyListener lsMod;
private int middle;
private int margin;
private MappingParameters mappingParameters;
private List<MappingIODefinition> inputMappings;
private List<MappingIODefinition> outputMappings;
private Button wAddInput;
private Button wAddOutput;
private interface ApplyChanges
{
public void applyChanges();
}
private class MappingParametersTab implements ApplyChanges
{
private TableView wMappingParameters;
private MappingParameters parameters;
public MappingParametersTab(TableView wMappingParameters, MappingParameters parameters)
{
this.wMappingParameters = wMappingParameters;
this.parameters = parameters;
}
public void applyChanges()
{
int nrLines = wMappingParameters.nrNonEmpty();
String variables[] = new String[nrLines];
String inputFields[] = new String[nrLines];
parameters.setVariable(variables);
parameters.setInputField(inputFields);
for (int i = 0; i < nrLines; i++)
{
TableItem item = wMappingParameters.getNonEmpty(i);
parameters.getVariable()[i] = item.getText(1);
parameters.getInputField()[i] = item.getText(2);
}
}
}
private class MappingDefinitionTab implements ApplyChanges
{
private MappingIODefinition definition;
private Text wInputStep;
private Text wOutputStep;
private Button wMainPath;
private Text wDescription;
private TableView wFieldMappings;
public MappingDefinitionTab(MappingIODefinition definition, Text inputStep, Text outputStep,
Button mainPath, Text description, TableView fieldMappings)
{
super();
this.definition = definition;
wInputStep = inputStep;
wOutputStep = outputStep;
wMainPath = mainPath;
wDescription = description;
wFieldMappings = fieldMappings;
}
public void applyChanges()
{
// The input step
definition.setInputStepname(wInputStep.getText());
// The output step
definition.setOutputStepname(wOutputStep.getText());
// The description
definition.setDescription(wDescription.getText());
// The main path flag
definition.setMainDataPath(wMainPath.getSelection());
// The grid
//
int nrLines = wFieldMappings.nrNonEmpty();
definition.getValueRenames().clear();
for (int i = 0; i < nrLines; i++)
{
TableItem item = wFieldMappings.getNonEmpty(i);
definition.getValueRenames().add(new MappingValueRename(item.getText(1), item.getText(2)));
}
}
}
private List<ApplyChanges> changeList;
public MappingDialog(Shell parent, Object in, TransMeta tr, String sname)
{
super(parent, (BaseStepMeta) in, tr, sname);
mappingMeta = (MappingMeta) in;
transModified = false;
// Make a copy for our own purposes...
// This allows us to change everything directly in the classes with
// listeners.
// Later we need to copy it to the input class on ok()
//
mappingParameters = (MappingParameters) mappingMeta.getMappingParameters().clone();
inputMappings = new ArrayList<MappingIODefinition>();
outputMappings = new ArrayList<MappingIODefinition>();
for (int i = 0; i < mappingMeta.getInputMappings().size(); i++)
inputMappings.add((MappingIODefinition) mappingMeta.getInputMappings().get(i).clone());
for (int i = 0; i < mappingMeta.getOutputMappings().size(); i++)
outputMappings.add((MappingIODefinition) mappingMeta.getOutputMappings().get(i).clone());
changeList = new ArrayList<ApplyChanges>();
}
public String open()
{
Shell parent = getParent();
Display display = parent.getDisplay();
shell = new Shell(parent, SWT.DIALOG_TRIM | SWT.RESIZE | SWT.MIN | SWT.MAX);
props.setLook(shell);
setShellImage(shell, mappingMeta);
lsMod = new ModifyListener()
{
public void modifyText(ModifyEvent e)
{
mappingMeta.setChanged();
}
};
changed = mappingMeta.hasChanged();
FormLayout formLayout = new FormLayout();
formLayout.marginWidth = Const.FORM_MARGIN;
formLayout.marginHeight = Const.FORM_MARGIN;
shell.setLayout(formLayout);
shell.setText(Messages.getString("MappingDialog.Shell.Title")); //$NON-NLS-1$
middle = props.getMiddlePct();
margin = Const.MARGIN;
// Stepname line
wlStepname = new Label(shell, SWT.RIGHT);
wlStepname.setText(Messages.getString("MappingDialog.Stepname.Label")); //$NON-NLS-1$
props.setLook(wlStepname);
fdlStepname = new FormData();
fdlStepname.left = new FormAttachment(0, 0);
fdlStepname.right = new FormAttachment(middle, -margin);
fdlStepname.top = new FormAttachment(0, margin);
wlStepname.setLayoutData(fdlStepname);
wStepname = new Text(shell, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
wStepname.setText(stepname);
props.setLook(wStepname);
wStepname.addModifyListener(lsMod);
fdStepname = new FormData();
fdStepname.left = new FormAttachment(middle, 0);
fdStepname.top = new FormAttachment(0, margin);
fdStepname.right = new FormAttachment(100, 0);
wStepname.setLayoutData(fdStepname);
// Show a group with 2 main options: a transformation in the repository
// or on file
//
// //////////////////////////////////////////////////
// The key creation box
// //////////////////////////////////////////////////
//
gTransGroup = new Group(shell, SWT.SHADOW_ETCHED_IN);
gTransGroup.setText(Messages.getString("MappingDialog.TransGroup.Label")); //$NON-NLS-1$;
gTransGroup.setBackground(shell.getBackground()); // the default looks
// ugly
FormLayout transGroupLayout = new FormLayout();
transGroupLayout.marginLeft = margin * 2;
transGroupLayout.marginTop = margin * 2;
transGroupLayout.marginRight = margin * 2;
transGroupLayout.marginBottom = margin * 2;
gTransGroup.setLayout(transGroupLayout);
// Radio button: The mapping is in a file
//
wFileRadio = new Button(gTransGroup, SWT.RADIO);
props.setLook(wFileRadio);
wFileRadio.setSelection(false);
wFileRadio.setText(Messages.getString("MappingDialog.RadioFile.Label")); //$NON-NLS-1$
wFileRadio.setToolTipText(Messages.getString("MappingDialog.RadioFile.Tooltip", Const.CR)); //$NON-NLS-1$ //$NON-NLS-2$
FormData fdFileRadio = new FormData();
fdFileRadio.left = new FormAttachment(0, 0);
fdFileRadio.right = new FormAttachment(100, 0);
fdFileRadio.top = new FormAttachment(0, 0);
wFileRadio.setLayoutData(fdFileRadio);
wbbFilename = new Button(gTransGroup, SWT.PUSH | SWT.CENTER); // Browse
props.setLook(wbbFilename);
wbbFilename.setText(Messages.getString("System.Button.Browse"));
wbbFilename.setToolTipText(Messages.getString("System.Tooltip.BrowseForFileOrDirAndAdd"));
FormData fdbFilename = new FormData();
fdbFilename.right = new FormAttachment(100, 0);
fdbFilename.top = new FormAttachment(wFileRadio, margin);
wbbFilename.setLayoutData(fdbFilename);
wbbFilename.addSelectionListener(new SelectionAdapter()
{
public void widgetSelected(SelectionEvent e)
{
selectFileTrans();
}
});
wFilename = new TextVar(transMeta, gTransGroup, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wFilename);
wFilename.addModifyListener(lsMod);
FormData fdFilename = new FormData();
fdFilename.left = new FormAttachment(0, 25);
fdFilename.right = new FormAttachment(wbbFilename, -margin);
fdFilename.top = new FormAttachment(wbbFilename, 0, SWT.CENTER);
wFilename.setLayoutData(fdFilename);
wFilename.addModifyListener(new ModifyListener()
{
public void modifyText(ModifyEvent e)
{
wFileRadio.setSelection(true);
wRepRadio.setSelection(false);
}
});
// Radio button: The mapping is in the repository
//
wRepRadio = new Button(gTransGroup, SWT.RADIO);
props.setLook(wRepRadio);
wRepRadio.setSelection(false);
wRepRadio.setText(Messages.getString("MappingDialog.RadioRep.Label")); //$NON-NLS-1$
wRepRadio.setToolTipText(Messages.getString("MappingDialog.RadioRep.Tooltip", Const.CR)); //$NON-NLS-1$ //$NON-NLS-2$
FormData fdRepRadio = new FormData();
fdRepRadio.left = new FormAttachment(0, 0);
fdRepRadio.right = new FormAttachment(100, 0);
fdRepRadio.top = new FormAttachment(wbbFilename, 2 * margin);
wRepRadio.setLayoutData(fdRepRadio);
wbTrans = new Button(gTransGroup, SWT.PUSH | SWT.CENTER); // Browse
props.setLook(wbTrans);
wbTrans.setText(Messages.getString("MappingDialog.Select.Button"));
wbTrans.setToolTipText(Messages.getString("System.Tooltip.BrowseForFileOrDirAndAdd"));
FormData fdbTrans = new FormData();
fdbTrans.right = new FormAttachment(100, 0);
fdbTrans.top = new FormAttachment(wRepRadio, 2 * margin);
wbTrans.setLayoutData(fdbTrans);
wbTrans.addSelectionListener(new SelectionAdapter()
{
public void widgetSelected(SelectionEvent e)
{
selectRepositoryTrans();
}
});
wTransDir = new TextVar(transMeta, gTransGroup, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wTransDir);
wTransDir.addModifyListener(lsMod);
FormData fdTransDir = new FormData();
fdTransDir.left = new FormAttachment(middle + (100 - middle) / 2, 0);
fdTransDir.right = new FormAttachment(wbTrans, -margin);
fdTransDir.top = new FormAttachment(wbTrans, 0, SWT.CENTER);
wTransDir.setLayoutData(fdTransDir);
wTransName = new TextVar(transMeta, gTransGroup, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wTransName);
wTransName.addModifyListener(lsMod);
FormData fdTransName = new FormData();
fdTransName.left = new FormAttachment(0, 25);
fdTransName.right = new FormAttachment(wTransDir, -margin);
fdTransName.top = new FormAttachment(wbTrans, 0, SWT.CENTER);
wTransName.setLayoutData(fdTransName);
wEditTrans = new Button(gTransGroup, SWT.PUSH | SWT.CENTER); // Browse
props.setLook(wEditTrans);
wEditTrans.setText(Messages.getString("MappingDialog.Edit.Button"));
wEditTrans.setToolTipText(Messages.getString("System.Tooltip.BrowseForFileOrDirAndAdd"));
FormData fdEditTrans = new FormData();
fdEditTrans.left = new FormAttachment(0, 0);
fdEditTrans.right = new FormAttachment(100, 0);
fdEditTrans.top = new FormAttachment(wTransName, 3 * margin);
wEditTrans.setLayoutData(fdEditTrans);
wEditTrans.addSelectionListener(new SelectionAdapter()
{
public void widgetSelected(SelectionEvent e)
{
editTrans();
}
});
FormData fdTransGroup = new FormData();
fdTransGroup.left = new FormAttachment(0, 0);
fdTransGroup.top = new FormAttachment(wStepname, 2 * margin);
fdTransGroup.right = new FormAttachment(100, 0);
// fdTransGroup.bottom = new FormAttachment(wStepname, 350);
gTransGroup.setLayoutData(fdTransGroup);
//
// Add a tab folder for the parameters and various input and output
// streams
//
wTabFolder = new CTabFolder(shell, SWT.BORDER);
props.setLook(wTabFolder, Props.WIDGET_STYLE_TAB);
wTabFolder.setSimple(false);
wTabFolder.setUnselectedCloseVisible(true);
FormData fdTabFolder = new FormData();
fdTabFolder.left = new FormAttachment(0, 0);
fdTabFolder.right = new FormAttachment(100, 0);
fdTabFolder.top = new FormAttachment(gTransGroup, margin * 2);
fdTabFolder.bottom = new FormAttachment(100, -75);
wTabFolder.setLayoutData(fdTabFolder);
// Now add buttons that will allow us to add or remove input or output
// tabs...
wAddInput = new Button(shell, SWT.PUSH);
props.setLook(wAddInput);
wAddInput.setText(Messages.getString("MappingDialog.button.AddInput"));
wAddInput.addSelectionListener(new SelectionAdapter()
{
@Override
public void widgetSelected(SelectionEvent event)
{
// Simply add a new MappingIODefinition object to the
// inputMappings
MappingIODefinition definition = new MappingIODefinition();
inputMappings.add(definition);
int index = inputMappings.size() - 1;
addInputMappingDefinitionTab(definition, index);
}
});
wAddOutput = new Button(shell, SWT.PUSH);
props.setLook(wAddOutput);
wAddOutput.setText(Messages.getString("MappingDialog.button.AddOutput"));
wAddOutput.addSelectionListener(new SelectionAdapter()
{
@Override
public void widgetSelected(SelectionEvent event)
{
// Simply add a new MappingIODefinition object to the
// inputMappings
MappingIODefinition definition = new MappingIODefinition();
outputMappings.add(definition);
int index = outputMappings.size() - 1;
addOutputMappingDefinitionTab(definition, index);
}
});
setButtonPositions(new Button[] { wAddInput, wAddOutput }, margin, wTabFolder);
// Some buttons
wOK = new Button(shell, SWT.PUSH);
wOK.setText(Messages.getString("System.Button.OK")); //$NON-NLS-1$
wCancel = new Button(shell, SWT.PUSH);
wCancel.setText(Messages.getString("System.Button.Cancel")); //$NON-NLS-1$
setButtonPositions(new Button[] { wOK, wCancel }, margin, null);
// Add listeners
lsCancel = new Listener()
{
public void handleEvent(Event e)
{
cancel();
}
};
lsOK = new Listener()
{
public void handleEvent(Event e)
{
ok();
}
};
wCancel.addListener(SWT.Selection, lsCancel);
wOK.addListener(SWT.Selection, lsOK);
lsDef = new SelectionAdapter()
{
public void widgetDefaultSelected(SelectionEvent e)
{
ok();
}
};
wStepname.addSelectionListener(lsDef);
// Detect X or ALT-F4 or something that kills this window...
shell.addShellListener(new ShellAdapter()
{
public void shellClosed(ShellEvent e)
{
cancel();
}
});
// Set the shell size, based upon previous time...
setSize();
getData();
mappingMeta.setChanged(changed);
wTabFolder.setSelection(0);
shell.open();
while (!shell.isDisposed())
{
if (!display.readAndDispatch())
display.sleep();
}
return stepname;
}
private void selectRepositoryTrans()
{
try
{
SelectObjectDialog sod = new SelectObjectDialog(shell, repository);
String transName = sod.open();
RepositoryDirectory repdir = sod.getDirectory();
if (transName != null && repdir != null)
{
loadRepositoryTrans(transName, repdir);
wTransName.setText(mappingTransMeta.getName());
wTransDir.setText(mappingTransMeta.getDirectory().getPath());
wFilename.setText("");
wRepRadio.setSelection(true);
wFileRadio.setSelection(false);
}
} catch (KettleException ke)
{
new ErrorDialog(
shell,
Messages.getString("MappingDialog.ErrorSelectingObject.DialogTitle"), Messages.getString("MappingDialog.ErrorSelectingObject.DialogMessage"), ke); //$NON-NLS-1$ //$NON-NLS-2$
}
}
private void loadRepositoryTrans(String transName, RepositoryDirectory repdir) throws KettleException
{
// Read the transformation...
//
mappingTransMeta = new TransMeta(repository, transMeta.environmentSubstitute(transName), repdir);
mappingTransMeta.clearChanged();
}
private void selectFileTrans()
{
String curFile = wFilename.getText();
FileObject root = null;
try
{
root = KettleVFS.getFileObject(curFile != null ? curFile : Const.USER_HOME_DIRECTORY);
VfsFileChooserDialog vfsFileChooser = new VfsFileChooserDialog(root.getParent(), root);
FileObject file = vfsFileChooser.open(shell, null, Const.STRING_TRANS_FILTER_EXT, Const
.getTransformationFilterNames(), VfsFileChooserDialog.VFS_DIALOG_OPEN_FILE);
if (file == null) {
return;
}
String fname = null;
fname = file.getURL().getFile();
if (fname != null)
{
loadFileTrans(fname);
wFilename.setText(mappingTransMeta.getFilename());
wTransName.setText(Const.NVL(mappingTransMeta.getName(), ""));
wTransDir.setText("");
wFileRadio.setSelection(true);
wRepRadio.setSelection(false);
}
} catch (IOException e)
{
new ErrorDialog(
shell,
Messages.getString("MappingDialog.ErrorLoadingTransformation.DialogTitle"), Messages.getString("MappingDialog.ErrorLoadingTransformation.DialogMessage"), e); //$NON-NLS-1$ //$NON-NLS-2$
} catch (KettleException e)
{
new ErrorDialog(
shell,
Messages.getString("MappingDialog.ErrorLoadingTransformation.DialogTitle"), Messages.getString("MappingDialog.ErrorLoadingTransformation.DialogMessage"), e); //$NON-NLS-1$ //$NON-NLS-2$
}
}
private void loadFileTrans(String fname) throws KettleException
{
mappingTransMeta = new TransMeta(transMeta.environmentSubstitute(fname));
mappingTransMeta.clearChanged();
}
private void editTrans()
{
// Load the transformation again to make sure it's still there and
// refreshed
// It's an extra check to make sure it's still OK...
try
{
loadTransformation();
// If we're still here, mappingTransMeta is valid.
SpoonInterface spoon = SpoonFactory.getInstance();
if (spoon != null)
{
spoon.addTransGraph(mappingTransMeta);
}
} catch (KettleException e)
{
new ErrorDialog(shell, Messages.getString("MappingDialog.ErrorShowingTransformation.Title"),
Messages.getString("MappingDialog.ErrorShowingTransformation.Message"), e);
}
}
private void loadTransformation() throws KettleException
{
if (wFileRadio.getSelection() && !Const.isEmpty(wFilename.getText())) // Read
// from
// file...
{
loadFileTrans(wFilename.getText());
} else
{
if (wRepRadio.getSelection() && repository != null && !Const.isEmpty(wTransName.getText())
&& !Const.isEmpty(wTransDir.getText()))
{
RepositoryDirectory repdir = repository.getDirectoryTree().findDirectory(wTransDir.getText());
if (repdir == null)
{
throw new KettleException(Messages.getString("MappingDialog.Exception.UnableToFindRepositoryDirectory)"));
}
loadRepositoryTrans(wTransName.getText(), repdir);
} else
{
throw new KettleException(Messages.getString("MappingDialog.Exception.NoValidMappingDetailsFound"));
}
}
}
/**
* Copy information from the meta-data input to the dialog fields.
*/
public void getData()
{
wStepname.selectAll();
wFilename.setText(Const.NVL(mappingMeta.getFileName(), ""));
wTransName.setText(Const.NVL(mappingMeta.getTransName(), ""));
wTransDir.setText(Const.NVL(mappingMeta.getDirectoryPath(), ""));
// if we have a filename, then we use the filename, otherwise we go with
// the repository...
wFileRadio.setSelection(false);
wRepRadio.setSelection(false);
if (!Const.isEmpty(mappingMeta.getFileName()))
{
wFileRadio.setSelection(true);
} else
{
if (repository != null && !Const.isEmpty(mappingMeta.getTransName())
&& !Const.isEmpty(mappingMeta.getDirectoryPath()))
{
wRepRadio.setSelection(true);
}
}
setFlags();
// Add the parameters tab
addParametersTab(mappingParameters);
wTabFolder.setSelection(0);
// Now add the input stream tabs: where is our data coming from?
for (int i = 0; i < inputMappings.size(); i++)
{
addInputMappingDefinitionTab(inputMappings.get(i), i);
}
// Now add the output stream tabs: where is our data going to?
for (int i = 0; i < outputMappings.size(); i++)
{
addOutputMappingDefinitionTab(outputMappings.get(i), i);
}
try
{
loadTransformation();
} catch (Throwable t)
{
}
}
private void addOutputMappingDefinitionTab(MappingIODefinition definition, int index)
{
addMappingDefinitionTab(outputMappings.get(index), index + 1 + inputMappings.size(),
Messages.getString("MappingDialog.OutputTab.Title"),
Messages.getString("MappingDialog.InputTab.Tooltip"),
Messages.getString("MappingDialog.OutputTab.label.InputSourceStepName"),
Messages.getString("MappingDialog.OutputTab.label.OutputTargetStepName"),
Messages.getString("MappingDialog.OutputTab.label.Description"),
Messages.getString("MappingDialog.OutputTab.column.SourceField"),
Messages.getString("MappingDialog.OutputTab.column.TargetField"), false);
}
private void addInputMappingDefinitionTab(MappingIODefinition definition, int index)
{
addMappingDefinitionTab(definition, index + 1, Messages.getString("MappingDialog.InputTab.Title"),
Messages.getString("MappingDialog.InputTab.Tooltip"),
Messages.getString("MappingDialog.InputTab.label.InputSourceStepName"),
Messages.getString("MappingDialog.InputTab.label.OutputTargetStepName"),
Messages.getString("MappingDialog.InputTab.label.Description"),
Messages.getString("MappingDialog.InputTab.column.SourceField"),
Messages.getString("MappingDialog.InputTab.column.TargetField"), true);
}
private void addParametersTab(final MappingParameters parameters)
{
CTabItem wParametersTab = new CTabItem(wTabFolder, SWT.NONE);
wParametersTab.setText(Messages.getString("MappingDialog.Parameters.Title")); //$NON-NLS-1$
wParametersTab.setToolTipText(Messages.getString("MappingDialog.Parameters.Tooltip")); //$NON-NLS-1$
Composite wParametersComposite = new Composite(wTabFolder, SWT.NONE);
props.setLook(wParametersComposite);
FormLayout parameterTabLayout = new FormLayout();
parameterTabLayout.marginWidth = Const.FORM_MARGIN;
parameterTabLayout.marginHeight = Const.FORM_MARGIN;
wParametersComposite.setLayout(parameterTabLayout);
// Now add a tableview with the 2 columns to specify: input and output
// fields for the source and target steps.
//
ColumnInfo[] colinfo = new ColumnInfo[] {
new ColumnInfo(
Messages.getString("MappingDialog.Parameters.column.Variable"), ColumnInfo.COLUMN_TYPE_TEXT, false, false), //$NON-NLS-1$
new ColumnInfo(
Messages.getString("MappingDialog.Parameters.column.ValueOrField"), ColumnInfo.COLUMN_TYPE_TEXT, false, false), //$NON-NLS-1$
};
colinfo[1].setUsingVariables(true);
final TableView wMappingParameters = new TableView(transMeta, wParametersComposite,
SWT.FULL_SELECTION | SWT.SINGLE | SWT.BORDER, colinfo, parameters.getVariable().length,
lsMod, props);
props.setLook(wMappingParameters);
FormData fdMappings = new FormData();
fdMappings.left = new FormAttachment(0, 0);
fdMappings.right = new FormAttachment(100, 0);
fdMappings.top = new FormAttachment(0, 0);
fdMappings.bottom = new FormAttachment(100, -30);
wMappingParameters.setLayoutData(fdMappings);
for (int i = 0; i < parameters.getVariable().length; i++)
{
TableItem tableItem = wMappingParameters.table.getItem(i);
tableItem.setText(1, parameters.getVariable()[i]);
tableItem.setText(2, parameters.getInputField()[i]);
}
wMappingParameters.setRowNums();
wMappingParameters.optWidth(true);
FormData fdParametersComposite = new FormData();
fdParametersComposite.left = new FormAttachment(0, 0);
fdParametersComposite.top = new FormAttachment(0, 0);
fdParametersComposite.right = new FormAttachment(100, 0);
fdParametersComposite.bottom = new FormAttachment(100, 0);
wParametersComposite.setLayoutData(fdParametersComposite);
wParametersComposite.layout();
wParametersTab.setControl(wParametersComposite);
changeList.add(new MappingParametersTab(wMappingParameters, parameters));
}
protected String selectTransformationStepname(boolean getTransformationStep, boolean mappingInput)
{
String dialogTitle = Messages.getString("MappingDialog.SelectTransStep.Title");
String dialogMessage = Messages.getString("MappingDialog.SelectTransStep.Message");
if (getTransformationStep)
{
dialogTitle = Messages.getString("MappingDialog.SelectTransStep.Title");
dialogMessage = Messages.getString("MappingDialog.SelectTransStep.Message");
String[] stepnames;
if (mappingInput)
{
stepnames = transMeta.getPrevStepNames(stepMeta);
} else
{
stepnames = transMeta.getNextStepNames(stepMeta);
}
EnterSelectionDialog dialog = new EnterSelectionDialog(shell, stepnames, dialogTitle,
dialogMessage);
return dialog.open();
} else
{
dialogTitle = Messages.getString("MappingDialog.SelectMappingStep.Title");
dialogMessage = Messages.getString("MappingDialog.SelectMappingStep.Message");
String[] stepnames = getMappingSteps(mappingTransMeta, mappingInput);
EnterSelectionDialog dialog = new EnterSelectionDialog(shell, stepnames, dialogTitle,
dialogMessage);
return dialog.open();
}
}
public static String[] getMappingSteps(TransMeta mappingTransMeta, boolean mappingInput)
{
List<StepMeta> steps = new ArrayList<StepMeta>();
for (StepMeta stepMeta : mappingTransMeta.getSteps())
{
if (mappingInput && stepMeta.getStepID().equals("MappingInput"))
{
steps.add(stepMeta);
}
if (!mappingInput && stepMeta.getStepID().equals("MappingOutput"))
{
steps.add(stepMeta);
}
}
String[] stepnames = new String[steps.size()];
for (int i = 0; i < stepnames.length; i++)
stepnames[i] = steps.get(i).getName();
return stepnames;
}
public RowMetaInterface getFieldsFromStep(String stepname, boolean getTransformationStep,
boolean mappingInput) throws KettleException
{
if (!(mappingInput ^ getTransformationStep))
{
if (Const.isEmpty(stepname))
{
// If we don't have a specified stepname we return the input row
// metadata
//
return transMeta.getPrevStepFields(this.stepname);
} else
{
// OK, a fieldname is specified...
// See if we can find it...
StepMeta stepMeta = transMeta.findStep(stepname);
if (stepMeta == null)
{
throw new KettleException(Messages.getString("MappingDialog.Exception.SpecifiedStepWasNotFound", stepname));
}
return transMeta.getStepFields(stepMeta);
}
} else
{
if (Const.isEmpty(stepname))
{
// If we don't have a specified stepname we select the one and
// only "mapping input" step.
//
String[] stepnames = getMappingSteps(mappingTransMeta, mappingInput);
if (stepnames.length > 1)
{
throw new KettleException(Messages.getString("MappingDialog.Exception.OnlyOneMappingInputStepAllowed", "" + stepnames.length));
}
if (stepnames.length == 0)
{
throw new KettleException(Messages.getString("MappingDialog.Exception.OneMappingInputStepRequired", "" + stepnames.length));
}
return mappingTransMeta.getStepFields(stepnames[0]);
} else
{
// OK, a fieldname is specified...
// See if we can find it...
StepMeta stepMeta = mappingTransMeta.findStep(stepname);
if (stepMeta == null)
{
throw new KettleException(Messages.getString("MappingDialog.Exception.SpecifiedStepWasNotFound", stepname));
}
return mappingTransMeta.getStepFields(stepMeta);
}
}
}
private void addMappingDefinitionTab(final MappingIODefinition definition, int index,
final String tabTitle, final String tabTooltip, String inputStepLabel, String outputStepLabel,
String descriptionLabel, String sourceColumnLabel, String targetColumnLabel, final boolean input)
{
final CTabItem wTab;
if (index >= wTabFolder.getItemCount())
{
wTab = new CTabItem(wTabFolder, SWT.CLOSE);
} else
{
wTab = new CTabItem(wTabFolder, SWT.CLOSE, index);
}
setMappingDefinitionTabNameAndToolTip(wTab, tabTitle, tabTooltip, definition, input);
Composite wInputComposite = new Composite(wTabFolder, SWT.NONE);
props.setLook(wInputComposite);
FormLayout tabLayout = new FormLayout();
tabLayout.marginWidth = Const.FORM_MARGIN;
tabLayout.marginHeight = Const.FORM_MARGIN;
wInputComposite.setLayout(tabLayout);
// What's the stepname to read from? (empty is OK too)
//
Button wbInputStep = new Button(wInputComposite, SWT.PUSH);
props.setLook(wbInputStep);
wbInputStep.setText(Messages.getString("MappingDialog.button.SourceStepName"));
FormData fdbInputStep = new FormData();
fdbInputStep.top = new FormAttachment(0, 0);
fdbInputStep.right = new FormAttachment(100, 0); // First one in the
// left top corner
wbInputStep.setLayoutData(fdbInputStep);
Label wlInputStep = new Label(wInputComposite, SWT.RIGHT);
props.setLook(wlInputStep);
wlInputStep.setText(inputStepLabel); //$NON-NLS-1$
FormData fdlInputStep = new FormData();
fdlInputStep.top = new FormAttachment(wbInputStep, 0, SWT.CENTER);
fdlInputStep.left = new FormAttachment(0, 0); // First one in the left
// top corner
fdlInputStep.right = new FormAttachment(middle, -margin);
wlInputStep.setLayoutData(fdlInputStep);
final Text wInputStep = new Text(wInputComposite, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wInputStep);
wInputStep.setText(Const.NVL(definition.getInputStepname(), ""));
wInputStep.addModifyListener(lsMod);
FormData fdInputStep = new FormData();
fdInputStep.top = new FormAttachment(wbInputStep, 0, SWT.CENTER);
fdInputStep.left = new FormAttachment(middle, 0); // To the right of
// the label
fdInputStep.right = new FormAttachment(wbInputStep, -margin);
wInputStep.setLayoutData(fdInputStep);
wInputStep.addFocusListener(new FocusAdapter()
{
@Override
public void focusLost(FocusEvent event)
{
definition.setInputStepname(wInputStep.getText());
setMappingDefinitionTabNameAndToolTip(wTab, tabTitle, tabTooltip, definition, input);
}
});
wbInputStep.addSelectionListener(new SelectionAdapter()
{
@Override
public void widgetSelected(SelectionEvent event)
{
String stepName = selectTransformationStepname(input, input);
if (stepName != null)
{
wInputStep.setText(stepName);
definition.setInputStepname(stepName);
setMappingDefinitionTabNameAndToolTip(wTab, tabTitle, tabTooltip, definition, input);
}
}
});
// What's the step name to read from? (empty is OK too)
//
Button wbOutputStep = new Button(wInputComposite, SWT.PUSH);
props.setLook(wbOutputStep);
wbOutputStep.setText(Messages.getString("MappingDialog.button.SourceStepName"));
FormData fdbOutputStep = new FormData();
fdbOutputStep.top = new FormAttachment(wbInputStep, margin);
fdbOutputStep.right = new FormAttachment(100, 0);
wbOutputStep.setLayoutData(fdbOutputStep);
Label wlOutputStep = new Label(wInputComposite, SWT.RIGHT);
props.setLook(wlOutputStep);
wlOutputStep.setText(outputStepLabel); //$NON-NLS-1$
FormData fdlOutputStep = new FormData();
fdlOutputStep.top = new FormAttachment(wbOutputStep, 0, SWT.CENTER);
fdlOutputStep.left = new FormAttachment(0, 0);
fdlOutputStep.right = new FormAttachment(middle, -margin);
wlOutputStep.setLayoutData(fdlOutputStep);
final Text wOutputStep = new Text(wInputComposite, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wOutputStep);
wOutputStep.setText(Const.NVL(definition.getOutputStepname(), ""));
wOutputStep.addModifyListener(lsMod);
FormData fdOutputStep = new FormData();
fdOutputStep.top = new FormAttachment(wbOutputStep, 0, SWT.CENTER);
fdOutputStep.left = new FormAttachment(middle, 0); // To the right of
// the label
fdOutputStep.right = new FormAttachment(wbOutputStep, -margin);
wOutputStep.setLayoutData(fdOutputStep);
// Add a checkbox to indicate the main step to read from, the main data
// path...
//
Label wlMainPath = new Label(wInputComposite, SWT.RIGHT);
props.setLook(wlMainPath);
wlMainPath.setText(Messages.getString("MappingDialog.input.MainDataPath")); //$NON-NLS-1$
FormData fdlMainPath = new FormData();
fdlMainPath.top = new FormAttachment(wbOutputStep, margin);
fdlMainPath.left = new FormAttachment(0, 0);
fdlMainPath.right = new FormAttachment(middle, -margin);
wlMainPath.setLayoutData(fdlMainPath);
Button wMainPath = new Button(wInputComposite, SWT.CHECK);
props.setLook(wMainPath);
FormData fdMainPath = new FormData();
fdMainPath.top = new FormAttachment(wbOutputStep, margin);
fdMainPath.left = new FormAttachment(middle, 0);
// fdMainPath.right = new FormAttachment(100, 0); // who cares, it's a
// checkbox
wMainPath.setLayoutData(fdMainPath);
wMainPath.setSelection(definition.isMainDataPath());
wMainPath.addSelectionListener(new SelectionAdapter()
{
@Override
public void widgetSelected(SelectionEvent event)
{
definition.setMainDataPath(!definition.isMainDataPath()); // flip
// the
// switch
}
});
// Add a checkbox to indicate that all output mappings need to rename
// the values back...
//
Label wlRenameOutput = new Label(wInputComposite, SWT.RIGHT);
props.setLook(wlRenameOutput);
wlRenameOutput.setText(Messages.getString("MappingDialog.input.RenamingOnOutput")); //$NON-NLS-1$
FormData fdlRenameOutput = new FormData();
fdlRenameOutput.top = new FormAttachment(wMainPath, margin);
fdlRenameOutput.left = new FormAttachment(0, 0);
fdlRenameOutput.right = new FormAttachment(middle, -margin);
wlRenameOutput.setLayoutData(fdlRenameOutput);
Button wRenameOutput = new Button(wInputComposite, SWT.CHECK);
props.setLook(wRenameOutput);
FormData fdRenameOutput = new FormData();
fdRenameOutput.top = new FormAttachment(wMainPath, margin);
fdRenameOutput.left = new FormAttachment(middle, 0);
// fdRenameOutput.right = new FormAttachment(100, 0); // who cares, it's
// a check box
wRenameOutput.setLayoutData(fdRenameOutput);
wRenameOutput.setSelection(definition.isRenamingOnOutput());
wRenameOutput.addSelectionListener(new SelectionAdapter()
{
@Override
public void widgetSelected(SelectionEvent event)
{
definition.setRenamingOnOutput(!definition.isRenamingOnOutput()); // flip
// the
// switch
}
});
// Allow for a small description
//
Label wlDescription = new Label(wInputComposite, SWT.RIGHT);
props.setLook(wlDescription);
wlDescription.setText(descriptionLabel); //$NON-NLS-1$
FormData fdlDescription = new FormData();
fdlDescription.top = new FormAttachment(wRenameOutput, margin);
fdlDescription.left = new FormAttachment(0, 0); // First one in the left
// top corner
fdlDescription.right = new FormAttachment(middle, -margin);
wlDescription.setLayoutData(fdlDescription);
final Text wDescription = new Text(wInputComposite, SWT.MULTI | SWT.LEFT | SWT.BORDER | SWT.V_SCROLL
| SWT.H_SCROLL);
props.setLook(wDescription);
wDescription.setText(Const.NVL(definition.getDescription(), ""));
wDescription.addModifyListener(lsMod);
FormData fdDescription = new FormData();
fdDescription.top = new FormAttachment(wRenameOutput, margin);
fdDescription.bottom = new FormAttachment(wRenameOutput, 100 + margin);
fdDescription.left = new FormAttachment(middle, 0); // To the right of
// the label
fdDescription.right = new FormAttachment(wbOutputStep, -margin);
wDescription.setLayoutData(fdDescription);
wDescription.addFocusListener(new FocusAdapter()
{
@Override
public void focusLost(FocusEvent event)
{
definition.setDescription(wDescription.getText());
}
});
// Now add a table view with the 2 columns to specify: input and output
// fields for the source and target steps.
//
final Button wbEnterMapping = new Button(wInputComposite, SWT.PUSH);
props.setLook(wbEnterMapping);
wbEnterMapping.setText(Messages.getString("MappingDialog.button.EnterMapping"));
FormData fdbEnterMapping = new FormData();
fdbEnterMapping.top = new FormAttachment(wDescription, margin * 2);
fdbEnterMapping.right = new FormAttachment(100, 0); // First one in the
// left top corner
wbEnterMapping.setLayoutData(fdbEnterMapping);
ColumnInfo[] colinfo = new ColumnInfo[] {
new ColumnInfo(sourceColumnLabel, ColumnInfo.COLUMN_TYPE_TEXT, false, false), //$NON-NLS-1$
new ColumnInfo(targetColumnLabel, ColumnInfo.COLUMN_TYPE_TEXT, false, false), //$NON-NLS-1$
};
final TableView wFieldMappings = new TableView(transMeta, wInputComposite, SWT.FULL_SELECTION
| SWT.SINGLE | SWT.BORDER, colinfo, 1, lsMod, props);
props.setLook(wFieldMappings);
FormData fdMappings = new FormData();
fdMappings.left = new FormAttachment(0, 0);
fdMappings.right = new FormAttachment(wbEnterMapping, -margin);
fdMappings.top = new FormAttachment(wDescription, margin * 2);
fdMappings.bottom = new FormAttachment(100, -20);
wFieldMappings.setLayoutData(fdMappings);
for (MappingValueRename valueRename : definition.getValueRenames())
{
TableItem tableItem = new TableItem(wFieldMappings.table, SWT.NONE);
tableItem.setText(1, valueRename.getSourceValueName());
tableItem.setText(2, valueRename.getTargetValueName());
}
wFieldMappings.removeEmptyRows();
wFieldMappings.setRowNums();
wFieldMappings.optWidth(true);
wbEnterMapping.addSelectionListener(new SelectionAdapter()
{
@Override
public void widgetSelected(SelectionEvent arg0)
{
try
{
RowMetaInterface sourceRowMeta = getFieldsFromStep(wInputStep.getText(), true, input);
RowMetaInterface targetRowMeta = getFieldsFromStep(wOutputStep.getText(), false, input);
String sourceFields[] = sourceRowMeta.getFieldNames();
String targetFields[] = targetRowMeta.getFieldNames();
EnterMappingDialog dialog = new EnterMappingDialog(shell, sourceFields, targetFields);
List<SourceToTargetMapping> mappings = dialog.open();
if (mappings != null)
{
// first clear the dialog...
wFieldMappings.clearAll(false);
//
definition.getValueRenames().clear();
// Now add the new values...
for (int i = 0; i < mappings.size(); i++)
{
SourceToTargetMapping mapping = mappings.get(i);
TableItem item = new TableItem(wFieldMappings.table, SWT.NONE);
item.setText(1, mapping.getSourceString(sourceFields));
item.setText(2, mapping.getTargetString(targetFields));
String source = input ? item.getText(1) : item.getText(2);
String target = input ? item.getText(2) : item.getText(1);
definition.getValueRenames().add(new MappingValueRename(source, target));
}
wFieldMappings.removeEmptyRows();
wFieldMappings.setRowNums();
wFieldMappings.optWidth(true);
}
} catch (KettleException e)
{
new ErrorDialog(shell, Messages.getString("System.Dialog.Error.Title"), Messages.getString("MappingDialog.Exception.ErrorGettingMappingSourceAndTargetFields", e.toString()), e);
}
}
});
wOutputStep.addFocusListener(new FocusAdapter()
{
@Override
public void focusLost(FocusEvent event)
{
definition.setOutputStepname(wOutputStep.getText());
try
{
enableMappingButton(wbEnterMapping, input, wInputStep.getText(), wOutputStep.getText());
} catch (KettleException e)
{
// Show the missing/wrong step name error
//
new ErrorDialog(shell, "Error", "Unexpected error", e);
}
}
});
wbOutputStep.addSelectionListener(new SelectionAdapter()
{
@Override
public void widgetSelected(SelectionEvent event)
{
String stepName = selectTransformationStepname(!input, input);
if (stepName != null)
{
wOutputStep.setText(stepName);
definition.setOutputStepname(stepName);
try
{
enableMappingButton(wbEnterMapping, input, wInputStep.getText(), wOutputStep
.getText());
} catch (KettleException e)
{
// Show the missing/wrong stepname error
new ErrorDialog(shell, "Error", "Unexpected error", e);
}
}
}
});
FormData fdParametersComposite = new FormData();
fdParametersComposite.left = new FormAttachment(0, 0);
fdParametersComposite.top = new FormAttachment(0, 0);
fdParametersComposite.right = new FormAttachment(100, 0);
fdParametersComposite.bottom = new FormAttachment(100, 0);
wInputComposite.setLayoutData(fdParametersComposite);
wInputComposite.layout();
wTab.setControl(wInputComposite);
final ApplyChanges applyChanges = new MappingDefinitionTab(definition, wInputStep, wOutputStep,
wMainPath, wDescription, wFieldMappings);
changeList.add(applyChanges);
// OK, suppose for some weird reason the user wants to remove an input
// or output tab...
wTabFolder.addCTabFolder2Listener(new CTabFolder2Adapter()
{
@Override
public void close(CTabFolderEvent event)
{
if (event.item.equals(wTab))
{
// The user has the audacity to try and close this mapping
// definition tab.
// We really should warn him that this is a bad idea...
MessageBox box = new MessageBox(shell, SWT.YES | SWT.NO);
box.setText(Messages.getString("MappingDialog.CloseDefinitionTabAreYouSure.Title"));
box.setMessage(Messages.getString("MappingDialog.CloseDefinitionTabAreYouSure.Message"));
int answer = box.open();
if (answer != SWT.YES)
{
event.doit = false;
} else
{
// Remove it from our list to make sure it's gone...
if (input)
inputMappings.remove(definition);
else
outputMappings.remove(definition);
// remove it from the changeList too...
// Otherwise the dialog leaks memory.
//
changeList.remove(applyChanges);
}
}
}
});
wTabFolder.setSelection(wTab);
}
/**
* Enables or disables the mapping button. We can only enable it if the
* target steps allows a mapping to be made against it.
*
* @param button
* The button to disable or enable
* @param input
* input or output. If it's true, we keep the button enabled all
* the time.
* @param sourceStepname
* The mapping output step
* @param targetStepname
* The target step to verify
* @throws KettleException
*/
private void enableMappingButton(final Button button, boolean input, String sourceStepname,
String targetStepname) throws KettleException
{
if (input)
return; // nothing to do
boolean enabled = false;
if (mappingTransMeta != null)
{
StepMeta mappingInputStep = mappingTransMeta.findMappingInputStep(sourceStepname);
if (mappingInputStep != null)
{
StepMeta mappingOutputStep = transMeta.findMappingOutputStep(targetStepname);
RowMetaInterface requiredFields = mappingOutputStep.getStepMetaInterface()
.getRequiredFields();
if (requiredFields != null && requiredFields.size() > 0)
{
enabled = true;
}
}
}
button.setEnabled(enabled);
}
private void setMappingDefinitionTabNameAndToolTip(CTabItem wTab, String tabTitle, String tabTooltip,
MappingIODefinition definition, boolean input)
{
String stepname;
if (input)
{
stepname = definition.getInputStepname();
} else
{
stepname = definition.getOutputStepname();
}
String description = definition.getDescription();
if (Const.isEmpty(stepname))
{
wTab.setText(tabTitle); //$NON-NLS-1$
} else
{
wTab.setText(tabTitle + " : " + stepname); //$NON-NLS-1$ $NON-NLS-2$
}
String tooltip = tabTooltip; //$NON-NLS-1$
if (!Const.isEmpty(stepname))
{
tooltip += Const.CR + Const.CR + stepname;
}
if (!Const.isEmpty(description))
{
tooltip += Const.CR + Const.CR + description;
}
wTab.setToolTipText(tooltip); //$NON-NLS-1$
}
private void setFlags()
{
if (repository == null)
{
wRepRadio.setEnabled(false);
wbTrans.setEnabled(false);
wTransName.setEnabled(false);
wTransDir.setEnabled(false);
}
}
private void cancel()
{
stepname = null;
mappingMeta.setChanged(changed);
dispose();
}
private void ok()
{
if (Const.isEmpty(wStepname.getText())) return;
try
{
stepname = wStepname.getText(); // return value
loadTransformation();
mappingMeta.setFileName(wFilename.getText());
mappingMeta.setTransName(wTransName.getText());
mappingMeta.setDirectoryPath(wTransDir.getText());
// Load the information on the tabs, optionally do some
// verifications...
//
collectInformation();
mappingMeta.setMappingParameters(mappingParameters);
mappingMeta.setInputMappings(inputMappings);
mappingMeta.setOutputMappings(outputMappings);
mappingMeta.setChanged(true);
dispose();
} catch (KettleException e)
{
new ErrorDialog(shell, Messages.getString("MappingDialog.ErrorLoadingSpecifiedTransformation.Title"), Messages.getString("MappingDialog.ErrorLoadingSpecifiedTransformation.Message"), e);
}
}
private void collectInformation()
{
for (ApplyChanges applyChanges : changeList)
{
applyChanges.applyChanges(); // collect information from all
// tabs...
}
}
}
|
PDI-1425 : Unexpected error thrown from Spoon whilst trying to map Access fields to MySQL fields
git-svn-id: 51b39fcfd0d3a6ea7caa15377cad4af13b9d2664@8416 5fb7f6ec-07c1-534a-b4ca-9155e429e800
|
src-ui/org/pentaho/di/ui/trans/steps/mapping/MappingDialog.java
|
PDI-1425 : Unexpected error thrown from Spoon whilst trying to map Access fields to MySQL fields
|
<ide><path>rc-ui/org/pentaho/di/ui/trans/steps/mapping/MappingDialog.java
<ide> return transMeta.getStepFields(stepMeta);
<ide> }
<ide>
<del> } else
<add> }
<add> else
<ide> {
<ide> if (Const.isEmpty(stepname))
<ide> {
<ide> throw new KettleException(Messages.getString("MappingDialog.Exception.OneMappingInputStepRequired", "" + stepnames.length));
<ide> }
<ide> return mappingTransMeta.getStepFields(stepnames[0]);
<del> } else
<add> }
<add> else
<ide> {
<ide> // OK, a fieldname is specified...
<ide> // See if we can find it...
<ide> {
<ide> try
<ide> {
<add> loadTransformation();
<ide> RowMetaInterface sourceRowMeta = getFieldsFromStep(wInputStep.getText(), true, input);
<ide> RowMetaInterface targetRowMeta = getFieldsFromStep(wOutputStep.getText(), false, input);
<ide> String sourceFields[] = sourceRowMeta.getFieldNames();
|
|
Java
|
lgpl-2.1
|
d85244e4e9c376082a76372adad98ea257e08136
| 0 |
threerings/narya,threerings/narya,threerings/narya,threerings/narya,threerings/narya
|
//
// $Id$
//
// Narya library - tools for developing networked games
// Copyright (C) 2002-2007 Three Rings Design, Inc., All Rights Reserved
// http://www.threerings.net/code/narya/
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.threerings.crowd.chat.client;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.samskivert.util.Collections;
import com.samskivert.util.HashIntMap;
import com.samskivert.util.ObserverList;
import com.samskivert.util.ResultListener;
import com.samskivert.util.StringUtil;
import com.threerings.util.MessageBundle;
import com.threerings.util.MessageManager;
import com.threerings.util.Name;
import com.threerings.util.TimeUtil;
import com.threerings.presents.client.BasicDirector;
import com.threerings.presents.client.Client;
import com.threerings.presents.data.ClientObject;
import com.threerings.presents.dobj.DObject;
import com.threerings.presents.dobj.MessageEvent;
import com.threerings.presents.dobj.MessageListener;
import com.threerings.crowd.chat.data.ChatCodes;
import com.threerings.crowd.chat.data.ChatMessage;
import com.threerings.crowd.chat.data.SystemMessage;
import com.threerings.crowd.chat.data.TellFeedbackMessage;
import com.threerings.crowd.chat.data.UserMessage;
import com.threerings.crowd.chat.data.UserSystemMessage;
import com.threerings.crowd.client.LocationObserver;
import com.threerings.crowd.data.BodyObject;
import com.threerings.crowd.data.CrowdCodes;
import com.threerings.crowd.data.PlaceObject;
import com.threerings.crowd.util.CrowdContext;
import static com.threerings.crowd.Log.log;
/**
* The chat director is the client side coordinator of all chat related services. It handles both
* place constrained chat as well as direct messaging.
*/
public class ChatDirector extends BasicDirector
implements ChatCodes, LocationObserver, MessageListener
{
/**
* An interface to receive information about the {@link #MAX_CHATTERS} most recent users that
* we've been chatting with.
*/
public static interface ChatterObserver
{
/**
* Called when the list of chatters has been changed.
*/
void chattersUpdated (Iterator<Name> chatternames);
}
/**
* An interface for those who would like to validate whether usernames may be added to the
* chatter list.
*/
public static interface ChatterValidator
{
/**
* Returns whether the username may be added to the chatters list.
*/
boolean isChatterValid (Name username);
}
/**
* Used to implement a slash command (e.g. <code>/who</code>).
*/
public abstract static class CommandHandler
{
/**
* Handles the specified chat command.
*
* @param speakSvc an optional SpeakService object representing the object to send the chat
* message on.
* @param command the slash command that was used to invoke this handler
* (e.g. <code>/tell</code>).
* @param args the arguments provided along with the command (e.g. <code>Bob hello</code>)
* or <code>null</code> if no arguments were supplied.
* @param history an in/out parameter that allows the command to modify the text that will
* be appended to the chat history. If this is set to null, nothing will be appended.
*
* @return an untranslated string that will be reported to the chat box to convey an error
* response to the user, or {@link ChatCodes#SUCCESS}.
*/
public abstract String handleCommand (SpeakService speakSvc, String command, String args,
String[] history);
/**
* Returns true if this user should have access to this chat command.
*/
public boolean checkAccess (BodyObject user) {
return true;
}
}
/**
* Creates a chat director and initializes it with the supplied context. The chat director will
* register itself as a location observer so that it can automatically process place
* constrained chat.
*
* @param msgmgr the message manager via which we do our translations.
* @param bundle the message bundle from which we obtain our chat-related translation strings.
*/
public ChatDirector (CrowdContext ctx, MessageManager msgmgr, String bundle)
{
super(ctx);
// keep the context around
_ctx = ctx;
_msgmgr = msgmgr;
_bundle = bundle;
// register ourselves as a location observer
_ctx.getLocationDirector().addLocationObserver(this);
// register our default chat handlers
if (_bundle == null || _msgmgr == null) {
log.warning("Null bundle or message manager given to ChatDirector");
return;
}
registerCommandHandlers();
}
/**
* Registers all the chat-command handlers.
*/
protected void registerCommandHandlers ()
{
MessageBundle msg = _msgmgr.getBundle(_bundle);
registerCommandHandler(msg, "help", new HelpHandler());
registerCommandHandler(msg, "clear", new ClearHandler());
registerCommandHandler(msg, "speak", new SpeakHandler());
registerCommandHandler(msg, "emote", new EmoteHandler());
registerCommandHandler(msg, "think", new ThinkHandler());
registerCommandHandler(msg, "tell", new TellHandler());
registerCommandHandler(msg, "broadcast", new BroadcastHandler());
}
/**
* Adds the supplied chat display to the front of the chat display list. It will subsequently
* be notified of incoming chat messages as well as tell responses.
*/
public void pushChatDisplay (ChatDisplay display)
{
_displays.add(0, display);
}
/**
* Adds the supplied chat display to the end of the chat display list. It will subsequently be
* notified of incoming chat messages as well as tell responses.
*/
public void addChatDisplay (ChatDisplay display)
{
_displays.add(display);
}
/**
* Removes the specified chat display from the chat display list. The display will no longer
* receive chat related notifications.
*/
public void removeChatDisplay (ChatDisplay display)
{
_displays.remove(display);
}
/**
* Adds the specified chat filter to the list of filters. All chat requests and receipts will
* be filtered with all filters before they being sent or dispatched locally.
*/
public void addChatFilter (ChatFilter filter)
{
_filters.add(filter);
}
/**
* Removes the specified chat filter from the list of chat filter.
*/
public void removeChatFilter (ChatFilter filter)
{
_filters.remove(filter);
}
/**
* Adds an observer that watches the chatters list, and updates it immediately.
*/
public void addChatterObserver (ChatterObserver co)
{
_chatterObservers.add(co);
co.chattersUpdated(_chatters.listIterator());
}
/**
* Removes an observer from the list of chatter observers.
*/
public void removeChatterObserver (ChatterObserver co)
{
_chatterObservers.remove(co);
}
/**
* Sets the validator that decides if a username is valid to be added to the chatter list, or
* null if no such filtering is desired.
*/
public void setChatterValidator (ChatterValidator validator)
{
_chatterValidator = validator;
}
/**
* Enables or disables the chat mogrifier. The mogrifier converts chat speak like LOL, WTF,
* etc. into phrases, words and can also transform them into emotes. The mogrifier is
* configured via the <code>x.mogrifies</code> and <code>x.transforms</code> translation
* properties.
*/
public void setMogrifyChat (boolean mogrifyChat)
{
_mogrifyChat = mogrifyChat;
}
/**
* Registers a chat command handler.
*
* @param msg the message bundle via which the slash command will be translated (as
* <code>c.</code><i>command</i>). If no translation exists the command will be
* <code>/</code><i>command</i>.
* @param command the name of the command that will be used to invoke this handler (e.g.
* <code>tell</code> if the command will be invoked as <code>/tell</code>).
* @param handler the chat command handler itself.
*/
public void registerCommandHandler (MessageBundle msg, String command, CommandHandler handler)
{
String key = "c." + command;
if (msg.exists(key)) {
StringTokenizer st = new StringTokenizer(msg.get(key));
while (st.hasMoreTokens()) {
_handlers.put(st.nextToken(), handler);
}
} else {
// fall back to just using the English command
_handlers.put(command, handler);
}
}
/**
* Return the current size of the history.
*/
public int getCommandHistorySize ()
{
return _history.size();
}
/**
* Get the chat history entry at the specified index, with 0 being the oldest.
*/
public String getCommandHistory (int index)
{
return _history.get(index);
}
/**
* Clear the chat command history.
*/
public void clearCommandHistory ()
{
_history.clear();
}
/**
* Requests that all chat displays clear their contents.
*/
public void clearDisplays ()
{
_displays.apply(new ObserverList.ObserverOp<ChatDisplay>() {
public boolean apply (ChatDisplay observer) {
observer.clear();
return true;
}
});
}
/**
* Display a system INFO message as if it had come from the server. The localtype of the
* message will be PLACE_CHAT_TYPE.
*
* Info messages are sent when something happens that was neither directly triggered by the
* user, nor requires direct action.
*/
public void displayInfo (String bundle, String message)
{
displaySystem(bundle, message, SystemMessage.INFO, PLACE_CHAT_TYPE);
}
/**
* Display a system INFO message as if it had come from the server.
*
* Info messages are sent when something happens that was neither directly triggered by the
* user, nor requires direct action.
*/
public void displayInfo (String bundle, String message, String localtype)
{
displaySystem(bundle, message, SystemMessage.INFO, localtype);
}
/**
* Display a system FEEDBACK message as if it had come from the server. The localtype of the
* message will be PLACE_CHAT_TYPE.
*
* Feedback messages are sent in direct response to a user action, usually to indicate success
* or failure of the user's action.
*/
public void displayFeedback (String bundle, String message)
{
displaySystem(bundle, message, SystemMessage.FEEDBACK, PLACE_CHAT_TYPE);
}
/**
* Display a system ATTENTION message as if it had come from the server. The localtype of the
* message will be PLACE_CHAT_TYPE.
*
* Attention messages are sent when something requires user action that did not result from
* direct action by the user.
*/
public void displayAttention (String bundle, String message)
{
displaySystem(bundle, message, SystemMessage.ATTENTION, PLACE_CHAT_TYPE);
}
/**
* Dispatches the provided message to our chat displays.
*/
public void dispatchMessage (ChatMessage message, String localType)
{
setClientInfo(message, localType);
dispatchPreparedMessage(message);
}
/**
* Parses and delivers the supplied chat message. Slash command processing and mogrification
* are performed and the message is added to the chat history if appropriate.
*
* @param speakSvc the SpeakService representing the target dobj of the speak or null if we
* should speak in the "default" way.
* @param text the text to be parsed and sent.
* @param record if text is a command, should it be added to the history?
*
* @return <code>ChatCodes#SUCCESS</code> if the message was parsed and sent correctly, a
* translatable error string if there was some problem.
*/
public String requestChat (SpeakService speakSvc, String text, boolean record)
{
if (text.startsWith("/")) {
// split the text up into a command and arguments
String command = text.substring(1).toLowerCase();
String[] hist = new String[1];
String args = "";
int sidx = text.indexOf(" ");
if (sidx != -1) {
command = text.substring(1, sidx).toLowerCase();
args = text.substring(sidx + 1).trim();
}
HashMap<String, CommandHandler> possibleCommands = getCommandHandlers(command);
switch (possibleCommands.size()) {
case 0:
StringTokenizer tok = new StringTokenizer(text);
return MessageBundle.tcompose("m.unknown_command", tok.nextToken());
case 1:
Map.Entry<String, CommandHandler> entry =
possibleCommands.entrySet().iterator().next();
String cmdName = entry.getKey();
CommandHandler cmd = entry.getValue();
String result = cmd.handleCommand(speakSvc, cmdName, args, hist);
if (!result.equals(ChatCodes.SUCCESS)) {
return result;
}
if (record) {
// get the final history-ready command string
hist[0] = "/" + ((hist[0] == null) ? command : hist[0]);
// remove from history if it was present and add it to the end
addToHistory(hist[0]);
}
return result;
default:
String alternativeCommands = "";
Iterator<String> itr = Collections.getSortedIterator(possibleCommands.keySet());
while (itr.hasNext()) {
alternativeCommands += " /" + itr.next();
}
return MessageBundle.tcompose("m.unspecific_command", alternativeCommands);
}
}
// if not a command then just speak
String message = text.trim();
if (StringUtil.isBlank(message)) {
// report silent failure for now
return ChatCodes.SUCCESS;
}
return deliverChat(speakSvc, message, ChatCodes.DEFAULT_MODE);
}
/**
* Requests that a speak message with the specified mode be generated and delivered via the
* supplied speak service instance (which will be associated with a particular "speak
* object"). The message will first be validated by all registered {@link ChatFilter}s (and
* possibly vetoed) before being dispatched.
*
* @param speakService the speak service to use when generating the speak request or null if we
* should speak in the current "place".
* @param message the contents of the speak message.
* @param mode a speech mode that will be interpreted by the {@link ChatDisplay}
* implementations that eventually display this speak message.
*/
public void requestSpeak (SpeakService speakService, String message, byte mode)
{
if (speakService == null) {
if (_place == null) {
return;
}
speakService = _place.speakService;
}
// make sure they can say what they want to say
message = filter(message, null, true);
if (message == null) {
return;
}
// dispatch a speak request using the supplied speak service
speakService.speak(_ctx.getClient(), message, mode);
}
/**
* Requests to send a site-wide broadcast message.
*
* @param message the contents of the message.
*/
public void requestBroadcast (String message)
{
message = filter(message, null, true);
if (message == null) {
displayFeedback(_bundle, MessageBundle.compose("m.broadcast_failed", "m.filtered"));
return;
}
_cservice.broadcast(_ctx.getClient(), message, new ChatService.InvocationListener() {
public void requestFailed (String reason) {
reason = MessageBundle.compose("m.broadcast_failed", reason);
displayFeedback(_bundle, reason);
}
});
}
/**
* Requests that a tell message be delivered to the specified target user.
*
* @param target the username of the user to which the tell message should be delivered.
* @param msg the contents of the tell message.
* @param rl an optional result listener if you'd like to be notified of success or failure.
*/
public <T extends Name> void requestTell (
final T target, String msg, final ResultListener<T> rl)
{
// make sure they can say what they want to say
final String message = filter(msg, target, true);
if (message == null) {
if (rl != null) {
rl.requestFailed(null);
}
return;
}
// create a listener that will report success or failure
ChatService.TellListener listener = new ChatService.TellListener() {
public void tellSucceeded (long idletime, String awayMessage) {
success();
// if they have an away message, report that
if (awayMessage != null) {
awayMessage = filter(awayMessage, target, false);
if (awayMessage != null) {
String msg = MessageBundle.tcompose("m.recipient_afk", target, awayMessage);
displayFeedback(_bundle, msg);
}
}
// if they are idle, report that
if (idletime > 0L) {
// adjust by the time it took them to become idle
idletime += _ctx.getConfig().getValue(IDLE_TIME_KEY, DEFAULT_IDLE_TIME);
String msg = MessageBundle.compose(
"m.recipient_idle", MessageBundle.taint(target),
TimeUtil.getTimeOrderString(idletime, TimeUtil.MINUTE));
displayFeedback(_bundle, msg);
}
}
protected void success () {
dispatchMessage(new TellFeedbackMessage(target, message, false),
ChatCodes.PLACE_CHAT_TYPE);
addChatter(target);
if (rl != null) {
rl.requestCompleted(target);
}
}
public void requestFailed (String reason) {
String msg = MessageBundle.compose(
"m.tell_failed", MessageBundle.taint(target), reason);
TellFeedbackMessage tfm = new TellFeedbackMessage(target, msg, true);
tfm.bundle = _bundle;
dispatchMessage(tfm, ChatCodes.PLACE_CHAT_TYPE);
if (rl != null) {
rl.requestFailed(null);
}
}
};
_cservice.tell(_ctx.getClient(), target, message, listener);
}
/**
* Configures a message that will be automatically reported to anyone that sends a tell message
* to this client to indicate that we are busy or away from the keyboard.
*/
public void setAwayMessage (String message)
{
if (message != null) {
message = filter(message, null, true);
if (message == null) {
// they filtered away their own away message... change it to something
message = "...";
}
}
// pass the buck right on along
_cservice.away(_ctx.getClient(), message);
}
/**
* Adds an additional object via which chat messages may arrive. The chat director assumes the
* caller will be managing the subscription to this object and will remain subscribed to it for
* as long as it remains in effect as an auxiliary chat source.
*
* @param localtype a type to be associated with all chat messages that arrive on the specified
* DObject.
*/
public void addAuxiliarySource (DObject source, String localtype)
{
source.addListener(this);
_auxes.put(source.getOid(), localtype);
}
/**
* Removes a previously added auxiliary chat source.
*/
public void removeAuxiliarySource (DObject source)
{
source.removeListener(this);
_auxes.remove(source.getOid());
}
/**
* Run a message through all the currently registered filters.
*/
public String filter (String msg, Name otherUser, boolean outgoing)
{
_filterMessageOp.setMessage(msg, otherUser, outgoing);
_filters.apply(_filterMessageOp);
return _filterMessageOp.getMessage();
}
/**
* Runs the supplied message through the various chat mogrifications.
*/
public String mogrifyChat (String text)
{
return mogrifyChat(text, false, true);
}
// documentation inherited
public boolean locationMayChange (int placeId)
{
// we accept all location change requests
return true;
}
// documentation inherited
public void locationDidChange (PlaceObject place)
{
if (_place != null) {
// unlisten to our old object
_place.removeListener(this);
}
// listen to the new object
_place = place;
if (_place != null) {
_place.addListener(this);
}
}
// documentation inherited
public void locationChangeFailed (int placeId, String reason)
{
// nothing we care about
}
// documentation inherited
public void messageReceived (MessageEvent event)
{
if (CHAT_NOTIFICATION.equals(event.getName())) {
ChatMessage msg = (ChatMessage)event.getArgs()[0];
String localtype = getLocalType(event.getTargetOid());
processReceivedMessage(msg, localtype);
}
}
@Override
public void clientDidLogon (Client client)
{
super.clientDidLogon(client);
// listen on the client object for tells
addAuxiliarySource(_clobj = client.getClientObject(), USER_CHAT_TYPE);
}
@Override
public void clientObjectDidChange (Client client)
{
super.clientObjectDidChange(client);
// change what we're listening to for tells
removeAuxiliarySource(_clobj);
addAuxiliarySource(_clobj = client.getClientObject(), USER_CHAT_TYPE);
clearDisplays();
}
@Override
public void clientDidLogoff (Client client)
{
super.clientDidLogoff(client);
// stop listening to it for tells
if (_clobj != null) {
removeAuxiliarySource(_clobj);
_clobj = null;
}
// in fact, clear out all auxiliary sources
_auxes.clear();
clearDisplays();
// clear out the list of people we've chatted with
_chatters.clear();
notifyChatterObservers();
// clear the _place
locationDidChange(null);
// clear our service
_cservice = null;
}
/**
* Processes and dispatches the specified chat message.
*/
protected void processReceivedMessage (ChatMessage msg, String localtype)
{
String autoResponse = null;
Name speaker = null;
Name speakerDisplay = null;
byte mode = (byte)-1;
// figure out if the message was triggered by another user
if (msg instanceof UserMessage) {
UserMessage umsg = (UserMessage)msg;
speaker = umsg.speaker;
speakerDisplay = umsg.getSpeakerDisplayName();
mode = umsg.mode;
} else if (msg instanceof UserSystemMessage) {
speaker = ((UserSystemMessage)msg).speaker;
speakerDisplay = speaker;
}
// Translate and timestamp the message. This would happen during dispatch but we
// need to do it ahead of filtering.
setClientInfo(msg, localtype);
// if there was an originating speaker, see if we want to hear it
if (speaker != null) {
if ((msg.message = filter(msg.message, speaker, false)) == null) {
return;
}
if (USER_CHAT_TYPE.equals(localtype) &&
mode == ChatCodes.DEFAULT_MODE) {
// if it was a tell, add the speaker as a chatter
addChatter(speaker);
// note whether or not we have an auto-response
BodyObject self = (BodyObject)_ctx.getClient().getClientObject();
if (!StringUtil.isBlank(self.awayMessage)) {
autoResponse = self.awayMessage;
}
}
}
// and send it off!
dispatchMessage(msg, localtype);
// if we auto-responded, report as much
if (autoResponse != null) {
String amsg = MessageBundle.tcompose(
"m.auto_responded", speakerDisplay, autoResponse);
displayFeedback(_bundle, amsg);
}
}
/**
* Dispatch a message to chat displays once it is fully prepared with the clientinfo.
*/
protected void dispatchPreparedMessage (ChatMessage message)
{
_displayMessageOp.setMessage(message);
_displays.apply(_displayMessageOp);
}
/**
* Called to determine whether we are permitted to post the supplied chat message. Derived
* classes may wish to throttle chat or restrict certain types in certain circumstances for
* whatever reason.
*
* @return null if the chat is permitted, SUCCESS if the chat is permitted and has already been
* dealt with, or a translatable string indicating the reason for rejection if not.
*/
protected String checkCanChat (SpeakService speakSvc, String message, byte mode)
{
return null;
}
/**
* Delivers a plain chat message (not a slash command) on the specified speak service in the
* specified mode. The message will be mogrified and filtered prior to delivery.
*
* @return {@link ChatCodes#SUCCESS} if the message was delivered or a string indicating why it
* failed.
*/
protected String deliverChat (SpeakService speakSvc, String message, byte mode)
{
// run the message through our mogrification process
message = mogrifyChat(message, true, mode != ChatCodes.EMOTE_MODE);
// mogrification may result in something being turned into a slash command, in which case
// we have to run everything through again from the start
if (message.startsWith("/")) {
return requestChat(speakSvc, message, false);
}
// make sure this client is not restricted from performing this chat message for some
// reason or other
String errmsg = checkCanChat(speakSvc, message, mode);
if (errmsg != null) {
return errmsg;
}
// speak on the specified service
requestSpeak(speakSvc, message, mode);
return ChatCodes.SUCCESS;
}
/**
* Adds the specified command to the history.
*/
protected void addToHistory (String cmd)
{
// remove any previous instance of this command
_history.remove(cmd);
// append it to the end
_history.add(cmd);
// prune the history once it extends beyond max size
if (_history.size() > MAX_COMMAND_HISTORY) {
_history.remove(0);
}
}
/**
* Mogrifies common literary crutches into more appealing chat or commands.
*
* @param transformsAllowed if true, the chat may transformed into a different mode. (lol ->
* /emote laughs)
* @param capFirst if true, the first letter of the text is capitalized. This is not desired if
* the chat is already an emote.
*/
protected String mogrifyChat (String text, boolean transformsAllowed, boolean capFirst)
{
int tlen = text.length();
if (tlen == 0) {
return text;
// check to make sure there aren't too many caps
} else if (tlen > 7 && suppressTooManyCaps()) {
// count caps
int caps = 0;
for (int ii=0; ii < tlen; ii++) {
if (Character.isUpperCase(text.charAt(ii))) {
caps++;
if (caps > (tlen / 2)) {
// lowercase the whole string if there are
text = text.toLowerCase();
break;
}
}
}
}
StringBuffer buf = new StringBuffer(text);
buf = mogrifyChat(buf, transformsAllowed, capFirst);
return buf.toString();
}
/** Helper function for {@link #mogrifyChat(String,boolean,boolean)}. */
protected StringBuffer mogrifyChat (
StringBuffer buf, boolean transformsAllowed, boolean capFirst)
{
if (_mogrifyChat) {
// do the generic mogrifications and translations
buf = translatedReplacements("x.mogrifies", buf);
// perform themed expansions and transformations
if (transformsAllowed) {
buf = translatedReplacements("x.transforms", buf);
}
}
/*
// capitalize the first letter
if (capFirst) {
buf.setCharAt(0, Character.toUpperCase(buf.charAt(0)));
}
// and capitalize any letters after a sentence-ending punctuation
Pattern p = Pattern.compile("([^\\.][\\.\\?\\!](\\s)+\\p{Ll})");
Matcher m = p.matcher(buf);
if (m.find()) {
buf = new StringBuilder();
m.appendReplacement(buf, m.group().toUpperCase());
while (m.find()) {
m.appendReplacement(buf, m.group().toUpperCase());
}
m.appendTail(buf);
}
*/
return buf;
}
/**
* Do all the replacements (mogrifications) specified in the translation string specified by
* the key.
*/
protected StringBuffer translatedReplacements (String key, StringBuffer buf)
{
MessageBundle bundle = _msgmgr.getBundle(_bundle);
if (!bundle.exists(key)) {
return buf;
}
StringTokenizer st = new StringTokenizer(bundle.get(key), "#");
// apply the replacements to each mogrification that matches
while (st.hasMoreTokens()) {
String pattern = st.nextToken();
String replace = st.nextToken();
Matcher m = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE).matcher(buf);
if (m.find()) {
buf = new StringBuffer();
m.appendReplacement(buf, replace);
// they may match more than once
while (m.find()) {
m.appendReplacement(buf, replace);
}
m.appendTail(buf);
}
}
return buf;
}
/**
* Return true if we should lowercase messages containing more than half upper-case characters.
*/
protected boolean suppressTooManyCaps ()
{
return true;
}
/**
* Check that after mogrification the message is not too long.
* @return an error message if it is too long, or null.
*/
protected String checkLength (String msg)
{
return null; // everything's ok by default
}
/**
* Returns a hashmap containing all command handlers that match the specified command (i.e. the
* specified command is a prefix of their registered command string).
*/
protected HashMap<String, CommandHandler> getCommandHandlers (String command)
{
HashMap<String, CommandHandler> matches = Maps.newHashMap();
BodyObject user = (BodyObject)_ctx.getClient().getClientObject();
for (Map.Entry<String, CommandHandler> entry : _handlers.entrySet()) {
String cmd = entry.getKey();
if (!cmd.startsWith(command)) {
continue;
}
CommandHandler handler = entry.getValue();
if (!handler.checkAccess(user)) {
continue;
}
matches.put(cmd, handler);
}
return matches;
}
/**
* Adds a chatter to our list of recent chatters.
*/
protected void addChatter (Name name)
{
// check to see if the chatter validator approves..
if ((_chatterValidator != null) && (!_chatterValidator.isChatterValid(name))) {
return;
}
boolean wasthere = _chatters.remove(name);
_chatters.addFirst(name);
if (!wasthere) {
if (_chatters.size() > MAX_CHATTERS) {
_chatters.removeLast();
}
notifyChatterObservers();
}
}
/**
* Notifies all registered {@link ChatterObserver}s that the list of chatters has changed.
*/
protected void notifyChatterObservers ()
{
_chatterObservers.apply(new ObserverList.ObserverOp<ChatterObserver>() {
public boolean apply (ChatterObserver observer) {
observer.chattersUpdated(_chatters.listIterator());
return true;
}
});
}
/**
* Set the "client info" on the specified message, if not already set.
*/
protected void setClientInfo (ChatMessage msg, String localType)
{
if (msg.localtype == null) {
msg.setClientInfo(xlate(msg.bundle, msg.message), localType);
}
}
/**
* Translates the specified message using the specified bundle.
*/
protected String xlate (String bundle, String message)
{
if (bundle != null && _msgmgr != null) {
MessageBundle msgb = _msgmgr.getBundle(bundle);
if (msgb == null) {
log.warning("No message bundle available to translate message", "bundle", bundle,
"message", message);
} else {
message = msgb.xlate(message);
}
}
return message;
}
/**
* Display the specified system message as if it had come from the server.
*/
protected void displaySystem (String bundle, String message, byte attLevel, String localtype)
{
// nothing should be untranslated, so pass the default bundle if need be.
if (bundle == null) {
bundle = _bundle;
}
SystemMessage msg = new SystemMessage(message, bundle, attLevel);
dispatchMessage(msg, localtype);
}
/**
* Looks up and returns the message type associated with the specified oid.
*/
protected String getLocalType (int oid)
{
String type = _auxes.get(oid);
return (type == null) ? PLACE_CHAT_TYPE : type;
}
@Override
protected void registerServices (Client client)
{
client.addServiceGroup(CrowdCodes.CROWD_GROUP);
}
@Override
protected void fetchServices (Client client)
{
// get a handle on our chat service
_cservice = client.requireService(ChatService.class);
}
/**
* An operation that checks with all chat filters to properly filter a message prior to sending
* to the server or displaying.
*/
protected static class FilterMessageOp
implements ObserverList.ObserverOp<ChatFilter>
{
public void setMessage (String msg, Name otherUser, boolean outgoing)
{
_msg = msg;
_otherUser = otherUser;
_out = outgoing;
}
public boolean apply (ChatFilter observer)
{
if (_msg != null) {
_msg = observer.filter(_msg, _otherUser, _out);
}
return true;
}
public String getMessage ()
{
return _msg;
}
protected Name _otherUser;
protected String _msg;
protected boolean _out;
}
/**
* An observer op used to dispatch ChatMessages on the client.
*/
protected static class DisplayMessageOp
implements ObserverList.ObserverOp<ChatDisplay>
{
public void setMessage (ChatMessage message)
{
_message = message;
_displayed = false;
}
public boolean apply (ChatDisplay observer)
{
if (observer.displayMessage(_message, _displayed)) {
_displayed = true;
}
return true;
}
protected ChatMessage _message;
protected boolean _displayed;
}
/** Implements <code>/help</code>. */
protected class HelpHandler extends CommandHandler
{
@Override
public String handleCommand (SpeakService speakSvc, String command,
String args, String[] history)
{
String hcmd = "";
// grab the command they want help on
if (!StringUtil.isBlank(args)) {
hcmd = args;
int sidx = args.indexOf(" ");
if (sidx != -1) {
hcmd = args.substring(0, sidx);
}
}
// let the user give commands with or with the /
if (hcmd.startsWith("/")) {
hcmd = hcmd.substring(1);
}
// handle "/help help" and "/help someboguscommand"
HashMap<String, CommandHandler> possibleCommands = getCommandHandlers(hcmd);
if (hcmd.equals("help") || possibleCommands.isEmpty()) {
possibleCommands = getCommandHandlers("");
possibleCommands.remove("help"); // remove help from the list
}
// if there is only one possible command display its usage
switch (possibleCommands.size()) {
case 1:
Iterator<String> itr = possibleCommands.keySet().iterator();
// this is a little funny, but we display the feeback message by hand and return
// SUCCESS so that the chat entry field doesn't think that we've failed and
// preserve our command text
displayFeedback(null, "m.usage_" + itr.next());
return ChatCodes.SUCCESS;
default:
Object[] commands = possibleCommands.keySet().toArray();
Arrays.sort(commands);
String commandList = "";
for (Object element : commands) {
commandList += " /" + element;
}
return MessageBundle.tcompose("m.usage_help", commandList);
}
}
}
/** Implements <code>/clear</code>. */
protected class ClearHandler extends CommandHandler
{
@Override
public String handleCommand (SpeakService speakSvc, String command,
String args, String[] history)
{
clearDisplays();
return ChatCodes.SUCCESS;
}
}
/** Implements <code>/speak</code>. */
protected class SpeakHandler extends CommandHandler
{
@Override
public String handleCommand (SpeakService speakSvc, String command,
String args, String[] history)
{
if (StringUtil.isBlank(args)) {
return "m.usage_speak";
}
// note the command to be stored in the history
history[0] = command + " ";
// we do not propogate the speakSvc, because /speak means use
// the default channel..
return requestChat(null, args, true);
}
}
/** Implements <code>/emote</code>. */
protected class EmoteHandler extends CommandHandler
{
@Override
public String handleCommand (SpeakService speakSvc, String command,
String args, String[] history)
{
if (StringUtil.isBlank(args)) {
return "m.usage_emote";
}
// note the command to be stored in the history
history[0] = command + " ";
return deliverChat(speakSvc, args, ChatCodes.EMOTE_MODE);
}
}
/** Implements <code>/think</code>. */
protected class ThinkHandler extends CommandHandler
{
@Override
public String handleCommand (SpeakService speakSvc, String command,
String args, String[] history)
{
if (StringUtil.isBlank(args)) {
return "m.usage_think";
}
// note the command to be stored in the history
history[0] = command + " ";
return deliverChat(speakSvc, args, ChatCodes.THINK_MODE);
}
}
/** Implements <code>/tell</code>. */
protected class TellHandler extends CommandHandler
{
@Override
public String handleCommand (SpeakService speakSvc, final String command,
String args, String[] history)
{
if (StringUtil.isBlank(args)) {
return "m.usage_tell";
}
final boolean useQuotes = args.startsWith("\"");
String[] bits = parseTell(args);
String handle = bits[0];
String message = bits[1];
// validate that we didn't eat all the tokens making the handle
if (StringUtil.isBlank(message)) {
return "m.usage_tell";
}
// make sure we're not trying to tell something to ourselves
BodyObject self = (BodyObject)_ctx.getClient().getClientObject();
if (handle.equalsIgnoreCase(self.getVisibleName().toString())) {
return "m.talk_self";
}
// and lets just give things an opportunity to sanitize the name
Name target = normalizeAsName(handle);
// mogrify the chat
message = mogrifyChat(message);
String err = checkLength(message);
if (err != null) {
return err;
}
// clear out from the history any tells that are mistypes
for (Iterator<String> iter = _history.iterator(); iter.hasNext(); ) {
String hist = iter.next();
if (hist.startsWith("/" + command)) {
String harg = hist.substring(command.length() + 1).trim();
// we blow away any historic tells that have msg content
if (!StringUtil.isBlank(parseTell(harg)[1])) {
iter.remove();
}
}
}
// store the full command in the history, even if it was mistyped
final String histEntry = command + " " +
(useQuotes ? ("\"" + target + "\"") : target.toString()) + " " + message;
history[0] = histEntry;
// request to send this text as a tell message
requestTell(target, escapeMessage(message), new ResultListener<Name>() {
public void requestCompleted (Name target) {
// replace the full one in the history with just: /tell "<handle>"
String newEntry = "/" + command + " " +
(useQuotes ? ("\"" + target + "\"") : String.valueOf(target)) + " ";
_history.remove(newEntry);
int dex = _history.lastIndexOf("/" + histEntry);
if (dex >= 0) {
_history.set(dex, newEntry);
} else {
_history.add(newEntry);
}
}
public void requestFailed (Exception cause) {
// do nothing
}
});
return ChatCodes.SUCCESS;
}
/**
* Parse the tell into two strings, handle and message. If either one is null then the
* parsing did not succeed.
*/
protected String[] parseTell (String args)
{
String handle, message;
if (args.startsWith("\"")) {
int nextQuote = args.indexOf('"', 1);
if (nextQuote == -1 || nextQuote == 1) {
handle = message = null; // bogus parsing
} else {
handle = args.substring(1, nextQuote).trim();
message = args.substring(nextQuote + 1).trim();
}
} else {
StringTokenizer st = new StringTokenizer(args);
handle = st.nextToken();
message = args.substring(handle.length()).trim();
}
return new String[] { handle, message };
}
/**
* Turn the user-entered string into a Name object, doing any particular normalization we
* want to do along the way so that "/tell Bob" and "/tell BoB" don't both show up in
* history.
*/
protected Name normalizeAsName (String handle)
{
return new Name(handle);
}
/**
* Escape or otherwise do any final processing on the message prior to sending it.
*/
protected String escapeMessage (String msg)
{
return msg;
}
}
/** Implements <code>/broadcast</code>. */
protected class BroadcastHandler extends CommandHandler
{
@Override
public String handleCommand (SpeakService speakSvc, String command,
String args, String[] history)
{
if (StringUtil.isBlank(args)) {
return "m.usage_broadcast";
}
// mogrify and verify length
args = mogrifyChat(args);
String err = checkLength(args);
if (err != null) {
return err;
}
// request the broadcast
requestBroadcast(args);
// note the command to be stored in the history
history[0] = command + " ";
return ChatCodes.SUCCESS;
}
@Override
public boolean checkAccess (BodyObject user)
{
return user.checkAccess(ChatCodes.BROADCAST_ACCESS) == null;
}
}
/** Our active chat context. */
protected CrowdContext _ctx;
/** Provides access to chat-related server-side services. */
protected ChatService _cservice;
/** The message manager. */
protected MessageManager _msgmgr;
/** The bundle to use for our own internal messages. */
protected String _bundle;
/** The place object that we currently occupy. */
protected PlaceObject _place;
/** The client object that we're listening to for tells. */
protected ClientObject _clobj;
/** Whether or not to run chat through the mogrifier. */
protected boolean _mogrifyChat= true;
/** A list of registered chat displays. */
protected ObserverList<ChatDisplay> _displays =
new ObserverList<ChatDisplay>(ObserverList.SAFE_IN_ORDER_NOTIFY);
/** A list of registered chat filters. */
protected ObserverList<ChatFilter> _filters =
new ObserverList<ChatFilter>(ObserverList.SAFE_IN_ORDER_NOTIFY);
/** A mapping from auxiliary chat objects to the types under which
* they are registered. */
protected HashIntMap<String> _auxes = new HashIntMap<String>();
/** Validator of who may be added to the chatters list. */
protected ChatterValidator _chatterValidator;
/** Usernames of users we've recently chatted with. */
protected LinkedList<Name> _chatters = new LinkedList<Name>();
/** Observers that are watching our chatters list. */
protected ObserverList<ChatterObserver> _chatterObservers =
new ObserverList<ChatterObserver>(ObserverList.SAFE_IN_ORDER_NOTIFY);
/** Operation used to filter chat messages. */
protected FilterMessageOp _filterMessageOp = new FilterMessageOp();
/** Operation used to display chat messages. */
protected DisplayMessageOp _displayMessageOp = new DisplayMessageOp();
/** Registered chat command handlers. */
protected static HashMap<String, CommandHandler> _handlers = Maps.newHashMap();
/** A history of chat commands. */
protected static ArrayList<String> _history = Lists.newArrayList();
/** The maximum number of chatter usernames to track. */
protected static final int MAX_CHATTERS = 6;
/** The maximum number of commands to keep in the chat history. */
protected static final int MAX_COMMAND_HISTORY = 10;
}
|
src/java/com/threerings/crowd/chat/client/ChatDirector.java
|
//
// $Id$
//
// Narya library - tools for developing networked games
// Copyright (C) 2002-2007 Three Rings Design, Inc., All Rights Reserved
// http://www.threerings.net/code/narya/
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.threerings.crowd.chat.client;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.samskivert.util.Collections;
import com.samskivert.util.HashIntMap;
import com.samskivert.util.ObserverList;
import com.samskivert.util.ResultListener;
import com.samskivert.util.StringUtil;
import com.threerings.util.MessageBundle;
import com.threerings.util.MessageManager;
import com.threerings.util.Name;
import com.threerings.util.TimeUtil;
import com.threerings.presents.client.BasicDirector;
import com.threerings.presents.client.Client;
import com.threerings.presents.data.ClientObject;
import com.threerings.presents.dobj.DObject;
import com.threerings.presents.dobj.MessageEvent;
import com.threerings.presents.dobj.MessageListener;
import com.threerings.crowd.chat.data.ChatCodes;
import com.threerings.crowd.chat.data.ChatMessage;
import com.threerings.crowd.chat.data.SystemMessage;
import com.threerings.crowd.chat.data.TellFeedbackMessage;
import com.threerings.crowd.chat.data.UserMessage;
import com.threerings.crowd.chat.data.UserSystemMessage;
import com.threerings.crowd.client.LocationObserver;
import com.threerings.crowd.data.BodyObject;
import com.threerings.crowd.data.CrowdCodes;
import com.threerings.crowd.data.PlaceObject;
import com.threerings.crowd.util.CrowdContext;
import static com.threerings.crowd.Log.log;
/**
* The chat director is the client side coordinator of all chat related services. It handles both
* place constrained chat as well as direct messaging.
*/
public class ChatDirector extends BasicDirector
implements ChatCodes, LocationObserver, MessageListener
{
/**
* An interface to receive information about the {@link #MAX_CHATTERS} most recent users that
* we've been chatting with.
*/
public static interface ChatterObserver
{
/**
* Called when the list of chatters has been changed.
*/
void chattersUpdated (Iterator<Name> chatternames);
}
/**
* An interface for those who would like to validate whether usernames may be added to the
* chatter list.
*/
public static interface ChatterValidator
{
/**
* Returns whether the username may be added to the chatters list.
*/
boolean isChatterValid (Name username);
}
/**
* Used to implement a slash command (e.g. <code>/who</code>).
*/
public abstract static class CommandHandler
{
/**
* Handles the specified chat command.
*
* @param speakSvc an optional SpeakService object representing the object to send the chat
* message on.
* @param command the slash command that was used to invoke this handler
* (e.g. <code>/tell</code>).
* @param args the arguments provided along with the command (e.g. <code>Bob hello</code>)
* or <code>null</code> if no arguments were supplied.
* @param history an in/out parameter that allows the command to modify the text that will
* be appended to the chat history. If this is set to null, nothing will be appended.
*
* @return an untranslated string that will be reported to the chat box to convey an error
* response to the user, or {@link ChatCodes#SUCCESS}.
*/
public abstract String handleCommand (SpeakService speakSvc, String command, String args,
String[] history);
/**
* Returns true if this user should have access to this chat command.
*/
public boolean checkAccess (BodyObject user)
{
return true;
}
}
/**
* Creates a chat director and initializes it with the supplied context. The chat director will
* register itself as a location observer so that it can automatically process place
* constrained chat.
*
* @param msgmgr the message manager via which we do our translations.
* @param bundle the message bundle from which we obtain our chat-related translation strings.
*/
public ChatDirector (CrowdContext ctx, MessageManager msgmgr, String bundle)
{
super(ctx);
// keep the context around
_ctx = ctx;
_msgmgr = msgmgr;
_bundle = bundle;
// register ourselves as a location observer
_ctx.getLocationDirector().addLocationObserver(this);
// register our default chat handlers
if (_bundle == null || _msgmgr == null) {
log.warning("Null bundle or message manager given to ChatDirector");
return;
}
registerCommandHandlers();
}
/**
* Registers all the chat-command handlers.
*/
protected void registerCommandHandlers ()
{
MessageBundle msg = _msgmgr.getBundle(_bundle);
registerCommandHandler(msg, "help", new HelpHandler());
registerCommandHandler(msg, "clear", new ClearHandler());
registerCommandHandler(msg, "speak", new SpeakHandler());
registerCommandHandler(msg, "emote", new EmoteHandler());
registerCommandHandler(msg, "think", new ThinkHandler());
registerCommandHandler(msg, "tell", new TellHandler());
registerCommandHandler(msg, "broadcast", new BroadcastHandler());
}
/**
* Adds the supplied chat display to the front of the chat display list. It will subsequently
* be notified of incoming chat messages as well as tell responses.
*/
public void pushChatDisplay (ChatDisplay display)
{
_displays.add(0, display);
}
/**
* Adds the supplied chat display to the end of the chat display list. It will subsequently be
* notified of incoming chat messages as well as tell responses.
*/
public void addChatDisplay (ChatDisplay display)
{
_displays.add(display);
}
/**
* Removes the specified chat display from the chat display list. The display will no longer
* receive chat related notifications.
*/
public void removeChatDisplay (ChatDisplay display)
{
_displays.remove(display);
}
/**
* Adds the specified chat filter to the list of filters. All chat requests and receipts will
* be filtered with all filters before they being sent or dispatched locally.
*/
public void addChatFilter (ChatFilter filter)
{
_filters.add(filter);
}
/**
* Removes the specified chat validator from the list of chat validators.
*/
public void removeChatFilter (ChatFilter filter)
{
_filters.remove(filter);
}
/**
* Adds an observer that watches the chatters list, and updates it immediately.
*/
public void addChatterObserver (ChatterObserver co)
{
_chatterObservers.add(co);
co.chattersUpdated(_chatters.listIterator());
}
/**
* Removes an observer from the list of chatter observers.
*/
public void removeChatterObserver (ChatterObserver co)
{
_chatterObservers.remove(co);
}
/**
* Sets the validator that decides if a username is valid to be added to the chatter list, or
* null if no such filtering is desired.
*/
public void setChatterValidator (ChatterValidator validator)
{
_chatterValidator = validator;
}
/**
* Enables or disables the chat mogrifier. The mogrifier converts chat speak like LOL, WTF,
* etc. into phrases, words and can also transform them into emotes. The mogrifier is
* configured via the <code>x.mogrifies</code> and <code>x.transforms</code> translation
* properties.
*/
public void setMogrifyChat (boolean mogrifyChat)
{
_mogrifyChat = mogrifyChat;
}
/**
* Registers a chat command handler.
*
* @param msg the message bundle via which the slash command will be translated (as
* <code>c.</code><i>command</i>). If no translation exists the command will be
* <code>/</code><i>command</i>.
* @param command the name of the command that will be used to invoke this handler
* (e.g. <code>tell</code> if the command will be invoked as <code>/tell</code>).
* @param handler the chat command handler itself.
*/
public void registerCommandHandler (MessageBundle msg, String command, CommandHandler handler)
{
String key = "c." + command;
if (msg.exists(key)) {
StringTokenizer st = new StringTokenizer(msg.get(key));
while (st.hasMoreTokens()) {
_handlers.put(st.nextToken(), handler);
}
} else {
// fall back to just using the English command
_handlers.put(command, handler);
}
}
/**
* Return the current size of the history.
*/
public int getCommandHistorySize ()
{
return _history.size();
}
/**
* Get the chat history entry at the specified index, with 0 being the oldest.
*/
public String getCommandHistory (int index)
{
return _history.get(index);
}
/**
* Clear the chat command history.
*/
public void clearCommandHistory ()
{
_history.clear();
}
/**
* Requests that all chat displays clear their contents.
*/
public void clearDisplays ()
{
_displays.apply(new ObserverList.ObserverOp<ChatDisplay>() {
public boolean apply (ChatDisplay observer) {
observer.clear();
return true;
}
});
}
/**
* Display a system INFO message as if it had come from the server. The localtype of the
* message will be PLACE_CHAT_TYPE.
*
* Info messages are sent when something happens that was neither directly triggered by the
* user, nor requires direct action.
*/
public void displayInfo (String bundle, String message)
{
displaySystem(bundle, message, SystemMessage.INFO, PLACE_CHAT_TYPE);
}
/**
* Display a system INFO message as if it had come from the server.
*
* Info messages are sent when something happens that was neither directly triggered by the
* user, nor requires direct action.
*/
public void displayInfo (String bundle, String message, String localtype)
{
displaySystem(bundle, message, SystemMessage.INFO, localtype);
}
/**
* Display a system FEEDBACK message as if it had come from the server. The localtype of the
* message will be PLACE_CHAT_TYPE.
*
* Feedback messages are sent in direct response to a user action, usually to indicate success
* or failure of the user's action.
*/
public void displayFeedback (String bundle, String message)
{
displaySystem(bundle, message, SystemMessage.FEEDBACK, PLACE_CHAT_TYPE);
}
/**
* Display a system ATTENTION message as if it had come from the server. The localtype of the
* message will be PLACE_CHAT_TYPE.
*
* Attention messages are sent when something requires user action that did not result from
* direct action by the user.
*/
public void displayAttention (String bundle, String message)
{
displaySystem(bundle, message, SystemMessage.ATTENTION, PLACE_CHAT_TYPE);
}
/**
* Dispatches the provided message to our chat displays.
*/
public void dispatchMessage (ChatMessage message, String localType)
{
setClientInfo(message, localType);
dispatchPreparedMessage(message);
}
/**
* Parses and delivers the supplied chat message. Slash command processing and mogrification
* are performed and the message is added to the chat history if appropriate.
*
* @param speakSvc the SpeakService representing the target dobj of the speak or null if we
* should speak in the "default" way.
* @param text the text to be parsed and sent.
* @param record if text is a command, should it be added to the history?
*
* @return <code>ChatCodes#SUCCESS</code> if the message was parsed and sent correctly, a
* translatable error string if there was some problem.
*/
public String requestChat (SpeakService speakSvc, String text, boolean record)
{
if (text.startsWith("/")) {
// split the text up into a command and arguments
String command = text.substring(1).toLowerCase();
String[] hist = new String[1];
String args = "";
int sidx = text.indexOf(" ");
if (sidx != -1) {
command = text.substring(1, sidx).toLowerCase();
args = text.substring(sidx + 1).trim();
}
HashMap<String, CommandHandler> possibleCommands = getCommandHandlers(command);
switch (possibleCommands.size()) {
case 0:
StringTokenizer tok = new StringTokenizer(text);
return MessageBundle.tcompose("m.unknown_command", tok.nextToken());
case 1:
Map.Entry<String, CommandHandler> entry =
possibleCommands.entrySet().iterator().next();
String cmdName = entry.getKey();
CommandHandler cmd = entry.getValue();
String result = cmd.handleCommand(speakSvc, cmdName, args, hist);
if (!result.equals(ChatCodes.SUCCESS)) {
return result;
}
if (record) {
// get the final history-ready command string
hist[0] = "/" + ((hist[0] == null) ? command : hist[0]);
// remove from history if it was present and add it to the end
addToHistory(hist[0]);
}
return result;
default:
String alternativeCommands = "";
Iterator<String> itr = Collections.getSortedIterator(possibleCommands.keySet());
while (itr.hasNext()) {
alternativeCommands += " /" + itr.next();
}
return MessageBundle.tcompose("m.unspecific_command", alternativeCommands);
}
}
// if not a command then just speak
String message = text.trim();
if (StringUtil.isBlank(message)) {
// report silent failure for now
return ChatCodes.SUCCESS;
}
return deliverChat(speakSvc, message, ChatCodes.DEFAULT_MODE);
}
/**
* Requests that a speak message with the specified mode be generated and delivered via the
* supplied speak service instance (which will be associated with a particular "speak
* object"). The message will first be validated by all registered {@link ChatFilter}s (and
* possibly vetoed) before being dispatched.
*
* @param speakService the speak service to use when generating the speak request or null if we
* should speak in the current "place".
* @param message the contents of the speak message.
* @param mode a speech mode that will be interpreted by the {@link ChatDisplay}
* implementations that eventually display this speak message.
*/
public void requestSpeak (SpeakService speakService, String message, byte mode)
{
if (speakService == null) {
if (_place == null) {
return;
}
speakService = _place.speakService;
}
// make sure they can say what they want to say
message = filter(message, null, true);
if (message == null) {
return;
}
// dispatch a speak request using the supplied speak service
speakService.speak(_ctx.getClient(), message, mode);
}
/**
* Requests to send a site-wide broadcast message.
*
* @param message the contents of the message.
*/
public void requestBroadcast (String message)
{
message = filter(message, null, true);
if (message == null) {
displayFeedback(_bundle, MessageBundle.compose("m.broadcast_failed", "m.filtered"));
return;
}
_cservice.broadcast(_ctx.getClient(), message, new ChatService.InvocationListener() {
public void requestFailed (String reason) {
reason = MessageBundle.compose("m.broadcast_failed", reason);
displayFeedback(_bundle, reason);
}
});
}
/**
* Requests that a tell message be delivered to the specified target user.
*
* @param target the username of the user to which the tell message should be delivered.
* @param msg the contents of the tell message.
* @param rl an optional result listener if you'd like to be notified of success or failure.
*/
public <T extends Name> void requestTell (
final T target, String msg, final ResultListener<T> rl)
{
// make sure they can say what they want to say
final String message = filter(msg, target, true);
if (message == null) {
if (rl != null) {
rl.requestFailed(null);
}
return;
}
// create a listener that will report success or failure
ChatService.TellListener listener = new ChatService.TellListener() {
public void tellSucceeded (long idletime, String awayMessage) {
success();
// if they have an away message, report that
if (awayMessage != null) {
awayMessage = filter(awayMessage, target, false);
if (awayMessage != null) {
String msg = MessageBundle.tcompose("m.recipient_afk", target, awayMessage);
displayFeedback(_bundle, msg);
}
}
// if they are idle, report that
if (idletime > 0L) {
// adjust by the time it took them to become idle
idletime += _ctx.getConfig().getValue(IDLE_TIME_KEY, DEFAULT_IDLE_TIME);
String msg = MessageBundle.compose(
"m.recipient_idle", MessageBundle.taint(target),
TimeUtil.getTimeOrderString(idletime, TimeUtil.MINUTE));
displayFeedback(_bundle, msg);
}
}
protected void success () {
dispatchMessage(new TellFeedbackMessage(target, message, false),
ChatCodes.PLACE_CHAT_TYPE);
addChatter(target);
if (rl != null) {
rl.requestCompleted(target);
}
}
public void requestFailed (String reason) {
String msg = MessageBundle.compose(
"m.tell_failed", MessageBundle.taint(target), reason);
TellFeedbackMessage tfm = new TellFeedbackMessage(target, msg, true);
tfm.bundle = _bundle;
dispatchMessage(tfm, ChatCodes.PLACE_CHAT_TYPE);
if (rl != null) {
rl.requestFailed(null);
}
}
};
_cservice.tell(_ctx.getClient(), target, message, listener);
}
/**
* Configures a message that will be automatically reported to anyone that sends a tell message
* to this client to indicate that we are busy or away from the keyboard.
*/
public void setAwayMessage (String message)
{
if (message != null) {
message = filter(message, null, true);
if (message == null) {
// they filtered away their own away message.. change it to something
message = "...";
}
}
// pass the buck right on along
_cservice.away(_ctx.getClient(), message);
}
/**
* Adds an additional object via which chat messages may arrive. The chat director assumes the
* caller will be managing the subscription to this object and will remain subscribed to it for
* as long as it remains in effect as an auxiliary chat source.
*
* @param localtype a type to be associated with all chat messages that arrive on the specified
* DObject.
*/
public void addAuxiliarySource (DObject source, String localtype)
{
source.addListener(this);
_auxes.put(source.getOid(), localtype);
}
/**
* Removes a previously added auxiliary chat source.
*/
public void removeAuxiliarySource (DObject source)
{
source.removeListener(this);
_auxes.remove(source.getOid());
}
/**
* Run a message through all the currently registered filters.
*/
public String filter (String msg, Name otherUser, boolean outgoing)
{
_filterMessageOp.setMessage(msg, otherUser, outgoing);
_filters.apply(_filterMessageOp);
return _filterMessageOp.getMessage();
}
/**
* Runs the supplied message through the various chat mogrifications.
*/
public String mogrifyChat (String text)
{
return mogrifyChat(text, false, true);
}
// documentation inherited
public boolean locationMayChange (int placeId)
{
// we accept all location change requests
return true;
}
// documentation inherited
public void locationDidChange (PlaceObject place)
{
if (_place != null) {
// unlisten to our old object
_place.removeListener(this);
}
// listen to the new object
_place = place;
if (_place != null) {
_place.addListener(this);
}
}
// documentation inherited
public void locationChangeFailed (int placeId, String reason)
{
// nothing we care about
}
// documentation inherited
public void messageReceived (MessageEvent event)
{
if (CHAT_NOTIFICATION.equals(event.getName())) {
ChatMessage msg = (ChatMessage)event.getArgs()[0];
String localtype = getLocalType(event.getTargetOid());
processReceivedMessage(msg, localtype);
}
}
@Override
public void clientDidLogon (Client client)
{
super.clientDidLogon(client);
// listen on the client object for tells
addAuxiliarySource(_clobj = client.getClientObject(), USER_CHAT_TYPE);
}
@Override
public void clientObjectDidChange (Client client)
{
super.clientObjectDidChange(client);
// change what we're listening to for tells
removeAuxiliarySource(_clobj);
addAuxiliarySource(_clobj = client.getClientObject(), USER_CHAT_TYPE);
clearDisplays();
}
@Override
public void clientDidLogoff (Client client)
{
super.clientDidLogoff(client);
// stop listening to it for tells
if (_clobj != null) {
removeAuxiliarySource(_clobj);
_clobj = null;
}
// in fact, clear out all auxiliary sources
_auxes.clear();
clearDisplays();
// clear out the list of people we've chatted with
_chatters.clear();
notifyChatterObservers();
// clear the _place
locationDidChange(null);
// clear our service
_cservice = null;
}
/**
* Processes and dispatches the specified chat message.
*/
protected void processReceivedMessage (ChatMessage msg, String localtype)
{
String autoResponse = null;
Name speaker = null;
Name speakerDisplay = null;
byte mode = (byte)-1;
// figure out if the message was triggered by another user
if (msg instanceof UserMessage) {
UserMessage umsg = (UserMessage)msg;
speaker = umsg.speaker;
speakerDisplay = umsg.getSpeakerDisplayName();
mode = umsg.mode;
} else if (msg instanceof UserSystemMessage) {
speaker = ((UserSystemMessage)msg).speaker;
speakerDisplay = speaker;
}
// Translate and timestamp the message. This would happen during dispatch but we
// need to do it ahead of filtering.
setClientInfo(msg, localtype);
// if there was an originating speaker, see if we want to hear it
if (speaker != null) {
if ((msg.message = filter(msg.message, speaker, false)) == null) {
return;
}
if (USER_CHAT_TYPE.equals(localtype) &&
mode == ChatCodes.DEFAULT_MODE) {
// if it was a tell, add the speaker as a chatter
addChatter(speaker);
// note whether or not we have an auto-response
BodyObject self = (BodyObject)_ctx.getClient().getClientObject();
if (!StringUtil.isBlank(self.awayMessage)) {
autoResponse = self.awayMessage;
}
}
}
// and send it off!
dispatchMessage(msg, localtype);
// if we auto-responded, report as much
if (autoResponse != null) {
String amsg = MessageBundle.tcompose(
"m.auto_responded", speakerDisplay, autoResponse);
displayFeedback(_bundle, amsg);
}
}
/**
* Dispatch a message to chat displays once it is fully prepared with the clientinfo.
*/
protected void dispatchPreparedMessage (ChatMessage message)
{
_displayMessageOp.setMessage(message);
_displays.apply(_displayMessageOp);
}
/**
* Called to determine whether we are permitted to post the supplied chat message. Derived
* classes may wish to throttle chat or restrict certain types in certain circumstances for
* whatever reason.
*
* @return null if the chat is permitted, SUCCESS if the chat is permitted and has already been
* dealt with, or a translatable string indicating the reason for rejection if not.
*/
protected String checkCanChat (SpeakService speakSvc, String message, byte mode)
{
return null;
}
/**
* Delivers a plain chat message (not a slash command) on the specified speak service in the
* specified mode. The message will be mogrified and filtered prior to delivery.
*
* @return {@link ChatCodes#SUCCESS} if the message was delivered or a string indicating why it
* failed.
*/
protected String deliverChat (SpeakService speakSvc, String message, byte mode)
{
// run the message through our mogrification process
message = mogrifyChat(message, true, mode != ChatCodes.EMOTE_MODE);
// mogrification may result in something being turned into a slash command, in which case
// we have to run everything through again from the start
if (message.startsWith("/")) {
return requestChat(speakSvc, message, false);
}
// make sure this client is not restricted from performing this chat message for some
// reason or other
String errmsg = checkCanChat(speakSvc, message, mode);
if (errmsg != null) {
return errmsg;
}
// speak on the specified service
requestSpeak(speakSvc, message, mode);
return ChatCodes.SUCCESS;
}
/**
* Adds the specified command to the history.
*/
protected void addToHistory (String cmd)
{
// remove any previous instance of this command
_history.remove(cmd);
// append it to the end
_history.add(cmd);
// prune the history once it extends beyond max size
if (_history.size() > MAX_COMMAND_HISTORY) {
_history.remove(0);
}
}
/**
* Mogrifies common literary crutches into more appealing chat or commands.
*
* @param transformsAllowed if true, the chat may transformed into a different mode. (lol ->
* /emote laughs)
* @param capFirst if true, the first letter of the text is capitalized. This is not desired if
* the chat is already an emote.
*/
protected String mogrifyChat (
String text, boolean transformsAllowed, boolean capFirst)
{
int tlen = text.length();
if (tlen == 0) {
return text;
// check to make sure there aren't too many caps
} else if (tlen > 7 && suppressTooManyCaps()) {
// count caps
int caps = 0;
for (int ii=0; ii < tlen; ii++) {
if (Character.isUpperCase(text.charAt(ii))) {
caps++;
if (caps > (tlen / 2)) {
// lowercase the whole string if there are
text = text.toLowerCase();
break;
}
}
}
}
StringBuffer buf = new StringBuffer(text);
buf = mogrifyChat(buf, transformsAllowed, capFirst);
return buf.toString();
}
/** Helper function for {@link #mogrifyChat(String,boolean,boolean)}. */
protected StringBuffer mogrifyChat (
StringBuffer buf, boolean transformsAllowed, boolean capFirst)
{
if (_mogrifyChat) {
// do the generic mogrifications and translations
buf = translatedReplacements("x.mogrifies", buf);
// perform themed expansions and transformations
if (transformsAllowed) {
buf = translatedReplacements("x.transforms", buf);
}
}
/*
// capitalize the first letter
if (capFirst) {
buf.setCharAt(0, Character.toUpperCase(buf.charAt(0)));
}
// and capitalize any letters after a sentence-ending punctuation
Pattern p = Pattern.compile("([^\\.][\\.\\?\\!](\\s)+\\p{Ll})");
Matcher m = p.matcher(buf);
if (m.find()) {
buf = new StringBuilder();
m.appendReplacement(buf, m.group().toUpperCase());
while (m.find()) {
m.appendReplacement(buf, m.group().toUpperCase());
}
m.appendTail(buf);
}
*/
return buf;
}
/**
* Do all the replacements (mogrifications) specified in the translation string specified by
* the key.
*/
protected StringBuffer translatedReplacements (String key, StringBuffer buf)
{
MessageBundle bundle = _msgmgr.getBundle(_bundle);
if (!bundle.exists(key)) {
return buf;
}
StringTokenizer st = new StringTokenizer(bundle.get(key), "#");
// apply the replacements to each mogrification that matches
while (st.hasMoreTokens()) {
String pattern = st.nextToken();
String replace = st.nextToken();
Matcher m = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE).matcher(buf);
if (m.find()) {
buf = new StringBuffer();
m.appendReplacement(buf, replace);
// they may match more than once
while (m.find()) {
m.appendReplacement(buf, replace);
}
m.appendTail(buf);
}
}
return buf;
}
/**
* Return true if we should lowercase messages containing more than half upper-case characters.
*/
protected boolean suppressTooManyCaps ()
{
return true;
}
/**
* Check that after mogrification the message is not too long.
* @return an error message if it is too long, or null.
*/
protected String checkLength (String msg)
{
return null; // everything's ok by default
}
/**
* Returns a hashmap containing all command handlers that match the specified command (i.e. the
* specified command is a prefix of their registered command string).
*/
protected HashMap<String, CommandHandler> getCommandHandlers (String command)
{
HashMap<String, CommandHandler> matches = Maps.newHashMap();
BodyObject user = (BodyObject)_ctx.getClient().getClientObject();
for (Map.Entry<String, CommandHandler> entry : _handlers.entrySet()) {
String cmd = entry.getKey();
if (!cmd.startsWith(command)) {
continue;
}
CommandHandler handler = entry.getValue();
if (!handler.checkAccess(user)) {
continue;
}
matches.put(cmd, handler);
}
return matches;
}
/**
* Adds a chatter to our list of recent chatters.
*/
protected void addChatter (Name name)
{
// check to see if the chatter validator approves..
if ((_chatterValidator != null) && (!_chatterValidator.isChatterValid(name))) {
return;
}
boolean wasthere = _chatters.remove(name);
_chatters.addFirst(name);
if (!wasthere) {
if (_chatters.size() > MAX_CHATTERS) {
_chatters.removeLast();
}
notifyChatterObservers();
}
}
/**
* Notifies all registered {@link ChatterObserver}s that the list of chatters has changed.
*/
protected void notifyChatterObservers ()
{
_chatterObservers.apply(new ObserverList.ObserverOp<ChatterObserver>() {
public boolean apply (ChatterObserver observer) {
observer.chattersUpdated(_chatters.listIterator());
return true;
}
});
}
/**
* Set the "client info" on the specified message, if not already set.
*/
protected void setClientInfo (ChatMessage msg, String localType)
{
if (msg.localtype == null) {
msg.setClientInfo(xlate(msg.bundle, msg.message), localType);
}
}
/**
* Translates the specified message using the specified bundle.
*/
protected String xlate (String bundle, String message)
{
if (bundle != null && _msgmgr != null) {
MessageBundle msgb = _msgmgr.getBundle(bundle);
if (msgb == null) {
log.warning("No message bundle available to translate message", "bundle", bundle,
"message", message);
} else {
message = msgb.xlate(message);
}
}
return message;
}
/**
* Display the specified system message as if it had come from the server.
*/
protected void displaySystem (String bundle, String message, byte attLevel, String localtype)
{
// nothing should be untranslated, so pass the default bundle if need be.
if (bundle == null) {
bundle = _bundle;
}
SystemMessage msg = new SystemMessage(message, bundle, attLevel);
dispatchMessage(msg, localtype);
}
/**
* Looks up and returns the message type associated with the specified oid.
*/
protected String getLocalType (int oid)
{
String type = _auxes.get(oid);
return (type == null) ? PLACE_CHAT_TYPE : type;
}
@Override
protected void registerServices (Client client)
{
client.addServiceGroup(CrowdCodes.CROWD_GROUP);
}
@Override
protected void fetchServices (Client client)
{
// get a handle on our chat service
_cservice = client.requireService(ChatService.class);
}
/**
* An operation that checks with all chat filters to properly filter a message prior to sending
* to the server or displaying.
*/
protected static class FilterMessageOp
implements ObserverList.ObserverOp<ChatFilter>
{
public void setMessage (String msg, Name otherUser, boolean outgoing)
{
_msg = msg;
_otherUser = otherUser;
_out = outgoing;
}
public boolean apply (ChatFilter observer)
{
if (_msg != null) {
_msg = observer.filter(_msg, _otherUser, _out);
}
return true;
}
public String getMessage ()
{
return _msg;
}
protected Name _otherUser;
protected String _msg;
protected boolean _out;
}
/**
* An observer op used to dispatch ChatMessages on the client.
*/
protected static class DisplayMessageOp
implements ObserverList.ObserverOp<ChatDisplay>
{
public void setMessage (ChatMessage message)
{
_message = message;
_displayed = false;
}
public boolean apply (ChatDisplay observer)
{
if (observer.displayMessage(_message, _displayed)) {
_displayed = true;
}
return true;
}
protected ChatMessage _message;
protected boolean _displayed;
}
/** Implements <code>/help</code>. */
protected class HelpHandler extends CommandHandler
{
@Override
public String handleCommand (SpeakService speakSvc, String command,
String args, String[] history)
{
String hcmd = "";
// grab the command they want help on
if (!StringUtil.isBlank(args)) {
hcmd = args;
int sidx = args.indexOf(" ");
if (sidx != -1) {
hcmd = args.substring(0, sidx);
}
}
// let the user give commands with or with the /
if (hcmd.startsWith("/")) {
hcmd = hcmd.substring(1);
}
// handle "/help help" and "/help someboguscommand"
HashMap<String, CommandHandler> possibleCommands = getCommandHandlers(hcmd);
if (hcmd.equals("help") || possibleCommands.isEmpty()) {
possibleCommands = getCommandHandlers("");
possibleCommands.remove("help"); // remove help from the list
}
// if there is only one possible command display its usage
switch (possibleCommands.size()) {
case 1:
Iterator<String> itr = possibleCommands.keySet().iterator();
// this is a little funny, but we display the feeback message by hand and return
// SUCCESS so that the chat entry field doesn't think that we've failed and
// preserve our command text
displayFeedback(null, "m.usage_" + itr.next());
return ChatCodes.SUCCESS;
default:
Object[] commands = possibleCommands.keySet().toArray();
Arrays.sort(commands);
String commandList = "";
for (Object element : commands) {
commandList += " /" + element;
}
return MessageBundle.tcompose("m.usage_help", commandList);
}
}
}
/** Implements <code>/clear</code>. */
protected class ClearHandler extends CommandHandler
{
@Override
public String handleCommand (SpeakService speakSvc, String command,
String args, String[] history)
{
clearDisplays();
return ChatCodes.SUCCESS;
}
}
/** Implements <code>/speak</code>. */
protected class SpeakHandler extends CommandHandler
{
@Override
public String handleCommand (SpeakService speakSvc, String command,
String args, String[] history)
{
if (StringUtil.isBlank(args)) {
return "m.usage_speak";
}
// note the command to be stored in the history
history[0] = command + " ";
// we do not propogate the speakSvc, because /speak means use
// the default channel..
return requestChat(null, args, true);
}
}
/** Implements <code>/emote</code>. */
protected class EmoteHandler extends CommandHandler
{
@Override
public String handleCommand (SpeakService speakSvc, String command,
String args, String[] history)
{
if (StringUtil.isBlank(args)) {
return "m.usage_emote";
}
// note the command to be stored in the history
history[0] = command + " ";
return deliverChat(speakSvc, args, ChatCodes.EMOTE_MODE);
}
}
/** Implements <code>/think</code>. */
protected class ThinkHandler extends CommandHandler
{
@Override
public String handleCommand (SpeakService speakSvc, String command,
String args, String[] history)
{
if (StringUtil.isBlank(args)) {
return "m.usage_think";
}
// note the command to be stored in the history
history[0] = command + " ";
return deliverChat(speakSvc, args, ChatCodes.THINK_MODE);
}
}
/** Implements <code>/tell</code>. */
protected class TellHandler extends CommandHandler
{
@Override
public String handleCommand (SpeakService speakSvc, final String command,
String args, String[] history)
{
if (StringUtil.isBlank(args)) {
return "m.usage_tell";
}
final boolean useQuotes = args.startsWith("\"");
String[] bits = parseTell(args);
String handle = bits[0];
String message = bits[1];
// validate that we didn't eat all the tokens making the handle
if (StringUtil.isBlank(message)) {
return "m.usage_tell";
}
// make sure we're not trying to tell something to ourselves
BodyObject self = (BodyObject)_ctx.getClient().getClientObject();
if (handle.equalsIgnoreCase(self.getVisibleName().toString())) {
return "m.talk_self";
}
// and lets just give things an opportunity to sanitize the name
Name target = normalizeAsName(handle);
// mogrify the chat
message = mogrifyChat(message);
String err = checkLength(message);
if (err != null) {
return err;
}
// clear out from the history any tells that are mistypes
for (Iterator<String> iter = _history.iterator(); iter.hasNext(); ) {
String hist = iter.next();
if (hist.startsWith("/" + command)) {
String harg = hist.substring(command.length() + 1).trim();
// we blow away any historic tells that have msg content
if (!StringUtil.isBlank(parseTell(harg)[1])) {
iter.remove();
}
}
}
// store the full command in the history, even if it was mistyped
final String histEntry = command + " " +
(useQuotes ? ("\"" + target + "\"") : target.toString()) + " " + message;
history[0] = histEntry;
// request to send this text as a tell message
requestTell(target, escapeMessage(message), new ResultListener<Name>() {
public void requestCompleted (Name target) {
// replace the full one in the history with just: /tell "<handle>"
String newEntry = "/" + command + " " +
(useQuotes ? ("\"" + target + "\"") : String.valueOf(target)) + " ";
_history.remove(newEntry);
int dex = _history.lastIndexOf("/" + histEntry);
if (dex >= 0) {
_history.set(dex, newEntry);
} else {
_history.add(newEntry);
}
}
public void requestFailed (Exception cause) {
// do nothing
}
});
return ChatCodes.SUCCESS;
}
/**
* Parse the tell into two strings, handle and message. If either one is null then the
* parsing did not succeed.
*/
protected String[] parseTell (String args)
{
String handle, message;
if (args.startsWith("\"")) {
int nextQuote = args.indexOf('"', 1);
if (nextQuote == -1 || nextQuote == 1) {
handle = message = null; // bogus parsing
} else {
handle = args.substring(1, nextQuote).trim();
message = args.substring(nextQuote + 1).trim();
}
} else {
StringTokenizer st = new StringTokenizer(args);
handle = st.nextToken();
message = args.substring(handle.length()).trim();
}
return new String[] { handle, message };
}
/**
* Turn the user-entered string into a Name object, doing any particular normalization we
* want to do along the way so that "/tell Bob" and "/tell BoB" don't both show up in
* history.
*/
protected Name normalizeAsName (String handle)
{
return new Name(handle);
}
/**
* Escape or otherwise do any final processing on the message prior to sending it.
*/
protected String escapeMessage (String msg)
{
return msg;
}
}
/** Implements <code>/broadcast</code>. */
protected class BroadcastHandler extends CommandHandler
{
@Override
public String handleCommand (SpeakService speakSvc, String command,
String args, String[] history)
{
if (StringUtil.isBlank(args)) {
return "m.usage_broadcast";
}
// mogrify and verify length
args = mogrifyChat(args);
String err = checkLength(args);
if (err != null) {
return err;
}
// request the broadcast
requestBroadcast(args);
// note the command to be stored in the history
history[0] = command + " ";
return ChatCodes.SUCCESS;
}
@Override
public boolean checkAccess (BodyObject user)
{
return user.checkAccess(ChatCodes.BROADCAST_ACCESS) == null;
}
}
/** Our active chat context. */
protected CrowdContext _ctx;
/** Provides access to chat-related server-side services. */
protected ChatService _cservice;
/** The message manager. */
protected MessageManager _msgmgr;
/** The bundle to use for our own internal messages. */
protected String _bundle;
/** The place object that we currently occupy. */
protected PlaceObject _place;
/** The client object that we're listening to for tells. */
protected ClientObject _clobj;
/** Whether or not to run chat through the mogrifier. */
protected boolean _mogrifyChat= true;
/** A list of registered chat displays. */
protected ObserverList<ChatDisplay> _displays =
new ObserverList<ChatDisplay>(ObserverList.SAFE_IN_ORDER_NOTIFY);
/** A list of registered chat filters. */
protected ObserverList<ChatFilter> _filters =
new ObserverList<ChatFilter>(ObserverList.SAFE_IN_ORDER_NOTIFY);
/** A mapping from auxiliary chat objects to the types under which
* they are registered. */
protected HashIntMap<String> _auxes = new HashIntMap<String>();
/** Validator of who may be added to the chatters list. */
protected ChatterValidator _chatterValidator;
/** Usernames of users we've recently chatted with. */
protected LinkedList<Name> _chatters = new LinkedList<Name>();
/** Observers that are watching our chatters list. */
protected ObserverList<ChatterObserver> _chatterObservers =
new ObserverList<ChatterObserver>(ObserverList.SAFE_IN_ORDER_NOTIFY);
/** Operation used to filter chat messages. */
protected FilterMessageOp _filterMessageOp = new FilterMessageOp();
/** Operation used to display chat messages. */
protected DisplayMessageOp _displayMessageOp = new DisplayMessageOp();
/** Registered chat command handlers. */
protected static HashMap<String, CommandHandler> _handlers = Maps.newHashMap();
/** A history of chat commands. */
protected static ArrayList<String> _history = Lists.newArrayList();
/** The maximum number of chatter usernames to track. */
protected static final int MAX_CHATTERS = 6;
/** The maximum number of commands to keep in the chat history. */
protected static final int MAX_COMMAND_HISTORY = 10;
}
|
s/validator/filter/ in an appropriate place, and some other comment widening
git-svn-id: a1a4b28b82a3276cc491891159dd9963a0a72fae@5822 542714f4-19e9-0310-aa3c-eee0fc999fb1
|
src/java/com/threerings/crowd/chat/client/ChatDirector.java
|
s/validator/filter/ in an appropriate place, and some other comment widening
|
<ide><path>rc/java/com/threerings/crowd/chat/client/ChatDirector.java
<ide> * message on.
<ide> * @param command the slash command that was used to invoke this handler
<ide> * (e.g. <code>/tell</code>).
<del> * @param args the arguments provided along with the command (e.g. <code>Bob hello</code>)
<add> * @param args the arguments provided along with the command (e.g. <code>Bob hello</code>)
<ide> * or <code>null</code> if no arguments were supplied.
<ide> * @param history an in/out parameter that allows the command to modify the text that will
<ide> * be appended to the chat history. If this is set to null, nothing will be appended.
<ide> /**
<ide> * Returns true if this user should have access to this chat command.
<ide> */
<del> public boolean checkAccess (BodyObject user)
<del> {
<add> public boolean checkAccess (BodyObject user) {
<ide> return true;
<ide> }
<ide> }
<ide> }
<ide>
<ide> /**
<del> * Adds the specified chat filter to the list of filters. All chat requests and receipts will
<add> * Adds the specified chat filter to the list of filters. All chat requests and receipts will
<ide> * be filtered with all filters before they being sent or dispatched locally.
<ide> */
<ide> public void addChatFilter (ChatFilter filter)
<ide> }
<ide>
<ide> /**
<del> * Removes the specified chat validator from the list of chat validators.
<add> * Removes the specified chat filter from the list of chat filter.
<ide> */
<ide> public void removeChatFilter (ChatFilter filter)
<ide> {
<ide> * @param msg the message bundle via which the slash command will be translated (as
<ide> * <code>c.</code><i>command</i>). If no translation exists the command will be
<ide> * <code>/</code><i>command</i>.
<del> * @param command the name of the command that will be used to invoke this handler
<del> * (e.g. <code>tell</code> if the command will be invoked as <code>/tell</code>).
<add> * @param command the name of the command that will be used to invoke this handler (e.g.
<add> * <code>tell</code> if the command will be invoked as <code>/tell</code>).
<ide> * @param handler the chat command handler itself.
<ide> */
<ide> public void registerCommandHandler (MessageBundle msg, String command, CommandHandler handler)
<ide> }
<ide>
<ide> /**
<del> * Display a system INFO message as if it had come from the server. The localtype of the
<add> * Display a system INFO message as if it had come from the server. The localtype of the
<ide> * message will be PLACE_CHAT_TYPE.
<ide> *
<ide> * Info messages are sent when something happens that was neither directly triggered by the
<ide> }
<ide>
<ide> /**
<del> * Display a system FEEDBACK message as if it had come from the server. The localtype of the
<add> * Display a system FEEDBACK message as if it had come from the server. The localtype of the
<ide> * message will be PLACE_CHAT_TYPE.
<ide> *
<ide> * Feedback messages are sent in direct response to a user action, usually to indicate success
<ide> }
<ide>
<ide> /**
<del> * Display a system ATTENTION message as if it had come from the server. The localtype of the
<add> * Display a system ATTENTION message as if it had come from the server. The localtype of the
<ide> * message will be PLACE_CHAT_TYPE.
<ide> *
<ide> * Attention messages are sent when something requires user action that did not result from
<ide> if (message != null) {
<ide> message = filter(message, null, true);
<ide> if (message == null) {
<del> // they filtered away their own away message.. change it to something
<add> // they filtered away their own away message... change it to something
<ide> message = "...";
<ide> }
<ide> }
<ide> * @param capFirst if true, the first letter of the text is capitalized. This is not desired if
<ide> * the chat is already an emote.
<ide> */
<del> protected String mogrifyChat (
<del> String text, boolean transformsAllowed, boolean capFirst)
<add> protected String mogrifyChat (String text, boolean transformsAllowed, boolean capFirst)
<ide> {
<ide> int tlen = text.length();
<ide> if (tlen == 0) {
|
|
Java
|
apache-2.0
|
b63cc82cb524d8374375f33580fa338f3dfc80bf
| 0 |
thlcly/LeetCodeOJ
|
package com.leetcode.aaront;
import java.util.Arrays;
/**
* @author tonyhui
* @since 16/3/20
*/
public class RotateArray {
public static void main(String[] args) {
int[] nums = {1, 2, 3, 4, 5, 6, 7};
rotate(nums, 3);
System.out.println(Arrays.toString(nums));
}
/**
* 效率较低,不能ac
*
* @param nums
* @param k
*/
public static void rotate(int[] nums, int k) {
int step = k % (nums.length);
for (int i = 0; i < step; i++) {
int temp = nums[nums.length - 1];
move(nums);
nums[0] = temp;
}
}
public static void move(int[] nums) {
for (int i = nums.length - 1; i > 0; i--) {
nums[i] = nums[i - 1];
}
}
/**
* 高效方法 O(n)
* 思路:
* 1 2 3 4 5 6 7 8 9 10 / 4
* step 1: 10 9 8 7 6 5 4 3 2 1
* step 2: 7 8 9 10 6 5 4 3 2 1
* step 3: 7 8 9 10 1 2 3 4 5 6
* ooh amazing ! it is perfect algorithm
*/
public void rotate2(int[] nums, int k) {
k %= nums.length;
reverse(nums, 0, nums.length - 1); // reverse the whole array
reverse(nums, 0, k - 1); // reverse the first part
reverse(nums, k, nums.length - 1); // reverse the second part
}
public void reverse(int[] nums, int l, int r) {
while (l < r) {
int temp = nums[l];
nums[l++] = nums[r];
nums[r--] = temp;
}
}
}
|
189/src/com/leetcode/aaront/RotateArray.java
|
package com.leetcode.aaront;
/**
* @author tonyhui
* @since 16/3/20
*/
public class RotateArray {
public static void main(String[] args) {
int[] nums = {1,2,3,4,5,6,7};
rotate(nums, 3);
for(int i = 0;i<nums.length;i++){
System.out.println(nums[i]);
}
}
/**
* 效率较低,不能ac
* @param nums
* @param k
*/
public static void rotate(int[] nums, int k) {
int step=k%nums.length;
for (int i = 0; i <= step; i++) {
int temp = nums[0];
move(nums);
nums[nums.length-1] = temp;
}
}
public static void move(int[] nums) {
for (int i = 0, len = nums.length; i < len - 1; i++) {
nums[i]=nums[i+1];
}
}
}
|
refer Okami algorithm the time complexity is O(n)
|
189/src/com/leetcode/aaront/RotateArray.java
|
refer Okami algorithm the time complexity is O(n)
|
<ide><path>89/src/com/leetcode/aaront/RotateArray.java
<ide> package com.leetcode.aaront;
<add>
<add>import java.util.Arrays;
<ide>
<ide> /**
<ide> * @author tonyhui
<ide> public class RotateArray {
<ide> public static void main(String[] args) {
<ide>
<del> int[] nums = {1,2,3,4,5,6,7};
<add> int[] nums = {1, 2, 3, 4, 5, 6, 7};
<ide> rotate(nums, 3);
<del> for(int i = 0;i<nums.length;i++){
<del> System.out.println(nums[i]);
<del> }
<add> System.out.println(Arrays.toString(nums));
<ide> }
<ide>
<ide> /**
<ide> * 效率较低,不能ac
<add> *
<ide> * @param nums
<ide> * @param k
<ide> */
<ide>
<ide> public static void rotate(int[] nums, int k) {
<del> int step=k%nums.length;
<del> for (int i = 0; i <= step; i++) {
<del> int temp = nums[0];
<add> int step = k % (nums.length);
<add> for (int i = 0; i < step; i++) {
<add> int temp = nums[nums.length - 1];
<ide> move(nums);
<del> nums[nums.length-1] = temp;
<add> nums[0] = temp;
<add> }
<add>
<add> }
<add>
<add> public static void move(int[] nums) {
<add> for (int i = nums.length - 1; i > 0; i--) {
<add> nums[i] = nums[i - 1];
<ide> }
<ide> }
<ide>
<del> public static void move(int[] nums) {
<del> for (int i = 0, len = nums.length; i < len - 1; i++) {
<del> nums[i]=nums[i+1];
<add> /**
<add> * 高效方法 O(n)
<add> * 思路:
<add> * 1 2 3 4 5 6 7 8 9 10 / 4
<add> * step 1: 10 9 8 7 6 5 4 3 2 1
<add> * step 2: 7 8 9 10 6 5 4 3 2 1
<add> * step 3: 7 8 9 10 1 2 3 4 5 6
<add> * ooh amazing ! it is perfect algorithm
<add> */
<add>
<add> public void rotate2(int[] nums, int k) {
<add> k %= nums.length;
<add> reverse(nums, 0, nums.length - 1); // reverse the whole array
<add> reverse(nums, 0, k - 1); // reverse the first part
<add> reverse(nums, k, nums.length - 1); // reverse the second part
<add> }
<add>
<add> public void reverse(int[] nums, int l, int r) {
<add> while (l < r) {
<add> int temp = nums[l];
<add> nums[l++] = nums[r];
<add> nums[r--] = temp;
<ide> }
<ide> }
<ide> }
|
|
Java
|
mit
|
error: pathspec 'android/java/com/sometrik/framework/FWActionSheet.java' did not match any file(s) known to git
|
1e06de10c5cf61e89a968fefcfd81bd20cfb3137
| 1 |
Sometrik/framework,Sometrik/framework,Sometrik/framework
|
package com.sometrik.framework;
import com.sometrik.framework.NativeCommand.Selector;
import android.graphics.Bitmap;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.widget.PopupMenu;
public class FWActionSheet extends PopupMenu implements NativeCommandHandler {
private FrameWork frame;
private MenuInflater inflater;
private Menu menu;
private int id;
public FWActionSheet(FrameWork frame, View anchor, int id) {
super(frame, anchor);
this.id = id;
inflater = new MenuInflater(frame);
menu = getMenu();
}
@Override
public void onScreenOrientationChange(boolean isLandscape) {
// TODO Auto-generated method stub
}
@Override
public void addChild(View view) {
// TODO Auto-generated method stub
}
@Override
public void addOption(int optionId, String text) {
menu.add(Menu.NONE, optionId, Menu.NONE, text);
}
@Override
public void addColumn(String text, int columnType) {
// TODO Auto-generated method stub
}
@Override
public void addData(String text, int row, int column, int sheet) {
// TODO Auto-generated method stub
}
@Override
public void setValue(String v) {
// TODO Auto-generated method stub
}
@Override
public void setBitmap(Bitmap bitmap) {
// TODO Auto-generated method stub
}
@Override
public void addImageUrl(String url, int width, int height) {
// TODO Auto-generated method stub
}
@Override
public void setValue(int v) {
if (v > 0) {
show();
}
}
@Override
public void reshape(int value, int size) {
// TODO Auto-generated method stub
}
@Override
public void reshape(int size) {
// TODO Auto-generated method stub
}
@Override
public void setViewVisibility(boolean visible) {
// TODO Auto-generated method stub
}
@Override
public void setStyle(Selector selector, String key, String value) {
// TODO Auto-generated method stub
}
@Override
public void setError(boolean hasError, String errorText) {
// TODO Auto-generated method stub
}
@Override
public void clear() {
// TODO Auto-generated method stub
}
@Override
public void flush() {
// TODO Auto-generated method stub
}
@Override
public void deinitialize() {
// TODO Auto-generated method stub
}
@Override
public int getElementId() {
return id;
}
}
|
android/java/com/sometrik/framework/FWActionSheet.java
|
Add java FWActionSheet
|
android/java/com/sometrik/framework/FWActionSheet.java
|
Add java FWActionSheet
|
<ide><path>ndroid/java/com/sometrik/framework/FWActionSheet.java
<add>package com.sometrik.framework;
<add>
<add>import com.sometrik.framework.NativeCommand.Selector;
<add>
<add>import android.graphics.Bitmap;
<add>import android.view.Menu;
<add>import android.view.MenuInflater;
<add>import android.view.View;
<add>import android.widget.PopupMenu;
<add>
<add>public class FWActionSheet extends PopupMenu implements NativeCommandHandler {
<add>
<add> private FrameWork frame;
<add> private MenuInflater inflater;
<add> private Menu menu;
<add> private int id;
<add>
<add> public FWActionSheet(FrameWork frame, View anchor, int id) {
<add> super(frame, anchor);
<add> this.id = id;
<add> inflater = new MenuInflater(frame);
<add> menu = getMenu();
<add> }
<add>
<add> @Override
<add> public void onScreenOrientationChange(boolean isLandscape) {
<add> // TODO Auto-generated method stub
<add>
<add> }
<add>
<add> @Override
<add> public void addChild(View view) {
<add> // TODO Auto-generated method stub
<add>
<add> }
<add>
<add> @Override
<add> public void addOption(int optionId, String text) {
<add> menu.add(Menu.NONE, optionId, Menu.NONE, text);
<add> }
<add>
<add> @Override
<add> public void addColumn(String text, int columnType) {
<add> // TODO Auto-generated method stub
<add>
<add> }
<add>
<add> @Override
<add> public void addData(String text, int row, int column, int sheet) {
<add> // TODO Auto-generated method stub
<add>
<add> }
<add>
<add> @Override
<add> public void setValue(String v) {
<add> // TODO Auto-generated method stub
<add>
<add> }
<add>
<add> @Override
<add> public void setBitmap(Bitmap bitmap) {
<add> // TODO Auto-generated method stub
<add>
<add> }
<add>
<add> @Override
<add> public void addImageUrl(String url, int width, int height) {
<add> // TODO Auto-generated method stub
<add>
<add> }
<add>
<add> @Override
<add> public void setValue(int v) {
<add> if (v > 0) {
<add> show();
<add> }
<add> }
<add>
<add> @Override
<add> public void reshape(int value, int size) {
<add> // TODO Auto-generated method stub
<add>
<add> }
<add>
<add> @Override
<add> public void reshape(int size) {
<add> // TODO Auto-generated method stub
<add>
<add> }
<add>
<add> @Override
<add> public void setViewVisibility(boolean visible) {
<add> // TODO Auto-generated method stub
<add>
<add> }
<add>
<add> @Override
<add> public void setStyle(Selector selector, String key, String value) {
<add> // TODO Auto-generated method stub
<add>
<add> }
<add>
<add> @Override
<add> public void setError(boolean hasError, String errorText) {
<add> // TODO Auto-generated method stub
<add>
<add> }
<add>
<add> @Override
<add> public void clear() {
<add> // TODO Auto-generated method stub
<add>
<add> }
<add>
<add> @Override
<add> public void flush() {
<add> // TODO Auto-generated method stub
<add>
<add> }
<add>
<add> @Override
<add> public void deinitialize() {
<add> // TODO Auto-generated method stub
<add>
<add> }
<add>
<add> @Override
<add> public int getElementId() {
<add> return id;
<add> }
<add>
<add>}
|
|
Java
|
apache-2.0
|
c0da01d0f21449479c0288409d3bbf06d2f53c4f
| 0 |
citygml4j/citygml4j
|
/*
* citygml4j - The Open Source Java API for CityGML
* https://github.com/citygml4j
*
* Copyright 2013-2018 Claus Nagel <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.citygml4j.builder.cityjson.marshal.util;
import org.citygml4j.builder.cityjson.marshal.CityJSONMarshaller;
import org.citygml4j.model.gml.geometry.complexes.CompositeSurface;
import org.citygml4j.model.gml.geometry.primitives.AbstractSurface;
import org.citygml4j.model.gml.geometry.primitives.OrientableSurface;
import org.citygml4j.model.gml.geometry.primitives.Polygon;
import org.citygml4j.model.gml.geometry.primitives.Surface;
import org.citygml4j.util.walker.GeometryWalker;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class SurfaceCollector extends GeometryWalker {
private int lod;
private Map<Integer, List<AbstractSurface>> surfaces = new HashMap<>();
public boolean hasSurfaces() {
return !surfaces.isEmpty();
}
public Collection<AbstractSurface> getSurfaces(int lod) {
return surfaces.get(lod);
}
public void setLod(int lod) {
this.lod = lod;
}
@Override
public void visit(CompositeSurface surface) {
collect(surface);
}
@Override
public void visit(OrientableSurface surface) {
collect(surface);
}
@Override
public void visit(Surface surface) {
collect(surface);
}
@Override
public void visit(Polygon surface) {
collect(surface);
}
private void collect(AbstractSurface surface) {
if (!surface.hasLocalProperty(CityJSONMarshaller.GEOMETRY_XLINK_TARGET)) {
List<AbstractSurface> tmp = surfaces.computeIfAbsent(lod, k -> new ArrayList<>());
tmp.add(surface);
}
}
}
|
src/main/java/org/citygml4j/builder/cityjson/marshal/util/SurfaceCollector.java
|
/*
* citygml4j - The Open Source Java API for CityGML
* https://github.com/citygml4j
*
* Copyright 2013-2018 Claus Nagel <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.citygml4j.builder.cityjson.marshal.util;
import org.citygml4j.builder.cityjson.marshal.CityJSONMarshaller;
import org.citygml4j.model.gml.geometry.complexes.CompositeSurface;
import org.citygml4j.model.gml.geometry.primitives.AbstractSurface;
import org.citygml4j.model.gml.geometry.primitives.OrientableSurface;
import org.citygml4j.model.gml.geometry.primitives.Polygon;
import org.citygml4j.model.gml.geometry.primitives.Surface;
import org.citygml4j.util.walker.GeometryWalker;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class SurfaceCollector extends GeometryWalker {
private int lod;
private Map<Integer, List<AbstractSurface>> surfaces = new HashMap<>();
public boolean hasSurfaces() {
return !surfaces.isEmpty();
}
public Collection<AbstractSurface> getSurfaces(int lod) {
return surfaces.get(lod);
}
public void setLod(int lod) {
this.lod = lod;
}
@Override
public void visit(CompositeSurface surface) {
collect(surface);
}
@Override
public void visit(OrientableSurface surface) {
collect(surface);
}
@Override
public void visit(Surface surface) {
collect(surface);
}
@Override
public void visit(Polygon surface) {
collect(surface);
}
private void collect(AbstractSurface surface) {
if (!surface.hasLocalProperty(CityJSONMarshaller.GEOMETRY_XLINK_TARGET)) {
List<AbstractSurface> tmp = surfaces.get(lod);
if (tmp == null) {
tmp = new ArrayList<>();
surfaces.put(lod, tmp);
}
tmp.add(surface);
}
}
}
|
minor change
|
src/main/java/org/citygml4j/builder/cityjson/marshal/util/SurfaceCollector.java
|
minor change
|
<ide><path>rc/main/java/org/citygml4j/builder/cityjson/marshal/util/SurfaceCollector.java
<ide>
<ide> private void collect(AbstractSurface surface) {
<ide> if (!surface.hasLocalProperty(CityJSONMarshaller.GEOMETRY_XLINK_TARGET)) {
<del> List<AbstractSurface> tmp = surfaces.get(lod);
<del> if (tmp == null) {
<del> tmp = new ArrayList<>();
<del> surfaces.put(lod, tmp);
<del> }
<del>
<add> List<AbstractSurface> tmp = surfaces.computeIfAbsent(lod, k -> new ArrayList<>());
<ide> tmp.add(surface);
<ide> }
<ide> }
|
|
Java
|
mit
|
31485f34d80b1e7d37204a034cba5597a848f53f
| 0 |
ensonik/molecule,testinfected/molecule,testinfected/molecule,testinfected/molecule,ensonik/molecule,ensonik/molecule,ensonik/molecule,ensonik/molecule,testinfected/molecule,testinfected/molecule
|
package com.vtence.molecule.util;
import org.hamcrest.Matcher;
import org.junit.Test;
import java.util.Arrays;
import java.util.List;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.nullValue;
public class AcceptEncodingTest {
@Test public void
selectsNoEncodingWhenThereAreNonCandidates() {
assertSelected("gzip", in(), nullValue());
}
@Test public void
selectsAcceptableEncodingWithHighestQuality() {
assertSelected("compress; q=0.5, gzip", in("compress", "gzip"), equalTo("gzip"));
assertSelected("gzip, deflate", in("deflate", "gzip"), equalTo("gzip"));
}
@Test public void
selectsNoEncodingWhenCandidatesAreNotAcceptable() {
assertSelected("compress, deflate; q=0", in("gzip", "deflate"), nullValue());
}
@Test public void
considersIdentityEncodingAcceptableByDefault() {
assertSelected("", in("gzip", "identity"), equalTo("identity"));
assertSelected("deflate, gzip", in("identity"), equalTo("identity"));
assertSelected("deflate; q=0, gzip; q=0", in("gzip", "deflate", "identity"),
equalTo("identity"));
assertSelected("*; q=0, identity; q=0.1", in("gzip", "deflate", "identity"),
equalTo("identity"));
}
@Test public void
considersIdentityEncodingNoLongerAcceptableWhenExplicitlyOrImplicitlyRefused() {
assertSelected("identity; q=0", in("identity"), nullValue());
assertSelected("*; q=0", in("identity"), nullValue());
}
@Test public void
selectsFirstOfHighestQualityEncodingsWhenAnyIsAcceptable() {
assertSelected("*", in("gzip", "deflate", "identity"), equalTo("gzip"));
assertSelected("gzip; q=0.9, *", in("gzip", "deflate", "compress"), equalTo("deflate"));
}
private void assertSelected(String header,
List<String> candidates,
Matcher<? super String> matcher) {
AcceptEncoding acceptEncoding = AcceptEncoding.parse(header);
assertThat("selected encoding", acceptEncoding.selectBestEncoding(candidates), matcher);
}
public static List<String> in(String... candidates) {
return Arrays.asList(candidates);
}
}
|
src/test/java/com/vtence/molecule/util/AcceptEncodingTest.java
|
package com.vtence.molecule.util;
import org.hamcrest.Matcher;
import org.junit.Test;
import java.util.Arrays;
import java.util.List;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.nullValue;
public class AcceptEncodingTest {
@Test public void
selectsNoEncodingWhenThereAreNonCandidates() {
assertSelected("gzip", in(), nullValue());
}
@Test public void
selectsAcceptableEncodingWithHighestQuality() {
assertSelected("compress; q=0.5, gzip", in("compress", "gzip"), equalTo("gzip"));
assertSelected("gzip, deflate", in("deflate", "gzip"), equalTo("gzip"));
}
@Test public void
selectsNoEncodingWhenCandidatesAreNotAcceptable() {
assertSelected("compress, deflate; q=0", in("gzip", "deflate"), nullValue());
}
@Test public void
considersIdentityEncodingAcceptableByDefault() {
assertSelected("", in("identity"), equalTo("identity"));
assertSelected("deflate, gzip", in("identity"), equalTo("identity"));
assertSelected("deflate; q=0, gzip; q=0", in("gzip", "deflate", "identity"),
equalTo("identity"));
assertSelected("*; q=0, identity; q=0.1", in("gzip", "deflate", "identity"),
equalTo("identity"));
}
@Test public void
considersIdentityEncodingNoLongerAcceptableWhenExplicitlyOrImplicitlyRefused() {
assertSelected("identity; q=0", in("identity"), nullValue());
assertSelected("*; q=0", in("identity"), nullValue());
}
@Test public void
selectsFirstOfHighestQualityEncodingsWhenAnyIsAcceptable() {
assertSelected("*", in("gzip", "deflate", "identity"), equalTo("gzip"));
assertSelected("gzip; q=0.9, *", in("gzip", "deflate", "compress"), equalTo("deflate"));
}
private void assertSelected(String header,
List<String> candidates,
Matcher<? super String> matcher) {
AcceptEncoding acceptEncoding = AcceptEncoding.parse(header);
assertThat("selected encoding", acceptEncoding.selectBestEncoding(candidates), matcher);
}
public static List<String> in(String... candidates) {
return Arrays.asList(candidates);
}
}
|
Clarify that identity encoding is the best option when no accept-encoding header is present in the request
|
src/test/java/com/vtence/molecule/util/AcceptEncodingTest.java
|
Clarify that identity encoding is the best option when no accept-encoding header is present in the request
|
<ide><path>rc/test/java/com/vtence/molecule/util/AcceptEncodingTest.java
<ide>
<ide> @Test public void
<ide> considersIdentityEncodingAcceptableByDefault() {
<del> assertSelected("", in("identity"), equalTo("identity"));
<add> assertSelected("", in("gzip", "identity"), equalTo("identity"));
<ide> assertSelected("deflate, gzip", in("identity"), equalTo("identity"));
<ide> assertSelected("deflate; q=0, gzip; q=0", in("gzip", "deflate", "identity"),
<ide> equalTo("identity"));
|
|
Java
|
apache-2.0
|
f7b5e97e86462c482ea059dd977d46bfea892116
| 0 |
ning/collector,pierre/collector,pierre/collector,ning/collector,ning/collector,ning/collector,pierre/collector,pierre/collector,pierre/collector,ning/collector,pierre/collector
|
/*
* Copyright 2010-2011 Ning, Inc.
*
* Ning licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.ning.metrics.collector.binder.providers;
import com.ning.metrics.collector.binder.config.CollectorConfig;
import com.ning.metrics.collector.util.NamedThreadFactory;
import com.ning.metrics.serialization.event.Event;
import com.ning.metrics.serialization.event.Granularity;
import com.ning.metrics.serialization.event.SmileBucketEvent;
import com.ning.metrics.serialization.event.SmileEnvelopeEvent;
import com.ning.metrics.serialization.smile.JsonStreamToSmileBucketEvent;
import com.ning.metrics.serialization.writer.DiskSpoolEventWriter;
import com.ning.metrics.serialization.writer.MockEventWriter;
import org.apache.log4j.Logger;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.smile.SmileFactory;
import org.codehaus.jackson.smile.SmileGenerator;
import org.codehaus.jackson.smile.SmileParser;
import org.joda.time.DateTime;
import org.skife.config.ConfigurationObjectFactory;
import org.testng.Assert;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.atomic.AtomicBoolean;
public class TestDiskSpoolEventWriterProvider
{
private static final Logger log = Logger.getLogger(TestDiskSpoolEventWriterProvider.class);
private static final String tmpFile = System.getProperty("java.io.tmpdir") + "TestDiskSpoolEventWriterProvider";
private Event originalEvent;
private DiskSpoolEventWriter writer;
private static final Granularity EVENT_GRANULARITY = Granularity.MONTHLY;
private static final DateTime EVENT_DATE_TIME = new DateTime(2010, 1, 1, 12, 0, 0, 42);
private static final String EVENT_NAME = "mySmile";
private final AtomicBoolean testsRun = new AtomicBoolean(false);
abstract static class TestConfig implements CollectorConfig
{
@Override
public long getFlushIntervalInSeconds()
{
return 1;
}
@Override
public String getSpoolDirectoryName()
{
return tmpFile;
}
}
@BeforeTest(alwaysRun = true)
public void setUp() throws IOException
{
createSmilePayload();
final CollectorConfig config = new ConfigurationObjectFactory(System.getProperties()).build(TestConfig.class);
writer = new DiskSpoolEventWriterProvider(
new MockEventWriter()
{
@Override
public void write(final Event event) throws IOException
{
try {
Assert.assertEquals(event.getClass(), SmileBucketEvent.class);
Assert.assertEquals(((SmileBucketEvent) event).getNumberOfEvent(), 5);
Assert.assertEquals(event.getName(), originalEvent.getName());
Assert.assertEquals(event.getGranularity(), originalEvent.getGranularity());
Assert.assertEquals(event.getOutputDir("bleh"), originalEvent.getOutputDir("bleh"));
final DateTime eventDateTime = SmileEnvelopeEvent.getEventDateTimeFromJson(((SmileBucketEvent) event).getBucket().get(0));
Assert.assertEquals(eventDateTime, EVENT_DATE_TIME);
Assert.assertEquals(event.getSerializedEvent(), originalEvent.getSerializedEvent());
}
finally {
testsRun.set(true);
}
}
},
new ScheduledThreadPoolExecutor(1, new NamedThreadFactory("spool to HDFS promoter")),
config
).get();
}
@AfterTest(alwaysRun = true)
public void tearDown() throws IOException
{
new File(tmpFile).delete();
}
@Test(groups = "slow")
public void testGet() throws Exception
{
Assert.assertEquals(writer.getDiskSpoolSize(), 0);
writer.write(originalEvent); // Goes to disk
writer.commit();
//Assert.assertTrue(writer.getDiskSpoolSize() > 0); -- too tiny, less than 1K
writer.flush(); // Picked up from disk, handed off to handler above
Assert.assertEquals(writer.getDiskSpoolSize(), 0);
while (!testsRun.get()) {
log.info("Tests still running, sleeping...");
Thread.sleep(100);
}
}
void createSmilePayload() throws IOException
{
// Use same configuration as SmileEnvelopeEvent
final SmileFactory f = new SmileFactory();
f.configure(SmileGenerator.Feature.CHECK_SHARED_NAMES, true);
f.configure(SmileGenerator.Feature.CHECK_SHARED_STRING_VALUES, true);
f.configure(SmileParser.Feature.REQUIRE_HEADER, false);
final ByteArrayOutputStream stream = new ByteArrayOutputStream();
final JsonGenerator g = f.createJsonGenerator(stream);
// Add multiple events in the bucket
addObject(g, "pierre");
addObject(g, "tatu");
addObject(g, "on");
addObject(g, "a");
addObject(g, "tree");
g.close(); // important: will force flushing of output, close underlying output stream
final Collection<SmileBucketEvent> buckets = JsonStreamToSmileBucketEvent.extractEvent(EVENT_NAME, new ByteArrayInputStream(stream.toByteArray()));
// This is one BucketEvent with 5 Smile events (the collection return one element because the output paths are the same)
originalEvent = (SmileBucketEvent) buckets.toArray()[0];
}
private void addObject(final JsonGenerator g, final String randomness) throws IOException
{
g.writeStartObject();
g.writeStringField(SmileEnvelopeEvent.SMILE_EVENT_GRANULARITY_TOKEN_NAME, EVENT_GRANULARITY.toString());
g.writeObjectFieldStart("name");
g.writeStringField("first", randomness);
g.writeStringField("last", "Sixpack");
g.writeEndObject(); // for field 'name'
g.writeStringField("gender", "MALE");
g.writeNumberField(SmileEnvelopeEvent.SMILE_EVENT_DATETIME_TOKEN_NAME, EVENT_DATE_TIME.getMillis());
g.writeBooleanField("verified", false);
g.writeEndObject();
}
}
|
src/test/java/com/ning/metrics/collector/binder/providers/TestDiskSpoolEventWriterProvider.java
|
/*
* Copyright 2010-2011 Ning, Inc.
*
* Ning licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.ning.metrics.collector.binder.providers;
import com.ning.metrics.collector.binder.config.CollectorConfig;
import com.ning.metrics.collector.util.NamedThreadFactory;
import com.ning.metrics.serialization.event.Event;
import com.ning.metrics.serialization.event.Granularity;
import com.ning.metrics.serialization.event.SmileBucketEvent;
import com.ning.metrics.serialization.event.SmileEnvelopeEvent;
import com.ning.metrics.serialization.smile.JsonStreamToSmileBucketEvent;
import com.ning.metrics.serialization.writer.DiskSpoolEventWriter;
import com.ning.metrics.serialization.writer.MockEventWriter;
import org.apache.log4j.Logger;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.smile.SmileFactory;
import org.codehaus.jackson.smile.SmileGenerator;
import org.codehaus.jackson.smile.SmileParser;
import org.joda.time.DateTime;
import org.skife.config.ConfigurationObjectFactory;
import org.testng.Assert;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.atomic.AtomicBoolean;
public class TestDiskSpoolEventWriterProvider
{
private static final Logger log = Logger.getLogger(TestDiskSpoolEventWriterProvider.class);
private Event originalEvent;
private DiskSpoolEventWriter writer;
private static final Granularity EVENT_GRANULARITY = Granularity.MONTHLY;
private static final DateTime EVENT_DATE_TIME = new DateTime(2010, 1, 1, 12, 0, 0, 42);
private static final String EVENT_NAME = "mySmile";
private final AtomicBoolean testsRun = new AtomicBoolean(false);
private final String tmpFile = System.getProperty("java.io.tmpdir") + "TestDiskSpoolEventWriterProvider";
abstract class TestConfig implements CollectorConfig
{
@Override
public long getFlushIntervalInSeconds()
{
return 1;
}
@Override
public String getSpoolDirectoryName()
{
return tmpFile;
}
}
@BeforeTest(alwaysRun = true)
public void setUp() throws IOException
{
createSmilePayload();
final CollectorConfig config = new ConfigurationObjectFactory(System.getProperties()).build(CollectorConfig.class);
writer = new DiskSpoolEventWriterProvider(
new MockEventWriter()
{
@Override
public void write(final Event event) throws IOException
{
Assert.assertEquals(event.getClass(), SmileBucketEvent.class);
Assert.assertEquals(((SmileBucketEvent) event).getNumberOfEvent(), 5);
Assert.assertEquals(event.getName(), originalEvent.getName());
Assert.assertEquals(event.getGranularity(), originalEvent.getGranularity());
Assert.assertEquals(event.getOutputDir("bleh"), originalEvent.getOutputDir("bleh"));
final DateTime eventDateTime = SmileEnvelopeEvent.getEventDateTimeFromJson(((SmileBucketEvent) event).getBucket().get(0));
Assert.assertEquals(eventDateTime, EVENT_DATE_TIME);
Assert.assertEquals(event.getSerializedEvent(), originalEvent.getSerializedEvent());
testsRun.set(true);
}
},
new ScheduledThreadPoolExecutor(1, new NamedThreadFactory("spool to HDFS promoter")),
config
).get();
}
@AfterTest(alwaysRun = true)
public void tearDown() throws IOException
{
new File(tmpFile).delete();
}
@Test(groups = "slow")
public void testGet() throws Exception
{
writer.write(originalEvent); // Goes to disk
writer.flush(); // Picked up from disk, handed off to handler above
while (!testsRun.get()) {
log.info("Tests still running, sleeping...");
Thread.sleep(100);
}
}
void createSmilePayload() throws IOException
{
// Use same configuration as SmileEnvelopeEvent
final SmileFactory f = new SmileFactory();
f.configure(SmileGenerator.Feature.CHECK_SHARED_NAMES, true);
f.configure(SmileGenerator.Feature.CHECK_SHARED_STRING_VALUES, true);
f.configure(SmileParser.Feature.REQUIRE_HEADER, false);
final ByteArrayOutputStream stream = new ByteArrayOutputStream();
final JsonGenerator g = f.createJsonGenerator(stream);
// Add multiple events in the bucket
addObject(g, "pierre");
addObject(g, "tatu");
addObject(g, "on");
addObject(g, "a");
addObject(g, "tree");
g.close(); // important: will force flushing of output, close underlying output stream
final Collection<SmileBucketEvent> buckets = JsonStreamToSmileBucketEvent.extractEvent(EVENT_NAME, new ByteArrayInputStream(stream.toByteArray()));
// This is one BucketEvent with 5 Smile events (the collection return one element because the output paths are the same)
originalEvent = (SmileBucketEvent) buckets.toArray()[0];
}
private void addObject(final JsonGenerator g, final String randomness) throws IOException
{
g.writeStartObject();
g.writeStringField(SmileEnvelopeEvent.SMILE_EVENT_GRANULARITY_TOKEN_NAME, EVENT_GRANULARITY.toString());
g.writeObjectFieldStart("name");
g.writeStringField("first", randomness);
g.writeStringField("last", "Sixpack");
g.writeEndObject(); // for field 'name'
g.writeStringField("gender", "MALE");
g.writeNumberField(SmileEnvelopeEvent.SMILE_EVENT_DATETIME_TOKEN_NAME, EVENT_DATE_TIME.getMillis());
g.writeBooleanField("verified", false);
g.writeEndObject();
}
}
|
tesT: make TestDiskSpoolEventWriterProvider really work
Signed-off-by: Pierre-Alexandre Meyer <[email protected]>
|
src/test/java/com/ning/metrics/collector/binder/providers/TestDiskSpoolEventWriterProvider.java
|
tesT: make TestDiskSpoolEventWriterProvider really work
|
<ide><path>rc/test/java/com/ning/metrics/collector/binder/providers/TestDiskSpoolEventWriterProvider.java
<ide> public class TestDiskSpoolEventWriterProvider
<ide> {
<ide> private static final Logger log = Logger.getLogger(TestDiskSpoolEventWriterProvider.class);
<add> private static final String tmpFile = System.getProperty("java.io.tmpdir") + "TestDiskSpoolEventWriterProvider";
<ide>
<ide> private Event originalEvent;
<ide> private DiskSpoolEventWriter writer;
<ide> private static final DateTime EVENT_DATE_TIME = new DateTime(2010, 1, 1, 12, 0, 0, 42);
<ide> private static final String EVENT_NAME = "mySmile";
<ide> private final AtomicBoolean testsRun = new AtomicBoolean(false);
<del> private final String tmpFile = System.getProperty("java.io.tmpdir") + "TestDiskSpoolEventWriterProvider";
<ide>
<del> abstract class TestConfig implements CollectorConfig
<add> abstract static class TestConfig implements CollectorConfig
<ide> {
<ide> @Override
<ide> public long getFlushIntervalInSeconds()
<ide> {
<ide> createSmilePayload();
<ide>
<del> final CollectorConfig config = new ConfigurationObjectFactory(System.getProperties()).build(CollectorConfig.class);
<add> final CollectorConfig config = new ConfigurationObjectFactory(System.getProperties()).build(TestConfig.class);
<ide>
<ide> writer = new DiskSpoolEventWriterProvider(
<ide> new MockEventWriter()
<ide> @Override
<ide> public void write(final Event event) throws IOException
<ide> {
<del> Assert.assertEquals(event.getClass(), SmileBucketEvent.class);
<del> Assert.assertEquals(((SmileBucketEvent) event).getNumberOfEvent(), 5);
<add> try {
<add> Assert.assertEquals(event.getClass(), SmileBucketEvent.class);
<add> Assert.assertEquals(((SmileBucketEvent) event).getNumberOfEvent(), 5);
<ide>
<del> Assert.assertEquals(event.getName(), originalEvent.getName());
<del> Assert.assertEquals(event.getGranularity(), originalEvent.getGranularity());
<del> Assert.assertEquals(event.getOutputDir("bleh"), originalEvent.getOutputDir("bleh"));
<add> Assert.assertEquals(event.getName(), originalEvent.getName());
<add> Assert.assertEquals(event.getGranularity(), originalEvent.getGranularity());
<add> Assert.assertEquals(event.getOutputDir("bleh"), originalEvent.getOutputDir("bleh"));
<ide>
<del> final DateTime eventDateTime = SmileEnvelopeEvent.getEventDateTimeFromJson(((SmileBucketEvent) event).getBucket().get(0));
<del> Assert.assertEquals(eventDateTime, EVENT_DATE_TIME);
<add> final DateTime eventDateTime = SmileEnvelopeEvent.getEventDateTimeFromJson(((SmileBucketEvent) event).getBucket().get(0));
<add> Assert.assertEquals(eventDateTime, EVENT_DATE_TIME);
<ide>
<del> Assert.assertEquals(event.getSerializedEvent(), originalEvent.getSerializedEvent());
<del>
<del> testsRun.set(true);
<add> Assert.assertEquals(event.getSerializedEvent(), originalEvent.getSerializedEvent());
<add> }
<add> finally {
<add> testsRun.set(true);
<add> }
<ide> }
<ide> },
<ide> new ScheduledThreadPoolExecutor(1, new NamedThreadFactory("spool to HDFS promoter")),
<ide> @Test(groups = "slow")
<ide> public void testGet() throws Exception
<ide> {
<add> Assert.assertEquals(writer.getDiskSpoolSize(), 0);
<add>
<ide> writer.write(originalEvent); // Goes to disk
<add> writer.commit();
<add> //Assert.assertTrue(writer.getDiskSpoolSize() > 0); -- too tiny, less than 1K
<add>
<ide> writer.flush(); // Picked up from disk, handed off to handler above
<add> Assert.assertEquals(writer.getDiskSpoolSize(), 0);
<add>
<ide> while (!testsRun.get()) {
<ide> log.info("Tests still running, sleeping...");
<ide> Thread.sleep(100);
|
|
Java
|
apache-2.0
|
91c9fb2251600c21935458f8b01a4e3ffde5577e
| 0 |
atomix/atomix,kuujo/copycat,atomix/atomix,kuujo/copycat
|
/*
* Copyright 2015-present Open Networking Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.atomix.protocols.raft.roles;
import com.google.common.base.Throwables;
import com.google.common.collect.Sets;
import io.atomix.cluster.ClusterMembershipEvent;
import io.atomix.cluster.ClusterMembershipEventListener;
import io.atomix.primitive.session.SessionId;
import io.atomix.protocols.raft.RaftError;
import io.atomix.protocols.raft.RaftException;
import io.atomix.protocols.raft.RaftServer;
import io.atomix.protocols.raft.cluster.RaftMember;
import io.atomix.protocols.raft.cluster.impl.DefaultRaftMember;
import io.atomix.protocols.raft.cluster.impl.RaftMemberContext;
import io.atomix.protocols.raft.impl.MetadataResult;
import io.atomix.protocols.raft.impl.OperationResult;
import io.atomix.protocols.raft.impl.PendingCommand;
import io.atomix.protocols.raft.impl.RaftContext;
import io.atomix.protocols.raft.protocol.AppendRequest;
import io.atomix.protocols.raft.protocol.AppendResponse;
import io.atomix.protocols.raft.protocol.CloseSessionRequest;
import io.atomix.protocols.raft.protocol.CloseSessionResponse;
import io.atomix.protocols.raft.protocol.CommandRequest;
import io.atomix.protocols.raft.protocol.CommandResponse;
import io.atomix.protocols.raft.protocol.JoinRequest;
import io.atomix.protocols.raft.protocol.JoinResponse;
import io.atomix.protocols.raft.protocol.KeepAliveRequest;
import io.atomix.protocols.raft.protocol.KeepAliveResponse;
import io.atomix.protocols.raft.protocol.LeaveRequest;
import io.atomix.protocols.raft.protocol.LeaveResponse;
import io.atomix.protocols.raft.protocol.MetadataRequest;
import io.atomix.protocols.raft.protocol.MetadataResponse;
import io.atomix.protocols.raft.protocol.OpenSessionRequest;
import io.atomix.protocols.raft.protocol.OpenSessionResponse;
import io.atomix.protocols.raft.protocol.PollRequest;
import io.atomix.protocols.raft.protocol.PollResponse;
import io.atomix.protocols.raft.protocol.QueryRequest;
import io.atomix.protocols.raft.protocol.QueryResponse;
import io.atomix.protocols.raft.protocol.RaftResponse;
import io.atomix.protocols.raft.protocol.ReconfigureRequest;
import io.atomix.protocols.raft.protocol.ReconfigureResponse;
import io.atomix.protocols.raft.protocol.TransferRequest;
import io.atomix.protocols.raft.protocol.TransferResponse;
import io.atomix.protocols.raft.protocol.VoteRequest;
import io.atomix.protocols.raft.protocol.VoteResponse;
import io.atomix.protocols.raft.session.RaftSession;
import io.atomix.protocols.raft.storage.log.entry.CloseSessionEntry;
import io.atomix.protocols.raft.storage.log.entry.CommandEntry;
import io.atomix.protocols.raft.storage.log.entry.ConfigurationEntry;
import io.atomix.protocols.raft.storage.log.entry.InitializeEntry;
import io.atomix.protocols.raft.storage.log.entry.KeepAliveEntry;
import io.atomix.protocols.raft.storage.log.entry.MetadataEntry;
import io.atomix.protocols.raft.storage.log.entry.OpenSessionEntry;
import io.atomix.protocols.raft.storage.log.entry.QueryEntry;
import io.atomix.protocols.raft.storage.log.entry.RaftLogEntry;
import io.atomix.protocols.raft.storage.system.Configuration;
import io.atomix.storage.StorageException;
import io.atomix.storage.journal.Indexed;
import io.atomix.utils.concurrent.Futures;
import io.atomix.utils.concurrent.Scheduled;
import java.time.Duration;
import java.time.Instant;
import java.util.Collection;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.stream.Collectors;
/**
* Leader state.
*/
public final class LeaderRole extends ActiveRole {
private static final int MAX_PENDING_COMMANDS = 1000;
private static final int MAX_APPEND_ATTEMPTS = 5;
private final ClusterMembershipEventListener clusterListener = this::handleClusterEvent;
private final LeaderAppender appender;
private Scheduled appendTimer;
private final Set<SessionId> expiring = Sets.newHashSet();
private long configuring;
private boolean transferring;
public LeaderRole(RaftContext context) {
super(context);
this.appender = new LeaderAppender(this);
}
@Override
public RaftServer.Role role() {
return RaftServer.Role.LEADER;
}
@Override
public synchronized CompletableFuture<RaftRole> start() {
// Reset state for the leader.
takeLeadership();
// Append initial entries to the log, including an initial no-op entry and the server's configuration.
appendInitialEntries().join();
// Commit the initial leader entries.
commitInitialEntries();
// Register the cluster event listener.
raft.getMembershipService().addListener(clusterListener);
return super.start()
.thenRun(this::startAppendTimer)
.thenApply(v -> this);
}
/**
* Sets the current node as the cluster leader.
*/
private void takeLeadership() {
raft.setLeader(raft.getCluster().getMember().memberId());
raft.getCluster().getRemoteMemberStates().forEach(m -> m.resetState(raft.getLog()));
}
/**
* Appends initial entries to the log to take leadership.
*/
private CompletableFuture<Void> appendInitialEntries() {
final long term = raft.getTerm();
return appendAndCompact(new InitializeEntry(term, appender.getTime())).thenApply(index -> null);
}
/**
* Commits a no-op entry to the log, ensuring any entries from a previous term are committed.
*/
private CompletableFuture<Void> commitInitialEntries() {
// The Raft protocol dictates that leaders cannot commit entries from previous terms until
// at least one entry from their current term has been stored on a majority of servers. Thus,
// we force entries to be appended up to the leader's no-op entry. The LeaderAppender will ensure
// that the commitIndex is not increased until the no-op entry (appender.index()) is committed.
CompletableFuture<Void> future = new CompletableFuture<>();
appender.appendEntries(appender.getIndex()).whenComplete((resultIndex, error) -> {
raft.checkThread();
if (isRunning()) {
if (error == null) {
raft.getServiceManager().apply(resultIndex);
future.complete(null);
} else {
raft.setLeader(null);
raft.transition(RaftServer.Role.FOLLOWER);
}
}
});
return future;
}
/**
* Starts sending AppendEntries requests to all cluster members.
*/
private void startAppendTimer() {
// Set a timer that will be used to periodically synchronize with other nodes
// in the cluster. This timer acts as a heartbeat to ensure this node remains
// the leader.
log.trace("Starting append timer");
appendTimer = raft.getThreadContext().schedule(Duration.ZERO, raft.getHeartbeatInterval(), this::appendMembers);
}
/**
* Sends AppendEntries requests to members of the cluster that haven't heard from the leader in a while.
*/
private void appendMembers() {
raft.checkThread();
if (isRunning()) {
appender.appendEntries();
}
}
/**
* Handles a cluster event.
*/
private void handleClusterEvent(ClusterMembershipEvent event) {
raft.getThreadContext().execute(() -> {
if (event.type() == ClusterMembershipEvent.Type.MEMBER_REMOVED) {
log.debug("Node {} deactivated", event.subject().id());
raft.getSessions().getSessions().stream()
.filter(session -> session.memberId().equals(event.subject().id()))
.forEach(this::expireSession);
}
});
}
/**
* Expires the given session.
*/
private void expireSession(RaftSession session) {
if (expiring.add(session.sessionId())) {
log.debug("Expiring session due to heartbeat failure: {}", session);
appendAndCompact(new CloseSessionEntry(raft.getTerm(), System.currentTimeMillis(), session.sessionId().id(), true, false))
.whenCompleteAsync((entry, error) -> {
if (error != null) {
expiring.remove(session.sessionId());
return;
}
appender.appendEntries(entry.index()).whenComplete((commitIndex, commitError) -> {
raft.checkThread();
if (isRunning()) {
if (commitError == null) {
raft.getServiceManager().<Long>apply(entry.index())
.whenCompleteAsync((r, e) -> expiring.remove(session.sessionId()), raft.getThreadContext());
} else {
expiring.remove(session.sessionId());
}
}
});
}, raft.getThreadContext());
}
}
/**
* Returns a boolean value indicating whether a configuration is currently being committed.
*
* @return Indicates whether a configuration is currently being committed.
*/
private boolean configuring() {
return configuring > 0;
}
/**
* Returns a boolean value indicating whether the leader is still being initialized.
*
* @return Indicates whether the leader is still being initialized.
*/
private boolean initializing() {
// If the leader index is 0 or is greater than the commitIndex, do not allow configuration changes.
// Configuration changes should not be allowed until the leader has committed a no-op entry.
// See https://groups.google.com/forum/#!topic/raft-dev/t4xj6dJTP6E
return appender.getIndex() == 0 || raft.getCommitIndex() < appender.getIndex();
}
/**
* Commits the given configuration.
*/
protected CompletableFuture<Long> configure(Collection<RaftMember> members) {
raft.checkThread();
final long term = raft.getTerm();
return appendAndCompact(new ConfigurationEntry(term, System.currentTimeMillis(), members))
.thenComposeAsync(entry -> {
// Store the index of the configuration entry in order to prevent other configurations from
// being logged and committed concurrently. This is an important safety property of Raft.
configuring = entry.index();
raft.getCluster().configure(new Configuration(entry.index(), entry.entry().term(), entry.entry().timestamp(), entry.entry().members()));
return appender.appendEntries(entry.index()).whenComplete((commitIndex, commitError) -> {
raft.checkThread();
if (isRunning() && commitError == null) {
raft.getServiceManager().<OperationResult>apply(entry.index());
}
configuring = 0;
});
}, raft.getThreadContext());
}
@Override
public CompletableFuture<JoinResponse> onJoin(final JoinRequest request) {
raft.checkThread();
logRequest(request);
// If another configuration change is already under way, reject the configuration.
// If the leader index is 0 or is greater than the commitIndex, reject the join requests.
// Configuration changes should not be allowed until the leader has committed a no-op entry.
// See https://groups.google.com/forum/#!topic/raft-dev/t4xj6dJTP6E
if (configuring() || initializing()) {
return CompletableFuture.completedFuture(logResponse(JoinResponse.builder()
.withStatus(RaftResponse.Status.ERROR)
.build()));
}
// If the member is already a known member of the cluster, complete the join successfully.
if (raft.getCluster().getMember(request.member().memberId()) != null) {
return CompletableFuture.completedFuture(logResponse(JoinResponse.builder()
.withStatus(RaftResponse.Status.OK)
.withIndex(raft.getCluster().getConfiguration().index())
.withTerm(raft.getCluster().getConfiguration().term())
.withTime(raft.getCluster().getConfiguration().time())
.withMembers(raft.getCluster().getMembers())
.build()));
}
RaftMember member = request.member();
// Add the joining member to the members list. If the joining member's type is ACTIVE, join the member in the
// PROMOTABLE state to allow it to get caught up without impacting the quorum size.
Collection<RaftMember> members = raft.getCluster().getMembers();
members.add(new DefaultRaftMember(member.memberId(), member.getType(), Instant.now()));
CompletableFuture<JoinResponse> future = new CompletableFuture<>();
configure(members).whenComplete((index, error) -> {
if (error == null) {
future.complete(logResponse(JoinResponse.builder()
.withStatus(RaftResponse.Status.OK)
.withIndex(index)
.withTerm(raft.getCluster().getConfiguration().term())
.withTime(raft.getCluster().getConfiguration().time())
.withMembers(members)
.build()));
} else {
future.complete(logResponse(JoinResponse.builder()
.withStatus(RaftResponse.Status.ERROR)
.withError(RaftError.Type.PROTOCOL_ERROR)
.build()));
}
});
return future;
}
@Override
public CompletableFuture<ReconfigureResponse> onReconfigure(final ReconfigureRequest request) {
raft.checkThread();
logRequest(request);
// If another configuration change is already under way, reject the configuration.
// If the leader index is 0 or is greater than the commitIndex, reject the promote requests.
// Configuration changes should not be allowed until the leader has committed a no-op entry.
// See https://groups.google.com/forum/#!topic/raft-dev/t4xj6dJTP6E
if (configuring() || initializing()) {
return CompletableFuture.completedFuture(logResponse(ReconfigureResponse.builder()
.withStatus(RaftResponse.Status.ERROR)
.build()));
}
// If the member is not a known member of the cluster, fail the promotion.
DefaultRaftMember existingMember = raft.getCluster().getMember(request.member().memberId());
if (existingMember == null) {
return CompletableFuture.completedFuture(logResponse(ReconfigureResponse.builder()
.withStatus(RaftResponse.Status.ERROR)
.withError(RaftError.Type.UNKNOWN_SESSION)
.build()));
}
// If the configuration request index is less than the last known configuration index for
// the leader, fail the request to ensure servers can't reconfigure an old configuration.
if (request.index() > 0 && request.index() < raft.getCluster().getConfiguration().index()
|| request.term() != raft.getCluster().getConfiguration().term()) {
return CompletableFuture.completedFuture(logResponse(ReconfigureResponse.builder()
.withStatus(RaftResponse.Status.ERROR)
.withError(RaftError.Type.CONFIGURATION_ERROR)
.build()));
}
// If the member type has not changed, complete the configuration change successfully.
if (existingMember.getType() == request.member().getType()) {
Configuration configuration = raft.getCluster().getConfiguration();
return CompletableFuture.completedFuture(logResponse(ReconfigureResponse.builder()
.withStatus(RaftResponse.Status.OK)
.withIndex(configuration.index())
.withTerm(raft.getCluster().getConfiguration().term())
.withTime(raft.getCluster().getConfiguration().time())
.withMembers(configuration.members())
.build()));
}
// Update the member type.
existingMember.update(request.member().getType(), Instant.now());
Collection<RaftMember> members = raft.getCluster().getMembers();
CompletableFuture<ReconfigureResponse> future = new CompletableFuture<>();
configure(members).whenComplete((index, error) -> {
if (error == null) {
future.complete(logResponse(ReconfigureResponse.builder()
.withStatus(RaftResponse.Status.OK)
.withIndex(index)
.withTerm(raft.getCluster().getConfiguration().term())
.withTime(raft.getCluster().getConfiguration().time())
.withMembers(members)
.build()));
} else {
future.complete(logResponse(ReconfigureResponse.builder()
.withStatus(RaftResponse.Status.ERROR)
.withError(RaftError.Type.PROTOCOL_ERROR)
.build()));
}
});
return future;
}
@Override
public CompletableFuture<LeaveResponse> onLeave(final LeaveRequest request) {
raft.checkThread();
logRequest(request);
// If another configuration change is already under way, reject the configuration.
// If the leader index is 0 or is greater than the commitIndex, reject the join requests.
// Configuration changes should not be allowed until the leader has committed a no-op entry.
// See https://groups.google.com/forum/#!topic/raft-dev/t4xj6dJTP6E
if (configuring() || initializing()) {
return CompletableFuture.completedFuture(logResponse(LeaveResponse.builder()
.withStatus(RaftResponse.Status.ERROR)
.build()));
}
// If the leaving member is not a known member of the cluster, complete the leave successfully.
if (raft.getCluster().getMember(request.member().memberId()) == null) {
return CompletableFuture.completedFuture(logResponse(LeaveResponse.builder()
.withStatus(RaftResponse.Status.OK)
.withMembers(raft.getCluster().getMembers())
.build()));
}
RaftMember member = request.member();
Collection<RaftMember> members = raft.getCluster().getMembers();
members.remove(member);
CompletableFuture<LeaveResponse> future = new CompletableFuture<>();
configure(members).whenComplete((index, error) -> {
if (error == null) {
future.complete(logResponse(LeaveResponse.builder()
.withStatus(RaftResponse.Status.OK)
.withIndex(index)
.withTerm(raft.getCluster().getConfiguration().term())
.withTime(raft.getCluster().getConfiguration().time())
.withMembers(members)
.build()));
} else {
future.complete(logResponse(LeaveResponse.builder()
.withStatus(RaftResponse.Status.ERROR)
.withError(RaftError.Type.PROTOCOL_ERROR)
.build()));
}
});
return future;
}
@Override
public CompletableFuture<TransferResponse> onTransfer(final TransferRequest request) {
logRequest(request);
RaftMemberContext member = raft.getCluster().getMemberState(request.member());
if (member == null) {
return CompletableFuture.completedFuture(logResponse(TransferResponse.builder()
.withStatus(RaftResponse.Status.ERROR)
.withError(RaftError.Type.ILLEGAL_MEMBER_STATE)
.build()));
}
transferring = true;
CompletableFuture<TransferResponse> future = new CompletableFuture<>();
appender.appendEntries(raft.getLogWriter().getLastIndex()).whenComplete((result, error) -> {
if (isRunning()) {
if (error == null) {
log.debug("Transferring leadership to {}", request.member());
raft.transition(RaftServer.Role.FOLLOWER);
future.complete(logResponse(TransferResponse.builder()
.withStatus(RaftResponse.Status.OK)
.build()));
} else if (error instanceof CompletionException && error.getCause() instanceof RaftException) {
future.complete(logResponse(TransferResponse.builder()
.withStatus(RaftResponse.Status.ERROR)
.withError(((RaftException) error.getCause()).getType(), error.getMessage())
.build()));
} else if (error instanceof RaftException) {
future.complete(logResponse(TransferResponse.builder()
.withStatus(RaftResponse.Status.ERROR)
.withError(((RaftException) error).getType(), error.getMessage())
.build()));
} else {
future.complete(logResponse(TransferResponse.builder()
.withStatus(RaftResponse.Status.ERROR)
.withError(RaftError.Type.PROTOCOL_ERROR, error.getMessage())
.build()));
}
} else {
future.complete(logResponse(TransferResponse.builder()
.withStatus(RaftResponse.Status.ERROR)
.withError(RaftError.Type.ILLEGAL_MEMBER_STATE)
.build()));
}
});
return future;
}
@Override
public CompletableFuture<PollResponse> onPoll(final PollRequest request) {
logRequest(request);
// If a member sends a PollRequest to the leader, that indicates that it likely healed from
// a network partition and may have had its status set to UNAVAILABLE by the leader. In order
// to ensure heartbeats are immediately stored to the member, update its status if necessary.
RaftMemberContext member = raft.getCluster().getMemberState(request.candidate());
if (member != null) {
member.resetFailureCount();
}
return CompletableFuture.completedFuture(logResponse(PollResponse.builder()
.withStatus(RaftResponse.Status.OK)
.withTerm(raft.getTerm())
.withAccepted(false)
.build()));
}
@Override
public CompletableFuture<VoteResponse> onVote(final VoteRequest request) {
if (updateTermAndLeader(request.term(), null)) {
log.debug("Received greater term");
raft.transition(RaftServer.Role.FOLLOWER);
return super.onVote(request);
} else {
logRequest(request);
return CompletableFuture.completedFuture(logResponse(VoteResponse.builder()
.withStatus(RaftResponse.Status.OK)
.withTerm(raft.getTerm())
.withVoted(false)
.build()));
}
}
@Override
public CompletableFuture<AppendResponse> onAppend(final AppendRequest request) {
raft.checkThread();
if (updateTermAndLeader(request.term(), request.leader())) {
CompletableFuture<AppendResponse> future = super.onAppend(request);
raft.transition(RaftServer.Role.FOLLOWER);
return future;
} else if (request.term() < raft.getTerm()) {
logRequest(request);
return CompletableFuture.completedFuture(logResponse(AppendResponse.builder()
.withStatus(RaftResponse.Status.OK)
.withTerm(raft.getTerm())
.withSucceeded(false)
.withLastLogIndex(raft.getLogWriter().getLastIndex())
.build()));
} else {
raft.setLeader(request.leader());
raft.transition(RaftServer.Role.FOLLOWER);
return super.onAppend(request);
}
}
@Override
public CompletableFuture<MetadataResponse> onMetadata(MetadataRequest request) {
raft.checkThread();
logRequest(request);
if (transferring) {
return CompletableFuture.completedFuture(logResponse(MetadataResponse.builder()
.withStatus(RaftResponse.Status.ERROR)
.withError(RaftError.Type.ILLEGAL_MEMBER_STATE)
.build()));
}
CompletableFuture<MetadataResponse> future = new CompletableFuture<>();
Indexed<MetadataEntry> entry = new Indexed<>(
raft.getLastApplied(),
new MetadataEntry(raft.getTerm(), System.currentTimeMillis(), request.session()), 0);
raft.getServiceManager().<MetadataResult>apply(entry).whenComplete((result, error) -> {
if (error == null) {
future.complete(logResponse(MetadataResponse.builder()
.withStatus(RaftResponse.Status.OK)
.withSessions(result.sessions())
.build()));
} else {
future.complete(logResponse(MetadataResponse.builder()
.withStatus(RaftResponse.Status.ERROR)
.withError(RaftError.Type.PROTOCOL_ERROR)
.build()));
}
});
return future;
}
@Override
public CompletableFuture<CommandResponse> onCommand(final CommandRequest request) {
raft.checkThread();
logRequest(request);
if (transferring) {
return CompletableFuture.completedFuture(logResponse(CommandResponse.builder()
.withStatus(RaftResponse.Status.ERROR)
.withError(RaftError.Type.ILLEGAL_MEMBER_STATE)
.build()));
}
// Get the client's server session. If the session doesn't exist, return an unknown session error.
RaftSession session = raft.getSessions().getSession(request.session());
if (session == null) {
return CompletableFuture.completedFuture(logResponse(CommandResponse.builder()
.withStatus(RaftResponse.Status.ERROR)
.withError(RaftError.Type.UNKNOWN_SESSION)
.build()));
}
final long sequenceNumber = request.sequenceNumber();
// If a command with the given sequence number is already pending, return the existing future to ensure
// duplicate requests aren't committed as duplicate entries in the log.
PendingCommand existingCommand = session.getCommand(sequenceNumber);
if (existingCommand != null) {
if (sequenceNumber <= session.nextRequestSequence()) {
drainCommands(sequenceNumber, session);
}
log.trace("Returning pending result for command sequence {}", sequenceNumber);
return existingCommand.future();
}
final CompletableFuture<CommandResponse> future = new CompletableFuture<>();
// If the request sequence number is greater than the next sequence number, that indicates a command is missing.
// Register the command request and return a future to be completed once commands are properly sequenced.
// If the session's current sequence number is too far beyond the last known sequence number, reject the command
// to force it to be resent by the client.
if (sequenceNumber > session.nextRequestSequence()) {
if (session.getCommands().size() < MAX_PENDING_COMMANDS) {
log.trace("Registered sequence command {} > {}", sequenceNumber, session.nextRequestSequence());
session.registerCommand(request.sequenceNumber(), new PendingCommand(request, future));
return future;
} else {
return CompletableFuture.completedFuture(logResponse(CommandResponse.builder()
.withStatus(RaftResponse.Status.ERROR)
.withError(RaftError.Type.COMMAND_FAILURE)
.withLastSequence(session.getRequestSequence())
.build()));
}
}
// If the command has already been applied to the state machine then return a cached result if possible, otherwise
// return null.
if (sequenceNumber <= session.getCommandSequence()) {
OperationResult result = session.getResult(sequenceNumber);
if (result != null) {
completeOperation(result, CommandResponse.builder(), null, future);
} else {
future.complete(CommandResponse.builder()
.withStatus(RaftResponse.Status.ERROR)
.withError(RaftError.Type.PROTOCOL_ERROR)
.build());
}
}
// Otherwise, commit the command and update the request sequence number, then drain pending commands.
else {
commitCommand(request, future);
session.setRequestSequence(sequenceNumber);
drainCommands(sequenceNumber, session);
}
return future.thenApply(this::logResponse);
}
/**
* Sequentially drains pending commands from the session's command request queue.
*
* @param session the session for which to drain commands
*/
private void drainCommands(long sequenceNumber, RaftSession session) {
// First we need to drain any commands that exist in the queue *prior* to the next sequence number. This is
// possible if commands from the prior term are committed after a leader change.
long nextSequence = session.nextRequestSequence();
for (long i = sequenceNumber; i < nextSequence; i++) {
PendingCommand nextCommand = session.removeCommand(i);
if (nextCommand != null) {
commitCommand(nextCommand.request(), nextCommand.future());
}
}
// Finally, drain any commands that are sequenced in the session.
PendingCommand nextCommand = session.removeCommand(nextSequence);
while (nextCommand != null) {
commitCommand(nextCommand.request(), nextCommand.future());
session.setRequestSequence(nextSequence);
nextSequence = session.nextRequestSequence();
nextCommand = session.removeCommand(nextSequence);
}
}
/**
* Commits a command.
*
* @param request the command request
* @param future the command response future
*/
private void commitCommand(CommandRequest request, CompletableFuture<CommandResponse> future) {
final long term = raft.getTerm();
final long timestamp = System.currentTimeMillis();
CommandEntry command = new CommandEntry(term, timestamp, request.session(), request.sequenceNumber(), request.operation());
appendAndCompact(command)
.whenCompleteAsync((entry, error) -> {
if (error != null) {
Throwable cause = Throwables.getRootCause(error);
if (Throwables.getRootCause(error) instanceof StorageException.TooLarge) {
log.warn("Failed to append command {}", command, cause);
future.complete(CommandResponse.builder()
.withStatus(RaftResponse.Status.ERROR)
.withError(RaftError.Type.PROTOCOL_ERROR)
.build());
} else {
future.complete(CommandResponse.builder()
.withStatus(RaftResponse.Status.ERROR)
.withError(RaftError.Type.COMMAND_FAILURE)
.build());
}
return;
}
// Replicate the command to followers.
appender.appendEntries(entry.index()).whenComplete((commitIndex, commitError) -> {
raft.checkThread();
if (isRunning()) {
// If the command was successfully committed, apply it to the state machine.
if (commitError == null) {
raft.getServiceManager().<OperationResult>apply(entry.index()).whenComplete((r, e) -> {
completeOperation(r, CommandResponse.builder(), e, future);
});
} else {
future.complete(CommandResponse.builder()
.withStatus(RaftResponse.Status.ERROR)
.withError(RaftError.Type.COMMAND_FAILURE)
.build());
}
} else {
future.complete(CommandResponse.builder()
.withStatus(RaftResponse.Status.ERROR)
.withError(RaftError.Type.COMMAND_FAILURE)
.build());
}
});
}, raft.getThreadContext());
}
@Override
public CompletableFuture<QueryResponse> onQuery(final QueryRequest request) {
raft.checkThread();
logRequest(request);
// If this server has not yet applied entries up to the client's session ID, forward the
// query to the leader. This ensures that a follower does not tell the client its session
// doesn't exist if the follower hasn't had a chance to see the session's registration entry.
if (raft.getLastApplied() < request.session()) {
return CompletableFuture.completedFuture(logResponse(QueryResponse.builder()
.withStatus(RaftResponse.Status.ERROR)
.withError(RaftError.Type.UNKNOWN_SESSION, "Session has not yet been created. You're seeing into the future!")
.build()));
}
// Look up the client's session.
RaftSession session = raft.getSessions().getSession(request.session());
if (session == null) {
log.warn("Unknown session {}", request.session());
return CompletableFuture.completedFuture(logResponse(QueryResponse.builder()
.withStatus(RaftResponse.Status.ERROR)
.withError(RaftError.Type.UNKNOWN_SESSION)
.build()));
}
final Indexed<QueryEntry> entry = new Indexed<>(
request.index(),
new QueryEntry(
raft.getTerm(),
System.currentTimeMillis(),
request.session(),
request.sequenceNumber(),
request.operation()), 0);
final CompletableFuture<QueryResponse> future;
switch (session.readConsistency()) {
case SEQUENTIAL:
future = queryLocal(entry);
break;
case LINEARIZABLE_LEASE:
future = queryBoundedLinearizable(entry);
break;
case LINEARIZABLE:
future = queryLinearizable(entry);
break;
default:
future = Futures.exceptionalFuture(new IllegalStateException("Unknown consistency level: " + session.readConsistency()));
break;
}
return future.thenApply(this::logResponse);
}
/**
* Executes a bounded linearizable query.
* <p>
* Bounded linearizable queries succeed as long as this server remains the leader. This is possible
* since the leader will step down in the event it fails to contact a majority of the cluster.
*/
private CompletableFuture<QueryResponse> queryBoundedLinearizable(Indexed<QueryEntry> entry) {
return applyQuery(entry);
}
/**
* Executes a linearizable query.
* <p>
* Linearizable queries are first sequenced with commands and then applied to the state machine. Once
* applied, we verify the node's leadership prior to responding successfully to the query.
*/
private CompletableFuture<QueryResponse> queryLinearizable(Indexed<QueryEntry> entry) {
return applyQuery(entry)
.thenComposeAsync(response -> appender.appendEntries()
.thenApply(index -> response)
.exceptionally(error -> QueryResponse.builder()
.withStatus(RaftResponse.Status.ERROR)
.withError(RaftError.Type.QUERY_FAILURE, error.getMessage())
.build()), raft.getThreadContext());
}
@Override
public CompletableFuture<OpenSessionResponse> onOpenSession(OpenSessionRequest request) {
final long term = raft.getTerm();
final long timestamp = System.currentTimeMillis();
final long minTimeout = request.minTimeout();
// If the client submitted a session timeout, use the client's timeout, otherwise use the configured
// default server session timeout.
final long maxTimeout;
if (request.maxTimeout() != 0) {
maxTimeout = request.maxTimeout();
} else {
maxTimeout = raft.getSessionTimeout().toMillis();
}
raft.checkThread();
logRequest(request);
CompletableFuture<OpenSessionResponse> future = new CompletableFuture<>();
appendAndCompact(new OpenSessionEntry(
term,
timestamp,
request.node(),
request.serviceName(),
request.serviceType(),
request.serviceConfig(),
request.readConsistency(),
minTimeout,
maxTimeout))
.whenCompleteAsync((entry, error) -> {
if (error != null) {
future.complete(logResponse(OpenSessionResponse.builder()
.withStatus(RaftResponse.Status.ERROR)
.withError(RaftError.Type.PROTOCOL_ERROR)
.build()));
return;
}
appender.appendEntries(entry.index()).whenComplete((commitIndex, commitError) -> {
raft.checkThread();
if (isRunning()) {
if (commitError == null) {
raft.getServiceManager().<Long>apply(entry.index()).whenComplete((sessionId, sessionError) -> {
if (sessionError == null) {
future.complete(logResponse(OpenSessionResponse.builder()
.withStatus(RaftResponse.Status.OK)
.withSession(sessionId)
.withTimeout(maxTimeout)
.build()));
} else if (sessionError instanceof CompletionException && sessionError.getCause() instanceof RaftException) {
future.complete(logResponse(OpenSessionResponse.builder()
.withStatus(RaftResponse.Status.ERROR)
.withError(((RaftException) sessionError.getCause()).getType(), sessionError.getMessage())
.build()));
} else if (sessionError instanceof RaftException) {
future.complete(logResponse(OpenSessionResponse.builder()
.withStatus(RaftResponse.Status.ERROR)
.withError(((RaftException) sessionError).getType(), sessionError.getMessage())
.build()));
} else {
future.complete(logResponse(OpenSessionResponse.builder()
.withStatus(RaftResponse.Status.ERROR)
.withError(RaftError.Type.PROTOCOL_ERROR, sessionError.getMessage())
.build()));
}
});
} else {
future.complete(logResponse(OpenSessionResponse.builder()
.withStatus(RaftResponse.Status.ERROR)
.withError(RaftError.Type.PROTOCOL_ERROR)
.build()));
}
} else {
future.complete(logResponse(OpenSessionResponse.builder()
.withStatus(RaftResponse.Status.ERROR)
.withError(RaftError.Type.ILLEGAL_MEMBER_STATE)
.build()));
}
});
}, raft.getThreadContext());
return future;
}
@Override
public CompletableFuture<KeepAliveResponse> onKeepAlive(KeepAliveRequest request) {
final long term = raft.getTerm();
final long timestamp = System.currentTimeMillis();
raft.checkThread();
logRequest(request);
CompletableFuture<KeepAliveResponse> future = new CompletableFuture<>();
appendAndCompact(new KeepAliveEntry(term, timestamp, request.sessionIds(), request.commandSequenceNumbers(), request.eventIndexes()))
.whenCompleteAsync((entry, error) -> {
if (error != null) {
future.complete(logResponse(KeepAliveResponse.builder()
.withStatus(RaftResponse.Status.ERROR)
.withLeader(raft.getCluster().getMember().memberId())
.withError(RaftError.Type.PROTOCOL_ERROR)
.build()));
return;
}
appender.appendEntries(entry.index()).whenComplete((commitIndex, commitError) -> {
raft.checkThread();
if (isRunning()) {
if (commitError == null) {
raft.getServiceManager().<long[]>apply(entry.index()).whenCompleteAsync((sessionResult, sessionError) -> {
if (sessionError == null) {
future.complete(logResponse(KeepAliveResponse.builder()
.withStatus(RaftResponse.Status.OK)
.withLeader(raft.getCluster().getMember().memberId())
.withMembers(raft.getCluster().getMembers().stream()
.map(RaftMember::memberId)
.filter(m -> m != null)
.collect(Collectors.toList()))
.withSessionIds(sessionResult)
.build()));
} else if (sessionError instanceof CompletionException && sessionError.getCause() instanceof RaftException) {
future.complete(logResponse(KeepAliveResponse.builder()
.withStatus(RaftResponse.Status.ERROR)
.withLeader(raft.getCluster().getMember().memberId())
.withError(((RaftException) sessionError.getCause()).getType(), sessionError.getMessage())
.build()));
} else if (sessionError instanceof RaftException) {
future.complete(logResponse(KeepAliveResponse.builder()
.withStatus(RaftResponse.Status.ERROR)
.withLeader(raft.getCluster().getMember().memberId())
.withError(((RaftException) sessionError).getType(), sessionError.getMessage())
.build()));
} else {
future.complete(logResponse(KeepAliveResponse.builder()
.withStatus(RaftResponse.Status.ERROR)
.withLeader(raft.getCluster().getMember().memberId())
.withError(RaftError.Type.PROTOCOL_ERROR, sessionError.getMessage())
.build()));
}
}, raft.getThreadContext());
} else {
future.complete(logResponse(KeepAliveResponse.builder()
.withStatus(RaftResponse.Status.ERROR)
.withLeader(raft.getCluster().getMember().memberId())
.withError(RaftError.Type.PROTOCOL_ERROR)
.build()));
}
} else {
RaftMember leader = raft.getLeader();
future.complete(logResponse(KeepAliveResponse.builder()
.withStatus(RaftResponse.Status.ERROR)
.withLeader(leader != null ? leader.memberId() : null)
.withError(RaftError.Type.ILLEGAL_MEMBER_STATE)
.build()));
}
});
}, raft.getThreadContext());
return future;
}
@Override
public CompletableFuture<CloseSessionResponse> onCloseSession(CloseSessionRequest request) {
final long term = raft.getTerm();
final long timestamp = System.currentTimeMillis();
raft.checkThread();
logRequest(request);
CompletableFuture<CloseSessionResponse> future = new CompletableFuture<>();
appendAndCompact(new CloseSessionEntry(term, timestamp, request.session(), false, request.delete()))
.whenCompleteAsync((entry, error) -> {
if (error != null) {
future.complete(logResponse(CloseSessionResponse.builder()
.withStatus(RaftResponse.Status.ERROR)
.withError(RaftError.Type.PROTOCOL_ERROR)
.build()));
return;
}
appender.appendEntries(entry.index()).whenComplete((commitIndex, commitError) -> {
raft.checkThread();
if (isRunning()) {
if (commitError == null) {
raft.getServiceManager().<Long>apply(entry.index()).whenComplete((closeResult, closeError) -> {
if (closeError == null) {
future.complete(logResponse(CloseSessionResponse.builder()
.withStatus(RaftResponse.Status.OK)
.build()));
} else if (closeError instanceof CompletionException && closeError.getCause() instanceof RaftException) {
future.complete(logResponse(CloseSessionResponse.builder()
.withStatus(RaftResponse.Status.ERROR)
.withError(((RaftException) closeError.getCause()).getType(), closeError.getMessage())
.build()));
} else if (closeError instanceof RaftException) {
future.complete(logResponse(CloseSessionResponse.builder()
.withStatus(RaftResponse.Status.ERROR)
.withError(((RaftException) closeError).getType(), closeError.getMessage())
.build()));
} else {
future.complete(logResponse(CloseSessionResponse.builder()
.withStatus(RaftResponse.Status.ERROR)
.withError(RaftError.Type.PROTOCOL_ERROR, closeError.getMessage())
.build()));
}
});
} else {
future.complete(logResponse(CloseSessionResponse.builder()
.withStatus(RaftResponse.Status.ERROR)
.withError(RaftError.Type.PROTOCOL_ERROR)
.build()));
}
} else {
future.complete(logResponse(CloseSessionResponse.builder()
.withStatus(RaftResponse.Status.ERROR)
.withError(RaftError.Type.ILLEGAL_MEMBER_STATE)
.build()));
}
});
}, raft.getThreadContext());
return future;
}
/**
* Appends an entry to the Raft log and compacts logs if necessary.
*
* @param entry the entry to append
* @param <E> the entry type
* @return a completable future to be completed once the entry has been appended
*/
private <E extends RaftLogEntry> CompletableFuture<Indexed<E>> appendAndCompact(E entry) {
return appendAndCompact(entry, 0);
}
/**
* Appends an entry to the Raft log and compacts logs if necessary.
*
* @param entry the entry to append
* @param attempt the append attempt count
* @param <E> the entry type
* @return a completable future to be completed once the entry has been appended
*/
protected <E extends RaftLogEntry> CompletableFuture<Indexed<E>> appendAndCompact(E entry, int attempt) {
if (attempt == MAX_APPEND_ATTEMPTS) {
return Futures.exceptionalFuture(new StorageException.OutOfDiskSpace("Not enough space to append entry"));
} else {
try {
return CompletableFuture.completedFuture(raft.getLogWriter().append(entry))
.thenApply(indexed -> {
log.trace("Appended {}", indexed);
return indexed;
});
} catch (StorageException.TooLarge e) {
return Futures.exceptionalFuture(e);
} catch (StorageException.OutOfDiskSpace e) {
log.warn("Caught OutOfDiskSpace error! Force compacting logs...");
return raft.getServiceManager().compact().thenCompose(v -> appendAndCompact(entry, attempt + 1));
}
}
}
/**
* Cancels the append timer.
*/
private void cancelAppendTimer() {
if (appendTimer != null) {
log.trace("Cancelling append timer");
appendTimer.cancel();
}
}
/**
* Ensures the local server is not the leader.
*/
private void stepDown() {
if (raft.getLeader() != null && raft.getLeader().equals(raft.getCluster().getMember())) {
raft.setLeader(null);
}
}
/**
* Fails pending commands.
*/
private void failPendingCommands() {
for (RaftSession session : raft.getSessions().getSessions()) {
for (PendingCommand command : session.clearCommands()) {
command.future().complete(logResponse(CommandResponse.builder()
.withStatus(RaftResponse.Status.ERROR)
.withError(RaftError.Type.COMMAND_FAILURE, "Request sequence number " + command.request().sequenceNumber() + " out of sequence")
.withLastSequence(session.getRequestSequence())
.build()));
}
}
}
@Override
public synchronized CompletableFuture<Void> stop() {
raft.getMembershipService().removeListener(clusterListener);
return super.stop()
.thenRun(appender::close)
.thenRun(this::cancelAppendTimer)
.thenRun(this::stepDown)
.thenRun(this::failPendingCommands);
}
}
|
protocols/raft/src/main/java/io/atomix/protocols/raft/roles/LeaderRole.java
|
/*
* Copyright 2015-present Open Networking Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.atomix.protocols.raft.roles;
import com.google.common.base.Throwables;
import com.google.common.collect.Sets;
import io.atomix.cluster.ClusterMembershipEvent;
import io.atomix.cluster.ClusterMembershipEventListener;
import io.atomix.primitive.session.SessionId;
import io.atomix.protocols.raft.RaftError;
import io.atomix.protocols.raft.RaftException;
import io.atomix.protocols.raft.RaftServer;
import io.atomix.protocols.raft.cluster.RaftMember;
import io.atomix.protocols.raft.cluster.impl.DefaultRaftMember;
import io.atomix.protocols.raft.cluster.impl.RaftMemberContext;
import io.atomix.protocols.raft.impl.MetadataResult;
import io.atomix.protocols.raft.impl.OperationResult;
import io.atomix.protocols.raft.impl.PendingCommand;
import io.atomix.protocols.raft.impl.RaftContext;
import io.atomix.protocols.raft.protocol.AppendRequest;
import io.atomix.protocols.raft.protocol.AppendResponse;
import io.atomix.protocols.raft.protocol.CloseSessionRequest;
import io.atomix.protocols.raft.protocol.CloseSessionResponse;
import io.atomix.protocols.raft.protocol.CommandRequest;
import io.atomix.protocols.raft.protocol.CommandResponse;
import io.atomix.protocols.raft.protocol.JoinRequest;
import io.atomix.protocols.raft.protocol.JoinResponse;
import io.atomix.protocols.raft.protocol.KeepAliveRequest;
import io.atomix.protocols.raft.protocol.KeepAliveResponse;
import io.atomix.protocols.raft.protocol.LeaveRequest;
import io.atomix.protocols.raft.protocol.LeaveResponse;
import io.atomix.protocols.raft.protocol.MetadataRequest;
import io.atomix.protocols.raft.protocol.MetadataResponse;
import io.atomix.protocols.raft.protocol.OpenSessionRequest;
import io.atomix.protocols.raft.protocol.OpenSessionResponse;
import io.atomix.protocols.raft.protocol.PollRequest;
import io.atomix.protocols.raft.protocol.PollResponse;
import io.atomix.protocols.raft.protocol.QueryRequest;
import io.atomix.protocols.raft.protocol.QueryResponse;
import io.atomix.protocols.raft.protocol.RaftResponse;
import io.atomix.protocols.raft.protocol.ReconfigureRequest;
import io.atomix.protocols.raft.protocol.ReconfigureResponse;
import io.atomix.protocols.raft.protocol.TransferRequest;
import io.atomix.protocols.raft.protocol.TransferResponse;
import io.atomix.protocols.raft.protocol.VoteRequest;
import io.atomix.protocols.raft.protocol.VoteResponse;
import io.atomix.protocols.raft.session.RaftSession;
import io.atomix.protocols.raft.storage.log.entry.CloseSessionEntry;
import io.atomix.protocols.raft.storage.log.entry.CommandEntry;
import io.atomix.protocols.raft.storage.log.entry.ConfigurationEntry;
import io.atomix.protocols.raft.storage.log.entry.InitializeEntry;
import io.atomix.protocols.raft.storage.log.entry.KeepAliveEntry;
import io.atomix.protocols.raft.storage.log.entry.MetadataEntry;
import io.atomix.protocols.raft.storage.log.entry.OpenSessionEntry;
import io.atomix.protocols.raft.storage.log.entry.QueryEntry;
import io.atomix.protocols.raft.storage.log.entry.RaftLogEntry;
import io.atomix.protocols.raft.storage.system.Configuration;
import io.atomix.storage.StorageException;
import io.atomix.storage.journal.Indexed;
import io.atomix.utils.concurrent.Futures;
import io.atomix.utils.concurrent.Scheduled;
import java.time.Duration;
import java.time.Instant;
import java.util.Collection;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.stream.Collectors;
/**
* Leader state.
*/
public final class LeaderRole extends ActiveRole {
private static final int MAX_PENDING_COMMANDS = 1000;
private static final int MAX_APPEND_ATTEMPTS = 5;
private final ClusterMembershipEventListener clusterListener = this::handleClusterEvent;
private final LeaderAppender appender;
private Scheduled appendTimer;
private final Set<SessionId> expiring = Sets.newHashSet();
private long configuring;
private boolean transferring;
public LeaderRole(RaftContext context) {
super(context);
this.appender = new LeaderAppender(this);
}
@Override
public RaftServer.Role role() {
return RaftServer.Role.LEADER;
}
@Override
public synchronized CompletableFuture<RaftRole> start() {
// Reset state for the leader.
takeLeadership();
// Append initial entries to the log, including an initial no-op entry and the server's configuration.
appendInitialEntries().join();
// Commit the initial leader entries.
commitInitialEntries();
// Register the cluster event listener.
raft.getMembershipService().addListener(clusterListener);
return super.start()
.thenRun(this::startAppendTimer)
.thenApply(v -> this);
}
/**
* Sets the current node as the cluster leader.
*/
private void takeLeadership() {
raft.setLeader(raft.getCluster().getMember().memberId());
raft.getCluster().getRemoteMemberStates().forEach(m -> m.resetState(raft.getLog()));
}
/**
* Appends initial entries to the log to take leadership.
*/
private CompletableFuture<Void> appendInitialEntries() {
final long term = raft.getTerm();
return appendAndCompact(new InitializeEntry(term, appender.getTime())).thenApply(index -> null);
}
/**
* Commits a no-op entry to the log, ensuring any entries from a previous term are committed.
*/
private CompletableFuture<Void> commitInitialEntries() {
// The Raft protocol dictates that leaders cannot commit entries from previous terms until
// at least one entry from their current term has been stored on a majority of servers. Thus,
// we force entries to be appended up to the leader's no-op entry. The LeaderAppender will ensure
// that the commitIndex is not increased until the no-op entry (appender.index()) is committed.
CompletableFuture<Void> future = new CompletableFuture<>();
appender.appendEntries(appender.getIndex()).whenComplete((resultIndex, error) -> {
raft.checkThread();
if (isRunning()) {
if (error == null) {
raft.getServiceManager().apply(resultIndex);
future.complete(null);
} else {
raft.setLeader(null);
raft.transition(RaftServer.Role.FOLLOWER);
}
}
});
return future;
}
/**
* Starts sending AppendEntries requests to all cluster members.
*/
private void startAppendTimer() {
// Set a timer that will be used to periodically synchronize with other nodes
// in the cluster. This timer acts as a heartbeat to ensure this node remains
// the leader.
log.trace("Starting append timer");
appendTimer = raft.getThreadContext().schedule(Duration.ZERO, raft.getHeartbeatInterval(), this::appendMembers);
}
/**
* Sends AppendEntries requests to members of the cluster that haven't heard from the leader in a while.
*/
private void appendMembers() {
raft.checkThread();
if (isRunning()) {
appender.appendEntries();
}
}
/**
* Handles a cluster event.
*/
private void handleClusterEvent(ClusterMembershipEvent event) {
raft.getThreadContext().execute(() -> {
if (event.type() == ClusterMembershipEvent.Type.MEMBER_REMOVED) {
log.debug("Node {} deactivated", event.subject().id());
raft.getSessions().getSessions().stream()
.filter(session -> session.memberId().equals(event.subject().id()))
.forEach(this::expireSession);
}
});
}
/**
* Expires the given session.
*/
private void expireSession(RaftSession session) {
if (expiring.add(session.sessionId())) {
log.debug("Expiring session due to heartbeat failure: {}", session);
appendAndCompact(new CloseSessionEntry(raft.getTerm(), System.currentTimeMillis(), session.sessionId().id(), true, false))
.whenCompleteAsync((entry, error) -> {
if (error != null) {
expiring.remove(session.sessionId());
return;
}
appender.appendEntries(entry.index()).whenComplete((commitIndex, commitError) -> {
raft.checkThread();
if (isRunning()) {
if (commitError == null) {
raft.getServiceManager().<Long>apply(entry.index())
.whenCompleteAsync((r, e) -> expiring.remove(session.sessionId()), raft.getThreadContext());
} else {
expiring.remove(session.sessionId());
}
}
});
}, raft.getThreadContext());
}
}
/**
* Returns a boolean value indicating whether a configuration is currently being committed.
*
* @return Indicates whether a configuration is currently being committed.
*/
private boolean configuring() {
return configuring > 0;
}
/**
* Returns a boolean value indicating whether the leader is still being initialized.
*
* @return Indicates whether the leader is still being initialized.
*/
private boolean initializing() {
// If the leader index is 0 or is greater than the commitIndex, do not allow configuration changes.
// Configuration changes should not be allowed until the leader has committed a no-op entry.
// See https://groups.google.com/forum/#!topic/raft-dev/t4xj6dJTP6E
return appender.getIndex() == 0 || raft.getCommitIndex() < appender.getIndex();
}
/**
* Commits the given configuration.
*/
protected CompletableFuture<Long> configure(Collection<RaftMember> members) {
raft.checkThread();
final long term = raft.getTerm();
return appendAndCompact(new ConfigurationEntry(term, System.currentTimeMillis(), members))
.thenComposeAsync(entry -> {
// Store the index of the configuration entry in order to prevent other configurations from
// being logged and committed concurrently. This is an important safety property of Raft.
configuring = entry.index();
raft.getCluster().configure(new Configuration(entry.index(), entry.entry().term(), entry.entry().timestamp(), entry.entry().members()));
return appender.appendEntries(entry.index()).whenComplete((commitIndex, commitError) -> {
raft.checkThread();
if (isRunning() && commitError == null) {
raft.getServiceManager().<OperationResult>apply(entry.index());
}
configuring = 0;
});
}, raft.getThreadContext());
}
@Override
public CompletableFuture<JoinResponse> onJoin(final JoinRequest request) {
raft.checkThread();
logRequest(request);
// If another configuration change is already under way, reject the configuration.
// If the leader index is 0 or is greater than the commitIndex, reject the join requests.
// Configuration changes should not be allowed until the leader has committed a no-op entry.
// See https://groups.google.com/forum/#!topic/raft-dev/t4xj6dJTP6E
if (configuring() || initializing()) {
return CompletableFuture.completedFuture(logResponse(JoinResponse.builder()
.withStatus(RaftResponse.Status.ERROR)
.build()));
}
// If the member is already a known member of the cluster, complete the join successfully.
if (raft.getCluster().getMember(request.member().memberId()) != null) {
return CompletableFuture.completedFuture(logResponse(JoinResponse.builder()
.withStatus(RaftResponse.Status.OK)
.withIndex(raft.getCluster().getConfiguration().index())
.withTerm(raft.getCluster().getConfiguration().term())
.withTime(raft.getCluster().getConfiguration().time())
.withMembers(raft.getCluster().getMembers())
.build()));
}
RaftMember member = request.member();
// Add the joining member to the members list. If the joining member's type is ACTIVE, join the member in the
// PROMOTABLE state to allow it to get caught up without impacting the quorum size.
Collection<RaftMember> members = raft.getCluster().getMembers();
members.add(new DefaultRaftMember(member.memberId(), member.getType(), Instant.now()));
CompletableFuture<JoinResponse> future = new CompletableFuture<>();
configure(members).whenComplete((index, error) -> {
if (error == null) {
future.complete(logResponse(JoinResponse.builder()
.withStatus(RaftResponse.Status.OK)
.withIndex(index)
.withTerm(raft.getCluster().getConfiguration().term())
.withTime(raft.getCluster().getConfiguration().time())
.withMembers(members)
.build()));
} else {
future.complete(logResponse(JoinResponse.builder()
.withStatus(RaftResponse.Status.ERROR)
.withError(RaftError.Type.PROTOCOL_ERROR)
.build()));
}
});
return future;
}
@Override
public CompletableFuture<ReconfigureResponse> onReconfigure(final ReconfigureRequest request) {
raft.checkThread();
logRequest(request);
// If another configuration change is already under way, reject the configuration.
// If the leader index is 0 or is greater than the commitIndex, reject the promote requests.
// Configuration changes should not be allowed until the leader has committed a no-op entry.
// See https://groups.google.com/forum/#!topic/raft-dev/t4xj6dJTP6E
if (configuring() || initializing()) {
return CompletableFuture.completedFuture(logResponse(ReconfigureResponse.builder()
.withStatus(RaftResponse.Status.ERROR)
.build()));
}
// If the member is not a known member of the cluster, fail the promotion.
DefaultRaftMember existingMember = raft.getCluster().getMember(request.member().memberId());
if (existingMember == null) {
return CompletableFuture.completedFuture(logResponse(ReconfigureResponse.builder()
.withStatus(RaftResponse.Status.ERROR)
.withError(RaftError.Type.UNKNOWN_SESSION)
.build()));
}
// If the configuration request index is less than the last known configuration index for
// the leader, fail the request to ensure servers can't reconfigure an old configuration.
if (request.index() > 0 && request.index() < raft.getCluster().getConfiguration().index()
|| request.term() != raft.getCluster().getConfiguration().term()) {
return CompletableFuture.completedFuture(logResponse(ReconfigureResponse.builder()
.withStatus(RaftResponse.Status.ERROR)
.withError(RaftError.Type.CONFIGURATION_ERROR)
.build()));
}
// If the member type has not changed, complete the configuration change successfully.
if (existingMember.getType() == request.member().getType()) {
Configuration configuration = raft.getCluster().getConfiguration();
return CompletableFuture.completedFuture(logResponse(ReconfigureResponse.builder()
.withStatus(RaftResponse.Status.OK)
.withIndex(configuration.index())
.withTerm(raft.getCluster().getConfiguration().term())
.withTime(raft.getCluster().getConfiguration().time())
.withMembers(configuration.members())
.build()));
}
// Update the member type.
existingMember.update(request.member().getType(), Instant.now());
Collection<RaftMember> members = raft.getCluster().getMembers();
CompletableFuture<ReconfigureResponse> future = new CompletableFuture<>();
configure(members).whenComplete((index, error) -> {
if (error == null) {
future.complete(logResponse(ReconfigureResponse.builder()
.withStatus(RaftResponse.Status.OK)
.withIndex(index)
.withTerm(raft.getCluster().getConfiguration().term())
.withTime(raft.getCluster().getConfiguration().time())
.withMembers(members)
.build()));
} else {
future.complete(logResponse(ReconfigureResponse.builder()
.withStatus(RaftResponse.Status.ERROR)
.withError(RaftError.Type.PROTOCOL_ERROR)
.build()));
}
});
return future;
}
@Override
public CompletableFuture<LeaveResponse> onLeave(final LeaveRequest request) {
raft.checkThread();
logRequest(request);
// If another configuration change is already under way, reject the configuration.
// If the leader index is 0 or is greater than the commitIndex, reject the join requests.
// Configuration changes should not be allowed until the leader has committed a no-op entry.
// See https://groups.google.com/forum/#!topic/raft-dev/t4xj6dJTP6E
if (configuring() || initializing()) {
return CompletableFuture.completedFuture(logResponse(LeaveResponse.builder()
.withStatus(RaftResponse.Status.ERROR)
.build()));
}
// If the leaving member is not a known member of the cluster, complete the leave successfully.
if (raft.getCluster().getMember(request.member().memberId()) == null) {
return CompletableFuture.completedFuture(logResponse(LeaveResponse.builder()
.withStatus(RaftResponse.Status.OK)
.withMembers(raft.getCluster().getMembers())
.build()));
}
RaftMember member = request.member();
Collection<RaftMember> members = raft.getCluster().getMembers();
members.remove(member);
CompletableFuture<LeaveResponse> future = new CompletableFuture<>();
configure(members).whenComplete((index, error) -> {
if (error == null) {
future.complete(logResponse(LeaveResponse.builder()
.withStatus(RaftResponse.Status.OK)
.withIndex(index)
.withTerm(raft.getCluster().getConfiguration().term())
.withTime(raft.getCluster().getConfiguration().time())
.withMembers(members)
.build()));
} else {
future.complete(logResponse(LeaveResponse.builder()
.withStatus(RaftResponse.Status.ERROR)
.withError(RaftError.Type.PROTOCOL_ERROR)
.build()));
}
});
return future;
}
@Override
public CompletableFuture<TransferResponse> onTransfer(final TransferRequest request) {
logRequest(request);
RaftMemberContext member = raft.getCluster().getMemberState(request.member());
if (member == null) {
return CompletableFuture.completedFuture(logResponse(TransferResponse.builder()
.withStatus(RaftResponse.Status.ERROR)
.withError(RaftError.Type.ILLEGAL_MEMBER_STATE)
.build()));
}
transferring = true;
CompletableFuture<TransferResponse> future = new CompletableFuture<>();
appender.appendEntries(raft.getLogWriter().getLastIndex()).whenComplete((result, error) -> {
if (isRunning()) {
if (error == null) {
log.debug("Transferring leadership to {}", request.member());
raft.transition(RaftServer.Role.FOLLOWER);
future.complete(logResponse(TransferResponse.builder()
.withStatus(RaftResponse.Status.OK)
.build()));
} else if (error instanceof CompletionException && error.getCause() instanceof RaftException) {
future.complete(logResponse(TransferResponse.builder()
.withStatus(RaftResponse.Status.ERROR)
.withError(((RaftException) error.getCause()).getType(), error.getMessage())
.build()));
} else if (error instanceof RaftException) {
future.complete(logResponse(TransferResponse.builder()
.withStatus(RaftResponse.Status.ERROR)
.withError(((RaftException) error).getType(), error.getMessage())
.build()));
} else {
future.complete(logResponse(TransferResponse.builder()
.withStatus(RaftResponse.Status.ERROR)
.withError(RaftError.Type.PROTOCOL_ERROR, error.getMessage())
.build()));
}
} else {
future.complete(logResponse(TransferResponse.builder()
.withStatus(RaftResponse.Status.ERROR)
.withError(RaftError.Type.ILLEGAL_MEMBER_STATE)
.build()));
}
});
return future;
}
@Override
public CompletableFuture<PollResponse> onPoll(final PollRequest request) {
logRequest(request);
// If a member sends a PollRequest to the leader, that indicates that it likely healed from
// a network partition and may have had its status set to UNAVAILABLE by the leader. In order
// to ensure heartbeats are immediately stored to the member, update its status if necessary.
RaftMemberContext member = raft.getCluster().getMemberState(request.candidate());
if (member != null) {
member.resetFailureCount();
}
return CompletableFuture.completedFuture(logResponse(PollResponse.builder()
.withStatus(RaftResponse.Status.OK)
.withTerm(raft.getTerm())
.withAccepted(false)
.build()));
}
@Override
public CompletableFuture<VoteResponse> onVote(final VoteRequest request) {
if (updateTermAndLeader(request.term(), null)) {
log.debug("Received greater term");
raft.transition(RaftServer.Role.FOLLOWER);
return super.onVote(request);
} else {
logRequest(request);
return CompletableFuture.completedFuture(logResponse(VoteResponse.builder()
.withStatus(RaftResponse.Status.OK)
.withTerm(raft.getTerm())
.withVoted(false)
.build()));
}
}
@Override
public CompletableFuture<AppendResponse> onAppend(final AppendRequest request) {
raft.checkThread();
if (updateTermAndLeader(request.term(), request.leader())) {
CompletableFuture<AppendResponse> future = super.onAppend(request);
raft.transition(RaftServer.Role.FOLLOWER);
return future;
} else if (request.term() < raft.getTerm()) {
logRequest(request);
return CompletableFuture.completedFuture(logResponse(AppendResponse.builder()
.withStatus(RaftResponse.Status.OK)
.withTerm(raft.getTerm())
.withSucceeded(false)
.withLastLogIndex(raft.getLogWriter().getLastIndex())
.build()));
} else {
raft.setLeader(request.leader());
raft.transition(RaftServer.Role.FOLLOWER);
return super.onAppend(request);
}
}
@Override
public CompletableFuture<MetadataResponse> onMetadata(MetadataRequest request) {
raft.checkThread();
logRequest(request);
if (transferring) {
return CompletableFuture.completedFuture(logResponse(MetadataResponse.builder()
.withStatus(RaftResponse.Status.ERROR)
.withError(RaftError.Type.ILLEGAL_MEMBER_STATE)
.build()));
}
CompletableFuture<MetadataResponse> future = new CompletableFuture<>();
Indexed<MetadataEntry> entry = new Indexed<>(
raft.getLastApplied(),
new MetadataEntry(raft.getTerm(), System.currentTimeMillis(), request.session()), 0);
raft.getServiceManager().<MetadataResult>apply(entry).whenComplete((result, error) -> {
if (error == null) {
future.complete(logResponse(MetadataResponse.builder()
.withStatus(RaftResponse.Status.OK)
.withSessions(result.sessions())
.build()));
} else {
future.complete(logResponse(MetadataResponse.builder()
.withStatus(RaftResponse.Status.ERROR)
.withError(RaftError.Type.PROTOCOL_ERROR)
.build()));
}
});
return future;
}
@Override
public CompletableFuture<CommandResponse> onCommand(final CommandRequest request) {
raft.checkThread();
logRequest(request);
if (transferring) {
return CompletableFuture.completedFuture(logResponse(CommandResponse.builder()
.withStatus(RaftResponse.Status.ERROR)
.withError(RaftError.Type.ILLEGAL_MEMBER_STATE)
.build()));
}
// Get the client's server session. If the session doesn't exist, return an unknown session error.
RaftSession session = raft.getSessions().getSession(request.session());
if (session == null) {
return CompletableFuture.completedFuture(logResponse(CommandResponse.builder()
.withStatus(RaftResponse.Status.ERROR)
.withError(RaftError.Type.UNKNOWN_SESSION)
.build()));
}
final long sequenceNumber = request.sequenceNumber();
// If a command with the given sequence number is already pending, return the existing future to ensure
// duplicate requests aren't committed as duplicate entries in the log.
PendingCommand existingCommand = session.getCommand(sequenceNumber);
if (existingCommand != null) {
if (sequenceNumber <= session.nextRequestSequence()) {
drainCommands(sequenceNumber, session);
}
log.trace("Returning pending result for command sequence {}", sequenceNumber);
return existingCommand.future();
}
final CompletableFuture<CommandResponse> future = new CompletableFuture<>();
// If the request sequence number is greater than the next sequence number, that indicates a command is missing.
// Register the command request and return a future to be completed once commands are properly sequenced.
// If the session's current sequence number is too far beyond the last known sequence number, reject the command
// to force it to be resent by the client.
if (sequenceNumber > session.nextRequestSequence()) {
if (session.getCommands().size() < MAX_PENDING_COMMANDS) {
log.trace("Registered sequence command {} > {}", sequenceNumber, session.nextRequestSequence());
session.registerCommand(request.sequenceNumber(), new PendingCommand(request, future));
return future;
} else {
return CompletableFuture.completedFuture(logResponse(CommandResponse.builder()
.withStatus(RaftResponse.Status.ERROR)
.withError(RaftError.Type.COMMAND_FAILURE)
.withLastSequence(session.getRequestSequence())
.build()));
}
}
// If the command has already been applied to the state machine then return a cached result if possible, otherwise
// return null.
if (sequenceNumber <= session.getCommandSequence()) {
OperationResult result = session.getResult(sequenceNumber);
if (result != null) {
completeOperation(result, CommandResponse.builder(), null, future);
} else {
future.complete(CommandResponse.builder()
.withStatus(RaftResponse.Status.ERROR)
.withError(RaftError.Type.PROTOCOL_ERROR)
.build());
}
}
// Otherwise, commit the command and update the request sequence number.
else {
commitCommand(request, future);
session.setRequestSequence(sequenceNumber);
}
return future.thenApply(this::logResponse);
}
/**
* Sequentially drains pending commands from the session's command request queue.
*
* @param session the session for which to drain commands
*/
private void drainCommands(long sequenceNumber, RaftSession session) {
// First we need to drain any commands that exist in the queue *prior* to the next sequence number. This is
// possible if commands from the prior term are committed after a leader change.
long nextSequence = session.nextRequestSequence();
for (long i = sequenceNumber; i < nextSequence; i++) {
PendingCommand nextCommand = session.removeCommand(i);
if (nextCommand != null) {
commitCommand(nextCommand.request(), nextCommand.future());
}
}
// Finally, drain any commands that are sequenced in the session.
PendingCommand nextCommand = session.removeCommand(nextSequence);
while (nextCommand != null) {
commitCommand(nextCommand.request(), nextCommand.future());
session.setRequestSequence(nextSequence);
nextSequence = session.nextRequestSequence();
nextCommand = session.removeCommand(nextSequence);
}
}
/**
* Commits a command.
*
* @param request the command request
* @param future the command response future
*/
private void commitCommand(CommandRequest request, CompletableFuture<CommandResponse> future) {
final long term = raft.getTerm();
final long timestamp = System.currentTimeMillis();
CommandEntry command = new CommandEntry(term, timestamp, request.session(), request.sequenceNumber(), request.operation());
appendAndCompact(command)
.whenCompleteAsync((entry, error) -> {
if (error != null) {
Throwable cause = Throwables.getRootCause(error);
if (Throwables.getRootCause(error) instanceof StorageException.TooLarge) {
log.warn("Failed to append command {}", command, cause);
future.complete(CommandResponse.builder()
.withStatus(RaftResponse.Status.ERROR)
.withError(RaftError.Type.PROTOCOL_ERROR)
.build());
} else {
future.complete(CommandResponse.builder()
.withStatus(RaftResponse.Status.ERROR)
.withError(RaftError.Type.COMMAND_FAILURE)
.build());
}
return;
}
// Replicate the command to followers.
appender.appendEntries(entry.index()).whenComplete((commitIndex, commitError) -> {
raft.checkThread();
if (isRunning()) {
// If the command was successfully committed, apply it to the state machine.
if (commitError == null) {
raft.getServiceManager().<OperationResult>apply(entry.index()).whenComplete((r, e) -> {
completeOperation(r, CommandResponse.builder(), e, future);
});
} else {
future.complete(CommandResponse.builder()
.withStatus(RaftResponse.Status.ERROR)
.withError(RaftError.Type.COMMAND_FAILURE)
.build());
}
} else {
future.complete(CommandResponse.builder()
.withStatus(RaftResponse.Status.ERROR)
.withError(RaftError.Type.COMMAND_FAILURE)
.build());
}
});
}, raft.getThreadContext());
}
@Override
public CompletableFuture<QueryResponse> onQuery(final QueryRequest request) {
raft.checkThread();
logRequest(request);
// If this server has not yet applied entries up to the client's session ID, forward the
// query to the leader. This ensures that a follower does not tell the client its session
// doesn't exist if the follower hasn't had a chance to see the session's registration entry.
if (raft.getLastApplied() < request.session()) {
return CompletableFuture.completedFuture(logResponse(QueryResponse.builder()
.withStatus(RaftResponse.Status.ERROR)
.withError(RaftError.Type.UNKNOWN_SESSION, "Session has not yet been created. You're seeing into the future!")
.build()));
}
// Look up the client's session.
RaftSession session = raft.getSessions().getSession(request.session());
if (session == null) {
log.warn("Unknown session {}", request.session());
return CompletableFuture.completedFuture(logResponse(QueryResponse.builder()
.withStatus(RaftResponse.Status.ERROR)
.withError(RaftError.Type.UNKNOWN_SESSION)
.build()));
}
final Indexed<QueryEntry> entry = new Indexed<>(
request.index(),
new QueryEntry(
raft.getTerm(),
System.currentTimeMillis(),
request.session(),
request.sequenceNumber(),
request.operation()), 0);
final CompletableFuture<QueryResponse> future;
switch (session.readConsistency()) {
case SEQUENTIAL:
future = queryLocal(entry);
break;
case LINEARIZABLE_LEASE:
future = queryBoundedLinearizable(entry);
break;
case LINEARIZABLE:
future = queryLinearizable(entry);
break;
default:
future = Futures.exceptionalFuture(new IllegalStateException("Unknown consistency level: " + session.readConsistency()));
break;
}
return future.thenApply(this::logResponse);
}
/**
* Executes a bounded linearizable query.
* <p>
* Bounded linearizable queries succeed as long as this server remains the leader. This is possible
* since the leader will step down in the event it fails to contact a majority of the cluster.
*/
private CompletableFuture<QueryResponse> queryBoundedLinearizable(Indexed<QueryEntry> entry) {
return applyQuery(entry);
}
/**
* Executes a linearizable query.
* <p>
* Linearizable queries are first sequenced with commands and then applied to the state machine. Once
* applied, we verify the node's leadership prior to responding successfully to the query.
*/
private CompletableFuture<QueryResponse> queryLinearizable(Indexed<QueryEntry> entry) {
return applyQuery(entry)
.thenComposeAsync(response -> appender.appendEntries()
.thenApply(index -> response)
.exceptionally(error -> QueryResponse.builder()
.withStatus(RaftResponse.Status.ERROR)
.withError(RaftError.Type.QUERY_FAILURE, error.getMessage())
.build()), raft.getThreadContext());
}
@Override
public CompletableFuture<OpenSessionResponse> onOpenSession(OpenSessionRequest request) {
final long term = raft.getTerm();
final long timestamp = System.currentTimeMillis();
final long minTimeout = request.minTimeout();
// If the client submitted a session timeout, use the client's timeout, otherwise use the configured
// default server session timeout.
final long maxTimeout;
if (request.maxTimeout() != 0) {
maxTimeout = request.maxTimeout();
} else {
maxTimeout = raft.getSessionTimeout().toMillis();
}
raft.checkThread();
logRequest(request);
CompletableFuture<OpenSessionResponse> future = new CompletableFuture<>();
appendAndCompact(new OpenSessionEntry(
term,
timestamp,
request.node(),
request.serviceName(),
request.serviceType(),
request.serviceConfig(),
request.readConsistency(),
minTimeout,
maxTimeout))
.whenCompleteAsync((entry, error) -> {
if (error != null) {
future.complete(logResponse(OpenSessionResponse.builder()
.withStatus(RaftResponse.Status.ERROR)
.withError(RaftError.Type.PROTOCOL_ERROR)
.build()));
return;
}
appender.appendEntries(entry.index()).whenComplete((commitIndex, commitError) -> {
raft.checkThread();
if (isRunning()) {
if (commitError == null) {
raft.getServiceManager().<Long>apply(entry.index()).whenComplete((sessionId, sessionError) -> {
if (sessionError == null) {
future.complete(logResponse(OpenSessionResponse.builder()
.withStatus(RaftResponse.Status.OK)
.withSession(sessionId)
.withTimeout(maxTimeout)
.build()));
} else if (sessionError instanceof CompletionException && sessionError.getCause() instanceof RaftException) {
future.complete(logResponse(OpenSessionResponse.builder()
.withStatus(RaftResponse.Status.ERROR)
.withError(((RaftException) sessionError.getCause()).getType(), sessionError.getMessage())
.build()));
} else if (sessionError instanceof RaftException) {
future.complete(logResponse(OpenSessionResponse.builder()
.withStatus(RaftResponse.Status.ERROR)
.withError(((RaftException) sessionError).getType(), sessionError.getMessage())
.build()));
} else {
future.complete(logResponse(OpenSessionResponse.builder()
.withStatus(RaftResponse.Status.ERROR)
.withError(RaftError.Type.PROTOCOL_ERROR, sessionError.getMessage())
.build()));
}
});
} else {
future.complete(logResponse(OpenSessionResponse.builder()
.withStatus(RaftResponse.Status.ERROR)
.withError(RaftError.Type.PROTOCOL_ERROR)
.build()));
}
} else {
future.complete(logResponse(OpenSessionResponse.builder()
.withStatus(RaftResponse.Status.ERROR)
.withError(RaftError.Type.ILLEGAL_MEMBER_STATE)
.build()));
}
});
}, raft.getThreadContext());
return future;
}
@Override
public CompletableFuture<KeepAliveResponse> onKeepAlive(KeepAliveRequest request) {
final long term = raft.getTerm();
final long timestamp = System.currentTimeMillis();
raft.checkThread();
logRequest(request);
CompletableFuture<KeepAliveResponse> future = new CompletableFuture<>();
appendAndCompact(new KeepAliveEntry(term, timestamp, request.sessionIds(), request.commandSequenceNumbers(), request.eventIndexes()))
.whenCompleteAsync((entry, error) -> {
if (error != null) {
future.complete(logResponse(KeepAliveResponse.builder()
.withStatus(RaftResponse.Status.ERROR)
.withLeader(raft.getCluster().getMember().memberId())
.withError(RaftError.Type.PROTOCOL_ERROR)
.build()));
return;
}
appender.appendEntries(entry.index()).whenComplete((commitIndex, commitError) -> {
raft.checkThread();
if (isRunning()) {
if (commitError == null) {
raft.getServiceManager().<long[]>apply(entry.index()).whenCompleteAsync((sessionResult, sessionError) -> {
if (sessionError == null) {
future.complete(logResponse(KeepAliveResponse.builder()
.withStatus(RaftResponse.Status.OK)
.withLeader(raft.getCluster().getMember().memberId())
.withMembers(raft.getCluster().getMembers().stream()
.map(RaftMember::memberId)
.filter(m -> m != null)
.collect(Collectors.toList()))
.withSessionIds(sessionResult)
.build()));
} else if (sessionError instanceof CompletionException && sessionError.getCause() instanceof RaftException) {
future.complete(logResponse(KeepAliveResponse.builder()
.withStatus(RaftResponse.Status.ERROR)
.withLeader(raft.getCluster().getMember().memberId())
.withError(((RaftException) sessionError.getCause()).getType(), sessionError.getMessage())
.build()));
} else if (sessionError instanceof RaftException) {
future.complete(logResponse(KeepAliveResponse.builder()
.withStatus(RaftResponse.Status.ERROR)
.withLeader(raft.getCluster().getMember().memberId())
.withError(((RaftException) sessionError).getType(), sessionError.getMessage())
.build()));
} else {
future.complete(logResponse(KeepAliveResponse.builder()
.withStatus(RaftResponse.Status.ERROR)
.withLeader(raft.getCluster().getMember().memberId())
.withError(RaftError.Type.PROTOCOL_ERROR, sessionError.getMessage())
.build()));
}
}, raft.getThreadContext());
} else {
future.complete(logResponse(KeepAliveResponse.builder()
.withStatus(RaftResponse.Status.ERROR)
.withLeader(raft.getCluster().getMember().memberId())
.withError(RaftError.Type.PROTOCOL_ERROR)
.build()));
}
} else {
RaftMember leader = raft.getLeader();
future.complete(logResponse(KeepAliveResponse.builder()
.withStatus(RaftResponse.Status.ERROR)
.withLeader(leader != null ? leader.memberId() : null)
.withError(RaftError.Type.ILLEGAL_MEMBER_STATE)
.build()));
}
});
}, raft.getThreadContext());
return future;
}
@Override
public CompletableFuture<CloseSessionResponse> onCloseSession(CloseSessionRequest request) {
final long term = raft.getTerm();
final long timestamp = System.currentTimeMillis();
raft.checkThread();
logRequest(request);
CompletableFuture<CloseSessionResponse> future = new CompletableFuture<>();
appendAndCompact(new CloseSessionEntry(term, timestamp, request.session(), false, request.delete()))
.whenCompleteAsync((entry, error) -> {
if (error != null) {
future.complete(logResponse(CloseSessionResponse.builder()
.withStatus(RaftResponse.Status.ERROR)
.withError(RaftError.Type.PROTOCOL_ERROR)
.build()));
return;
}
appender.appendEntries(entry.index()).whenComplete((commitIndex, commitError) -> {
raft.checkThread();
if (isRunning()) {
if (commitError == null) {
raft.getServiceManager().<Long>apply(entry.index()).whenComplete((closeResult, closeError) -> {
if (closeError == null) {
future.complete(logResponse(CloseSessionResponse.builder()
.withStatus(RaftResponse.Status.OK)
.build()));
} else if (closeError instanceof CompletionException && closeError.getCause() instanceof RaftException) {
future.complete(logResponse(CloseSessionResponse.builder()
.withStatus(RaftResponse.Status.ERROR)
.withError(((RaftException) closeError.getCause()).getType(), closeError.getMessage())
.build()));
} else if (closeError instanceof RaftException) {
future.complete(logResponse(CloseSessionResponse.builder()
.withStatus(RaftResponse.Status.ERROR)
.withError(((RaftException) closeError).getType(), closeError.getMessage())
.build()));
} else {
future.complete(logResponse(CloseSessionResponse.builder()
.withStatus(RaftResponse.Status.ERROR)
.withError(RaftError.Type.PROTOCOL_ERROR, closeError.getMessage())
.build()));
}
});
} else {
future.complete(logResponse(CloseSessionResponse.builder()
.withStatus(RaftResponse.Status.ERROR)
.withError(RaftError.Type.PROTOCOL_ERROR)
.build()));
}
} else {
future.complete(logResponse(CloseSessionResponse.builder()
.withStatus(RaftResponse.Status.ERROR)
.withError(RaftError.Type.ILLEGAL_MEMBER_STATE)
.build()));
}
});
}, raft.getThreadContext());
return future;
}
/**
* Appends an entry to the Raft log and compacts logs if necessary.
*
* @param entry the entry to append
* @param <E> the entry type
* @return a completable future to be completed once the entry has been appended
*/
private <E extends RaftLogEntry> CompletableFuture<Indexed<E>> appendAndCompact(E entry) {
return appendAndCompact(entry, 0);
}
/**
* Appends an entry to the Raft log and compacts logs if necessary.
*
* @param entry the entry to append
* @param attempt the append attempt count
* @param <E> the entry type
* @return a completable future to be completed once the entry has been appended
*/
protected <E extends RaftLogEntry> CompletableFuture<Indexed<E>> appendAndCompact(E entry, int attempt) {
if (attempt == MAX_APPEND_ATTEMPTS) {
return Futures.exceptionalFuture(new StorageException.OutOfDiskSpace("Not enough space to append entry"));
} else {
try {
return CompletableFuture.completedFuture(raft.getLogWriter().append(entry))
.thenApply(indexed -> {
log.trace("Appended {}", indexed);
return indexed;
});
} catch (StorageException.TooLarge e) {
return Futures.exceptionalFuture(e);
} catch (StorageException.OutOfDiskSpace e) {
log.warn("Caught OutOfDiskSpace error! Force compacting logs...");
return raft.getServiceManager().compact().thenCompose(v -> appendAndCompact(entry, attempt + 1));
}
}
}
/**
* Cancels the append timer.
*/
private void cancelAppendTimer() {
if (appendTimer != null) {
log.trace("Cancelling append timer");
appendTimer.cancel();
}
}
/**
* Ensures the local server is not the leader.
*/
private void stepDown() {
if (raft.getLeader() != null && raft.getLeader().equals(raft.getCluster().getMember())) {
raft.setLeader(null);
}
}
/**
* Fails pending commands.
*/
private void failPendingCommands() {
for (RaftSession session : raft.getSessions().getSessions()) {
for (PendingCommand command : session.clearCommands()) {
command.future().complete(logResponse(CommandResponse.builder()
.withStatus(RaftResponse.Status.ERROR)
.withError(RaftError.Type.COMMAND_FAILURE, "Request sequence number " + command.request().sequenceNumber() + " out of sequence")
.withLastSequence(session.getRequestSequence())
.build()));
}
}
}
@Override
public synchronized CompletableFuture<Void> stop() {
raft.getMembershipService().removeListener(clusterListener);
return super.stop()
.thenRun(appender::close)
.thenRun(this::cancelAppendTimer)
.thenRun(this::stepDown)
.thenRun(this::failPendingCommands);
}
}
|
Ensure pending commands are immediately drained when in sequence command is committed.
|
protocols/raft/src/main/java/io/atomix/protocols/raft/roles/LeaderRole.java
|
Ensure pending commands are immediately drained when in sequence command is committed.
|
<ide><path>rotocols/raft/src/main/java/io/atomix/protocols/raft/roles/LeaderRole.java
<ide> .build());
<ide> }
<ide> }
<del> // Otherwise, commit the command and update the request sequence number.
<add> // Otherwise, commit the command and update the request sequence number, then drain pending commands.
<ide> else {
<ide> commitCommand(request, future);
<ide> session.setRequestSequence(sequenceNumber);
<add> drainCommands(sequenceNumber, session);
<ide> }
<ide>
<ide> return future.thenApply(this::logResponse);
|
|
Java
|
agpl-3.0
|
9269d4b92d1d411bae71c1b82fb2915417d624aa
| 0 |
Peergos/Peergos,Peergos/Peergos,Peergos/Peergos
|
package peergos.shared.user.fs;
import java.util.function.*;
import java.util.logging.*;
import jsinterop.annotations.*;
import peergos.shared.*;
import peergos.shared.crypto.*;
import peergos.shared.crypto.hash.*;
import peergos.shared.crypto.random.*;
import peergos.shared.crypto.symmetric.*;
import peergos.shared.storage.*;
import peergos.shared.storage.auth.*;
import peergos.shared.user.*;
import peergos.shared.user.fs.cryptree.*;
import peergos.shared.util.*;
import java.time.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.stream.*;
public class FileUploader implements AutoCloseable {
private static final Logger LOG = Logger.getGlobal();
private final String name;
private final long offset, length;
private final FileProperties props;
private final SymmetricKey baseKey;
private final SymmetricKey dataKey;
private final long nchunks;
private final Location parentLocation;
private final Optional<Bat> parentBat;
private final SymmetricKey parentparentKey;
private final ProgressConsumer<Long> monitor;
private final AsyncReader reader; // resettable input stream
private final byte[] firstLocation;
private final Optional<Bat> firstBat;
@JsConstructor
public FileUploader(String name, String mimeType, AsyncReader fileData,
int offsetHi, int offsetLow, int lengthHi, int lengthLow,
SymmetricKey baseKey,
SymmetricKey dataKey,
Location parentLocation,
Optional<Bat> parentBat,
SymmetricKey parentparentKey,
ProgressConsumer<Long> monitor,
FileProperties fileProperties,
byte[] firstLocation,
Optional<Bat> firstBat) {
long length = (lengthLow & 0xFFFFFFFFL) + ((lengthHi & 0xFFFFFFFFL) << 32);
if (fileProperties == null)
this.props = new FileProperties(name, false, false, mimeType, length, LocalDateTime.now(),
false, Optional.empty(), Optional.empty());
else
this.props = fileProperties;
if (baseKey == null) baseKey = SymmetricKey.random();
long offset = (offsetLow & 0xFFFFFFFFL) + ((offsetHi & 0xFFFFFFFFL) << 32);
// Process and upload chunk by chunk to avoid running out of RAM, in reverse order to build linked list
this.nchunks = length > 0 ? (length + Chunk.MAX_SIZE - 1) / Chunk.MAX_SIZE : 1;
this.name = name;
this.offset = offset;
this.length = length;
this.reader = fileData;
this.baseKey = baseKey;
this.dataKey = dataKey;
this.parentLocation = parentLocation;
this.parentBat = parentBat;
this.parentparentKey = parentparentKey;
this.monitor = monitor;
this.firstLocation = firstLocation;
this.firstBat = firstBat;
}
public FileUploader(String name, String mimeType, AsyncReader fileData, long offset, long length,
SymmetricKey baseKey, SymmetricKey dataKey, Location parentLocation, Optional<Bat> parentBat,
SymmetricKey parentparentKey, ProgressConsumer<Long> monitor, FileProperties fileProperties,
byte[] firstLocation, Optional<Bat> firstBat) {
this(name, mimeType, fileData, (int)(offset >> 32), (int) offset, (int) (length >> 32), (int) length,
baseKey, dataKey, parentLocation, parentBat, parentparentKey, monitor, fileProperties, firstLocation, firstBat);
}
private static class AsyncUploadQueue {
private final LinkedList<CompletableFuture<ChunkUpload>> toUpload = new LinkedList<>();
private final LinkedList<CompletableFuture<Boolean>> waitingWorkers = new LinkedList<>();
private final LinkedList<CompletableFuture<ChunkUpload>> waitingUploaders = new LinkedList<>();
private static final int MAX_QUEUE_SIZE = 10;
public synchronized CompletableFuture<Boolean> add(ChunkUpload chunk) {
if (! waitingUploaders.isEmpty()) {
waitingUploaders.poll().complete(chunk);
return Futures.of(true);
}
toUpload.add(Futures.of(chunk));
if (toUpload.size() < MAX_QUEUE_SIZE) {
return Futures.of(true);
}
CompletableFuture<Boolean> wait = new CompletableFuture<>();
waitingWorkers.add(wait);
return wait;
}
public synchronized CompletableFuture<ChunkUpload> poll() {
if (! toUpload.isEmpty()) {
CompletableFuture<ChunkUpload> res = toUpload.poll();
if (! waitingWorkers.isEmpty()) {
CompletableFuture<Boolean> worker = waitingWorkers.poll();
runAsync(() -> Futures.of(worker.complete(true)));
}
return res;
}
CompletableFuture<ChunkUpload> wait = new CompletableFuture<>();
waitingUploaders.add(wait);
return wait;
}
}
private static <V> CompletableFuture<V> runAsync(Supplier<CompletableFuture<V>> work) {
CompletableFuture<V> res = new CompletableFuture<>();
ForkJoinPool.commonPool().execute(() -> {
try {
work.get()
.thenApply(res::complete)
.exceptionally(res::completeExceptionally);
} catch (Throwable t) {
res.completeExceptionally(t);
}
});
return res;
}
public CompletableFuture<Snapshot> upload(Snapshot current,
Committer c,
NetworkAccess network,
PublicKeyHash owner,
SigningPrivateKeyAndPublicHash writer,
Optional<BatId> mirrorBat,
SafeRandom random,
Hasher hasher) {
long t1 = System.currentTimeMillis();
AsyncUploadQueue queue = new AsyncUploadQueue();
List<Integer> input = IntStream.range(0, (int) nchunks).mapToObj(i -> Integer.valueOf(i)).collect(Collectors.toList());
CompletableFuture<Snapshot> res = new CompletableFuture<>();
Futures.reduceAll(input, true,
(p, i) -> runAsync(() -> encryptChunk(i, owner, writer, mirrorBat, MaybeMultihash.empty(), random, hasher, network.isJavascript())
.thenCompose(queue::add)),
(a, b) -> b)
.exceptionally(res::completeExceptionally);
Futures.reduceAll(input, current,
(s, i) -> queue.poll().thenCompose(chunk -> uploadChunk(s, c, chunk, writer, network, monitor)),
(a, b) -> b)
.thenApply(x -> {
LOG.info("File encryption, upload took: " +(System.currentTimeMillis()-t1) + " mS");
return x;
}).thenApply(res::complete)
.exceptionally(res::completeExceptionally);
return res;
}
private static class ChunkUpload {
public final LocatedChunk chunk;
public final CryptreeNode metadata;
public final List<FragmentWithHash> fragments;
public ChunkUpload(LocatedChunk chunk, CryptreeNode metadata, List<FragmentWithHash> fragments) {
this.chunk = chunk;
this.metadata = metadata;
this.fragments = fragments;
}
}
public CompletableFuture<ChunkUpload> encryptChunk(
long chunkIndex,
PublicKeyHash owner,
SigningPrivateKeyAndPublicHash writer,
Optional<BatId> mirrorBat,
MaybeMultihash ourExistingHash,
SafeRandom random,
Hasher hasher,
boolean isJS) {
System.out.println("encrypting chunk: "+chunkIndex + " of "+name);
long position = chunkIndex * Chunk.MAX_SIZE;
long fileLength = length;
boolean isLastChunk = fileLength < position + Chunk.MAX_SIZE;
int length = isLastChunk ? (int)(fileLength - position) : Chunk.MAX_SIZE;
byte[] data = new byte[length];
return reader.readIntoArray(data, 0, data.length).thenCompose(b -> {
byte[] nonce = baseKey.createNonce();
return FileProperties.calculateMapKey(props.streamSecret.get(), firstLocation, firstBat,
chunkIndex * Chunk.MAX_SIZE, hasher)
.thenCompose(mapKeyAndBat -> {
Chunk rawChunk = new Chunk(data, dataKey, mapKeyAndBat.left, nonce);
LocatedChunk chunk = new LocatedChunk(new Location(owner, writer.publicKeyHash, rawChunk.mapKey()), mapKeyAndBat.right, ourExistingHash, rawChunk);
return FileProperties.calculateNextMapKey(props.streamSecret.get(), mapKeyAndBat.left, mapKeyAndBat.right, hasher)
.thenCompose(nextMapKeyAndBat -> {
Optional<Bat> nextChunkBat = nextMapKeyAndBat.right;
Location nextChunkLocation = new Location(owner, writer.publicKeyHash, nextMapKeyAndBat.left);
if (! writer.publicKeyHash.equals(chunk.location.writer))
throw new IllegalStateException("Trying to write a chunk to the wrong signing key space!");
RelativeCapability nextChunk = RelativeCapability.buildSubsequentChunk(nextChunkLocation.getMapKey(), nextChunkBat, baseKey);
return CryptreeNode.createFile(chunk.existingHash, chunk.location.writer, baseKey,
chunk.chunk.key(), props, chunk.chunk.data(), parentLocation, parentBat, parentparentKey, nextChunk,
chunk.bat, mirrorBat, random, hasher, isJS)
.thenApply(p -> new ChunkUpload(chunk, p.left, p.right));
});
});
});
}
public static CompletableFuture<Snapshot> uploadChunk(Snapshot current,
Committer committer,
ChunkUpload file,
SigningPrivateKeyAndPublicHash writer,
NetworkAccess network,
ProgressConsumer<Long> monitor) {
CryptreeNode metadata = file.metadata;
LocatedChunk chunk = file.chunk;
List<Fragment> fragments = file.fragments.stream()
.filter(f -> !f.isInlined())
.map(f -> f.fragment)
.collect(Collectors.toList());
CappedProgressConsumer progress = new CappedProgressConsumer(monitor, chunk.chunk.length());
if (fragments.size() < file.fragments.size() || fragments.isEmpty())
progress.accept((long) chunk.chunk.length());
System.out.println("Uploading chunk with " + fragments.size() + " fragments\n");
return IpfsTransaction.call(chunk.location.owner,
tid -> network.uploadFragments(fragments, chunk.location.owner, writer, progress, tid)
.thenCompose(hashes -> network.uploadChunk(current, committer, metadata, chunk.location.owner,
chunk.chunk.mapKey(), writer, tid)),
network.dhtClient);
}
public static CompletableFuture<Snapshot> uploadChunk(Snapshot current,
Committer committer,
SigningPrivateKeyAndPublicHash writer,
FileProperties props,
Location parentLocation,
Optional<Bat> parentBat,
SymmetricKey parentparentKey,
SymmetricKey baseKey,
LocatedChunk chunk,
Location nextChunkLocation,
Optional<Bat> nextChunkBat,
Optional<SymmetricLinkToSigner> writerLink,
Optional<BatId> mirrorBat,
SafeRandom random,
Hasher hasher,
NetworkAccess network,
ProgressConsumer<Long> monitor) {
CappedProgressConsumer progress = new CappedProgressConsumer(monitor, chunk.chunk.length());
if (! writer.publicKeyHash.equals(chunk.location.writer))
throw new IllegalStateException("Trying to write a chunk to the wrong signing key space!");
RelativeCapability nextChunk = RelativeCapability.buildSubsequentChunk(nextChunkLocation.getMapKey(), nextChunkBat, baseKey);
return CryptreeNode.createFile(chunk.existingHash, chunk.location.writer, baseKey,
chunk.chunk.key(), props, chunk.chunk.data(), parentLocation, parentBat, parentparentKey, nextChunk,
chunk.bat, mirrorBat, random, hasher, network.isJavascript())
.thenCompose(file -> uploadChunk(current, committer, new ChunkUpload(chunk, file.left.withWriterLink(baseKey, writerLink), file.right),
writer, network, progress));
}
public void close() {
reader.close();
}
}
|
src/peergos/shared/user/fs/FileUploader.java
|
package peergos.shared.user.fs;
import java.util.function.*;
import java.util.logging.*;
import jsinterop.annotations.*;
import peergos.shared.*;
import peergos.shared.crypto.*;
import peergos.shared.crypto.hash.*;
import peergos.shared.crypto.random.*;
import peergos.shared.crypto.symmetric.*;
import peergos.shared.storage.*;
import peergos.shared.storage.auth.*;
import peergos.shared.user.*;
import peergos.shared.user.fs.cryptree.*;
import peergos.shared.util.*;
import java.time.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.stream.*;
public class FileUploader implements AutoCloseable {
private static final Logger LOG = Logger.getGlobal();
private final String name;
private final long offset, length;
private final FileProperties props;
private final SymmetricKey baseKey;
private final SymmetricKey dataKey;
private final long nchunks;
private final Location parentLocation;
private final Optional<Bat> parentBat;
private final SymmetricKey parentparentKey;
private final ProgressConsumer<Long> monitor;
private final AsyncReader reader; // resettable input stream
private final byte[] firstLocation;
private final Optional<Bat> firstBat;
@JsConstructor
public FileUploader(String name, String mimeType, AsyncReader fileData,
int offsetHi, int offsetLow, int lengthHi, int lengthLow,
SymmetricKey baseKey,
SymmetricKey dataKey,
Location parentLocation,
Optional<Bat> parentBat,
SymmetricKey parentparentKey,
ProgressConsumer<Long> monitor,
FileProperties fileProperties,
byte[] firstLocation,
Optional<Bat> firstBat) {
long length = (lengthLow & 0xFFFFFFFFL) + ((lengthHi & 0xFFFFFFFFL) << 32);
if (fileProperties == null)
this.props = new FileProperties(name, false, false, mimeType, length, LocalDateTime.now(),
false, Optional.empty(), Optional.empty());
else
this.props = fileProperties;
if (baseKey == null) baseKey = SymmetricKey.random();
long offset = (offsetLow & 0xFFFFFFFFL) + ((offsetHi & 0xFFFFFFFFL) << 32);
// Process and upload chunk by chunk to avoid running out of RAM, in reverse order to build linked list
this.nchunks = length > 0 ? (length + Chunk.MAX_SIZE - 1) / Chunk.MAX_SIZE : 1;
this.name = name;
this.offset = offset;
this.length = length;
this.reader = fileData;
this.baseKey = baseKey;
this.dataKey = dataKey;
this.parentLocation = parentLocation;
this.parentBat = parentBat;
this.parentparentKey = parentparentKey;
this.monitor = monitor;
this.firstLocation = firstLocation;
this.firstBat = firstBat;
}
public FileUploader(String name, String mimeType, AsyncReader fileData, long offset, long length,
SymmetricKey baseKey, SymmetricKey dataKey, Location parentLocation, Optional<Bat> parentBat,
SymmetricKey parentparentKey, ProgressConsumer<Long> monitor, FileProperties fileProperties,
byte[] firstLocation, Optional<Bat> firstBat) {
this(name, mimeType, fileData, (int)(offset >> 32), (int) offset, (int) (length >> 32), (int) length,
baseKey, dataKey, parentLocation, parentBat, parentparentKey, monitor, fileProperties, firstLocation, firstBat);
}
private static class AsyncUploadQueue {
private final LinkedList<CompletableFuture<ChunkUpload>> toUpload = new LinkedList<>();
private final LinkedList<CompletableFuture<Boolean>> waitingWorkers = new LinkedList<>();
private final LinkedList<CompletableFuture<ChunkUpload>> waitingUploaders = new LinkedList<>();
private static final int MAX_QUEUE_SIZE = 10;
public synchronized CompletableFuture<Boolean> add(ChunkUpload chunk) {
if (! waitingUploaders.isEmpty()) {
waitingUploaders.poll().complete(chunk);
return Futures.of(true);
}
toUpload.add(Futures.of(chunk));
if (toUpload.size() < MAX_QUEUE_SIZE) {
return Futures.of(true);
}
CompletableFuture<Boolean> wait = new CompletableFuture<>();
waitingWorkers.add(wait);
return wait;
}
public synchronized CompletableFuture<ChunkUpload> poll() {
if (! toUpload.isEmpty()) {
CompletableFuture<ChunkUpload> res = toUpload.poll();
if (! waitingWorkers.isEmpty()) {
CompletableFuture<Boolean> worker = waitingWorkers.poll();
runAsync(() -> Futures.of(worker.complete(true)));
}
return res;
}
CompletableFuture<ChunkUpload> wait = new CompletableFuture<>();
waitingUploaders.add(wait);
return wait;
}
}
private static <V> CompletableFuture<V> runAsync(Supplier<CompletableFuture<V>> work) {
CompletableFuture<V> res = new CompletableFuture<>();
ForkJoinPool.commonPool().execute(() -> work.get()
.thenApply(res::complete)
.exceptionally(res::completeExceptionally));
return res;
}
public CompletableFuture<Snapshot> upload(Snapshot current,
Committer c,
NetworkAccess network,
PublicKeyHash owner,
SigningPrivateKeyAndPublicHash writer,
Optional<BatId> mirrorBat,
SafeRandom random,
Hasher hasher) {
long t1 = System.currentTimeMillis();
AsyncUploadQueue queue = new AsyncUploadQueue();
List<Integer> input = IntStream.range(0, (int) nchunks).mapToObj(i -> Integer.valueOf(i)).collect(Collectors.toList());
Futures.reduceAll(input, true,
(p, i) -> runAsync(() -> encryptChunk(i, owner, writer, mirrorBat, MaybeMultihash.empty(), random, hasher, network.isJavascript())
.thenCompose(queue::add)),
(a, b) -> b);
return Futures.reduceAll(input, current,
(s, i) -> queue.poll().thenCompose(chunk -> uploadChunk(s, c, chunk, writer, network, monitor)),
(a, b) -> b)
.thenApply(x -> {
LOG.info("File encryption, upload took: " +(System.currentTimeMillis()-t1) + " mS");
return x;
});
}
private static class ChunkUpload {
public final LocatedChunk chunk;
public final CryptreeNode metadata;
public final List<FragmentWithHash> fragments;
public ChunkUpload(LocatedChunk chunk, CryptreeNode metadata, List<FragmentWithHash> fragments) {
this.chunk = chunk;
this.metadata = metadata;
this.fragments = fragments;
}
}
public CompletableFuture<ChunkUpload> encryptChunk(
long chunkIndex,
PublicKeyHash owner,
SigningPrivateKeyAndPublicHash writer,
Optional<BatId> mirrorBat,
MaybeMultihash ourExistingHash,
SafeRandom random,
Hasher hasher,
boolean isJS) {
System.out.println("encrypting chunk: "+chunkIndex + " of "+name);
long position = chunkIndex * Chunk.MAX_SIZE;
long fileLength = length;
boolean isLastChunk = fileLength < position + Chunk.MAX_SIZE;
int length = isLastChunk ? (int)(fileLength - position) : Chunk.MAX_SIZE;
byte[] data = new byte[length];
return reader.readIntoArray(data, 0, data.length).thenCompose(b -> {
byte[] nonce = baseKey.createNonce();
return FileProperties.calculateMapKey(props.streamSecret.get(), firstLocation, firstBat,
chunkIndex * Chunk.MAX_SIZE, hasher)
.thenCompose(mapKeyAndBat -> {
Chunk rawChunk = new Chunk(data, dataKey, mapKeyAndBat.left, nonce);
LocatedChunk chunk = new LocatedChunk(new Location(owner, writer.publicKeyHash, rawChunk.mapKey()), mapKeyAndBat.right, ourExistingHash, rawChunk);
return FileProperties.calculateNextMapKey(props.streamSecret.get(), mapKeyAndBat.left, mapKeyAndBat.right, hasher)
.thenCompose(nextMapKeyAndBat -> {
Optional<Bat> nextChunkBat = nextMapKeyAndBat.right;
Location nextChunkLocation = new Location(owner, writer.publicKeyHash, nextMapKeyAndBat.left);
if (! writer.publicKeyHash.equals(chunk.location.writer))
throw new IllegalStateException("Trying to write a chunk to the wrong signing key space!");
RelativeCapability nextChunk = RelativeCapability.buildSubsequentChunk(nextChunkLocation.getMapKey(), nextChunkBat, baseKey);
return CryptreeNode.createFile(chunk.existingHash, chunk.location.writer, baseKey,
chunk.chunk.key(), props, chunk.chunk.data(), parentLocation, parentBat, parentparentKey, nextChunk,
chunk.bat, mirrorBat, random, hasher, isJS)
.thenApply(p -> new ChunkUpload(chunk, p.left, p.right));
});
});
});
}
public static CompletableFuture<Snapshot> uploadChunk(Snapshot current,
Committer committer,
ChunkUpload file,
SigningPrivateKeyAndPublicHash writer,
NetworkAccess network,
ProgressConsumer<Long> monitor) {
CryptreeNode metadata = file.metadata;
LocatedChunk chunk = file.chunk;
List<Fragment> fragments = file.fragments.stream()
.filter(f -> !f.isInlined())
.map(f -> f.fragment)
.collect(Collectors.toList());
CappedProgressConsumer progress = new CappedProgressConsumer(monitor, chunk.chunk.length());
if (fragments.size() < file.fragments.size() || fragments.isEmpty())
progress.accept((long) chunk.chunk.length());
System.out.println("Uploading chunk with " + fragments.size() + " fragments\n");
return IpfsTransaction.call(chunk.location.owner,
tid -> network.uploadFragments(fragments, chunk.location.owner, writer, progress, tid)
.thenCompose(hashes -> network.uploadChunk(current, committer, metadata, chunk.location.owner,
chunk.chunk.mapKey(), writer, tid)),
network.dhtClient);
}
public static CompletableFuture<Snapshot> uploadChunk(Snapshot current,
Committer committer,
SigningPrivateKeyAndPublicHash writer,
FileProperties props,
Location parentLocation,
Optional<Bat> parentBat,
SymmetricKey parentparentKey,
SymmetricKey baseKey,
LocatedChunk chunk,
Location nextChunkLocation,
Optional<Bat> nextChunkBat,
Optional<SymmetricLinkToSigner> writerLink,
Optional<BatId> mirrorBat,
SafeRandom random,
Hasher hasher,
NetworkAccess network,
ProgressConsumer<Long> monitor) {
CappedProgressConsumer progress = new CappedProgressConsumer(monitor, chunk.chunk.length());
if (! writer.publicKeyHash.equals(chunk.location.writer))
throw new IllegalStateException("Trying to write a chunk to the wrong signing key space!");
RelativeCapability nextChunk = RelativeCapability.buildSubsequentChunk(nextChunkLocation.getMapKey(), nextChunkBat, baseKey);
return CryptreeNode.createFile(chunk.existingHash, chunk.location.writer, baseKey,
chunk.chunk.key(), props, chunk.chunk.data(), parentLocation, parentBat, parentparentKey, nextChunk,
chunk.bat, mirrorBat, random, hasher, network.isJavascript())
.thenCompose(file -> uploadChunk(current, committer, new ChunkUpload(chunk, file.left.withWriterLink(baseKey, writerLink), file.right),
writer, network, progress));
}
public void close() {
reader.close();
}
}
|
Fix error handling in file upload encryption queue
|
src/peergos/shared/user/fs/FileUploader.java
|
Fix error handling in file upload encryption queue
|
<ide><path>rc/peergos/shared/user/fs/FileUploader.java
<ide>
<ide> private static <V> CompletableFuture<V> runAsync(Supplier<CompletableFuture<V>> work) {
<ide> CompletableFuture<V> res = new CompletableFuture<>();
<del> ForkJoinPool.commonPool().execute(() -> work.get()
<del> .thenApply(res::complete)
<del> .exceptionally(res::completeExceptionally));
<add> ForkJoinPool.commonPool().execute(() -> {
<add> try {
<add> work.get()
<add> .thenApply(res::complete)
<add> .exceptionally(res::completeExceptionally);
<add> } catch (Throwable t) {
<add> res.completeExceptionally(t);
<add> }
<add> });
<ide> return res;
<ide> }
<ide>
<ide>
<ide> AsyncUploadQueue queue = new AsyncUploadQueue();
<ide> List<Integer> input = IntStream.range(0, (int) nchunks).mapToObj(i -> Integer.valueOf(i)).collect(Collectors.toList());
<add> CompletableFuture<Snapshot> res = new CompletableFuture<>();
<ide> Futures.reduceAll(input, true,
<ide> (p, i) -> runAsync(() -> encryptChunk(i, owner, writer, mirrorBat, MaybeMultihash.empty(), random, hasher, network.isJavascript())
<ide> .thenCompose(queue::add)),
<del> (a, b) -> b);
<del> return Futures.reduceAll(input, current,
<add> (a, b) -> b)
<add> .exceptionally(res::completeExceptionally);
<add> Futures.reduceAll(input, current,
<ide> (s, i) -> queue.poll().thenCompose(chunk -> uploadChunk(s, c, chunk, writer, network, monitor)),
<ide> (a, b) -> b)
<ide> .thenApply(x -> {
<ide> LOG.info("File encryption, upload took: " +(System.currentTimeMillis()-t1) + " mS");
<ide> return x;
<del> });
<add> }).thenApply(res::complete)
<add> .exceptionally(res::completeExceptionally);
<add>
<add> return res;
<ide> }
<ide>
<ide> private static class ChunkUpload {
|
|
Java
|
agpl-3.0
|
6c46334f8253f4d8d144061d851ae630793fed91
| 0 |
elki-project/elki,elki-project/elki,elki-project/elki
|
package de.lmu.ifi.dbs.elki.utilities.datastructures.arraylike;
/*
This file is part of ELKI:
Environment for Developing KDD-Applications Supported by Index-Structures
Copyright (C) 2015
Ludwig-Maximilians-Universität München
Lehr- und Forschungseinheit für Datenbanksysteme
ELKI Development Team
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import java.util.Arrays;
/**
* Array of double values.
*
* TODO: add remove, sort etc.
*
* @author Erich Schubert
*/
public class DoubleArray implements NumberArrayAdapter<Double, DoubleArray> {
/**
* Maximum array size permitted by Java.
*
* This is JVM dependent, but 2^31 - 5 is the usual OpenJDK8 value.
*/
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 5;
/**
* Last value where we can double the array size.
*/
private static final int LAST_DOUBLE_SIZE = MAX_ARRAY_SIZE >> 1;
/**
* (Reused) store for numerical attributes.
*/
public double[] data;
/**
* Number of numerical attributes.
*/
public int size;
/**
* Constructor.
*/
public DoubleArray() {
this(11);
}
/**
* Constructor.
*
* @param initialsize Initial size.
*/
public DoubleArray(int initialsize) {
if(initialsize < 0) {
initialsize = 11;
}
else if(initialsize > MAX_ARRAY_SIZE) {
initialsize = MAX_ARRAY_SIZE;
}
this.data = new double[initialsize];
this.size = 0;
}
/**
* Constructor from an existing array.
*
* The new array will be allocated as small as possible, so modifications will
* cause a resize!
*
* @param existing Existing array
*/
public DoubleArray(DoubleArray existing) {
this.data = Arrays.copyOf(existing.data, existing.size);
this.size = existing.size;
}
/**
* Reset the numeric attribute counter.
*/
public void clear() {
size = 0;
}
/**
* Add a numeric attribute value.
*
* @param attribute Attribute value.
*/
public void add(double attribute) {
if(data.length == size) {
grow();
}
data[size++] = attribute;
}
/**
* Grow the current array.
*
* @throws OutOfMemoryError
*/
private void grow() throws OutOfMemoryError {
if(data.length == MAX_ARRAY_SIZE) {
throw new OutOfMemoryError("Array size has reached the Java maximum.");
}
final int newsize = (size >= LAST_DOUBLE_SIZE) ? MAX_ARRAY_SIZE : (size << 1);
data = Arrays.copyOf(data, newsize);
}
/**
* Get the value at this position.
*
* @param pos Position
* @return Value
*/
public double get(int pos) {
if(pos < 0 || pos >= size) {
throw new ArrayIndexOutOfBoundsException(pos);
}
return data[pos];
}
/**
* Set the value at this position.
*
* @param pos Position
* @param value Value
*/
public void set(int pos, double value) {
if(pos < 0 || pos > size) {
throw new ArrayIndexOutOfBoundsException(pos);
}
if(pos == size) {
add(value);
return;
}
data[pos] = value;
}
/**
* Remove a range from the array.
*
* @param start Start
* @param len Length
*/
public void remove(int start, int len) {
final int end = start + len;
if(end > size) {
throw new ArrayIndexOutOfBoundsException(size);
}
System.arraycopy(data, end, data, start, size - end);
size -= len;
}
/**
* Insert a value at the given position.
*
* @param pos Insert position
* @param val Value to insert
*/
public void insert(int pos, double val) {
if(size == data.length) {
double[] oldd = data;
data = new double[size << 1];
System.arraycopy(oldd, 0, data, 0, pos);
System.arraycopy(oldd, pos, data, pos + 1, size - pos);
}
else {
System.arraycopy(data, pos, data, pos + 1, size - pos);
}
data[pos] = val;
size++;
}
/**
* Get the size of the array.
*
* @return Size
*/
public int size() {
return size;
}
/**
* Sort the contents.
*/
public void sort() {
Arrays.sort(data, 0, size);
}
// NumberArrayAdapter:
@Override
public int size(DoubleArray array) {
return array.size;
}
@Override
public Double get(DoubleArray array, int off) throws IndexOutOfBoundsException {
return array.data[off];
}
@Override
public double getDouble(DoubleArray array, int off) throws IndexOutOfBoundsException {
return array.data[off];
}
@Override
public float getFloat(DoubleArray array, int off) throws IndexOutOfBoundsException {
return (float) array.data[off];
}
@Override
public int getInteger(DoubleArray array, int off) throws IndexOutOfBoundsException {
return (int) array.data[off];
}
@Override
public short getShort(DoubleArray array, int off) throws IndexOutOfBoundsException {
return (short) array.data[off];
}
@Override
public long getLong(DoubleArray array, int off) throws IndexOutOfBoundsException {
return (long) array.data[off];
}
@Override
public byte getByte(DoubleArray array, int off) throws IndexOutOfBoundsException {
return (byte) array.data[off];
}
/**
* Return a copy of the contents as array.
*
* @return Copy of the contents.
*/
public double[] toArray() {
return Arrays.copyOf(data, size);
}
}
|
elki/src/main/java/de/lmu/ifi/dbs/elki/utilities/datastructures/arraylike/DoubleArray.java
|
package de.lmu.ifi.dbs.elki.utilities.datastructures.arraylike;
/*
This file is part of ELKI:
Environment for Developing KDD-Applications Supported by Index-Structures
Copyright (C) 2015
Ludwig-Maximilians-Universität München
Lehr- und Forschungseinheit für Datenbanksysteme
ELKI Development Team
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import java.util.Arrays;
/**
* Array of double values.
*
* TODO: add remove, sort etc.
*
* @author Erich Schubert
*/
public class DoubleArray implements NumberArrayAdapter<Double, DoubleArray> {
/**
* (Reused) store for numerical attributes.
*/
public double[] data;
/**
* Number of numerical attributes.
*/
public int size;
/**
* Constructor.
*/
public DoubleArray() {
this(11);
}
/**
* Constructor.
*
* @param initialsize Initial size.
*/
public DoubleArray(int initialsize) {
this.data = new double[initialsize];
this.size = 0;
}
/**
* Constructor from an existing array.
*
* The new array will be allocated as small as possible, so modifications will
* cause a resize!
*
* @param existing Existing array
*/
public DoubleArray(DoubleArray existing) {
this.data = Arrays.copyOf(existing.data, existing.size);
this.size = existing.size;
}
/**
* Reset the numeric attribute counter.
*/
public void clear() {
size = 0;
}
/**
* Add a numeric attribute value.
*
* @param attribute Attribute value.
*/
public void add(double attribute) {
if(data.length == size) {
data = Arrays.copyOf(data, size << 1);
}
data[size++] = attribute;
}
/**
* Get the value at this position.
*
* @param pos Position
* @return Value
*/
public double get(int pos) {
if(pos < 0 || pos >= size) {
throw new ArrayIndexOutOfBoundsException(pos);
}
return data[pos];
}
/**
* Set the value at this position.
*
* @param pos Position
* @param value Value
*/
public void set(int pos, double value) {
if(pos < 0 || pos > size) {
throw new ArrayIndexOutOfBoundsException(pos);
}
if(pos == size) {
add(value);
return;
}
data[pos] = value;
}
/**
* Remove a range from the array.
*
* @param start Start
* @param len Length
*/
public void remove(int start, int len) {
final int end = start + len;
if(end > size) {
throw new ArrayIndexOutOfBoundsException(size);
}
System.arraycopy(data, end, data, start, size - end);
size -= len;
}
/**
* Insert a value at the given position.
*
* @param pos Insert position
* @param val Value to insert
*/
public void insert(int pos, double val) {
if(size == data.length) {
double[] oldd = data;
data = new double[size << 1];
System.arraycopy(oldd, 0, data, 0, pos);
System.arraycopy(oldd, pos, data, pos + 1, size - pos);
}
else {
System.arraycopy(data, pos, data, pos + 1, size - pos);
}
data[pos] = val;
size++;
}
/**
* Get the size of the array.
*
* @return Size
*/
public int size() {
return size;
}
/**
* Sort the contents.
*/
public void sort() {
Arrays.sort(data, 0, size);
}
// NumberArrayAdapter:
@Override
public int size(DoubleArray array) {
return array.size;
}
@Override
public Double get(DoubleArray array, int off) throws IndexOutOfBoundsException {
return array.data[off];
}
@Override
public double getDouble(DoubleArray array, int off) throws IndexOutOfBoundsException {
return array.data[off];
}
@Override
public float getFloat(DoubleArray array, int off) throws IndexOutOfBoundsException {
return (float) array.data[off];
}
@Override
public int getInteger(DoubleArray array, int off) throws IndexOutOfBoundsException {
return (int) array.data[off];
}
@Override
public short getShort(DoubleArray array, int off) throws IndexOutOfBoundsException {
return (short) array.data[off];
}
@Override
public long getLong(DoubleArray array, int off) throws IndexOutOfBoundsException {
return (long) array.data[off];
}
@Override
public byte getByte(DoubleArray array, int off) throws IndexOutOfBoundsException {
return (byte) array.data[off];
}
/**
* Return a copy of the contents as array.
*
* @return Copy of the contents.
*/
public double[] toArray() {
return Arrays.copyOf(data, size);
}
}
|
Better out-of-memory handling in DoubleArray (stop doubling, exception).
|
elki/src/main/java/de/lmu/ifi/dbs/elki/utilities/datastructures/arraylike/DoubleArray.java
|
Better out-of-memory handling in DoubleArray (stop doubling, exception).
|
<ide><path>lki/src/main/java/de/lmu/ifi/dbs/elki/utilities/datastructures/arraylike/DoubleArray.java
<ide> */
<ide> public class DoubleArray implements NumberArrayAdapter<Double, DoubleArray> {
<ide> /**
<add> * Maximum array size permitted by Java.
<add> *
<add> * This is JVM dependent, but 2^31 - 5 is the usual OpenJDK8 value.
<add> */
<add> private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 5;
<add>
<add> /**
<add> * Last value where we can double the array size.
<add> */
<add> private static final int LAST_DOUBLE_SIZE = MAX_ARRAY_SIZE >> 1;
<add>
<add> /**
<ide> * (Reused) store for numerical attributes.
<ide> */
<ide> public double[] data;
<ide> * @param initialsize Initial size.
<ide> */
<ide> public DoubleArray(int initialsize) {
<add> if(initialsize < 0) {
<add> initialsize = 11;
<add> }
<add> else if(initialsize > MAX_ARRAY_SIZE) {
<add> initialsize = MAX_ARRAY_SIZE;
<add> }
<ide> this.data = new double[initialsize];
<ide> this.size = 0;
<ide> }
<ide> */
<ide> public void add(double attribute) {
<ide> if(data.length == size) {
<del> data = Arrays.copyOf(data, size << 1);
<add> grow();
<ide> }
<ide> data[size++] = attribute;
<add> }
<add>
<add> /**
<add> * Grow the current array.
<add> *
<add> * @throws OutOfMemoryError
<add> */
<add> private void grow() throws OutOfMemoryError {
<add> if(data.length == MAX_ARRAY_SIZE) {
<add> throw new OutOfMemoryError("Array size has reached the Java maximum.");
<add> }
<add> final int newsize = (size >= LAST_DOUBLE_SIZE) ? MAX_ARRAY_SIZE : (size << 1);
<add> data = Arrays.copyOf(data, newsize);
<ide> }
<ide>
<ide> /**
|
|
Java
|
mit
|
217cd9a61bc2a8710e0eaf34339fd3442bca94b6
| 0 |
nicoribeiro/java_efactura_uy,nicoribeiro/java_efactura_uy,nicoribeiro/java_efactura_uy,nicoribeiro/java_efactura_uy
|
package com.bluedot.efactura.controllers;
import java.awt.print.PrinterException;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.bluedot.commons.controllers.AbstractController;
import com.bluedot.commons.error.APIException;
import com.bluedot.commons.error.APIException.APIErrors;
import com.bluedot.commons.error.ErrorMessage;
import com.bluedot.commons.security.Secured;
import com.bluedot.commons.utils.DateHandler;
import com.bluedot.commons.utils.JSONUtils;
import com.bluedot.commons.utils.Print;
import com.bluedot.commons.utils.Tuple;
import com.bluedot.efactura.GenerateInvoice;
import com.bluedot.efactura.MODO_SISTEMA;
import com.bluedot.efactura.microControllers.factory.EfacturaMicroControllersFactory;
import com.bluedot.efactura.microControllers.factory.EfacturaMicroControllersFactoryBuilder;
import com.bluedot.efactura.model.CFE;
import com.bluedot.efactura.model.DireccionDocumento;
import com.bluedot.efactura.model.Empresa;
import com.bluedot.efactura.model.Sobre;
import com.bluedot.efactura.model.SobreEmitido;
import com.bluedot.efactura.model.TipoDoc;
import com.bluedot.efactura.pollers.PollerManager;
import com.bluedot.efactura.serializers.EfacturaJSONSerializerProvider;
import com.fasterxml.jackson.databind.JsonNode;
import com.google.inject.Inject;
import com.play4jpa.jpa.db.Tx;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import play.Play;
import play.libs.F.Promise;
import play.mvc.BodyParser;
import play.mvc.Result;
import play.mvc.Security;
@ErrorMessage
@Tx
@Security.Authenticated(Secured.class)
@Api(value = "Operaciones de Documentos")
public class DocumentController extends AbstractController {
private static boolean initialized = false;
final static Logger logger = LoggerFactory.getLogger(DocumentController.class);
private PollerManager pollerManager;
@Inject
public DocumentController(PollerManager pollerManager){
super();
this.pollerManager = pollerManager;
if (!initialized) {
init();
}
}
private synchronized void init() {
initialized = true;
pollerManager.queue();
}
public Promise<Result> cambiarModo(String modo) throws APIException {
MODO_SISTEMA modoEnum = MODO_SISTEMA.valueOf(modo);
if (modoEnum == null)
throw APIException.raise(APIErrors.BAD_PARAMETER_VALUE).withParams("modo");
EfacturaMicroControllersFactory factory = (new EfacturaMicroControllersFactoryBuilder())
.getMicroControllersFactory();
factory.setModo(modoEnum);
return json(OK);
}
@ApiOperation(value = "Crear CFE",
response = CFE.class
)
@BodyParser.Of(BodyParser.Json.class)
public Promise<Result> aceptarDocumento(String rut) throws APIException {
// TODO meter mutex
Empresa empresa = Empresa.findByRUT(rut, true);
JsonNode jsonNode = request().body().asJson();
JSONObject document = new JSONObject(jsonNode.toString());
EfacturaMicroControllersFactory factory = (new EfacturaMicroControllersFactoryBuilder())
.getMicroControllersFactory();
// TODO estos controles se pueden mover a una annotation
if (!document.has("Encabezado"))
throw APIException.raise(APIErrors.MISSING_PARAMETER).withParams("Encabezado");
if (!document.getJSONObject("Encabezado").has("IdDoc"))
throw APIException.raise(APIErrors.MISSING_PARAMETER).withParams("IdDoc");
if (!document.getJSONObject("Encabezado").getJSONObject("IdDoc").has("TipoCFE"))
throw APIException.raise(APIErrors.MISSING_PARAMETER).withParams("TipoCFE");
if (!document.getJSONObject("Encabezado").getJSONObject("IdDoc").has("id"))
throw APIException.raise(APIErrors.MISSING_PARAMETER).withParams("id");
TipoDoc tipo = TipoDoc
.fromInt(document.getJSONObject("Encabezado").getJSONObject("IdDoc").getInt("TipoCFE"));
if (tipo == null)
throw APIException.raise(APIErrors.BAD_PARAMETER_VALUE).withParams("TipoCFE");
String id = document.getJSONObject("Encabezado").getJSONObject("IdDoc").getString("id");
CFE cfe = CFE.findByGeneradorId(empresa, id, DireccionDocumento.EMITIDO);
if (cfe != null)
throw APIException.raise(APIErrors.EXISTE_CFE).withParams("generadorId", id);
switch (tipo) {
case eFactura:
case eTicket:
case eResguardo:
cfe = factory.getCFEMicroController(empresa).create(tipo, document, true);
break;
case Nota_de_Credito_de_eFactura:
case Nota_de_Credito_de_eTicket:
case Nota_de_Debito_de_eFactura:
case Nota_de_Debito_de_eTicket:
if (!document.has("Referencia"))
throw APIException.raise(APIErrors.MISSING_PARAMETER).withParams("Referencia");
cfe = factory.getCFEMicroController(empresa).create(tipo, document, true);
break;
case eFactura_Venta_por_Cuenta_Ajena:
case eTicket_Venta_por_Cuenta_Ajena:
case Nota_de_Credito_de_eFactura_Venta_por_Cuenta_Ajena:
case Nota_de_Credito_de_eTicket_Venta_por_Cuenta_Ajena:
case Nota_de_Debito_de_eTicket_Venta_por_Cuenta_Ajena:
case Nota_de_Debito_de_eFactura_Venta_por_Cuenta_Ajena:
if (!document.has("CompFiscal"))
throw APIException.raise(APIErrors.MISSING_PARAMETER).withParams("CompFiscal");
cfe = factory.getCFEMicroController(empresa).create(tipo, document, true);
break;
case eFactura_Contingencia:
case eFactura_Venta_por_Cuenta_Ajena_Contingencia:
case eFactura_Exportacion:
case eFactura_Exportacion_Contingencia:
case eRemito:
case eRemito_Contingencia:
case eRemito_de_Exportacion:
case eRemito_de_Exportacion_Contingencia:
case eResguardo_Contingencia:
case Nota_de_Credito_de_eFactura_Contingencia:
case Nota_de_Credito_de_eFactura_Exportacion:
case Nota_de_Credito_de_eFactura_Exportacion_Contingencia:
case Nota_de_Credito_de_eFactura_Venta_por_Cuenta_Ajena_Contingencia:
case Nota_de_Credito_de_eTicket_Contingencia:
case Nota_de_Credito_de_eTicket_Venta_por_Cuenta_Ajena_Contingencia:
case Nota_de_Debito_de_eFactura_Contingencia:
case Nota_de_Debito_de_eFactura_Exportacion:
case Nota_de_Debito_de_eFactura_Exportacion_Contingencia:
case Nota_de_Debito_de_eFactura_Venta_por_Cuenta_Ajena_Contingencia:
case Nota_de_Debito_de_eTicket_Contingencia:
case Nota_de_Debito_de_eTicket_Venta_por_Cuenta_Ajena_Contingencia:
case eTicket_Contingencia:
case eTicket_Venta_por_Cuenta_Ajena_Contingencia:
throw APIException.raise(APIErrors.NOT_SUPPORTED).setDetailMessage(tipo.toString());
}
if (cfe != null) {
if (document.has("Adenda"))
cfe.setAdenda(document.getJSONArray("Adenda").toString());
JSONObject error = null;
if (cfe.getFechaEmision()==null)
cfe.setFechaEmision(new Date());
try {
factory.getServiceMicroController(empresa).enviar(cfe);
} catch (APIException e) {
logger.error("APIException:", e);
error = e.getJSONObject();
}
JSONObject result = procesar_resultado(empresa, cfe, error);
return json(result.toString());
} else
throw APIException.raise(APIErrors.NO_CFE_CREATED);
}
/**
* @param empresa
* @param cfe
* @param error
* @return
* @throws APIException
*/
private JSONObject procesar_resultado(Empresa empresa, CFE cfe, JSONObject error) throws APIException {
JSONObject result;
if (error != null) {
JSONObject cfeJson = new JSONObject();
cfeJson.put("nro", cfe.getNro());
cfeJson.put("serie", cfe.getSerie());
result = JSONUtils.merge(cfeJson, error);
}
else {
JSONObject cfeJson;
try {
cfeJson = EfacturaJSONSerializerProvider.getCFESerializer().objectToJson(cfe);
} catch (JSONException e) {
throw APIException.raise(APIErrors.BAD_JSON);
}
result = JSONUtils.merge(cfeJson, new JSONObject(OK));
}
try {
generarPDF(empresa, cfe);
} catch (Throwable e) {
}
return result;
}
@BodyParser.Of(BodyParser.Json.class)
public Promise<Result> reenviarDocumento(String rut, int nro, String serie, int idTipoDoc) throws APIException {
// TODO meter mutex
Empresa empresa = Empresa.findByRUT(rut, true);
EfacturaMicroControllersFactory factory = (new EfacturaMicroControllersFactoryBuilder())
.getMicroControllersFactory();
TipoDoc tipo = TipoDoc.fromInt(idTipoDoc);
List<CFE> cfes = CFE.findById(empresa, tipo, serie, nro, null, DireccionDocumento.EMITIDO, true);
if (cfes.size()>1)
throw APIException.raise(APIErrors.CFE_NO_ENCONTRADO).withParams("RUT+NRO+SERIE+TIPODOC",rut+"-"+nro+"-"+serie+"-"+idTipoDoc).setDetailMessage("No identifica a un unico cfe");
CFE cfe = cfes.get(0);
JSONObject error = null;
try {
if (cfe.getEstado() == null)
factory.getServiceMicroController(empresa).reenviar(cfe.getSobreEmitido());
} catch (APIException e) {
logger.error("APIException:", e);
error = e.getJSONObject();
}
JSONObject result = procesar_resultado(empresa, cfe, error);
return json(result.toString());
}
public Promise<Result> anularDocumento(String rut, int nro, String serie, int idTipoDoc) throws APIException {
Empresa empresa = Empresa.findByRUT(rut, true);
EfacturaMicroControllersFactory factory = (new EfacturaMicroControllersFactoryBuilder())
.getMicroControllersFactory();
TipoDoc tipo = TipoDoc.fromInt(idTipoDoc);
List<CFE> cfes = CFE.findById(empresa, tipo, serie, nro, null, DireccionDocumento.EMITIDO, true);
if (cfes.size()>1)
throw APIException.raise(APIErrors.CFE_NO_ENCONTRADO).withParams("RUT+NRO+SERIE+TIPODOC",rut+"-"+nro+"-"+serie+"-"+idTipoDoc).setDetailMessage("No identifica a un unico cfe");
CFE cfe = cfes.get(0);
factory.getServiceMicroController(empresa).anularDocumento(cfe);
return json(OK);
}
public Promise<Result> resultadoDocumentosFecha(String rut, String fecha) throws APIException {
Empresa empresa = Empresa.findByRUT(rut, true);
EfacturaMicroControllersFactory factory = (new EfacturaMicroControllersFactoryBuilder())
.getMicroControllersFactory();
Date date = DateHandler.fromStringToDate(fecha, new SimpleDateFormat("yyyyMMdd"));
factory.getServiceMicroController(empresa).consultarResultados(date);
return json(OK);
}
public Promise<Result> resultadoDocumento(String rut, int nro, String serie, int idTipoDoc) throws APIException {
Empresa empresa = Empresa.findByRUT(rut, true);
EfacturaMicroControllersFactory factory = (new EfacturaMicroControllersFactoryBuilder())
.getMicroControllersFactory();
TipoDoc tipo = TipoDoc.fromInt(idTipoDoc);
if (tipo == null)
throw APIException.raise(APIErrors.BAD_PARAMETER_VALUE).withParams("TipoDoc", idTipoDoc);
List<CFE> cfes = CFE.findById(empresa, tipo, serie, nro, null, DireccionDocumento.EMITIDO, true);
if (cfes.size()>1)
throw APIException.raise(APIErrors.CFE_NO_ENCONTRADO).withParams("RUT+NRO+SERIE+TIPODOC",rut+"-"+nro+"-"+serie+"-"+idTipoDoc).setDetailMessage("No identifica a un unico cfe");
CFE cfe = cfes.get(0);
JSONObject error = null;
try {
if (cfe.getEstado() == null)
factory.getServiceMicroController(empresa).consultaResultado(cfe.getSobreEmitido());
} catch (APIException e) {
logger.error("APIException:", e);
error = e.getJSONObject();
}
JSONObject cfeJson = EfacturaJSONSerializerProvider.getCFESerializer().objectToJson(cfe);
if (error != null)
cfeJson = JSONUtils.merge(cfeJson, error);
else
cfeJson = JSONUtils.merge(cfeJson, new JSONObject(OK));
return json(cfeJson.toString());
}
public Promise<Result> enviarCfeEmpresa(String rut, int nro, String serie, int idTipoDoc) throws APIException {
Empresa empresa = Empresa.findByRUT(rut, true);
EfacturaMicroControllersFactory factory = (new EfacturaMicroControllersFactoryBuilder())
.getMicroControllersFactory();
TipoDoc tipo = TipoDoc.fromInt(idTipoDoc);
if (tipo == null)
throw APIException.raise(APIErrors.BAD_PARAMETER_VALUE).withParams("TipoDoc", idTipoDoc);
List<CFE> cfes = CFE.findById(empresa, tipo, serie, nro, null, DireccionDocumento.EMITIDO, true);
if (cfes.size()>1)
throw APIException.raise(APIErrors.CFE_NO_ENCONTRADO).withParams("RUT+NRO+SERIE+TIPODOC",rut+"-"+nro+"-"+serie+"-"+idTipoDoc).setDetailMessage("No identifica a un unico cfe");
CFE cfe = cfes.get(0);
JSONObject error = null;
try {
factory.getServiceMicroController(empresa).enviarCfeEmpresa(cfe);
} catch (APIException e) {
logger.error("APIException:", e);
error = e.getJSONObject();
}
if (error == null)
error = new JSONObject(OK);
return json(error.toString());
}
public Promise<Result> procesarEmailEntrantes(String rut) throws APIException {
Empresa empresaReceptora = Empresa.findByRUT(rut, true);
EfacturaMicroControllersFactory factory = (new EfacturaMicroControllersFactoryBuilder())
.getMicroControllersFactory();
factory.getServiceMicroController(empresaReceptora).getDocumentosEntrantes();
return json(OK);
}
public Promise<Result> getDocumentos(String rut) throws APIException {
Empresa empresaReceptora = Empresa.findByRUT(rut, true);
Date fromDate = request().getQueryString("fromDate") != null ? (new Date(Long.parseLong(request().getQueryString("fromDate")) * 1000)) : null;
Date toDate = request().getQueryString("toDate") != null ? (new Date(Long.parseLong(request().getQueryString("toDate")) * 1000)) : null;
int page = request().getQueryString("page") != null ? Integer.parseInt(request().getQueryString("page")) : 1;
int pageSize = request().getQueryString("pageSize") != null ? Math.min(Integer.parseInt(request().getQueryString("pageSize")), 50) : 50;
if (page <=0)
page = 1;
if (pageSize <=0)
pageSize = 10;
DireccionDocumento direccion = request().getQueryString("direccion") != null ? DireccionDocumento.valueOf(request().getQueryString("direccion")) : DireccionDocumento.AMBOS;
Tuple<List<CFE>,Long> cfes = CFE.find(empresaReceptora, fromDate, toDate, page, pageSize, direccion);
JSONArray cfeArray = EfacturaJSONSerializerProvider.getCFESerializer().objectToJson(cfes.item1);
return json(JSONUtils.createObjectList(cfeArray, cfes.item2, page, pageSize).toString());
}
public Promise<Result> pdfDocumento(String rut, int nro, String serie, int idTipoDoc, boolean print)
throws APIException {
Empresa empresa = Empresa.findByRUT(rut, true);
TipoDoc tipo = TipoDoc.fromInt(idTipoDoc);
List<CFE> cfes = CFE.findById(empresa, tipo, serie, nro, null, DireccionDocumento.EMITIDO, true);
if (cfes.size()>1)
throw APIException.raise(APIErrors.CFE_NO_ENCONTRADO).withParams("RUT+NRO+SERIE+TIPODOC",rut+"-"+nro+"-"+serie+"-"+idTipoDoc).setDetailMessage("No identifica a un unico cfe");
CFE cfe = cfes.get(0);
try {
File pdf = generarPDF(empresa, cfe);
if (print)
Print.print(null, pdf);
return Promise.<Result>pure(ok(pdf));
} catch (IOException | PrinterException e) {
throw APIException.raise(e);
}
}
/**
* @param nro
* @param serie
* @param idTipoDoc
* @param empresa
* @param cfe
* @return
* @throws IOException
* @throws FileNotFoundException
*/
private File generarPDF(Empresa empresa, CFE cfe) throws IOException, FileNotFoundException {
logger.info("Generando PDF tipoDoc:{} - serie:{} - nro:{}", cfe.getTipo().value, cfe.getSerie(), cfe.getNro());
GenerateInvoice generateInvoice = new GenerateInvoice(cfe, empresa);
String filename = cfe.getTipo().value + "-" + cfe.getSerie() + "-" + cfe.getNro() + ".pdf";
Calendar cal = Calendar.getInstance();
cal.setTime(cfe.getFechaEmision());
int year = cal.get(Calendar.YEAR);
String path = Play.application().configuration().getString("documentos.pdf.path", "/mnt/efacturas") + File.separator + empresa.getRut() + File.separator + year;
// Check Directory
File directory = new File(path);
if (! directory.exists()){
directory.mkdirs();
// If you require it to make the entire directory path including parents,
// use directory.mkdirs(); here instead.
}
// Write file
File pdf = new File(path + File.separator + filename);
ByteArrayOutputStream byteArrayOutputStream = generateInvoice.createPDF();
try (OutputStream outputStream = new FileOutputStream(pdf)) {
byteArrayOutputStream.writeTo(outputStream);
}
return pdf;
}
}
|
app/com/bluedot/efactura/controllers/DocumentController.java
|
package com.bluedot.efactura.controllers;
import java.awt.print.PrinterException;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.bluedot.commons.controllers.AbstractController;
import com.bluedot.commons.error.APIException;
import com.bluedot.commons.error.APIException.APIErrors;
import com.bluedot.commons.error.ErrorMessage;
import com.bluedot.commons.security.Secured;
import com.bluedot.commons.utils.DateHandler;
import com.bluedot.commons.utils.JSONUtils;
import com.bluedot.commons.utils.Print;
import com.bluedot.commons.utils.Tuple;
import com.bluedot.efactura.GenerateInvoice;
import com.bluedot.efactura.MODO_SISTEMA;
import com.bluedot.efactura.microControllers.factory.EfacturaMicroControllersFactory;
import com.bluedot.efactura.microControllers.factory.EfacturaMicroControllersFactoryBuilder;
import com.bluedot.efactura.model.CFE;
import com.bluedot.efactura.model.DireccionDocumento;
import com.bluedot.efactura.model.Empresa;
import com.bluedot.efactura.model.Sobre;
import com.bluedot.efactura.model.SobreEmitido;
import com.bluedot.efactura.model.TipoDoc;
import com.bluedot.efactura.pollers.PollerManager;
import com.bluedot.efactura.serializers.EfacturaJSONSerializerProvider;
import com.fasterxml.jackson.databind.JsonNode;
import com.google.inject.Inject;
import com.play4jpa.jpa.db.Tx;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import play.Play;
import play.libs.F.Promise;
import play.mvc.BodyParser;
import play.mvc.Result;
import play.mvc.Security;
@ErrorMessage
@Tx
@Security.Authenticated(Secured.class)
@Api(value = "Operaciones de Documentos")
public class DocumentController extends AbstractController {
private static boolean initialized = false;
final static Logger logger = LoggerFactory.getLogger(DocumentController.class);
private PollerManager pollerManager;
@Inject
public DocumentController(PollerManager pollerManager){
super();
this.pollerManager = pollerManager;
if (!initialized) {
init();
}
}
private synchronized void init() {
initialized = true;
pollerManager.queue();
}
public Promise<Result> cambiarModo(String modo) throws APIException {
MODO_SISTEMA modoEnum = MODO_SISTEMA.valueOf(modo);
if (modoEnum == null)
throw APIException.raise(APIErrors.BAD_PARAMETER_VALUE).withParams("modo");
EfacturaMicroControllersFactory factory = (new EfacturaMicroControllersFactoryBuilder())
.getMicroControllersFactory();
factory.setModo(modoEnum);
return json(OK);
}
@ApiOperation(value = "Crear CFE",
response = CFE.class
)
@BodyParser.Of(BodyParser.Json.class)
public Promise<Result> aceptarDocumento(String rut) throws APIException {
// TODO meter mutex
Empresa empresa = Empresa.findByRUT(rut, true);
JsonNode jsonNode = request().body().asJson();
JSONObject document = new JSONObject(jsonNode.toString());
EfacturaMicroControllersFactory factory = (new EfacturaMicroControllersFactoryBuilder())
.getMicroControllersFactory();
// TODO estos controles se pueden mover a una annotation
if (!document.has("Encabezado"))
throw APIException.raise(APIErrors.MISSING_PARAMETER).withParams("Encabezado");
if (!document.getJSONObject("Encabezado").has("IdDoc"))
throw APIException.raise(APIErrors.MISSING_PARAMETER).withParams("IdDoc");
if (!document.getJSONObject("Encabezado").getJSONObject("IdDoc").has("TipoCFE"))
throw APIException.raise(APIErrors.MISSING_PARAMETER).withParams("TipoCFE");
if (!document.getJSONObject("Encabezado").getJSONObject("IdDoc").has("id"))
throw APIException.raise(APIErrors.MISSING_PARAMETER).withParams("id");
TipoDoc tipo = TipoDoc
.fromInt(document.getJSONObject("Encabezado").getJSONObject("IdDoc").getInt("TipoCFE"));
if (tipo == null)
throw APIException.raise(APIErrors.BAD_PARAMETER_VALUE).withParams("TipoCFE");
String id = document.getJSONObject("Encabezado").getJSONObject("IdDoc").getString("id");
CFE cfe = CFE.findByGeneradorId(empresa, id, DireccionDocumento.EMITIDO);
if (cfe != null)
throw APIException.raise(APIErrors.EXISTE_CFE).withParams("generadorId", id);
switch (tipo) {
case eFactura:
case eTicket:
case eResguardo:
cfe = factory.getCFEMicroController(empresa).create(tipo, document, true);
break;
case Nota_de_Credito_de_eFactura:
case Nota_de_Credito_de_eTicket:
case Nota_de_Debito_de_eFactura:
case Nota_de_Debito_de_eTicket:
if (!document.has("Referencia"))
throw APIException.raise(APIErrors.MISSING_PARAMETER).withParams("Referencia");
cfe = factory.getCFEMicroController(empresa).create(tipo, document, true);
break;
case eFactura_Venta_por_Cuenta_Ajena:
case eTicket_Venta_por_Cuenta_Ajena:
case Nota_de_Credito_de_eFactura_Venta_por_Cuenta_Ajena:
case Nota_de_Credito_de_eTicket_Venta_por_Cuenta_Ajena:
case Nota_de_Debito_de_eTicket_Venta_por_Cuenta_Ajena:
case Nota_de_Debito_de_eFactura_Venta_por_Cuenta_Ajena:
if (!document.has("CompFiscal"))
throw APIException.raise(APIErrors.MISSING_PARAMETER).withParams("CompFiscal");
cfe = factory.getCFEMicroController(empresa).create(tipo, document, true);
break;
case eFactura_Contingencia:
case eFactura_Venta_por_Cuenta_Ajena_Contingencia:
case eFactura_Exportacion:
case eFactura_Exportacion_Contingencia:
case eRemito:
case eRemito_Contingencia:
case eRemito_de_Exportacion:
case eRemito_de_Exportacion_Contingencia:
case eResguardo_Contingencia:
case Nota_de_Credito_de_eFactura_Contingencia:
case Nota_de_Credito_de_eFactura_Exportacion:
case Nota_de_Credito_de_eFactura_Exportacion_Contingencia:
case Nota_de_Credito_de_eFactura_Venta_por_Cuenta_Ajena_Contingencia:
case Nota_de_Credito_de_eTicket_Contingencia:
case Nota_de_Credito_de_eTicket_Venta_por_Cuenta_Ajena_Contingencia:
case Nota_de_Debito_de_eFactura_Contingencia:
case Nota_de_Debito_de_eFactura_Exportacion:
case Nota_de_Debito_de_eFactura_Exportacion_Contingencia:
case Nota_de_Debito_de_eFactura_Venta_por_Cuenta_Ajena_Contingencia:
case Nota_de_Debito_de_eTicket_Contingencia:
case Nota_de_Debito_de_eTicket_Venta_por_Cuenta_Ajena_Contingencia:
case eTicket_Contingencia:
case eTicket_Venta_por_Cuenta_Ajena_Contingencia:
throw APIException.raise(APIErrors.NOT_SUPPORTED).setDetailMessage(tipo.toString());
}
if (cfe != null) {
if (document.has("Adenda"))
cfe.setAdenda(document.getJSONArray("Adenda").toString());
JSONObject error = null;
if (cfe.getFechaEmision()==null)
cfe.setFechaEmision(new Date());
try {
factory.getServiceMicroController(empresa).enviar(cfe);
} catch (APIException e) {
logger.error("APIException:", e);
error = e.getJSONObject();
}
JSONObject result = procesar_resultado(empresa, cfe, error);
return json(result.toString());
} else
throw APIException.raise(APIErrors.NO_CFE_CREATED);
}
/**
* @param empresa
* @param cfe
* @param error
* @return
* @throws APIException
*/
private JSONObject procesar_resultado(Empresa empresa, CFE cfe, JSONObject error) throws APIException {
JSONObject result;
if (error != null) {
JSONObject cfeJson = new JSONObject();
cfeJson.put("nro", cfe.getNro());
cfeJson.put("serie", cfe.getSerie());
result = JSONUtils.merge(cfeJson, error);
}
else {
JSONObject cfeJson;
try {
cfeJson = EfacturaJSONSerializerProvider.getCFESerializer().objectToJson(cfe);
} catch (JSONException e) {
throw APIException.raise(APIErrors.BAD_JSON);
}
result = JSONUtils.merge(cfeJson, new JSONObject(OK));
}
try {
generarPDF(empresa, cfe);
} catch (Throwable e) {
}
return result;
}
@BodyParser.Of(BodyParser.Json.class)
public Promise<Result> reenviarDocumento(String rut, int nro, String serie, int idTipoDoc) throws APIException {
// TODO meter mutex
Empresa empresa = Empresa.findByRUT(rut, true);
EfacturaMicroControllersFactory factory = (new EfacturaMicroControllersFactoryBuilder())
.getMicroControllersFactory();
TipoDoc tipo = TipoDoc.fromInt(idTipoDoc);
List<CFE> cfes = CFE.findById(empresa, tipo, serie, nro, null, DireccionDocumento.EMITIDO, true);
if (cfes.size()>1)
throw APIException.raise(APIErrors.CFE_NO_ENCONTRADO).withParams("RUT+NRO+SERIE+TIPODOC",rut+"-"+nro+"-"+serie+"-"+idTipoDoc).setDetailMessage("No identifica a un unico cfe");
CFE cfe = cfes.get(0);
JSONObject error = null;
try {
if (cfe.getEstado() == null)
factory.getServiceMicroController(empresa).reenviar(cfe.getSobreEmitido());
} catch (APIException e) {
logger.error("APIException:", e);
error = e.getJSONObject();
}
JSONObject result = procesar_resultado(empresa, cfe, error);
return json(result.toString());
}
public Promise<Result> anularDocumento(String rut, int nro, String serie, int idTipoDoc) throws APIException {
Empresa empresa = Empresa.findByRUT(rut, true);
EfacturaMicroControllersFactory factory = (new EfacturaMicroControllersFactoryBuilder())
.getMicroControllersFactory();
TipoDoc tipo = TipoDoc.fromInt(idTipoDoc);
List<CFE> cfes = CFE.findById(empresa, tipo, serie, nro, null, DireccionDocumento.EMITIDO, true);
if (cfes.size()>1)
throw APIException.raise(APIErrors.CFE_NO_ENCONTRADO).withParams("RUT+NRO+SERIE+TIPODOC",rut+"-"+nro+"-"+serie+"-"+idTipoDoc).setDetailMessage("No identifica a un unico cfe");
CFE cfe = cfes.get(0);
factory.getServiceMicroController(empresa).anularDocumento(cfe);
return json(OK);
}
public Promise<Result> resultadoDocumentosFecha(String rut, String fecha) throws APIException {
Empresa empresa = Empresa.findByRUT(rut, true);
EfacturaMicroControllersFactory factory = (new EfacturaMicroControllersFactoryBuilder())
.getMicroControllersFactory();
Date date = DateHandler.fromStringToDate(fecha, new SimpleDateFormat("yyyyMMdd"));
factory.getServiceMicroController(empresa).consultarResultados(date);
return json(OK);
}
public Promise<Result> resultadoDocumento(String rut, int nro, String serie, int idTipoDoc) throws APIException {
Empresa empresa = Empresa.findByRUT(rut, true);
EfacturaMicroControllersFactory factory = (new EfacturaMicroControllersFactoryBuilder())
.getMicroControllersFactory();
TipoDoc tipo = TipoDoc.fromInt(idTipoDoc);
if (tipo == null)
throw APIException.raise(APIErrors.BAD_PARAMETER_VALUE).withParams("TipoDoc", idTipoDoc);
List<CFE> cfes = CFE.findById(empresa, tipo, serie, nro, null, DireccionDocumento.EMITIDO, true);
if (cfes.size()>1)
throw APIException.raise(APIErrors.CFE_NO_ENCONTRADO).withParams("RUT+NRO+SERIE+TIPODOC",rut+"-"+nro+"-"+serie+"-"+idTipoDoc).setDetailMessage("No identifica a un unico cfe");
CFE cfe = cfes.get(0);
JSONObject error = null;
try {
if (cfe.getEstado() == null)
factory.getServiceMicroController(empresa).consultaResultado(cfe.getSobreEmitido());
} catch (APIException e) {
logger.error("APIException:", e);
error = e.getJSONObject();
}
JSONObject cfeJson = EfacturaJSONSerializerProvider.getCFESerializer().objectToJson(cfe);
if (error != null)
cfeJson = JSONUtils.merge(cfeJson, error);
else
cfeJson = JSONUtils.merge(cfeJson, new JSONObject(OK));
return json(cfeJson.toString());
}
public Promise<Result> enviarCfeEmpresa(String rut, int nro, String serie, int idTipoDoc) throws APIException {
Empresa empresa = Empresa.findByRUT(rut, true);
EfacturaMicroControllersFactory factory = (new EfacturaMicroControllersFactoryBuilder())
.getMicroControllersFactory();
TipoDoc tipo = TipoDoc.fromInt(idTipoDoc);
if (tipo == null)
throw APIException.raise(APIErrors.BAD_PARAMETER_VALUE).withParams("TipoDoc", idTipoDoc);
List<CFE> cfes = CFE.findById(empresa, tipo, serie, nro, null, DireccionDocumento.EMITIDO, true);
if (cfes.size()>1)
throw APIException.raise(APIErrors.CFE_NO_ENCONTRADO).withParams("RUT+NRO+SERIE+TIPODOC",rut+"-"+nro+"-"+serie+"-"+idTipoDoc).setDetailMessage("No identifica a un unico cfe");
CFE cfe = cfes.get(0);
JSONObject error = null;
try {
factory.getServiceMicroController(empresa).enviarCfeEmpresa(cfe);
} catch (APIException e) {
logger.error("APIException:", e);
error = e.getJSONObject();
}
if (error == null)
error = new JSONObject(OK);
return json(error.toString());
}
public Promise<Result> procesarEmailEntrantes(String rut) throws APIException {
Empresa empresaReceptora = Empresa.findByRUT(rut, true);
EfacturaMicroControllersFactory factory = (new EfacturaMicroControllersFactoryBuilder())
.getMicroControllersFactory();
factory.getServiceMicroController(empresaReceptora).getDocumentosEntrantes();
return json(OK);
}
public Promise<Result> getDocumentos(String rut) throws APIException {
Empresa empresaReceptora = Empresa.findByRUT(rut, true);
Date fromDate = request().getQueryString("fromDate") != null ? (new Date(Long.parseLong(request().getQueryString("fromDate")) * 1000)) : null;
Date toDate = request().getQueryString("toDate") != null ? (new Date(Long.parseLong(request().getQueryString("toDate")) * 1000)) : null;
int page = request().getQueryString("page") != null ? Integer.parseInt(request().getQueryString("page")) : 1;
int pageSize = request().getQueryString("pageSize") != null ? Math.min(Integer.parseInt(request().getQueryString("pageSize")), 50) : 50;
if (page <=0)
page = 1;
if (pageSize <=0)
pageSize = 10;
DireccionDocumento direccion = request().getQueryString("direccion") != null ? DireccionDocumento.valueOf(request().getQueryString("direccion")) : DireccionDocumento.AMBOS;
Tuple<List<CFE>,Long> cfes = CFE.find(empresaReceptora, fromDate, toDate, page, pageSize, direccion);
JSONArray cfeArray = EfacturaJSONSerializerProvider.getCFESerializer().objectToJson(cfes.item1);
return json(JSONUtils.createObjectList(cfeArray, cfes.item2, page, pageSize).toString());
}
public Promise<Result> pdfDocumento(String rut, int nro, String serie, int idTipoDoc, boolean print)
throws APIException {
Empresa empresa = Empresa.findByRUT(rut, true);
TipoDoc tipo = TipoDoc.fromInt(idTipoDoc);
List<CFE> cfes = CFE.findById(empresa, tipo, serie, nro, null, DireccionDocumento.EMITIDO, true);
if (cfes.size()>1)
throw APIException.raise(APIErrors.CFE_NO_ENCONTRADO).withParams("RUT+NRO+SERIE+TIPODOC",rut+"-"+nro+"-"+serie+"-"+idTipoDoc).setDetailMessage("No identifica a un unico cfe");
CFE cfe = cfes.get(0);
try {
File pdf = generarPDF(empresa, cfe);
if (print)
Print.print(null, pdf);
return Promise.<Result>pure(ok(pdf));
} catch (IOException | PrinterException e) {
throw APIException.raise(e);
}
}
/**
* @param nro
* @param serie
* @param idTipoDoc
* @param empresa
* @param cfe
* @return
* @throws IOException
* @throws FileNotFoundException
*/
private File generarPDF(Empresa empresa, CFE cfe) throws IOException, FileNotFoundException {
logger.info("Generando PDF tipoDoc:{} - serie:{} - nro:{}", cfe.getTipo().value, cfe.getSerie(), cfe.getNro());
GenerateInvoice generateInvoice = new GenerateInvoice(cfe, empresa);
String filename = cfe.getTipo().value + "-" + cfe.getSerie() + "-" + cfe.getNro() + ".pdf";
String path = Play.application().configuration().getString("documentos.pdf.path", "/mnt/efacturas");
File pdf = new File(path + File.separator + filename);
ByteArrayOutputStream byteArrayOutputStream = generateInvoice.createPDF();
try (OutputStream outputStream = new FileOutputStream(pdf)) {
byteArrayOutputStream.writeTo(outputStream);
}
return pdf;
}
}
|
Uso de rut y mes en el path de los pdf
|
app/com/bluedot/efactura/controllers/DocumentController.java
|
Uso de rut y mes en el path de los pdf
|
<ide><path>pp/com/bluedot/efactura/controllers/DocumentController.java
<ide> import java.io.IOException;
<ide> import java.io.OutputStream;
<ide> import java.text.SimpleDateFormat;
<add>import java.util.Calendar;
<ide> import java.util.Date;
<ide> import java.util.List;
<add>import java.util.TimeZone;
<ide>
<ide> import org.json.JSONArray;
<ide> import org.json.JSONException;
<ide>
<ide> String filename = cfe.getTipo().value + "-" + cfe.getSerie() + "-" + cfe.getNro() + ".pdf";
<ide>
<del> String path = Play.application().configuration().getString("documentos.pdf.path", "/mnt/efacturas");
<del>
<add> Calendar cal = Calendar.getInstance();
<add> cal.setTime(cfe.getFechaEmision());
<add> int year = cal.get(Calendar.YEAR);
<add>
<add> String path = Play.application().configuration().getString("documentos.pdf.path", "/mnt/efacturas") + File.separator + empresa.getRut() + File.separator + year;
<add>
<add> // Check Directory
<add> File directory = new File(path);
<add> if (! directory.exists()){
<add> directory.mkdirs();
<add> // If you require it to make the entire directory path including parents,
<add> // use directory.mkdirs(); here instead.
<add> }
<add>
<add> // Write file
<ide> File pdf = new File(path + File.separator + filename);
<del>
<ide> ByteArrayOutputStream byteArrayOutputStream = generateInvoice.createPDF();
<del>
<ide> try (OutputStream outputStream = new FileOutputStream(pdf)) {
<ide> byteArrayOutputStream.writeTo(outputStream);
<ide> }
<ide> return pdf;
<ide> }
<del>
<ide> }
|
|
JavaScript
|
mit
|
1e6858b873281c64b6b13eedf5d84315c5dfaf77
| 0 |
nozzle/react-static,nozzle/react-static
|
import React from 'react'
import jsesc from 'jsesc'
const REGEX_FOR_SCRIPT = /<(\/)?(script)/gi
const generateRouteInformation = embeddedRouteInfo => ({
__html: `
window.__routeInfo = ${JSON.stringify(embeddedRouteInfo).replace(
REGEX_FOR_SCRIPT,
'<"+"$1$2'
)};`,
})
// Not only do we pass react-helmet attributes and the app.js here, but
// we also need to hard code site props and route props into the page to
// prevent flashing when react mounts onto the HTML.
export const makeBodyWithMeta = ({
head,
route,
// This embeddedRouteInfo will be inlined into the HTML for this route.
// It should only include the full props, not the partials.
embeddedRouteInfo,
clientScripts = [],
ClientCssHash,
config,
}) => ({ children, ...rest }) => (
<body {...head.bodyProps} {...rest}>
{children}
<ClientCssHash />
{!route.redirect && (
<script
type="text/javascript"
dangerouslySetInnerHTML={generateRouteInformation(embeddedRouteInfo)}
/>
)}
{!route.redirect &&
clientScripts.map(script => (
<script key={script} defer type="text/javascript" src={`${config.publicPath}${script}`} />
))}
</body>
)
|
src/static/components/BodyWithMeta.js
|
import React from 'react'
import jsesc from 'jsesc'
const REGEX_FOR_SCRIPT = /<(\/)?(script)/gi
const generateRouteInformation = embeddedRouteInfo => ({
__html: `
window.__routeInfo = ${jsesc(JSON.stringify(embeddedRouteInfo), {
isScriptContext: true,
}).replace(REGEX_FOR_SCRIPT, '<"+"$1$2')};`,
})
// Not only do we pass react-helmet attributes and the app.js here, but
// we also need to hard code site props and route props into the page to
// prevent flashing when react mounts onto the HTML.
export const makeBodyWithMeta = ({
head,
route,
// This embeddedRouteInfo will be inlined into the HTML for this route.
// It should only include the full props, not the partials.
embeddedRouteInfo,
clientScripts = [],
ClientCssHash,
config,
}) => ({ children, ...rest }) => (
<body {...head.bodyProps} {...rest}>
{children}
<ClientCssHash />
{!route.redirect && (
<script
type="text/javascript"
dangerouslySetInnerHTML={generateRouteInformation(embeddedRouteInfo)}
/>
)}
{!route.redirect &&
clientScripts.map(script => (
<script key={script} defer type="text/javascript" src={`${config.publicPath}${script}`} />
))}
</body>
)
|
Remove jsesc for now.
|
src/static/components/BodyWithMeta.js
|
Remove jsesc for now.
|
<ide><path>rc/static/components/BodyWithMeta.js
<ide>
<ide> const generateRouteInformation = embeddedRouteInfo => ({
<ide> __html: `
<del> window.__routeInfo = ${jsesc(JSON.stringify(embeddedRouteInfo), {
<del> isScriptContext: true,
<del> }).replace(REGEX_FOR_SCRIPT, '<"+"$1$2')};`,
<add> window.__routeInfo = ${JSON.stringify(embeddedRouteInfo).replace(
<add> REGEX_FOR_SCRIPT,
<add> '<"+"$1$2'
<add> )};`,
<ide> })
<ide>
<ide> // Not only do we pass react-helmet attributes and the app.js here, but
|
|
Java
|
mit
|
04207d1d2f534eec75f018f00ea54adf92537141
| 0 |
theevanelement/Apollo-Launcher
|
package fr.neamar.kiss;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.ListActivity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.support.annotation.NonNull;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.util.TypedValue;
import android.view.ContextMenu;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewAnimationUtils;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.RotateAnimation;
import android.view.animation.TranslateAnimation;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;
import java.util.ArrayList;
import fr.neamar.kiss.adapter.RecordAdapter;
import fr.neamar.kiss.pojo.Pojo;
import fr.neamar.kiss.result.Result;
import fr.neamar.kiss.searcher.ApplicationsSearcher;
import fr.neamar.kiss.searcher.HistorySearcher;
import fr.neamar.kiss.searcher.NullSearcher;
import fr.neamar.kiss.searcher.QueryInterface;
import fr.neamar.kiss.searcher.QuerySearcher;
import fr.neamar.kiss.searcher.Searcher;
public class MainActivity extends ListActivity implements QueryInterface {
public static final String START_LOAD = "fr.neamar.summon.START_LOAD";
public static final String LOAD_OVER = "fr.neamar.summon.LOAD_OVER";
public static final String FULL_LOAD_OVER = "fr.neamar.summon.FULL_LOAD_OVER";
/**
* IDS for the favorites buttons
*/
private final int[] favsIds = new int[]{R.id.favorite0, R.id.favorite1, R.id.favorite2, R.id.favorite3, R.id.favorite4};
private final int[] favsCircleIds = new int[]{R.id.favcircle0, R.id.favcircle1, R.id.favcircle2, R.id.favcircle3, R.id.favcircle4};
private final int[] favsLayoutIds = new int[]{R.id.fav_layout_0, R.id.fav_layout_1, R.id.fav_layout_2, R.id.fav_layout_3, R.id.fav_layout_4};
/**
* Number of favorites to retrieve.
* We need to pad this number to account for removed items still in history
*/
private final int tryToRetrieve = favsIds.length + 2;
/**
* InputType with spellecheck and swiping
*/
private final int spellcheckEnabledType = InputType.TYPE_CLASS_TEXT |
InputType.TYPE_TEXT_FLAG_AUTO_CORRECT;
/**
* Adapter to display records
*/
public RecordAdapter adapter;
/**
* Store user preferences
*/
private SharedPreferences prefs;
private BroadcastReceiver mReceiver;
/**
* View for the Search text
*/
private EditText searchEditText;
private final Runnable displayKeyboardRunnable = new Runnable() {
@Override
public void run() {
showKeyboard();
}
};
/**
* Menu button
*/
private View menuButton;
/**
* Kiss bar
*/
private View kissBar;
/**
* Task launched on text change
*/
private Searcher searcher;
private ListView resultsListView;
private LinearLayout main_empty_layout;
private boolean isEmptyMenuVisible = false;
/**
* Called when the activity is first created.
*/
@SuppressLint("NewApi")
@Override
public void onCreate(Bundle savedInstanceState) {
// Initialize UI
prefs = PreferenceManager.getDefaultSharedPreferences(this);
String theme = prefs.getString("theme", "light");
if (theme.equals("dark")) {
setTheme(R.style.AppThemeDark);
} else if (theme.equals("transparent")) {
setTheme(R.style.AppThemeTransparent);
} else if (theme.equals("semi-transparent")) {
setTheme(R.style.AppThemeSemiTransparent);
} else if (theme.equals("semi-transparent-dark")) {
setTheme(R.style.AppThemeSemiTransparentDark);
}
super.onCreate(savedInstanceState);
IntentFilter intentFilter = new IntentFilter(START_LOAD);
IntentFilter intentFilterBis = new IntentFilter(LOAD_OVER);
IntentFilter intentFilterTer = new IntentFilter(FULL_LOAD_OVER);
mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equalsIgnoreCase(LOAD_OVER)) {
updateRecords(searchEditText.getText().toString());
} else if (intent.getAction().equalsIgnoreCase(FULL_LOAD_OVER)) {
displayLoader(false);
} else if (intent.getAction().equalsIgnoreCase(START_LOAD)) {
displayLoader(true);
}
}
};
this.registerReceiver(mReceiver, intentFilter);
this.registerReceiver(mReceiver, intentFilterBis);
this.registerReceiver(mReceiver, intentFilterTer);
KissApplication.initDataHandler(this);
// Initialize preferences
PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
prefs = PreferenceManager.getDefaultSharedPreferences(this);
// Lock launcher into portrait mode
// Do it here (before initializing the view) to make the transition as smooth as possible
if (prefs.getBoolean("force-portrait", true)) {
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_USER_PORTRAIT);
} else {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
}
setContentView(R.layout.main);
// Create adapter for records
adapter = new RecordAdapter(this, this, R.layout.item_app, new ArrayList<Result>());
setListAdapter(adapter);
searchEditText = (EditText) findViewById(R.id.searchEditText);
// Listen to changes
searchEditText.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
// Auto left-trim text.
if (s.length() > 0 && s.charAt(0) == ' ')
s.delete(0, 1);
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
updateRecords(s.toString());
displayClearOnInput();
}
});
// On validate, launch first record
searchEditText.setOnEditorActionListener(new OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
RecordAdapter adapter = ((RecordAdapter) getListView().getAdapter());
adapter.onClick(adapter.getCount() - 1, null);
return true;
}
});
searchEditText.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (prefs.getBoolean("history-hide", false) && prefs.getBoolean("history-onclick", false)) {
//show history only if no search text is added
if (((EditText) v).getText().toString().isEmpty()) {
searcher = new HistorySearcher(MainActivity.this);
searcher.execute();
}
}
}
});
kissBar = findViewById(R.id.main_kissbar);
menuButton = findViewById(R.id.menuButton);
registerForContextMenu(menuButton);
resultsListView = getListView();
// resultsListView = (ListView) findViewById(R.id.list);
main_empty_layout = (LinearLayout) findViewById(R.id.main_empty);
getListView().setLongClickable(true);
getListView().setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View v, int pos, long id) {
((RecordAdapter) parent.getAdapter()).onLongClick(pos, v);
return true;
}
});
// Enable swiping
if (prefs.getBoolean("enable-spellcheck", false)) {
searchEditText.setInputType(spellcheckEnabledType);
}
// Hide the "X" after the text field, instead displaying the menu button
displayClearOnInput();
// Apply effects depending on current Android version
applyDesignTweaks();
}
/**
* Apply some tweaks to the design, depending on the current SDK version
*/
private void applyDesignTweaks() {
final int[] tweakableIds = new int[]{
R.id.menuButton,
// Barely visible on the clearbutton, since it disappears instant. Can be seen on long click though
R.id.clearButton,
R.id.launcherButton,
R.id.favorite0,
R.id.favorite1,
R.id.favorite2,
R.id.favorite3,
R.id.favorite4,
};
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
TypedValue outValue = new TypedValue();
getTheme().resolveAttribute(android.R.attr.selectableItemBackgroundBorderless, outValue, true);
for (int id : tweakableIds) {
findViewById(id).setBackgroundResource(outValue.resourceId);
}
} else if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
TypedValue outValue = new TypedValue();
getTheme().resolveAttribute(android.R.attr.selectableItemBackground, outValue, true);
for (int id : tweakableIds) {
findViewById(id).setBackgroundResource(outValue.resourceId);
}
}
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
adapter.onClick(position, v);
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_settings, menu);
}
@Override
public boolean onContextItemSelected(MenuItem item) {
return onOptionsItemSelected(item);
}
/**
* Empty text field on resume and show keyboard
*/
protected void onResume() {
if (prefs.getBoolean("require-layout-update", false)) {
// Restart current activity to refresh view, since some preferences
// may require using a new UI
prefs.edit().putBoolean("require-layout-update", false).commit();
Intent i = new Intent(this, getClass());
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_NO_ANIMATION);
finish();
overridePendingTransition(0, 0);
startActivity(i);
overridePendingTransition(0, 0);
}
if (kissBar.getVisibility() != View.VISIBLE) {
updateRecords(searchEditText.getText().toString());
displayClearOnInput();
} else {
displayKissBar(false);
}
// Activity manifest specifies stateAlwaysHidden as windowSoftInputMode
// so the keyboard will be hidden by default
// we may want to display it if the setting is set
if (prefs.getBoolean("display-keyboard", false)) {
// Display keyboard
showKeyboard();
new Handler().postDelayed(displayKeyboardRunnable, 10);
// For some weird reasons, keyboard may be hidden by the system
// So we have to run this multiple time at different time
// See https://github.com/Neamar/KISS/issues/119
new Handler().postDelayed(displayKeyboardRunnable, 100);
new Handler().postDelayed(displayKeyboardRunnable, 500);
} else {
// Not used (thanks windowSoftInputMode)
// unless coming back from KISS settings
hideKeyboard();
}
super.onResume();
}
@Override
protected void onDestroy() {
super.onDestroy();
// unregister our receiver
this.unregisterReceiver(this.mReceiver);
KissApplication.getCameraHandler().releaseCamera();
}
@Override
protected void onPause() {
super.onPause();
KissApplication.getCameraHandler().releaseCamera();
}
@Override
protected void onNewIntent(Intent intent) {
// Empty method,
// This is called when the user press Home again while already browsing MainActivity
// onResume() will be called right after, hiding the kissbar if any.
// http://developer.android.com/reference/android/app/Activity.html#onNewIntent(android.content.Intent)
}
@Override
public void onBackPressed() {
// Is the kiss menu visible?
if (menuButton.getVisibility() == View.VISIBLE) {
displayKissBar(false);
} else {
// If no kissmenu, empty the search bar
searchEditText.setText("");
}
// No call to super.onBackPressed, since this would quit the launcher.
}
@Override
public boolean onKeyDown(int keycode, @NonNull KeyEvent e) {
switch (keycode) {
case KeyEvent.KEYCODE_MENU:
// For user with a physical menu button, we still want to display *our* contextual menu
menuButton.showContextMenu();
return true;
}
return super.onKeyDown(keycode, e);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.settings:
startActivity(new Intent(android.provider.Settings.ACTION_SETTINGS));
return true;
case R.id.wallpaper:
hideKeyboard();
Intent intent = new Intent(Intent.ACTION_SET_WALLPAPER);
startActivity(Intent.createChooser(intent, getString(R.string.menu_wallpaper)));
return true;
case R.id.preferences:
startActivity(new Intent(this, SettingsActivity.class));
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_settings, menu);
return true;
}
/**
* Display menu, on short or long press.
*
* @param menuButton "kebab" menu (3 dots)
*/
public void onMenuButtonClicked(View menuButton) {
// When the kiss bar is displayed, the button can still be clicked in a few areas (due to favorite margin)
// To fix this, we discard any click event occurring when the kissbar is displayed
// if (kissBar.getVisibility() != View.VISIBLE)
menuButton.showContextMenu();
}
/**
* Clear text content when touching the cross button
*/
@SuppressWarnings("UnusedParameters")
public void onClearButtonClicked(View clearButton) {
searchEditText.setText("");
}
/**
* Display KISS menu
*/
public void onLauncherButtonClicked(View launcherButton) {
// Display or hide the kiss bar, according to current view tag (showMenu / hideMenu).
// displayKissBar(launcherButton.getTag().equals("showMenu"));
boolean display;
if (resultsListView.getVisibility() == View.VISIBLE) {
display = false;
} else {
display = true;
}
displayKissBar(display);
}
public void onShowFavoritesButtonClicked(View launcherButton) {
// Display or hide the kiss bar, according to current view tag (showMenu / hideMenu).
// displayFavoritesBar(launcherButton.getTag().equals("showMenu"));
boolean display;
if (kissBar.getVisibility() == View.VISIBLE) {
display = false;
} else {
display = true;
}
displayFavoritesBar(display);
}
public void onFavoriteButtonClicked(View favorite) {
// Favorites handling
Pojo pojo = KissApplication.getDataHandler(MainActivity.this).getFavorites(tryToRetrieve)
.get(Integer.parseInt((String) favorite.getTag()));
final Result result = Result.fromPojo(MainActivity.this, pojo);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
result.fastLaunch(MainActivity.this);
}
}, KissApplication.TOUCH_DELAY);
// Can take out if we want. This is just so that the next time you press the Home button,
// it goes to the main screen and doesn't still have the Favorites displayed. The only downside
// is that you see it go away before the app loads so it doesn't look the best, but it's just
// aesthetic
kissBar.setVisibility(View.GONE);
}
private void displayClearOnInput() {
final View clearButton = findViewById(R.id.clearButton);
if (searchEditText.getText().length() > 0) {
clearButton.setVisibility(View.VISIBLE);
menuButton.setVisibility(View.INVISIBLE);
} else {
clearButton.setVisibility(View.INVISIBLE);
menuButton.setVisibility(View.VISIBLE);
}
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR1)
private void displayLoader(Boolean display) {
final View loaderBar = findViewById(R.id.loaderBar);
final View launcherButton = findViewById(R.id.launcherButton);
int animationDuration = getResources().getInteger(
android.R.integer.config_longAnimTime);
if (!display) {
launcherButton.setVisibility(View.VISIBLE);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
// Animate transition from loader to launch button
launcherButton.setAlpha(0);
launcherButton.animate()
.alpha(1f)
.setDuration(animationDuration)
.setListener(null);
loaderBar.animate()
.alpha(0f)
.setDuration(animationDuration)
.setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
loaderBar.setVisibility(View.GONE);
loaderBar.setAlpha(1);
}
});
} else {
loaderBar.setVisibility(View.GONE);
}
} else {
launcherButton.setVisibility(View.INVISIBLE);
loaderBar.setVisibility(View.VISIBLE);
}
}
private void displayKissBar(Boolean display) {
final ImageView launcherButton = (ImageView) findViewById(R.id.launcherButton);
// get the center for the clipping circle
int cx = (launcherButton.getLeft() + launcherButton.getRight()) / 2;
int cy = (launcherButton.getTop() + launcherButton.getBottom()) / 2;
// get the final radius for the clipping circle
int finalRadius = Math.max(kissBar.getWidth(), kissBar.getHeight());
if (display) {
// Display the app list
// resultsListView.setAdapter(adapter);
kissBar.setVisibility(View.GONE);
resultsListView.setVisibility(View.VISIBLE);
if (searcher != null) {
searcher.cancel(true);
}
searcher = new ApplicationsSearcher(MainActivity.this);
searcher.execute();
// Reveal the bar
// if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
// Animator anim = ViewAnimationUtils.createCircularReveal(kissBar, cx, cy, 0, finalRadius);
// kissBar.setVisibility(View.VISIBLE);
// anim.start();
// } else {
// // No animation before Lollipop
// kissBar.setVisibility(View.VISIBLE);
// }
// Retrieve favorites. Try to retrieve more, since some favorites can't be displayed (e.g. search queries)
// retrieveFavorites();
hideKeyboard();
} else {
// Hide the bar
// if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
// Animator anim = ViewAnimationUtils.createCircularReveal(kissBar, cx, cy, finalRadius, 0);
// anim.addListener(new AnimatorListenerAdapter() {
// @Override
// public void onAnimationEnd(Animator animation) {
// kissBar.setVisibility(View.GONE);
//// resultsListView.setVisibility(View.GONE);
//// adapter.setVisibility(0);
// super.onAnimationEnd(animation);
// }
// });
// anim.start();
// } else {
// // No animation before Lollipop
// kissBar.setVisibility(View.GONE);
//// adapter.setVisibility(0);
//// resultsListView.setVisibility(View.GONE);
// }
// searcher.onPostExecute();
resultsListView.setVisibility(View.GONE);
// resultsListView.setAdapter(null);
// kissBar.setVisibility(View.VISIBLE);
// kissBar.setVisibility(View.GONE);
searchEditText.setText("");
}
}
private void displayFavoritesBar(Boolean display) {
final ImageView launcherButton = (ImageView) findViewById(R.id.launcherButton2);
ArrayList<Pojo> favoritesPojo = KissApplication.getDataHandler(MainActivity.this)
.getFavorites(tryToRetrieve);
int location[] = {0, 0};
launcherButton.getLocationInWindow(location);
int startX = location[0];
int startY = location[1];
int duration = 1000; //Normally 300. Just made this 1000 to make the rotation more apparent. Can switch back to 300 after presentation.
if (display) {
resultsListView.setVisibility(View.GONE);
searchEditText.setText("");
if (isEmptyMenuVisible) {
main_empty_layout.setVisibility(View.VISIBLE);
}
// kissBar.setVisibility(View.INVISIBLE);
if (favoritesPojo.size() > 0) {
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
for (int i = 0; i < favoritesPojo.size(); i++) {
// if (i < 4) {
FrameLayout layout = (FrameLayout) findViewById(favsLayoutIds[i]);
int endLocation[] = {0, 0};
layout.getLocationInWindow(endLocation);
int endX = endLocation[0];
int endY = endLocation[1];
int deltaX = startX - endX;
int deltaY = startY - endY;
AnimationSet animation = new AnimationSet(true);
RotateAnimation rotateAnimation = new RotateAnimation(-180, 0, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
rotateAnimation.setDuration(duration);
animation.addAnimation(rotateAnimation);
TranslateAnimation transAnimation = new TranslateAnimation(Animation.ABSOLUTE, deltaX, Animation.ABSOLUTE,
0, Animation.ABSOLUTE, deltaY, Animation.ABSOLUTE, 0);
transAnimation.setDuration(duration);
animation.addAnimation(transAnimation);
// transAnimation.setStartOffset(0);
kissBar.setVisibility(View.VISIBLE);
layout.startAnimation(animation);
}
} else {
// No animation before Lollipop
kissBar.setVisibility(View.VISIBLE);
}
}
// Retrieve favorites. Try to retrieve more, since some favorites can't be displayed (e.g. search queries)
retrieveFavorites();
hideKeyboard();
} else {
if (favoritesPojo.size() > 0) {
// Hide the bar
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
for (int i = 0; i < favoritesPojo.size(); i++) {
// if (i < 4) {
FrameLayout layout = (FrameLayout) findViewById(favsLayoutIds[i]);
int endLocation[] = {0, 0};
layout.getLocationInWindow(endLocation);
int endX = endLocation[0];
int endY = endLocation[1];
int deltaX = startX - endX;
int deltaY = startY - endY;
AnimationSet animation = new AnimationSet(true);
RotateAnimation rotateAnimation = new RotateAnimation(0, -180, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
rotateAnimation.setDuration(duration);
animation.addAnimation(rotateAnimation);
TranslateAnimation transAnimation = new TranslateAnimation(Animation.ABSOLUTE, 0, Animation.ABSOLUTE,
deltaX, Animation.ABSOLUTE, 0, Animation.ABSOLUTE, deltaY);
transAnimation.setDuration(duration);
animation.addAnimation(transAnimation);
// transAnimation.setStartOffset(0);
// kissBar.setVisibility(View.GONE);
layout.startAnimation(animation);
layout.postDelayed(new Runnable() {
@Override
public void run() {
kissBar.setVisibility(View.GONE);
}
}, duration);
}
} else {
// No animation before Lollipop
kissBar.setVisibility(View.GONE);
}
}
if (isEmptyMenuVisible) {
// TranslateAnimation emptyMenuAnimation = new TranslateAnimation(0, 0, 0, 0);
// emptyMenuAnimation.setDuration(duration);
// main_empty_layout.startAnimation(emptyMenuAnimation);
// main_empty_layout.postDelayed(new Runnable() {
// @Override
// public void run() {
// main_empty_layout.setVisibility(View.VISIBLE);
// }
// }, duration);
main_empty_layout.setVisibility(View.VISIBLE);
}
searchEditText.setText("");
}
}
public void retrieveFavorites() {
ArrayList<Pojo> favoritesPojo = KissApplication.getDataHandler(MainActivity.this)
.getFavorites(tryToRetrieve);
boolean isAtLeast1FavoriteApp = false;
if (favoritesPojo.size() == 0) {
Toast toast = Toast.makeText(MainActivity.this, getString(R.string.no_favorites), Toast.LENGTH_SHORT);
toast.show();
isAtLeast1FavoriteApp = false;
} else if (favoritesPojo.size() > 0) {
isAtLeast1FavoriteApp = true;
}
if (isAtLeast1FavoriteApp && isEmptyMenuVisible) {
main_empty_layout.setVisibility(View.INVISIBLE);
}
// Don't look for items after favIds length, we won't be able to display them
for (int i = 0; i < Math.min(favsIds.length, favoritesPojo.size()); i++) {
Pojo pojo = favoritesPojo.get(i);
ImageView image = (ImageView) findViewById(favsIds[i]);
ImageView circle = (ImageView) findViewById(favsCircleIds[i]);
Result result = Result.fromPojo(MainActivity.this, pojo);
Drawable drawable = result.getDrawable(MainActivity.this);
if (drawable != null)
image.setImageDrawable(drawable);
image.setVisibility(View.VISIBLE);
circle.setVisibility(View.VISIBLE);
image.setContentDescription(pojo.displayName);
}
// Hide empty favorites (not enough favorites yet)
for (int i = favoritesPojo.size(); i < favsIds.length; i++) {
findViewById(favsIds[i]).setVisibility(View.GONE);
findViewById(favsCircleIds[i]).setVisibility(View.GONE);
}
}
/**
* This function gets called on changes. It will ask all the providers for
* data
*
* @param query the query on which to search
*/
private void updateRecords(String query) {
if (searcher != null) {
searcher.cancel(true);
}
if (query.length() == 0) {
if (prefs.getBoolean("history-hide", false)) {
searcher = new NullSearcher(this);
//Hide default scrollview
findViewById(R.id.main_empty).setVisibility(View.INVISIBLE);
isEmptyMenuVisible = false;
} else {
searcher = new HistorySearcher(this);
//Show default scrollview
findViewById(R.id.main_empty).setVisibility(View.VISIBLE);
isEmptyMenuVisible = true;
}
} else {
searcher = new QuerySearcher(this, query);
}
searcher.execute();
}
public void resetTask() {
searcher = null;
}
/**
* Call this function when we're leaving the activity We can't use
* onPause(), since it may be called for a configuration change
*/
public void launchOccurred(int index, Result result) {
// We selected an item on the list,
// now we can cleanup the filter:
if (!searchEditText.getText().toString().equals("")) {
searchEditText.setText("");
hideKeyboard();
}
}
private void hideKeyboard() {
// Check if no view has focus:
View view = this.getCurrentFocus();
if (view != null) {
InputMethodManager inputManager = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
}
private void showKeyboard() {
searchEditText.requestFocus();
InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
mgr.showSoftInput(searchEditText, InputMethodManager.SHOW_IMPLICIT);
}
public int getFavIconsSize() {
return favsIds.length;
}
}
|
app/src/main/java/fr/neamar/kiss/MainActivity.java
|
package fr.neamar.kiss;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.ListActivity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.support.annotation.NonNull;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.util.TypedValue;
import android.view.ContextMenu;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewAnimationUtils;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;
import java.util.ArrayList;
import fr.neamar.kiss.adapter.RecordAdapter;
import fr.neamar.kiss.pojo.Pojo;
import fr.neamar.kiss.result.Result;
import fr.neamar.kiss.searcher.ApplicationsSearcher;
import fr.neamar.kiss.searcher.HistorySearcher;
import fr.neamar.kiss.searcher.NullSearcher;
import fr.neamar.kiss.searcher.QueryInterface;
import fr.neamar.kiss.searcher.QuerySearcher;
import fr.neamar.kiss.searcher.Searcher;
public class MainActivity extends ListActivity implements QueryInterface {
public static final String START_LOAD = "fr.neamar.summon.START_LOAD";
public static final String LOAD_OVER = "fr.neamar.summon.LOAD_OVER";
public static final String FULL_LOAD_OVER = "fr.neamar.summon.FULL_LOAD_OVER";
/**
* IDS for the favorites buttons
*/
private final int[] favsIds = new int[]{R.id.favorite0, R.id.favorite1, R.id.favorite2, R.id.favorite3, R.id.favorite4};
private final int[] favsCircleIds = new int[]{R.id.favcircle0, R.id.favcircle1, R.id.favcircle2, R.id.favcircle3, R.id.favcircle4};
private final int[] favsLayoutIds = new int[]{R.id.fav_layout_0, R.id.fav_layout_1, R.id.fav_layout_2, R.id.fav_layout_3, R.id.fav_layout_4};
/**
* Number of favorites to retrieve.
* We need to pad this number to account for removed items still in history
*/
private final int tryToRetrieve = favsIds.length + 2;
/**
* InputType with spellecheck and swiping
*/
private final int spellcheckEnabledType = InputType.TYPE_CLASS_TEXT |
InputType.TYPE_TEXT_FLAG_AUTO_CORRECT;
/**
* Adapter to display records
*/
public RecordAdapter adapter;
/**
* Store user preferences
*/
private SharedPreferences prefs;
private BroadcastReceiver mReceiver;
/**
* View for the Search text
*/
private EditText searchEditText;
private final Runnable displayKeyboardRunnable = new Runnable() {
@Override
public void run() {
showKeyboard();
}
};
/**
* Menu button
*/
private View menuButton;
/**
* Kiss bar
*/
private View kissBar;
/**
* Task launched on text change
*/
private Searcher searcher;
private ListView resultsListView;
private LinearLayout main_empty_layout;
private boolean isEmptyMenuVisible = false;
/**
* Called when the activity is first created.
*/
@SuppressLint("NewApi")
@Override
public void onCreate(Bundle savedInstanceState) {
// Initialize UI
prefs = PreferenceManager.getDefaultSharedPreferences(this);
String theme = prefs.getString("theme", "light");
if (theme.equals("dark")) {
setTheme(R.style.AppThemeDark);
} else if (theme.equals("transparent")) {
setTheme(R.style.AppThemeTransparent);
} else if (theme.equals("semi-transparent")) {
setTheme(R.style.AppThemeSemiTransparent);
} else if (theme.equals("semi-transparent-dark")) {
setTheme(R.style.AppThemeSemiTransparentDark);
}
super.onCreate(savedInstanceState);
IntentFilter intentFilter = new IntentFilter(START_LOAD);
IntentFilter intentFilterBis = new IntentFilter(LOAD_OVER);
IntentFilter intentFilterTer = new IntentFilter(FULL_LOAD_OVER);
mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equalsIgnoreCase(LOAD_OVER)) {
updateRecords(searchEditText.getText().toString());
} else if (intent.getAction().equalsIgnoreCase(FULL_LOAD_OVER)) {
displayLoader(false);
} else if (intent.getAction().equalsIgnoreCase(START_LOAD)) {
displayLoader(true);
}
}
};
this.registerReceiver(mReceiver, intentFilter);
this.registerReceiver(mReceiver, intentFilterBis);
this.registerReceiver(mReceiver, intentFilterTer);
KissApplication.initDataHandler(this);
// Initialize preferences
PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
prefs = PreferenceManager.getDefaultSharedPreferences(this);
// Lock launcher into portrait mode
// Do it here (before initializing the view) to make the transition as smooth as possible
if (prefs.getBoolean("force-portrait", true)) {
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_USER_PORTRAIT);
} else {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
}
setContentView(R.layout.main);
// Create adapter for records
adapter = new RecordAdapter(this, this, R.layout.item_app, new ArrayList<Result>());
setListAdapter(adapter);
searchEditText = (EditText) findViewById(R.id.searchEditText);
// Listen to changes
searchEditText.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
// Auto left-trim text.
if (s.length() > 0 && s.charAt(0) == ' ')
s.delete(0, 1);
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
updateRecords(s.toString());
displayClearOnInput();
}
});
// On validate, launch first record
searchEditText.setOnEditorActionListener(new OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
RecordAdapter adapter = ((RecordAdapter) getListView().getAdapter());
adapter.onClick(adapter.getCount() - 1, null);
return true;
}
});
searchEditText.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (prefs.getBoolean("history-hide", false) && prefs.getBoolean("history-onclick", false)) {
//show history only if no search text is added
if (((EditText) v).getText().toString().isEmpty()) {
searcher = new HistorySearcher(MainActivity.this);
searcher.execute();
}
}
}
});
kissBar = findViewById(R.id.main_kissbar);
menuButton = findViewById(R.id.menuButton);
registerForContextMenu(menuButton);
resultsListView = getListView();
// resultsListView = (ListView) findViewById(R.id.list);
main_empty_layout = (LinearLayout) findViewById(R.id.main_empty);
getListView().setLongClickable(true);
getListView().setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View v, int pos, long id) {
((RecordAdapter) parent.getAdapter()).onLongClick(pos, v);
return true;
}
});
// Enable swiping
if (prefs.getBoolean("enable-spellcheck", false)) {
searchEditText.setInputType(spellcheckEnabledType);
}
// Hide the "X" after the text field, instead displaying the menu button
displayClearOnInput();
// Apply effects depending on current Android version
applyDesignTweaks();
}
/**
* Apply some tweaks to the design, depending on the current SDK version
*/
private void applyDesignTweaks() {
final int[] tweakableIds = new int[]{
R.id.menuButton,
// Barely visible on the clearbutton, since it disappears instant. Can be seen on long click though
R.id.clearButton,
R.id.launcherButton,
R.id.favorite0,
R.id.favorite1,
R.id.favorite2,
R.id.favorite3,
R.id.favorite4,
};
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
TypedValue outValue = new TypedValue();
getTheme().resolveAttribute(android.R.attr.selectableItemBackgroundBorderless, outValue, true);
for (int id : tweakableIds) {
findViewById(id).setBackgroundResource(outValue.resourceId);
}
} else if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
TypedValue outValue = new TypedValue();
getTheme().resolveAttribute(android.R.attr.selectableItemBackground, outValue, true);
for (int id : tweakableIds) {
findViewById(id).setBackgroundResource(outValue.resourceId);
}
}
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
adapter.onClick(position, v);
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_settings, menu);
}
@Override
public boolean onContextItemSelected(MenuItem item) {
return onOptionsItemSelected(item);
}
/**
* Empty text field on resume and show keyboard
*/
protected void onResume() {
if (prefs.getBoolean("require-layout-update", false)) {
// Restart current activity to refresh view, since some preferences
// may require using a new UI
prefs.edit().putBoolean("require-layout-update", false).commit();
Intent i = new Intent(this, getClass());
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_NO_ANIMATION);
finish();
overridePendingTransition(0, 0);
startActivity(i);
overridePendingTransition(0, 0);
}
if (kissBar.getVisibility() != View.VISIBLE) {
updateRecords(searchEditText.getText().toString());
displayClearOnInput();
} else {
displayKissBar(false);
}
// Activity manifest specifies stateAlwaysHidden as windowSoftInputMode
// so the keyboard will be hidden by default
// we may want to display it if the setting is set
if (prefs.getBoolean("display-keyboard", false)) {
// Display keyboard
showKeyboard();
new Handler().postDelayed(displayKeyboardRunnable, 10);
// For some weird reasons, keyboard may be hidden by the system
// So we have to run this multiple time at different time
// See https://github.com/Neamar/KISS/issues/119
new Handler().postDelayed(displayKeyboardRunnable, 100);
new Handler().postDelayed(displayKeyboardRunnable, 500);
} else {
// Not used (thanks windowSoftInputMode)
// unless coming back from KISS settings
hideKeyboard();
}
super.onResume();
}
@Override
protected void onDestroy() {
super.onDestroy();
// unregister our receiver
this.unregisterReceiver(this.mReceiver);
KissApplication.getCameraHandler().releaseCamera();
}
@Override
protected void onPause() {
super.onPause();
KissApplication.getCameraHandler().releaseCamera();
}
@Override
protected void onNewIntent(Intent intent) {
// Empty method,
// This is called when the user press Home again while already browsing MainActivity
// onResume() will be called right after, hiding the kissbar if any.
// http://developer.android.com/reference/android/app/Activity.html#onNewIntent(android.content.Intent)
}
@Override
public void onBackPressed() {
// Is the kiss menu visible?
if (menuButton.getVisibility() == View.VISIBLE) {
displayKissBar(false);
} else {
// If no kissmenu, empty the search bar
searchEditText.setText("");
}
// No call to super.onBackPressed, since this would quit the launcher.
}
@Override
public boolean onKeyDown(int keycode, @NonNull KeyEvent e) {
switch (keycode) {
case KeyEvent.KEYCODE_MENU:
// For user with a physical menu button, we still want to display *our* contextual menu
menuButton.showContextMenu();
return true;
}
return super.onKeyDown(keycode, e);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.settings:
startActivity(new Intent(android.provider.Settings.ACTION_SETTINGS));
return true;
case R.id.wallpaper:
hideKeyboard();
Intent intent = new Intent(Intent.ACTION_SET_WALLPAPER);
startActivity(Intent.createChooser(intent, getString(R.string.menu_wallpaper)));
return true;
case R.id.preferences:
startActivity(new Intent(this, SettingsActivity.class));
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_settings, menu);
return true;
}
/**
* Display menu, on short or long press.
*
* @param menuButton "kebab" menu (3 dots)
*/
public void onMenuButtonClicked(View menuButton) {
// When the kiss bar is displayed, the button can still be clicked in a few areas (due to favorite margin)
// To fix this, we discard any click event occurring when the kissbar is displayed
// if (kissBar.getVisibility() != View.VISIBLE)
menuButton.showContextMenu();
}
/**
* Clear text content when touching the cross button
*/
@SuppressWarnings("UnusedParameters")
public void onClearButtonClicked(View clearButton) {
searchEditText.setText("");
}
/**
* Display KISS menu
*/
public void onLauncherButtonClicked(View launcherButton) {
// Display or hide the kiss bar, according to current view tag (showMenu / hideMenu).
// displayKissBar(launcherButton.getTag().equals("showMenu"));
boolean display;
if (resultsListView.getVisibility() == View.VISIBLE) {
display = false;
} else {
display = true;
}
displayKissBar(display);
}
public void onShowFavoritesButtonClicked(View launcherButton) {
// Display or hide the kiss bar, according to current view tag (showMenu / hideMenu).
// displayFavoritesBar(launcherButton.getTag().equals("showMenu"));
boolean display;
if (kissBar.getVisibility() == View.VISIBLE) {
display = false;
} else {
display = true;
}
displayFavoritesBar(display);
}
public void onFavoriteButtonClicked(View favorite) {
// Favorites handling
Pojo pojo = KissApplication.getDataHandler(MainActivity.this).getFavorites(tryToRetrieve)
.get(Integer.parseInt((String) favorite.getTag()));
final Result result = Result.fromPojo(MainActivity.this, pojo);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
result.fastLaunch(MainActivity.this);
}
}, KissApplication.TOUCH_DELAY);
// Can take out if we want. This is just so that the next time you press the Home button,
// it goes to the main screen and doesn't still have the Favorites displayed. The only downside
// is that you see it go away before the app loads so it doesn't look the best, but it's just
// aesthetic
kissBar.setVisibility(View.GONE);
}
private void displayClearOnInput() {
final View clearButton = findViewById(R.id.clearButton);
if (searchEditText.getText().length() > 0) {
clearButton.setVisibility(View.VISIBLE);
menuButton.setVisibility(View.INVISIBLE);
} else {
clearButton.setVisibility(View.INVISIBLE);
menuButton.setVisibility(View.VISIBLE);
}
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR1)
private void displayLoader(Boolean display) {
final View loaderBar = findViewById(R.id.loaderBar);
final View launcherButton = findViewById(R.id.launcherButton);
int animationDuration = getResources().getInteger(
android.R.integer.config_longAnimTime);
if (!display) {
launcherButton.setVisibility(View.VISIBLE);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
// Animate transition from loader to launch button
launcherButton.setAlpha(0);
launcherButton.animate()
.alpha(1f)
.setDuration(animationDuration)
.setListener(null);
loaderBar.animate()
.alpha(0f)
.setDuration(animationDuration)
.setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
loaderBar.setVisibility(View.GONE);
loaderBar.setAlpha(1);
}
});
} else {
loaderBar.setVisibility(View.GONE);
}
} else {
launcherButton.setVisibility(View.INVISIBLE);
loaderBar.setVisibility(View.VISIBLE);
}
}
private void displayKissBar(Boolean display) {
final ImageView launcherButton = (ImageView) findViewById(R.id.launcherButton);
// get the center for the clipping circle
int cx = (launcherButton.getLeft() + launcherButton.getRight()) / 2;
int cy = (launcherButton.getTop() + launcherButton.getBottom()) / 2;
// get the final radius for the clipping circle
int finalRadius = Math.max(kissBar.getWidth(), kissBar.getHeight());
if (display) {
// Display the app list
// resultsListView.setAdapter(adapter);
kissBar.setVisibility(View.GONE);
resultsListView.setVisibility(View.VISIBLE);
if (searcher != null) {
searcher.cancel(true);
}
searcher = new ApplicationsSearcher(MainActivity.this);
searcher.execute();
// Reveal the bar
// if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
// Animator anim = ViewAnimationUtils.createCircularReveal(kissBar, cx, cy, 0, finalRadius);
// kissBar.setVisibility(View.VISIBLE);
// anim.start();
// } else {
// // No animation before Lollipop
// kissBar.setVisibility(View.VISIBLE);
// }
// Retrieve favorites. Try to retrieve more, since some favorites can't be displayed (e.g. search queries)
// retrieveFavorites();
hideKeyboard();
} else {
// Hide the bar
// if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
// Animator anim = ViewAnimationUtils.createCircularReveal(kissBar, cx, cy, finalRadius, 0);
// anim.addListener(new AnimatorListenerAdapter() {
// @Override
// public void onAnimationEnd(Animator animation) {
// kissBar.setVisibility(View.GONE);
//// resultsListView.setVisibility(View.GONE);
//// adapter.setVisibility(0);
// super.onAnimationEnd(animation);
// }
// });
// anim.start();
// } else {
// // No animation before Lollipop
// kissBar.setVisibility(View.GONE);
//// adapter.setVisibility(0);
//// resultsListView.setVisibility(View.GONE);
// }
// searcher.onPostExecute();
resultsListView.setVisibility(View.GONE);
// resultsListView.setAdapter(null);
// kissBar.setVisibility(View.VISIBLE);
// kissBar.setVisibility(View.GONE);
searchEditText.setText("");
}
}
private void displayFavoritesBar(Boolean display) {
final ImageView launcherButton = (ImageView) findViewById(R.id.launcherButton2);
ArrayList<Pojo> favoritesPojo = KissApplication.getDataHandler(MainActivity.this)
.getFavorites(tryToRetrieve);
int location[] = {0, 0};
launcherButton.getLocationInWindow(location);
int startX = location[0];
int startY = location[1];
int duration = 300;
if (display) {
resultsListView.setVisibility(View.GONE);
searchEditText.setText("");
if (isEmptyMenuVisible) {
main_empty_layout.setVisibility(View.VISIBLE);
}
// kissBar.setVisibility(View.INVISIBLE);
if (favoritesPojo.size() > 0) {
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
for (int i = 0; i < favoritesPojo.size(); i++) {
// if (i < 4) {
FrameLayout layout = (FrameLayout) findViewById(favsLayoutIds[i]);
int endLocation[] = {0, 0};
layout.getLocationInWindow(endLocation);
int endX = endLocation[0];
int endY = endLocation[1];
int deltaX = startX - endX;
int deltaY = startY - endY;
TranslateAnimation transAnimation = new TranslateAnimation(Animation.ABSOLUTE, deltaX, Animation.ABSOLUTE,
0, Animation.ABSOLUTE, deltaY, Animation.ABSOLUTE, 0);
transAnimation.setDuration(duration);
// transAnimation.setStartOffset(0);
kissBar.setVisibility(View.VISIBLE);
layout.startAnimation(transAnimation);
}
} else {
// No animation before Lollipop
kissBar.setVisibility(View.VISIBLE);
}
}
// Retrieve favorites. Try to retrieve more, since some favorites can't be displayed (e.g. search queries)
retrieveFavorites();
hideKeyboard();
} else {
if (favoritesPojo.size() > 0) {
// Hide the bar
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
for (int i = 0; i < favoritesPojo.size(); i++) {
// if (i < 4) {
FrameLayout layout = (FrameLayout) findViewById(favsLayoutIds[i]);
int endLocation[] = {0, 0};
layout.getLocationInWindow(endLocation);
int endX = endLocation[0];
int endY = endLocation[1];
int deltaX = startX - endX;
int deltaY = startY - endY;
TranslateAnimation transAnimation = new TranslateAnimation(Animation.ABSOLUTE, 0, Animation.ABSOLUTE,
deltaX, Animation.ABSOLUTE, 0, Animation.ABSOLUTE, deltaY);
transAnimation.setDuration(duration);
// transAnimation.setStartOffset(0);
// kissBar.setVisibility(View.GONE);
layout.startAnimation(transAnimation);
layout.postDelayed(new Runnable() {
@Override
public void run() {
kissBar.setVisibility(View.GONE);
}
}, duration);
}
} else {
// No animation before Lollipop
kissBar.setVisibility(View.GONE);
}
}
if (isEmptyMenuVisible) {
// TranslateAnimation emptyMenuAnimation = new TranslateAnimation(0, 0, 0, 0);
// emptyMenuAnimation.setDuration(duration);
// main_empty_layout.startAnimation(emptyMenuAnimation);
// main_empty_layout.postDelayed(new Runnable() {
// @Override
// public void run() {
// main_empty_layout.setVisibility(View.VISIBLE);
// }
// }, duration);
main_empty_layout.setVisibility(View.VISIBLE);
}
searchEditText.setText("");
}
}
public void retrieveFavorites() {
ArrayList<Pojo> favoritesPojo = KissApplication.getDataHandler(MainActivity.this)
.getFavorites(tryToRetrieve);
boolean isAtLeast1FavoriteApp = false;
if (favoritesPojo.size() == 0) {
Toast toast = Toast.makeText(MainActivity.this, getString(R.string.no_favorites), Toast.LENGTH_SHORT);
toast.show();
isAtLeast1FavoriteApp = false;
} else if (favoritesPojo.size() > 0) {
isAtLeast1FavoriteApp = true;
}
if (isAtLeast1FavoriteApp && isEmptyMenuVisible) {
main_empty_layout.setVisibility(View.INVISIBLE);
}
// Don't look for items after favIds length, we won't be able to display them
for (int i = 0; i < Math.min(favsIds.length, favoritesPojo.size()); i++) {
Pojo pojo = favoritesPojo.get(i);
ImageView image = (ImageView) findViewById(favsIds[i]);
ImageView circle = (ImageView) findViewById(favsCircleIds[i]);
Result result = Result.fromPojo(MainActivity.this, pojo);
Drawable drawable = result.getDrawable(MainActivity.this);
if (drawable != null)
image.setImageDrawable(drawable);
image.setVisibility(View.VISIBLE);
circle.setVisibility(View.VISIBLE);
image.setContentDescription(pojo.displayName);
}
// Hide empty favorites (not enough favorites yet)
for (int i = favoritesPojo.size(); i < favsIds.length; i++) {
findViewById(favsIds[i]).setVisibility(View.GONE);
findViewById(favsCircleIds[i]).setVisibility(View.GONE);
}
}
/**
* This function gets called on changes. It will ask all the providers for
* data
*
* @param query the query on which to search
*/
private void updateRecords(String query) {
if (searcher != null) {
searcher.cancel(true);
}
if (query.length() == 0) {
if (prefs.getBoolean("history-hide", false)) {
searcher = new NullSearcher(this);
//Hide default scrollview
findViewById(R.id.main_empty).setVisibility(View.INVISIBLE);
isEmptyMenuVisible = false;
} else {
searcher = new HistorySearcher(this);
//Show default scrollview
findViewById(R.id.main_empty).setVisibility(View.VISIBLE);
isEmptyMenuVisible = true;
}
} else {
searcher = new QuerySearcher(this, query);
}
searcher.execute();
}
public void resetTask() {
searcher = null;
}
/**
* Call this function when we're leaving the activity We can't use
* onPause(), since it may be called for a configuration change
*/
public void launchOccurred(int index, Result result) {
// We selected an item on the list,
// now we can cleanup the filter:
if (!searchEditText.getText().toString().equals("")) {
searchEditText.setText("");
hideKeyboard();
}
}
private void hideKeyboard() {
// Check if no view has focus:
View view = this.getCurrentFocus();
if (view != null) {
InputMethodManager inputManager = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
}
private void showKeyboard() {
searchEditText.requestFocus();
InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
mgr.showSoftInput(searchEditText, InputMethodManager.SHOW_IMPLICIT);
}
public int getFavIconsSize() {
return favsIds.length;
}
}
|
Added in rotation to Favorites animation
|
app/src/main/java/fr/neamar/kiss/MainActivity.java
|
Added in rotation to Favorites animation
|
<ide><path>pp/src/main/java/fr/neamar/kiss/MainActivity.java
<ide> import android.view.View;
<ide> import android.view.ViewAnimationUtils;
<ide> import android.view.animation.Animation;
<add>import android.view.animation.AnimationSet;
<add>import android.view.animation.RotateAnimation;
<ide> import android.view.animation.TranslateAnimation;
<ide> import android.view.inputmethod.InputMethodManager;
<ide> import android.widget.AdapterView;
<ide> launcherButton.getLocationInWindow(location);
<ide> int startX = location[0];
<ide> int startY = location[1];
<del> int duration = 300;
<add> int duration = 1000; //Normally 300. Just made this 1000 to make the rotation more apparent. Can switch back to 300 after presentation.
<ide>
<ide> if (display) {
<ide>
<ide> int deltaX = startX - endX;
<ide> int deltaY = startY - endY;
<ide>
<add> AnimationSet animation = new AnimationSet(true);
<add> RotateAnimation rotateAnimation = new RotateAnimation(-180, 0, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
<add> rotateAnimation.setDuration(duration);
<add> animation.addAnimation(rotateAnimation);
<add>
<ide> TranslateAnimation transAnimation = new TranslateAnimation(Animation.ABSOLUTE, deltaX, Animation.ABSOLUTE,
<ide> 0, Animation.ABSOLUTE, deltaY, Animation.ABSOLUTE, 0);
<ide> transAnimation.setDuration(duration);
<add> animation.addAnimation(transAnimation);
<add>
<ide> // transAnimation.setStartOffset(0);
<ide> kissBar.setVisibility(View.VISIBLE);
<del> layout.startAnimation(transAnimation);
<add> layout.startAnimation(animation);
<ide> }
<ide> } else {
<ide> // No animation before Lollipop
<ide> int deltaX = startX - endX;
<ide> int deltaY = startY - endY;
<ide>
<add> AnimationSet animation = new AnimationSet(true);
<add> RotateAnimation rotateAnimation = new RotateAnimation(0, -180, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
<add> rotateAnimation.setDuration(duration);
<add> animation.addAnimation(rotateAnimation);
<add>
<ide> TranslateAnimation transAnimation = new TranslateAnimation(Animation.ABSOLUTE, 0, Animation.ABSOLUTE,
<ide> deltaX, Animation.ABSOLUTE, 0, Animation.ABSOLUTE, deltaY);
<ide> transAnimation.setDuration(duration);
<add> animation.addAnimation(transAnimation);
<ide> // transAnimation.setStartOffset(0);
<ide> // kissBar.setVisibility(View.GONE);
<del> layout.startAnimation(transAnimation);
<add> layout.startAnimation(animation);
<ide> layout.postDelayed(new Runnable() {
<ide> @Override
<ide> public void run() {
|
|
Java
|
bsd-3-clause
|
1146ac3258df246b5ff171a52df30cca6f0443b1
| 0 |
ThreeTen/threetenbp,jnehlmeier/threetenbp,jnehlmeier/threetenbp,pepyakin/threetenbp,naixx/threetenbp,pepyakin/threetenbp,naixx/threetenbp,ThreeTen/threetenbp
|
/*
* Copyright (c) 2007-2012, Stephen Colebourne & Michael Nascimento Santos
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of JSR-310 nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package javax.time;
import static javax.time.calendrical.LocalDateTimeField.INSTANT_SECONDS;
import static javax.time.calendrical.LocalDateTimeField.NANO_OF_SECOND;
import java.io.Serializable;
import java.math.BigDecimal;
import java.math.BigInteger;
import javax.time.calendrical.AdjustableDateTime;
import javax.time.calendrical.DateTime;
import javax.time.calendrical.DateTimeField;
import javax.time.calendrical.DateTimeValueRange;
import javax.time.calendrical.LocalDateTimeField;
import javax.time.calendrical.LocalPeriodUnit;
import javax.time.calendrical.PeriodUnit;
import javax.time.format.DateTimeFormatters;
import javax.time.format.DateTimeParseException;
/**
* An instantaneous point on the time-line.
* <p>
* This class models a single instantaneous point on the time-line.
* This might be used to record event time-stamps in the application.
* <p>
* For practicality, the instant is stored with some constraints.
* The measurable time-line is restricted to the number of seconds that can be held
* in a {@code long}. This is greater than the current estimated age of the universe.
* The instant is stored to nanosecond resolution.
* <p>
* The range of an instant requires the storage of a number larger than a {@code long}.
* To achieve this, the class stores a {@code long} representing epoch-seconds and an
* {@code int} representing nanosecond-of-second, which will always be between 0 and 999,999,999.
* The epoch-seconds are measured from the standard Java epoch of {@code 1970-01-01T00:00:00Z}
* where instants after the epoch have positive values, and earlier instants have negative values.
* For both the epoch-second and nanosecond parts, a larger value is always later on the time-line
* than a smaller value.
*
* <h4>Time-scale</h4>
* <p>
* The length of the solar day is the standard way that humans measure time.
* This has traditionally been subdivided into 24 hours of 60 minutes of 60 seconds,
* forming a 86400 second day.
* <p>
* Modern timekeeping is based on atomic clocks which precisely define an SI second
* relative to the transitions of a Caesium atom. The length of an SI second was defined
* to be very close to the 86400th fraction of a day.
* <p>
* Unfortunately, as the Earth rotates the length of the day varies.
* In addition, over time the average length of the day is getting longer as the Earth slows.
* As a result, the length of a solar day in 2012 is slightly longer than 86400 SI seconds.
* The actual length of any given day and the amount by which the Earth is slowing
* are not predictable and can only be determined by measurement.
* The UT1 time-scale captures the accurate length of day, but is only available some
* time after the day has completed.
* <p>
* The UTC time-scale is a standard approach to bundle up all the additional fractions
* of a second from UT1 into whole seconds, known as <i>leap-seconds</i>.
* A leap-second may be added or removed depending on the Earth's rotational changes.
* As such, UTC permits a day to have 86399 SI seconds or 86401 SI seconds where
* necessary in order to keep the day aligned with the Sun.
* <p>
* The modern UTC time-scale was introduced in 1972, introducing the concept of whole leap-seconds.
* Between 1958 and 1972, the definition of UTC was complex, with minor sub-second leaps and
* alterations to the length of the notional second. As of 2012, discussions are underway
* to change the definition of UTC again, with the potential to remove leap seconds or
* introduce other changes.
* <p>
* Given the complexity of accurate timekeeping described above, this Java API defines
* its own time-scale with a simplification. The Java time-scale is defined as follows:
* <ul>
* <li>midday will always be exactly as defined by the agreed international civil time</li>
* <li>other times during the day will be broadly in line with the agreed international civil time</li>
* <li>the day will be divided into exactly 86400 subdivisions, referred to as "seconds"</li>
* <li>the Java "second" may differ from an SI second</li>
* </ul>
* Agreed international civil time is the base time-scale agreed by international convention,
* which in 2012 is UTC (with leap-seconds).
* <p>
* In 2012, the definition of the Java time-scale is the same as UTC for all days except
* those where a leap-second occurs. On days where a leap-second does occur, the time-scale
* effectively eliminates the leap-second, maintaining the fiction of 86400 seconds in the day.
* <p>
* The main benefit of always dividing the day into 86400 subdivisions is that it matches the
* expectations of most users of the API. The alternative is to force every user to understand
* what a leap second is and to force them to have special logic to handle them.
* Most applications do not have access to a clock that is accurate enough to record leap-seconds.
* Most applications also do not have a problem with a second being a very small amount longer or
* shorter than a real SI second during a leap-second.
* <p>
* If an application does have access to an accurate clock that reports leap-seconds, then the
* recommended technique to implement the Java time-scale is to use the UTC-SLS convention.
* <a href="http://www.cl.cam.ac.uk/~mgk25/time/utc-sls/">UTC-SLS</a> effectively smoothes the
* leap-second over the last 1000 seconds of the day, making each of the last 1000 "seconds"
* 1/1000th longer or shorter than a real SI second.
* <p>
* One final problem is the definition of the agreed international civil time before the
* introduction of modern UTC in 1972. This includes the Java epoch of {@code 1970-01-01}.
* It is intended that instants before 1972 be interpreted based on the solar day divided
* into 86400 subdivisions.
* <p>
* The Java time-scale is used for all date-time classes supplied by JSR-310.
* This includes {@code Instant}, {@code LocalDate}, {@code LocalTime}, {@code OffsetDateTime},
* {@code ZonedDateTime} and {@code Duration}.
*
* <h4>Implementation notes</h4>
* This class is immutable and thread-safe.
*/
public final class Instant
implements AdjustableDateTime, Comparable<Instant>, Serializable {
/**
* Constant for the 1970-01-01T00:00:00Z epoch instant.
*/
public static final Instant EPOCH = new Instant(0, 0);
/**
* Serialization version.
*/
private static final long serialVersionUID = 1L;
/**
* Constant for nanos per second.
*/
private static final int NANOS_PER_SECOND = 1000000000;
/**
* BigInteger constant for a billion.
*/
static final BigInteger BILLION = BigInteger.valueOf(NANOS_PER_SECOND);
/**
* The number of seconds from the epoch of 1970-01-01T00:00:00Z.
*/
private final long seconds;
/**
* The number of nanoseconds, later along the time-line, from the seconds field.
* This is always positive, and never exceeds 999,999,999.
*/
private final int nanos;
//-----------------------------------------------------------------------
/**
* Obtains the current instant from the system clock.
* <p>
* This will query the {@link Clock#systemUTC() system UTC clock} to
* obtain the current instant.
* <p>
* Using this method will prevent the ability to use an alternate time-source for
* testing because the clock is effectively hard-coded.
*
* @return the current instant using the system clock, not null
*/
public static Instant now() {
return Clock.systemUTC().instant();
}
/**
* Obtains the current instant from the specified clock.
* <p>
* This will query the specified clock to obtain the current time.
* <p>
* Using this method allows the use of an alternate clock for testing.
* The alternate clock may be introduced using {@link Clock dependency injection}.
*
* @param clock the clock to use, not null
* @return the current instant, not null
*/
public static Instant now(Clock clock) {
DateTimes.checkNotNull(clock, "Clock must not be null");
return clock.instant();
}
//-----------------------------------------------------------------------
/**
* Obtains an instance of {@code Instant} using seconds from the
* epoch of 1970-01-01T00:00:00Z.
* <p>
* The nanosecond field is set to zero.
*
* @param epochSecond the number of seconds from 1970-01-01T00:00:00Z
* @return an instant, not null
*/
public static Instant ofEpochSecond(long epochSecond) {
return create(epochSecond, 0);
}
/**
* Obtains an instance of {@code Instant} using seconds from the
* epoch of 1970-01-01T00:00:00Z and nanosecond fraction of second.
* <p>
* This method allows an arbitrary number of nanoseconds to be passed in.
* The factory will alter the values of the second and nanosecond in order
* to ensure that the stored nanosecond is in the range 0 to 999,999,999.
* For example, the following will result in the exactly the same instant:
* <pre>
* Instant.ofSeconds(3, 1);
* Instant.ofSeconds(4, -999999999);
* Instant.ofSeconds(2, 1000000001);
* </pre>
*
* @param epochSecond the number of seconds from 1970-01-01T00:00:00Z
* @param nanoAdjustment the nanosecond adjustment to the number of seconds, positive or negative
* @return an instant, not null
* @throws ArithmeticException if the calculation exceeds the supported range
*/
public static Instant ofEpochSecond(long epochSecond, long nanoAdjustment) {
long secs = DateTimes.safeAdd(epochSecond, DateTimes.floorDiv(nanoAdjustment, NANOS_PER_SECOND));
int nos = DateTimes.floorMod(nanoAdjustment, NANOS_PER_SECOND);
return create(secs, nos);
}
/**
* Obtains an instance of {@code Instant} using seconds from the
* epoch of 1970-01-01T00:00:00Z.
* <p>
* The seconds and nanoseconds are extracted from the specified {@code BigDecimal}.
* If the decimal is larger than {@code Long.MAX_VALUE} or has more than 9 decimal
* places then an exception is thrown.
*
* @param epochSecond the number of seconds from 1970-01-01T00:00:00Z, up to scale 9
* @return an instant, not null
* @throws ArithmeticException if the calculation exceeds the supported range
*/
public static Instant ofEpochSecond(BigDecimal epochSecond) {
DateTimes.checkNotNull(epochSecond, "Seconds must not be null");
return ofEpochNano(epochSecond.movePointRight(9).toBigIntegerExact());
}
//-----------------------------------------------------------------------
/**
* Obtains an instance of {@code Instant} using milliseconds from the
* epoch of 1970-01-01T00:00:00Z.
* <p>
* The seconds and nanoseconds are extracted from the specified milliseconds.
*
* @param epochMilli the number of milliseconds from 1970-01-01T00:00:00Z
* @return an instant, not null
*/
public static Instant ofEpochMilli(long epochMilli) {
long secs = DateTimes.floorDiv(epochMilli, 1000);
int mos = DateTimes.floorMod(epochMilli, 1000);
return create(secs, mos * 1000000);
}
//-----------------------------------------------------------------------
/**
* Obtains an instance of {@code Instant} using nanoseconds from the
* epoch of 1970-01-01T00:00:00Z.
* <p>
* The seconds and nanoseconds are extracted from the specified nanoseconds.
*
* @param epochNano the number of nanoseconds from 1970-01-01T00:00:00Z
* @return an instant, not null
*/
public static Instant ofEpochNano(long epochNano) {
long secs = DateTimes.floorDiv(epochNano, NANOS_PER_SECOND);
int nos = DateTimes.floorMod(epochNano, NANOS_PER_SECOND);
return create(secs, nos);
}
/**
* Obtains an instance of {@code Instant} using nanoseconds from the
* epoch of 1970-01-01T00:00:00Z.
* <p>
* The seconds and nanoseconds are extracted from the specified {@code BigInteger}.
* If the resulting seconds value is larger than {@code Long.MAX_VALUE} then an
* exception is thrown.
*
* @param epochNano the number of nanoseconds from 1970-01-01T00:00:00Z, not null
* @return an instant, not null
* @throws ArithmeticException if the calculation exceeds the supported range
*/
public static Instant ofEpochNano(BigInteger epochNano) {
DateTimes.checkNotNull(epochNano, "Nanos must not be null");
BigInteger[] divRem = epochNano.divideAndRemainder(BILLION);
if (divRem[0].bitLength() > 63) {
throw new ArithmeticException("Exceeds capacity of Duration: " + epochNano);
}
return ofEpochSecond(divRem[0].longValue(), divRem[1].intValue());
}
/**
* Obtains an instance of {@code Instant} from a calendrical.
* <p>
* A calendrical represents some form of date and time information.
* This factory converts the arbitrary calendrical to an instance of {@code Instant}.
*
* @param calendrical the calendrical to convert, not null
* @return the instant, not null
* @throws DateTimeException if unable to convert to an {@code Instant}
*/
public static Instant from(DateTime calendrical) {
long instantSecs = calendrical.get(INSTANT_SECONDS);
long nanoOfSecond;
try {
nanoOfSecond = calendrical.get(NANO_OF_SECOND);
} catch (DateTimeException ex) {
nanoOfSecond = 0;
}
return Instant.ofEpochSecond(instantSecs, nanoOfSecond);
}
//-----------------------------------------------------------------------
/**
* Obtains an instance of {@code Instant} from a text string such as
* {@code 2007-12-03T10:15:30:00}.
* <p>
* The string must represent a valid instant in UTC and is parsed using
* {@link DateTimeFormatters#isoInstant()}.
*
* @param text the text to parse, not null
* @return the parsed instant, not null
* @throws DateTimeParseException if the text cannot be parsed
*/
public static Instant parse(final CharSequence text) {
return DateTimeFormatters.isoInstant().parse(text, Instant.class);
}
//-----------------------------------------------------------------------
/**
* Obtains an instance of {@code Instant} using seconds and nanoseconds.
*
* @param seconds the length of the duration in seconds
* @param nanoOfSecond the nano-of-second, from 0 to 999,999,999
*/
private static Instant create(long seconds, int nanoOfSecond) {
if ((seconds | nanoOfSecond) == 0) {
return EPOCH;
}
return new Instant(seconds, nanoOfSecond);
}
/**
* Constructs an instance of {@code Instant} using seconds from the epoch of
* 1970-01-01T00:00:00Z and nanosecond fraction of second.
*
* @param epochSecond the number of seconds from 1970-01-01T00:00:00Z
* @param nanos the nanoseconds within the second, must be positive
*/
private Instant(long epochSecond, int nanos) {
super();
this.seconds = epochSecond;
this.nanos = nanos;
}
/**
* Resolves singletons.
*
* @return the resolved instance, not null
*/
private Object readResolve() {
return (seconds | nanos) == 0 ? EPOCH : this;
}
//-----------------------------------------------------------------------
/**
* Gets the number of seconds from the Java epoch of 1970-01-01T00:00:00Z.
* <p>
* The epoch second count is a simple incrementing count of seconds where
* second 0 is 1970-01-01T00:00:00Z.
* The nanosecond part of the day is returned by {@code getNanosOfSecond}.
*
* @return the seconds from the epoch of 1970-01-01T00:00:00Z
*/
public long getEpochSecond() {
return seconds;
}
/**
* Gets the number of nanoseconds, later along the time-line, from the start
* of the second.
* <p>
* The nanosecond-of-second value measures the total number of nanoseconds from
* the second returned by {@code getEpochSecond}.
*
* @return the nanoseconds within the second, always positive, never exceeds 999,999,999
*/
public int getNano() {
return nanos;
}
//-----------------------------------------------------------------------
/**
* Returns a copy of this instant with the specified duration added.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param duration the duration to add, positive or negative, not null
* @return an {@code Instant} based on this instant with the specified duration added, not null
* @throws ArithmeticException if the calculation exceeds the supported range
*/
public Instant plus(Duration duration) {
long secsToAdd = duration.getSeconds();
int nanosToAdd = duration.getNano();
if ((secsToAdd | nanosToAdd) == 0) {
return this;
}
return plus(secsToAdd, nanosToAdd);
}
//-----------------------------------------------------------------------
/**
* Returns a copy of this instant with the specified duration in seconds added.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param secondsToAdd the seconds to add, positive or negative
* @return an {@code Instant} based on this instant with the specified seconds added, not null
* @throws ArithmeticException if the calculation exceeds the supported range
*/
public Instant plusSeconds(long secondsToAdd) {
return plus(secondsToAdd, 0);
}
/**
* Returns a copy of this instant with the specified duration in milliseconds added.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param millisToAdd the milliseconds to add, positive or negative
* @return an {@code Instant} based on this instant with the specified milliseconds added, not null
* @throws ArithmeticException if the calculation exceeds the supported range
*/
public Instant plusMillis(long millisToAdd) {
return plus(millisToAdd / 1000, (millisToAdd % 1000) * 1000000);
}
/**
* Returns a copy of this instant with the specified duration in nanoseconds added.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param nanosToAdd the nanoseconds to add, positive or negative
* @return an {@code Instant} based on this instant with the specified nanoseconds added, not null
* @throws ArithmeticException if the calculation exceeds the supported range
*/
public Instant plusNanos(long nanosToAdd) {
return plus(0, nanosToAdd);
}
/**
* Returns a copy of this instant with the specified duration added.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param secondsToAdd the seconds to add, positive or negative
* @param nanosToAdd the nanos to add, positive or negative
* @return an {@code Instant} based on this instant with the specified seconds added, not null
* @throws ArithmeticException if the calculation exceeds the supported range
*/
private Instant plus(long secondsToAdd, long nanosToAdd) {
if ((secondsToAdd | nanosToAdd) == 0) {
return this;
}
long epochSec = DateTimes.safeAdd(seconds, secondsToAdd);
epochSec = DateTimes.safeAdd(epochSec, nanosToAdd / NANOS_PER_SECOND);
nanosToAdd = nanosToAdd % NANOS_PER_SECOND;
long nanoAdjustment = nanos + nanosToAdd; // safe int+NANOS_PER_SECOND
return ofEpochSecond(epochSec, nanoAdjustment);
}
//-----------------------------------------------------------------------
/**
* Returns a copy of this instant with the specified duration subtracted.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param duration the duration to subtract, positive or negative, not null
* @return an {@code Instant} based on this instant with the specified duration subtracted, not null
* @throws ArithmeticException if the calculation exceeds the supported range
*/
public Instant minus(Duration duration) {
long secsToSubtract = duration.getSeconds();
int nanosToSubtract = duration.getNano();
if ((secsToSubtract | nanosToSubtract) == 0) {
return this;
}
long secs = DateTimes.safeSubtract(seconds, secsToSubtract);
long nanoAdjustment = ((long) nanos) - nanosToSubtract; // safe int+int
return ofEpochSecond(secs, nanoAdjustment);
}
//-----------------------------------------------------------------------
/**
* Returns a copy of this instant with the specified duration in seconds subtracted.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param secondsToSubtract the seconds to subtract, positive or negative
* @return an {@code Instant} based on this instant with the specified seconds subtracted, not null
* @throws ArithmeticException if the calculation exceeds the supported range
*/
public Instant minusSeconds(long secondsToSubtract) {
if (secondsToSubtract == Long.MIN_VALUE) {
return plusSeconds(Long.MAX_VALUE).plusSeconds(1);
}
return plusSeconds(-secondsToSubtract);
}
/**
* Returns a copy of this instant with the specified duration in milliseconds subtracted.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param millisToSubtract the milliseconds to subtract, positive or negative
* @return an {@code Instant} based on this instant with the specified milliseconds subtracted, not null
* @throws ArithmeticException if the calculation exceeds the supported range
*/
public Instant minusMillis(long millisToSubtract) {
if (millisToSubtract == Long.MIN_VALUE) {
return plusMillis(Long.MAX_VALUE).plusMillis(1);
}
return plusMillis(-millisToSubtract);
}
/**
* Returns a copy of this instant with the specified duration in nanoseconds subtracted.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param nanosToSubtract the nanoseconds to subtract, positive or negative
* @return an {@code Instant} based on this instant with the specified nanoseconds subtracted, not null
* @throws ArithmeticException if the calculation exceeds the supported range
*/
public Instant minusNanos(long nanosToSubtract) {
if (nanosToSubtract == Long.MIN_VALUE) {
return plusNanos(Long.MAX_VALUE).plusNanos(1);
}
return plusNanos(-nanosToSubtract);
}
//-----------------------------------------------------------------------
@Override
public DateTimeValueRange range(DateTimeField field) {
if (field instanceof LocalDateTimeField) {
return field.range();
}
return field.doRange(this);
}
@Override
public long get(DateTimeField field) {
if (field instanceof LocalDateTimeField) {
switch ((LocalDateTimeField) field) {
case NANO_OF_SECOND: return nanos;
case MICRO_OF_SECOND: return nanos / 1000;
case MILLI_OF_SECOND: return nanos / 1000000;
case INSTANT_SECONDS: return seconds;
}
throw new DateTimeException("Unsupported field: " + field.getName());
}
return field.doGet(this);
}
@Override
public Instant with(DateTimeField field, long newValue) {
if (field instanceof LocalDateTimeField) {
LocalDateTimeField f = (LocalDateTimeField) field;
f.checkValidValue(newValue);
switch (f) {
case MILLI_OF_SECOND: {
int nval = (int) newValue * 1000000;
return (nval != nanos ? create(seconds, nval) : this);
}
case MICRO_OF_SECOND: {
int nval = (int) newValue * 1000;
return (nval != nanos ? create(seconds, nval) : this);
}
case NANO_OF_SECOND: return (newValue != nanos ? create(seconds, (int) newValue) : this);
case INSTANT_SECONDS: return (newValue != seconds ? create(newValue, nanos) : this);
}
throw new DateTimeException("Unsupported field: " + field.getName());
}
return field.doSet(this, newValue);
}
@Override
public Instant plus(long periodAmount, PeriodUnit unit) {
if (unit instanceof LocalPeriodUnit) {
switch ((LocalPeriodUnit) unit) {
case NANOS: return plusNanos(periodAmount);
case MICROS: return plus(periodAmount / 1000000, (periodAmount % 1000000) * 1000);
case MILLIS: return plusMillis(periodAmount);
case SECONDS: return plusSeconds(periodAmount);
case MINUTES: return plusSeconds(DateTimes.safeMultiply(periodAmount, DateTimes.SECONDS_PER_MINUTE));
case HOURS: return plusSeconds(DateTimes.safeMultiply(periodAmount, DateTimes.SECONDS_PER_HOUR));
case HALF_DAYS: return plusSeconds(DateTimes.safeMultiply(periodAmount, DateTimes.SECONDS_PER_DAY / 2));
case DAYS: return plusSeconds(DateTimes.safeMultiply(periodAmount, DateTimes.SECONDS_PER_DAY));
}
throw new DateTimeException("Unsupported unit: " + unit.getName());
}
return unit.doAdd(this, periodAmount);
}
@Override
public Instant minus(long periodAmount, PeriodUnit unit) {
return plus(DateTimes.safeNegate(periodAmount), unit);
}
//-------------------------------------------------------------------------
/**
* Extracts date-time information in a generic way.
* <p>
* This method exists to fulfill the {@link DateTime} interface.
* This implementation always returns null.
*
* @param <R> the type to extract
* @param type the type to extract, null returns null
* @return the extracted object, null if unable to extract
*/
@Override
public <T> T extract(Class<T> type) {
return null;
}
//-----------------------------------------------------------------------
/**
* Converts this instant to the number of seconds from the epoch
* of 1970-01-01T00:00:00Z expressed as a {@code BigDecimal}.
*
* @return the number of seconds since the epoch of 1970-01-01T00:00:00Z, scale 9, not null
*/
public BigDecimal toEpochSecond() {
return BigDecimal.valueOf(seconds).add(BigDecimal.valueOf(nanos, 9));
}
/**
* Converts this instant to the number of nanoseconds from the epoch
* of 1970-01-01T00:00:00Z expressed as a {@code BigInteger}.
*
* @return the number of nanoseconds since the epoch of 1970-01-01T00:00:00Z, not null
*/
public BigInteger toEpochNano() {
return BigInteger.valueOf(seconds).multiply(BILLION).add(BigInteger.valueOf(nanos));
}
//-----------------------------------------------------------------------
/**
* Converts this instant to the number of milliseconds from the epoch
* of 1970-01-01T00:00:00Z.
* <p>
* If this instant represents a point on the time-line too far in the future
* or past to fit in a {@code long} milliseconds, then an exception is thrown.
* <p>
* If this instant has greater than millisecond precision, then the conversion
* will drop any excess precision information as though the amount in nanoseconds
* was subject to integer division by one million.
*
* @return the number of milliseconds since the epoch of 1970-01-01T00:00:00Z
* @throws ArithmeticException if the calculation exceeds the supported range
*/
public long toEpochMilli() {
long millis = DateTimes.safeMultiply(seconds, 1000);
return millis + nanos / 1000000;
}
//-----------------------------------------------------------------------
/**
* Compares this instant to the specified instant.
* <p>
* The comparison is based on the time-line position of the instants.
*
* @param otherInstant the other instant to compare to, not null
* @return the comparator value, negative if less, positive if greater
* @throws NullPointerException if otherInstant is null
*/
public int compareTo(Instant otherInstant) {
int cmp = DateTimes.safeCompare(seconds, otherInstant.seconds);
if (cmp != 0) {
return cmp;
}
return DateTimes.safeCompare(nanos, otherInstant.nanos);
}
/**
* Checks if this instant is after the specified instant.
* <p>
* The comparison is based on the time-line position of the instants.
*
* @param otherInstant the other instant to compare to, not null
* @return true if this instant is after the specified instant
* @throws NullPointerException if otherInstant is null
*/
public boolean isAfter(Instant otherInstant) {
return compareTo(otherInstant) > 0;
}
/**
* Checks if this instant is before the specified instant.
* <p>
* The comparison is based on the time-line position of the instants.
*
* @param otherInstant the other instant to compare to, not null
* @return true if this instant is before the specified instant
* @throws NullPointerException if otherInstant is null
*/
public boolean isBefore(Instant otherInstant) {
return compareTo(otherInstant) < 0;
}
//-----------------------------------------------------------------------
/**
* Checks if this instant is equal to the specified instant.
* <p>
* The comparison is based on the time-line position of the instants.
*
* @param otherInstant the other instant, null returns false
* @return true if the other instant is equal to this one
*/
@Override
public boolean equals(Object otherInstant) {
if (this == otherInstant) {
return true;
}
if (otherInstant instanceof Instant) {
Instant other = (Instant) otherInstant;
return this.seconds == other.seconds &&
this.nanos == other.nanos;
}
return false;
}
/**
* Returns a hash code for this instant.
*
* @return a suitable hash code
*/
@Override
public int hashCode() {
return ((int) (seconds ^ (seconds >>> 32))) + 51 * nanos;
}
//-----------------------------------------------------------------------
/**
* A string representation of this instant using ISO-8601 representation.
* <p>
* The format used is the same as {@link DateTimeFormatters#isoInstant()}.
*
* @return an ISO-8601 representation of this instant, not null
*/
@Override
public String toString() {
return DateTimeFormatters.isoInstant().print(this);
}
}
|
src/main/java/javax/time/Instant.java
|
/*
* Copyright (c) 2007-2012, Stephen Colebourne & Michael Nascimento Santos
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of JSR-310 nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package javax.time;
import static javax.time.calendrical.LocalDateTimeField.INSTANT_SECONDS;
import static javax.time.calendrical.LocalDateTimeField.NANO_OF_SECOND;
import java.io.Serializable;
import java.math.BigDecimal;
import java.math.BigInteger;
import javax.time.calendrical.AdjustableDateTime;
import javax.time.calendrical.DateTime;
import javax.time.calendrical.DateTimeField;
import javax.time.calendrical.DateTimeValueRange;
import javax.time.calendrical.LocalDateTimeField;
import javax.time.calendrical.LocalPeriodUnit;
import javax.time.calendrical.PeriodUnit;
import javax.time.format.DateTimeFormatters;
import javax.time.format.DateTimeParseException;
/**
* An instantaneous point on the time-line.
* <p>
* This class models a single instantaneous point on the time-line.
* This might be used to record event time-stamps in the application.
* <p>
* For practicality, the instant is stored with some constraints.
* The measurable time-line is restricted to the number of seconds that can be held
* in a {@code long}. This is greater than the current estimated age of the universe.
* The instant is stored to nanosecond resolution.
* <p>
* The range of an instant requires the storage of a number larger than a {@code long}.
* To achieve this, the class stores a {@code long} representing epoch-seconds and an
* {@code int} representing nanosecond-of-second, which will always be between 0 and 999,999,999.
* The epoch-seconds are measured from the standard Java epoch of {@code 1970-01-01T00:00:00Z}
* where instants after the epoch have positive values, and earlier instants have negative values.
* For both the epoch-second and nanosecond parts, a larger value is always later on the time-line
* than a smaller value.
*
* <h4>Time-scale</h4>
* <p>
* The length of the solar day is the standard way that humans measure time.
* This has traditionally been subdivided into 24 hours of 60 minutes of 60 seconds,
* forming a 86400 second day.
* <p>
* Modern timekeeping is based on atomic clocks which precisely define an SI second
* relative to the transitions of a Caesium atom. The length of an SI second was defined
* to be very close to the 86400th fraction of a day.
* <p>
* Unfortunately, as the Earth rotates the length of the day varies.
* In addition, over time the average length of the day is getting longer as the Earth slows.
* As a result, the length of a solar day in 2012 is slightly longer than 86400 SI seconds.
* The actual length of any given day and the amount by which the Earth is slowing
* are not predictable and can only be determined by measurement.
* The UT1 time-scale captures the accurate length of day, but is only available some
* time after the day has completed.
* <p>
* The UTC time-scale is a standard approach to bundle up all the additional fractions
* of a second from UT1 into whole seconds, known as <i>leap-seconds</i>.
* A leap-second may be added or removed depending on the Earth's rotational changes.
* As such, UTC permits a day to have 86399 SI seconds or 86401 SI seconds where
* necessary in order to keep the day aligned with the Sun.
* <p>
* The modern UTC time-scale was introduced in 1972, introducing the concept of whole leap-seconds.
* Between 1958 and 1972, the definition of UTC was complex, with minor sub-second leaps and
* alterations to the length of the notional second. As of 2012, discussions are underway
* to change the definition of UTC again, with the potential to remove leap seconds or
* introduce other changes.
* <p>
* Given the complexity of accurate timekeeping described above, this Java API defines
* its own time-scale with a simplification. The Java time-scale is defined as follows:
* <ul>
* <li>midday will always be exactly as defined by the agreed international civil time</li>
* <li>other times during the day will be broadly in line with the agreed international civil time</li>
* <li>the day will be divided into exactly 86400 subdivisions, referred to as "seconds"</li>
* <li>the Java "second" may differ from an SI second</li>
* </ul>
* Agreed international civil time is the base time-scale agreed by international convention,
* which in 2012 is UTC (with leap-seconds).
* <p>
* In 2012, the definition of the Java time-scale is the same as UTC for all days except
* those where a leap-second occurs. On days where a leap-second does occur, the time-scale
* effectively eliminates the leap-second, maintaining the fiction of 86400 seconds in the day.
* <p>
* The main benefit of always dividing the day into 86400 subdivisions is that it matches the
* expectations of most users of the API. The alternative is to force every user to understand
* what a leap second is and to force them to have special logic to handle them.
* Most applications do not have access to a clock that is accurate enough to record leap-seconds.
* Most applications also do not have a problem with a second being a very small amount longer or
* shorter than a real SI second during a leap-second.
* <p>
* If an application does have access to an accurate clock that reports leap-seconds, then the
* recommended technique to implement the Java time-scale is to use the UTC-SLS convention.
* <a href="http://www.cl.cam.ac.uk/~mgk25/time/utc-sls/">UTC-SLS</a> effectively smoothes the
* leap-second over the last 1000 seconds of the day, making each of the last 1000 "seconds"
* 1/1000th longer or shorter than a real SI second.
* <p>
* One final problem is the definition of the agreed international civil time before the
* introduction of modern UTC in 1972. This includes the Java epoch of {@code 1970-01-01}.
* It is intended that instants before 1972 be interpreted based on the solar day divided
* into 86400 subdivisions.
* <p>
* The Java time-scale is used for all date-time classes supplied by JSR-310.
* This includes {@code Instant}, {@code LocalDate}, {@code LocalTime}, {@code OffsetDateTime},
* {@code ZonedDateTime} and {@code Duration}.
*
* <h4>Implementation notes</h4>
* This class is immutable and thread-safe.
*/
public final class Instant
implements AdjustableDateTime, Comparable<Instant>, Serializable {
/**
* Constant for the 1970-01-01T00:00:00Z epoch instant.
*/
public static final Instant EPOCH = new Instant(0, 0);
/**
* Serialization version.
*/
private static final long serialVersionUID = 1L;
/**
* Constant for nanos per second.
*/
private static final int NANOS_PER_SECOND = 1000000000;
/**
* BigInteger constant for a billion.
*/
static final BigInteger BILLION = BigInteger.valueOf(NANOS_PER_SECOND);
/**
* The number of seconds from the epoch of 1970-01-01T00:00:00Z.
*/
private final long seconds;
/**
* The number of nanoseconds, later along the time-line, from the seconds field.
* This is always positive, and never exceeds 999,999,999.
*/
private final int nanos;
//-----------------------------------------------------------------------
/**
* Obtains the current instant from the system clock.
* <p>
* This will query the {@link Clock#systemUTC() system UTC clock} to
* obtain the current instant.
* <p>
* Using this method will prevent the ability to use an alternate time-source for
* testing because the clock is effectively hard-coded.
*
* @return the current instant using the system clock, not null
*/
public static Instant now() {
return Clock.systemUTC().instant();
}
/**
* Obtains the current instant from the specified clock.
* <p>
* This will query the specified clock to obtain the current time.
* <p>
* Using this method allows the use of an alternate clock for testing.
* The alternate clock may be introduced using {@link Clock dependency injection}.
*
* @param clock the clock to use, not null
* @return the current instant, not null
*/
public static Instant now(Clock clock) {
DateTimes.checkNotNull(clock, "Clock must not be null");
return clock.instant();
}
//-----------------------------------------------------------------------
/**
* Obtains an instance of {@code Instant} using seconds from the
* epoch of 1970-01-01T00:00:00Z.
* <p>
* The nanosecond field is set to zero.
*
* @param epochSecond the number of seconds from 1970-01-01T00:00:00Z
* @return an instant, not null
*/
public static Instant ofEpochSecond(long epochSecond) {
return create(epochSecond, 0);
}
/**
* Obtains an instance of {@code Instant} using seconds from the
* epoch of 1970-01-01T00:00:00Z and nanosecond fraction of second.
* <p>
* This method allows an arbitrary number of nanoseconds to be passed in.
* The factory will alter the values of the second and nanosecond in order
* to ensure that the stored nanosecond is in the range 0 to 999,999,999.
* For example, the following will result in the exactly the same instant:
* <pre>
* Instant.ofSeconds(3, 1);
* Instant.ofSeconds(4, -999999999);
* Instant.ofSeconds(2, 1000000001);
* </pre>
*
* @param epochSecond the number of seconds from 1970-01-01T00:00:00Z
* @param nanoAdjustment the nanosecond adjustment to the number of seconds, positive or negative
* @return an instant, not null
* @throws ArithmeticException if the calculation exceeds the supported range
*/
public static Instant ofEpochSecond(long epochSecond, long nanoAdjustment) {
long secs = DateTimes.safeAdd(epochSecond, DateTimes.floorDiv(nanoAdjustment, NANOS_PER_SECOND));
int nos = DateTimes.floorMod(nanoAdjustment, NANOS_PER_SECOND);
return create(secs, nos);
}
/**
* Obtains an instance of {@code Instant} using seconds from the
* epoch of 1970-01-01T00:00:00Z.
* <p>
* The seconds and nanoseconds are extracted from the specified {@code BigDecimal}.
* If the decimal is larger than {@code Long.MAX_VALUE} or has more than 9 decimal
* places then an exception is thrown.
*
* @param epochSecond the number of seconds from 1970-01-01T00:00:00Z, up to scale 9
* @return an instant, not null
* @throws ArithmeticException if the calculation exceeds the supported range
*/
public static Instant ofEpochSecond(BigDecimal epochSecond) {
DateTimes.checkNotNull(epochSecond, "Seconds must not be null");
return ofEpochNano(epochSecond.movePointRight(9).toBigIntegerExact());
}
//-----------------------------------------------------------------------
/**
* Obtains an instance of {@code Instant} using milliseconds from the
* epoch of 1970-01-01T00:00:00Z.
* <p>
* The seconds and nanoseconds are extracted from the specified milliseconds.
*
* @param epochMilli the number of milliseconds from 1970-01-01T00:00:00Z
* @return an instant, not null
*/
public static Instant ofEpochMilli(long epochMilli) {
long secs = DateTimes.floorDiv(epochMilli, 1000);
int mos = DateTimes.floorMod(epochMilli, 1000);
return create(secs, mos * 1000000);
}
//-----------------------------------------------------------------------
/**
* Obtains an instance of {@code Instant} using nanoseconds from the
* epoch of 1970-01-01T00:00:00Z.
* <p>
* The seconds and nanoseconds are extracted from the specified nanoseconds.
*
* @param epochNano the number of nanoseconds from 1970-01-01T00:00:00Z
* @return an instant, not null
*/
public static Instant ofEpochNano(long epochNano) {
long secs = DateTimes.floorDiv(epochNano, NANOS_PER_SECOND);
int nos = DateTimes.floorMod(epochNano, NANOS_PER_SECOND);
return create(secs, nos);
}
/**
* Obtains an instance of {@code Instant} using nanoseconds from the
* epoch of 1970-01-01T00:00:00Z.
* <p>
* The seconds and nanoseconds are extracted from the specified {@code BigInteger}.
* If the resulting seconds value is larger than {@code Long.MAX_VALUE} then an
* exception is thrown.
*
* @param epochNano the number of nanoseconds from 1970-01-01T00:00:00Z, not null
* @return an instant, not null
* @throws ArithmeticException if the calculation exceeds the supported range
*/
public static Instant ofEpochNano(BigInteger epochNano) {
DateTimes.checkNotNull(epochNano, "Nanos must not be null");
BigInteger[] divRem = epochNano.divideAndRemainder(BILLION);
if (divRem[0].bitLength() > 63) {
throw new ArithmeticException("Exceeds capacity of Duration: " + epochNano);
}
return ofEpochSecond(divRem[0].longValue(), divRem[1].intValue());
}
/**
* Obtains an instance of {@code Instant} from a calendrical.
* <p>
* A calendrical represents some form of date and time information.
* This factory converts the arbitrary calendrical to an instance of {@code Instant}.
*
* @param calendrical the calendrical to convert, not null
* @return the instant, not null
* @throws DateTimeException if unable to convert to an {@code Instant}
*/
public static Instant from(DateTime calendrical) {
long instantSecs = calendrical.get(INSTANT_SECONDS);
long nanoOfSecond;
try {
nanoOfSecond = calendrical.get(NANO_OF_SECOND);
} catch (DateTimeException ex) {
nanoOfSecond = 0;
}
return Instant.ofEpochSecond(instantSecs, nanoOfSecond);
}
//-----------------------------------------------------------------------
/**
* Obtains an instance of {@code Instant} from a text string such as
* {@code 2007-12-03T10:15:30:00}.
* <p>
* The string must represent a valid instant in UTC and is parsed using
* {@link DateTimeFormatters#isoInstant()}.
*
* @param text the text to parse, not null
* @return the parsed instant, not null
* @throws DateTimeParseException if the text cannot be parsed
*/
public static Instant parse(final CharSequence text) {
return DateTimeFormatters.isoInstant().parse(text, Instant.class);
}
//-----------------------------------------------------------------------
/**
* Obtains an instance of {@code Instant} using seconds and nanoseconds.
*
* @param seconds the length of the duration in seconds
* @param nanoOfSecond the nano-of-second, from 0 to 999,999,999
*/
private static Instant create(long seconds, int nanoOfSecond) {
if ((seconds | nanoOfSecond) == 0) {
return EPOCH;
}
return new Instant(seconds, nanoOfSecond);
}
/**
* Constructs an instance of {@code Instant} using seconds from the epoch of
* 1970-01-01T00:00:00Z and nanosecond fraction of second.
*
* @param epochSecond the number of seconds from 1970-01-01T00:00:00Z
* @param nanos the nanoseconds within the second, must be positive
*/
private Instant(long epochSecond, int nanos) {
super();
this.seconds = epochSecond;
this.nanos = nanos;
}
/**
* Resolves singletons.
*
* @return the resolved instance, not null
*/
private Object readResolve() {
return (seconds | nanos) == 0 ? EPOCH : this;
}
//-----------------------------------------------------------------------
/**
* Gets the number of seconds from the Java epoch of 1970-01-01T00:00:00Z.
* <p>
* The epoch second count is a simple incrementing count of seconds where
* second 0 is 1970-01-01T00:00:00Z.
* The nanosecond part of the day is returned by {@code getNanosOfSecond}.
*
* @return the seconds from the epoch of 1970-01-01T00:00:00Z
*/
public long getEpochSecond() {
return seconds;
}
/**
* Gets the number of nanoseconds, later along the time-line, from the start
* of the second.
* <p>
* The nanosecond-of-second value measures the total number of nanoseconds from
* the second returned by {@code getEpochSecond}.
*
* @return the nanoseconds within the second, always positive, never exceeds 999,999,999
*/
public int getNano() {
return nanos;
}
//-----------------------------------------------------------------------
/**
* Returns a copy of this instant with the specified duration added.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param duration the duration to add, positive or negative, not null
* @return an {@code Instant} based on this instant with the specified duration added, not null
* @throws ArithmeticException if the calculation exceeds the supported range
*/
public Instant plus(Duration duration) {
long secsToAdd = duration.getSeconds();
int nanosToAdd = duration.getNano();
if ((secsToAdd | nanosToAdd) == 0) {
return this;
}
return plus(secsToAdd, nanosToAdd);
}
//-----------------------------------------------------------------------
/**
* Returns a copy of this instant with the specified duration in seconds added.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param secondsToAdd the seconds to add, positive or negative
* @return an {@code Instant} based on this instant with the specified seconds added, not null
* @throws ArithmeticException if the calculation exceeds the supported range
*/
public Instant plusSeconds(long secondsToAdd) {
if (secondsToAdd == 0) {
return this;
}
return plus(secondsToAdd, 0);
}
/**
* Returns a copy of this instant with the specified duration in milliseconds added.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param millisToAdd the milliseconds to add, positive or negative
* @return an {@code Instant} based on this instant with the specified milliseconds added, not null
* @throws ArithmeticException if the calculation exceeds the supported range
*/
public Instant plusMillis(long millisToAdd) {
return plus(millisToAdd / 1000, (millisToAdd % 1000) * 1000000);
}
/**
* Returns a copy of this instant with the specified duration in nanoseconds added.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param nanosToAdd the nanoseconds to add, positive or negative
* @return an {@code Instant} based on this instant with the specified nanoseconds added, not null
* @throws ArithmeticException if the calculation exceeds the supported range
*/
public Instant plusNanos(long nanosToAdd) {
return plus(0, nanosToAdd);
}
/**
* Returns a copy of this instant with the specified duration added.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param secondsToAdd the seconds to add, positive or negative
* @param nanosToAdd the nanos to add, positive or negative
* @return an {@code Instant} based on this instant with the specified seconds added, not null
* @throws ArithmeticException if the calculation exceeds the supported range
*/
private Instant plus(long secondsToAdd, long nanosToAdd) {
if ((secondsToAdd | nanosToAdd) == 0) {
return this;
}
long epochSec = DateTimes.safeAdd(seconds, secondsToAdd);
epochSec = DateTimes.safeAdd(epochSec, nanosToAdd / NANOS_PER_SECOND);
nanosToAdd = nanosToAdd % NANOS_PER_SECOND;
long nanoAdjustment = nanos + nanosToAdd; // safe int+NANOS_PER_SECOND
return ofEpochSecond(epochSec, nanoAdjustment);
}
//-----------------------------------------------------------------------
/**
* Returns a copy of this instant with the specified duration subtracted.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param duration the duration to subtract, positive or negative, not null
* @return an {@code Instant} based on this instant with the specified duration subtracted, not null
* @throws ArithmeticException if the calculation exceeds the supported range
*/
public Instant minus(Duration duration) {
long secsToSubtract = duration.getSeconds();
int nanosToSubtract = duration.getNano();
if ((secsToSubtract | nanosToSubtract) == 0) {
return this;
}
long secs = DateTimes.safeSubtract(seconds, secsToSubtract);
long nanoAdjustment = ((long) nanos) - nanosToSubtract; // safe int+int
return ofEpochSecond(secs, nanoAdjustment);
}
//-----------------------------------------------------------------------
/**
* Returns a copy of this instant with the specified duration in seconds subtracted.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param secondsToSubtract the seconds to subtract, positive or negative
* @return an {@code Instant} based on this instant with the specified seconds subtracted, not null
* @throws ArithmeticException if the calculation exceeds the supported range
*/
public Instant minusSeconds(long secondsToSubtract) {
if (secondsToSubtract == Long.MIN_VALUE) {
return plusSeconds(Long.MAX_VALUE).plusSeconds(1);
}
return plusSeconds(-secondsToSubtract);
}
/**
* Returns a copy of this instant with the specified duration in milliseconds subtracted.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param millisToSubtract the milliseconds to subtract, positive or negative
* @return an {@code Instant} based on this instant with the specified milliseconds subtracted, not null
* @throws ArithmeticException if the calculation exceeds the supported range
*/
public Instant minusMillis(long millisToSubtract) {
if (millisToSubtract == Long.MIN_VALUE) {
return plusMillis(Long.MAX_VALUE).plusMillis(1);
}
return plusMillis(-millisToSubtract);
}
/**
* Returns a copy of this instant with the specified duration in nanoseconds subtracted.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param nanosToSubtract the nanoseconds to subtract, positive or negative
* @return an {@code Instant} based on this instant with the specified nanoseconds subtracted, not null
* @throws ArithmeticException if the calculation exceeds the supported range
*/
public Instant minusNanos(long nanosToSubtract) {
if (nanosToSubtract == Long.MIN_VALUE) {
return plusNanos(Long.MAX_VALUE).plusNanos(1);
}
return plusNanos(-nanosToSubtract);
}
//-----------------------------------------------------------------------
@Override
public DateTimeValueRange range(DateTimeField field) {
if (field instanceof LocalDateTimeField) {
return field.range();
}
return field.doRange(this);
}
@Override
public long get(DateTimeField field) {
if (field instanceof LocalDateTimeField) {
switch ((LocalDateTimeField) field) {
case NANO_OF_SECOND: return nanos;
case MICRO_OF_SECOND: return nanos / 1000;
case MILLI_OF_SECOND: return nanos / 1000000;
case INSTANT_SECONDS: return seconds;
}
throw new DateTimeException("Unsupported field: " + field.getName());
}
return field.doGet(this);
}
@Override
public Instant with(DateTimeField field, long newValue) {
if (field instanceof LocalDateTimeField) {
LocalDateTimeField f = (LocalDateTimeField) field;
f.checkValidValue(newValue);
switch (f) {
case MILLI_OF_SECOND: return (newValue != nanos ? create(seconds, (int) newValue * 1000000) : this);
case MICRO_OF_SECOND: return (newValue != nanos ? create(seconds, (int) newValue * 1000) : this);
case NANO_OF_SECOND: return (newValue != nanos ? create(seconds, (int) newValue) : this);
case INSTANT_SECONDS: return (newValue != seconds ? create(newValue, nanos) : this);
}
throw new DateTimeException("Unsupported field: " + field.getName());
}
return field.doSet(this, newValue);
}
@Override
public Instant plus(long periodAmount, PeriodUnit unit) {
if (unit instanceof LocalPeriodUnit) {
switch ((LocalPeriodUnit) unit) {
case NANOS: return plusNanos(periodAmount);
case MICROS: return plus(periodAmount / 1000000, (periodAmount % 1000000) * 1000);
case MILLIS: return plusMillis(periodAmount);
case SECONDS: return plusSeconds(periodAmount);
case MINUTES: return plusSeconds(DateTimes.safeMultiply(periodAmount, DateTimes.SECONDS_PER_MINUTE));
case HOURS: return plusSeconds(DateTimes.safeMultiply(periodAmount, DateTimes.SECONDS_PER_HOUR));
case HALF_DAYS: return plusSeconds(DateTimes.safeMultiply(periodAmount, DateTimes.SECONDS_PER_DAY / 2));
case DAYS: return plusSeconds(DateTimes.safeMultiply(periodAmount, DateTimes.SECONDS_PER_DAY));
}
throw new DateTimeException("Unsupported unit: " + unit.getName());
}
return unit.doAdd(this, periodAmount);
}
@Override
public Instant minus(long periodAmount, PeriodUnit unit) {
return plus(DateTimes.safeNegate(periodAmount), unit);
}
//-------------------------------------------------------------------------
/**
* Extracts date-time information in a generic way.
* <p>
* This method exists to fulfill the {@link DateTime} interface.
* This implementation always returns null.
*
* @param <R> the type to extract
* @param type the type to extract, null returns null
* @return the extracted object, null if unable to extract
*/
@Override
public <T> T extract(Class<T> type) {
return null;
}
//-----------------------------------------------------------------------
/**
* Converts this instant to the number of seconds from the epoch
* of 1970-01-01T00:00:00Z expressed as a {@code BigDecimal}.
*
* @return the number of seconds since the epoch of 1970-01-01T00:00:00Z, scale 9, not null
*/
public BigDecimal toEpochSecond() {
return BigDecimal.valueOf(seconds).add(BigDecimal.valueOf(nanos, 9));
}
/**
* Converts this instant to the number of nanoseconds from the epoch
* of 1970-01-01T00:00:00Z expressed as a {@code BigInteger}.
*
* @return the number of nanoseconds since the epoch of 1970-01-01T00:00:00Z, not null
*/
public BigInteger toEpochNano() {
return BigInteger.valueOf(seconds).multiply(BILLION).add(BigInteger.valueOf(nanos));
}
//-----------------------------------------------------------------------
/**
* Converts this instant to the number of milliseconds from the epoch
* of 1970-01-01T00:00:00Z.
* <p>
* If this instant represents a point on the time-line too far in the future
* or past to fit in a {@code long} milliseconds, then an exception is thrown.
* <p>
* If this instant has greater than millisecond precision, then the conversion
* will drop any excess precision information as though the amount in nanoseconds
* was subject to integer division by one million.
*
* @return the number of milliseconds since the epoch of 1970-01-01T00:00:00Z
* @throws ArithmeticException if the calculation exceeds the supported range
*/
public long toEpochMilli() {
long millis = DateTimes.safeMultiply(seconds, 1000);
return millis + nanos / 1000000;
}
//-----------------------------------------------------------------------
/**
* Compares this instant to the specified instant.
* <p>
* The comparison is based on the time-line position of the instants.
*
* @param otherInstant the other instant to compare to, not null
* @return the comparator value, negative if less, positive if greater
* @throws NullPointerException if otherInstant is null
*/
public int compareTo(Instant otherInstant) {
int cmp = DateTimes.safeCompare(seconds, otherInstant.seconds);
if (cmp != 0) {
return cmp;
}
return DateTimes.safeCompare(nanos, otherInstant.nanos);
}
/**
* Checks if this instant is after the specified instant.
* <p>
* The comparison is based on the time-line position of the instants.
*
* @param otherInstant the other instant to compare to, not null
* @return true if this instant is after the specified instant
* @throws NullPointerException if otherInstant is null
*/
public boolean isAfter(Instant otherInstant) {
return compareTo(otherInstant) > 0;
}
/**
* Checks if this instant is before the specified instant.
* <p>
* The comparison is based on the time-line position of the instants.
*
* @param otherInstant the other instant to compare to, not null
* @return true if this instant is before the specified instant
* @throws NullPointerException if otherInstant is null
*/
public boolean isBefore(Instant otherInstant) {
return compareTo(otherInstant) < 0;
}
//-----------------------------------------------------------------------
/**
* Checks if this instant is equal to the specified instant.
* <p>
* The comparison is based on the time-line position of the instants.
*
* @param otherInstant the other instant, null returns false
* @return true if the other instant is equal to this one
*/
@Override
public boolean equals(Object otherInstant) {
if (this == otherInstant) {
return true;
}
if (otherInstant instanceof Instant) {
Instant other = (Instant) otherInstant;
return this.seconds == other.seconds &&
this.nanos == other.nanos;
}
return false;
}
/**
* Returns a hash code for this instant.
*
* @return a suitable hash code
*/
@Override
public int hashCode() {
return ((int) (seconds ^ (seconds >>> 32))) + 51 * nanos;
}
//-----------------------------------------------------------------------
/**
* A string representation of this instant using ISO-8601 representation.
* <p>
* The format used is the same as {@link DateTimeFormatters#isoInstant()}.
*
* @return an ISO-8601 representation of this instant, not null
*/
@Override
public String toString() {
return DateTimeFormatters.isoInstant().print(this);
}
}
|
Minor fixes to Instant implementation
|
src/main/java/javax/time/Instant.java
|
Minor fixes to Instant implementation
|
<ide><path>rc/main/java/javax/time/Instant.java
<ide> * @throws ArithmeticException if the calculation exceeds the supported range
<ide> */
<ide> public Instant plusSeconds(long secondsToAdd) {
<del> if (secondsToAdd == 0) {
<del> return this;
<del> }
<ide> return plus(secondsToAdd, 0);
<ide> }
<ide>
<ide> LocalDateTimeField f = (LocalDateTimeField) field;
<ide> f.checkValidValue(newValue);
<ide> switch (f) {
<del> case MILLI_OF_SECOND: return (newValue != nanos ? create(seconds, (int) newValue * 1000000) : this);
<del> case MICRO_OF_SECOND: return (newValue != nanos ? create(seconds, (int) newValue * 1000) : this);
<add> case MILLI_OF_SECOND: {
<add> int nval = (int) newValue * 1000000;
<add> return (nval != nanos ? create(seconds, nval) : this);
<add> }
<add> case MICRO_OF_SECOND: {
<add> int nval = (int) newValue * 1000;
<add> return (nval != nanos ? create(seconds, nval) : this);
<add> }
<ide> case NANO_OF_SECOND: return (newValue != nanos ? create(seconds, (int) newValue) : this);
<ide> case INSTANT_SECONDS: return (newValue != seconds ? create(newValue, nanos) : this);
<ide> }
|
|
Java
|
mpl-2.0
|
c7d2b969266ed6f6e3fa254cc85884b0e7333742
| 0 |
Helioviewer-Project/JHelioviewer-SWHV,Helioviewer-Project/JHelioviewer-SWHV,Helioviewer-Project/JHelioviewer-SWHV,Helioviewer-Project/JHelioviewer-SWHV,Helioviewer-Project/JHelioviewer-SWHV
|
package org.helioviewer.jhv.plugins.swhvhekplugin;
import java.awt.Color;
import java.awt.Component;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.swing.ImageIcon;
import org.helioviewer.jhv.base.astronomy.Position;
import org.helioviewer.jhv.base.astronomy.Sun;
import org.helioviewer.jhv.base.math.Mat4d;
import org.helioviewer.jhv.base.math.Quatd;
import org.helioviewer.jhv.base.math.Vec2d;
import org.helioviewer.jhv.base.math.Vec3d;
import org.helioviewer.jhv.camera.GL3DViewport;
import org.helioviewer.jhv.data.datatype.event.JHVCoordinateSystem;
import org.helioviewer.jhv.data.datatype.event.JHVEvent;
import org.helioviewer.jhv.data.datatype.event.JHVEventParameter;
import org.helioviewer.jhv.data.datatype.event.JHVPositionInformation;
import org.helioviewer.jhv.display.Displayer;
import org.helioviewer.jhv.gui.ImageViewerGui;
import org.helioviewer.jhv.gui.UIGlobals;
import org.helioviewer.jhv.layers.Layers;
import org.helioviewer.jhv.opengl.GLHelper;
import org.helioviewer.jhv.opengl.GLTexture;
import org.helioviewer.jhv.renderable.gui.AbstractRenderable;
import com.jogamp.opengl.GL2;
import com.jogamp.opengl.util.awt.TextRenderer;
public class SWHVHEKPluginRenderable extends AbstractRenderable {
private static final SWHVHEKPopupController controller = new SWHVHEKPopupController();
private static final double LINEWIDTH = 0.5;
private static final double LINEWIDTH_CACTUS = 1.01;
private static final double LINEWIDTH_HI = 1;
private static HashMap<String, GLTexture> iconCacheId = new HashMap<String, GLTexture>();
private final static double ICON_SIZE = 0.1;
private final static double ICON_SIZE_HIGHLIGHTED = 0.16;
private final static int LEFT_MARGIN_TEXT = 10;
private final static int RIGHT_MARGIN_TEXT = 10;
private final static int TOP_MARGIN_TEXT = 5;
private final static int BOTTOM_MARGIN_TEXT = 5;
private final static int MOUSE_OFFSET_X = 25;
private final static int MOUSE_OFFSET_Y = 25;
private void bindTexture(GL2 gl, String key, ImageIcon icon) {
GLTexture tex = iconCacheId.get(key);
if (tex == null) {
BufferedImage bi = new BufferedImage(icon.getIconWidth(), icon.getIconHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics graph = bi.createGraphics();
icon.paintIcon(null, graph, 0, 0);
graph.dispose();
tex = new GLTexture(gl);
tex.bind(gl, GL2.GL_TEXTURE_2D, GL2.GL_TEXTURE0);
tex.copyBufferedImage2D(gl, bi);
iconCacheId.put(key, tex);
}
tex.bind(gl, GL2.GL_TEXTURE_2D, GL2.GL_TEXTURE0);
}
private void interPolatedDraw(GL2 gl, int mres, double r_start, double r_end, double t_start, double t_end, Quatd q) {
gl.glBegin(GL2.GL_LINE_STRIP);
{
for (int i = 0; i <= mres; i++) {
double alpha = 1. - i / (double) mres;
double r = alpha * r_start + (1 - alpha) * (r_end);
double theta = alpha * t_start + (1 - alpha) * (t_end);
Vec3d res = q.rotateInverseVector(new Vec3d(r * Math.cos(theta), r * Math.sin(theta), 0));
gl.glVertex3f((float) res.x, (float) res.y, (float) res.z);
}
}
gl.glEnd();
}
private final int texCoordHelpers[][] = { { 0, 0 }, { 1, 0 }, { 1, 1 }, { 0, 1 } };;
private void drawCactusArc(GL2 gl, JHVEvent evt, Date timestamp) {
Map<String, JHVEventParameter> params = evt.getAllEventParameters();
double angularWidthDegree = SWHVHEKData.readCMEAngularWidthDegree(params);
double angularWidth = Math.toRadians(angularWidthDegree);
double principalAngleDegree = SWHVHEKData.readCMEPrincipalAngleDegree(params);
double principalAngle = Math.toRadians(principalAngleDegree);
double speed = SWHVHEKData.readCMESpeed(params);
double factor = Sun.RadiusMeter;
double distSunBegin = 2.4;
double distSun = distSunBegin + speed * (timestamp.getTime() - evt.getStartDate().getTime()) / factor;
int lineResolution = 2;
Date date = new Date((evt.getStartDate().getTime() + evt.getEndDate().getTime()) / 2);
Position.Latitudinal p = Sun.getEarth(date);
Quatd q = new Quatd(p.lat, p.lon);
double thetaStart = principalAngle - angularWidth / 2.;
double thetaEnd = principalAngle + angularWidth / 2.;
Color color = evt.getEventRelationShip().getRelationshipColor();
if (color == null) {
color = evt.getColor();
}
gl.glColor3f(0f, 0f, 0f);
GLHelper.lineWidth(gl, LINEWIDTH_CACTUS * 1.2);
int angularResolution = (int) (angularWidthDegree / 4);
interPolatedDraw(gl, angularResolution, distSun, distSun, thetaStart, principalAngle, q);
interPolatedDraw(gl, angularResolution, distSun, distSun, principalAngle, thetaEnd, q);
gl.glColor3f(color.getRed() / 255f, color.getGreen() / 255f, color.getBlue() / 255f);
GLHelper.lineWidth(gl, LINEWIDTH_CACTUS);
interPolatedDraw(gl, angularResolution, distSun, distSun, thetaStart, principalAngle, q);
interPolatedDraw(gl, angularResolution, distSun, distSun, principalAngle, thetaEnd, q);
interPolatedDraw(gl, lineResolution, distSunBegin, distSun + 0.05, thetaStart, thetaStart, q);
interPolatedDraw(gl, lineResolution, distSunBegin, distSun + 0.05, principalAngle, principalAngle, q);
interPolatedDraw(gl, lineResolution, distSunBegin, distSun + 0.05, thetaEnd, thetaEnd, q);
String type = evt.getJHVEventType().getEventType();
bindTexture(gl, type, evt.getIcon());
gl.glTexParameteri(GL2.GL_TEXTURE_2D, GL2.GL_TEXTURE_MAG_FILTER, GL2.GL_LINEAR);
double sz = ICON_SIZE;
if (evt.isHighlighted()) {
sz = ICON_SIZE_HIGHLIGHTED;
}
gl.glColor3f(1, 1, 1);
gl.glEnable(GL2.GL_CULL_FACE);
gl.glEnable(GL2.GL_TEXTURE_2D);
gl.glBegin(GL2.GL_QUADS);
{
for (int i = 0; i < texCoordHelpers.length; i++) {
int[] el = texCoordHelpers[i];
double deltatheta = sz / distSun * (el[1] * 2 - 1);
double deltar = sz * (el[0] * 2 - 1);
double r = distSun + deltar;
double theta = principalAngle + deltatheta;
Vec3d res = q.rotateInverseVector(new Vec3d(r * Math.cos(theta), r * Math.sin(theta), 0));
gl.glTexCoord2f(el[0], el[1]);
gl.glVertex3f((float) res.x, (float) res.y, (float) res.z);
}
}
gl.glEnd();
gl.glDisable(GL2.GL_TEXTURE_2D);
gl.glDisable(GL2.GL_CULL_FACE);
}
private void drawPolygon(GL2 gl, JHVEvent evt, Date timestamp) {
HashMap<JHVCoordinateSystem, JHVPositionInformation> pi = evt.getPositioningInformation();
if (!pi.containsKey(JHVCoordinateSystem.JHV)) {
return;
}
JHVPositionInformation el = pi.get(JHVCoordinateSystem.JHV);
List<Vec3d> points = el.getBoundCC();
if (points == null || points.size() == 0) {
points = el.getBoundBox();
if (points == null || points.size() == 0) {
return;
}
}
Color color = evt.getEventRelationShip().getRelationshipColor();
if (color == null) {
color = evt.getColor();
}
gl.glColor3f(color.getRed() / 255f, color.getGreen() / 255f, color.getBlue() / 255f);
GLHelper.lineWidth(gl, evt.isHighlighted() ? LINEWIDTH_HI : LINEWIDTH);
// draw bounds
Vec3d oldBoundaryPoint3d = null;
for (Vec3d point : points) {
int divpoints = 10;
gl.glBegin(GL2.GL_LINE_STRIP);
if (oldBoundaryPoint3d != null) {
for (int j = 0; j <= divpoints; j++) {
double alpha = 1. - j / (double) divpoints;
double xnew = alpha * oldBoundaryPoint3d.x + (1 - alpha) * point.x;
double ynew = alpha * oldBoundaryPoint3d.y + (1 - alpha) * point.y;
double znew = alpha * oldBoundaryPoint3d.z + (1 - alpha) * point.z;
double r = Math.sqrt(xnew * xnew + ynew * ynew + znew * znew);
gl.glVertex3f((float) (xnew / r), (float) -(ynew / r), (float) (znew / r));
}
}
gl.glEnd();
oldBoundaryPoint3d = point;
}
}
private void drawIcon(GL2 gl, JHVEvent evt, Date timestamp) {
String type = evt.getJHVEventType().getEventType();
HashMap<JHVCoordinateSystem, JHVPositionInformation> pi = evt.getPositioningInformation();
if (pi.containsKey(JHVCoordinateSystem.JHV)) {
JHVPositionInformation el = pi.get(JHVCoordinateSystem.JHV);
if (el.centralPoint() != null) {
Vec3d pt = el.centralPoint();
bindTexture(gl, type, evt.getIcon());
if (evt.isHighlighted()) {
this.drawImage3d(gl, pt.x, pt.y, pt.z, ICON_SIZE_HIGHLIGHTED, ICON_SIZE_HIGHLIGHTED);
} else {
this.drawImage3d(gl, pt.x, pt.y, pt.z, ICON_SIZE, ICON_SIZE);
}
}
}
}
private void drawImage3d(GL2 gl, double x, double y, double z, double width, double height) {
y = -y;
gl.glTexParameteri(GL2.GL_TEXTURE_2D, GL2.GL_TEXTURE_MAG_FILTER, GL2.GL_LINEAR);
gl.glColor3f(1, 1, 1);
double width2 = width / 2.;
double height2 = height / 2.;
Vec3d sourceDir = new Vec3d(0, 0, 1);
Vec3d targetDir = new Vec3d(x, y, z);
Vec3d axis = sourceDir.cross(targetDir);
axis.normalize();
Mat4d r = Mat4d.rotation(Math.atan2(x, z), Vec3d.YAxis);
r.rotate(-Math.asin(y / targetDir.length()), Vec3d.XAxis);
Vec3d p0 = new Vec3d(-width2, -height2, 0);
Vec3d p1 = new Vec3d(-width2, height2, 0);
Vec3d p2 = new Vec3d(width2, height2, 0);
Vec3d p3 = new Vec3d(width2, -height2, 0);
p0 = r.multiply(p0);
p1 = r.multiply(p1);
p2 = r.multiply(p2);
p3 = r.multiply(p3);
p0.add(targetDir);
p1.add(targetDir);
p2.add(targetDir);
p3.add(targetDir);
gl.glEnable(GL2.GL_CULL_FACE);
gl.glEnable(GL2.GL_TEXTURE_2D);
gl.glBegin(GL2.GL_QUADS);
{
gl.glTexCoord2f(1, 1);
gl.glVertex3f((float) p3.x, (float) p3.y, (float) p3.z);
gl.glTexCoord2f(1, 0);
gl.glVertex3f((float) p2.x, (float) p2.y, (float) p2.z);
gl.glTexCoord2f(0, 0);
gl.glVertex3f((float) p1.x, (float) p1.y, (float) p1.z);
gl.glTexCoord2f(0, 1);
gl.glVertex3f((float) p0.x, (float) p0.y, (float) p0.z);
}
gl.glEnd();
gl.glDisable(GL2.GL_TEXTURE_2D);
gl.glDisable(GL2.GL_CULL_FACE);
}
private static final double vpScale = 0.019;
private TextRenderer textRenderer;
private Font font;
private float oldFontSize = -1;
public void drawText(GL2 gl, JHVEvent evt, Point pt) {
int height = Displayer.getGLHeight();
int width = Displayer.getGLWidth();
float fontSize = (int) (height * vpScale);
if (textRenderer == null || fontSize != oldFontSize) {
oldFontSize = fontSize;
font = UIGlobals.UIFontRoboto.deriveFont(fontSize);
if (textRenderer != null) {
textRenderer.dispose();
}
textRenderer = new TextRenderer(font, true, true);
textRenderer.setUseVertexArrays(true);
textRenderer.setSmoothing(false);
textRenderer.setColor(Color.WHITE);
}
textRenderer.beginRendering(width, height, true);
Map<String, JHVEventParameter> params = evt.getVisibleEventParameters();
Vec2d bd = new Vec2d(0, 0);
int ct = 0;
for (Entry<String, JHVEventParameter> entry : params.entrySet()) {
String txt = entry.getValue().getParameterDisplayName() + " : " + entry.getValue().getParameterValue();
Rectangle2D bound = textRenderer.getBounds(txt);
if (bd.x < bound.getWidth())
bd.x = bound.getWidth();
ct++;
}
bd.y = fontSize * 1.1 * (ct);
Point textInit = new Point(pt.x, pt.y);
float w = (float) (bd.x + LEFT_MARGIN_TEXT + RIGHT_MARGIN_TEXT);
float h = (float) (bd.y + BOTTOM_MARGIN_TEXT + TOP_MARGIN_TEXT);
// Correct if out of view
if (w + pt.x + MOUSE_OFFSET_X - LEFT_MARGIN_TEXT > width) {
textInit.x -= (w + pt.x + MOUSE_OFFSET_X - LEFT_MARGIN_TEXT - width);
}
if (h + pt.y + MOUSE_OFFSET_Y - fontSize - TOP_MARGIN_TEXT > height) {
textInit.y -= (h + pt.y + MOUSE_OFFSET_Y - fontSize - TOP_MARGIN_TEXT - height);
}
float left = textInit.x + MOUSE_OFFSET_X - LEFT_MARGIN_TEXT;
float bottom = textInit.y + MOUSE_OFFSET_Y - fontSize - TOP_MARGIN_TEXT;
gl.glColor4f(0.5f, 0.5f, 0.5f, 0.75f);
gl.glDisable(GL2.GL_TEXTURE_2D);
gl.glPushMatrix();
gl.glLoadIdentity();
{
gl.glBegin(GL2.GL_QUADS);
gl.glVertex2f(left, height - bottom);
gl.glVertex2f(left, height - bottom - h);
gl.glVertex2f(left + w, height - bottom - h);
gl.glVertex2f(left + w, height - bottom);
gl.glEnd();
}
gl.glPopMatrix();
gl.glEnable(GL2.GL_TEXTURE_2D);
textRenderer.setColor(Color.WHITE);
int deltaY = MOUSE_OFFSET_Y;
for (Entry<String, JHVEventParameter> entry : params.entrySet()) {
String txt = entry.getValue().getParameterDisplayName() + " : " + entry.getValue().getParameterValue();
textRenderer.draw(txt, textInit.x + MOUSE_OFFSET_X, height - textInit.y - deltaY);
deltaY += fontSize * 1.1;
}
textRenderer.endRendering();
gl.glDisable(GL2.GL_TEXTURE_2D);
}
@Override
public void render(GL2 gl, GL3DViewport vp) {
if (isVisible[vp.getIndex()]) {
ArrayList<JHVEvent> eventsToDraw = SWHVHEKData.getSingletonInstance().getActiveEvents(controller.currentTime);
for (JHVEvent evt : eventsToDraw) {
if (evt.getName().equals("Coronal Mass Ejection")) {
drawCactusArc(gl, evt, controller.currentTime);
} else {
drawPolygon(gl, evt, controller.currentTime);
gl.glDisable(GL2.GL_DEPTH_TEST);
drawIcon(gl, evt, controller.currentTime);
gl.glEnable(GL2.GL_DEPTH_TEST);
}
}
SWHVHEKSettings.resetCactusColor();
}
}
@Override
public void renderFloat(GL2 gl, GL3DViewport vp) {
if (isVisible[vp.getIndex()]) {
if (SWHVHEKPopupController.mouseOverJHVEvent != null) {
drawText(gl, SWHVHEKPopupController.mouseOverJHVEvent, SWHVHEKPopupController.mouseOverPosition);
}
}
}
@Override
public void remove(GL2 gl) {
dispose(gl);
ImageViewerGui.getInputController().removePlugin(controller);
}
@Override
public Component getOptionsPanel() {
return null;
}
@Override
public String getName() {
return "SWEK events";
}
@Override
public void setVisible(boolean isVisible) {
super.setVisible(isVisible);
if (isVisible) {
controller.timeChanged(Layers.addTimeListener(controller));
ImageViewerGui.getInputController().addPlugin(controller);
} else {
ImageViewerGui.getInputController().removePlugin(controller);
Layers.removeTimeListener(controller);
}
}
@Override
public String getTimeString() {
return null;
}
@Override
public boolean isDeletable() {
return false;
}
@Override
public void init(GL2 gl) {
setVisible(true);
}
@Override
public void dispose(GL2 gl) {
for (GLTexture el : iconCacheId.values()) {
el.delete(gl);
}
iconCacheId.clear();
}
@Override
public void renderMiniview(GL2 gl, GL3DViewport vp) {
}
}
|
src/plugins/swhvhekplugin-3d/src/org/helioviewer/jhv/plugins/swhvhekplugin/SWHVHEKPluginRenderable.java
|
package org.helioviewer.jhv.plugins.swhvhekplugin;
import java.awt.Color;
import java.awt.Component;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.swing.ImageIcon;
import org.helioviewer.jhv.base.astronomy.Position;
import org.helioviewer.jhv.base.astronomy.Sun;
import org.helioviewer.jhv.base.math.Mat4d;
import org.helioviewer.jhv.base.math.Quatd;
import org.helioviewer.jhv.base.math.Vec2d;
import org.helioviewer.jhv.base.math.Vec3d;
import org.helioviewer.jhv.camera.GL3DViewport;
import org.helioviewer.jhv.data.datatype.event.JHVCoordinateSystem;
import org.helioviewer.jhv.data.datatype.event.JHVEvent;
import org.helioviewer.jhv.data.datatype.event.JHVEventParameter;
import org.helioviewer.jhv.data.datatype.event.JHVPositionInformation;
import org.helioviewer.jhv.display.Displayer;
import org.helioviewer.jhv.gui.ImageViewerGui;
import org.helioviewer.jhv.gui.UIGlobals;
import org.helioviewer.jhv.layers.Layers;
import org.helioviewer.jhv.opengl.GLHelper;
import org.helioviewer.jhv.opengl.GLTexture;
import org.helioviewer.jhv.renderable.gui.AbstractRenderable;
import com.jogamp.opengl.GL2;
import com.jogamp.opengl.util.awt.TextRenderer;
public class SWHVHEKPluginRenderable extends AbstractRenderable {
private static final SWHVHEKPopupController controller = new SWHVHEKPopupController();
private static final double LINEWIDTH = 0.5;
private static final double LINEWIDTH_CACTUS = 1.01;
private static final double LINEWIDTH_HI = 1;
private static HashMap<String, GLTexture> iconCacheId = new HashMap<String, GLTexture>();
private final static double ICON_SIZE = 0.1;
private final static double ICON_SIZE_HIGHLIGHTED = 0.16;
private final static int LEFT_MARGIN_TEXT = 10;
private final static int RIGHT_MARGIN_TEXT = 10;
private final static int TOP_MARGIN_TEXT = 5;
private final static int BOTTOM_MARGIN_TEXT = 5;
private final static int MOUSE_OFFSET_X = 45;
private final static int MOUSE_OFFSET_Y = 45;
private JHVEvent highLightedEvent = null;
private void bindTexture(GL2 gl, String key, ImageIcon icon) {
GLTexture tex = iconCacheId.get(key);
if (tex == null) {
BufferedImage bi = new BufferedImage(icon.getIconWidth(), icon.getIconHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics graph = bi.createGraphics();
icon.paintIcon(null, graph, 0, 0);
graph.dispose();
tex = new GLTexture(gl);
tex.bind(gl, GL2.GL_TEXTURE_2D, GL2.GL_TEXTURE0);
tex.copyBufferedImage2D(gl, bi);
iconCacheId.put(key, tex);
}
tex.bind(gl, GL2.GL_TEXTURE_2D, GL2.GL_TEXTURE0);
}
private void interPolatedDraw(GL2 gl, int mres, double r_start, double r_end, double t_start, double t_end, Quatd q) {
gl.glBegin(GL2.GL_LINE_STRIP);
{
for (int i = 0; i <= mres; i++) {
double alpha = 1. - i / (double) mres;
double r = alpha * r_start + (1 - alpha) * (r_end);
double theta = alpha * t_start + (1 - alpha) * (t_end);
Vec3d res = q.rotateInverseVector(new Vec3d(r * Math.cos(theta), r * Math.sin(theta), 0));
gl.glVertex3f((float) res.x, (float) res.y, (float) res.z);
}
}
gl.glEnd();
}
private final int texCoordHelpers[][] = { { 0, 0 }, { 1, 0 }, { 1, 1 }, { 0, 1 } };;
private void drawCactusArc(GL2 gl, JHVEvent evt, Date timestamp) {
Map<String, JHVEventParameter> params = evt.getAllEventParameters();
double angularWidthDegree = SWHVHEKData.readCMEAngularWidthDegree(params);
double angularWidth = Math.toRadians(angularWidthDegree);
double principalAngleDegree = SWHVHEKData.readCMEPrincipalAngleDegree(params);
double principalAngle = Math.toRadians(principalAngleDegree);
double speed = SWHVHEKData.readCMESpeed(params);
double factor = Sun.RadiusMeter;
double distSunBegin = 2.4;
double distSun = distSunBegin + speed * (timestamp.getTime() - evt.getStartDate().getTime()) / factor;
int lineResolution = 2;
Date date = new Date((evt.getStartDate().getTime() + evt.getEndDate().getTime()) / 2);
Position.Latitudinal p = Sun.getEarth(date);
Quatd q = new Quatd(p.lat, p.lon);
double thetaStart = principalAngle - angularWidth / 2.;
double thetaEnd = principalAngle + angularWidth / 2.;
Color color = evt.getEventRelationShip().getRelationshipColor();
if (color == null) {
color = evt.getColor();
}
gl.glColor3f(0f, 0f, 0f);
GLHelper.lineWidth(gl, LINEWIDTH_CACTUS * 1.2);
int angularResolution = (int) (angularWidthDegree / 4);
interPolatedDraw(gl, angularResolution, distSun, distSun, thetaStart, principalAngle, q);
interPolatedDraw(gl, angularResolution, distSun, distSun, principalAngle, thetaEnd, q);
gl.glColor3f(color.getRed() / 255f, color.getGreen() / 255f, color.getBlue() / 255f);
GLHelper.lineWidth(gl, LINEWIDTH_CACTUS);
interPolatedDraw(gl, angularResolution, distSun, distSun, thetaStart, principalAngle, q);
interPolatedDraw(gl, angularResolution, distSun, distSun, principalAngle, thetaEnd, q);
interPolatedDraw(gl, lineResolution, distSunBegin, distSun + 0.05, thetaStart, thetaStart, q);
interPolatedDraw(gl, lineResolution, distSunBegin, distSun + 0.05, principalAngle, principalAngle, q);
interPolatedDraw(gl, lineResolution, distSunBegin, distSun + 0.05, thetaEnd, thetaEnd, q);
String type = evt.getJHVEventType().getEventType();
bindTexture(gl, type, evt.getIcon());
gl.glTexParameteri(GL2.GL_TEXTURE_2D, GL2.GL_TEXTURE_MAG_FILTER, GL2.GL_LINEAR);
double sz = ICON_SIZE;
if (evt.isHighlighted()) {
sz = ICON_SIZE_HIGHLIGHTED;
}
gl.glColor3f(1, 1, 1);
gl.glEnable(GL2.GL_CULL_FACE);
gl.glEnable(GL2.GL_TEXTURE_2D);
gl.glBegin(GL2.GL_QUADS);
{
for (int i = 0; i < texCoordHelpers.length; i++) {
int[] el = texCoordHelpers[i];
double deltatheta = sz / distSun * (el[1] * 2 - 1);
double deltar = sz * (el[0] * 2 - 1);
double r = distSun + deltar;
double theta = principalAngle + deltatheta;
Vec3d res = q.rotateInverseVector(new Vec3d(r * Math.cos(theta), r * Math.sin(theta), 0));
gl.glTexCoord2f(el[0], el[1]);
gl.glVertex3f((float) res.x, (float) res.y, (float) res.z);
}
}
gl.glEnd();
gl.glDisable(GL2.GL_TEXTURE_2D);
gl.glDisable(GL2.GL_CULL_FACE);
}
private void drawPolygon(GL2 gl, JHVEvent evt, Date timestamp) {
HashMap<JHVCoordinateSystem, JHVPositionInformation> pi = evt.getPositioningInformation();
if (!pi.containsKey(JHVCoordinateSystem.JHV)) {
return;
}
JHVPositionInformation el = pi.get(JHVCoordinateSystem.JHV);
List<Vec3d> points = el.getBoundCC();
if (points == null || points.size() == 0) {
points = el.getBoundBox();
if (points == null || points.size() == 0) {
return;
}
}
Color color = evt.getEventRelationShip().getRelationshipColor();
if (color == null) {
color = evt.getColor();
}
gl.glColor3f(color.getRed() / 255f, color.getGreen() / 255f, color.getBlue() / 255f);
GLHelper.lineWidth(gl, evt.isHighlighted() ? LINEWIDTH_HI : LINEWIDTH);
// draw bounds
Vec3d oldBoundaryPoint3d = null;
for (Vec3d point : points) {
int divpoints = 10;
gl.glBegin(GL2.GL_LINE_STRIP);
if (oldBoundaryPoint3d != null) {
for (int j = 0; j <= divpoints; j++) {
double alpha = 1. - j / (double) divpoints;
double xnew = alpha * oldBoundaryPoint3d.x + (1 - alpha) * point.x;
double ynew = alpha * oldBoundaryPoint3d.y + (1 - alpha) * point.y;
double znew = alpha * oldBoundaryPoint3d.z + (1 - alpha) * point.z;
double r = Math.sqrt(xnew * xnew + ynew * ynew + znew * znew);
gl.glVertex3f((float) (xnew / r), (float) -(ynew / r), (float) (znew / r));
}
}
gl.glEnd();
oldBoundaryPoint3d = point;
}
}
private void drawIcon(GL2 gl, JHVEvent evt, Date timestamp) {
String type = evt.getJHVEventType().getEventType();
HashMap<JHVCoordinateSystem, JHVPositionInformation> pi = evt.getPositioningInformation();
if (pi.containsKey(JHVCoordinateSystem.JHV)) {
JHVPositionInformation el = pi.get(JHVCoordinateSystem.JHV);
if (el.centralPoint() != null) {
Vec3d pt = el.centralPoint();
bindTexture(gl, type, evt.getIcon());
if (evt.isHighlighted()) {
this.drawImage3d(gl, pt.x, pt.y, pt.z, ICON_SIZE_HIGHLIGHTED, ICON_SIZE_HIGHLIGHTED);
} else {
this.drawImage3d(gl, pt.x, pt.y, pt.z, ICON_SIZE, ICON_SIZE);
}
}
}
}
private void drawImage3d(GL2 gl, double x, double y, double z, double width, double height) {
y = -y;
gl.glTexParameteri(GL2.GL_TEXTURE_2D, GL2.GL_TEXTURE_MAG_FILTER, GL2.GL_LINEAR);
gl.glColor3f(1, 1, 1);
double width2 = width / 2.;
double height2 = height / 2.;
Vec3d sourceDir = new Vec3d(0, 0, 1);
Vec3d targetDir = new Vec3d(x, y, z);
Vec3d axis = sourceDir.cross(targetDir);
axis.normalize();
Mat4d r = Mat4d.rotation(Math.atan2(x, z), Vec3d.YAxis);
r.rotate(-Math.asin(y / targetDir.length()), Vec3d.XAxis);
Vec3d p0 = new Vec3d(-width2, -height2, 0);
Vec3d p1 = new Vec3d(-width2, height2, 0);
Vec3d p2 = new Vec3d(width2, height2, 0);
Vec3d p3 = new Vec3d(width2, -height2, 0);
p0 = r.multiply(p0);
p1 = r.multiply(p1);
p2 = r.multiply(p2);
p3 = r.multiply(p3);
p0.add(targetDir);
p1.add(targetDir);
p2.add(targetDir);
p3.add(targetDir);
gl.glEnable(GL2.GL_CULL_FACE);
gl.glEnable(GL2.GL_TEXTURE_2D);
gl.glBegin(GL2.GL_QUADS);
{
gl.glTexCoord2f(1, 1);
gl.glVertex3f((float) p3.x, (float) p3.y, (float) p3.z);
gl.glTexCoord2f(1, 0);
gl.glVertex3f((float) p2.x, (float) p2.y, (float) p2.z);
gl.glTexCoord2f(0, 0);
gl.glVertex3f((float) p1.x, (float) p1.y, (float) p1.z);
gl.glTexCoord2f(0, 1);
gl.glVertex3f((float) p0.x, (float) p0.y, (float) p0.z);
}
gl.glEnd();
gl.glDisable(GL2.GL_TEXTURE_2D);
gl.glDisable(GL2.GL_CULL_FACE);
}
private static final double vpScale = 0.019;
private TextRenderer textRenderer;
private Font font;
private float oldFontSize = -1;
public void drawText(GL2 gl, JHVEvent evt, Point pt) {
int height = Displayer.getGLHeight();
int width = Displayer.getGLWidth();
float fontSize = (int) (height * vpScale);
if (textRenderer == null || fontSize != oldFontSize) {
oldFontSize = fontSize;
font = UIGlobals.UIFontRoboto.deriveFont(fontSize);
if (textRenderer != null) {
textRenderer.dispose();
}
textRenderer = new TextRenderer(font, true, true);
textRenderer.setUseVertexArrays(true);
textRenderer.setSmoothing(false);
textRenderer.setColor(Color.WHITE);
}
textRenderer.beginRendering(width, height, true);
Map<String, JHVEventParameter> params = evt.getVisibleEventParameters();
Vec2d bd = new Vec2d(0, 0);
int ct = 0;
for (Entry<String, JHVEventParameter> entry : params.entrySet()) {
String txt = entry.getValue().getParameterDisplayName() + " : " + entry.getValue().getParameterValue();
Rectangle2D bound = textRenderer.getBounds(txt);
if (bd.x < bound.getWidth())
bd.x = bound.getWidth();
ct++;
}
bd.y = fontSize * 1.1 * (ct);
Point textInit = new Point(pt.x, pt.y);
float w = (float) (bd.x + LEFT_MARGIN_TEXT + RIGHT_MARGIN_TEXT);
float h = (float) (bd.y + BOTTOM_MARGIN_TEXT + TOP_MARGIN_TEXT);
// Correct if out of view
if (w + pt.x + MOUSE_OFFSET_X - LEFT_MARGIN_TEXT > width) {
textInit.x -= (w + pt.x + MOUSE_OFFSET_X - LEFT_MARGIN_TEXT - width);
}
if (h + pt.y + MOUSE_OFFSET_Y - fontSize - TOP_MARGIN_TEXT > height) {
textInit.y -= (h + pt.y + MOUSE_OFFSET_Y - fontSize - TOP_MARGIN_TEXT - height);
}
float left = textInit.x + MOUSE_OFFSET_X - LEFT_MARGIN_TEXT;
float bottom = textInit.y + MOUSE_OFFSET_Y - fontSize - TOP_MARGIN_TEXT;
gl.glColor4f(0.5f, 0.5f, 0.5f, 0.75f);
gl.glDisable(GL2.GL_TEXTURE_2D);
gl.glPushMatrix();
gl.glLoadIdentity();
{
gl.glBegin(GL2.GL_QUADS);
gl.glVertex2f(left, height - bottom);
gl.glVertex2f(left, height - bottom - h);
gl.glVertex2f(left + w, height - bottom - h);
gl.glVertex2f(left + w, height - bottom);
gl.glEnd();
}
gl.glPopMatrix();
gl.glEnable(GL2.GL_TEXTURE_2D);
textRenderer.setColor(Color.WHITE);
int deltaY = MOUSE_OFFSET_Y;
for (Entry<String, JHVEventParameter> entry : params.entrySet()) {
String txt = entry.getValue().getParameterDisplayName() + " : " + entry.getValue().getParameterValue();
textRenderer.draw(txt, textInit.x + MOUSE_OFFSET_X, height - textInit.y - deltaY);
deltaY += fontSize * 1.1;
}
textRenderer.endRendering();
gl.glDisable(GL2.GL_TEXTURE_2D);
}
@Override
public void render(GL2 gl, GL3DViewport vp) {
if (isVisible[vp.getIndex()]) {
ArrayList<JHVEvent> eventsToDraw = SWHVHEKData.getSingletonInstance().getActiveEvents(controller.currentTime);
highLightedEvent = null;
for (JHVEvent evt : eventsToDraw) {
if (evt.getName().equals("Coronal Mass Ejection")) {
drawCactusArc(gl, evt, controller.currentTime);
} else {
drawPolygon(gl, evt, controller.currentTime);
gl.glDisable(GL2.GL_DEPTH_TEST);
drawIcon(gl, evt, controller.currentTime);
gl.glEnable(GL2.GL_DEPTH_TEST);
}
if (evt.isHighlighted()) {
highLightedEvent = evt;
}
}
SWHVHEKSettings.resetCactusColor();
}
}
@Override
public void renderFloat(GL2 gl, GL3DViewport vp) {
if (isVisible[vp.getIndex()]) {
if (SWHVHEKPopupController.mouseOverJHVEvent != null) {
drawText(gl, SWHVHEKPopupController.mouseOverJHVEvent, SWHVHEKPopupController.mouseOverPosition);
}
}
}
@Override
public void remove(GL2 gl) {
dispose(gl);
ImageViewerGui.getInputController().removePlugin(controller);
}
@Override
public Component getOptionsPanel() {
return null;
}
@Override
public String getName() {
return "SWEK events";
}
@Override
public void setVisible(boolean isVisible) {
super.setVisible(isVisible);
if (isVisible) {
controller.timeChanged(Layers.addTimeListener(controller));
ImageViewerGui.getInputController().addPlugin(controller);
} else {
ImageViewerGui.getInputController().removePlugin(controller);
Layers.removeTimeListener(controller);
}
}
@Override
public String getTimeString() {
return null;
}
@Override
public boolean isDeletable() {
return false;
}
@Override
public void init(GL2 gl) {
setVisible(true);
}
@Override
public void dispose(GL2 gl) {
for (GLTexture el : iconCacheId.values()) {
el.delete(gl);
}
iconCacheId.clear();
}
@Override
public void renderMiniview(GL2 gl, GL3DViewport vp) {
}
}
|
reduce offset + clean
git-svn-id: 4e353c0944fe8da334633afc35765ef362dec675@5880 b4e469a2-07ce-4b26-9273-4d7d95a670c7
|
src/plugins/swhvhekplugin-3d/src/org/helioviewer/jhv/plugins/swhvhekplugin/SWHVHEKPluginRenderable.java
|
reduce offset + clean
|
<ide><path>rc/plugins/swhvhekplugin-3d/src/org/helioviewer/jhv/plugins/swhvhekplugin/SWHVHEKPluginRenderable.java
<ide> private final static int RIGHT_MARGIN_TEXT = 10;
<ide> private final static int TOP_MARGIN_TEXT = 5;
<ide> private final static int BOTTOM_MARGIN_TEXT = 5;
<del> private final static int MOUSE_OFFSET_X = 45;
<del> private final static int MOUSE_OFFSET_Y = 45;
<del> private JHVEvent highLightedEvent = null;
<add> private final static int MOUSE_OFFSET_X = 25;
<add> private final static int MOUSE_OFFSET_Y = 25;
<ide>
<ide> private void bindTexture(GL2 gl, String key, ImageIcon icon) {
<ide> GLTexture tex = iconCacheId.get(key);
<ide> public void render(GL2 gl, GL3DViewport vp) {
<ide> if (isVisible[vp.getIndex()]) {
<ide> ArrayList<JHVEvent> eventsToDraw = SWHVHEKData.getSingletonInstance().getActiveEvents(controller.currentTime);
<del> highLightedEvent = null;
<ide> for (JHVEvent evt : eventsToDraw) {
<ide> if (evt.getName().equals("Coronal Mass Ejection")) {
<ide> drawCactusArc(gl, evt, controller.currentTime);
<ide> gl.glDisable(GL2.GL_DEPTH_TEST);
<ide> drawIcon(gl, evt, controller.currentTime);
<ide> gl.glEnable(GL2.GL_DEPTH_TEST);
<del> }
<del> if (evt.isHighlighted()) {
<del> highLightedEvent = evt;
<ide> }
<ide> }
<ide>
|
|
Java
|
mit
|
b75189dfa3a5e8232e4fc267e25349e02435a7a8
| 0 |
jbosboom/streamjit,jbosboom/streamjit
|
package edu.mit.streamjit.test.sanity;
import com.google.common.base.Supplier;
import com.google.common.collect.ImmutableList;
import com.jeffreybosboom.serviceproviderprocessor.ServiceProvider;
import edu.mit.streamjit.api.DuplicateSplitter;
import edu.mit.streamjit.api.Identity;
import edu.mit.streamjit.api.Input;
import edu.mit.streamjit.api.Joiner;
import edu.mit.streamjit.api.RoundrobinJoiner;
import edu.mit.streamjit.api.RoundrobinSplitter;
import edu.mit.streamjit.api.Splitjoin;
import edu.mit.streamjit.api.Splitter;
import edu.mit.streamjit.api.WeightedRoundrobinJoiner;
import edu.mit.streamjit.api.WeightedRoundrobinSplitter;
import edu.mit.streamjit.impl.blob.Buffer;
import edu.mit.streamjit.impl.common.InputBufferFactory;
import edu.mit.streamjit.test.SuppliedBenchmark;
import edu.mit.streamjit.test.Benchmark;
import edu.mit.streamjit.test.Benchmark.Dataset;
import edu.mit.streamjit.test.BenchmarkProvider;
import edu.mit.streamjit.test.Datasets;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Queue;
/**
* Tests that splitjoins using the built-in splitters order their elements
* properly.
*
* TODO: we run the simulator even if we aren't going to run any of the
* benchmarks. We'll need to do that lazily at some point.
*
* TODO: the splitjoin simulator should be refactored into a splitter simulator
* and joiner simulator, so we can plug any of the splitters with any of the
* joiners. Right now we have a copy for the duplicate splitter.
* @see SplitjoinComputeSanity
* @author Jeffrey Bosboom <[email protected]>
* @since 8/20/2013
*/
@ServiceProvider(BenchmarkProvider.class)
public final class SplitjoinOrderSanity implements BenchmarkProvider {
@Override
public Iterator<Benchmark> iterator() {
Benchmark[] benchmarks = {
rr_rr(7, 1, 1),
rr_rr(7, 5, 5),
rr_rr(7, 5, 3),
rr_rr(7, 3, 5),
wrr_rr(1, new int[]{1}, 1),
wrr_rr(7, new int[]{1, 1, 1, 1, 1, 1, 1}, 1),
wrr_rr(7, new int[]{5, 5, 5, 5, 5, 5, 5}, 5),
rr_wrr(1, 1, new int[]{1}),
rr_wrr(7, 1, new int[]{1, 1, 1, 1, 1, 1, 1}),
rr_wrr(7, 5, new int[]{5, 5, 5, 5, 5, 5, 5}),
wrr_wrr(1, new int[]{1}, new int[]{1}),
wrr_wrr(7, new int[]{1, 1, 1, 1, 1, 1, 1}, new int[]{1, 1, 1, 1, 1, 1, 1}),
wrr_wrr(7, new int[]{5, 5, 5, 5, 5, 5, 5}, new int[]{5, 5, 5, 5, 5, 5, 5}),
wrr_wrr(7, new int[]{1, 2, 3, 4, 3, 2, 1}, new int[]{1, 2, 3, 4, 3, 2, 1}),
dup_rr(7, 1),
dup_rr(7, 7),
dup_wrr(1, new int[]{1}),
dup_wrr(7, new int[]{1, 1, 1, 1, 1, 1, 1}),
dup_wrr(7, new int[]{5, 5, 5, 5, 5, 5, 5}),
};
return Arrays.asList(benchmarks).iterator();
}
private static Benchmark rr_rr(int width, int splitRate, int joinRate) {
String name = String.format("RR(%d) x %dw x RR(%d)", splitRate, width, joinRate);
return new SuppliedBenchmark(name,
new SplitjoinSupplier(width, new RoundrobinSplitterSupplier(splitRate), new RoundrobinJoinerSupplier(joinRate)),
simulateRoundrobin(Datasets.allIntsInRange(0, 1_000_000), width, splitRate, joinRate));
}
private static Benchmark wrr_rr(int width, int[] splitRates, int joinRate) {
String name = String.format("WRR(%s) x %dw x RR(%d)", Arrays.toString(splitRates), width, joinRate);
return new SuppliedBenchmark(name,
new SplitjoinSupplier(width, new WeightedRoundrobinSplitterSupplier(splitRates), new RoundrobinJoinerSupplier(joinRate)),
simulateRoundrobin(Datasets.allIntsInRange(0, 1_000_000), width, splitRates, joinRate));
}
private static Benchmark rr_wrr(int width, int splitRate, int[] joinRates) {
String name = String.format("RR(%d) x %dw x WRR(%s)", splitRate, width, Arrays.toString(joinRates));
return new SuppliedBenchmark(name,
new SplitjoinSupplier(width, new RoundrobinSplitterSupplier(splitRate), new WeightedRoundrobinJoinerSupplier(joinRates)),
simulateRoundrobin(Datasets.allIntsInRange(0, 1_000_000), width, splitRate, joinRates));
}
private static Benchmark wrr_wrr(int width, int[] splitRates, int[] joinRates) {
String name = String.format("WRR(%s) x %dw x WRR(%s)", Arrays.toString(splitRates), width, Arrays.toString(joinRates));
return new SuppliedBenchmark(name,
new SplitjoinSupplier(width, new WeightedRoundrobinSplitterSupplier(splitRates), new WeightedRoundrobinJoinerSupplier(joinRates)),
simulateRoundrobin(Datasets.allIntsInRange(0, 1_000_000), width, splitRates, joinRates));
}
private static Benchmark dup_rr(int width, int joinRate) {
String name = String.format("dup x %dw x RR(%d)", width, joinRate);
Dataset dataset = Datasets.allIntsInRange(0, 1_000_000);
dataset = dataset.withOutput(Datasets.lazyInput(DuplicateSimulator.create(dataset.input(), width, joinRate)));
return new SuppliedBenchmark(name,
new SplitjoinSupplier(width, new DuplicateSplitterSupplier(), new RoundrobinJoinerSupplier(joinRate)),
dataset);
}
private static Benchmark dup_wrr(int width, int[] joinRates) {
String name = String.format("dup x %dw x WRR(%s)", width, Arrays.toString(joinRates));
Dataset dataset = Datasets.allIntsInRange(0, 1_000_000);
dataset = dataset.withOutput(Datasets.lazyInput(DuplicateSimulator.create(dataset.input(), width, joinRates)));
return new SuppliedBenchmark(name,
new SplitjoinSupplier(width, new DuplicateSplitterSupplier(), new WeightedRoundrobinJoinerSupplier(joinRates)),
dataset);
}
private static final class SplitjoinSupplier implements Supplier<Splitjoin<Integer, Integer>> {
private final int width;
private final Supplier<? extends Splitter<Integer, Integer>> splitter;
private final Supplier<? extends Joiner<Integer, Integer>> joiner;
private SplitjoinSupplier(int width, Supplier<? extends Splitter<Integer, Integer>> splitter, Supplier<? extends Joiner<Integer, Integer>> joiner) {
this.width = width;
this.splitter = splitter;
this.joiner = joiner;
}
@Override
public Splitjoin<Integer, Integer> get() {
ImmutableList.Builder<Identity<Integer>> builder = ImmutableList.builder();
//Can't use Collections.nCopies because we need distinct filters.
for (int i = 0; i < width; ++i)
builder.add(new Identity<Integer>());
return new Splitjoin<>(splitter.get(), joiner.get(), builder.build());
}
}
//I'd like to use ConstructorSupplier here, but the generics won't work
//because e.g. RoundrobinSplitter.class is a raw type.
private static final class RoundrobinSplitterSupplier implements Supplier<Splitter<Integer, Integer>> {
private final int rate;
private RoundrobinSplitterSupplier(int rate) {
this.rate = rate;
}
@Override
public Splitter<Integer, Integer> get() {
return new RoundrobinSplitter<>(rate);
}
}
private static final class RoundrobinJoinerSupplier implements Supplier<Joiner<Integer, Integer>> {
private final int rate;
private RoundrobinJoinerSupplier(int rate) {
this.rate = rate;
}
@Override
public Joiner<Integer, Integer> get() {
return new RoundrobinJoiner<>(rate);
}
}
private static final class WeightedRoundrobinSplitterSupplier implements Supplier<Splitter<Integer, Integer>> {
private final int[] rates;
private WeightedRoundrobinSplitterSupplier(int[] rates) {
this.rates = rates;
}
@Override
public Splitter<Integer, Integer> get() {
return new WeightedRoundrobinSplitter<>(rates);
}
}
private static final class WeightedRoundrobinJoinerSupplier implements Supplier<Joiner<Integer, Integer>> {
private final int[] rates;
private WeightedRoundrobinJoinerSupplier(int[] rates) {
this.rates = rates;
}
@Override
public Joiner<Integer, Integer> get() {
return new WeightedRoundrobinJoiner<>(rates);
}
}
private static final class DuplicateSplitterSupplier implements Supplier<Splitter<Integer, Integer>> {
@Override
public Splitter<Integer, Integer> get() {
return new DuplicateSplitter<>();
}
}
/**
* Simulates a roundrobin splitjoin, returning a Dataset with reference
* output.
*/
private static Dataset simulateRoundrobin(Dataset dataset, int width, int splitRate, int joinRate) {
int[] splitRates = new int[width], joinRates = new int[width];
Arrays.fill(splitRates, splitRate);
Arrays.fill(joinRates, joinRate);
return simulateRoundrobin(dataset, width, splitRates, joinRates);
}
private static Dataset simulateRoundrobin(Dataset dataset, int width, int[] splitRates, int joinRate) {
int[] joinRates = new int[width];
Arrays.fill(joinRates, joinRate);
return simulateRoundrobin(dataset, width, splitRates, joinRates);
}
private static Dataset simulateRoundrobin(Dataset dataset, int width, int splitRate, int[] joinRates) {
int[] splitRates = new int[width];
Arrays.fill(splitRates, splitRate);
return simulateRoundrobin(dataset, width, splitRates, joinRates);
}
/**
* Simulates a weighted roundrobin splitjoin, returning a Dataset with
* reference output.
*/
private static Dataset simulateRoundrobin(Dataset dataset, int width, int[] splitRates, int[] joinRates) {
List<Queue<Object>> bins = new ArrayList<>(width);
for (int i = 0; i < width; ++i)
bins.add(new ArrayDeque<>());
int splitReq = 0;
for (int i : splitRates)
splitReq += i;
Buffer buffer = InputBufferFactory.unwrap(dataset.input()).createReadableBuffer(splitReq);
while (buffer.size() >= splitReq)
for (int i = 0; i < bins.size(); ++i)
for (int j = 0; j < splitRates[i]; ++j)
bins.get(i).add(buffer.read());
List<Object> output = new ArrayList<>();
while (ready(bins, joinRates)) {
for (int i = 0; i < bins.size(); ++i)
for (int j = 0; j < joinRates[i]; ++j)
output.add(bins.get(i).remove());
}
return dataset.withOutput(Input.fromIterable(output));
}
private static final class DuplicateSimulator<T> implements Supplier<Input<T>> {
private final Input<T> input;
private final int width;
private final int[] joinRates;
public static <T> DuplicateSimulator<T> create(Input<T> input, int width, int joinRate) {
int[] joinRates = new int[width];
Arrays.fill(joinRates, joinRate);
return create(input, width, joinRates);
}
public static <T> DuplicateSimulator<T> create(Input<T> input, int width, int[] joinRates) {
return new DuplicateSimulator<>(input, width, joinRates);
}
private DuplicateSimulator(Input<T> input, int width, int[] joinRates) {
this.input = input;
this.width = width;
this.joinRates = joinRates;
}
@Override
@SuppressWarnings("unchecked")
public Input<T> get() {
List<Queue<T>> bins = new ArrayList<>(width);
for (int i = 0; i < width; ++i)
bins.add(new ArrayDeque<T>());
Buffer buffer = InputBufferFactory.unwrap(input).createReadableBuffer(42);
while (buffer.size() > 0) {
Object o = buffer.read();
for (int i = 0; i < bins.size(); ++i)
bins.get(i).add((T)o);
}
List<T> output = new ArrayList<>();
while (ready(bins, joinRates)) {
for (int i = 0; i < bins.size(); ++i)
for (int j = 0; j < joinRates[i]; ++j)
output.add(bins.get(i).remove());
}
return Input.fromIterable(output);
}
}
private static <T> boolean ready(List<Queue<T>> bins, int[] joinRates) {
for (int i = 0; i < bins.size(); ++i)
if (bins.get(i).size() < joinRates[i])
return false;
return true;
}
}
|
src/edu/mit/streamjit/test/sanity/SplitjoinOrderSanity.java
|
package edu.mit.streamjit.test.sanity;
import com.google.common.base.Supplier;
import com.google.common.collect.ImmutableList;
import com.jeffreybosboom.serviceproviderprocessor.ServiceProvider;
import edu.mit.streamjit.api.DuplicateSplitter;
import edu.mit.streamjit.api.Identity;
import edu.mit.streamjit.api.Input;
import edu.mit.streamjit.api.Joiner;
import edu.mit.streamjit.api.RoundrobinJoiner;
import edu.mit.streamjit.api.RoundrobinSplitter;
import edu.mit.streamjit.api.Splitjoin;
import edu.mit.streamjit.api.Splitter;
import edu.mit.streamjit.api.WeightedRoundrobinJoiner;
import edu.mit.streamjit.api.WeightedRoundrobinSplitter;
import edu.mit.streamjit.impl.blob.Buffer;
import edu.mit.streamjit.impl.common.InputBufferFactory;
import edu.mit.streamjit.test.SuppliedBenchmark;
import edu.mit.streamjit.test.Benchmark;
import edu.mit.streamjit.test.Benchmark.Dataset;
import edu.mit.streamjit.test.BenchmarkProvider;
import edu.mit.streamjit.test.Datasets;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Queue;
/**
* Tests that splitjoins using the built-in splitters order their elements
* properly.
*
* TODO: we run the simulator even if we aren't going to run any of the
* benchmarks. We'll need to do that lazily at some point.
*
* TODO: the splitjoin simulator should be refactored into a splitter simulator
* and joiner simulator, so we can plug any of the splitters with any of the
* joiners. Right now we have a copy for the duplicate splitter.
* @see SplitjoinComputeSanity
* @author Jeffrey Bosboom <[email protected]>
* @since 8/20/2013
*/
@ServiceProvider(BenchmarkProvider.class)
public final class SplitjoinOrderSanity implements BenchmarkProvider {
@Override
public Iterator<Benchmark> iterator() {
Benchmark[] benchmarks = {
rr_rr(7, 1, 1),
rr_rr(7, 5, 5),
rr_rr(7, 5, 3),
rr_rr(7, 3, 5),
wrr_rr(1, new int[]{1}, 1),
wrr_rr(7, new int[]{1, 1, 1, 1, 1, 1, 1}, 1),
wrr_rr(7, new int[]{5, 5, 5, 5, 5, 5, 5}, 5),
rr_wrr(1, 1, new int[]{1}),
rr_wrr(7, 1, new int[]{1, 1, 1, 1, 1, 1, 1}),
rr_wrr(7, 5, new int[]{5, 5, 5, 5, 5, 5, 5}),
wrr_wrr(1, new int[]{1}, new int[]{1}),
wrr_wrr(7, new int[]{1, 1, 1, 1, 1, 1, 1}, new int[]{1, 1, 1, 1, 1, 1, 1}),
wrr_wrr(7, new int[]{5, 5, 5, 5, 5, 5, 5}, new int[]{5, 5, 5, 5, 5, 5, 5}),
wrr_wrr(7, new int[]{1, 2, 3, 4, 3, 2, 1}, new int[]{1, 2, 3, 4, 3, 2, 1}),
dup_rr(7, 1),
dup_rr(7, 7),
dup_wrr(1, new int[]{1}),
dup_wrr(7, new int[]{1, 1, 1, 1, 1, 1, 1}),
dup_wrr(7, new int[]{5, 5, 5, 5, 5, 5, 5}),
};
return Arrays.asList(benchmarks).iterator();
}
private static Benchmark rr_rr(int width, int splitRate, int joinRate) {
String name = String.format("RR(%d) x %dw x RR(%d)", splitRate, width, joinRate);
return new SuppliedBenchmark(name,
new SplitjoinSupplier(width, new RoundrobinSplitterSupplier(splitRate), new RoundrobinJoinerSupplier(joinRate)),
simulateRoundrobin(Datasets.allIntsInRange(0, 1_000_000), width, splitRate, joinRate));
}
private static Benchmark wrr_rr(int width, int[] splitRates, int joinRate) {
String name = String.format("WRR(%s) x %dw x RR(%d)", Arrays.toString(splitRates), width, joinRate);
return new SuppliedBenchmark(name,
new SplitjoinSupplier(width, new WeightedRoundrobinSplitterSupplier(splitRates), new RoundrobinJoinerSupplier(joinRate)),
simulateRoundrobin(Datasets.allIntsInRange(0, 1_000_000), width, splitRates, joinRate));
}
private static Benchmark rr_wrr(int width, int splitRate, int[] joinRates) {
String name = String.format("RR(%d) x %dw x WRR(%s)", splitRate, width, Arrays.toString(joinRates));
return new SuppliedBenchmark(name,
new SplitjoinSupplier(width, new RoundrobinSplitterSupplier(splitRate), new WeightedRoundrobinJoinerSupplier(joinRates)),
simulateRoundrobin(Datasets.allIntsInRange(0, 1_000_000), width, splitRate, joinRates));
}
private static Benchmark wrr_wrr(int width, int[] splitRates, int[] joinRates) {
String name = String.format("WRR(%s) x %dw x WRR(%s)", Arrays.toString(splitRates), width, Arrays.toString(joinRates));
return new SuppliedBenchmark(name,
new SplitjoinSupplier(width, new WeightedRoundrobinSplitterSupplier(splitRates), new WeightedRoundrobinJoinerSupplier(joinRates)),
simulateRoundrobin(Datasets.allIntsInRange(0, 1_000_000), width, splitRates, joinRates));
}
private static Benchmark dup_rr(int width, int joinRate) {
String name = String.format("dup x %dw x RR(%d)", width, joinRate);
Dataset dataset = Datasets.allIntsInRange(0, 1_000_000);
dataset = dataset.withInput(Datasets.lazyInput(DuplicateSimulator.create(dataset.input(), width, joinRate)));
return new SuppliedBenchmark(name,
new SplitjoinSupplier(width, new DuplicateSplitterSupplier(), new RoundrobinJoinerSupplier(joinRate)),
dataset);
}
private static Benchmark dup_wrr(int width, int[] joinRates) {
String name = String.format("dup x %dw x WRR(%s)", width, Arrays.toString(joinRates));
Dataset dataset = Datasets.allIntsInRange(0, 1_000_000);
dataset = dataset.withInput(Datasets.lazyInput(DuplicateSimulator.create(dataset.input(), width, joinRates)));
return new SuppliedBenchmark(name,
new SplitjoinSupplier(width, new DuplicateSplitterSupplier(), new WeightedRoundrobinJoinerSupplier(joinRates)),
dataset);
}
private static final class SplitjoinSupplier implements Supplier<Splitjoin<Integer, Integer>> {
private final int width;
private final Supplier<? extends Splitter<Integer, Integer>> splitter;
private final Supplier<? extends Joiner<Integer, Integer>> joiner;
private SplitjoinSupplier(int width, Supplier<? extends Splitter<Integer, Integer>> splitter, Supplier<? extends Joiner<Integer, Integer>> joiner) {
this.width = width;
this.splitter = splitter;
this.joiner = joiner;
}
@Override
public Splitjoin<Integer, Integer> get() {
ImmutableList.Builder<Identity<Integer>> builder = ImmutableList.builder();
//Can't use Collections.nCopies because we need distinct filters.
for (int i = 0; i < width; ++i)
builder.add(new Identity<Integer>());
return new Splitjoin<>(splitter.get(), joiner.get(), builder.build());
}
}
//I'd like to use ConstructorSupplier here, but the generics won't work
//because e.g. RoundrobinSplitter.class is a raw type.
private static final class RoundrobinSplitterSupplier implements Supplier<Splitter<Integer, Integer>> {
private final int rate;
private RoundrobinSplitterSupplier(int rate) {
this.rate = rate;
}
@Override
public Splitter<Integer, Integer> get() {
return new RoundrobinSplitter<>(rate);
}
}
private static final class RoundrobinJoinerSupplier implements Supplier<Joiner<Integer, Integer>> {
private final int rate;
private RoundrobinJoinerSupplier(int rate) {
this.rate = rate;
}
@Override
public Joiner<Integer, Integer> get() {
return new RoundrobinJoiner<>(rate);
}
}
private static final class WeightedRoundrobinSplitterSupplier implements Supplier<Splitter<Integer, Integer>> {
private final int[] rates;
private WeightedRoundrobinSplitterSupplier(int[] rates) {
this.rates = rates;
}
@Override
public Splitter<Integer, Integer> get() {
return new WeightedRoundrobinSplitter<>(rates);
}
}
private static final class WeightedRoundrobinJoinerSupplier implements Supplier<Joiner<Integer, Integer>> {
private final int[] rates;
private WeightedRoundrobinJoinerSupplier(int[] rates) {
this.rates = rates;
}
@Override
public Joiner<Integer, Integer> get() {
return new WeightedRoundrobinJoiner<>(rates);
}
}
private static final class DuplicateSplitterSupplier implements Supplier<Splitter<Integer, Integer>> {
@Override
public Splitter<Integer, Integer> get() {
return new DuplicateSplitter<>();
}
}
/**
* Simulates a roundrobin splitjoin, returning a Dataset with reference
* output.
*/
private static Dataset simulateRoundrobin(Dataset dataset, int width, int splitRate, int joinRate) {
int[] splitRates = new int[width], joinRates = new int[width];
Arrays.fill(splitRates, splitRate);
Arrays.fill(joinRates, joinRate);
return simulateRoundrobin(dataset, width, splitRates, joinRates);
}
private static Dataset simulateRoundrobin(Dataset dataset, int width, int[] splitRates, int joinRate) {
int[] joinRates = new int[width];
Arrays.fill(joinRates, joinRate);
return simulateRoundrobin(dataset, width, splitRates, joinRates);
}
private static Dataset simulateRoundrobin(Dataset dataset, int width, int splitRate, int[] joinRates) {
int[] splitRates = new int[width];
Arrays.fill(splitRates, splitRate);
return simulateRoundrobin(dataset, width, splitRates, joinRates);
}
/**
* Simulates a weighted roundrobin splitjoin, returning a Dataset with
* reference output.
*/
private static Dataset simulateRoundrobin(Dataset dataset, int width, int[] splitRates, int[] joinRates) {
List<Queue<Object>> bins = new ArrayList<>(width);
for (int i = 0; i < width; ++i)
bins.add(new ArrayDeque<>());
int splitReq = 0;
for (int i : splitRates)
splitReq += i;
Buffer buffer = InputBufferFactory.unwrap(dataset.input()).createReadableBuffer(splitReq);
while (buffer.size() >= splitReq)
for (int i = 0; i < bins.size(); ++i)
for (int j = 0; j < splitRates[i]; ++j)
bins.get(i).add(buffer.read());
List<Object> output = new ArrayList<>();
while (ready(bins, joinRates)) {
for (int i = 0; i < bins.size(); ++i)
for (int j = 0; j < joinRates[i]; ++j)
output.add(bins.get(i).remove());
}
return dataset.withOutput(Input.fromIterable(output));
}
private static final class DuplicateSimulator<T> implements Supplier<Input<T>> {
private final Input<T> input;
private final int width;
private final int[] joinRates;
public static <T> DuplicateSimulator<T> create(Input<T> input, int width, int joinRate) {
int[] joinRates = new int[width];
Arrays.fill(joinRates, joinRate);
return create(input, width, joinRates);
}
public static <T> DuplicateSimulator<T> create(Input<T> input, int width, int[] joinRates) {
return new DuplicateSimulator<>(input, width, joinRates);
}
private DuplicateSimulator(Input<T> input, int width, int[] joinRates) {
this.input = input;
this.width = width;
this.joinRates = joinRates;
}
@Override
@SuppressWarnings("unchecked")
public Input<T> get() {
List<Queue<T>> bins = new ArrayList<>(width);
for (int i = 0; i < width; ++i)
bins.add(new ArrayDeque<T>());
Buffer buffer = InputBufferFactory.unwrap(input).createReadableBuffer(42);
while (buffer.size() > 0) {
Object o = buffer.read();
for (int i = 0; i < bins.size(); ++i)
bins.get(i).add((T)o);
}
List<T> output = new ArrayList<>();
while (ready(bins, joinRates)) {
for (int i = 0; i < bins.size(); ++i)
for (int j = 0; j < joinRates[i]; ++j)
output.add(bins.get(i).remove());
}
return Input.fromIterable(output);
}
}
private static <T> boolean ready(List<Queue<T>> bins, int[] joinRates) {
for (int i = 0; i < bins.size(); ++i)
if (bins.get(i).size() < joinRates[i])
return false;
return true;
}
}
|
SplitjoinOrderSanity: withInput -> withOutput (oops)
|
src/edu/mit/streamjit/test/sanity/SplitjoinOrderSanity.java
|
SplitjoinOrderSanity: withInput -> withOutput (oops)
|
<ide><path>rc/edu/mit/streamjit/test/sanity/SplitjoinOrderSanity.java
<ide> private static Benchmark dup_rr(int width, int joinRate) {
<ide> String name = String.format("dup x %dw x RR(%d)", width, joinRate);
<ide> Dataset dataset = Datasets.allIntsInRange(0, 1_000_000);
<del> dataset = dataset.withInput(Datasets.lazyInput(DuplicateSimulator.create(dataset.input(), width, joinRate)));
<add> dataset = dataset.withOutput(Datasets.lazyInput(DuplicateSimulator.create(dataset.input(), width, joinRate)));
<ide> return new SuppliedBenchmark(name,
<ide> new SplitjoinSupplier(width, new DuplicateSplitterSupplier(), new RoundrobinJoinerSupplier(joinRate)),
<ide> dataset);
<ide> private static Benchmark dup_wrr(int width, int[] joinRates) {
<ide> String name = String.format("dup x %dw x WRR(%s)", width, Arrays.toString(joinRates));
<ide> Dataset dataset = Datasets.allIntsInRange(0, 1_000_000);
<del> dataset = dataset.withInput(Datasets.lazyInput(DuplicateSimulator.create(dataset.input(), width, joinRates)));
<add> dataset = dataset.withOutput(Datasets.lazyInput(DuplicateSimulator.create(dataset.input(), width, joinRates)));
<ide> return new SuppliedBenchmark(name,
<ide> new SplitjoinSupplier(width, new DuplicateSplitterSupplier(), new WeightedRoundrobinJoinerSupplier(joinRates)),
<ide> dataset);
|
|
Java
|
apache-2.0
|
7807214bbd9da7275650359dd1e9e54f8452b1b0
| 0 |
irfanah/zxing,0111001101111010/zxing,zootsuitbrian/zxing,catalindavid/zxing,huangsongyan/zxing,zzhui1988/zxing,eddyb/zxing,krishnanMurali/zxing,sitexa/zxing,ren545457803/zxing,angrilove/zxing,geeklain/zxing,OnecloudVideo/zxing,Kevinsu917/zxing,cncomer/zxing,Yi-Kun/zxing,bittorrent/zxing,Akylas/zxing,10045125/zxing,Fedhaier/zxing,Kabele/zxing,YongHuiLuo/zxing,allenmo/zxing,wanjingyan001/zxing,danielZhang0601/zxing,daverix/zxing,zhangyihao/zxing,kyosho81/zxing,east119/zxing,meixililu/zxing,micwallace/webscanner,YongHuiLuo/zxing,mecury/zxing,lijian17/zxing,irwinai/zxing,zhangyihao/zxing,Akylas/zxing,GeorgeMe/zxing,keqingyuan/zxing,ForeverLucky/zxing,zootsuitbrian/zxing,whycode/zxing,Akylas/zxing,MonkeyZZZZ/Zxing,danielZhang0601/zxing,wirthandrel/zxing,slayerlp/zxing,irfanah/zxing,JasOXIII/zxing,wangdoubleyan/zxing,ChristingKim/zxing,BraveAction/zxing,917386389/zxing,todotobe1/zxing,layeka/zxing,menglifei/zxing,mig1098/zxing,irwinai/zxing,YLBFDEV/zxing,andyao/zxing,1yvT0s/zxing,juoni/zxing,meixililu/zxing,SriramRamesh/zxing,gank0326/zxing,FloatingGuy/zxing,kailIII/zxing,lijian17/zxing,sitexa/zxing,JerryChin/zxing,menglifei/zxing,micwallace/webscanner,shwethamallya89/zxing,l-dobrev/zxing,zxing/zxing,0111001101111010/zxing,HiWong/zxing,Kevinsu917/zxing,reidwooten99/zxing,huihui4045/zxing,tanelihuuskonen/zxing,sunil1989/zxing,JasOXIII/zxing,1shawn/zxing,GeorgeMe/zxing,YLBFDEV/zxing,iris-iriswang/zxing,wangxd1213/zxing,daverix/zxing,ouyangkongtong/zxing,wangxd1213/zxing,loaf/zxing,sunil1989/zxing,ptrnov/zxing,Akylas/zxing,micwallace/webscanner,ptrnov/zxing,ssakitha/QR-Code-Reader,MonkeyZZZZ/Zxing,0111001101111010/zxing,huangzl233/zxing,saif-hmk/zxing,finch0219/zxing,qianchenglenger/zxing,saif-hmk/zxing,JerryChin/zxing,SriramRamesh/zxing,rustemferreira/zxing-projectx,daverix/zxing,lvbaosong/zxing,andyao/zxing,eddyb/zxing,zootsuitbrian/zxing,shwethamallya89/zxing,Matrix44/zxing,Akylas/zxing,hgl888/zxing,ChanJLee/zxing,roudunyy/zxing,Luise-li/zxing,DONIKAN/zxing,jianwoo/zxing,zjcscut/zxing,t123yh/zxing,Luise-li/zxing,juoni/zxing,bittorrent/zxing,Yi-Kun/zxing,wangdoubleyan/zxing,ssakitha/QR-Code-Reader,kharohiy/zxing,ChanJLee/zxing,GeekHades/zxing,huihui4045/zxing,mecury/zxing,Matrix44/zxing,easycold/zxing,allenmo/zxing,manl1100/zxing,TestSmirk/zxing,reidwooten99/zxing,zilaiyedaren/zxing,mig1098/zxing,huopochuan/zxing,ChristingKim/zxing,andyshao/zxing,geeklain/zxing,t123yh/zxing,ale13jo/zxing,daverix/zxing,nickperez1285/zxing,andyshao/zxing,bestwpw/zxing,BraveAction/zxing,mayfourth/zxing,zzhui1988/zxing,tks-dp/zxing,zootsuitbrian/zxing,Akylas/zxing,zjcscut/zxing,wangjun/zxing,zootsuitbrian/zxing,cncomer/zxing,zootsuitbrian/zxing,huopochuan/zxing,Solvoj/zxing,huangsongyan/zxing,zootsuitbrian/zxing,roudunyy/zxing,Kabele/zxing,lvbaosong/zxing,Akylas/zxing,yuanhuihui/zxing,cnbin/zxing,917386389/zxing,tanelihuuskonen/zxing,ikenneth/zxing,huangzl233/zxing,TestSmirk/zxing,liboLiao/zxing,slayerlp/zxing,freakynit/zxing,joni1408/zxing,0111001101111010/zxing,daverix/zxing,finch0219/zxing,WB-ZZ-TEAM/zxing,l-dobrev/zxing,eight-pack-abdominals/ZXing,1shawn/zxing,Matrix44/zxing,yuanhuihui/zxing,cnbin/zxing,praveen062/zxing,wangjun/zxing,qingsong-xu/zxing,ikenneth/zxing,layeka/zxing,zilaiyedaren/zxing,DONIKAN/zxing,praveen062/zxing,ctoliver/zxing,freakynit/zxing,Peter32/zxing,befairyliu/zxing,whycode/zxing,joni1408/zxing,projectocolibri/zxing,liuchaoya/zxing,keqingyuan/zxing,zonamovil/zxing,projectocolibri/zxing,rustemferreira/zxing-projectx,wanjingyan001/zxing,ZhernakovMikhail/zxing,angrilove/zxing,sysujzh/zxing,Peter32/zxing,ale13jo/zxing,YuYongzhi/zxing,RatanPaul/zxing,kharohiy/zxing,zonamovil/zxing,eight-pack-abdominals/ZXing,YuYongzhi/zxing,hiagodotme/zxing,roadrunner1987/zxing,qianchenglenger/zxing,catalindavid/zxing,roadrunner1987/zxing,DavidLDawes/zxing,ssakitha/sakisolutions,krishnanMurali/zxing,mayfourth/zxing,wirthandrel/zxing,easycold/zxing,GeekHades/zxing,hgl888/zxing,shixingxing/zxing,Matrix44/zxing,Solvoj/zxing,RatanPaul/zxing,kyosho81/zxing,nickperez1285/zxing,geeklain/zxing,tks-dp/zxing,WB-ZZ-TEAM/zxing,jianwoo/zxing,hiagodotme/zxing,befairyliu/zxing,liuchaoya/zxing,HiWong/zxing,fhchina/zxing,ZhernakovMikhail/zxing,qingsong-xu/zxing,erbear/zxing,ssakitha/sakisolutions,graug/zxing,graug/zxing,ouyangkongtong/zxing,kailIII/zxing,liboLiao/zxing,ren545457803/zxing,shixingxing/zxing,iris-iriswang/zxing,Fedhaier/zxing,todotobe1/zxing,sysujzh/zxing,east119/zxing,FloatingGuy/zxing,ForeverLucky/zxing,manl1100/zxing,fhchina/zxing,bestwpw/zxing,ctoliver/zxing,1yvT0s/zxing,loaf/zxing,zxing/zxing,erbear/zxing,DavidLDawes/zxing,OnecloudVideo/zxing
|
/*
* Copyright 2008 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.zxing.oned;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.ChecksumException;
import com.google.zxing.DecodeHintType;
import com.google.zxing.FormatException;
import com.google.zxing.NotFoundException;
import com.google.zxing.Result;
import com.google.zxing.ResultPoint;
import com.google.zxing.common.BitArray;
import java.util.Arrays;
import java.util.Map;
/**
* <p>Decodes Code 39 barcodes. This does not support "Full ASCII Code 39" yet.</p>
*
* @author Sean Owen
* @see Code93Reader
*/
public final class Code39Reader extends OneDReader {
static final String ALPHABET_STRING = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-. *$/+%";
private static final char[] ALPHABET = ALPHABET_STRING.toCharArray();
/**
* These represent the encodings of characters, as patterns of wide and narrow bars.
* The 9 least-significant bits of each int correspond to the pattern of wide and narrow,
* with 1s representing "wide" and 0s representing narrow.
*/
static final int[] CHARACTER_ENCODINGS = {
0x034, 0x121, 0x061, 0x160, 0x031, 0x130, 0x070, 0x025, 0x124, 0x064, // 0-9
0x109, 0x049, 0x148, 0x019, 0x118, 0x058, 0x00D, 0x10C, 0x04C, 0x01C, // A-J
0x103, 0x043, 0x142, 0x013, 0x112, 0x052, 0x007, 0x106, 0x046, 0x016, // K-T
0x181, 0x0C1, 0x1C0, 0x091, 0x190, 0x0D0, 0x085, 0x184, 0x0C4, 0x094, // U-*
0x0A8, 0x0A2, 0x08A, 0x02A // $-%
};
private static final int ASTERISK_ENCODING = CHARACTER_ENCODINGS[39];
private final boolean usingCheckDigit;
private final boolean extendedMode;
private final StringBuilder decodeRowResult;
private final int[] counters;
/**
* Creates a reader that assumes all encoded data is data, and does not treat the final
* character as a check digit. It will not decoded "extended Code 39" sequences.
*/
public Code39Reader() {
this(false);
}
/**
* Creates a reader that can be configured to check the last character as a check digit.
* It will not decoded "extended Code 39" sequences.
*
* @param usingCheckDigit if true, treat the last data character as a check digit, not
* data, and verify that the checksum passes.
*/
public Code39Reader(boolean usingCheckDigit) {
this(usingCheckDigit, false);
}
/**
* Creates a reader that can be configured to check the last character as a check digit,
* or optionally attempt to decode "extended Code 39" sequences that are used to encode
* the full ASCII character set.
*
* @param usingCheckDigit if true, treat the last data character as a check digit, not
* data, and verify that the checksum passes.
* @param extendedMode if true, will attempt to decode extended Code 39 sequences in the
* text.
*/
public Code39Reader(boolean usingCheckDigit, boolean extendedMode) {
this.usingCheckDigit = usingCheckDigit;
this.extendedMode = extendedMode;
decodeRowResult = new StringBuilder(20);
counters = new int[9];
}
@Override
public Result decodeRow(int rowNumber, BitArray row, Map<DecodeHintType,?> hints)
throws NotFoundException, ChecksumException, FormatException {
int[] theCounters = counters;
Arrays.fill(theCounters, 0);
StringBuilder result = decodeRowResult;
result.setLength(0);
int[] start = findAsteriskPattern(row, theCounters);
// Read off white space
int nextStart = row.getNextSet(start[1]);
int end = row.getSize();
char decodedChar;
int lastStart;
do {
recordPattern(row, nextStart, theCounters);
int pattern = toNarrowWidePattern(theCounters);
if (pattern < 0) {
throw NotFoundException.getNotFoundInstance();
}
decodedChar = patternToChar(pattern);
result.append(decodedChar);
lastStart = nextStart;
for (int counter : theCounters) {
nextStart += counter;
}
// Read off white space
nextStart = row.getNextSet(nextStart);
} while (decodedChar != '*');
result.setLength(result.length() - 1); // remove asterisk
// Look for whitespace after pattern:
int lastPatternSize = 0;
for (int counter : theCounters) {
lastPatternSize += counter;
}
int whiteSpaceAfterEnd = nextStart - lastStart - lastPatternSize;
// If 50% of last pattern size, following last pattern, is not whitespace, fail
// (but if it's whitespace to the very end of the image, that's OK)
if (nextStart != end && (whiteSpaceAfterEnd >> 1) < lastPatternSize) {
throw NotFoundException.getNotFoundInstance();
}
if (usingCheckDigit) {
int max = result.length() - 1;
int total = 0;
for (int i = 0; i < max; i++) {
total += ALPHABET_STRING.indexOf(decodeRowResult.charAt(i));
}
if (result.charAt(max) != ALPHABET[total % 43]) {
throw ChecksumException.getChecksumInstance();
}
result.setLength(max);
}
if (result.length() == 0) {
// false positive
throw NotFoundException.getNotFoundInstance();
}
String resultString;
if (extendedMode) {
resultString = decodeExtended(result);
} else {
resultString = result.toString();
}
float left = (float) (start[1] + start[0]) / 2.0f;
float right = lastStart + lastPatternSize / 2.0f;
return new Result(
resultString,
null,
new ResultPoint[]{
new ResultPoint(left, (float) rowNumber),
new ResultPoint(right, (float) rowNumber)},
BarcodeFormat.CODE_39);
}
private static int[] findAsteriskPattern(BitArray row, int[] counters) throws NotFoundException {
int width = row.getSize();
int rowOffset = row.getNextSet(0);
int counterPosition = 0;
int patternStart = rowOffset;
boolean isWhite = false;
int patternLength = counters.length;
for (int i = rowOffset; i < width; i++) {
if (row.get(i) ^ isWhite) {
counters[counterPosition]++;
} else {
if (counterPosition == patternLength - 1) {
// Look for whitespace before start pattern, >= 50% of width of start pattern
if (toNarrowWidePattern(counters) == ASTERISK_ENCODING &&
row.isRange(Math.max(0, patternStart - ((i - patternStart) >> 1)), patternStart, false)) {
return new int[]{patternStart, i};
}
patternStart += counters[0] + counters[1];
System.arraycopy(counters, 2, counters, 0, patternLength - 2);
counters[patternLength - 2] = 0;
counters[patternLength - 1] = 0;
counterPosition--;
} else {
counterPosition++;
}
counters[counterPosition] = 1;
isWhite = !isWhite;
}
}
throw NotFoundException.getNotFoundInstance();
}
// For efficiency, returns -1 on failure. Not throwing here saved as many as 700 exceptions
// per image when using some of our blackbox images.
private static int toNarrowWidePattern(int[] counters) {
int numCounters = counters.length;
int maxNarrowCounter = 0;
int wideCounters;
do {
int minCounter = Integer.MAX_VALUE;
for (int counter : counters) {
if (counter < minCounter && counter > maxNarrowCounter) {
minCounter = counter;
}
}
maxNarrowCounter = minCounter;
wideCounters = 0;
int totalWideCountersWidth = 0;
int pattern = 0;
for (int i = 0; i < numCounters; i++) {
int counter = counters[i];
if (counter > maxNarrowCounter) {
pattern |= 1 << (numCounters - 1 - i);
wideCounters++;
totalWideCountersWidth += counter;
}
}
if (wideCounters == 3) {
// Found 3 wide counters, but are they close enough in width?
// We can perform a cheap, conservative check to see if any individual
// counter is more than 1.5 times the average:
for (int i = 0; i < numCounters && wideCounters > 0; i++) {
int counter = counters[i];
if (counter > maxNarrowCounter) {
wideCounters--;
// totalWideCountersWidth = 3 * average, so this checks if counter >= 3/2 * average
if ((counter << 1) >= totalWideCountersWidth) {
return -1;
}
}
}
return pattern;
}
} while (wideCounters > 3);
return -1;
}
private static char patternToChar(int pattern) throws NotFoundException {
for (int i = 0; i < CHARACTER_ENCODINGS.length; i++) {
if (CHARACTER_ENCODINGS[i] == pattern) {
return ALPHABET[i];
}
}
throw NotFoundException.getNotFoundInstance();
}
private static String decodeExtended(CharSequence encoded) throws FormatException {
int length = encoded.length();
StringBuilder decoded = new StringBuilder(length);
for (int i = 0; i < length; i++) {
char c = encoded.charAt(i);
if (c == '+' || c == '$' || c == '%' || c == '/') {
char next = encoded.charAt(i + 1);
char decodedChar = '\0';
switch (c) {
case '+':
// +A to +Z map to a to z
if (next >= 'A' && next <= 'Z') {
decodedChar = (char) (next + 32);
} else {
throw FormatException.getFormatInstance();
}
break;
case '$':
// $A to $Z map to control codes SH to SB
if (next >= 'A' && next <= 'Z') {
decodedChar = (char) (next - 64);
} else {
throw FormatException.getFormatInstance();
}
break;
case '%':
// %A to %E map to control codes ESC to US
if (next >= 'A' && next <= 'E') {
decodedChar = (char) (next - 38);
} else if (next >= 'F' && next <= 'W') {
decodedChar = (char) (next - 11);
} else {
throw FormatException.getFormatInstance();
}
break;
case '/':
// /A to /O map to ! to , and /Z maps to :
if (next >= 'A' && next <= 'O') {
decodedChar = (char) (next - 32);
} else if (next == 'Z') {
decodedChar = ':';
} else {
throw FormatException.getFormatInstance();
}
break;
}
decoded.append(decodedChar);
// bump up i again since we read two characters
i++;
} else {
decoded.append(c);
}
}
return decoded.toString();
}
}
|
core/src/com/google/zxing/oned/Code39Reader.java
|
/*
* Copyright 2008 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.zxing.oned;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.ChecksumException;
import com.google.zxing.DecodeHintType;
import com.google.zxing.FormatException;
import com.google.zxing.NotFoundException;
import com.google.zxing.Result;
import com.google.zxing.ResultPoint;
import com.google.zxing.common.BitArray;
import java.util.Arrays;
import java.util.Map;
/**
* <p>Decodes Code 39 barcodes. This does not support "Full ASCII Code 39" yet.</p>
*
* @author Sean Owen
* @see Code93Reader
*/
public final class Code39Reader extends OneDReader {
static final String ALPHABET_STRING = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-. *$/+%";
private static final char[] ALPHABET = ALPHABET_STRING.toCharArray();
/**
* These represent the encodings of characters, as patterns of wide and narrow bars.
* The 9 least-significant bits of each int correspond to the pattern of wide and narrow,
* with 1s representing "wide" and 0s representing narrow.
*/
static final int[] CHARACTER_ENCODINGS = {
0x034, 0x121, 0x061, 0x160, 0x031, 0x130, 0x070, 0x025, 0x124, 0x064, // 0-9
0x109, 0x049, 0x148, 0x019, 0x118, 0x058, 0x00D, 0x10C, 0x04C, 0x01C, // A-J
0x103, 0x043, 0x142, 0x013, 0x112, 0x052, 0x007, 0x106, 0x046, 0x016, // K-T
0x181, 0x0C1, 0x1C0, 0x091, 0x190, 0x0D0, 0x085, 0x184, 0x0C4, 0x094, // U-*
0x0A8, 0x0A2, 0x08A, 0x02A // $-%
};
private static final int ASTERISK_ENCODING = CHARACTER_ENCODINGS[39];
private final boolean usingCheckDigit;
private final boolean extendedMode;
private final StringBuilder decodeRowResult;
private final int[] counters;
/**
* Creates a reader that assumes all encoded data is data, and does not treat the final
* character as a check digit. It will not decoded "extended Code 39" sequences.
*/
public Code39Reader() {
this(false);
}
/**
* Creates a reader that can be configured to check the last character as a check digit.
* It will not decoded "extended Code 39" sequences.
*
* @param usingCheckDigit if true, treat the last data character as a check digit, not
* data, and verify that the checksum passes.
*/
public Code39Reader(boolean usingCheckDigit) {
this(usingCheckDigit, false);
}
/**
* Creates a reader that can be configured to check the last character as a check digit,
* or optionally attempt to decode "extended Code 39" sequences that are used to encode
* the full ASCII character set.
*
* @param usingCheckDigit if true, treat the last data character as a check digit, not
* data, and verify that the checksum passes.
* @param extendedMode if true, will attempt to decode extended Code 39 sequences in the
* text.
*/
public Code39Reader(boolean usingCheckDigit, boolean extendedMode) {
this.usingCheckDigit = usingCheckDigit;
this.extendedMode = extendedMode;
decodeRowResult = new StringBuilder(20);
counters = new int[9];
}
@Override
public Result decodeRow(int rowNumber, BitArray row, Map<DecodeHintType,?> hints)
throws NotFoundException, ChecksumException, FormatException {
int[] theCounters = counters;
Arrays.fill(theCounters, 0);
StringBuilder result = decodeRowResult;
result.setLength(0);
int[] start = findAsteriskPattern(row, theCounters);
// Read off white space
int nextStart = row.getNextSet(start[1]);
int end = row.getSize();
char decodedChar;
int lastStart;
do {
recordPattern(row, nextStart, theCounters);
int pattern = toNarrowWidePattern(theCounters);
if (pattern < 0) {
throw NotFoundException.getNotFoundInstance();
}
decodedChar = patternToChar(pattern);
result.append(decodedChar);
lastStart = nextStart;
for (int counter : theCounters) {
nextStart += counter;
}
// Read off white space
nextStart = row.getNextSet(nextStart);
} while (decodedChar != '*');
result.setLength(result.length() - 1); // remove asterisk
// Look for whitespace after pattern:
int lastPatternSize = 0;
for (int counter : theCounters) {
lastPatternSize += counter;
}
int whiteSpaceAfterEnd = nextStart - lastStart - lastPatternSize;
// If 50% of last pattern size, following last pattern, is not whitespace, fail
// (but if it's whitespace to the very end of the image, that's OK)
if (nextStart != end && (whiteSpaceAfterEnd >> 1) < lastPatternSize) {
throw NotFoundException.getNotFoundInstance();
}
if (usingCheckDigit) {
int max = result.length() - 1;
int total = 0;
for (int i = 0; i < max; i++) {
total += ALPHABET_STRING.indexOf(decodeRowResult.charAt(i));
}
if (result.charAt(max) != ALPHABET[total % 43]) {
throw ChecksumException.getChecksumInstance();
}
result.setLength(max);
}
if (result.length() == 0) {
// false positive
throw NotFoundException.getNotFoundInstance();
}
String resultString;
if (extendedMode) {
resultString = decodeExtended(result);
} else {
resultString = result.toString();
}
float left = (float) (start[1] + start[0]) / 2.0f;
float right = (float) (nextStart + lastStart) / 2.0f;
return new Result(
resultString,
null,
new ResultPoint[]{
new ResultPoint(left, (float) rowNumber),
new ResultPoint(right, (float) rowNumber)},
BarcodeFormat.CODE_39);
}
private static int[] findAsteriskPattern(BitArray row, int[] counters) throws NotFoundException {
int width = row.getSize();
int rowOffset = row.getNextSet(0);
int counterPosition = 0;
int patternStart = rowOffset;
boolean isWhite = false;
int patternLength = counters.length;
for (int i = rowOffset; i < width; i++) {
if (row.get(i) ^ isWhite) {
counters[counterPosition]++;
} else {
if (counterPosition == patternLength - 1) {
// Look for whitespace before start pattern, >= 50% of width of start pattern
if (toNarrowWidePattern(counters) == ASTERISK_ENCODING &&
row.isRange(Math.max(0, patternStart - ((i - patternStart) >> 1)), patternStart, false)) {
return new int[]{patternStart, i};
}
patternStart += counters[0] + counters[1];
System.arraycopy(counters, 2, counters, 0, patternLength - 2);
counters[patternLength - 2] = 0;
counters[patternLength - 1] = 0;
counterPosition--;
} else {
counterPosition++;
}
counters[counterPosition] = 1;
isWhite = !isWhite;
}
}
throw NotFoundException.getNotFoundInstance();
}
// For efficiency, returns -1 on failure. Not throwing here saved as many as 700 exceptions
// per image when using some of our blackbox images.
private static int toNarrowWidePattern(int[] counters) {
int numCounters = counters.length;
int maxNarrowCounter = 0;
int wideCounters;
do {
int minCounter = Integer.MAX_VALUE;
for (int counter : counters) {
if (counter < minCounter && counter > maxNarrowCounter) {
minCounter = counter;
}
}
maxNarrowCounter = minCounter;
wideCounters = 0;
int totalWideCountersWidth = 0;
int pattern = 0;
for (int i = 0; i < numCounters; i++) {
int counter = counters[i];
if (counter > maxNarrowCounter) {
pattern |= 1 << (numCounters - 1 - i);
wideCounters++;
totalWideCountersWidth += counter;
}
}
if (wideCounters == 3) {
// Found 3 wide counters, but are they close enough in width?
// We can perform a cheap, conservative check to see if any individual
// counter is more than 1.5 times the average:
for (int i = 0; i < numCounters && wideCounters > 0; i++) {
int counter = counters[i];
if (counter > maxNarrowCounter) {
wideCounters--;
// totalWideCountersWidth = 3 * average, so this checks if counter >= 3/2 * average
if ((counter << 1) >= totalWideCountersWidth) {
return -1;
}
}
}
return pattern;
}
} while (wideCounters > 3);
return -1;
}
private static char patternToChar(int pattern) throws NotFoundException {
for (int i = 0; i < CHARACTER_ENCODINGS.length; i++) {
if (CHARACTER_ENCODINGS[i] == pattern) {
return ALPHABET[i];
}
}
throw NotFoundException.getNotFoundInstance();
}
private static String decodeExtended(CharSequence encoded) throws FormatException {
int length = encoded.length();
StringBuilder decoded = new StringBuilder(length);
for (int i = 0; i < length; i++) {
char c = encoded.charAt(i);
if (c == '+' || c == '$' || c == '%' || c == '/') {
char next = encoded.charAt(i + 1);
char decodedChar = '\0';
switch (c) {
case '+':
// +A to +Z map to a to z
if (next >= 'A' && next <= 'Z') {
decodedChar = (char) (next + 32);
} else {
throw FormatException.getFormatInstance();
}
break;
case '$':
// $A to $Z map to control codes SH to SB
if (next >= 'A' && next <= 'Z') {
decodedChar = (char) (next - 64);
} else {
throw FormatException.getFormatInstance();
}
break;
case '%':
// %A to %E map to control codes ESC to US
if (next >= 'A' && next <= 'E') {
decodedChar = (char) (next - 38);
} else if (next >= 'F' && next <= 'W') {
decodedChar = (char) (next - 11);
} else {
throw FormatException.getFormatInstance();
}
break;
case '/':
// /A to /O map to ! to , and /Z maps to :
if (next >= 'A' && next <= 'O') {
decodedChar = (char) (next - 32);
} else if (next == 'Z') {
decodedChar = ':';
} else {
throw FormatException.getFormatInstance();
}
break;
}
decoded.append(decodedChar);
// bump up i again since we read two characters
i++;
} else {
decoded.append(c);
}
}
return decoded.toString();
}
}
|
Issue 1776 fix bad location of Code 39 end pattern when followed by lots of white space
git-svn-id: b10e9e05a96f28f96949e4aa4212c55f640c8f96@2886 59b500cc-1b3d-0410-9834-0bbf25fbcc57
|
core/src/com/google/zxing/oned/Code39Reader.java
|
Issue 1776 fix bad location of Code 39 end pattern when followed by lots of white space
|
<ide><path>ore/src/com/google/zxing/oned/Code39Reader.java
<ide> }
<ide>
<ide> float left = (float) (start[1] + start[0]) / 2.0f;
<del> float right = (float) (nextStart + lastStart) / 2.0f;
<add> float right = lastStart + lastPatternSize / 2.0f;
<ide> return new Result(
<ide> resultString,
<ide> null,
|
|
Java
|
apache-2.0
|
3f2933b6e7dba839d782d5df3c279e3023c5bc21
| 0 |
looker-open-source/java-spanner,looker-open-source/java-spanner,looker-open-source/java-spanner,googleapis/java-spanner,googleapis/java-spanner,googleapis/java-spanner
|
/*
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.spanner.connection.it;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.fail;
import com.google.cloud.spanner.ErrorCode;
import com.google.cloud.spanner.Mutation;
import com.google.cloud.spanner.ParallelIntegrationTest;
import com.google.cloud.spanner.ResultSet;
import com.google.cloud.spanner.SpannerBatchUpdateException;
import com.google.cloud.spanner.SpannerException;
import com.google.cloud.spanner.Statement;
import com.google.cloud.spanner.connection.ITAbstractSpannerTest;
import com.google.cloud.spanner.connection.SqlScriptVerifier;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.runners.MethodSorters;
@Category(ParallelIntegrationTest.class)
@RunWith(JUnit4.class)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class ITReadWriteAutocommitSpannerTest extends ITAbstractSpannerTest {
@Override
protected void appendConnectionUri(StringBuilder uri) {
uri.append(";autocommit=true");
}
@Override
public boolean doCreateDefaultTestTable() {
return true;
}
@Test
public void test01_SqlScript() throws Exception {
SqlScriptVerifier verifier = new SqlScriptVerifier(new ITConnectionProvider());
verifier.verifyStatementsInFile(
"ITReadWriteAutocommitSpannerTest.sql", SqlScriptVerifier.class);
}
@Test
public void test02_WriteMutation() {
try (ITConnection connection = createConnection()) {
connection.write(
Mutation.newInsertBuilder("TEST").set("ID").to(9999L).set("NAME").to("FOO").build());
assertThat(connection.getCommitTimestamp(), is(notNullValue()));
}
}
@Test
public void test03_MultipleStatements_WithTimeouts() {
try (ITConnection connection = createConnection()) {
// do an insert that should succeed
assertThat(
connection.executeUpdate(
Statement.of("INSERT INTO TEST (ID, NAME) VALUES (1000, 'test')")),
is(equalTo(1L)));
// check that the insert succeeded
try (ResultSet rs =
connection.executeQuery(Statement.of("SELECT * FROM TEST WHERE ID=1000"))) {
assertThat(rs.next(), is(true));
assertThat(rs.getString("NAME"), is(equalTo("test")));
assertThat(rs.next(), is(false));
}
// do an update that should always time out (both on real Spanner as well as on the emulator)
connection.setStatementTimeout(1L, TimeUnit.NANOSECONDS);
try {
connection.executeUpdate(Statement.of("UPDATE TEST SET NAME='test18' WHERE ID=1000"));
fail("missing expected exception");
} catch (SpannerException e) {
assertThat(e.getErrorCode(), is(equalTo(ErrorCode.DEADLINE_EXCEEDED)));
}
// remove the timeout setting
connection.clearStatementTimeout();
// do a delete that should succeed
connection.executeUpdate(Statement.of("DELETE FROM TEST WHERE ID=1000"));
// verify that the delete did succeed
try (ResultSet rs =
connection.executeQuery(Statement.of("SELECT * FROM TEST WHERE ID=1000"))) {
assertThat(rs.next(), is(false));
}
}
}
@Test
public void test04_BatchUpdate() {
try (ITConnection connection = createConnection()) {
long[] updateCounts =
connection.executeBatchUpdate(
Arrays.asList(
Statement.of("INSERT INTO TEST (ID, NAME) VALUES (10, 'Batch value 1')"),
Statement.of("INSERT INTO TEST (ID, NAME) VALUES (11, 'Batch value 2')"),
Statement.of("INSERT INTO TEST (ID, NAME) VALUES (12, 'Batch value 3')"),
Statement.of("INSERT INTO TEST (ID, NAME) VALUES (13, 'Batch value 4')"),
Statement.of("INSERT INTO TEST (ID, NAME) VALUES (14, 'Batch value 5')"),
Statement.of("INSERT INTO TEST (ID, NAME) VALUES (15, 'Batch value 6')"),
Statement.of("INSERT INTO TEST (ID, NAME) VALUES (16, 'Batch value 7')"),
Statement.of("INSERT INTO TEST (ID, NAME) VALUES (17, 'Batch value 8')"),
Statement.of("INSERT INTO TEST (ID, NAME) VALUES (18, 'Batch value 9')"),
Statement.of("INSERT INTO TEST (ID, NAME) VALUES (19, 'Batch value 10')"),
Statement.of("INSERT INTO TEST (ID, NAME) VALUES (20, 'Batch value 11')")));
assertThat(
updateCounts, is(equalTo(new long[] {1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L})));
try (ResultSet rs =
connection.executeQuery(
Statement.of("SELECT COUNT(*) FROM TEST WHERE ID>=10 AND ID<=20"))) {
assertThat(rs.next(), is(true));
assertThat(rs.getLong(0), is(equalTo(11L)));
}
}
}
@Test
public void test05_BatchUpdateWithException() {
try (ITConnection con1 = createConnection();
ITConnection con2 = createConnection()) {
try {
con1.executeBatchUpdate(
Arrays.asList(
Statement.of("INSERT INTO TEST (ID, NAME) VALUES (21, 'Batch value 1')"),
Statement.of("INSERT INTO TEST (ID, NAME) VALUES (22, 'Batch value 2')"),
Statement.of("INSERT INTO TEST (ID, NAME) VALUES (23, 'Batch value 3')"),
Statement.of("INSERT INTO TEST (ID, NAME) VALUES (24, 'Batch value 4')"),
Statement.of("INSERT INTO TEST (ID, NAME) VALUES (25, 'Batch value 5')"),
Statement.of("INSERT INTO TEST_NOT_FOUND (ID, NAME) VALUES (26, 'Batch value 6')"),
Statement.of("INSERT INTO TEST (ID, NAME) VALUES (27, 'Batch value 7')"),
Statement.of("INSERT INTO TEST (ID, NAME) VALUES (28, 'Batch value 8')"),
Statement.of("INSERT INTO TEST (ID, NAME) VALUES (29, 'Batch value 9')"),
Statement.of("INSERT INTO TEST (ID, NAME) VALUES (30, 'Batch value 10')")));
fail("Missing batch update exception");
} catch (SpannerBatchUpdateException e) {
assertThat(e.getUpdateCounts(), is(equalTo(new long[] {1L, 1L, 1L, 1L, 1L})));
}
// Verify that the values cannot be read on the connection that did the insert.
try (ResultSet rs =
con1.executeQuery(Statement.of("SELECT COUNT(*) FROM TEST WHERE ID>=21 AND ID<=30"))) {
assertThat(rs.next(), is(true));
assertThat(rs.getLong(0), is(equalTo(0L)));
}
// Verify that the values can also not be read on another connection.
try (ResultSet rs =
con2.executeQuery(Statement.of("SELECT COUNT(*) FROM TEST WHERE ID>=21 AND ID<=30"))) {
assertThat(rs.next(), is(true));
assertThat(rs.getLong(0), is(equalTo(0L)));
}
}
}
}
|
google-cloud-spanner/src/test/java/com/google/cloud/spanner/connection/it/ITReadWriteAutocommitSpannerTest.java
|
/*
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.spanner.connection.it;
import static com.google.cloud.spanner.testing.EmulatorSpannerHelper.isUsingEmulator;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.fail;
import static org.junit.Assume.assumeFalse;
import com.google.cloud.spanner.ErrorCode;
import com.google.cloud.spanner.Mutation;
import com.google.cloud.spanner.ParallelIntegrationTest;
import com.google.cloud.spanner.ResultSet;
import com.google.cloud.spanner.SpannerBatchUpdateException;
import com.google.cloud.spanner.SpannerException;
import com.google.cloud.spanner.Statement;
import com.google.cloud.spanner.connection.ITAbstractSpannerTest;
import com.google.cloud.spanner.connection.SqlScriptVerifier;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.runners.MethodSorters;
@Category(ParallelIntegrationTest.class)
@RunWith(JUnit4.class)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class ITReadWriteAutocommitSpannerTest extends ITAbstractSpannerTest {
@Override
protected void appendConnectionUri(StringBuilder uri) {
uri.append(";autocommit=true");
}
@Override
public boolean doCreateDefaultTestTable() {
return true;
}
@Test
public void test01_SqlScript() throws Exception {
SqlScriptVerifier verifier = new SqlScriptVerifier(new ITConnectionProvider());
verifier.verifyStatementsInFile(
"ITReadWriteAutocommitSpannerTest.sql", SqlScriptVerifier.class);
}
@Test
public void test02_WriteMutation() {
try (ITConnection connection = createConnection()) {
connection.write(
Mutation.newInsertBuilder("TEST").set("ID").to(9999L).set("NAME").to("FOO").build());
assertThat(connection.getCommitTimestamp(), is(notNullValue()));
}
}
@Test
public void test03_MultipleStatements_WithTimeouts() {
assumeFalse(
"Rolling back a transaction while an update statement is still in flight can cause the transaction to remain active on the emulator",
isUsingEmulator());
try (ITConnection connection = createConnection()) {
// do an insert that should succeed
assertThat(
connection.executeUpdate(
Statement.of("INSERT INTO TEST (ID, NAME) VALUES (1000, 'test')")),
is(equalTo(1L)));
// check that the insert succeeded
try (ResultSet rs =
connection.executeQuery(Statement.of("SELECT * FROM TEST WHERE ID=1000"))) {
assertThat(rs.next(), is(true));
assertThat(rs.getString("NAME"), is(equalTo("test")));
assertThat(rs.next(), is(false));
}
// do an update that should time out
connection.setStatementTimeout(1L, TimeUnit.MILLISECONDS);
try {
connection.executeUpdate(Statement.of("UPDATE TEST SET NAME='test18' WHERE ID=1000"));
fail("missing expected exception");
} catch (SpannerException e) {
assertThat(e.getErrorCode(), is(equalTo(ErrorCode.DEADLINE_EXCEEDED)));
}
// remove the timeout setting
connection.clearStatementTimeout();
// do a delete that should succeed
connection.executeUpdate(Statement.of("DELETE FROM TEST WHERE ID=1000"));
// verify that the delete did succeed
try (ResultSet rs =
connection.executeQuery(Statement.of("SELECT * FROM TEST WHERE ID=1000"))) {
assertThat(rs.next(), is(false));
}
}
}
@Test
public void test04_BatchUpdate() {
try (ITConnection connection = createConnection()) {
long[] updateCounts =
connection.executeBatchUpdate(
Arrays.asList(
Statement.of("INSERT INTO TEST (ID, NAME) VALUES (10, 'Batch value 1')"),
Statement.of("INSERT INTO TEST (ID, NAME) VALUES (11, 'Batch value 2')"),
Statement.of("INSERT INTO TEST (ID, NAME) VALUES (12, 'Batch value 3')"),
Statement.of("INSERT INTO TEST (ID, NAME) VALUES (13, 'Batch value 4')"),
Statement.of("INSERT INTO TEST (ID, NAME) VALUES (14, 'Batch value 5')"),
Statement.of("INSERT INTO TEST (ID, NAME) VALUES (15, 'Batch value 6')"),
Statement.of("INSERT INTO TEST (ID, NAME) VALUES (16, 'Batch value 7')"),
Statement.of("INSERT INTO TEST (ID, NAME) VALUES (17, 'Batch value 8')"),
Statement.of("INSERT INTO TEST (ID, NAME) VALUES (18, 'Batch value 9')"),
Statement.of("INSERT INTO TEST (ID, NAME) VALUES (19, 'Batch value 10')"),
Statement.of("INSERT INTO TEST (ID, NAME) VALUES (20, 'Batch value 11')")));
assertThat(
updateCounts, is(equalTo(new long[] {1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L})));
try (ResultSet rs =
connection.executeQuery(
Statement.of("SELECT COUNT(*) FROM TEST WHERE ID>=10 AND ID<=20"))) {
assertThat(rs.next(), is(true));
assertThat(rs.getLong(0), is(equalTo(11L)));
}
}
}
@Test
public void test05_BatchUpdateWithException() {
try (ITConnection con1 = createConnection();
ITConnection con2 = createConnection()) {
try {
con1.executeBatchUpdate(
Arrays.asList(
Statement.of("INSERT INTO TEST (ID, NAME) VALUES (21, 'Batch value 1')"),
Statement.of("INSERT INTO TEST (ID, NAME) VALUES (22, 'Batch value 2')"),
Statement.of("INSERT INTO TEST (ID, NAME) VALUES (23, 'Batch value 3')"),
Statement.of("INSERT INTO TEST (ID, NAME) VALUES (24, 'Batch value 4')"),
Statement.of("INSERT INTO TEST (ID, NAME) VALUES (25, 'Batch value 5')"),
Statement.of("INSERT INTO TEST_NOT_FOUND (ID, NAME) VALUES (26, 'Batch value 6')"),
Statement.of("INSERT INTO TEST (ID, NAME) VALUES (27, 'Batch value 7')"),
Statement.of("INSERT INTO TEST (ID, NAME) VALUES (28, 'Batch value 8')"),
Statement.of("INSERT INTO TEST (ID, NAME) VALUES (29, 'Batch value 9')"),
Statement.of("INSERT INTO TEST (ID, NAME) VALUES (30, 'Batch value 10')")));
fail("Missing batch update exception");
} catch (SpannerBatchUpdateException e) {
assertThat(e.getUpdateCounts(), is(equalTo(new long[] {1L, 1L, 1L, 1L, 1L})));
}
// Verify that the values cannot be read on the connection that did the insert.
try (ResultSet rs =
con1.executeQuery(Statement.of("SELECT COUNT(*) FROM TEST WHERE ID>=21 AND ID<=30"))) {
assertThat(rs.next(), is(true));
assertThat(rs.getLong(0), is(equalTo(0L)));
}
// Verify that the values can also not be read on another connection.
try (ResultSet rs =
con2.executeQuery(Statement.of("SELECT COUNT(*) FROM TEST WHERE ID>=21 AND ID<=30"))) {
assertThat(rs.next(), is(true));
assertThat(rs.getLong(0), is(equalTo(0L)));
}
}
}
}
|
test: enable timeout test on emulator (#952)
* test: enable timeout tests on emulator
* fix: remove test loop
|
google-cloud-spanner/src/test/java/com/google/cloud/spanner/connection/it/ITReadWriteAutocommitSpannerTest.java
|
test: enable timeout test on emulator (#952)
|
<ide><path>oogle-cloud-spanner/src/test/java/com/google/cloud/spanner/connection/it/ITReadWriteAutocommitSpannerTest.java
<ide>
<ide> package com.google.cloud.spanner.connection.it;
<ide>
<del>import static com.google.cloud.spanner.testing.EmulatorSpannerHelper.isUsingEmulator;
<ide> import static org.hamcrest.CoreMatchers.equalTo;
<ide> import static org.hamcrest.CoreMatchers.is;
<ide> import static org.hamcrest.CoreMatchers.notNullValue;
<ide> import static org.hamcrest.MatcherAssert.assertThat;
<ide> import static org.junit.Assert.fail;
<del>import static org.junit.Assume.assumeFalse;
<ide>
<ide> import com.google.cloud.spanner.ErrorCode;
<ide> import com.google.cloud.spanner.Mutation;
<ide>
<ide> @Test
<ide> public void test03_MultipleStatements_WithTimeouts() {
<del> assumeFalse(
<del> "Rolling back a transaction while an update statement is still in flight can cause the transaction to remain active on the emulator",
<del> isUsingEmulator());
<ide> try (ITConnection connection = createConnection()) {
<ide> // do an insert that should succeed
<ide> assertThat(
<ide> assertThat(rs.next(), is(false));
<ide> }
<ide>
<del> // do an update that should time out
<del> connection.setStatementTimeout(1L, TimeUnit.MILLISECONDS);
<add> // do an update that should always time out (both on real Spanner as well as on the emulator)
<add> connection.setStatementTimeout(1L, TimeUnit.NANOSECONDS);
<ide> try {
<ide> connection.executeUpdate(Statement.of("UPDATE TEST SET NAME='test18' WHERE ID=1000"));
<ide> fail("missing expected exception");
|
|
Java
|
apache-2.0
|
722578f6178252d4594f6d0343626d88d72732c9
| 0 |
kariminf/SentRep
|
package dz.aak.sentrep.ston;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
*
* @author Abdelkrime Aries
*
*/
public abstract class Parser {
// These are the characters to be ignored
private static String BL = "[\\t \\n\\r]+";
// Adpositional clause: time or location
private static final String ADPblock = "@adp\\:\\[(.*)adp\\:\\];?";
// Adjective
private static final String ADJblock = "@adj\\:\\[(.*)adj\\:\\];?";
// Relative clauses
private static final String RELblock = "@rel\\:\\[(.*)rel\\:\\];?";
// This is the regular expression used to separate main blocks
private static final Pattern CONT =
Pattern.compile("@r\\:\\[(.+)r\\:\\]@act\\:\\[(.+)act\\:\\]@sent\\:\\[(.+)sent\\:\\]");
//This is true when the parsing is a success
private boolean success = false;
/**
* The constructor of the parser
*/
public Parser() {
success = false;
}
/**
* The method to parse a STON description
* @param description STON description
*/
public void parse(String description){
description = description.replaceAll(BL, "");
description = description.toLowerCase();
//System.out.println(description);
Matcher m = CONT.matcher(description);
if (m.find()) {
String roles = m.group(1);
String actions = m.group(2);
if (! parseRoles(roles)) return;
if (! parseActions(actions)) return;
}
success = true;
parseSuccess();
}
/**
* This function tells us if the parsing goes well or not
* @return True: if the parsing succeed, False: else.
*/
public boolean parsed(){
return success;
}
/**
* Parses the roles' block
* @param description STON description of roles
* @return True if there is no error
*/
private boolean parseRoles(String description){
int idx;
while ((idx = description.indexOf("r:}")) >= 0) {
String role = description.substring(3, idx);
description = description.substring(idx+3);
//System.out.println(role);
if (! parseRole(role))
return false;
}
return true;
}
/**
* Parses the actions' block
* @param description STON description of actions
* @return True if there is no error
*/
private boolean parseActions (String description){
int idx;
while ((idx = description.indexOf("act:}")) >= 0) {
String action = description.substring(5, idx);
description = description.substring(idx+5);
//System.out.println(role);
if (! parseAction(action))
return false;
}
return true;
}
/**
* Parses one action block
* @param description STON description of one action
* @return True if there is no error
*/
private boolean parseAction(String description){
String id = "";
String synSetStr = "";
String tense = "";
boolean progressive = false;
boolean negated = false;
String modality = "none";
String subjects = "";
String objects = "";
String adpositional = "";
if (description.contains("@adp")){
Pattern timesPattern =
Pattern.compile("(.*)" + ADPblock + "(.*)");
Matcher m = timesPattern.matcher(description);
if (m.find()){
adpositional = m.group(2);
//System.out.println("time found");
description = m.group(1) + m.group(3);
}
}
for (String desc : description.split(";")){
desc = desc.trim();
if(desc.startsWith("id:")){
id = desc.split(":")[1];
continue;
}
if(desc.startsWith("synset:")){
synSetStr = desc.split(":")[1];
continue;
}
if(desc.startsWith("tense:")){
tense = desc.split(":")[1];
continue;
}
if(desc.startsWith("progressive:")){
String aspect = desc.split(":")[1];
aspect = aspect.trim().toUpperCase();
if(aspect.matches("yes")){
progressive = true;
}
continue;
}
if(desc.startsWith("negated:")){
String negate = desc.split(":")[1];
negate = negate.trim().toUpperCase();
if(negate.matches("yes")){
negated = true;
}
continue;
}
if(desc.startsWith("modality:")){
modality = desc.split(":")[1];
continue;
}
if(desc.startsWith("subjects:")){
subjects = desc.split(":")[1];
continue;
}
if(desc.startsWith("objects:")){
objects = desc.split(":")[1];
continue;
}
}
//The action must have an ID
if(id.length() < 1){
actionFail();
success = false;
return false;
}
// An action must have a synset which is a number
if (! synSetStr.matches("\\d+")){
roleFail();
success = false;
return false;
}
int synSet = Integer.parseInt(synSetStr);
addAction(id, synSet);
// There are three tenses
if(! tense.matches("past|present|future")){
tense = "present";
}
// There are three modalities: permissibility, possibility and obligation
if(! modality.matches("can|may|must")){
modality = "none";
}
//Defines verb specifications
addVerbSpecif(tense, modality, progressive, negated);
// Process subjects
if(subjects.length() > 2){
if (!(subjects.startsWith("[") && subjects.endsWith("]"))){
//System.out.println("subjects=" + subjects);
return false;
}
subjects = subjects.substring(1, subjects.length()-1);
addSubjects();
parseComponents(subjects);
}
//Process objects
if(objects.length() > 2){
if (!(objects.startsWith("[") && objects.endsWith("]")))
return false;
objects = objects.substring(1, objects.length()-1);
addObjects();
parseComponents(objects);
}
// Process time and place
if (adpositional.length()>0){
if (! parseAdpositionals(adpositional)) return false;
}
return true;
}
/**
* Subjects and objects are disjunctions of conjunctions, they are
* represented like [id11, ...|id21, ... | ...] <br/>
* For example: [mother, son|father] means: mother and son or father
* @param description STON description of IDs
* @return True if there is no error
*/
private boolean parseComponents(String description){
String[] disjunctions = description.split("\\|");
for (String disjunction: disjunctions){
Set<String> conjunctions = new HashSet<String>();
for (String conjunction: disjunction.split(",")){
conjunctions.add(conjunction);
}
addConjunctions(conjunctions);
}
return true;
}
/**
* Parse the
* @param description
* @return
*/
private boolean parseAdjectives(String description){
int idx;
while ((idx = description.indexOf("adj:}")) >= 0) {
String adjective = description.substring(5, idx);
description = description.substring(idx+5);
if (description.startsWith(","))
description = description.substring(1);
String[] descs = adjective.split(";");
int synSet = 0;
HashSet<Integer> advSynSets = new HashSet<Integer>();
for (String desc: descs){
if(desc.startsWith("synset:")){
String synSetStr = desc.split(":")[1];
synSet = Integer.parseInt(synSetStr);
continue;
}
if(desc.startsWith("adverbs:")){
String synSetStrs = desc.split(":")[1];
synSetStrs = synSetStrs.substring(1, synSetStrs.length()-1);
for (String AdvsynSetStr: synSetStrs.split(",")){
int AdvsynSet = Integer.parseInt(AdvsynSetStr);
advSynSets.add(AdvsynSet);
}
}
}
if (synSet < 1){
adjectiveFail();
success = false;
return false;
}
addAdjective(synSet, advSynSets);
}
return true;
}
//TODO complete role relatives
private boolean parseRRelatives(String description){
return true;
}
private boolean parseRole(String description){
String id = "";
String synSetStr = "";
String adjectives = "";
String relatives = "";
if (description.contains("@adj")){
Pattern adpPattern =
Pattern.compile("(.*)" + ADJblock + "(.*)");
Matcher m = adpPattern.matcher(description);
if (m.find()){
adjectives = m.group(2);
//System.out.println("time found");
description = m.group(1) + m.group(3);
}
}
if (description.contains("@rel")){
Pattern adpPattern =
Pattern.compile("(.*)" + RELblock + "(.*)");
Matcher m = adpPattern.matcher(description);
if (m.find()){
relatives = m.group(2);
//System.out.println("time found");
description = m.group(1) + m.group(3);
}
}
for (String desc: description.split(";")){
desc = desc.trim();
if(desc.startsWith("id:")){
id = desc.split(":")[1];
continue;
}
if(desc.startsWith("synset:")){
synSetStr = desc.split(":")[1];
continue;
}
}
//A role must have an ID
if (id.length() < 1){
roleFail();
success = false;
return false;
}
// A role must have a synset which is a number
if (! synSetStr.matches("\\d+")){
roleFail();
success = false;
return false;
}
int synSet = Integer.parseInt(synSetStr);
// Add the role
addRole(id, synSet);
//Process adjectives
if (adjectives.length() > 0){
if (! parseAdjectives(adjectives)) return false;
}
//Process relatives
if (relatives.length() > 0){
if (! parseRRelatives(relatives)) return false;
}
return true;
}
/**
*
* @param description
* @return
*/
private boolean parseAdpositionals(String description){
//TODO fix the adpositionals content
int idx;
while ((idx = description.indexOf("adp:}")) >= 0) {
String times = description.substring(5, idx);
description = description.substring(idx+5);
/*
Matcher m = Pattern.compile("synset\\:([^;]+)(;|$)").matcher(times);
if (! m.find()){
success = false;
return false;
}
String synSetStr = m.group(1);
int synSet = Integer.parseInt(synSetStr);
addAddpositional(synSet);
m = Pattern.compile("predicates\\:\\[(.+)\\]").matcher(times);
if ( m.find()){
String predicates = m.group(1);
parseComponents(predicates);
}
*/
}
return true;
}
//Action
/**
* It is called when the parser finds an action
* @param id each action has a unique ID
* @param synSet this is the synset
*/
protected abstract void addAction(String id, int synSet);
/**
* It is called to define the specifications of a verb
* @param tense It is the tense of the verb: past, present or future
* @param modality It is the modal verb: can, must, may, none
* @param progressive the action is progressive or not
* @param negated the action is negated or not
*/
protected abstract void addVerbSpecif(String tense, String modality, boolean progressive, boolean negated);
/**
* It is called when the action is failed; It means when the parser find something
* wrong in the action block
*/
protected abstract void actionFail();
//Subjects and Objects in the Action
/**
* It is called when the parser finds subjects
*/
protected abstract void addSubjects();
/**
* It is called when the parser finds objects
*/
protected abstract void addObjects();
//Role
/**
* It is called when the parser finds a role player
* @param id each role has a unique ID
* @param synSet wordnet synset of the Noun
*/
protected abstract void addRole(String id, int synSet);
/**
* It is called when the role player has an adjective
* @param synSet wordnet synset of the adjective which modify the noun in the role
* @param advSynSets wordnet synsets (Set) of adverbs which modify the adjective
*/
protected abstract void addAdjective(int synSet, Set<Integer> advSynSets);
/**
* It is called when the parsing of an adjective failed
*/
protected abstract void adjectiveFail();
/**
* it is called when the parsing of a role failed
*/
protected abstract void roleFail();
/**
* It is called when the parsing of adpositionals failed
*/
protected abstract void adpositionalFail();
/**
* It is called to add an adpositional: time or location
* @param type the type of the addpositional
*/
protected abstract void addAdpositional(String type);
//can be used for subjects, objects, places or times
protected abstract void addConjunctions(Set<String> IDs);
//Parse
protected abstract void parseSuccess();
}
|
src/main/dz/aak/sentrep/ston/Parser.java
|
package dz.aak.sentrep.ston;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
*
* @author Abdelkrime Aries
*
*/
public abstract class Parser {
// These are the characters to be ignored
private static String BL = "[\\t \\n\\r]+";
// This is the times block regular expression
private static final String TIMESblock = "@times\\:t\\:\\[(.*)t\\:\\];?";
// This is the places block regular expression
private static final String PLACESblock = "@places\\:p\\:\\[(.*)p\\:\\];?";
// This is the regular expression used to separate main blocks
private static final Pattern CONT =
Pattern.compile("@roles\\:r\\:\\[(.+)r\\:\\]@actions\\:act\\:\\[(.+)act\\:\\]");
//This is true when the parsing is a success
private boolean success = false;
/**
* The constructor of the parser
*/
public Parser() {
success = false;
}
/**
* The method to parse a STON description
* @param description STON description
*/
public void parse(String description){
description = description.replaceAll(BL, "");
//System.out.println(description);
Matcher m = CONT.matcher(description);
if (m.find()) {
String roles = m.group(1);
String actions = m.group(2);
if (! parseRoles(roles)) return;
if (! parseActions(actions)) return;
}
success = true;
parseSuccess();
}
/**
* This function tells us if the parsing goes well or not
* @return True: if the parsing succeed, False: else.
*/
public boolean parsed(){
return success;
}
/**
* Parses the roles' block
* @param description STON description of roles
* @return True if there is no error
*/
private boolean parseRoles(String description){
int idx;
while ((idx = description.indexOf("r:}")) >= 0) {
String role = description.substring(3, idx);
description = description.substring(idx+3);
//System.out.println(role);
if (! parseRole(role))
return false;
}
return true;
}
/**
* Parses the actions' block
* @param description STON description of actions
* @return True if there is no error
*/
private boolean parseActions (String description){
int idx;
while ((idx = description.indexOf("act:}")) >= 0) {
String action = description.substring(5, idx);
description = description.substring(idx+5);
//System.out.println(role);
if (! parseAction(action))
return false;
}
return true;
}
/**
* Parses one action block
* @param description STON description of one action
* @return True if there is no error
*/
private boolean parseAction(String description){
String description2 = description;
String id = "";
String synSetStr = "";
String tense = "";
boolean progressive = false;
boolean negated = false;
String modality = "NONE";
String subjects = "";
String objects = "";
String times = "";
String places = "";
if (description2.contains("@times")){
Pattern timesPattern =
Pattern.compile("(.*)" + TIMESblock + "(.*)");
Matcher m = timesPattern.matcher(description2);
if (m.find()){
times = m.group(2);
//System.out.println("time found");
description2 = m.group(1) + m.group(3);
}
}
if (description2.contains("@places")){
Pattern timesPattern =
Pattern.compile("(.*)" + PLACESblock + "(.*)");
Matcher m = timesPattern.matcher(description2);
if (m.find()){
places = m.group(2);
//System.out.println("time found");
description2 = m.group(1) + m.group(3);
}
}
String[] descs = description2.split(";");
for (String desc : descs){
desc = desc.trim();
if(desc.startsWith("id:")){
id = desc.split(":")[1];
continue;
}
if(desc.startsWith("synSet:")){
synSetStr = desc.split(":")[1];
continue;
}
if(desc.startsWith("tense:")){
tense = desc.split(":")[1];
continue;
}
if(desc.startsWith("progressive:")){
String aspect = desc.split(":")[1];
aspect = aspect.trim().toUpperCase();
if(aspect.matches("YES")){
progressive = true;
}
continue;
}
if(desc.startsWith("negated:")){
String negate = desc.split(":")[1];
negate = negate.trim().toUpperCase();
if(negate.matches("YES")){
negated = true;
}
continue;
}
if(desc.startsWith("modality:")){
modality = desc.split(":")[1];
continue;
}
if(desc.startsWith("subjects:")){
subjects = desc.split(":")[1];
continue;
}
if(desc.startsWith("objects:")){
objects = desc.split(":")[1];
continue;
}
}
if(id.length() < 1){
actionFail();
success = false;
return false;
}
int synSet = Integer.parseInt(synSetStr);
addAction(id, synSet);
//TODO add other components of the action
if(! tense.matches("PAST|PRESENT|FUTURE")){
tense = "PRESENT";
}
modality = modality.trim().toUpperCase();
if(! modality.matches("CAN|MAY|MUST")){
modality = "NONE";
}
addVerbSpecif(tense, modality, progressive, negated);
if (times.length()>0){
if (! parseTimes(times)) return false;
}
if (places.length()>0){
if (! parsePlaces(places)) return false;
}
if(subjects.length() > 2){
if (!(subjects.startsWith("[") && subjects.endsWith("]"))){
System.out.println("subjects=" + subjects);
return false;
}
subjects = subjects.substring(1, subjects.length()-1);
addSubjects();
parseComponents(subjects);
}
if(objects.length() > 2){
if (!(objects.startsWith("[") && objects.endsWith("]")))
return false;
objects = objects.substring(1, objects.length()-1);
addObjects();
parseComponents(objects);
}
return true;
}
/**
* Subjects and objects are disjunctions of conjunctions, they are
* represented like [id11, ...|id21, ... | ...] <br/>
* For example: [mother, son|father] means: mother and son or father
* @param description STON description of IDs
* @return True if there is no error
*/
private boolean parseComponents(String description){
String[] disjunctions = description.split("\\|");
for (String disjunction: disjunctions){
Set<String> conjunctions = new HashSet<String>();
for (String conjunction: disjunction.split(",")){
conjunctions.add(conjunction);
}
addConjunctions(conjunctions);
}
return true;
}
/**
* Parse the
* @param description
* @return
*/
private boolean parseAdjectives(String description){
int idx;
while ((idx = description.indexOf("adj:}")) >= 0) {
String adjective = description.substring(5, idx);
description = description.substring(idx+5);
if (description.startsWith(","))
description = description.substring(1);
String[] descs = adjective.split(";");
int synSet = 0;
HashSet<Integer> advSynSets = new HashSet<Integer>();
for (String desc: descs){
if(desc.startsWith("synSet:")){
String synSetStr = desc.split(":")[1];
synSet = Integer.parseInt(synSetStr);
continue;
}
if(desc.startsWith("adverbs:")){
String synSetStrs = desc.split(":")[1];
synSetStrs = synSetStrs.substring(1, synSetStrs.length()-1);
for (String AdvsynSetStr: synSetStrs.split(",")){
int AdvsynSet = Integer.parseInt(AdvsynSetStr);
advSynSets.add(AdvsynSet);
}
}
}
if (synSet < 1){
adjectiveFail();
success = false;
return false;
}
addAdjective(synSet, advSynSets);
}
return true;
}
private boolean parseRole(String description){
Matcher m = Pattern.compile("id\\:([^;]+)(;|$)").matcher(description);
if (! m.find()){
roleFail();
success = false;
return false;
}
String id = m.group(1);
m = Pattern.compile("synSet\\:([^;]+)(;|$)").matcher(description);
if (! m.find()){
roleFail();
success = false;
return false;
}
String synSetStr = m.group(1);
int synSet = Integer.parseInt(synSetStr);
addRole(id, synSet);
m = Pattern.compile("adjectives\\:\\[(.+adj\\:\\})\\]").matcher(description);
if (m.find()){
String adjectives = m.group(1);
if (! parseAdjectives(adjectives)) return false;
}
return true;
}
/**
*
* @param description
* @return
*/
private boolean parseTimes(String description){
int idx;
while ((idx = description.indexOf("t:}")) >= 0) {
String times = description.substring(3, idx);
description = description.substring(idx+3);
Matcher m = Pattern.compile("synSet\\:([^;]+)(;|$)").matcher(times);
if (! m.find()){
success = false;
return false;
}
String synSetStr = m.group(1);
int synSet = Integer.parseInt(synSetStr);
addTime(synSet);
m = Pattern.compile("predicates\\:\\[(.+)\\]").matcher(times);
if ( m.find()){
String predicates = m.group(1);
parseComponents(predicates);
}
}
return true;
}
/**
* Parse the places in an action
* @param description STON description for places
* @return
*/
private boolean parsePlaces(String description){
int idx;
while ((idx = description.indexOf("p:}")) >= 0) {
String times = description.substring(3, idx);
description = description.substring(idx+3);
Matcher m = Pattern.compile("synSet\\:([^;]+)(;|$)").matcher(times);
if (! m.find()){
success = false;
return false;
}
String synSetStr = m.group(1);
int synSet = Integer.parseInt(synSetStr);
addPlace(synSet);
m = Pattern.compile("predicates\\:\\[(.+)\\]").matcher(times);
if ( m.find()){
String predicates = m.group(1);
parseComponents(predicates);
}
}
return true;
}
//Action
/**
* It is called when the parser finds an action
* @param id each action has a unique ID
* @param synSet this is the synset
*/
protected abstract void addAction(String id, int synSet);
/**
* It is called to define the specifications of a verb
* @param tense It is the tense of the verb: past, present or future
* @param modality It is the modal verb: can, must, may, none
* @param progressive the action is progressive or not
* @param negated the action is negated or not
*/
protected abstract void addVerbSpecif(String tense, String modality, boolean progressive, boolean negated);
/**
* It is called when the action is failed; It means when the parser find something
* wrong in the action block
*/
protected abstract void actionFail();
//Subjects and Objects in the Action
/**
* It is called when the parser finds subjects
*/
protected abstract void addSubjects();
/**
* It is called when the parser finds objects
*/
protected abstract void addObjects();
//Role
/**
* It is called when the parser finds a role player
* @param id each role has a unique ID
* @param synSet wordnet synset of the Noun
*/
protected abstract void addRole(String id, int synSet);
/**
* It is called when the role player has an adjective
* @param synSet wordnet synset of the adjective which modify the noun in the role
* @param advSynSets wordnet synsets (Set) of adverbs which modify the adjective
*/
protected abstract void addAdjective(int synSet, Set<Integer> advSynSets);
/**
* It is called when the parsing of an adjective failed
*/
protected abstract void adjectiveFail();
/**
* it is called when the parsing of a role failed
*/
protected abstract void roleFail();
/**
* It is called when the parsing of times failed
*/
protected abstract void timesFail();
/**
* It is called to add a time
* @param synSet the synset of a time like: yesterday
*/
protected abstract void addTime(int synSet);
/**
* It is called to add a location
* @param synSetthe synset of a location like: outside
*/
protected abstract void addPlace(int synSet);
//can be used for subjects, objects, places or times
protected abstract void addConjunctions(Set<String> IDs);
//Parse
protected abstract void parseSuccess();
}
|
time+place => adpositioal, add role relatives
|
src/main/dz/aak/sentrep/ston/Parser.java
|
time+place => adpositioal, add role relatives
|
<ide><path>rc/main/dz/aak/sentrep/ston/Parser.java
<ide> // These are the characters to be ignored
<ide> private static String BL = "[\\t \\n\\r]+";
<ide>
<del> // This is the times block regular expression
<del> private static final String TIMESblock = "@times\\:t\\:\\[(.*)t\\:\\];?";
<del>
<del> // This is the places block regular expression
<del> private static final String PLACESblock = "@places\\:p\\:\\[(.*)p\\:\\];?";
<add> // Adpositional clause: time or location
<add> private static final String ADPblock = "@adp\\:\\[(.*)adp\\:\\];?";
<add>
<add> // Adjective
<add> private static final String ADJblock = "@adj\\:\\[(.*)adj\\:\\];?";
<add>
<add> // Relative clauses
<add> private static final String RELblock = "@rel\\:\\[(.*)rel\\:\\];?";
<ide>
<ide> // This is the regular expression used to separate main blocks
<ide> private static final Pattern CONT =
<del> Pattern.compile("@roles\\:r\\:\\[(.+)r\\:\\]@actions\\:act\\:\\[(.+)act\\:\\]");
<add> Pattern.compile("@r\\:\\[(.+)r\\:\\]@act\\:\\[(.+)act\\:\\]@sent\\:\\[(.+)sent\\:\\]");
<ide>
<ide> //This is true when the parsing is a success
<ide> private boolean success = false;
<ide> public void parse(String description){
<ide>
<ide> description = description.replaceAll(BL, "");
<add> description = description.toLowerCase();
<ide>
<ide> //System.out.println(description);
<ide> Matcher m = CONT.matcher(description);
<ide> */
<ide> private boolean parseAction(String description){
<ide>
<del> String description2 = description;
<del>
<ide> String id = "";
<ide> String synSetStr = "";
<ide> String tense = "";
<ide> boolean progressive = false;
<ide> boolean negated = false;
<del> String modality = "NONE";
<add> String modality = "none";
<ide> String subjects = "";
<ide> String objects = "";
<ide>
<del> String times = "";
<del> String places = "";
<del>
<del> if (description2.contains("@times")){
<add> String adpositional = "";
<add>
<add> if (description.contains("@adp")){
<ide>
<ide> Pattern timesPattern =
<del> Pattern.compile("(.*)" + TIMESblock + "(.*)");
<del> Matcher m = timesPattern.matcher(description2);
<add> Pattern.compile("(.*)" + ADPblock + "(.*)");
<add> Matcher m = timesPattern.matcher(description);
<ide> if (m.find()){
<del> times = m.group(2);
<add> adpositional = m.group(2);
<ide> //System.out.println("time found");
<del> description2 = m.group(1) + m.group(3);
<del> }
<del> }
<del>
<del> if (description2.contains("@places")){
<del>
<del> Pattern timesPattern =
<del> Pattern.compile("(.*)" + PLACESblock + "(.*)");
<del> Matcher m = timesPattern.matcher(description2);
<del> if (m.find()){
<del> places = m.group(2);
<del> //System.out.println("time found");
<del> description2 = m.group(1) + m.group(3);
<del> }
<del> }
<del>
<del> String[] descs = description2.split(";");
<del>
<del> for (String desc : descs){
<add> description = m.group(1) + m.group(3);
<add> }
<add> }
<add>
<add> for (String desc : description.split(";")){
<ide>
<ide> desc = desc.trim();
<ide>
<ide> continue;
<ide> }
<ide>
<del> if(desc.startsWith("synSet:")){
<add> if(desc.startsWith("synset:")){
<ide> synSetStr = desc.split(":")[1];
<ide> continue;
<ide> }
<ide> String aspect = desc.split(":")[1];
<ide> aspect = aspect.trim().toUpperCase();
<ide>
<del> if(aspect.matches("YES")){
<add> if(aspect.matches("yes")){
<ide> progressive = true;
<ide> }
<ide> continue;
<ide> String negate = desc.split(":")[1];
<ide> negate = negate.trim().toUpperCase();
<ide>
<del> if(negate.matches("YES")){
<add> if(negate.matches("yes")){
<ide> negated = true;
<ide> }
<ide> continue;
<ide> }
<ide> }
<ide>
<add> //The action must have an ID
<ide> if(id.length() < 1){
<ide> actionFail();
<ide> success = false;
<ide> return false;
<ide> }
<ide>
<add> // An action must have a synset which is a number
<add> if (! synSetStr.matches("\\d+")){
<add> roleFail();
<add> success = false;
<add> return false;
<add> }
<add>
<ide> int synSet = Integer.parseInt(synSetStr);
<ide>
<ide> addAction(id, synSet);
<ide>
<del> //TODO add other components of the action
<del> if(! tense.matches("PAST|PRESENT|FUTURE")){
<del> tense = "PRESENT";
<del> }
<del>
<del> modality = modality.trim().toUpperCase();
<del>
<del> if(! modality.matches("CAN|MAY|MUST")){
<del> modality = "NONE";
<del> }
<del>
<del>
<add> // There are three tenses
<add> if(! tense.matches("past|present|future")){
<add> tense = "present";
<add> }
<add>
<add> // There are three modalities: permissibility, possibility and obligation
<add> if(! modality.matches("can|may|must")){
<add> modality = "none";
<add> }
<add>
<add> //Defines verb specifications
<ide> addVerbSpecif(tense, modality, progressive, negated);
<del>
<del> if (times.length()>0){
<del> if (! parseTimes(times)) return false;
<del> }
<del>
<del> if (places.length()>0){
<del> if (! parsePlaces(places)) return false;
<del> }
<del>
<del>
<add>
<add> // Process subjects
<ide> if(subjects.length() > 2){
<ide> if (!(subjects.startsWith("[") && subjects.endsWith("]"))){
<del> System.out.println("subjects=" + subjects);
<add> //System.out.println("subjects=" + subjects);
<ide> return false;
<ide> }
<del>
<add>
<ide> subjects = subjects.substring(1, subjects.length()-1);
<ide> addSubjects();
<ide> parseComponents(subjects);
<ide>
<ide> }
<ide>
<add> //Process objects
<ide> if(objects.length() > 2){
<ide> if (!(objects.startsWith("[") && objects.endsWith("]")))
<ide> return false;
<ide>
<ide> }
<ide>
<add> // Process time and place
<add> if (adpositional.length()>0){
<add> if (! parseAdpositionals(adpositional)) return false;
<add> }
<ide>
<ide> return true;
<ide> }
<ide> int synSet = 0;
<ide> HashSet<Integer> advSynSets = new HashSet<Integer>();
<ide> for (String desc: descs){
<del> if(desc.startsWith("synSet:")){
<add> if(desc.startsWith("synset:")){
<ide> String synSetStr = desc.split(":")[1];
<ide> synSet = Integer.parseInt(synSetStr);
<ide> continue;
<ide> }
<ide>
<ide>
<add> //TODO complete role relatives
<add> private boolean parseRRelatives(String description){
<add>
<add> return true;
<add> }
<ide>
<ide> private boolean parseRole(String description){
<ide>
<del> Matcher m = Pattern.compile("id\\:([^;]+)(;|$)").matcher(description);
<del>
<del> if (! m.find()){
<add> String id = "";
<add> String synSetStr = "";
<add> String adjectives = "";
<add> String relatives = "";
<add>
<add> if (description.contains("@adj")){
<add>
<add> Pattern adpPattern =
<add> Pattern.compile("(.*)" + ADJblock + "(.*)");
<add> Matcher m = adpPattern.matcher(description);
<add> if (m.find()){
<add> adjectives = m.group(2);
<add> //System.out.println("time found");
<add> description = m.group(1) + m.group(3);
<add> }
<add> }
<add>
<add> if (description.contains("@rel")){
<add>
<add> Pattern adpPattern =
<add> Pattern.compile("(.*)" + RELblock + "(.*)");
<add> Matcher m = adpPattern.matcher(description);
<add> if (m.find()){
<add> relatives = m.group(2);
<add> //System.out.println("time found");
<add> description = m.group(1) + m.group(3);
<add> }
<add> }
<add>
<add> for (String desc: description.split(";")){
<add>
<add> desc = desc.trim();
<add>
<add> if(desc.startsWith("id:")){
<add> id = desc.split(":")[1];
<add> continue;
<add> }
<add>
<add> if(desc.startsWith("synset:")){
<add> synSetStr = desc.split(":")[1];
<add> continue;
<add> }
<add> }
<add>
<add> //A role must have an ID
<add> if (id.length() < 1){
<ide> roleFail();
<ide> success = false;
<ide> return false;
<ide> }
<ide>
<del> String id = m.group(1);
<del>
<del> m = Pattern.compile("synSet\\:([^;]+)(;|$)").matcher(description);
<del>
<del> if (! m.find()){
<add> // A role must have a synset which is a number
<add> if (! synSetStr.matches("\\d+")){
<ide> roleFail();
<ide> success = false;
<ide> return false;
<ide> }
<ide>
<del> String synSetStr = m.group(1);
<del>
<ide> int synSet = Integer.parseInt(synSetStr);
<ide>
<add> // Add the role
<ide> addRole(id, synSet);
<ide>
<del> m = Pattern.compile("adjectives\\:\\[(.+adj\\:\\})\\]").matcher(description);
<del>
<del> if (m.find()){
<del> String adjectives = m.group(1);
<add> //Process adjectives
<add> if (adjectives.length() > 0){
<ide> if (! parseAdjectives(adjectives)) return false;
<add> }
<add>
<add> //Process relatives
<add> if (relatives.length() > 0){
<add> if (! parseRRelatives(relatives)) return false;
<ide> }
<ide>
<ide> return true;
<ide> * @param description
<ide> * @return
<ide> */
<del> private boolean parseTimes(String description){
<del>
<add> private boolean parseAdpositionals(String description){
<add> //TODO fix the adpositionals content
<ide> int idx;
<del> while ((idx = description.indexOf("t:}")) >= 0) {
<del> String times = description.substring(3, idx);
<del> description = description.substring(idx+3);
<del>
<del> Matcher m = Pattern.compile("synSet\\:([^;]+)(;|$)").matcher(times);
<add> while ((idx = description.indexOf("adp:}")) >= 0) {
<add> String times = description.substring(5, idx);
<add> description = description.substring(idx+5);
<add>
<add> /*
<add> Matcher m = Pattern.compile("synset\\:([^;]+)(;|$)").matcher(times);
<ide> if (! m.find()){
<ide> success = false;
<ide> return false;
<ide>
<ide> int synSet = Integer.parseInt(synSetStr);
<ide>
<del> addTime(synSet);
<add> addAddpositional(synSet);
<ide>
<ide> m = Pattern.compile("predicates\\:\\[(.+)\\]").matcher(times);
<ide> if ( m.find()){
<ide> String predicates = m.group(1);
<ide> parseComponents(predicates);
<ide> }
<add> */
<ide>
<ide> }
<ide>
<ide> return true;
<ide> }
<ide>
<del> /**
<del> * Parse the places in an action
<del> * @param description STON description for places
<del> * @return
<del> */
<del> private boolean parsePlaces(String description){
<del>
<del> int idx;
<del> while ((idx = description.indexOf("p:}")) >= 0) {
<del> String times = description.substring(3, idx);
<del> description = description.substring(idx+3);
<del>
<del> Matcher m = Pattern.compile("synSet\\:([^;]+)(;|$)").matcher(times);
<del> if (! m.find()){
<del> success = false;
<del> return false;
<del> }
<del>
<del> String synSetStr = m.group(1);
<del>
<del> int synSet = Integer.parseInt(synSetStr);
<del>
<del> addPlace(synSet);
<del>
<del> m = Pattern.compile("predicates\\:\\[(.+)\\]").matcher(times);
<del> if ( m.find()){
<del> String predicates = m.group(1);
<del> parseComponents(predicates);
<del> }
<del>
<del> }
<del>
<del> return true;
<del> }
<del>
<del>
<ide>
<ide>
<ide> //Action
<ide> protected abstract void roleFail();
<ide>
<ide> /**
<del> * It is called when the parsing of times failed
<del> */
<del> protected abstract void timesFail();
<del>
<del> /**
<del> * It is called to add a time
<del> * @param synSet the synset of a time like: yesterday
<del> */
<del> protected abstract void addTime(int synSet);
<del>
<del> /**
<del> * It is called to add a location
<del> * @param synSetthe synset of a location like: outside
<del> */
<del> protected abstract void addPlace(int synSet);
<del>
<add> * It is called when the parsing of adpositionals failed
<add> */
<add> protected abstract void adpositionalFail();
<add>
<add> /**
<add> * It is called to add an adpositional: time or location
<add> * @param type the type of the addpositional
<add> */
<add> protected abstract void addAdpositional(String type);
<add>
<add>
<ide> //can be used for subjects, objects, places or times
<ide> protected abstract void addConjunctions(Set<String> IDs);
<ide>
|
|
Java
|
apache-2.0
|
fbb5355bfd68957a46b4c0637d10ae244b84c158
| 0 |
speedment/speedment,speedment/speedment
|
/**
*
* Copyright (c) 2006-2018, Speedment, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); You may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.speedment.tool.core.internal.controller;
import com.speedment.common.function.OptionalBoolean;
import com.speedment.common.injector.annotation.Inject;
import com.speedment.generator.core.component.EventComponent;
import com.speedment.runtime.config.Dbms;
import com.speedment.runtime.config.Document;
import com.speedment.runtime.config.Project;
import com.speedment.runtime.config.Schema;
import com.speedment.runtime.core.component.DbmsHandlerComponent;
import com.speedment.runtime.core.component.PasswordComponent;
import com.speedment.runtime.core.db.DbmsType;
import com.speedment.tool.config.DbmsProperty;
import com.speedment.tool.core.component.UserInterfaceComponent;
import com.speedment.tool.core.event.UIEvent;
import com.speedment.tool.core.exception.SpeedmentToolException;
import com.speedment.tool.core.internal.util.ConfigFileHelper;
import com.speedment.tool.core.resource.FontAwesome;
import com.speedment.tool.core.util.InjectionLoader;
import javafx.collections.FXCollections;
import javafx.collections.transformation.FilteredList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ComboBox;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.RowConstraints;
import javafx.stage.FileChooser;
import java.io.File;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Optional;
import java.util.OptionalDouble;
import java.util.OptionalInt;
import java.util.OptionalLong;
import java.util.ResourceBundle;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Stream;
import static java.util.Objects.requireNonNull;
import static java.util.stream.Collectors.toCollection;
import static javafx.beans.binding.Bindings.createBooleanBinding;
import static javafx.scene.layout.Region.USE_COMPUTED_SIZE;
/**
*
* @author Emil Forslund
*/
public final class ConnectController implements Initializable {
private final static String
DEFAULT_HOST = "127.0.0.1",
DEFAULT_USER = "root";
@Inject private UserInterfaceComponent ui;
@Inject private DbmsHandlerComponent dbmsHandler;
@Inject private PasswordComponent passwords;
@Inject private ConfigFileHelper cfHelper;
@Inject private EventComponent events;
@Inject private InjectionLoader loader;
@FXML private TextField fieldHost;
@FXML private TextField fieldPort;
@FXML private TextField fieldFile;
@FXML private Button fieldFileBtn;
@FXML private ComboBox<String> fieldType;
@FXML private TextField fieldName;
@FXML private TextField fieldSchema;
@FXML private TextField fieldUser;
@FXML private PasswordField fieldPass;
@FXML private Button buttonConnect;
@FXML private CheckBox enableConnectionUrl;
@FXML private TextArea areaConnectionUrl;
@FXML private GridPane grid;
@FXML private RowConstraints hostRow;
@FXML private RowConstraints fileRow;
@FXML private RowConstraints dbmsRow;
@FXML private RowConstraints schemaRow;
@FXML private RowConstraints userRow;
@FXML private RowConstraints passRow;
private FilteredList<Node> hostRowChildren;
private FilteredList<Node> fileRowChildren;
private FilteredList<Node> userRowChildren;
private FilteredList<Node> passRowChildren;
private FilteredList<Node> dbmsRowChildren;
private FilteredList<Node> schemaRowChildren;
@Override
public void initialize(URL location, ResourceBundle resources) {
fieldFileBtn.setGraphic(FontAwesome.FOLDER_OPEN.view());
buttonConnect.setGraphic(FontAwesome.SIGN_IN.view());
hostRowChildren = inRow(hostRow);
fileRowChildren = inRow(fileRow);
userRowChildren = inRow(userRow);
passRowChildren = inRow(passRow);
dbmsRowChildren = inRow(dbmsRow);
schemaRowChildren = inRow(schemaRow);
fieldType.setItems(getDbmsTypes()
.collect(toCollection(FXCollections::observableArrayList))
);
// Keep track of the generated values so that we don't overwrite user
// changes with automatic ones.
final AtomicReference<DbmsType> dbmsType = new AtomicReference<>();
final AtomicReference<String> generatedHost = new AtomicReference<>("");
final AtomicReference<String> generatedPort = new AtomicReference<>("");
final AtomicReference<String> generatedUser = new AtomicReference<>("");
final AtomicReference<String> generatedName = new AtomicReference<>("");
final AtomicReference<String> generatedSchema = new AtomicReference<>("");
final AtomicReference<String> generatedConnUrl = new AtomicReference<>("");
// Use this method reference to recalculate any default values.
final Runnable recalculateFields = () -> {
final DbmsType item = dbmsType.get();
// Hide name rows if particular Dbms doesn't support them.
toggleVisibility(hostRow, hostRowChildren, item.getConnectionType() == DbmsType.ConnectionType.HOST_AND_PORT);
toggleVisibility(fileRow, fileRowChildren, item.getConnectionType() == DbmsType.ConnectionType.DBMS_AS_FILE);
toggleVisibility(userRow, userRowChildren, item.hasDatabaseUsers());
toggleVisibility(passRow, passRowChildren, item.hasDatabaseUsers());
toggleVisibility(dbmsRow, dbmsRowChildren, item.hasDatabaseNames());
toggleVisibility(schemaRow, schemaRowChildren, item.hasSchemaNames());
if (fieldHost.getText().isEmpty()
|| fieldHost.getText().equals(generatedHost.get())) {
fieldHost.textProperty().setValue(DEFAULT_HOST);
generatedHost.set(DEFAULT_HOST);
}
// Disable Dbms User-property for database types that doesn't use it
if (item.hasDatabaseUsers()) {
fieldUser.setDisable(false);
fieldPass.setDisable(false);
if (fieldUser.getText().isEmpty()
|| fieldUser.getText().equals(generatedUser.get())) {
fieldUser.textProperty().setValue(DEFAULT_USER);
generatedUser.set(DEFAULT_USER);
}
} else {
generatedUser.set(DEFAULT_USER);
fieldUser.setDisable(true);
fieldPass.setDisable(true);
}
// Disable Dbms Name-property for database types that doesn't use it
if (item.hasDatabaseNames()) {
fieldName.setDisable(false);
if (fieldName.getText().isEmpty()
|| fieldName.getText().equals(generatedName.get())) {
item.getDefaultDbmsName().ifPresent(name -> {
fieldName.textProperty().setValue(name);
generatedName.set(name);
});
}
} else {
item.getDefaultDbmsName().ifPresent(generatedName::set);
fieldName.setDisable(true);
}
if (item.hasSchemaNames()) {
fieldSchema.setDisable(false);
if (fieldSchema.getText().isEmpty()
|| fieldSchema.getText().equals(generatedSchema.get())) {
item.getDefaultSchemaName().ifPresent(name -> {
fieldSchema.textProperty().setValue(name);
generatedSchema.set(name);
});
}
} else {
fieldSchema.setDisable(true);
}
fieldName.getTooltip().setText(item.getDbmsNameMeaning());
if (fieldPort.getText().isEmpty()
|| fieldPort.getText().equals(generatedPort.get())) {
final String port = Integer.toString(item.getDefaultPort());
fieldPort.textProperty().setValue(port);
generatedPort.set(port);
}
if (areaConnectionUrl.getText().isEmpty()
|| areaConnectionUrl.getText().equals(generatedConnUrl.get())) {
final String url = item.getConnectionUrlGenerator().from(
TemporaryDbms.create(
ui.projectProperty(),
fieldName.getText(),
fieldFile.getText(),
fieldHost.getText(),
Integer.parseInt(fieldPort.getText())
)
);
generatedConnUrl.set(url);
areaConnectionUrl.setText(url);
}
};
// If the user changes something, recalculate default values.
fieldType.getSelectionModel().selectedItemProperty()
.addListener((observable, old, typeName) -> {
if (!typeName.isEmpty()) {
dbmsType.set(findDbmsType(typeName));
recalculateFields.run();
}
});
fieldHost.textProperty().addListener((ob, o, n) -> recalculateFields.run());
fieldPort.textProperty().addListener((ob, o, n) -> recalculateFields.run());
fieldFile.textProperty().addListener((ob, o, n) -> recalculateFields.run());
fieldUser.textProperty().addListener((ob, o, n) -> recalculateFields.run());
fieldName.textProperty().addListener((ob, o, n) -> recalculateFields.run());
fieldSchema.textProperty().addListener((ob, o, n) -> recalculateFields.run());
areaConnectionUrl.textProperty().addListener((ob, o, n) -> recalculateFields.run());
// Disable the Connection Url field if the checkbox is not checked.
areaConnectionUrl.disableProperty().bind(
enableConnectionUrl.selectedProperty().not()
);
// Disable the file chooser if connection URL is enabled
fieldFileBtn.disableProperty().bind(
enableConnectionUrl.selectedProperty()
);
// Find the preferred dbms-type
final Optional<String> preferred = getDbmsTypes().findFirst();
if (preferred.isPresent()) {
fieldType.getSelectionModel().select(preferred.get());
} else {
final String msg = "Could not find any installed JDBC " +
"drivers. Make sure to include at least one JDBC driver " +
"as a dependency in the projects pom.xml-file under the " +
"speedment-maven-plugin <plugin> tag.";
ui.showError(
"Couldn't find any installed JDBC drivers",
msg
);
throw new SpeedmentToolException(msg);
}
// Disable the Connect-button if all fields have not been entered.
buttonConnect.disableProperty().bind(createBooleanBinding(
() -> ((fieldHost.textProperty().isEmpty().get()
|| fieldPort.textProperty().isEmpty().get())
&& dbmsType.get().getConnectionType() == DbmsType.ConnectionType.HOST_AND_PORT)
|| (fieldFile.textProperty().isEmpty().get() && dbmsType.get().getConnectionType() == DbmsType.ConnectionType.DBMS_AS_FILE)
|| fieldType.getSelectionModel().isEmpty()
|| (fieldName.textProperty().isEmpty().get() && dbmsType.get().hasDatabaseNames())
|| (fieldUser.textProperty().isEmpty().get() && dbmsType.get().hasDatabaseUsers()),
fieldHost.textProperty(),
fieldPort.textProperty(),
fieldFile.textProperty(),
fieldType.selectionModelProperty(),
fieldName.textProperty(),
fieldUser.textProperty()
));
// Load dbms from file-action
final FileChooser fileChooser = new FileChooser();
fieldFileBtn.setOnAction(ev -> {
fileChooser.setTitle("Open Database File");
if (!"".equals(fieldFile.getText().trim())) {
final Path path = Paths.get(fieldFile.getText().trim());
if (Files.exists(path.getParent())) {
final String parentFolder = path.getParent().toString();
if (!"".equals(parentFolder)) {
fileChooser.setInitialDirectory(new File(parentFolder));
}
}
if (Files.exists(path)) {
fileChooser.setInitialFileName(fieldFile.getText());
}
}
final File file = fileChooser.showOpenDialog(ui.getStage());
if (file != null) {
fieldFile.setText(Paths.get(".").toAbsolutePath().getParent().relativize(file.toPath()).toString());
}
});
// Connect to database action
buttonConnect.setOnAction(ev -> {
final DbmsType type = dbmsType.get();
// Register password in password component
passwords.put(
fieldName.getText(),
fieldPass.getText().toCharArray()
);
// Create a new Dbms using the settings configured.
final DbmsProperty dbms = ui.projectProperty()
.mutator().addNewDbms();
dbms.typeNameProperty().set(dbmsType.get().getName());
if (type.getConnectionType() == DbmsType.ConnectionType.HOST_AND_PORT) {
dbms.ipAddressProperty().set(fieldHost.getText());
dbms.portProperty().set(Integer.valueOf(fieldPort.getText()));
} else if (type.getConnectionType() == DbmsType.ConnectionType.DBMS_AS_FILE) {
dbms.localPathProperty().set(fieldFile.getText());
}
if (type.hasDatabaseUsers()) {
dbms.usernameProperty().set(fieldUser.getText());
}
dbms.nameProperty().set(Optional.of(fieldName.getText())
.filter(s -> dbmsType.get().hasDatabaseNames())
.filter(s -> !s.isEmpty())
.orElseGet(() -> type.getDefaultDbmsName().orElseGet(fieldName::getText)));
if (!areaConnectionUrl.getText().isEmpty()
&& !areaConnectionUrl.getText().equals(generatedConnUrl.get())) {
dbms.connectionUrlProperty().setValue(
areaConnectionUrl.getText()
);
}
final String schema = Optional.of(fieldSchema.getText())
.filter(s -> dbmsType.get().hasSchemaNames())
.filter(s -> !s.isEmpty())
.orElseGet(() -> type.getDefaultSchemaName().orElseGet(dbms::getName));
// Set the default project name to the name of the schema.
if (type.hasSchemaNames() || type.hasDatabaseNames()) {
ui.projectProperty().nameProperty()
.setValue(schema);
} else if (type.getConnectionType() == DbmsType.ConnectionType.DBMS_AS_FILE) {
String filename = Paths.get(fieldFile.getText()).getFileName().toString();
if (filename.contains(".")) {
filename = filename.substring(0, filename.lastIndexOf("."));
}
ui.projectProperty().nameProperty()
.setValue(filename);
} else {
ui.projectProperty().nameProperty()
.setValue("Demo");
}
// Connect to database
if (cfHelper.loadFromDatabase(dbms, schema)) {
loader.loadAndShow("Scene");
events.notify(UIEvent.OPEN_MAIN_WINDOW);
}
});
}
private Stream<String> getDbmsTypes() {
return dbmsHandler
.supportedDbmsTypes()
.map(DbmsType::getName);
}
private DbmsType findDbmsType(String dbmsTypeName) {
return dbmsHandler.findByName(dbmsTypeName).orElseThrow(() ->
new SpeedmentToolException(
"Could not find any DbmsType with name '" +
dbmsTypeName + "'."
));
}
private FilteredList<Node> inRow(RowConstraints row) {
final int index = grid.getRowConstraints().indexOf(row);
return grid.getChildren()
.filtered(node -> {
final Integer rowIndex = GridPane.getRowIndex(node);
return rowIndex != null && index == GridPane.getRowIndex(node);
});
}
private void toggleVisibility(RowConstraints row,
FilteredList<Node> children,
boolean show) {
if (show) {
row.setMaxHeight(USE_COMPUTED_SIZE);
row.setMinHeight(10);
} else {
row.setMaxHeight(0);
row.setMinHeight(0);
}
children.forEach(n -> {
n.setVisible(show);
n.setManaged(show);
});
}
private static final class TemporaryDbms implements Dbms {
public static TemporaryDbms create(Project project, String name, String file, String ip, int port) {
final Map<String, Object> data = new LinkedHashMap<>();
data.put(Dbms.ID, name);
data.put(Dbms.NAME, name);
data.put(Dbms.IP_ADDRESS, ip);
data.put(Dbms.PORT, port);
data.put(Dbms.LOCAL_PATH, file);
return new TemporaryDbms(project, data);
}
private final Project project;
private final Map<String, Object> data;
private TemporaryDbms(Project project, Map<String, Object> data) {
this.project = requireNonNull(project);
this.data = requireNonNull(data);
}
@Override
public Optional<Project> getParent() {
return Optional.of(project);
}
@Override
public Map<String, Object> getData() {
return data;
}
@Override
public Optional<Object> get(String key) {
return Optional.ofNullable(data.get(key));
}
@Override
public Optional<String> getAsString(String key) throws ClassCastException {
return get(key).map(String.class::cast);
}
@Override
public OptionalBoolean getAsBoolean(String key) throws ClassCastException {
return get(key)
.map(Boolean.class::cast)
.map(OptionalBoolean::of)
.orElseGet(OptionalBoolean::empty);
}
@Override
public OptionalLong getAsLong(String key) throws ClassCastException {
return get(key)
.map(Long.class::cast)
.map(OptionalLong::of)
.orElseGet(OptionalLong::empty);
}
@Override
public OptionalDouble getAsDouble(String key) throws ClassCastException {
return get(key)
.map(Double.class::cast)
.map(OptionalDouble::of)
.orElseGet(OptionalDouble::empty);
}
@Override
public OptionalInt getAsInt(String key) throws ClassCastException {
return get(key)
.map(Integer.class::cast)
.map(OptionalInt::of)
.orElseGet(OptionalInt::empty);
}
@Override
public void put(String key, Object value) {
throw new UnsupportedOperationException(
"This implementation of Dbms should not be modified."
);
}
@Override
public Stream<? extends Schema> schemas() {
return Stream.empty();
}
@Override
public Stream<? extends Document> children() {
return Stream.empty();
}
}
}
|
tool-parent/tool-core/src/main/java/com/speedment/tool/core/internal/controller/ConnectController.java
|
/**
*
* Copyright (c) 2006-2018, Speedment, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); You may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.speedment.tool.core.internal.controller;
import com.speedment.common.function.OptionalBoolean;
import com.speedment.common.injector.annotation.Inject;
import com.speedment.generator.core.component.EventComponent;
import com.speedment.runtime.config.Dbms;
import com.speedment.runtime.config.Document;
import com.speedment.runtime.config.Project;
import com.speedment.runtime.config.Schema;
import com.speedment.runtime.core.component.DbmsHandlerComponent;
import com.speedment.runtime.core.component.PasswordComponent;
import com.speedment.runtime.core.db.DbmsType;
import com.speedment.tool.config.DbmsProperty;
import com.speedment.tool.core.component.UserInterfaceComponent;
import com.speedment.tool.core.event.UIEvent;
import com.speedment.tool.core.exception.SpeedmentToolException;
import com.speedment.tool.core.internal.util.ConfigFileHelper;
import com.speedment.tool.core.resource.FontAwesome;
import com.speedment.tool.core.util.InjectionLoader;
import javafx.collections.FXCollections;
import javafx.collections.transformation.FilteredList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ComboBox;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.RowConstraints;
import javafx.stage.FileChooser;
import java.io.File;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Optional;
import java.util.OptionalDouble;
import java.util.OptionalInt;
import java.util.OptionalLong;
import java.util.ResourceBundle;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Stream;
import static java.util.Objects.requireNonNull;
import static java.util.stream.Collectors.toCollection;
import static javafx.beans.binding.Bindings.createBooleanBinding;
import static javafx.scene.layout.Region.USE_COMPUTED_SIZE;
/**
*
* @author Emil Forslund
*/
public final class ConnectController implements Initializable {
private final static String
DEFAULT_HOST = "127.0.0.1",
DEFAULT_USER = "root";
@Inject private UserInterfaceComponent ui;
@Inject private DbmsHandlerComponent dbmsHandler;
@Inject private PasswordComponent passwords;
@Inject private ConfigFileHelper cfHelper;
@Inject private EventComponent events;
@Inject private InjectionLoader loader;
@FXML private TextField fieldHost;
@FXML private TextField fieldPort;
@FXML private TextField fieldFile;
@FXML private Button fieldFileBtn;
@FXML private ComboBox<String> fieldType;
@FXML private TextField fieldName;
@FXML private TextField fieldSchema;
@FXML private TextField fieldUser;
@FXML private PasswordField fieldPass;
@FXML private Button buttonConnect;
@FXML private CheckBox enableConnectionUrl;
@FXML private TextArea areaConnectionUrl;
@FXML private GridPane grid;
@FXML private RowConstraints hostRow;
@FXML private RowConstraints fileRow;
@FXML private RowConstraints dbmsRow;
@FXML private RowConstraints schemaRow;
@FXML private RowConstraints userRow;
@FXML private RowConstraints passRow;
private FilteredList<Node> hostRowChildren;
private FilteredList<Node> fileRowChildren;
private FilteredList<Node> userRowChildren;
private FilteredList<Node> passRowChildren;
private FilteredList<Node> dbmsRowChildren;
private FilteredList<Node> schemaRowChildren;
@Override
public void initialize(URL location, ResourceBundle resources) {
fieldFileBtn.setGraphic(FontAwesome.FOLDER_OPEN.view());
buttonConnect.setGraphic(FontAwesome.SIGN_IN.view());
hostRowChildren = inRow(hostRow);
fileRowChildren = inRow(fileRow);
userRowChildren = inRow(userRow);
passRowChildren = inRow(passRow);
dbmsRowChildren = inRow(dbmsRow);
schemaRowChildren = inRow(schemaRow);
fieldType.setItems(getDbmsTypes()
.collect(toCollection(FXCollections::observableArrayList))
);
// Keep track of the generated values so that we don't overwrite user
// changes with automatic ones.
final AtomicReference<DbmsType> dbmsType = new AtomicReference<>();
final AtomicReference<String> generatedHost = new AtomicReference<>("");
final AtomicReference<String> generatedPort = new AtomicReference<>("");
final AtomicReference<String> generatedUser = new AtomicReference<>("");
final AtomicReference<String> generatedName = new AtomicReference<>("");
final AtomicReference<String> generatedSchema = new AtomicReference<>("");
final AtomicReference<String> generatedConnUrl = new AtomicReference<>("");
// Use this method reference to recalculate any default values.
final Runnable recalculateFields = () -> {
final DbmsType item = dbmsType.get();
// Hide name rows if particular Dbms doesn't support them.
toggleVisibility(hostRow, hostRowChildren, item.getConnectionType() == DbmsType.ConnectionType.HOST_AND_PORT);
toggleVisibility(fileRow, fileRowChildren, item.getConnectionType() == DbmsType.ConnectionType.DBMS_AS_FILE);
toggleVisibility(userRow, userRowChildren, item.hasDatabaseUsers());
toggleVisibility(passRow, passRowChildren, item.hasDatabaseUsers());
toggleVisibility(dbmsRow, dbmsRowChildren, item.hasDatabaseNames());
toggleVisibility(schemaRow, schemaRowChildren, item.hasSchemaNames());
if (fieldHost.getText().isEmpty()
|| fieldHost.getText().equals(generatedHost.get())) {
fieldHost.textProperty().setValue(DEFAULT_HOST);
generatedHost.set(DEFAULT_HOST);
}
// Disable Dbms User-property for database types that doesn't use it
if (item.hasDatabaseUsers()) {
fieldUser.setDisable(false);
fieldPass.setDisable(false);
if (fieldUser.getText().isEmpty()
|| fieldUser.getText().equals(generatedUser.get())) {
fieldUser.textProperty().setValue(DEFAULT_USER);
generatedUser.set(DEFAULT_USER);
}
} else {
generatedUser.set(DEFAULT_USER);
fieldUser.setDisable(true);
fieldPass.setDisable(true);
}
// Disable Dbms Name-property for database types that doesn't use it
if (item.hasDatabaseNames()) {
fieldName.setDisable(false);
if (fieldName.getText().isEmpty()
|| fieldName.getText().equals(generatedName.get())) {
item.getDefaultDbmsName().ifPresent(name -> {
fieldName.textProperty().setValue(name);
generatedName.set(name);
});
}
} else {
item.getDefaultDbmsName().ifPresent(generatedName::set);
fieldName.setDisable(true);
}
if (item.hasSchemaNames()) {
fieldSchema.setDisable(false);
if (fieldSchema.getText().isEmpty()
|| fieldSchema.getText().equals(generatedSchema.get())) {
item.getDefaultSchemaName().ifPresent(name -> {
fieldSchema.textProperty().setValue(name);
generatedSchema.set(name);
});
}
} else {
fieldSchema.setDisable(true);
}
fieldName.getTooltip().setText(item.getDbmsNameMeaning());
if (fieldPort.getText().isEmpty()
|| fieldPort.getText().equals(generatedPort.get())) {
final String port = Integer.toString(item.getDefaultPort());
fieldPort.textProperty().setValue(port);
generatedPort.set(port);
}
if (areaConnectionUrl.getText().isEmpty()
|| areaConnectionUrl.getText().equals(generatedConnUrl.get())) {
final String url = item.getConnectionUrlGenerator().from(
TemporaryDbms.create(
ui.projectProperty(),
fieldName.getText(),
fieldFile.getText(),
fieldHost.getText(),
Integer.parseInt(fieldPort.getText())
)
);
generatedConnUrl.set(url);
areaConnectionUrl.setText(url);
}
};
// If the user changes something, recalculate default values.
fieldType.getSelectionModel().selectedItemProperty()
.addListener((observable, old, typeName) -> {
if (!typeName.isEmpty()) {
dbmsType.set(findDbmsType(typeName));
recalculateFields.run();
}
});
fieldHost.textProperty().addListener((ob, o, n) -> recalculateFields.run());
fieldPort.textProperty().addListener((ob, o, n) -> recalculateFields.run());
fieldFile.textProperty().addListener((ob, o, n) -> recalculateFields.run());
fieldUser.textProperty().addListener((ob, o, n) -> recalculateFields.run());
fieldName.textProperty().addListener((ob, o, n) -> recalculateFields.run());
fieldSchema.textProperty().addListener((ob, o, n) -> recalculateFields.run());
areaConnectionUrl.textProperty().addListener((ob, o, n) -> recalculateFields.run());
// Disable the Connection Url field if the checkbox is not checked.
areaConnectionUrl.disableProperty().bind(
enableConnectionUrl.selectedProperty().not()
);
// Disable the file chooser if connection URL is enabled
fieldFileBtn.disableProperty().bind(
enableConnectionUrl.selectedProperty()
);
// Find the preferred dbms-type
final Optional<String> preferred = getDbmsTypes().findFirst();
if (preferred.isPresent()) {
fieldType.getSelectionModel().select(preferred.get());
} else {
final String msg = "Could not find any installed JDBC " +
"drivers. Make sure to include at least one JDBC driver " +
"as a dependency in the projects pom.xml-file under the " +
"speedment-maven-plugin <plugin> tag.";
ui.showError(
"Couldn't find any installed JDBC drivers",
msg
);
throw new SpeedmentToolException(msg);
}
// Disable the Connect-button if all fields have not been entered.
buttonConnect.disableProperty().bind(createBooleanBinding(
() -> ((fieldHost.textProperty().isEmpty().get()
|| fieldPort.textProperty().isEmpty().get())
&& dbmsType.get().getConnectionType() == DbmsType.ConnectionType.HOST_AND_PORT)
|| (fieldFile.textProperty().isEmpty().get() && dbmsType.get().getConnectionType() == DbmsType.ConnectionType.DBMS_AS_FILE)
|| fieldType.getSelectionModel().isEmpty()
|| (fieldName.textProperty().isEmpty().get() && dbmsType.get().hasDatabaseNames())
|| (fieldUser.textProperty().isEmpty().get() && dbmsType.get().hasDatabaseUsers()),
fieldHost.textProperty(),
fieldPort.textProperty(),
fieldFile.textProperty(),
fieldType.selectionModelProperty(),
fieldName.textProperty(),
fieldUser.textProperty()
));
// Load dbms from file-action
final FileChooser fileChooser = new FileChooser();
fieldFileBtn.setOnAction(ev -> {
fileChooser.setTitle("Open Database File");
if (!"".equals(fieldFile.getText().trim())) {
final Path path = Paths.get(fieldFile.getText().trim());
if (Files.exists(path.getParent())) {
final String parentFolder = path.getParent().toString();
if (!"".equals(parentFolder)) {
fileChooser.setInitialDirectory(new File(parentFolder));
}
}
if (Files.exists(path)) {
fileChooser.setInitialFileName(fieldFile.getText());
}
}
final File file = fileChooser.showOpenDialog(ui.getStage());
if (file != null) {
fieldFile.setText(Paths.get(".").toAbsolutePath().getParent().relativize(file.toPath()).toString());
}
});
// Connect to database action
buttonConnect.setOnAction(ev -> {
final DbmsType type = dbmsType.get();
// Register password in password component
passwords.put(
fieldName.getText(),
fieldPass.getText().toCharArray()
);
// Create a new Dbms using the settings configured.
final DbmsProperty dbms = ui.projectProperty()
.mutator().addNewDbms();
dbms.typeNameProperty().set(dbmsType.get().getName());
if (type.getConnectionType() == DbmsType.ConnectionType.HOST_AND_PORT) {
dbms.ipAddressProperty().set(fieldHost.getText());
dbms.portProperty().set(Integer.valueOf(fieldPort.getText()));
} else if (type.getConnectionType() == DbmsType.ConnectionType.DBMS_AS_FILE) {
dbms.localPathProperty().set(fieldFile.getText());
}
if (type.hasDatabaseUsers()) {
dbms.usernameProperty().set(fieldUser.getText());
}
Optional.of(fieldName.getText())
.filter(s -> dbmsType.get().hasDatabaseNames())
.filter(s -> !s.isEmpty())
.orElseGet(() -> type.getDefaultDbmsName().orElseGet(fieldName::getText));
if (!areaConnectionUrl.getText().isEmpty()
&& !areaConnectionUrl.getText().equals(generatedConnUrl.get())) {
dbms.connectionUrlProperty().setValue(
areaConnectionUrl.getText()
);
}
final String schema = Optional.of(fieldSchema.getText())
.filter(s -> dbmsType.get().hasSchemaNames())
.filter(s -> !s.isEmpty())
.orElseGet(() -> type.getDefaultSchemaName().orElseGet(dbms::getName));
// Set the default project name to the name of the schema.
if (type.hasSchemaNames() || type.hasDatabaseNames()) {
ui.projectProperty().nameProperty()
.setValue(schema);
} else if (type.getConnectionType() == DbmsType.ConnectionType.DBMS_AS_FILE) {
String filename = Paths.get(fieldFile.getText()).getFileName().toString();
if (filename.contains(".")) {
filename = filename.substring(0, filename.lastIndexOf("."));
}
ui.projectProperty().nameProperty()
.setValue(filename);
} else {
ui.projectProperty().nameProperty()
.setValue("Demo");
}
// Connect to database
if (cfHelper.loadFromDatabase(dbms, schema)) {
loader.loadAndShow("Scene");
events.notify(UIEvent.OPEN_MAIN_WINDOW);
}
});
}
private Stream<String> getDbmsTypes() {
return dbmsHandler
.supportedDbmsTypes()
.map(DbmsType::getName);
}
private DbmsType findDbmsType(String dbmsTypeName) {
return dbmsHandler.findByName(dbmsTypeName).orElseThrow(() ->
new SpeedmentToolException(
"Could not find any DbmsType with name '" +
dbmsTypeName + "'."
));
}
private FilteredList<Node> inRow(RowConstraints row) {
final int index = grid.getRowConstraints().indexOf(row);
return grid.getChildren()
.filtered(node -> {
final Integer rowIndex = GridPane.getRowIndex(node);
return rowIndex != null && index == GridPane.getRowIndex(node);
});
}
private void toggleVisibility(RowConstraints row,
FilteredList<Node> children,
boolean show) {
if (show) {
row.setMaxHeight(USE_COMPUTED_SIZE);
row.setMinHeight(10);
} else {
row.setMaxHeight(0);
row.setMinHeight(0);
}
children.forEach(n -> {
n.setVisible(show);
n.setManaged(show);
});
}
private static final class TemporaryDbms implements Dbms {
public static TemporaryDbms create(Project project, String name, String file, String ip, int port) {
final Map<String, Object> data = new LinkedHashMap<>();
data.put(Dbms.ID, name);
data.put(Dbms.NAME, name);
data.put(Dbms.IP_ADDRESS, ip);
data.put(Dbms.PORT, port);
data.put(Dbms.LOCAL_PATH, file);
return new TemporaryDbms(project, data);
}
private final Project project;
private final Map<String, Object> data;
private TemporaryDbms(Project project, Map<String, Object> data) {
this.project = requireNonNull(project);
this.data = requireNonNull(data);
}
@Override
public Optional<Project> getParent() {
return Optional.of(project);
}
@Override
public Map<String, Object> getData() {
return data;
}
@Override
public Optional<Object> get(String key) {
return Optional.ofNullable(data.get(key));
}
@Override
public Optional<String> getAsString(String key) throws ClassCastException {
return get(key).map(String.class::cast);
}
@Override
public OptionalBoolean getAsBoolean(String key) throws ClassCastException {
return get(key)
.map(Boolean.class::cast)
.map(OptionalBoolean::of)
.orElseGet(OptionalBoolean::empty);
}
@Override
public OptionalLong getAsLong(String key) throws ClassCastException {
return get(key)
.map(Long.class::cast)
.map(OptionalLong::of)
.orElseGet(OptionalLong::empty);
}
@Override
public OptionalDouble getAsDouble(String key) throws ClassCastException {
return get(key)
.map(Double.class::cast)
.map(OptionalDouble::of)
.orElseGet(OptionalDouble::empty);
}
@Override
public OptionalInt getAsInt(String key) throws ClassCastException {
return get(key)
.map(Integer.class::cast)
.map(OptionalInt::of)
.orElseGet(OptionalInt::empty);
}
@Override
public void put(String key, Object value) {
throw new UnsupportedOperationException(
"This implementation of Dbms should not be modified."
);
}
@Override
public Stream<? extends Schema> schemas() {
return Stream.empty();
}
@Override
public Stream<? extends Document> children() {
return Stream.empty();
}
}
}
|
tool-core: Fix bug with setting database name
|
tool-parent/tool-core/src/main/java/com/speedment/tool/core/internal/controller/ConnectController.java
|
tool-core: Fix bug with setting database name
|
<ide><path>ool-parent/tool-core/src/main/java/com/speedment/tool/core/internal/controller/ConnectController.java
<ide> dbms.usernameProperty().set(fieldUser.getText());
<ide> }
<ide>
<del> Optional.of(fieldName.getText())
<add> dbms.nameProperty().set(Optional.of(fieldName.getText())
<ide> .filter(s -> dbmsType.get().hasDatabaseNames())
<ide> .filter(s -> !s.isEmpty())
<del> .orElseGet(() -> type.getDefaultDbmsName().orElseGet(fieldName::getText));
<add> .orElseGet(() -> type.getDefaultDbmsName().orElseGet(fieldName::getText)));
<ide>
<ide> if (!areaConnectionUrl.getText().isEmpty()
<ide> && !areaConnectionUrl.getText().equals(generatedConnUrl.get())) {
|
|
JavaScript
|
bsd-3-clause
|
baffc7df5a0dd0ef4043a57e52d984e859a01742
| 0 |
ibm-js/dcharting
|
dojo.provide("dojox.charting.Chart2D");
dojo.require("dojox.gfx");
dojo.require("dojox.lang.functional");
dojo.require("dojox.lang.functional.fold");
dojo.require("dojox.lang.functional.reversed");
dojo.require("dojox.charting.Theme");
dojo.require("dojox.charting.Series");
// require all axes to support references by name
dojo.require("dojox.charting.axis2d.Default");
dojo.require("dojox.charting.axis2d.Invisible");
// require all plots to support references by name
dojo.require("dojox.charting.plot2d.Default");
dojo.require("dojox.charting.plot2d.Lines");
dojo.require("dojox.charting.plot2d.Areas");
dojo.require("dojox.charting.plot2d.Markers");
dojo.require("dojox.charting.plot2d.MarkersOnly");
dojo.require("dojox.charting.plot2d.Scatter");
dojo.require("dojox.charting.plot2d.Stacked");
dojo.require("dojox.charting.plot2d.StackedLines");
dojo.require("dojox.charting.plot2d.StackedAreas");
dojo.require("dojox.charting.plot2d.Columns");
dojo.require("dojox.charting.plot2d.StackedColumns");
dojo.require("dojox.charting.plot2d.ClusteredColumns");
dojo.require("dojox.charting.plot2d.Bars");
dojo.require("dojox.charting.plot2d.StackedBars");
dojo.require("dojox.charting.plot2d.ClusteredBars");
dojo.require("dojox.charting.plot2d.Grid");
dojo.require("dojox.charting.plot2d.Pie");
dojo.require("dojox.charting.plot2d.Bubble");
dojo.require("dojox.charting.plot2d.Candlesticks");
dojo.require("dojox.charting.plot2d.OHLC");
dojo.require("dojox.charting.plot2d.Spider");
/*=====
dojox.charting.__Chart2DCtorArgs = function(margins, stroke, fill, delayInMs){
// summary:
// The keyword arguments that can be passed in a Chart2D constructor.
//
// margins: Object?
// Optional margins for the chart, in the form of { l, t, r, b}.
// stroke: dojox.gfx.Stroke?
// An optional outline/stroke for the chart.
// fill: dojox.gfx.Fill?
// An optional fill for the chart.
// delayInMs: Number
// Delay in ms for delayedRender(). Default: 200.
this.margins = margins;
this.stroke = stroke;
this.fill = fill;
this.delayInMs = delayInMs;
}
=====*/
(function(){
var df = dojox.lang.functional, dc = dojox.charting, g = dojox.gfx,
clear = df.lambda("item.clear()"),
purge = df.lambda("item.purgeGroup()"),
destroy = df.lambda("item.destroy()"),
makeClean = df.lambda("item.dirty = false"),
makeDirty = df.lambda("item.dirty = true"),
getName = df.lambda("item.name");
dojo.declare("dojox.charting.Chart2D", null, {
// summary:
// The main chart object in dojox.charting. This will create a two dimensional
// chart based on dojox.gfx.
//
// description:
// dojox.charting.Chart2D is the primary object used for any kind of charts. It
// is simple to create--just pass it a node reference, which is used as the
// container for the chart--and a set of optional keyword arguments and go.
//
// Note that like most of dojox.gfx, most of dojox.charting.Chart2D's methods are
// designed to return a reference to the chart itself, to allow for functional
// chaining. This makes defining everything on a Chart very easy to do.
//
// example:
// Create an area chart, with smoothing.
// | new dojox.charting.Chart2D(node))
// | .addPlot("default", { type: "Areas", tension: "X" })
// | .setTheme(dojox.charting.themes.Shrooms)
// | .addSeries("Series A", [1, 2, 0.5, 1.5, 1, 2.8, 0.4])
// | .addSeries("Series B", [2.6, 1.8, 2, 1, 1.4, 0.7, 2])
// | .addSeries("Series C", [6.3, 1.8, 3, 0.5, 4.4, 2.7, 2])
// | .render();
//
// example:
// The form of data in a data series can take a number of forms: a simple array,
// an array of objects {x,y}, or something custom (as determined by the plot).
// Here's an example of a Candlestick chart, which expects an object of
// { open, high, low, close }.
// | new dojox.charting.Chart2D(node))
// | .addPlot("default", {type: "Candlesticks", gap: 1})
// | .addAxis("x", {fixLower: "major", fixUpper: "major", includeZero: true})
// | .addAxis("y", {vertical: true, fixLower: "major", fixUpper: "major", natural: true})
// | .addSeries("Series A", [
// | { open: 20, close: 16, high: 22, low: 8 },
// | { open: 16, close: 22, high: 26, low: 6, mid: 18 },
// | { open: 22, close: 18, high: 22, low: 11, mid: 21 },
// | { open: 18, close: 29, high: 32, low: 14, mid: 27 },
// | { open: 29, close: 24, high: 29, low: 13, mid: 27 },
// | { open: 24, close: 8, high: 24, low: 5 },
// | { open: 8, close: 16, high: 22, low: 2 },
// | { open: 16, close: 12, high: 19, low: 7 },
// | { open: 12, close: 20, high: 22, low: 8 },
// | { open: 20, close: 16, high: 22, low: 8 },
// | { open: 16, close: 22, high: 26, low: 6, mid: 18 },
// | { open: 22, close: 18, high: 22, low: 11, mid: 21 },
// | { open: 18, close: 29, high: 32, low: 14, mid: 27 },
// | { open: 29, close: 24, high: 29, low: 13, mid: 27 },
// | { open: 24, close: 8, high: 24, low: 5 },
// | { open: 8, close: 16, high: 22, low: 2 },
// | { open: 16, close: 12, high: 19, low: 7 },
// | { open: 12, close: 20, high: 22, low: 8 },
// | { open: 20, close: 16, high: 22, low: 8 },
// | { open: 16, close: 22, high: 26, low: 6 },
// | { open: 22, close: 18, high: 22, low: 11 },
// | { open: 18, close: 29, high: 32, low: 14 },
// | { open: 29, close: 24, high: 29, low: 13 },
// | { open: 24, close: 8, high: 24, low: 5 },
// | { open: 8, close: 16, high: 22, low: 2 },
// | { open: 16, close: 12, high: 19, low: 7 },
// | { open: 12, close: 20, high: 22, low: 8 },
// | { open: 20, close: 16, high: 22, low: 8 }
// | ],
// | { stroke: { color: "green" }, fill: "lightgreen" }
// | )
// | .render();
//
// theme: dojox.charting.Theme?
// An optional theme to use for styling the chart.
// axes: dojox.charting.Axis{}?
// A map of axes for use in plotting a chart.
// stack: dojox.charting.plot2d.Base[]
// A stack of plotters.
// plots: dojox.charting.plot2d.Base{}
// A map of plotter indices
// series: dojox.charting.Series[]
// The stack of data runs used to create plots.
// runs: dojox.charting.Series{}
// A map of series indices
// margins: Object?
// The margins around the chart. Default is { l:10, t:10, r:10, b:10 }.
// stroke: dojox.gfx.Stroke?
// The outline of the chart (stroke in vector graphics terms).
// fill: dojox.gfx.Fill?
// The color for the chart.
// node: DOMNode
// The container node passed to the constructor.
// surface: dojox.gfx.Surface
// The main graphics surface upon which a chart is drawn.
// dirty: Boolean
// A boolean flag indicating whether or not the chart needs to be updated/re-rendered.
// coords: Object
// The coordinates on a page of the containing node, as returned from dojo.coords.
constructor: function(/* DOMNode */node, /* dojox.charting.__Chart2DCtorArgs? */kwArgs){
// summary:
// The constructor for a new Chart2D. Initializes all parameters used for a chart.
// returns: dojox.charting.Chart2D
// The newly created chart.
// initialize parameters
if(!kwArgs){ kwArgs = {}; }
this.margins = kwArgs.margins ? kwArgs.margins : {l: 10, t: 10, r: 10, b: 10};
this.stroke = kwArgs.stroke;
this.fill = kwArgs.fill;
this.delayInMs = kwArgs.delayInMs || 200;
this.title = kwArgs.title;
this.titleGap = kwArgs.titleGap;
this.titlePos = kwArgs.titlePos;
this.titleFont = kwArgs.titleFont;
this.titleFontColor = kwArgs.titleFontColor;
this.chartTitle = null;
// default initialization
this.theme = null;
this.axes = {}; // map of axes
this.stack = []; // stack of plotters
this.plots = {}; // map of plotter indices
this.series = []; // stack of data runs
this.runs = {}; // map of data run indices
this.dirty = true;
this.coords = null;
// create a surface
this.node = dojo.byId(node);
var box = dojo.marginBox(node);
this.surface = g.createSurface(this.node, box.w || 400, box.h || 300);
},
destroy: function(){
// summary:
// Cleanup when a chart is to be destroyed.
// returns: void
dojo.forEach(this.series, destroy);
dojo.forEach(this.stack, destroy);
df.forIn(this.axes, destroy);
dojo.destroy(this.chartTitle);
this.surface.destroy();
},
getCoords: function(){
// summary:
// Get the coordinates and dimensions of the containing DOMNode, as
// returned by dojo.coords.
// returns: Object
// The resulting coordinates of the chart. See dojo.coords for details.
if(!this.coords){
this.coords = dojo.coords(this.node, true);
}
return this.coords; // Object
},
setTheme: function(theme){
// summary:
// Set a theme of the chart.
// theme: dojox.charting.Theme
// The theme to be used for visual rendering.
// returns: dojox.charting.Chart2D
// A reference to the current chart for functional chaining.
this.theme = theme.clone();
this.dirty = true;
return this; // dojox.charting.Chart2D
},
addAxis: function(name, kwArgs){
// summary:
// Add an axis to the chart, for rendering.
// name: String
// The name of the axis.
// kwArgs: dojox.charting.axis2d.__AxisCtorArgs?
// An optional keyword arguments object for use in defining details of an axis.
// returns: dojox.charting.Chart2D
// A reference to the current chart for functional chaining.
var axis;
if(!kwArgs || !("type" in kwArgs)){
axis = new dc.axis2d.Default(this, kwArgs);
}else{
axis = typeof kwArgs.type == "string" ?
new dc.axis2d[kwArgs.type](this, kwArgs) :
new kwArgs.type(this, kwArgs);
}
axis.name = name;
axis.dirty = true;
if(name in this.axes){
this.axes[name].destroy();
}
this.axes[name] = axis;
this.dirty = true;
return this; // dojox.charting.Chart2D
},
getAxis: function(name){
// summary:
// Get the given axis, by name.
// name: String
// The name the axis was defined by.
// returns: dojox.charting.axis2d.Default
// The axis as stored in the chart's axis map.
return this.axes[name]; // dojox.charting.axis2d.Default
},
removeAxis: function(name){
// summary:
// Remove the axis that was defined using name.
// name: String
// The axis name, as defined in addAxis.
// returns: dojox.charting.Chart2D
// A reference to the current chart for functional chaining.
if(name in this.axes){
// destroy the axis
this.axes[name].destroy();
delete this.axes[name];
// mark the chart as dirty
this.dirty = true;
}
return this; // dojox.charting.Chart2D
},
addPlot: function(name, kwArgs){
// summary:
// Add a new plot to the chart, defined by name and using the optional keyword arguments object.
// Note that dojox.charting assumes the main plot to be called "default"; if you do not have
// a plot called "default" and attempt to add data series to the chart without specifying the
// plot to be rendered on, you WILL get errors.
// name: String
// The name of the plot to be added to the chart. If you only plan on using one plot, call it "default".
// kwArgs: dojox.charting.plot2d.__PlotCtorArgs
// An object with optional parameters for the plot in question.
// returns: dojox.charting.Chart2D
// A reference to the current chart for functional chaining.
var plot;
if(!kwArgs || !("type" in kwArgs)){
plot = new dc.plot2d.Default(this, kwArgs);
}else{
plot = typeof kwArgs.type == "string" ?
new dc.plot2d[kwArgs.type](this, kwArgs) :
new kwArgs.type(this, kwArgs);
}
plot.name = name;
plot.dirty = true;
if(name in this.plots){
this.stack[this.plots[name]].destroy();
this.stack[this.plots[name]] = plot;
}else{
this.plots[name] = this.stack.length;
this.stack.push(plot);
}
this.dirty = true;
return this; // dojox.charting.Chart2D
},
removePlot: function(name){
// summary:
// Remove the plot defined using name from the chart's plot stack.
// name: String
// The name of the plot as defined using addPlot.
// returns: dojox.charting.Chart2D
// A reference to the current chart for functional chaining.
if(name in this.plots){
// get the index and remove the name
var index = this.plots[name];
delete this.plots[name];
// destroy the plot
this.stack[index].destroy();
// remove the plot from the stack
this.stack.splice(index, 1);
// update indices to reflect the shift
df.forIn(this.plots, function(idx, name, plots){
if(idx > index){
plots[name] = idx - 1;
}
});
// remove all related series
var ns = dojo.filter(this.series, function(run){ return run.plot != name; });
if(ns.length < this.series.length){
// kill all removed series
dojo.forEach(this.series, function(run){
if(run.plot == name){
run.destroy();
}
});
// rebuild all necessary data structures
this.runs = {};
dojo.forEach(ns, function(run, index){
this.runs[run.plot] = index;
}, this);
this.series = ns;
}
// mark the chart as dirty
this.dirty = true;
}
return this; // dojox.charting.Chart2D
},
getPlotOrder: function(){
// summary:
// Returns an array of plot names in the current order
// (the top-most plot is the first).
// returns: Array
return df.map(this.stack, getName); // Array
},
setPlotOrder: function(newOrder){
// summary:
// Sets new order of plots. newOrder cannot add or remove
// plots. Wrong names, or dups are ignored.
// newOrder: Array:
// Array of plot names compatible with getPlotOrder().
// returns: dojox.charting.Chart2D
// A reference to the current chart for functional chaining.
var names = {},
order = df.filter(newOrder, function(name){
if(!(name in this.plots) || (name in names)){
return false;
}
names[name] = 1;
return true;
}, this);
if(order.length < this.stack.length){
df.forEach(this.stack, function(plot){
var name = plot.name;
if(!(name in names)){
order.push(name);
}
});
}
var newStack = df.map(order, function(name){
return this.stack[this.plots[name]];
}, this);
df.forEach(newStack, function(plot, i){
this.plots[plot.name] = i;
}, this);
this.stack = newStack;
this.dirty = true;
return this; // dojox.charting.Chart2D
},
movePlotToFront: function(name){
// summary:
// Moves a given plot to front.
// name: String:
// Plot's name to move.
// returns: dojox.charting.Chart2D
// A reference to the current chart for functional chaining.
if(name in this.plots){
var index = this.plots[name];
if(index){
var newOrder = this.getPlotOrder();
newOrder.splice(index, 1);
newOrder.unshift(name);
return this.setPlotOrder(newOrder); // dojox.charting.Chart2D
}
}
return this; // dojox.charting.Chart2D
},
movePlotToBack: function(name){
// summary:
// Moves a given plot to back.
// name: String:
// Plot's name to move.
// returns: dojox.charting.Chart2D
// A reference to the current chart for functional chaining.
if(name in this.plots){
var index = this.plots[name];
if(index < this.stack.length - 1){
var newOrder = this.getPlotOrder();
newOrder.splice(index, 1);
newOrder.push(name);
return this.setPlotOrder(newOrder); // dojox.charting.Chart2D
}
}
return this; // dojox.charting.Chart2D
},
addSeries: function(name, data, kwArgs){
// summary:
// Add a data series to the chart for rendering.
// name: String:
// The name of the data series to be plotted.
// data: Array|Object:
// The array of data points (either numbers or objects) that
// represents the data to be drawn. Or it can be an object. In
// the latter case, it should have a property "data" (an array),
// destroy(), and setSeriesObject().
// kwArgs: dojox.charting.__SeriesCtorArgs?:
// An optional keyword arguments object that will be mixed into
// the resultant series object.
// returns: dojox.charting.Chart2D:
// A reference to the current chart for functional chaining.
var run = new dc.Series(this, data, kwArgs);
run.name = name;
if(name in this.runs){
this.series[this.runs[name]].destroy();
this.series[this.runs[name]] = run;
}else{
this.runs[name] = this.series.length;
this.series.push(run);
}
this.dirty = true;
// fix min/max
if(!("ymin" in run) && "min" in run){ run.ymin = run.min; }
if(!("ymax" in run) && "max" in run){ run.ymax = run.max; }
return this; // dojox.charting.Chart2D
},
removeSeries: function(name){
// summary:
// Remove the series defined by name from the chart.
// name: String
// The name of the series as defined by addSeries.
// returns: dojox.charting.Chart2D
// A reference to the current chart for functional chaining.
if(name in this.runs){
// get the index and remove the name
var index = this.runs[name];
delete this.runs[name];
// destroy the run
this.series[index].destroy();
// remove the run from the stack of series
this.series.splice(index, 1);
// update indices to reflect the shift
df.forIn(this.runs, function(idx, name, runs){
if(idx > index){
runs[name] = idx - 1;
}
});
this.dirty = true;
}
return this; // dojox.charting.Chart2D
},
updateSeries: function(name, data){
// summary:
// Update the given series with a new set of data points.
// name: String
// The name of the series as defined in addSeries.
// data: Array|Object:
// The array of data points (either numbers or objects) that
// represents the data to be drawn. Or it can be an object. In
// the latter case, it should have a property "data" (an array),
// destroy(), and setSeriesObject().
// returns: dojox.charting.Chart2D
// A reference to the current chart for functional chaining.
if(name in this.runs){
var run = this.series[this.runs[name]];
run.update(data);
this._invalidateDependentPlots(run.plot, false);
this._invalidateDependentPlots(run.plot, true);
}
return this; // dojox.charting.Chart2D
},
getSeriesOrder: function(plotName){
// summary:
// Returns an array of series names in the current order
// (the top-most series is the first) within a plot.
// plotName: String:
// Plot's name.
// returns: Array
return df.map(df.filter(this.series, function(run){
return run.plot == plotName;
}), getName);
},
setSeriesOrder: function(newOrder){
// summary:
// Sets new order of series within a plot. newOrder cannot add
// or remove series. Wrong names, or dups are ignored.
// newOrder: Array:
// Array of series names compatible with getPlotOrder(). All
// series should belong to the same plot.
// returns: dojox.charting.Chart2D
// A reference to the current chart for functional chaining.
var plotName, names = {},
order = df.filter(newOrder, function(name){
if(!(name in this.runs) || (name in names)){
return false;
}
var run = this.series[this.runs[name]];
if(plotName){
if(run.plot != plotName){
return false;
}
}else{
plotName = run.plot;
}
names[name] = 1;
return true;
}, this);
df.forEach(this.series, function(run){
var name = run.name;
if(!(name in names) && run.plot == plotName){
order.push(name);
}
});
var newSeries = df.map(order, function(name){
return this.series[this.runs[name]];
}, this);
this.series = newSeries.concat(df.filter(this.series, function(run){
return run.plot != plotName;
}));
df.forEach(this.series, function(run, i){
this.runs[run.name] = i;
}, this);
this.dirty = true;
return this; // dojox.charting.Chart2D
},
moveSeriesToFront: function(name){
// summary:
// Moves a given series to front of a plot.
// name: String:
// Series' name to move.
// returns: dojox.charting.Chart2D
// A reference to the current chart for functional chaining.
if(name in this.runs){
var index = this.runs[name],
newOrder = this.getSeriesOrder(this.series[index].plot);
if(name != newOrder[0]){
newOrder.splice(index, 1);
newOrder.unshift(name);
return this.setSeriesOrder(newOrder); // dojox.charting.Chart2D
}
}
return this; // dojox.charting.Chart2D
},
moveSeriesToBack: function(name){
// summary:
// Moves a given series to back of a plot.
// name: String:
// Series' name to move.
// returns: dojox.charting.Chart2D
// A reference to the current chart for functional chaining.
if(name in this.runs){
var index = this.runs[name],
newOrder = this.getSeriesOrder(this.series[index].plot);
if(name != newOrder[newOrder.length - 1]){
newOrder.splice(index, 1);
newOrder.push(name);
return this.setSeriesOrder(newOrder); // dojox.charting.Chart2D
}
}
return this; // dojox.charting.Chart2D
},
resize: function(width, height){
// summary:
// Resize the chart to the dimensions of width and height.
// width: Number
// The new width of the chart.
// height: Number
// The new height of the chart.
// returns: dojox.charting.Chart2D
// A reference to the current chart for functional chaining.
var box;
switch(arguments.length){
case 0:
box = dojo.marginBox(this.node);
break;
case 1:
box = width;
break;
default:
box = { w: width, h: height };
break;
}
dojo.marginBox(this.node, box);
this.surface.setDimensions(box.w, box.h);
this.dirty = true;
this.coords = null;
return this.render(); // dojox.charting.Chart2D
},
getGeometry: function(){
// summary:
// Returns a map of information about all axes in a chart and what they represent
// in terms of scaling (see dojox.charting.axis2d.Default.getScaler).
// returns: Object
// An map of geometry objects, a one-to-one mapping of axes.
var ret = {};
df.forIn(this.axes, function(axis){
if(axis.initialized()){
ret[axis.name] = {
name: axis.name,
vertical: axis.vertical,
scaler: axis.scaler,
ticks: axis.ticks
};
}
});
return ret; // Object
},
setAxisWindow: function(name, scale, offset, zoom){
// summary:
// Zooms an axis and all dependent plots. Can be used to zoom in 1D.
// name: String
// The name of the axis as defined by addAxis.
// scale: Number
// The scale on the target axis.
// offset: Number
// Any offest, as measured by axis tick
// zoom: Boolean|Object?
// The chart zooming animation trigger. This is null by default,
// e.g. {duration: 1200}, or just set true.
// returns: dojox.charting.Chart2D
// A reference to the current chart for functional chaining.
var axis = this.axes[name];
if(axis){
axis.setWindow(scale, offset);
dojo.forEach(this.stack,function(plot){
if(plot.hAxis == name || plot.vAxis == name){
plot.zoom = zoom;
}
})
}
return this; // dojox.charting.Chart2D
},
setWindow: function(sx, sy, dx, dy, zoom){
// summary:
// Zooms in or out any plots in two dimensions.
// sx: Number
// The scale for the x axis.
// sy: Number
// The scale for the y axis.
// dx: Number
// The pixel offset on the x axis.
// dy: Number
// The pixel offset on the y axis.
// zoom: Boolean|Object?
// The chart zooming animation trigger. This is null by default,
// e.g. {duration: 1200}, or just set true.
// returns: dojox.charting.Chart2D
// A reference to the current chart for functional chaining.
if(!("plotArea" in this)){
this.calculateGeometry();
}
df.forIn(this.axes, function(axis){
var scale, offset, bounds = axis.getScaler().bounds,
s = bounds.span / (bounds.upper - bounds.lower);
if(axis.vertical){
scale = sy;
offset = dy / s / scale;
}else{
scale = sx;
offset = dx / s / scale;
}
axis.setWindow(scale, offset);
});
dojo.forEach(this.stack, function(plot){ plot.zoom = zoom; });
return this; // dojox.charting.Chart2D
},
zoomIn: function(name, range){
// summary:
// Zoom the chart to a specific range on one axis. This calls render()
// directly as a convenience method.
// name: String
// The name of the axis as defined by addAxis.
// range: Array
// The end points of the zoom range, measured in axis ticks.
var axis = this.axes[name];
if(axis){
var scale, offset, bounds = axis.getScaler().bounds;
var lower = Math.min(range[0],range[1]);
var upper = Math.max(range[0],range[1]);
lower = range[0] < bounds.lower ? bounds.lower : lower;
upper = range[1] > bounds.upper ? bounds.upper : upper;
scale = (bounds.upper - bounds.lower) / (upper - lower);
offset = lower - bounds.lower;
this.setAxisWindow(name, scale, offset);
this.render();
}
},
calculateGeometry: function(){
// summary:
// Calculate the geometry of the chart based on the defined axes of
// a chart.
// returns: dojox.charting.Chart2D
// A reference to the current chart for functional chaining.
if(this.dirty){
return this.fullGeometry();
}
// calculate geometry
var dirty = dojo.filter(this.stack, function(plot){
return plot.dirty ||
(plot.hAxis && this.axes[plot.hAxis].dirty) ||
(plot.vAxis && this.axes[plot.vAxis].dirty);
}, this);
calculateAxes(dirty, this.plotArea);
return this; // dojox.charting.Chart2D
},
fullGeometry: function(){
// summary:
// Calculate the full geometry of the chart. This includes passing
// over all major elements of a chart (plots, axes, series, container)
// in order to ensure proper rendering.
// returns: dojox.charting.Chart2D
// A reference to the current chart for functional chaining.
this._makeDirty();
// clear old values
dojo.forEach(this.stack, clear);
// rebuild new connections, and add defaults
// set up a theme
if(!this.theme){
this.setTheme(new dojox.charting.Theme(dojox.charting._def));
}
// assign series
dojo.forEach(this.series, function(run){
if(!(run.plot in this.plots)){
var plot = new dc.plot2d.Default(this, {});
plot.name = run.plot;
this.plots[run.plot] = this.stack.length;
this.stack.push(plot);
}
this.stack[this.plots[run.plot]].addSeries(run);
}, this);
// assign axes
dojo.forEach(this.stack, function(plot){
if(plot.hAxis){
plot.setAxis(this.axes[plot.hAxis]);
}
if(plot.vAxis){
plot.setAxis(this.axes[plot.vAxis]);
}
}, this);
// calculate geometry
// 1st pass
var dim = this.dim = this.surface.getDimensions();
dim.width = g.normalizedLength(dim.width);
dim.height = g.normalizedLength(dim.height);
df.forIn(this.axes, clear);
calculateAxes(this.stack, dim);
// assumption: we don't have stacked axes yet
var offsets = this.offsets = { l: 0, r: 0, t: 0, b: 0 };
df.forIn(this.axes, function(axis){
df.forIn(axis.getOffsets(), function(o, i){ offsets[i] += o; });
});
// add title area
if(this.title){
this.titleGap = (this.titleGap==0) ? 0 : this.titleGap || this.theme.chart.titleGap || 20;
this.titlePos = this.titlePos || this.theme.chart.titlePos || "top";
this.titleFont = this.titleFont || this.theme.chart.titleFont;
this.titleFontColor = this.titleFontColor || this.theme.chart.titleFontColor || "black";
var tsize = g.normalizedLength(g.splitFontString(this.titleFont).size);
offsets[this.titlePos=="top" ? "t":"b"] += (tsize + this.titleGap);
}
// add margins
df.forIn(this.margins, function(o, i){ offsets[i] += o; });
// 2nd pass with realistic dimensions
this.plotArea = {
width: dim.width - offsets.l - offsets.r,
height: dim.height - offsets.t - offsets.b
};
df.forIn(this.axes, clear);
calculateAxes(this.stack, this.plotArea);
return this; // dojox.charting.Chart2D
},
render: function(){
// summary:
// Render the chart according to the current information defined. This should
// be the last call made when defining/creating a chart, or if data within the
// chart has been changed.
// returns: dojox.charting.Chart2D
// A reference to the current chart for functional chaining.
if(this.theme){
this.theme.clear();
}
if(this.dirty){
return this.fullRender();
}
this.calculateGeometry();
// go over the stack backwards
df.forEachRev(this.stack, function(plot){ plot.render(this.dim, this.offsets); }, this);
// go over axes
df.forIn(this.axes, function(axis){ axis.render(this.dim, this.offsets); }, this);
this._makeClean();
// BEGIN FOR HTML CANVAS
if(this.surface.render){ this.surface.render(); };
// END FOR HTML CANVAS
return this; // dojox.charting.Chart2D
},
fullRender: function(){
// summary:
// Force a full rendering of the chart, including full resets on the chart itself.
// You should not call this method directly unless absolutely necessary.
// returns: dojox.charting.Chart2D
// A reference to the current chart for functional chaining.
// calculate geometry
this.fullGeometry();
var offsets = this.offsets, dim = this.dim;
// get required colors
//var requiredColors = df.foldl(this.stack, "z + plot.getRequiredColors()", 0);
//this.theme.defineColors({num: requiredColors, cache: false});
// clear old shapes
dojo.forEach(this.series, purge);
df.forIn(this.axes, purge);
dojo.forEach(this.stack, purge);
//if it's HTML title
dojo.destroy(this.chartTitle);
this.surface.clear();
// generate shapes
// draw a plot background
var t = this.theme,
fill = t.plotarea && t.plotarea.fill,
stroke = t.plotarea && t.plotarea.stroke;
if(fill){
this.surface.createRect({
x: offsets.l - 1, y: offsets.t - 1,
width: dim.width - offsets.l - offsets.r + 2,
height: dim.height - offsets.t - offsets.b + 2
}).setFill(fill);
}
if(stroke){
this.surface.createRect({
x: offsets.l, y: offsets.t,
width: dim.width - offsets.l - offsets.r + 1,
height: dim.height - offsets.t - offsets.b + 1
}).setStroke(stroke);
}
// go over the stack backwards
df.foldr(this.stack, function(z, plot){ return plot.render(dim, offsets), 0; }, 0);
// pseudo-clipping: matting
fill = this.fill !== undefined ? this.fill : (t.chart && t.chart.fill);
stroke = this.stroke !== undefined ? this.stroke : (t.chart && t.chart.stroke);
// TRT: support for "inherit" as a named value in a theme.
if(fill == "inherit"){
// find the background color of the nearest ancestor node, and use that explicitly.
var node = this.node, fill = new dojo.Color(dojo.style(node, "backgroundColor"));
while(fill.a==0 && node!=document.documentElement){
fill = new dojo.Color(dojo.style(node, "backgroundColor"));
node = node.parentNode;
}
}
if(fill){
if(offsets.l){ // left
this.surface.createRect({
width: offsets.l,
height: dim.height + 1
}).setFill(fill);
}
if(offsets.r){ // right
this.surface.createRect({
x: dim.width - offsets.r,
width: offsets.r + 1,
height: dim.height + 2
}).setFill(fill);
}
if(offsets.t){ // top
this.surface.createRect({
width: dim.width + 1,
height: offsets.t
}).setFill(fill);
}
if(offsets.b){ // bottom
this.surface.createRect({
y: dim.height - offsets.b,
width: dim.width + 1,
height: offsets.b + 2
}).setFill(fill);
}
}
//create title: Whether to make chart title as a widget which extends dojox.charting.Element?
if(this.title){
var forceHtmlLabels = (g.renderer == "canvas"),
labelType = forceHtmlLabels || !dojo.isIE && !dojo.isOpera ? "html" : "gfx",
tsize = g.normalizedLength(g.splitFontString(this.titleFont).size);
this.chartTitle = dc.axis2d.common.createText[labelType](
this,
this.surface,
dim.width/2,
this.titlePos=="top" ? tsize + this.margins.t : dim.height - this.margins.b,
"middle",
this.title,
this.titleFont,
this.titleFontColor
);
}
if(stroke){
this.surface.createRect({
width: dim.width - 1,
height: dim.height - 1
}).setStroke(stroke);
}
// go over axes
df.forIn(this.axes, function(axis){ axis.render(dim, offsets); });
this._makeClean();
// BEGIN FOR HTML CANVAS
if(this.surface.render){ this.surface.render(); };
// END FOR HTML CANVAS
return this; // dojox.charting.Chart2D
},
delayedRender: function(){
// summary:
// Delayed render, which is used to collect multiple updates
// within a delayInMs time window.
// returns: dojox.charting.Chart2D
// A reference to the current chart for functional chaining.
if(!this._delayedRenderHandle){
this._delayedRenderHandle = setTimeout(
dojo.hitch(this, function(){
clearTimeout(this._delayedRenderHandle);
this._delayedRenderHandle = null;
this.render();
}),
this.delayInMs
);
}
return this; // dojox.charting.Chart2D
},
connectToPlot: function(name, object, method){
// summary:
// A convenience method to connect a function to a plot.
// name: String
// The name of the plot as defined by addPlot.
// object: Object
// The object to be connected.
// method: Function
// The function to be executed.
// returns: Array
// A handle to the connection, as defined by dojo.connect (see dojo.connect).
return name in this.plots ? this.stack[this.plots[name]].connect(object, method) : null; // Array
},
fireEvent: function(seriesName, eventName, index){
// summary:
// Fires a synthetic event for a series item.
// seriesName: String:
// Series name.
// eventName: String:
// Event name to simulate: onmouseover, onmouseout, onclick.
// index: Number:
// Valid data value index for the event.
// returns: dojox.charting.Chart2D
// A reference to the current chart for functional chaining.
if(seriesName in this.runs){
var plotName = this.series[this.runs[seriesName]].plot;
if(plotName in this.plots){
var plot = this.stack[this.plots[plotName]];
if(plot){
plot.fireEvent(seriesName, eventName, index);
}
}
}
return this; // dojox.charting.Chart2D
},
_makeClean: function(){
// reset dirty flags
dojo.forEach(this.axes, makeClean);
dojo.forEach(this.stack, makeClean);
dojo.forEach(this.series, makeClean);
this.dirty = false;
},
_makeDirty: function(){
// reset dirty flags
dojo.forEach(this.axes, makeDirty);
dojo.forEach(this.stack, makeDirty);
dojo.forEach(this.series, makeDirty);
this.dirty = true;
},
_invalidateDependentPlots: function(plotName, /* Boolean */ verticalAxis){
if(plotName in this.plots){
var plot = this.stack[this.plots[plotName]], axis,
axisName = verticalAxis ? "vAxis" : "hAxis";
if(plot[axisName]){
axis = this.axes[plot[axisName]];
if(axis && axis.dependOnData()){
axis.dirty = true;
// find all plots and mark them dirty
dojo.forEach(this.stack, function(p){
if(p[axisName] && p[axisName] == plot[axisName]){
p.dirty = true;
}
});
}
}else{
plot.dirty = true;
}
}
}
});
function hSection(stats){
return {min: stats.hmin, max: stats.hmax};
}
function vSection(stats){
return {min: stats.vmin, max: stats.vmax};
}
function hReplace(stats, h){
stats.hmin = h.min;
stats.hmax = h.max;
}
function vReplace(stats, v){
stats.vmin = v.min;
stats.vmax = v.max;
}
function combineStats(target, source){
if(target && source){
target.min = Math.min(target.min, source.min);
target.max = Math.max(target.max, source.max);
}
return target || source;
}
function calculateAxes(stack, plotArea){
var plots = {}, axes = {};
dojo.forEach(stack, function(plot){
var stats = plots[plot.name] = plot.getSeriesStats();
if(plot.hAxis){
axes[plot.hAxis] = combineStats(axes[plot.hAxis], hSection(stats));
}
if(plot.vAxis){
axes[plot.vAxis] = combineStats(axes[plot.vAxis], vSection(stats));
}
});
dojo.forEach(stack, function(plot){
var stats = plots[plot.name];
if(plot.hAxis){
hReplace(stats, axes[plot.hAxis]);
}
if(plot.vAxis){
vReplace(stats, axes[plot.vAxis]);
}
plot.initializeScalers(plotArea, stats);
});
}
})();
|
Chart2D.js
|
dojo.provide("dojox.charting.Chart2D");
dojo.require("dojox.gfx");
dojo.require("dojox.lang.functional");
dojo.require("dojox.lang.functional.fold");
dojo.require("dojox.lang.functional.reversed");
dojo.require("dojox.charting.Theme");
dojo.require("dojox.charting.Series");
// require all axes to support references by name
dojo.require("dojox.charting.axis2d.Default");
dojo.require("dojox.charting.axis2d.Invisible");
// require all plots to support references by name
dojo.require("dojox.charting.plot2d.Default");
dojo.require("dojox.charting.plot2d.Lines");
dojo.require("dojox.charting.plot2d.Areas");
dojo.require("dojox.charting.plot2d.Markers");
dojo.require("dojox.charting.plot2d.MarkersOnly");
dojo.require("dojox.charting.plot2d.Scatter");
dojo.require("dojox.charting.plot2d.Stacked");
dojo.require("dojox.charting.plot2d.StackedLines");
dojo.require("dojox.charting.plot2d.StackedAreas");
dojo.require("dojox.charting.plot2d.Columns");
dojo.require("dojox.charting.plot2d.StackedColumns");
dojo.require("dojox.charting.plot2d.ClusteredColumns");
dojo.require("dojox.charting.plot2d.Bars");
dojo.require("dojox.charting.plot2d.StackedBars");
dojo.require("dojox.charting.plot2d.ClusteredBars");
dojo.require("dojox.charting.plot2d.Grid");
dojo.require("dojox.charting.plot2d.Pie");
dojo.require("dojox.charting.plot2d.Bubble");
dojo.require("dojox.charting.plot2d.Candlesticks");
dojo.require("dojox.charting.plot2d.OHLC");
dojo.require("dojox.charting.plot2d.Spider");
/*=====
dojox.charting.__Chart2DCtorArgs = function(margins, stroke, fill, delayInMs){
// summary:
// The keyword arguments that can be passed in a Chart2D constructor.
//
// margins: Object?
// Optional margins for the chart, in the form of { l, t, r, b}.
// stroke: dojox.gfx.Stroke?
// An optional outline/stroke for the chart.
// fill: dojox.gfx.Fill?
// An optional fill for the chart.
// delayInMs: Number
// Delay in ms for delayedRender(). Default: 200.
this.margins = margins;
this.stroke = stroke;
this.fill = fill;
this.delayInMs = delayInMs;
}
=====*/
(function(){
var df = dojox.lang.functional, dc = dojox.charting, g = dojox.gfx,
clear = df.lambda("item.clear()"),
purge = df.lambda("item.purgeGroup()"),
destroy = df.lambda("item.destroy()"),
makeClean = df.lambda("item.dirty = false"),
makeDirty = df.lambda("item.dirty = true"),
getName = df.lambda("item.name");
dojo.declare("dojox.charting.Chart2D", null, {
// summary:
// The main chart object in dojox.charting. This will create a two dimensional
// chart based on dojox.gfx.
//
// description:
// dojox.charting.Chart2D is the primary object used for any kind of charts. It
// is simple to create--just pass it a node reference, which is used as the
// container for the chart--and a set of optional keyword arguments and go.
//
// Note that like most of dojox.gfx, most of dojox.charting.Chart2D's methods are
// designed to return a reference to the chart itself, to allow for functional
// chaining. This makes defining everything on a Chart very easy to do.
//
// example:
// Create an area chart, with smoothing.
// | new dojox.charting.Chart2D(node))
// | .addPlot("default", { type: "Areas", tension: "X" })
// | .setTheme(dojox.charting.themes.Shrooms)
// | .addSeries("Series A", [1, 2, 0.5, 1.5, 1, 2.8, 0.4])
// | .addSeries("Series B", [2.6, 1.8, 2, 1, 1.4, 0.7, 2])
// | .addSeries("Series C", [6.3, 1.8, 3, 0.5, 4.4, 2.7, 2])
// | .render();
//
// example:
// The form of data in a data series can take a number of forms: a simple array,
// an array of objects {x,y}, or something custom (as determined by the plot).
// Here's an example of a Candlestick chart, which expects an object of
// { open, high, low, close }.
// | new dojox.charting.Chart2D(node))
// | .addPlot("default", {type: "Candlesticks", gap: 1})
// | .addAxis("x", {fixLower: "major", fixUpper: "major", includeZero: true})
// | .addAxis("y", {vertical: true, fixLower: "major", fixUpper: "major", natural: true})
// | .addSeries("Series A", [
// | { open: 20, close: 16, high: 22, low: 8 },
// | { open: 16, close: 22, high: 26, low: 6, mid: 18 },
// | { open: 22, close: 18, high: 22, low: 11, mid: 21 },
// | { open: 18, close: 29, high: 32, low: 14, mid: 27 },
// | { open: 29, close: 24, high: 29, low: 13, mid: 27 },
// | { open: 24, close: 8, high: 24, low: 5 },
// | { open: 8, close: 16, high: 22, low: 2 },
// | { open: 16, close: 12, high: 19, low: 7 },
// | { open: 12, close: 20, high: 22, low: 8 },
// | { open: 20, close: 16, high: 22, low: 8 },
// | { open: 16, close: 22, high: 26, low: 6, mid: 18 },
// | { open: 22, close: 18, high: 22, low: 11, mid: 21 },
// | { open: 18, close: 29, high: 32, low: 14, mid: 27 },
// | { open: 29, close: 24, high: 29, low: 13, mid: 27 },
// | { open: 24, close: 8, high: 24, low: 5 },
// | { open: 8, close: 16, high: 22, low: 2 },
// | { open: 16, close: 12, high: 19, low: 7 },
// | { open: 12, close: 20, high: 22, low: 8 },
// | { open: 20, close: 16, high: 22, low: 8 },
// | { open: 16, close: 22, high: 26, low: 6 },
// | { open: 22, close: 18, high: 22, low: 11 },
// | { open: 18, close: 29, high: 32, low: 14 },
// | { open: 29, close: 24, high: 29, low: 13 },
// | { open: 24, close: 8, high: 24, low: 5 },
// | { open: 8, close: 16, high: 22, low: 2 },
// | { open: 16, close: 12, high: 19, low: 7 },
// | { open: 12, close: 20, high: 22, low: 8 },
// | { open: 20, close: 16, high: 22, low: 8 }
// | ],
// | { stroke: { color: "green" }, fill: "lightgreen" }
// | )
// | .render();
//
// theme: dojox.charting.Theme?
// An optional theme to use for styling the chart.
// axes: dojox.charting.Axis{}?
// A map of axes for use in plotting a chart.
// stack: dojox.charting.plot2d.Base[]
// A stack of plotters.
// plots: dojox.charting.plot2d.Base{}
// A map of plotter indices
// series: dojox.charting.Series[]
// The stack of data runs used to create plots.
// runs: dojox.charting.Series{}
// A map of series indices
// margins: Object?
// The margins around the chart. Default is { l:10, t:10, r:10, b:10 }.
// stroke: dojox.gfx.Stroke?
// The outline of the chart (stroke in vector graphics terms).
// fill: dojox.gfx.Fill?
// The color for the chart.
// node: DOMNode
// The container node passed to the constructor.
// surface: dojox.gfx.Surface
// The main graphics surface upon which a chart is drawn.
// dirty: Boolean
// A boolean flag indicating whether or not the chart needs to be updated/re-rendered.
// coords: Object
// The coordinates on a page of the containing node, as returned from dojo.coords.
constructor: function(/* DOMNode */node, /* dojox.charting.__Chart2DCtorArgs? */kwArgs){
// summary:
// The constructor for a new Chart2D. Initializes all parameters used for a chart.
// returns: dojox.charting.Chart2D
// The newly created chart.
// initialize parameters
if(!kwArgs){ kwArgs = {}; }
this.margins = kwArgs.margins ? kwArgs.margins : {l: 10, t: 10, r: 10, b: 10};
this.stroke = kwArgs.stroke;
this.fill = kwArgs.fill;
this.delayInMs = kwArgs.delayInMs || 200;
this.title = kwArgs.title;
this.titleGap = kwArgs.titleGap;
this.titlePos = kwArgs.titlePos;
this.titleFont = kwArgs.titleFont;
this.titleFontColor = kwArgs.titleFontColor;
this.chartTitle = null;
// default initialization
this.theme = null;
this.axes = {}; // map of axes
this.stack = []; // stack of plotters
this.plots = {}; // map of plotter indices
this.series = []; // stack of data runs
this.runs = {}; // map of data run indices
this.dirty = true;
this.coords = null;
// create a surface
this.node = dojo.byId(node);
var box = dojo.marginBox(node);
this.surface = g.createSurface(this.node, box.w || 400, box.h || 300);
},
destroy: function(){
// summary:
// Cleanup when a chart is to be destroyed.
// returns: void
dojo.forEach(this.series, destroy);
dojo.forEach(this.stack, destroy);
df.forIn(this.axes, destroy);
dojo.destroy(this.chartTitle);
this.surface.destroy();
},
getCoords: function(){
// summary:
// Get the coordinates and dimensions of the containing DOMNode, as
// returned by dojo.coords.
// returns: Object
// The resulting coordinates of the chart. See dojo.coords for details.
if(!this.coords){
this.coords = dojo.coords(this.node, true);
}
return this.coords; // Object
},
setTheme: function(theme){
// summary:
// Set a theme of the chart.
// theme: dojox.charting.Theme
// The theme to be used for visual rendering.
// returns: dojox.charting.Chart2D
// A reference to the current chart for functional chaining.
this.theme = theme.clone();
this.dirty = true;
return this; // dojox.charting.Chart2D
},
addAxis: function(name, kwArgs){
// summary:
// Add an axis to the chart, for rendering.
// name: String
// The name of the axis.
// kwArgs: dojox.charting.axis2d.__AxisCtorArgs?
// An optional keyword arguments object for use in defining details of an axis.
// returns: dojox.charting.Chart2D
// A reference to the current chart for functional chaining.
var axis;
if(!kwArgs || !("type" in kwArgs)){
axis = new dc.axis2d.Default(this, kwArgs);
}else{
axis = typeof kwArgs.type == "string" ?
new dc.axis2d[kwArgs.type](this, kwArgs) :
new kwArgs.type(this, kwArgs);
}
axis.name = name;
axis.dirty = true;
if(name in this.axes){
this.axes[name].destroy();
}
this.axes[name] = axis;
this.dirty = true;
return this; // dojox.charting.Chart2D
},
getAxis: function(name){
// summary:
// Get the given axis, by name.
// name: String
// The name the axis was defined by.
// returns: dojox.charting.axis2d.Default
// The axis as stored in the chart's axis map.
return this.axes[name]; // dojox.charting.axis2d.Default
},
removeAxis: function(name){
// summary:
// Remove the axis that was defined using name.
// name: String
// The axis name, as defined in addAxis.
// returns: dojox.charting.Chart2D
// A reference to the current chart for functional chaining.
if(name in this.axes){
// destroy the axis
this.axes[name].destroy();
delete this.axes[name];
// mark the chart as dirty
this.dirty = true;
}
return this; // dojox.charting.Chart2D
},
addPlot: function(name, kwArgs){
// summary:
// Add a new plot to the chart, defined by name and using the optional keyword arguments object.
// Note that dojox.charting assumes the main plot to be called "default"; if you do not have
// a plot called "default" and attempt to add data series to the chart without specifying the
// plot to be rendered on, you WILL get errors.
// name: String
// The name of the plot to be added to the chart. If you only plan on using one plot, call it "default".
// kwArgs: dojox.charting.plot2d.__PlotCtorArgs
// An object with optional parameters for the plot in question.
// returns: dojox.charting.Chart2D
// A reference to the current chart for functional chaining.
var plot;
if(!kwArgs || !("type" in kwArgs)){
plot = new dc.plot2d.Default(this, kwArgs);
}else{
plot = typeof kwArgs.type == "string" ?
new dc.plot2d[kwArgs.type](this, kwArgs) :
new kwArgs.type(this, kwArgs);
}
plot.name = name;
plot.dirty = true;
if(name in this.plots){
this.stack[this.plots[name]].destroy();
this.stack[this.plots[name]] = plot;
}else{
this.plots[name] = this.stack.length;
this.stack.push(plot);
}
this.dirty = true;
return this; // dojox.charting.Chart2D
},
removePlot: function(name){
// summary:
// Remove the plot defined using name from the chart's plot stack.
// name: String
// The name of the plot as defined using addPlot.
// returns: dojox.charting.Chart2D
// A reference to the current chart for functional chaining.
if(name in this.plots){
// get the index and remove the name
var index = this.plots[name];
delete this.plots[name];
// destroy the plot
this.stack[index].destroy();
// remove the plot from the stack
this.stack.splice(index, 1);
// update indices to reflect the shift
df.forIn(this.plots, function(idx, name, plots){
if(idx > index){
plots[name] = idx - 1;
}
});
// mark the chart as dirty
this.dirty = true;
}
return this; // dojox.charting.Chart2D
},
getPlotOrder: function(){
// summary:
// Returns an array of plot names in the current order
// (the top-most plot is the first).
// returns: Array
return df.map(this.stack, getName); // Array
},
setPlotOrder: function(newOrder){
// summary:
// Sets new order of plots. newOrder cannot add or remove
// plots. Wrong names, or dups are ignored.
// newOrder: Array:
// Array of plot names compatible with getPlotOrder().
// returns: dojox.charting.Chart2D
// A reference to the current chart for functional chaining.
var names = {},
order = df.filter(newOrder, function(name){
if(!(name in this.plots) || (name in names)){
return false;
}
names[name] = 1;
return true;
}, this);
if(order.length < this.stack.length){
df.forEach(this.stack, function(plot){
var name = plot.name;
if(!(name in names)){
order.push(name);
}
});
}
var newStack = df.map(order, function(name){
return this.stack[this.plots[name]];
}, this);
df.forEach(newStack, function(plot, i){
this.plots[plot.name] = i;
}, this);
this.stack = newStack;
this.dirty = true;
return this; // dojox.charting.Chart2D
},
movePlotToFront: function(name){
// summary:
// Moves a given plot to front.
// name: String:
// Plot's name to move.
// returns: dojox.charting.Chart2D
// A reference to the current chart for functional chaining.
if(name in this.plots){
var index = this.plots[name];
if(index){
var newOrder = this.getPlotOrder();
newOrder.splice(index, 1);
newOrder.unshift(name);
return this.setPlotOrder(newOrder); // dojox.charting.Chart2D
}
}
return this; // dojox.charting.Chart2D
},
movePlotToBack: function(name){
// summary:
// Moves a given plot to back.
// name: String:
// Plot's name to move.
// returns: dojox.charting.Chart2D
// A reference to the current chart for functional chaining.
if(name in this.plots){
var index = this.plots[name];
if(index < this.stack.length - 1){
var newOrder = this.getPlotOrder();
newOrder.splice(index, 1);
newOrder.push(name);
return this.setPlotOrder(newOrder); // dojox.charting.Chart2D
}
}
return this; // dojox.charting.Chart2D
},
addSeries: function(name, data, kwArgs){
// summary:
// Add a data series to the chart for rendering.
// name: String:
// The name of the data series to be plotted.
// data: Array|Object:
// The array of data points (either numbers or objects) that
// represents the data to be drawn. Or it can be an object. In
// the latter case, it should have a property "data" (an array),
// destroy(), and setSeriesObject().
// kwArgs: dojox.charting.__SeriesCtorArgs?:
// An optional keyword arguments object that will be mixed into
// the resultant series object.
// returns: dojox.charting.Chart2D:
// A reference to the current chart for functional chaining.
var run = new dc.Series(this, data, kwArgs);
run.name = name;
if(name in this.runs){
this.series[this.runs[name]].destroy();
this.series[this.runs[name]] = run;
}else{
this.runs[name] = this.series.length;
this.series.push(run);
}
this.dirty = true;
// fix min/max
if(!("ymin" in run) && "min" in run){ run.ymin = run.min; }
if(!("ymax" in run) && "max" in run){ run.ymax = run.max; }
return this; // dojox.charting.Chart2D
},
removeSeries: function(name){
// summary:
// Remove the series defined by name from the chart.
// name: String
// The name of the series as defined by addSeries.
// returns: dojox.charting.Chart2D
// A reference to the current chart for functional chaining.
if(name in this.runs){
// get the index and remove the name
var index = this.runs[name],
plotName = this.series[index].plot;
delete this.runs[name];
// destroy the run
this.series[index].destroy();
// remove the run from the stack of series
this.series.splice(index, 1);
// update indices to reflect the shift
df.forIn(this.runs, function(idx, name, runs){
if(idx > index){
runs[name] = idx - 1;
}
});
this.dirty = true;
}
return this; // dojox.charting.Chart2D
},
updateSeries: function(name, data){
// summary:
// Update the given series with a new set of data points.
// name: String
// The name of the series as defined in addSeries.
// data: Array|Object:
// The array of data points (either numbers or objects) that
// represents the data to be drawn. Or it can be an object. In
// the latter case, it should have a property "data" (an array),
// destroy(), and setSeriesObject().
// returns: dojox.charting.Chart2D
// A reference to the current chart for functional chaining.
if(name in this.runs){
var run = this.series[this.runs[name]];
run.update(data);
this._invalidateDependentPlots(run.plot, false);
this._invalidateDependentPlots(run.plot, true);
}
return this; // dojox.charting.Chart2D
},
getSeriesOrder: function(plotName){
// summary:
// Returns an array of series names in the current order
// (the top-most series is the first) within a plot.
// plotName: String:
// Plot's name.
// returns: Array
return df.map(df.filter(this.series, function(run){
return run.plot == plotName;
}), getName);
},
setSeriesOrder: function(newOrder){
// summary:
// Sets new order of series within a plot. newOrder cannot add
// or remove series. Wrong names, or dups are ignored.
// newOrder: Array:
// Array of series names compatible with getPlotOrder(). All
// series should belong to the same plot.
// returns: dojox.charting.Chart2D
// A reference to the current chart for functional chaining.
var plotName, names = {},
order = df.filter(newOrder, function(name){
if(!(name in this.runs) || (name in names)){
return false;
}
var run = this.series[this.runs[name]];
if(plotName){
if(run.plot != plotName){
return false;
}
}else{
plotName = run.plot;
}
names[name] = 1;
return true;
}, this);
df.forEach(this.series, function(run){
var name = run.name;
if(!(name in names) && run.plot == plotName){
order.push(name);
}
});
var newSeries = df.map(order, function(name){
return this.series[this.runs[name]];
}, this);
this.series = newSeries.concat(df.filter(this.series, function(run){
return run.plot != plotName;
}));
df.forEach(this.series, function(run, i){
this.runs[run.name] = i;
}, this);
this.dirty = true;
return this; // dojox.charting.Chart2D
},
moveSeriesToFront: function(name){
// summary:
// Moves a given series to front of a plot.
// name: String:
// Series' name to move.
// returns: dojox.charting.Chart2D
// A reference to the current chart for functional chaining.
if(name in this.runs){
var index = this.runs[name],
newOrder = this.getSeriesOrder(this.series[index].plot);
if(name != newOrder[0]){
newOrder.splice(index, 1);
newOrder.unshift(name);
return this.setSeriesOrder(newOrder); // dojox.charting.Chart2D
}
}
return this; // dojox.charting.Chart2D
},
moveSeriesToBack: function(name){
// summary:
// Moves a given series to back of a plot.
// name: String:
// Series' name to move.
// returns: dojox.charting.Chart2D
// A reference to the current chart for functional chaining.
if(name in this.runs){
var index = this.runs[name],
newOrder = this.getSeriesOrder(this.series[index].plot);
if(name != newOrder[newOrder.length - 1]){
newOrder.splice(index, 1);
newOrder.push(name);
return this.setSeriesOrder(newOrder); // dojox.charting.Chart2D
}
}
return this; // dojox.charting.Chart2D
},
resize: function(width, height){
// summary:
// Resize the chart to the dimensions of width and height.
// width: Number
// The new width of the chart.
// height: Number
// The new height of the chart.
// returns: dojox.charting.Chart2D
// A reference to the current chart for functional chaining.
var box;
switch(arguments.length){
case 0:
box = dojo.marginBox(this.node);
break;
case 1:
box = width;
break;
default:
box = { w: width, h: height };
break;
}
dojo.marginBox(this.node, box);
this.surface.setDimensions(box.w, box.h);
this.dirty = true;
this.coords = null;
return this.render(); // dojox.charting.Chart2D
},
getGeometry: function(){
// summary:
// Returns a map of information about all axes in a chart and what they represent
// in terms of scaling (see dojox.charting.axis2d.Default.getScaler).
// returns: Object
// An map of geometry objects, a one-to-one mapping of axes.
var ret = {};
df.forIn(this.axes, function(axis){
if(axis.initialized()){
ret[axis.name] = {
name: axis.name,
vertical: axis.vertical,
scaler: axis.scaler,
ticks: axis.ticks
};
}
});
return ret; // Object
},
setAxisWindow: function(name, scale, offset, zoom){
// summary:
// Zooms an axis and all dependent plots. Can be used to zoom in 1D.
// name: String
// The name of the axis as defined by addAxis.
// scale: Number
// The scale on the target axis.
// offset: Number
// Any offest, as measured by axis tick
// zoom: Boolean|Object?
// The chart zooming animation trigger. This is null by default,
// e.g. {duration: 1200}, or just set true.
// returns: dojox.charting.Chart2D
// A reference to the current chart for functional chaining.
var axis = this.axes[name];
if(axis){
axis.setWindow(scale, offset);
dojo.forEach(this.stack,function(plot){
if(plot.hAxis == name || plot.vAxis == name){
plot.zoom = zoom;
}
})
}
return this; // dojox.charting.Chart2D
},
setWindow: function(sx, sy, dx, dy, zoom){
// summary:
// Zooms in or out any plots in two dimensions.
// sx: Number
// The scale for the x axis.
// sy: Number
// The scale for the y axis.
// dx: Number
// The pixel offset on the x axis.
// dy: Number
// The pixel offset on the y axis.
// zoom: Boolean|Object?
// The chart zooming animation trigger. This is null by default,
// e.g. {duration: 1200}, or just set true.
// returns: dojox.charting.Chart2D
// A reference to the current chart for functional chaining.
if(!("plotArea" in this)){
this.calculateGeometry();
}
df.forIn(this.axes, function(axis){
var scale, offset, bounds = axis.getScaler().bounds,
s = bounds.span / (bounds.upper - bounds.lower);
if(axis.vertical){
scale = sy;
offset = dy / s / scale;
}else{
scale = sx;
offset = dx / s / scale;
}
axis.setWindow(scale, offset);
});
dojo.forEach(this.stack, function(plot){ plot.zoom = zoom; });
return this; // dojox.charting.Chart2D
},
zoomIn: function(name, range){
// summary:
// Zoom the chart to a specific range on one axis. This calls render()
// directly as a convenience method.
// name: String
// The name of the axis as defined by addAxis.
// range: Array
// The end points of the zoom range, measured in axis ticks.
var axis = this.axes[name];
if(axis){
var scale, offset, bounds = axis.getScaler().bounds;
var lower = Math.min(range[0],range[1]);
var upper = Math.max(range[0],range[1]);
lower = range[0] < bounds.lower ? bounds.lower : lower;
upper = range[1] > bounds.upper ? bounds.upper : upper;
scale = (bounds.upper - bounds.lower) / (upper - lower);
offset = lower - bounds.lower;
this.setAxisWindow(name, scale, offset);
this.render();
}
},
calculateGeometry: function(){
// summary:
// Calculate the geometry of the chart based on the defined axes of
// a chart.
// returns: dojox.charting.Chart2D
// A reference to the current chart for functional chaining.
if(this.dirty){
return this.fullGeometry();
}
// calculate geometry
var dirty = dojo.filter(this.stack, function(plot){
return plot.dirty ||
(plot.hAxis && this.axes[plot.hAxis].dirty) ||
(plot.vAxis && this.axes[plot.vAxis].dirty);
}, this);
calculateAxes(dirty, this.plotArea);
return this; // dojox.charting.Chart2D
},
fullGeometry: function(){
// summary:
// Calculate the full geometry of the chart. This includes passing
// over all major elements of a chart (plots, axes, series, container)
// in order to ensure proper rendering.
// returns: dojox.charting.Chart2D
// A reference to the current chart for functional chaining.
this._makeDirty();
// clear old values
dojo.forEach(this.stack, clear);
// rebuild new connections, and add defaults
// set up a theme
if(!this.theme){
this.setTheme(new dojox.charting.Theme(dojox.charting._def));
}
// assign series
dojo.forEach(this.series, function(run){
if(!(run.plot in this.plots)){
var plot = new dc.plot2d.Default(this, {});
plot.name = run.plot;
this.plots[run.plot] = this.stack.length;
this.stack.push(plot);
}
this.stack[this.plots[run.plot]].addSeries(run);
}, this);
// assign axes
dojo.forEach(this.stack, function(plot){
if(plot.hAxis){
plot.setAxis(this.axes[plot.hAxis]);
}
if(plot.vAxis){
plot.setAxis(this.axes[plot.vAxis]);
}
}, this);
// calculate geometry
// 1st pass
var dim = this.dim = this.surface.getDimensions();
dim.width = g.normalizedLength(dim.width);
dim.height = g.normalizedLength(dim.height);
df.forIn(this.axes, clear);
calculateAxes(this.stack, dim);
// assumption: we don't have stacked axes yet
var offsets = this.offsets = { l: 0, r: 0, t: 0, b: 0 };
df.forIn(this.axes, function(axis){
df.forIn(axis.getOffsets(), function(o, i){ offsets[i] += o; });
});
// add title area
if(this.title){
this.titleGap = (this.titleGap==0) ? 0 : this.titleGap || this.theme.chart.titleGap || 20;
this.titlePos = this.titlePos || this.theme.chart.titlePos || "top";
this.titleFont = this.titleFont || this.theme.chart.titleFont;
this.titleFontColor = this.titleFontColor || this.theme.chart.titleFontColor || "black";
var tsize = g.normalizedLength(g.splitFontString(this.titleFont).size);
offsets[this.titlePos=="top" ? "t":"b"] += (tsize + this.titleGap);
}
// add margins
df.forIn(this.margins, function(o, i){ offsets[i] += o; });
// 2nd pass with realistic dimensions
this.plotArea = {
width: dim.width - offsets.l - offsets.r,
height: dim.height - offsets.t - offsets.b
};
df.forIn(this.axes, clear);
calculateAxes(this.stack, this.plotArea);
return this; // dojox.charting.Chart2D
},
render: function(){
// summary:
// Render the chart according to the current information defined. This should
// be the last call made when defining/creating a chart, or if data within the
// chart has been changed.
// returns: dojox.charting.Chart2D
// A reference to the current chart for functional chaining.
if(this.theme){
this.theme.clear();
}
if(this.dirty){
return this.fullRender();
}
this.calculateGeometry();
// go over the stack backwards
df.forEachRev(this.stack, function(plot){ plot.render(this.dim, this.offsets); }, this);
// go over axes
df.forIn(this.axes, function(axis){ axis.render(this.dim, this.offsets); }, this);
this._makeClean();
// BEGIN FOR HTML CANVAS
if(this.surface.render){ this.surface.render(); };
// END FOR HTML CANVAS
return this; // dojox.charting.Chart2D
},
fullRender: function(){
// summary:
// Force a full rendering of the chart, including full resets on the chart itself.
// You should not call this method directly unless absolutely necessary.
// returns: dojox.charting.Chart2D
// A reference to the current chart for functional chaining.
// calculate geometry
this.fullGeometry();
var offsets = this.offsets, dim = this.dim;
// get required colors
//var requiredColors = df.foldl(this.stack, "z + plot.getRequiredColors()", 0);
//this.theme.defineColors({num: requiredColors, cache: false});
// clear old shapes
dojo.forEach(this.series, purge);
df.forIn(this.axes, purge);
dojo.forEach(this.stack, purge);
//if it's HTML title
dojo.destroy(this.chartTitle);
this.surface.clear();
// generate shapes
// draw a plot background
var t = this.theme,
fill = t.plotarea && t.plotarea.fill,
stroke = t.plotarea && t.plotarea.stroke;
if(fill){
this.surface.createRect({
x: offsets.l - 1, y: offsets.t - 1,
width: dim.width - offsets.l - offsets.r + 2,
height: dim.height - offsets.t - offsets.b + 2
}).setFill(fill);
}
if(stroke){
this.surface.createRect({
x: offsets.l, y: offsets.t,
width: dim.width - offsets.l - offsets.r + 1,
height: dim.height - offsets.t - offsets.b + 1
}).setStroke(stroke);
}
// go over the stack backwards
df.foldr(this.stack, function(z, plot){ return plot.render(dim, offsets), 0; }, 0);
// pseudo-clipping: matting
fill = this.fill !== undefined ? this.fill : (t.chart && t.chart.fill);
stroke = this.stroke !== undefined ? this.stroke : (t.chart && t.chart.stroke);
// TRT: support for "inherit" as a named value in a theme.
if(fill == "inherit"){
// find the background color of the nearest ancestor node, and use that explicitly.
var node = this.node, fill = new dojo.Color(dojo.style(node, "backgroundColor"));
while(fill.a==0 && node!=document.documentElement){
fill = new dojo.Color(dojo.style(node, "backgroundColor"));
node = node.parentNode;
}
}
if(fill){
if(offsets.l){ // left
this.surface.createRect({
width: offsets.l,
height: dim.height + 1
}).setFill(fill);
}
if(offsets.r){ // right
this.surface.createRect({
x: dim.width - offsets.r,
width: offsets.r + 1,
height: dim.height + 2
}).setFill(fill);
}
if(offsets.t){ // top
this.surface.createRect({
width: dim.width + 1,
height: offsets.t
}).setFill(fill);
}
if(offsets.b){ // bottom
this.surface.createRect({
y: dim.height - offsets.b,
width: dim.width + 1,
height: offsets.b + 2
}).setFill(fill);
}
}
//create title: Whether to make chart title as a widget which extends dojox.charting.Element?
if(this.title){
var forceHtmlLabels = (g.renderer == "canvas"),
labelType = forceHtmlLabels || !dojo.isIE && !dojo.isOpera ? "html" : "gfx",
tsize = g.normalizedLength(g.splitFontString(this.titleFont).size);
this.chartTitle = dc.axis2d.common.createText[labelType](
this,
this.surface,
dim.width/2,
this.titlePos=="top" ? tsize + this.margins.t : dim.height - this.margins.b,
"middle",
this.title,
this.titleFont,
this.titleFontColor
);
}
if(stroke){
this.surface.createRect({
width: dim.width - 1,
height: dim.height - 1
}).setStroke(stroke);
}
// go over axes
df.forIn(this.axes, function(axis){ axis.render(dim, offsets); });
this._makeClean();
// BEGIN FOR HTML CANVAS
if(this.surface.render){ this.surface.render(); };
// END FOR HTML CANVAS
return this; // dojox.charting.Chart2D
},
delayedRender: function(){
// summary:
// Delayed render, which is used to collect multiple updates
// within a delayInMs time window.
// returns: dojox.charting.Chart2D
// A reference to the current chart for functional chaining.
if(!this._delayedRenderHandle){
this._delayedRenderHandle = setTimeout(
dojo.hitch(this, function(){
clearTimeout(this._delayedRenderHandle);
this._delayedRenderHandle = null;
this.render();
}),
this.delayInMs
);
}
return this; // dojox.charting.Chart2D
},
connectToPlot: function(name, object, method){
// summary:
// A convenience method to connect a function to a plot.
// name: String
// The name of the plot as defined by addPlot.
// object: Object
// The object to be connected.
// method: Function
// The function to be executed.
// returns: Array
// A handle to the connection, as defined by dojo.connect (see dojo.connect).
return name in this.plots ? this.stack[this.plots[name]].connect(object, method) : null; // Array
},
fireEvent: function(seriesName, eventName, index){
// summary:
// Fires a synthetic event for a series item.
// seriesName: String:
// Series name.
// eventName: String:
// Event name to simulate: onmouseover, onmouseout, onclick.
// index: Number:
// Valid data value index for the event.
// returns: dojox.charting.Chart2D
// A reference to the current chart for functional chaining.
if(seriesName in this.runs){
var plotName = this.series[this.runs[seriesName]].plot;
if(plotName in this.plots){
var plot = this.stack[this.plots[plotName]];
if(plot){
plot.fireEvent(seriesName, eventName, index);
}
}
}
return this; // dojox.charting.Chart2D
},
_makeClean: function(){
// reset dirty flags
dojo.forEach(this.axes, makeClean);
dojo.forEach(this.stack, makeClean);
dojo.forEach(this.series, makeClean);
this.dirty = false;
},
_makeDirty: function(){
// reset dirty flags
dojo.forEach(this.axes, makeDirty);
dojo.forEach(this.stack, makeDirty);
dojo.forEach(this.series, makeDirty);
this.dirty = true;
},
_invalidateDependentPlots: function(plotName, /* Boolean */ verticalAxis){
if(plotName in this.plots){
var plot = this.stack[this.plots[plotName]], axis,
axisName = verticalAxis ? "vAxis" : "hAxis";
if(plot[axisName]){
axis = this.axes[plot[axisName]];
if(axis && axis.dependOnData()){
axis.dirty = true;
// find all plots and mark them dirty
dojo.forEach(this.stack, function(p){
if(p[axisName] && p[axisName] == plot[axisName]){
p.dirty = true;
}
});
}
}else{
plot.dirty = true;
}
}
}
});
function hSection(stats){
return {min: stats.hmin, max: stats.hmax};
}
function vSection(stats){
return {min: stats.vmin, max: stats.vmax};
}
function hReplace(stats, h){
stats.hmin = h.min;
stats.hmax = h.max;
}
function vReplace(stats, v){
stats.vmin = v.min;
stats.vmax = v.max;
}
function combineStats(target, source){
if(target && source){
target.min = Math.min(target.min, source.min);
target.max = Math.max(target.max, source.max);
}
return target || source;
}
function calculateAxes(stack, plotArea){
var plots = {}, axes = {};
dojo.forEach(stack, function(plot){
var stats = plots[plot.name] = plot.getSeriesStats();
if(plot.hAxis){
axes[plot.hAxis] = combineStats(axes[plot.hAxis], hSection(stats));
}
if(plot.vAxis){
axes[plot.vAxis] = combineStats(axes[plot.vAxis], vSection(stats));
}
});
dojo.forEach(stack, function(plot){
var stats = plots[plot.name];
if(plot.hAxis){
hReplace(stats, axes[plot.hAxis]);
}
if(plot.vAxis){
vReplace(stats, axes[plot.vAxis]);
}
plot.initializeScalers(plotArea, stats);
});
}
})();
|
Charting: remove plot with all its series, thx yoavrubin!, !strict, fixes #12093.
|
Chart2D.js
|
Charting: remove plot with all its series, thx yoavrubin!, !strict, fixes #12093.
|
<ide><path>hart2D.js
<ide> plots[name] = idx - 1;
<ide> }
<ide> });
<add> // remove all related series
<add> var ns = dojo.filter(this.series, function(run){ return run.plot != name; });
<add> if(ns.length < this.series.length){
<add> // kill all removed series
<add> dojo.forEach(this.series, function(run){
<add> if(run.plot == name){
<add> run.destroy();
<add> }
<add> });
<add> // rebuild all necessary data structures
<add> this.runs = {};
<add> dojo.forEach(ns, function(run, index){
<add> this.runs[run.plot] = index;
<add> }, this);
<add> this.series = ns;
<add> }
<ide> // mark the chart as dirty
<ide> this.dirty = true;
<ide> }
<ide> // A reference to the current chart for functional chaining.
<ide> if(name in this.runs){
<ide> // get the index and remove the name
<del> var index = this.runs[name],
<del> plotName = this.series[index].plot;
<add> var index = this.runs[name];
<ide> delete this.runs[name];
<ide> // destroy the run
<ide> this.series[index].destroy();
|
|
Java
|
mit
|
789841da97bf7c47d06bc9b6f8601cf7b1e9694b
| 0 |
jenkinsci/radargun-plugin,vjuranek/radargun-plugin,vjuranek/radargun-plugin,jenkinsci/radargun-plugin,jenkinsci/radargun-plugin,vjuranek/radargun-plugin
|
package org.jenkinsci.plugins.radargun;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.jenkinsci.plugins.radargun.config.NodeConfigSource;
import org.jenkinsci.plugins.radargun.config.RadarGunInstallationWrapper;
import org.jenkinsci.plugins.radargun.config.RadarGunInstance;
import org.jenkinsci.plugins.radargun.config.ScenarioSource;
import org.jenkinsci.plugins.radargun.config.ScriptSource;
import org.jenkinsci.plugins.radargun.model.RgMasterProcess;
import org.jenkinsci.plugins.radargun.model.RgProcess;
import org.jenkinsci.plugins.radargun.model.impl.Node;
import org.jenkinsci.plugins.radargun.model.impl.NodeList;
import org.jenkinsci.plugins.radargun.model.impl.RgMasterProcessImpl;
import org.jenkinsci.plugins.radargun.model.impl.RgSlaveProcessImpl;
import org.jenkinsci.plugins.radargun.util.ConsoleLogger;
import org.jenkinsci.plugins.radargun.util.Functions;
import org.jenkinsci.plugins.radargun.util.Resolver;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.StaplerRequest;
import hudson.AbortException;
import hudson.DescriptorExtensionList;
import hudson.Extension;
import hudson.Launcher;
import hudson.Util;
import hudson.model.AbstractBuild;
import hudson.model.AbstractProject;
import hudson.model.BuildListener;
import hudson.model.Descriptor;
import hudson.tasks.BuildStepDescriptor;
import hudson.tasks.Builder;
import hudson.util.ListBoxModel;
import net.sf.json.JSONObject;
public class RadarGunBuilder extends Builder {
private static Logger LOGGER = Logger.getLogger(RadarGunBuilder.class.getName());
private String radarGunName;
private RadarGunInstance radarGunInstance;
private final ScenarioSource scenarioSource;
private final NodeConfigSource nodeSource;
private final ScriptSource scriptSource;
private String remoteLoginProgram; //cannot be final as we re-assign it in readResolve() it it's null for backward compatibility reasons
private final String remoteLogin;
private final String workspacePath;
private final String pluginPath;
private final String pluginConfigPath;
private final String reporterPath;
@DataBoundConstructor
public RadarGunBuilder(RadarGunInstance radarGunInstance, ScenarioSource scenarioSource, NodeConfigSource nodeSource,
ScriptSource scriptSource, String remoteLoginProgram, String remoteLogin, String workspacePath, String pluginPath, String pluginConfigPath,
String reporterPath) {
this.radarGunInstance = radarGunInstance;
this.scenarioSource = scenarioSource;
this.nodeSource = nodeSource;
this.scriptSource = scriptSource;
this.remoteLoginProgram = remoteLoginProgram;
this.remoteLogin = remoteLogin;
this.workspacePath = Util.fixEmpty(workspacePath);
this.pluginPath = pluginPath;
this.pluginConfigPath = pluginConfigPath;
this.reporterPath = reporterPath;
}
/**
* For keeping backward compatibility defaults in ssh as a remote login program and converts RG name into RG installation wrapper
*/
public RadarGunBuilder readResolve() {
if ((radarGunInstance == null) && (radarGunName != null)) {
radarGunInstance = new RadarGunInstallationWrapper(radarGunName);
radarGunName = null;
}
if (this.remoteLoginProgram == null) {
this.remoteLoginProgram = RemoteLoginProgram.SSH.getName().toUpperCase();
}
return this;
}
public RadarGunInstance getRadarGunInstance() {
return radarGunInstance;
}
public ScenarioSource getScenarioSource() {
return scenarioSource;
}
public NodeConfigSource getNodeSource() {
return nodeSource;
}
public ScriptSource getScriptSource() {
return scriptSource;
}
public String getRemoteLoginProgram() {
return remoteLoginProgram;
}
public String getRemoteLogin() {
return remoteLogin;
}
public String getWorkspacePath() {
return workspacePath;
}
public String getPluginPath() {
return pluginPath;
}
public String getPluginConfigPath() {
return pluginConfigPath;
}
public String getReporterPath() {
return reporterPath;
}
@Override
public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener)
throws InterruptedException, IOException {
Resolver.init(build);
ConsoleLogger console = new ConsoleLogger(listener);
RadarGunInstallation rgInstall = Functions.getRgInstallation(radarGunInstance);
build.addAction(new RadarGunInvisibleAction(rgInstall.getHome()));
NodeList nodes = nodeSource.getNodesList(launcher.getChannel());
//check deprecated options
console.logAnnot("[RadarGun] WARN: As of RG plugin release 1.3, \"Start script\" config will be replaced by \"Remote login program\" "
+ "options with limited config. options. Please make sure you don't use anything special in your start scripts (besides launching "
+ "the RG master/slaves). If so, please move it into \"Node list\" section, where you can use \"beforeCmds:\" to execute "
+ "custom commands on remote machines.");
Functions.checkDeprecatedConfigs(nodes, console);
RgBuild rgBuild = new RgBuild(this, build, launcher, nodes, rgInstall);
List<RgProcess> rgProcesses = null;
ExecutorService executorService = null;
try {
rgProcesses = prepareRgProcesses(rgBuild);
executorService = Executors.newFixedThreadPool(rgProcesses.size());
for (RgProcess process : rgProcesses) {
process.start(executorService);
}
return waitForRgMaster(rgProcesses.get(0));
} catch (Exception e) {
console.logAnnot("[RadarGun] ERROR: something went wrong, caught exception: " + e.getMessage());
e.printStackTrace(console.getLogger());
return false;
} finally {
cleanup(rgProcesses, executorService);
}
}
private List<RgProcess> prepareRgProcesses(RgBuild rgBuild) {
List<RgProcess> rgProcesses = new ArrayList<RgProcess>(rgBuild.getNodes().getNodeCount());
rgProcesses.add(new RgMasterProcessImpl(rgBuild));
List<Node> slaves = rgBuild.getNodes().getSlaves();
for (int i = 0; i < slaves.size(); i++) {
rgProcesses.add(new RgSlaveProcessImpl(rgBuild, i));
}
return rgProcesses;
}
private boolean waitForRgMaster(RgProcess masterProc) throws AbortException {
boolean isSuccess = false;
try {
// wait for master process to be finished, failure of the slave process should be detected by RG master
isSuccess = masterProc.waitForResult() == 0;
} catch (InterruptedException e) {
//TODO actually shouln't fail the build but set it to canceled
LOGGER.log(Level.INFO, "Stopping the build - build interrupted", e);
//throw new AbortException(e.getMessage());
} catch (ExecutionException e) {
LOGGER.log(Level.INFO, "Failing the build - getting master result has failed", e);
throw new AbortException(e.getMessage());
}
return isSuccess;
}
private void cleanup(List<RgProcess> rgProcesses, ExecutorService executorService) {
if (executorService != null) {
List<Runnable> notStarted = executorService.shutdownNow();
LOGGER.log(Level.FINE, "Number of tasks that weren't started: " + notStarted.size());
}
try {
scriptSource.cleanup();
scenarioSource.cleanup();
} catch (Exception e) {
LOGGER.log(Level.WARNING, "Removing temporal files failed", e);
}
if (rgProcesses != null) {
try {
((RgMasterProcess)rgProcesses.get(0)).kill();
} catch(Exception e) {
LOGGER.log(Level.WARNING, "Killing RG master failed", e);
}
}
}
@Override
public DescriptorImpl getDescriptor() {
return (DescriptorImpl) super.getDescriptor();
}
@Extension
public static final class DescriptorImpl extends BuildStepDescriptor<Builder> {
private volatile List<RadarGunInstallation> installations = new ArrayList<>();
public DescriptorImpl() {
load();
}
public List<RadarGunInstallation> getInstallations() {
return installations;
}
public List<RadarGunInstallationWrapper> getInstallationWrappers() {
List<RadarGunInstallationWrapper> wrappers = new ArrayList<>();
for (RadarGunInstallation inst : installations) {
wrappers.add(new RadarGunInstallationWrapper(inst.getName()));
}
return wrappers;
}
public void setInstallations(RadarGunInstallation... installations) {
List<RadarGunInstallation> installs = new ArrayList<>();
for (RadarGunInstallation installation : installations) {
installs.add(installation);
}
this.installations = installs;
save();
}
public RadarGunInstallation getInstallation(String installationName) {
if (installationName == null || installationName.isEmpty())
return null;
for (RadarGunInstallation i : installations) {
if (i.getName().equals(installationName))
return i;
}
return null;
}
@Override
public boolean isApplicable(Class<? extends AbstractProject> aClass) {
return true;
}
public String getDisplayName() {
return "Run RadarGun";
}
@Override
public boolean configure(StaplerRequest req, JSONObject formData) throws FormException {
req.bindJSON(this, formData);
save();
return super.configure(req, formData);
}
public ListBoxModel doFillRadarGunNameItems() {
ListBoxModel lb = new ListBoxModel();
for (RadarGunInstallation rgi : installations) {
lb.add(rgi.getName(), rgi.getName());
}
return lb;
}
public static DescriptorExtensionList<RadarGunInstance, Descriptor<RadarGunInstance>> getRgInstances() {
return RadarGunInstance.all();
}
public static DescriptorExtensionList<ScenarioSource, Descriptor<ScenarioSource>> getScenarioSources() {
return ScenarioSource.all();
}
public static DescriptorExtensionList<NodeConfigSource, Descriptor<NodeConfigSource>> getNodeSources() {
return NodeConfigSource.all();
}
public static ListBoxModel doFillRemoteLoginProgramItems() {
ListBoxModel lb = new ListBoxModel();
for (RemoteLoginProgram remote : RemoteLoginProgram.values()) {
lb.add(remote.getName(), remote.getName().toUpperCase());
}
return lb;
}
public static DescriptorExtensionList<ScriptSource, Descriptor<ScriptSource>> getScriptSources() {
return ScriptSource.all();
}
}
}
|
src/main/java/org/jenkinsci/plugins/radargun/RadarGunBuilder.java
|
package org.jenkinsci.plugins.radargun;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.jenkinsci.plugins.radargun.config.NodeConfigSource;
import org.jenkinsci.plugins.radargun.config.RadarGunInstallationWrapper;
import org.jenkinsci.plugins.radargun.config.RadarGunInstance;
import org.jenkinsci.plugins.radargun.config.ScenarioSource;
import org.jenkinsci.plugins.radargun.config.ScriptSource;
import org.jenkinsci.plugins.radargun.model.RgMasterProcess;
import org.jenkinsci.plugins.radargun.model.RgProcess;
import org.jenkinsci.plugins.radargun.model.impl.Node;
import org.jenkinsci.plugins.radargun.model.impl.NodeList;
import org.jenkinsci.plugins.radargun.model.impl.RgMasterProcessImpl;
import org.jenkinsci.plugins.radargun.model.impl.RgSlaveProcessImpl;
import org.jenkinsci.plugins.radargun.util.ConsoleLogger;
import org.jenkinsci.plugins.radargun.util.Functions;
import org.jenkinsci.plugins.radargun.util.Resolver;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.StaplerRequest;
import hudson.AbortException;
import hudson.DescriptorExtensionList;
import hudson.Extension;
import hudson.Launcher;
import hudson.Util;
import hudson.model.AbstractBuild;
import hudson.model.AbstractProject;
import hudson.model.BuildListener;
import hudson.model.Descriptor;
import hudson.tasks.BuildStepDescriptor;
import hudson.tasks.Builder;
import hudson.util.ListBoxModel;
import net.sf.json.JSONObject;
public class RadarGunBuilder extends Builder {
private static Logger LOGGER = Logger.getLogger(RadarGunBuilder.class.getName());
private String radarGunName;
private RadarGunInstance radarGunInstance;
private final ScenarioSource scenarioSource;
private final NodeConfigSource nodeSource;
private final ScriptSource scriptSource;
private String remoteLoginProgram; //cannot be final as we re-assign it in readResolve() it it's null for backward compatibility reasons
private final String remoteLogin;
private final String workspacePath;
private final String pluginPath;
private final String pluginConfigPath;
private final String reporterPath;
@DataBoundConstructor
public RadarGunBuilder(RadarGunInstance radarGunInstance, ScenarioSource scenarioSource, NodeConfigSource nodeSource,
ScriptSource scriptSource, String remoteLoginProgram, String remoteLogin, String workspacePath, String pluginPath, String pluginConfigPath,
String reporterPath) {
this.radarGunInstance = radarGunInstance;
this.scenarioSource = scenarioSource;
this.nodeSource = nodeSource;
this.scriptSource = scriptSource;
this.remoteLoginProgram = remoteLoginProgram;
this.remoteLogin = remoteLogin;
this.workspacePath = Util.fixEmpty(workspacePath);
this.pluginPath = pluginPath;
this.pluginConfigPath = pluginConfigPath;
this.reporterPath = reporterPath;
}
/**
* For keeping backward compatibility defaults in ssh as a remote login program and converts RG name into RG installation wrapper
*/
public RadarGunBuilder readResolve() {
if ((radarGunInstance == null) && (radarGunName != null)) {
radarGunInstance = new RadarGunInstallationWrapper(radarGunName);
radarGunName = null;
}
if (this.remoteLoginProgram == null) {
this.remoteLoginProgram = RemoteLoginProgram.SSH.getName().toUpperCase();
}
return this;
}
public RadarGunInstance getRadarGunInstance() {
return radarGunInstance;
}
public ScenarioSource getScenarioSource() {
return scenarioSource;
}
public NodeConfigSource getNodeSource() {
return nodeSource;
}
public ScriptSource getScriptSource() {
return scriptSource;
}
public String getRemoteLoginProgram() {
return remoteLoginProgram;
}
public String getRemoteLogin() {
return remoteLogin;
}
public String getWorkspacePath() {
return workspacePath;
}
public String getPluginPath() {
return pluginPath;
}
public String getPluginConfigPath() {
return pluginConfigPath;
}
public String getReporterPath() {
return reporterPath;
}
@Override
public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener)
throws InterruptedException, IOException {
Resolver.init(build);
ConsoleLogger console = new ConsoleLogger(listener);
RadarGunInstallation rgInstall = Functions.getRgInstallation(radarGunInstance);
build.addAction(new RadarGunInvisibleAction(rgInstall.getHome()));
NodeList nodes = nodeSource.getNodesList(launcher.getChannel());
//check deprecated options
console.logAnnot("[RadarGun] WARN: As of RG plugin release 1.3, \"Start script\" config will be replaced by \"Remote login program\" "
+ "options with limited config. options. Please make sure you don't use anything special in your start scripts (besides launching "
+ "the RG master/slaves). If so, please move it into \"Node list\" section, where you can use \"beforeCmds:\" to execute "
+ "custom commands on remote machines.");
Functions.checkDeprecatedConfigs(nodes, console);
RgBuild rgBuild = new RgBuild(this, build, launcher, nodes, rgInstall);
List<RgProcess> rgProcesses = null;
ExecutorService executorService = null;
try {
rgProcesses = prepareRgProcesses(rgBuild);
executorService = Executors.newFixedThreadPool(rgProcesses.size());
for (RgProcess process : rgProcesses) {
process.start(executorService);
}
return waitForRgMaster(rgProcesses.get(0));
} catch (Exception e) {
console.logAnnot("[RadarGun] ERROR: something went wrong, caught exception: " + e.getMessage());
e.printStackTrace(console.getLogger());
return false;
} finally {
cleanup(rgProcesses, executorService);
}
}
private List<RgProcess> prepareRgProcesses(RgBuild rgBuild) {
List<RgProcess> rgProcesses = new ArrayList<RgProcess>(rgBuild.getNodes().getNodeCount());
rgProcesses.add(new RgMasterProcessImpl(rgBuild));
List<Node> slaves = rgBuild.getNodes().getSlaves();
for (int i = 0; i < slaves.size(); i++) {
rgProcesses.add(new RgSlaveProcessImpl(rgBuild, i));
}
return rgProcesses;
}
private boolean waitForRgMaster(RgProcess masterProc) throws AbortException {
boolean isSuccess = false;
try {
// wait for master process to be finished, failure of the slave process should be detected by RG master
isSuccess = masterProc.waitForResult() == 0;
} catch (InterruptedException e) {
//TODO actually shouln't fail the build but set it to canceled
LOGGER.log(Level.INFO, "Stopping the build - build interrupted", e);
//throw new AbortException(e.getMessage());
} catch (ExecutionException e) {
LOGGER.log(Level.INFO, "Failing the build - getting master result has failed", e);
throw new AbortException(e.getMessage());
}
return isSuccess;
}
private void cleanup(List<RgProcess> rgProcesses, ExecutorService executorService) {
if (executorService != null) {
List<Runnable> notStarted = executorService.shutdownNow();
LOGGER.log(Level.FINE, "Number of tasks that weren't started: " + notStarted.size());
}
try {
scriptSource.cleanup();
scenarioSource.cleanup();
} catch (Exception e) {
LOGGER.log(Level.WARNING, "Removing temporal files failed", e);
}
if (rgProcesses != null) {
try {
((RgMasterProcess)rgProcesses.get(0)).kill();
} catch(Exception e) {
LOGGER.log(Level.WARNING, "Killing RG master failed", e);
}
}
}
@Override
public DescriptorImpl getDescriptor() {
return (DescriptorImpl) super.getDescriptor();
}
@Extension
public static final class DescriptorImpl extends BuildStepDescriptor<Builder> {
private volatile List<RadarGunInstallation> installations = new ArrayList<>();
public DescriptorImpl() {
load();
}
public List<RadarGunInstallation> getInstallations() {
return installations;
}
public List<RadarGunInstallationWrapper> getInstallationWrappers() {
List<RadarGunInstallationWrapper> wrappers = new ArrayList<>();
for (RadarGunInstallation inst : installations) {
wrappers.add(new RadarGunInstallationWrapper(inst.getName()));
}
return wrappers;
}
public void setInstallations(RadarGunInstallation... installations) {
List<RadarGunInstallation> installs = new ArrayList<>();
for (RadarGunInstallation installation : installations) {
installs.add(installation);
}
this.installations = installs;
}
public RadarGunInstallation getInstallation(String installationName) {
if (installationName == null || installationName.isEmpty())
return null;
for (RadarGunInstallation i : installations) {
if (i.getName().equals(installationName))
return i;
}
return null;
}
@Override
public boolean isApplicable(Class<? extends AbstractProject> aClass) {
return true;
}
public String getDisplayName() {
return "Run RadarGun";
}
@Override
public boolean configure(StaplerRequest req, JSONObject formData) throws FormException {
req.bindJSON(this, formData);
save();
return super.configure(req, formData);
}
public ListBoxModel doFillRadarGunNameItems() {
ListBoxModel lb = new ListBoxModel();
for (RadarGunInstallation rgi : installations) {
lb.add(rgi.getName(), rgi.getName());
}
return lb;
}
public static DescriptorExtensionList<RadarGunInstance, Descriptor<RadarGunInstance>> getRgInstances() {
return RadarGunInstance.all();
}
public static DescriptorExtensionList<ScenarioSource, Descriptor<ScenarioSource>> getScenarioSources() {
return ScenarioSource.all();
}
public static DescriptorExtensionList<NodeConfigSource, Descriptor<NodeConfigSource>> getNodeSources() {
return NodeConfigSource.all();
}
public static ListBoxModel doFillRemoteLoginProgramItems() {
ListBoxModel lb = new ListBoxModel();
for (RemoteLoginProgram remote : RemoteLoginProgram.values()) {
lb.add(remote.getName(), remote.getName().toUpperCase());
}
return lb;
}
public static DescriptorExtensionList<ScriptSource, Descriptor<ScriptSource>> getScriptSources() {
return ScriptSource.all();
}
}
}
|
#73 Save RG installs when doing some changes
|
src/main/java/org/jenkinsci/plugins/radargun/RadarGunBuilder.java
|
#73 Save RG installs when doing some changes
|
<ide><path>rc/main/java/org/jenkinsci/plugins/radargun/RadarGunBuilder.java
<ide> installs.add(installation);
<ide> }
<ide> this.installations = installs;
<add> save();
<ide> }
<ide>
<ide> public RadarGunInstallation getInstallation(String installationName) {
|
|
Java
|
mit
|
7997187d7ca1f8b180f6cd44c9186c10e5a44daf
| 0 |
mfullen/cryptography_course,mfullen/cryptography_course
|
package com.mfullen.homework1;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Hex;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
/**
*
* @author mfullen
*/
public class AppTest
{
public static final String INVALID_CHAR = ".";
private String[] cipherTexts;
private String targetCipher;
private static final String UTF8 = "UTF-8";
@Before
public void setUp()
{
this.targetCipher = "32510ba9babebbbefd001547a810e67149caee11d945cd7fc81a05e9f85aac650e9052ba6a8cd8257bf14d13e6f0a803b54fde9e77472dbff89d71b57bddef121336cb85ccb8f3315f4b52e301d16e9f52f904";
String[] texts =
{
"315c4eeaa8b5f8aaf9174145bf43e1784b8fa00dc71d885a804e5ee9fa40b16349c146fb778cdf2d3aff021dfff5b403b510d0d0455468aeb98622b137dae857553ccd8883a7bc37520e06e515d22c954eba5025b8cc57ee59418ce7dc6bc41556bdb36bbca3e8774301fbcaa3b83b220809560987815f65286764703de0f3d524400a19b159610b11ef3e",
"234c02ecbbfbafa3ed18510abd11fa724fcda2018a1a8342cf064bbde548b12b07df44ba7191d9606ef4081ffde5ad46a5069d9f7f543bedb9c861bf29c7e205132eda9382b0bc2c5c4b45f919cf3a9f1cb74151f6d551f4480c82b2cb24cc5b028aa76eb7b4ab24171ab3cdadb8356f",
"32510ba9a7b2bba9b8005d43a304b5714cc0bb0c8a34884dd91304b8ad40b62b07df44ba6e9d8a2368e51d04e0e7b207b70b9b8261112bacb6c866a232dfe257527dc29398f5f3251a0d47e503c66e935de81230b59b7afb5f41afa8d661cb",
"32510ba9aab2a8a4fd06414fb517b5605cc0aa0dc91a8908c2064ba8ad5ea06a029056f47a8ad3306ef5021eafe1ac01a81197847a5c68a1b78769a37bc8f4575432c198ccb4ef63590256e305cd3a9544ee4160ead45aef520489e7da7d835402bca670bda8eb775200b8dabbba246b130f040d8ec6447e2c767f3d30ed81ea2e4c1404e1315a1010e7229be6636aaa",
"3f561ba9adb4b6ebec54424ba317b564418fac0dd35f8c08d31a1fe9e24fe56808c213f17c81d9607cee021dafe1e001b21ade877a5e68bea88d61b93ac5ee0d562e8e9582f5ef375f0a4ae20ed86e935de81230b59b73fb4302cd95d770c65b40aaa065f2a5e33a5a0bb5dcaba43722130f042f8ec85b7c2070",
"32510bfbacfbb9befd54415da243e1695ecabd58c519cd4bd2061bbde24eb76a19d84aba34d8de287be84d07e7e9a30ee714979c7e1123a8bd9822a33ecaf512472e8e8f8db3f9635c1949e640c621854eba0d79eccf52ff111284b4cc61d11902aebc66f2b2e436434eacc0aba938220b084800c2ca4e693522643573b2c4ce35050b0cf774201f0fe52ac9f26d71b6cf61a711cc229f77ace7aa88a2f19983122b11be87a59c355d25f8e4",
"32510bfbacfbb9befd54415da243e1695ecabd58c519cd4bd90f1fa6ea5ba47b01c909ba7696cf606ef40c04afe1ac0aa8148dd066592ded9f8774b529c7ea125d298e8883f5e9305f4b44f915cb2bd05af51373fd9b4af511039fa2d96f83414aaaf261bda2e97b170fb5cce2a53e675c154c0d9681596934777e2275b381ce2e40582afe67650b13e72287ff2270abcf73bb028932836fbdecfecee0a3b894473c1bbeb6b4913a536ce4f9b13f1efff71ea313c8661dd9a4ce",
"315c4eeaa8b5f8bffd11155ea506b56041c6a00c8a08854dd21a4bbde54ce56801d943ba708b8a3574f40c00fff9e00fa1439fd0654327a3bfc860b92f89ee04132ecb9298f5fd2d5e4b45e40ecc3b9d59e9417df7c95bba410e9aa2ca24c5474da2f276baa3ac325918b2daada43d6712150441c2e04f6565517f317da9d3",
"271946f9bbb2aeadec111841a81abc300ecaa01bd8069d5cc91005e9fe4aad6e04d513e96d99de2569bc5e50eeeca709b50a8a987f4264edb6896fb537d0a716132ddc938fb0f836480e06ed0fcd6e9759f40462f9cf57f4564186a2c1778f1543efa270bda5e933421cbe88a4a52222190f471e9bd15f652b653b7071aec59a2705081ffe72651d08f822c9ed6d76e48b63ab15d0208573a7eef027",
"466d06ece998b7a2fb1d464fed2ced7641ddaa3cc31c9941cf110abbf409ed39598005b3399ccfafb61d0315fca0a314be138a9f32503bedac8067f03adbf3575c3b8edc9ba7f537530541ab0f9f3cd04ff50d66f1d559ba520e89a2cb2a83"
};
this.cipherTexts = texts;
}
public String toHex(String arg)
{
try
{
return String.format("%02x", new BigInteger(1, arg.getBytes(UTF8)));
}
catch (UnsupportedEncodingException ex)
{
Logger.getLogger(AppTest.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
/**
* Xors 2 hex strings
*
* @param x
* @param y
* @return
*/
public String xor(String x, String y)
{
String xor = null;
try
{
BigInteger x1 = new BigInteger(x, 16);
BigInteger y1 = new BigInteger(y, 16);
BigInteger bigIntegerXor = x1.xor(y1);
xor = Hex.encodeHexString(bigIntegerXor.toByteArray());
}
catch (Exception e)
{
}
return xor;
}
public String xor2(String x, String y)
{
String xor = null;
try
{
BigInteger x1 = new BigInteger(x, 16);
BigInteger y1 = new BigInteger(y, 16);
BigInteger bigIntegerXor = x1.xor(y1);
xor = Hex.encodeHexString(bigIntegerXor.toByteArray());
xor = bigIntegerXor.toString(16);
}
catch (Exception e)
{
}
return xor;
}
public String xorHex(String a, String b)
{
int length = a.length() > b.length() ? b.length() : a.length();
char[] chars = new char[length];
for (int i = 0; i < chars.length; i++)
{
chars[i] = toHex(fromHex(a.charAt(i)) ^ fromHex(b.charAt(i)));
}
return new String(chars);
}
private static int fromHex(char c)
{
if (c >= '0' && c <= '9')
{
return c - '0';
}
if (c >= 'A' && c <= 'F')
{
return c - 'A' + 10;
}
if (c >= 'a' && c <= 'f')
{
return c - 'a' + 10;
}
throw new IllegalArgumentException();
}
private char toHex(int nybble)
{
if (nybble < 0 || nybble > 15)
{
throw new IllegalArgumentException();
}
return "0123456789ABCDEF".toLowerCase().charAt(nybble);
}
public boolean isValidAscii(char c)
{
if (c > 122)
{
return false;
}
if (c < 32 && c != 10)
{
return false;
}
if (c > 32 && c < 48)
{
return false;
}
return true;
}
public String filterAscii(String string)
{
StringBuilder output = new StringBuilder();
for (int i = 0; i < string.length(); i++)
{
char c = string.charAt(i);
if (isValidAscii(c))
{
output.append(c);
}
else
{
output.append(INVALID_CHAR);
}
}
return output.toString();
}
public String hexToAscii(String hex)
{
try
{
byte[] decodeHex = Hex.decodeHex(hex.toCharArray());
String string = new String(decodeHex, UTF8);
return filterAscii(string);
}
catch (Exception e)
{
//System.out.println("Error, returning : ");
//e.printStackTrace();
int x = 0;
}
return INVALID_CHAR;
}
/**
* Test of main method, of class App.
*/
@Test
public void testHelperMethods()
{
final String crib = "the";
String cribHex = toHex(crib);
String c1 = "3b101c091d53320c000910";
String c2 = "071d154502010a04000419";
String xor = xorHex(c1, c2);
assertEquals("746865", cribHex);
assertEquals("3c0d094c1f523808000d09", xor);
String xor1 = xorHex(xor, cribHex);
assertEquals("48656c", xor1);
assertEquals("Hel", hexToAscii(xor1));
assertEquals("48656c6c6f", toHex("Hello"));
String xor2 = xorHex("3c0d094c1f", toHex("Hello"));
assertEquals("the p", hexToAscii(xor2));
// {
// String xor3 = xor("c0d094c1f5", toHex("Hello"));
// assertEquals("the p", hexToAscii(xor3));
// }
// {
// String xor3 = xor("0d094c1f52", toHex("Hello"));
// assertEquals("the p", hexToAscii(xor3));
// }
// {
// String xor3 = xor("523808000d", toHex("Hello"));
// assertEquals("the p", hexToAscii(xor3));
// }
{
String xor3 = xor(xor, toHex("the program"));
assertEquals("Hello World", hexToAscii(xor3));
}
}
@Test
public void testHelperMethods2()
{
final String crib = "the";
String cribHex = toHex(crib);
String c1 = "3b101c091d53320c000910";
String c2 = "071d154502010a04000419";
String key = toHex("supersecret");
assertEquals("7375706572736563726574", key);
String c3 = xorHex(toHex("the mike"), key);
System.out.println("C3:" + c3);
String xor = xorHex(c1, c2);
assertEquals("746865", cribHex);
assertEquals("3c0d094c1f523808000d09", xor);
String xor1 = xorHex(xor, cribHex);
assertEquals("48656c", xor1);
assertEquals("Hel", hexToAscii(xor1));
String[] cribHexArray =
{
toHex("the"),
toHex("Hel"),
toHex("the "),
toHex("Hell"),
toHex("Hello"),
toHex("Hello "),
toHex("the p"),
toHex("the pr"),
toHex("ya"),
toHex(" "),
toHex("gram"),
toHex("pro"),
toHex("o W"),
toHex("the program"),
toHex("Hello World"),
toHex("mike"),
};
Map<String, List<String>> map = new HashMap<String, List<String>>();
System.out.println("Cipher Xor: " + xor);
for (String cribString : cribHexArray)
{
String ascCrib = hexToAscii(cribString);
for (int j = 0; j < xor.length(); j++)
{
String substring = xor.substring(j);
String xor2 = xorHex(substring, cribString);
if (!map.containsKey(ascCrib))
{
map.put(ascCrib, new ArrayList<String>());
}
String hexToAscii = hexToAscii(xor2);
String format = String.format("j:(%d) %s", j, hexToAscii);
if (!hexToAscii.contains(INVALID_CHAR))
{
List<String> get = map.get(ascCrib);
get.add(hexToAscii);
}
}
//System.out.println("");
//System.out.println("");
}
for (Map.Entry<String, List<String>> entry : map.entrySet())
{
String format = String.format("%s:\t %s", entry.getKey(), entry.getValue());
System.out.print(format);
System.out.println();
}
}
@Test
public void cipher1()
{
String[] cribHexArray =
{
toHex("the "),
toHex("we can "),
toHex("the second"),
toHex("Ever us"),
toHex(" the "),
toHex(" and "),
toHex("and"),
toHex(" "),
toHex("ssage"),
toHex(" about"),
toHex("toma"),
toHex("the nup"),
toHex("text produ"),
toHex("d probably"),
toHex("e"),
toHex("t"),
toHex("a"),
toHex("o"),
};
Map<String, List<String>> map = new HashMap<String, List<String>>();
String xorString = targetCipher;
for (int i = 0; i < cipherTexts.length; i++)
{
xorString = xorHex(cipherTexts[i], xorString);
for (String cribString : cribHexArray)
{
String ascCrib = hexToAscii(cribString);
//System.out.println("Doing Crib: " + hexToAscii(cribString));
for (int j = 0; j < xorString.length(); j++)
{
String substring = xorString.substring(j);
// System.out.println("Substring: " + substring + " : " + i);
String xor2 = xorHex(substring, cribString);
if (!map.containsKey(ascCrib))
{
map.put(ascCrib, new ArrayList<String>());
}
String hexToAscii = hexToAscii(xor2);
String format = String.format("j:(%d) %s", j, hexToAscii);
//System.out.println(format);
if (!hexToAscii.contains(INVALID_CHAR))
{
List<String> get = map.get(ascCrib);
get.add(hexToAscii);
}
}
//System.out.println("");
//System.out.println("");
}
System.out.println("");
}
for (Map.Entry<String, List<String>> entry : map.entrySet())
{
String format = String.format("%s: \t %s", entry.getKey(), entry.getValue());
System.out.print(format);
System.out.println();
}
}
@Test
public void cipher2()
{
String[] cribHexArray =
{
toHex("the "),
toHex("we can "),
toHex("the sec"),
toHex("Ever us"),
toHex(" the "),
toHex(" and "),
toHex("and"),
toHex(" "),
toHex("ssage"),
toHex("sage in"),
toHex(" about"),
toHex("toma"),
toHex("the nup"),
toHex("text produ"),
toHex("d probably"),
toHex("e"),
toHex("t"),
toHex("a"),
toHex("o"),
};
Map<String, List<String>> map = new HashMap<String, List<String>>();
String xorString = targetCipher;
for (int i = 0; i < cipherTexts.length; i++)
{
xorString = xorHex(cipherTexts[i], xorString);
for (String cribString : cribHexArray)
{
//System.out.println("Doing Crib: " + hexToAscii(cribString));
int length = xorString.length();
String ascCrib = hexToAscii(cribString);
for (int j = 0; j < xorString.length(); j += cribString.length())
{
String substring = xorString.substring(j);
// System.out.println("Substring: " + substring + " : " + i);
String xor2 = xorHex(substring, cribString);
if (!map.containsKey(ascCrib))
{
map.put(ascCrib, new ArrayList<String>());
}
String hexToAscii = hexToAscii(xor2);
String format = String.format("j:(%d) %s", j, hexToAscii);
//System.out.println(format);
if (!hexToAscii.contains(INVALID_CHAR))
{
List<String> get = map.get(ascCrib);
get.add(hexToAscii);
}
}
//System.out.println("");
//System.out.println("");
}
System.out.println("");
}
for (Map.Entry<String, List<String>> entry : map.entrySet())
{
String format = String.format("%s: \t %s", entry.getKey(), entry.getValue());
System.out.print(format);
System.out.println();
System.out.println();
}
}
@Test
public void cipher3()
{
String[] cText = new String[cipherTexts.length + 1];
System.arraycopy(cipherTexts, 0, cText, 0, cipherTexts.length);
cText[cipherTexts.length] = targetCipher;
String[][] xorMatrix = new String[cText.length][cText.length];
//Get Matrix of All Cipher Texts xored with one another
for (int i = 0; i < cText.length; i++)
{
for (int j = 0; j < cText.length; j++)
{
if (i != j)
{
xorMatrix[i][j] = xorHex(cText[i], cText[j]);
}
}
}
String[] cribHexArray =
{
toHex("the"),
toHex("the "),
toHex(" the "),
toHex("The "),
toHex("priv"),
toHex("The nic"),
toHex("We can "),
toHex("we can "),
toHex("euler"),
toHex("Ful"),
toHex("here"),
toHex("don"),
toHex("e"),
toHex("t"),
toHex("at"),
toHex(" "),
toHex("Who"),
toHex("What"),
toHex("Where"),
toHex("When"),
toHex("Why"),
toHex("How"),
toHex("You"),
toHex("you")
};
for (String cribHex : cribHexArray)
{
System.out.print("CribHex: " + hexToAscii(cribHex));
System.out.println();
for (String[] strings : xorMatrix)
{
for (String string : strings)
{
if (string != null)
{
String xorHex = xorHex(string, cribHex);
System.out.print(hexToAscii(xorHex));
}
}
System.out.println();
}
System.out.println();
}
}
@Test
public void exampleCipher()
{
String[] cText =
{
"3b101c091d53320c000910",
"071d154502010a04000419"
};
String[][] xorMatrix = new String[cText.length][cText.length];
//Get Matrix of All Cipher Texts xored with one another
for (int i = 0; i < cText.length; i++)
{
for (int j = 0; j < cText.length; j++)
{
if (i != j)
{
xorMatrix[i][j] = xorHex(cText[i], cText[j]);
}
}
}
String[] cribHexArray =
{
toHex("the"),
toHex("the "),
toHex("tel"),
toHex("ya"),
toHex("the "),
toHex("Hello"),
toHex("Hello "),
toHex(" W"),
toHex("orld"),
toHex("the pro"),
};
for (String cribHex : cribHexArray)
{
System.out.print("CribHex: " + hexToAscii(cribHex));
System.out.println();
for (String[] strings : xorMatrix)
{
for (String string : strings)
{
if (string != null)
{
for (int j = 0; j < string.length(); j++)
{
String substring = string.substring(j);
// System.out.println("Substring: " + substring + " : " + i);
//String xorHex = xorHex(string, cribHex);
String xorHex = xorHex(substring, cribHex);
String hexToAscii = hexToAscii(xorHex);
if (!hexToAscii.contains("."))
{
System.out.print(hexToAscii + "|");
}
}
}
}
System.out.println();
}
System.out.println();
}
}
@Test
public void exampleCipher2() throws DecoderException
{
String[] cText =
{
"3b101c091d53320c000910",
"071d154502010a04000419"
};
byte[][] xorMatrix = new byte[cText.length][cText[0].getBytes().length];
//Get Matrix of All Cipher Texts xored with one another
for (int i = 0; i < cText.length; i++)
{
try
{
xorMatrix[i] = Hex.decodeHex(cText[i].toCharArray());
}
catch (DecoderException ex)
{
Logger.getLogger(AppTest.class.getName()).log(Level.SEVERE, null, ex);
}
}
for (int i = 0; i < xorMatrix.length; i++)
{
// try
// {
byte[] col = xorMatrix[i];
System.out.print("[");
for (byte b : col)
{
System.out.print(b + " ");
}
System.out.print("]");
System.out.print("\t");
String text = new String(col);
System.out.print("\t");
System.out.print(text);
System.out.println();
//System.out.println();
//
// System.out.print("\t");
// text = new String(Hex.decodeHex(text.toCharArray()));
// System.out.print("\t");
// System.out.print(text);
// System.out.println();
// }
// catch (DecoderException ex)
// {
// Logger.getLogger(AppTest.class.getName()).log(Level.SEVERE, null, ex);
// }
}
byte[] xor = xorBytes(xorMatrix[0], xorMatrix[1]);
System.out.println("===================================================================================");
System.out.print("[");
for (byte b : xor)
{
System.out.print(b + " ");
}
System.out.print("]");
System.out.print("\t");
String text = new String(xor);
System.out.print("\t");
System.out.print("|" + text + "|");
System.out.println();
byte[] bite = xorBytes(xorMatrix[0], toHex(" ").getBytes());
System.out.print("]");
System.out.print("\t");
text = new String(bite);
System.out.print("\t");
System.out.print("|" + text + "|");
System.out.println();
// System.out.println();
// System.out.println("===================================");
// byte[] xorBytes = xorBytes(xor, " ".getBytes());
// text = new String(xorBytes);
// System.out.print("\t");
// System.out.print("|" + text + "|");
// System.out.println();
//
//
// System.out.println();
// System.out.println("===================================");
// xorBytes = xorBytes(xor, toHex(text).getBytes());
// text = new String(xorBytes);
// System.out.print("\t");
// System.out.print("|" + text + "|");
// System.out.println();
}
@Test
public void homeworkQuestion5()
{
byte message = 127;
byte key = 10 % 256;
byte encrypt = (byte) (message + key);
byte decrypt = (byte) (encrypt - key);
assertEquals(message, decrypt);
//message and key size are equal because of being bytes
}
@Test
public void homeworkQuestion7() throws DecoderException
{
String hexEncrypt = "6c73d5240a948c86981bc294814d";
String message = "attack at dawn";
String key = xorHex(toHex(message), hexEncrypt);
assertEquals("0d07a14569fface7ec3ba6f5f623", key);
assertEquals(message, hexToAscii(xorHex(key, hexEncrypt)));
String message2 = "attack at dusk";
String hexEncrypt2 = xorHex(toHex(message2), key);
System.out.println(hexEncrypt2);
assertEquals("6c73d5240a948c86981bc2808548", hexEncrypt2);
assertNotEquals(hexEncrypt, hexEncrypt2);
}
@Test
public void homeworkQuestion7_attempt2() throws DecoderException
{
String hexEncrypt = "09e1c5f70a65ac519458e7e53f36";
String message = "attack at dawn";
String key = xorHex(toHex(message), hexEncrypt);
System.out.println(key);
assertEquals("6895b196690e8c30e07883844858", key);
assertEquals(message, hexToAscii(xorHex(key, hexEncrypt)));
String message2 = "attack at dusk";
String hexEncrypt2 = xorHex(toHex(message2), key);
System.out.println(hexEncrypt2);
assertEquals("09e1c5f70a65ac519458e7f13b33", hexEncrypt2);
assertNotEquals(hexEncrypt, hexEncrypt2);
}
public byte[] xorBytes(byte[] b1, byte[] b2)
{
int length = b1.length > b2.length ? b2.length : b1.length;
byte[] xor = new byte[length];
for (int i = 0; i < length; i++)
{
xor[i] = (byte) (b1[i] ^ b2[i]);
}
return xor;
}
}
|
Cryptography/Part1/Homework1/src/test/java/com/mfullen/homework1/AppTest.java
|
package com.mfullen.homework1;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Hex;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
/**
*
* @author mfullen
*/
public class AppTest
{
public static final String INVALID_CHAR = ".";
private String[] cipherTexts;
private String targetCipher;
private static final String UTF8 = "UTF-8";
@Before
public void setUp()
{
this.targetCipher = "32510ba9babebbbefd001547a810e67149caee11d945cd7fc81a05e9f85aac650e9052ba6a8cd8257bf14d13e6f0a803b54fde9e77472dbff89d71b57bddef121336cb85ccb8f3315f4b52e301d16e9f52f904";
String[] texts =
{
"315c4eeaa8b5f8aaf9174145bf43e1784b8fa00dc71d885a804e5ee9fa40b16349c146fb778cdf2d3aff021dfff5b403b510d0d0455468aeb98622b137dae857553ccd8883a7bc37520e06e515d22c954eba5025b8cc57ee59418ce7dc6bc41556bdb36bbca3e8774301fbcaa3b83b220809560987815f65286764703de0f3d524400a19b159610b11ef3e",
"234c02ecbbfbafa3ed18510abd11fa724fcda2018a1a8342cf064bbde548b12b07df44ba7191d9606ef4081ffde5ad46a5069d9f7f543bedb9c861bf29c7e205132eda9382b0bc2c5c4b45f919cf3a9f1cb74151f6d551f4480c82b2cb24cc5b028aa76eb7b4ab24171ab3cdadb8356f",
"32510ba9a7b2bba9b8005d43a304b5714cc0bb0c8a34884dd91304b8ad40b62b07df44ba6e9d8a2368e51d04e0e7b207b70b9b8261112bacb6c866a232dfe257527dc29398f5f3251a0d47e503c66e935de81230b59b7afb5f41afa8d661cb",
"32510ba9aab2a8a4fd06414fb517b5605cc0aa0dc91a8908c2064ba8ad5ea06a029056f47a8ad3306ef5021eafe1ac01a81197847a5c68a1b78769a37bc8f4575432c198ccb4ef63590256e305cd3a9544ee4160ead45aef520489e7da7d835402bca670bda8eb775200b8dabbba246b130f040d8ec6447e2c767f3d30ed81ea2e4c1404e1315a1010e7229be6636aaa",
"3f561ba9adb4b6ebec54424ba317b564418fac0dd35f8c08d31a1fe9e24fe56808c213f17c81d9607cee021dafe1e001b21ade877a5e68bea88d61b93ac5ee0d562e8e9582f5ef375f0a4ae20ed86e935de81230b59b73fb4302cd95d770c65b40aaa065f2a5e33a5a0bb5dcaba43722130f042f8ec85b7c2070",
"32510bfbacfbb9befd54415da243e1695ecabd58c519cd4bd2061bbde24eb76a19d84aba34d8de287be84d07e7e9a30ee714979c7e1123a8bd9822a33ecaf512472e8e8f8db3f9635c1949e640c621854eba0d79eccf52ff111284b4cc61d11902aebc66f2b2e436434eacc0aba938220b084800c2ca4e693522643573b2c4ce35050b0cf774201f0fe52ac9f26d71b6cf61a711cc229f77ace7aa88a2f19983122b11be87a59c355d25f8e4",
"32510bfbacfbb9befd54415da243e1695ecabd58c519cd4bd90f1fa6ea5ba47b01c909ba7696cf606ef40c04afe1ac0aa8148dd066592ded9f8774b529c7ea125d298e8883f5e9305f4b44f915cb2bd05af51373fd9b4af511039fa2d96f83414aaaf261bda2e97b170fb5cce2a53e675c154c0d9681596934777e2275b381ce2e40582afe67650b13e72287ff2270abcf73bb028932836fbdecfecee0a3b894473c1bbeb6b4913a536ce4f9b13f1efff71ea313c8661dd9a4ce",
"315c4eeaa8b5f8bffd11155ea506b56041c6a00c8a08854dd21a4bbde54ce56801d943ba708b8a3574f40c00fff9e00fa1439fd0654327a3bfc860b92f89ee04132ecb9298f5fd2d5e4b45e40ecc3b9d59e9417df7c95bba410e9aa2ca24c5474da2f276baa3ac325918b2daada43d6712150441c2e04f6565517f317da9d3",
"271946f9bbb2aeadec111841a81abc300ecaa01bd8069d5cc91005e9fe4aad6e04d513e96d99de2569bc5e50eeeca709b50a8a987f4264edb6896fb537d0a716132ddc938fb0f836480e06ed0fcd6e9759f40462f9cf57f4564186a2c1778f1543efa270bda5e933421cbe88a4a52222190f471e9bd15f652b653b7071aec59a2705081ffe72651d08f822c9ed6d76e48b63ab15d0208573a7eef027",
"466d06ece998b7a2fb1d464fed2ced7641ddaa3cc31c9941cf110abbf409ed39598005b3399ccfafb61d0315fca0a314be138a9f32503bedac8067f03adbf3575c3b8edc9ba7f537530541ab0f9f3cd04ff50d66f1d559ba520e89a2cb2a83"
};
this.cipherTexts = texts;
}
public String toHex(String arg)
{
try
{
return String.format("%02x", new BigInteger(1, arg.getBytes(UTF8)));
}
catch (UnsupportedEncodingException ex)
{
Logger.getLogger(AppTest.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
/**
* Xors 2 hex strings
*
* @param x
* @param y
* @return
*/
public String xor(String x, String y)
{
String xor = null;
try
{
BigInteger x1 = new BigInteger(x, 16);
BigInteger y1 = new BigInteger(y, 16);
BigInteger bigIntegerXor = x1.xor(y1);
xor = Hex.encodeHexString(bigIntegerXor.toByteArray());
}
catch (Exception e)
{
}
return xor;
}
public String xor2(String x, String y)
{
String xor = null;
try
{
BigInteger x1 = new BigInteger(x, 16);
BigInteger y1 = new BigInteger(y, 16);
BigInteger bigIntegerXor = x1.xor(y1);
xor = Hex.encodeHexString(bigIntegerXor.toByteArray());
xor = bigIntegerXor.toString(16);
}
catch (Exception e)
{
}
return xor;
}
public String xorHex(String a, String b)
{
int length = a.length() > b.length() ? b.length() : a.length();
char[] chars = new char[length];
for (int i = 0; i < chars.length; i++)
{
chars[i] = toHex(fromHex(a.charAt(i)) ^ fromHex(b.charAt(i)));
}
return new String(chars);
}
private static int fromHex(char c)
{
if (c >= '0' && c <= '9')
{
return c - '0';
}
if (c >= 'A' && c <= 'F')
{
return c - 'A' + 10;
}
if (c >= 'a' && c <= 'f')
{
return c - 'a' + 10;
}
throw new IllegalArgumentException();
}
private char toHex(int nybble)
{
if (nybble < 0 || nybble > 15)
{
throw new IllegalArgumentException();
}
return "0123456789ABCDEF".toLowerCase().charAt(nybble);
}
public boolean isValidAscii(char c)
{
if (c > 122)
{
return false;
}
if (c < 32 && c != 10)
{
return false;
}
if (c > 32 && c < 48)
{
return false;
}
return true;
}
public String filterAscii(String string)
{
StringBuilder output = new StringBuilder();
for (int i = 0; i < string.length(); i++)
{
char c = string.charAt(i);
if (isValidAscii(c))
{
output.append(c);
}
else
{
output.append(INVALID_CHAR);
}
}
return output.toString();
}
public String hexToAscii(String hex)
{
try
{
byte[] decodeHex = Hex.decodeHex(hex.toCharArray());
String string = new String(decodeHex, UTF8);
return filterAscii(string);
}
catch (Exception e)
{
//System.out.println("Error, returning : ");
//e.printStackTrace();
int x = 0;
}
return INVALID_CHAR;
}
/**
* Test of main method, of class App.
*/
@Test
public void testHelperMethods()
{
final String crib = "the";
String cribHex = toHex(crib);
String c1 = "3b101c091d53320c000910";
String c2 = "071d154502010a04000419";
String xor = xorHex(c1, c2);
assertEquals("746865", cribHex);
assertEquals("3c0d094c1f523808000d09", xor);
String xor1 = xorHex(xor, cribHex);
assertEquals("48656c", xor1);
assertEquals("Hel", hexToAscii(xor1));
assertEquals("48656c6c6f", toHex("Hello"));
String xor2 = xorHex("3c0d094c1f", toHex("Hello"));
assertEquals("the p", hexToAscii(xor2));
// {
// String xor3 = xor("c0d094c1f5", toHex("Hello"));
// assertEquals("the p", hexToAscii(xor3));
// }
// {
// String xor3 = xor("0d094c1f52", toHex("Hello"));
// assertEquals("the p", hexToAscii(xor3));
// }
// {
// String xor3 = xor("523808000d", toHex("Hello"));
// assertEquals("the p", hexToAscii(xor3));
// }
{
String xor3 = xor(xor, toHex("the program"));
assertEquals("Hello World", hexToAscii(xor3));
}
}
@Test
public void testHelperMethods2()
{
final String crib = "the";
String cribHex = toHex(crib);
String c1 = "3b101c091d53320c000910";
String c2 = "071d154502010a04000419";
String key = toHex("supersecret");
assertEquals("7375706572736563726574", key);
String c3 = xorHex(toHex("the mike"), key);
System.out.println("C3:" + c3);
String xor = xorHex(c1, c2);
assertEquals("746865", cribHex);
assertEquals("3c0d094c1f523808000d09", xor);
String xor1 = xorHex(xor, cribHex);
assertEquals("48656c", xor1);
assertEquals("Hel", hexToAscii(xor1));
String[] cribHexArray =
{
toHex("the"),
toHex("Hel"),
toHex("the "),
toHex("Hell"),
toHex("Hello"),
toHex("Hello "),
toHex("the p"),
toHex("the pr"),
toHex("ya"),
toHex(" "),
toHex("gram"),
toHex("pro"),
toHex("o W"),
toHex("the program"),
toHex("Hello World"),
toHex("mike"),
};
Map<String, List<String>> map = new HashMap<String, List<String>>();
System.out.println("Cipher Xor: " + xor);
for (String cribString : cribHexArray)
{
String ascCrib = hexToAscii(cribString);
for (int j = 0; j < xor.length(); j++)
{
String substring = xor.substring(j);
String xor2 = xorHex(substring, cribString);
if (!map.containsKey(ascCrib))
{
map.put(ascCrib, new ArrayList<String>());
}
String hexToAscii = hexToAscii(xor2);
String format = String.format("j:(%d) %s", j, hexToAscii);
if (!hexToAscii.contains(INVALID_CHAR))
{
List<String> get = map.get(ascCrib);
get.add(hexToAscii);
}
}
//System.out.println("");
//System.out.println("");
}
for (Map.Entry<String, List<String>> entry : map.entrySet())
{
String format = String.format("%s:\t %s", entry.getKey(), entry.getValue());
System.out.print(format);
System.out.println();
}
}
@Test
public void cipher1()
{
String[] cribHexArray =
{
toHex("the "),
toHex("we can "),
toHex("the second"),
toHex("Ever us"),
toHex(" the "),
toHex(" and "),
toHex("and"),
toHex(" "),
toHex("ssage"),
toHex(" about"),
toHex("toma"),
toHex("the nup"),
toHex("text produ"),
toHex("d probably"),
toHex("e"),
toHex("t"),
toHex("a"),
toHex("o"),
};
Map<String, List<String>> map = new HashMap<String, List<String>>();
String xorString = targetCipher;
for (int i = 0; i < cipherTexts.length; i++)
{
xorString = xorHex(cipherTexts[i], xorString);
for (String cribString : cribHexArray)
{
String ascCrib = hexToAscii(cribString);
//System.out.println("Doing Crib: " + hexToAscii(cribString));
for (int j = 0; j < xorString.length(); j++)
{
String substring = xorString.substring(j);
// System.out.println("Substring: " + substring + " : " + i);
String xor2 = xorHex(substring, cribString);
if (!map.containsKey(ascCrib))
{
map.put(ascCrib, new ArrayList<String>());
}
String hexToAscii = hexToAscii(xor2);
String format = String.format("j:(%d) %s", j, hexToAscii);
//System.out.println(format);
if (!hexToAscii.contains(INVALID_CHAR))
{
List<String> get = map.get(ascCrib);
get.add(hexToAscii);
}
}
//System.out.println("");
//System.out.println("");
}
System.out.println("");
}
for (Map.Entry<String, List<String>> entry : map.entrySet())
{
String format = String.format("%s: \t %s", entry.getKey(), entry.getValue());
System.out.print(format);
System.out.println();
}
}
@Test
public void cipher2()
{
String[] cribHexArray =
{
toHex("the "),
toHex("we can "),
toHex("the sec"),
toHex("Ever us"),
toHex(" the "),
toHex(" and "),
toHex("and"),
toHex(" "),
toHex("ssage"),
toHex("sage in"),
toHex(" about"),
toHex("toma"),
toHex("the nup"),
toHex("text produ"),
toHex("d probably"),
toHex("e"),
toHex("t"),
toHex("a"),
toHex("o"),
};
Map<String, List<String>> map = new HashMap<String, List<String>>();
String xorString = targetCipher;
for (int i = 0; i < cipherTexts.length; i++)
{
xorString = xorHex(cipherTexts[i], xorString);
for (String cribString : cribHexArray)
{
//System.out.println("Doing Crib: " + hexToAscii(cribString));
int length = xorString.length();
String ascCrib = hexToAscii(cribString);
for (int j = 0; j < xorString.length(); j += cribString.length())
{
String substring = xorString.substring(j);
// System.out.println("Substring: " + substring + " : " + i);
String xor2 = xorHex(substring, cribString);
if (!map.containsKey(ascCrib))
{
map.put(ascCrib, new ArrayList<String>());
}
String hexToAscii = hexToAscii(xor2);
String format = String.format("j:(%d) %s", j, hexToAscii);
//System.out.println(format);
if (!hexToAscii.contains(INVALID_CHAR))
{
List<String> get = map.get(ascCrib);
get.add(hexToAscii);
}
}
//System.out.println("");
//System.out.println("");
}
System.out.println("");
}
for (Map.Entry<String, List<String>> entry : map.entrySet())
{
String format = String.format("%s: \t %s", entry.getKey(), entry.getValue());
System.out.print(format);
System.out.println();
System.out.println();
}
}
@Test
public void cipher3()
{
String[] cText = new String[cipherTexts.length + 1];
System.arraycopy(cipherTexts, 0, cText, 0, cipherTexts.length);
cText[cipherTexts.length] = targetCipher;
String[][] xorMatrix = new String[cText.length][cText.length];
//Get Matrix of All Cipher Texts xored with one another
for (int i = 0; i < cText.length; i++)
{
for (int j = 0; j < cText.length; j++)
{
if (i != j)
{
xorMatrix[i][j] = xorHex(cText[i], cText[j]);
}
}
}
String[] cribHexArray =
{
toHex("the"),
toHex("the "),
toHex(" the "),
toHex("The "),
toHex("priv"),
toHex("The nic"),
toHex("We can "),
toHex("we can "),
toHex("euler"),
toHex("Ful"),
toHex("here"),
toHex("don"),
toHex("e"),
toHex("t"),
toHex("at"),
toHex(" "),
toHex("Who"),
toHex("What"),
toHex("Where"),
toHex("When"),
toHex("Why"),
toHex("How"),
toHex("You"),
toHex("you")
};
for (String cribHex : cribHexArray)
{
System.out.print("CribHex: " + hexToAscii(cribHex));
System.out.println();
for (String[] strings : xorMatrix)
{
for (String string : strings)
{
if (string != null)
{
String xorHex = xorHex(string, cribHex);
System.out.print(hexToAscii(xorHex));
}
}
System.out.println();
}
System.out.println();
}
}
@Test
public void exampleCipher()
{
String[] cText =
{
"3b101c091d53320c000910",
"071d154502010a04000419"
};
String[][] xorMatrix = new String[cText.length][cText.length];
//Get Matrix of All Cipher Texts xored with one another
for (int i = 0; i < cText.length; i++)
{
for (int j = 0; j < cText.length; j++)
{
if (i != j)
{
xorMatrix[i][j] = xorHex(cText[i], cText[j]);
}
}
}
String[] cribHexArray =
{
toHex("the"),
toHex("the "),
toHex("tel"),
toHex("ya"),
toHex("the "),
toHex("Hello"),
toHex("Hello "),
toHex(" W"),
toHex("orld"),
toHex("the pro"),
};
for (String cribHex : cribHexArray)
{
System.out.print("CribHex: " + hexToAscii(cribHex));
System.out.println();
for (String[] strings : xorMatrix)
{
for (String string : strings)
{
if (string != null)
{
for (int j = 0; j < string.length(); j++)
{
String substring = string.substring(j);
// System.out.println("Substring: " + substring + " : " + i);
//String xorHex = xorHex(string, cribHex);
String xorHex = xorHex(substring, cribHex);
String hexToAscii = hexToAscii(xorHex);
if (!hexToAscii.contains("."))
{
System.out.print(hexToAscii + "|");
}
}
}
}
System.out.println();
}
System.out.println();
}
}
@Test
public void exampleCipher2() throws DecoderException
{
String[] cText =
{
"3b101c091d53320c000910",
"071d154502010a04000419"
};
byte[][] xorMatrix = new byte[cText.length][cText[0].getBytes().length];
//Get Matrix of All Cipher Texts xored with one another
for (int i = 0; i < cText.length; i++)
{
try
{
xorMatrix[i] = Hex.decodeHex(cText[i].toCharArray());
}
catch (DecoderException ex)
{
Logger.getLogger(AppTest.class.getName()).log(Level.SEVERE, null, ex);
}
}
for (int i = 0; i < xorMatrix.length; i++)
{
// try
// {
byte[] col = xorMatrix[i];
System.out.print("[");
for (byte b : col)
{
System.out.print(b + " ");
}
System.out.print("]");
System.out.print("\t");
String text = new String(col);
System.out.print("\t");
System.out.print(text);
System.out.println();
//System.out.println();
//
// System.out.print("\t");
// text = new String(Hex.decodeHex(text.toCharArray()));
// System.out.print("\t");
// System.out.print(text);
// System.out.println();
// }
// catch (DecoderException ex)
// {
// Logger.getLogger(AppTest.class.getName()).log(Level.SEVERE, null, ex);
// }
}
byte[] xor = xorBytes(xorMatrix[0], xorMatrix[1]);
System.out.println("===================================================================================");
System.out.print("[");
for (byte b : xor)
{
System.out.print(b + " ");
}
System.out.print("]");
System.out.print("\t");
String text = new String(xor);
System.out.print("\t");
System.out.print("|" + text + "|");
System.out.println();
byte[] bite = xorBytes(xorMatrix[0], toHex(" ").getBytes());
System.out.print("]");
System.out.print("\t");
text = new String(bite);
System.out.print("\t");
System.out.print("|" + text + "|");
System.out.println();
// System.out.println();
// System.out.println("===================================");
// byte[] xorBytes = xorBytes(xor, " ".getBytes());
// text = new String(xorBytes);
// System.out.print("\t");
// System.out.print("|" + text + "|");
// System.out.println();
//
//
// System.out.println();
// System.out.println("===================================");
// xorBytes = xorBytes(xor, toHex(text).getBytes());
// text = new String(xorBytes);
// System.out.print("\t");
// System.out.print("|" + text + "|");
// System.out.println();
}
@Test
public void homeworkQuestion7() throws DecoderException
{
String hexEncrypt = "6c73d5240a948c86981bc294814d";
String message = "attack at dawn";
String key = xorHex(toHex(message), hexEncrypt);
assertEquals("0d07a14569fface7ec3ba6f5f623", key);
assertEquals(message, hexToAscii(xorHex(key, hexEncrypt)));
String message2 = "attack at dusk";
String hexEncrypt2 = xorHex(toHex(message2), key);
System.out.println(hexEncrypt2);
assertEquals("6c73d5240a948c86981bc2808548", hexEncrypt2);
assertNotEquals(hexEncrypt, hexEncrypt2);
}
public byte[] xorBytes(byte[] b1, byte[] b2)
{
int length = b1.length > b2.length ? b2.length : b1.length;
byte[] xor = new byte[length];
for (int i = 0; i < length; i++)
{
xor[i] = (byte) (b1[i] ^ b2[i]);
}
return xor;
}
}
|
hw q7 attempt 2
|
Cryptography/Part1/Homework1/src/test/java/com/mfullen/homework1/AppTest.java
|
hw q7 attempt 2
|
<ide><path>ryptography/Part1/Homework1/src/test/java/com/mfullen/homework1/AppTest.java
<ide> }
<ide>
<ide> @Test
<add> public void homeworkQuestion5()
<add> {
<add> byte message = 127;
<add> byte key = 10 % 256;
<add>
<add> byte encrypt = (byte) (message + key);
<add> byte decrypt = (byte) (encrypt - key);
<add> assertEquals(message, decrypt);
<add> //message and key size are equal because of being bytes
<add> }
<add>
<add> @Test
<ide> public void homeworkQuestion7() throws DecoderException
<ide> {
<ide> String hexEncrypt = "6c73d5240a948c86981bc294814d";
<ide> assertNotEquals(hexEncrypt, hexEncrypt2);
<ide>
<ide> }
<add> @Test
<add> public void homeworkQuestion7_attempt2() throws DecoderException
<add> {
<add> String hexEncrypt = "09e1c5f70a65ac519458e7e53f36";
<add> String message = "attack at dawn";
<add> String key = xorHex(toHex(message), hexEncrypt);
<add> System.out.println(key);
<add> assertEquals("6895b196690e8c30e07883844858", key);
<add> assertEquals(message, hexToAscii(xorHex(key, hexEncrypt)));
<add>
<add> String message2 = "attack at dusk";
<add>
<add> String hexEncrypt2 = xorHex(toHex(message2), key);
<add> System.out.println(hexEncrypt2);
<add> assertEquals("09e1c5f70a65ac519458e7f13b33", hexEncrypt2);
<add> assertNotEquals(hexEncrypt, hexEncrypt2);
<add>
<add> }
<ide>
<ide> public byte[] xorBytes(byte[] b1, byte[] b2)
<ide> {
|
|
Java
|
bsd-3-clause
|
error: pathspec 'src/edu/afs/subsystems/launcherSubsystem/LauncherSubsystem.java' did not match any file(s) known to git
|
4eddd9702fb659d6472b0dfc9133196c51d29229
| 1 |
wando1/4373CommandBot
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package edu.afs.subsystems.launcherSubsystem;
import edu.wpi.first.wpilibj.command.Subsystem;
import edu.wpi.first.wpilibj.Encoder;
import edu.wpi.first.wpilibj.Victor;
import edu.afs.robot.RobotMap;
/**
*
* @author User
*/
public class LauncherSubsystem extends Subsystem {
// Put methods for controlling this subsystem
// here. Call these from Commands.
//TODO: Determine thresholds on launcher hardware.
private static final int UPPER_STOP_POSITION = 120;
private static final int UPPER_SLOW_POSITION = 115;
private static final int UPPER_MEDIUM_POSITION = 110;
private static final int LOWER_MEDIUM_POSITION = 15;
private static final int LOWER_SLOW_POSITION = 10;
private static final int LOWER_STOP_POSITION = 5;
private static final int MIN_ENCODER_VALUE = 0;
private static final int MAX_ENCODER_VALUE = 1023;
private static final double STOP = 0.0;
private static final double LOW_SPEED = 0.1;
private static final double MEDIUM_SPEED = 0.5;
private static final double HIGH_SPEED = 1.0;
static LauncherSubsystem instance = null;
Victor m_leftMotor;
Victor m_rightMotor;
Encoder m_launcherEncoder;
public static LauncherSubsystem getInstance () {
if (instance == null) {
instance = new LauncherSubsystem();
}
return instance;
}
private LauncherSubsystem () {
m_leftMotor = new Victor(RobotMap.LAUNCHER_LEFT_MOTOR_CHANNEL);
m_rightMotor = new Victor(RobotMap.LAUNCHER_RIGHT_MOTOR_CHANNEL);
m_launcherEncoder = new Encoder(RobotMap.LAUNCHER_ENCODER_MODULE,
RobotMap.LAUNCHER_ENCODER_A_CHANNEL,
RobotMap.LAUNCHER_ENCODER_MODULE,
RobotMap.LAUNCHER_ENCODER_B_CHANNEL,
false);
// Assume launcher starts in reset position. Set encoder count to zero.
m_launcherEncoder.reset();
// Start encoder count.
m_launcherEncoder.start();
resetLauncher();
}
public void fireLauncher(){
if(m_launcherEncoder.get() <= UPPER_STOP_POSITION){
// Determine motor speed on both launcher motors - ramp up.
double motorSpeed = getSpeed(getLauncherPosition(), true);
// Move upward.
m_leftMotor.set(motorSpeed);
m_rightMotor.set(motorSpeed);
}
}
public void resetLauncher(){
if(m_launcherEncoder.get() >= LOWER_STOP_POSITION){
// Determine motor speed on both launcher motors - ramp up.
double motorSpeed = getSpeed(getLauncherPosition(), false);
// Move downward.
m_leftMotor.set(motorSpeed);
m_rightMotor.set(motorSpeed);
}
}
// Returns value from 1.0 (max upward speed) to -1.0 (max downward speed)
// based on launcher arm position reported by shaft encoder (0 - 1023).
// We ramp the motor speed up and down to avoid over-stressing
// the launch mechanism.
private double getSpeed(int position, boolean isMovingUp){
double speed = 0.0;
if ((position >= MIN_ENCODER_VALUE) &&
(position <= MAX_ENCODER_VALUE)) {
//***LAUNCH***
// Map speed to valid position as launcher moves between reset
// position and top position.
if (isMovingUp == true){
// Ramp speed down as launcher approaches top position.
if (position >= UPPER_STOP_POSITION){
speed = STOP;
} else if(position >= UPPER_SLOW_POSITION){
speed = LOW_SPEED;
} else if (position >= UPPER_MEDIUM_POSITION){
speed = MEDIUM_SPEED;
}
// Ramp speed up as launcher leaves reset position moving up.
else if (position <= LOWER_MEDIUM_POSITION){
speed = MEDIUM_SPEED;
} else if (position <= LOWER_SLOW_POSITION){
speed = LOW_SPEED;
}
// Set speed to maximum between the two transition regions.
else {
speed = HIGH_SPEED;
}
//***RESET***
} else {
// Ramp speed up as launcher leaves top position moving down.
if(position >= UPPER_SLOW_POSITION){
speed = LOW_SPEED;
} else if (position >= UPPER_MEDIUM_POSITION){
speed = MEDIUM_SPEED;
}
// Ramp speed down as launcher approaches reset position.
else if (position <= LOWER_MEDIUM_POSITION){
speed = MEDIUM_SPEED;
} else if (position <= LOWER_SLOW_POSITION){
speed = LOW_SPEED;
} else if (position <= LOWER_STOP_POSITION){
speed = STOP;
}
// Set speed to maximum between the two transition regions.
else {
speed = HIGH_SPEED;
}
// We have the correct magnitude, now set direction.
speed = -speed;
} // End of if (isMovingUp == true) - else...
} else {
System.out.println("LauncherSubsystem::getSpeed::" +
"position arg out of range: " +
position);
}
return speed;
}
private int getLauncherPosition(){
return m_launcherEncoder.get();
}
public boolean isLauncherReset(){
if (m_launcherEncoder.get() <= LOWER_STOP_POSITION){
return true;
} else {
return false;
}
}
public boolean isLauncherFired(){
if (m_launcherEncoder.get() >= UPPER_STOP_POSITION){
return true;
} else {
return false;
}
}
public void initDefaultCommand() {
//TODO:Send launcher position to OI.
}
}
|
src/edu/afs/subsystems/launcherSubsystem/LauncherSubsystem.java
|
First pass at launch/reset functionality.
|
src/edu/afs/subsystems/launcherSubsystem/LauncherSubsystem.java
|
First pass at launch/reset functionality.
|
<ide><path>rc/edu/afs/subsystems/launcherSubsystem/LauncherSubsystem.java
<add>/*
<add> * To change this license header, choose License Headers in Project Properties.
<add> * To change this template file, choose Tools | Templates
<add> * and open the template in the editor.
<add> */
<add>package edu.afs.subsystems.launcherSubsystem;
<add>
<add>import edu.wpi.first.wpilibj.command.Subsystem;
<add>import edu.wpi.first.wpilibj.Encoder;
<add>import edu.wpi.first.wpilibj.Victor;
<add>import edu.afs.robot.RobotMap;
<add>
<add>/**
<add> *
<add> * @author User
<add> */
<add>public class LauncherSubsystem extends Subsystem {
<add> // Put methods for controlling this subsystem
<add> // here. Call these from Commands.
<add> //TODO: Determine thresholds on launcher hardware.
<add> private static final int UPPER_STOP_POSITION = 120;
<add> private static final int UPPER_SLOW_POSITION = 115;
<add> private static final int UPPER_MEDIUM_POSITION = 110;
<add>
<add> private static final int LOWER_MEDIUM_POSITION = 15;
<add> private static final int LOWER_SLOW_POSITION = 10;
<add> private static final int LOWER_STOP_POSITION = 5;
<add>
<add> private static final int MIN_ENCODER_VALUE = 0;
<add> private static final int MAX_ENCODER_VALUE = 1023;
<add>
<add> private static final double STOP = 0.0;
<add> private static final double LOW_SPEED = 0.1;
<add> private static final double MEDIUM_SPEED = 0.5;
<add> private static final double HIGH_SPEED = 1.0;
<add>
<add> static LauncherSubsystem instance = null;
<add> Victor m_leftMotor;
<add> Victor m_rightMotor;
<add> Encoder m_launcherEncoder;
<add>
<add> public static LauncherSubsystem getInstance () {
<add> if (instance == null) {
<add> instance = new LauncherSubsystem();
<add> }
<add> return instance;
<add> }
<add>
<add> private LauncherSubsystem () {
<add>
<add> m_leftMotor = new Victor(RobotMap.LAUNCHER_LEFT_MOTOR_CHANNEL);
<add> m_rightMotor = new Victor(RobotMap.LAUNCHER_RIGHT_MOTOR_CHANNEL);
<add> m_launcherEncoder = new Encoder(RobotMap.LAUNCHER_ENCODER_MODULE,
<add> RobotMap.LAUNCHER_ENCODER_A_CHANNEL,
<add> RobotMap.LAUNCHER_ENCODER_MODULE,
<add> RobotMap.LAUNCHER_ENCODER_B_CHANNEL,
<add> false);
<add>
<add> // Assume launcher starts in reset position. Set encoder count to zero.
<add> m_launcherEncoder.reset();
<add> // Start encoder count.
<add> m_launcherEncoder.start();
<add> resetLauncher();
<add> }
<add>
<add> public void fireLauncher(){
<add> if(m_launcherEncoder.get() <= UPPER_STOP_POSITION){
<add> // Determine motor speed on both launcher motors - ramp up.
<add> double motorSpeed = getSpeed(getLauncherPosition(), true);
<add> // Move upward.
<add> m_leftMotor.set(motorSpeed);
<add> m_rightMotor.set(motorSpeed);
<add> }
<add> }
<add>
<add> public void resetLauncher(){
<add> if(m_launcherEncoder.get() >= LOWER_STOP_POSITION){
<add> // Determine motor speed on both launcher motors - ramp up.
<add> double motorSpeed = getSpeed(getLauncherPosition(), false);
<add> // Move downward.
<add> m_leftMotor.set(motorSpeed);
<add> m_rightMotor.set(motorSpeed);
<add> }
<add>
<add> }
<add>
<add> // Returns value from 1.0 (max upward speed) to -1.0 (max downward speed)
<add> // based on launcher arm position reported by shaft encoder (0 - 1023).
<add> // We ramp the motor speed up and down to avoid over-stressing
<add> // the launch mechanism.
<add> private double getSpeed(int position, boolean isMovingUp){
<add> double speed = 0.0;
<add>
<add> if ((position >= MIN_ENCODER_VALUE) &&
<add> (position <= MAX_ENCODER_VALUE)) {
<add> //***LAUNCH***
<add> // Map speed to valid position as launcher moves between reset
<add> // position and top position.
<add> if (isMovingUp == true){
<add> // Ramp speed down as launcher approaches top position.
<add> if (position >= UPPER_STOP_POSITION){
<add> speed = STOP;
<add> } else if(position >= UPPER_SLOW_POSITION){
<add> speed = LOW_SPEED;
<add> } else if (position >= UPPER_MEDIUM_POSITION){
<add> speed = MEDIUM_SPEED;
<add> }
<add>
<add> // Ramp speed up as launcher leaves reset position moving up.
<add> else if (position <= LOWER_MEDIUM_POSITION){
<add> speed = MEDIUM_SPEED;
<add> } else if (position <= LOWER_SLOW_POSITION){
<add> speed = LOW_SPEED;
<add> }
<add>
<add> // Set speed to maximum between the two transition regions.
<add> else {
<add> speed = HIGH_SPEED;
<add> }
<add> //***RESET***
<add> } else {
<add> // Ramp speed up as launcher leaves top position moving down.
<add> if(position >= UPPER_SLOW_POSITION){
<add> speed = LOW_SPEED;
<add> } else if (position >= UPPER_MEDIUM_POSITION){
<add> speed = MEDIUM_SPEED;
<add> }
<add>
<add> // Ramp speed down as launcher approaches reset position.
<add> else if (position <= LOWER_MEDIUM_POSITION){
<add> speed = MEDIUM_SPEED;
<add> } else if (position <= LOWER_SLOW_POSITION){
<add> speed = LOW_SPEED;
<add> } else if (position <= LOWER_STOP_POSITION){
<add> speed = STOP;
<add> }
<add>
<add> // Set speed to maximum between the two transition regions.
<add> else {
<add> speed = HIGH_SPEED;
<add> }
<add>
<add> // We have the correct magnitude, now set direction.
<add> speed = -speed;
<add> } // End of if (isMovingUp == true) - else...
<add>
<add> } else {
<add> System.out.println("LauncherSubsystem::getSpeed::" +
<add> "position arg out of range: " +
<add> position);
<add> }
<add>
<add> return speed;
<add> }
<add>
<add> private int getLauncherPosition(){
<add> return m_launcherEncoder.get();
<add> }
<add>
<add> public boolean isLauncherReset(){
<add> if (m_launcherEncoder.get() <= LOWER_STOP_POSITION){
<add> return true;
<add> } else {
<add> return false;
<add> }
<add> }
<add>
<add> public boolean isLauncherFired(){
<add> if (m_launcherEncoder.get() >= UPPER_STOP_POSITION){
<add> return true;
<add> } else {
<add> return false;
<add> }
<add> }
<add>
<add> public void initDefaultCommand() {
<add> //TODO:Send launcher position to OI.
<add> }
<add>}
|
|
Java
|
apache-2.0
|
5244e2937eb8d01848f6548b116e23d7b775ef6a
| 0 |
debezium/debezium,debezium/debezium,debezium/debezium,debezium/debezium
|
/*
* Copyright Debezium Authors.
*
* Licensed under the Apache Software License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0
*/
package io.debezium.server.redis;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.enterprise.context.Dependent;
import javax.inject.Named;
import org.eclipse.microprofile.config.Config;
import org.eclipse.microprofile.config.ConfigProvider;
import org.eclipse.microprofile.config.inject.ConfigProperty;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.debezium.DebeziumException;
import io.debezium.engine.ChangeEvent;
import io.debezium.engine.DebeziumEngine;
import io.debezium.engine.DebeziumEngine.RecordCommitter;
import io.debezium.server.BaseChangeConsumer;
import io.debezium.util.DelayStrategy;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Pipeline;
import redis.clients.jedis.StreamEntryID;
import redis.clients.jedis.exceptions.JedisConnectionException;
import redis.clients.jedis.exceptions.JedisDataException;
/**
* Implementation of the consumer that delivers the messages into Redis (stream) destination.
*
* @author M Sazzadul Hoque
* @author Yossi Shirizli
*/
@Named("redis")
@Dependent
public class RedisStreamChangeConsumer extends BaseChangeConsumer
implements DebeziumEngine.ChangeConsumer<ChangeEvent<Object, Object>> {
private static final Logger LOGGER = LoggerFactory.getLogger(RedisStreamChangeConsumer.class);
private static final String PROP_PREFIX = "debezium.sink.redis.";
private static final String PROP_ADDRESS = PROP_PREFIX + "address";
private static final String PROP_USER = PROP_PREFIX + "user";
private static final String PROP_PASSWORD = PROP_PREFIX + "password";
private String address;
private String user;
private String password;
@ConfigProperty(name = PROP_PREFIX + "ssl.enabled", defaultValue = "false")
boolean sslEnabled;
@ConfigProperty(name = PROP_PREFIX + "batch.size", defaultValue = "500")
Integer batchSize;
@ConfigProperty(name = PROP_PREFIX + "retry.initial.delay.ms", defaultValue = "300")
Integer initialRetryDelay;
@ConfigProperty(name = PROP_PREFIX + "retry.max.delay.ms", defaultValue = "10000")
Integer maxRetryDelay;
@ConfigProperty(name = PROP_PREFIX + "null.key", defaultValue = "default")
String nullKey;
@ConfigProperty(name = PROP_PREFIX + "null.value", defaultValue = "default")
String nullValue;
private Jedis client = null;
@PostConstruct
void connect() {
final Config config = ConfigProvider.getConfig();
address = config.getValue(PROP_ADDRESS, String.class);
user = config.getOptionalValue(PROP_USER, String.class).orElse(null);
password = config.getOptionalValue(PROP_PASSWORD, String.class).orElse(null);
RedisConnection redisConnection = new RedisConnection(address, user, password, sslEnabled);
client = redisConnection.getRedisClient(RedisConnection.DEBEZIUM_REDIS_SINK_CLIENT_NAME);
}
@PreDestroy
void close() {
try {
if (client != null) {
client.close();
}
}
catch (Exception e) {
LOGGER.warn("Exception while closing Jedis: {}", client, e);
}
finally {
client = null;
}
}
/**
* Split collection to batches by batch size using a stream
*/
private <T> Stream<List<T>> batches(List<T> source, int length) {
if (source.isEmpty()) {
return Stream.empty();
}
int size = source.size();
int fullChunks = (size - 1) / length;
return IntStream.range(0, fullChunks + 1).mapToObj(
n -> source.subList(n * length, n == fullChunks ? size : (n + 1) * length));
}
@Override
public void handleBatch(List<ChangeEvent<Object, Object>> records,
RecordCommitter<ChangeEvent<Object, Object>> committer)
throws InterruptedException {
DelayStrategy delayStrategy = DelayStrategy.exponential(initialRetryDelay, maxRetryDelay);
LOGGER.trace("Handling a batch of {} records", records.size());
batches(records, batchSize).forEach(batch -> {
boolean completedSuccessfully = false;
// Clone the batch and remove the records that have been successfully processed.
// Move to the next batch once this list is empty.
List<ChangeEvent<Object, Object>> clonedBatch = batch.stream().collect(Collectors.toList());
// As long as we failed to execute the current batch to the stream, we should retry if the reason was either a connection error or OOM in Redis.
while (!completedSuccessfully) {
if (client == null) {
// Try to reconnect
try {
connect();
continue; // Managed to establish a new connection to Redis, avoid a redundant retry
}
catch (Exception e) {
close();
LOGGER.error("Can't connect to Redis", e);
}
}
else {
Pipeline pipeline;
try {
LOGGER.trace("Preparing a Redis Pipeline of {} records", clonedBatch.size());
// Make sure the connection is still alive before creating the pipeline
// to reduce the chance of ending up with duplicate records
client.ping();
pipeline = client.pipelined();
// Add the batch records to the stream(s) via Pipeline
for (ChangeEvent<Object, Object> record : clonedBatch) {
String destination = streamNameMapper.map(record.destination());
String key = (record.key() != null) ? getString(record.key()) : nullKey;
String value = (record.value() != null) ? getString(record.value()) : nullValue;
// Add the record to the destination stream
pipeline.xadd(destination, StreamEntryID.NEW_ENTRY, Collections.singletonMap(key, value));
}
// Sync the pipeline in Redis and parse the responses (response per command with the same order)
List<Object> responses = pipeline.syncAndReturnAll();
List<ChangeEvent<Object, Object>> processedRecords = new ArrayList<ChangeEvent<Object, Object>>();
int index = 0;
int totalOOMResponses = 0;
for (Object response : responses) {
String message = response.toString();
// When Redis reaches its max memory limitation, an OOM error message will be retrieved.
// In this case, we will retry execute the failed commands, assuming some memory will be freed eventually as result
// of evicting elements from the stream by the target DB.
if (message.contains("OOM command not allowed when used memory > 'maxmemory'")) {
totalOOMResponses++;
}
else {
// Mark the record as processed
ChangeEvent<Object, Object> currentRecord = clonedBatch.get(index);
committer.markProcessed(currentRecord);
processedRecords.add(currentRecord);
}
index++;
}
clonedBatch.removeAll(processedRecords);
if (totalOOMResponses > 0) {
LOGGER.warn("Redis runs OOM, {} command(s) failed", totalOOMResponses);
}
if (clonedBatch.size() == 0) {
completedSuccessfully = true;
}
}
catch (JedisConnectionException jce) {
LOGGER.error("Connection error", jce);
close();
}
catch (JedisDataException jde) {
// When Redis is starting, a JedisDataException will be thrown with this message.
// We will retry communicating with the target DB as once of the Redis is available, this message will be gone.
if (jde.getMessage().equals("LOADING Redis is loading the dataset in memory")) {
LOGGER.error("Redis is starting", jde);
}
else {
LOGGER.error("Unexpected JedisDataException", jde);
throw new DebeziumException(jde);
}
}
catch (Exception e) {
LOGGER.error("Unexpected Exception", e);
throw new DebeziumException(e);
}
}
// Failed to execute the transaction, retry...
delayStrategy.sleepWhen(!completedSuccessfully);
}
});
// Mark the whole batch as finished once the sub batches completed
committer.markBatchFinished();
}
}
|
debezium-server/debezium-server-redis/src/main/java/io/debezium/server/redis/RedisStreamChangeConsumer.java
|
/*
* Copyright Debezium Authors.
*
* Licensed under the Apache Software License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0
*/
package io.debezium.server.redis;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.enterprise.context.Dependent;
import javax.inject.Named;
import org.eclipse.microprofile.config.Config;
import org.eclipse.microprofile.config.ConfigProvider;
import org.eclipse.microprofile.config.inject.ConfigProperty;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.debezium.DebeziumException;
import io.debezium.engine.ChangeEvent;
import io.debezium.engine.DebeziumEngine;
import io.debezium.engine.DebeziumEngine.RecordCommitter;
import io.debezium.server.BaseChangeConsumer;
import io.debezium.util.DelayStrategy;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Pipeline;
import redis.clients.jedis.StreamEntryID;
import redis.clients.jedis.exceptions.JedisConnectionException;
import redis.clients.jedis.exceptions.JedisDataException;
/**
* Implementation of the consumer that delivers the messages into Redis (stream) destination.
*
* @author M Sazzadul Hoque
* @author Yossi Shirizli
*/
@Named("redis")
@Dependent
public class RedisStreamChangeConsumer extends BaseChangeConsumer
implements DebeziumEngine.ChangeConsumer<ChangeEvent<Object, Object>> {
private static final Logger LOGGER = LoggerFactory.getLogger(RedisStreamChangeConsumer.class);
private static final String PROP_PREFIX = "debezium.sink.redis.";
private static final String PROP_ADDRESS = PROP_PREFIX + "address";
private static final String PROP_USER = PROP_PREFIX + "user";
private static final String PROP_PASSWORD = PROP_PREFIX + "password";
private String address;
private String user;
private String password;
@ConfigProperty(name = PROP_PREFIX + "ssl.enabled", defaultValue = "false")
boolean sslEnabled;
@ConfigProperty(name = PROP_PREFIX + "batch.size", defaultValue = "500")
Integer batchSize;
@ConfigProperty(name = PROP_PREFIX + "retry.initial.delay.ms", defaultValue = "300")
Integer initialRetryDelay;
@ConfigProperty(name = PROP_PREFIX + "retry.max.delay.ms", defaultValue = "10000")
Integer maxRetryDelay;
@ConfigProperty(name = PROP_PREFIX + "null.key", defaultValue = "default")
String nullKey;
@ConfigProperty(name = PROP_PREFIX + "null.value", defaultValue = "default")
String nullValue;
private Jedis client = null;
@PostConstruct
void connect() {
final Config config = ConfigProvider.getConfig();
address = config.getValue(PROP_ADDRESS, String.class);
user = config.getOptionalValue(PROP_USER, String.class).orElse(null);
password = config.getOptionalValue(PROP_PASSWORD, String.class).orElse(null);
RedisConnection redisConnection = new RedisConnection(address, user, password, sslEnabled);
client = redisConnection.getRedisClient(RedisConnection.DEBEZIUM_REDIS_SINK_CLIENT_NAME);
}
@PreDestroy
void close() {
try {
client.close();
}
catch (Exception e) {
LOGGER.warn("Exception while closing Jedis: {}", client, e);
}
finally {
client = null;
}
}
/**
* Split collection to batches by batch size using a stream
*/
private <T> Stream<List<T>> batches(List<T> source, int length) {
if (source.isEmpty()) {
return Stream.empty();
}
int size = source.size();
int fullChunks = (size - 1) / length;
return IntStream.range(0, fullChunks + 1).mapToObj(
n -> source.subList(n * length, n == fullChunks ? size : (n + 1) * length));
}
@Override
public void handleBatch(List<ChangeEvent<Object, Object>> records,
RecordCommitter<ChangeEvent<Object, Object>> committer)
throws InterruptedException {
DelayStrategy delayStrategy = DelayStrategy.exponential(initialRetryDelay, maxRetryDelay);
LOGGER.trace("Handling a batch of {} records", records.size());
batches(records, batchSize).forEach(batch -> {
boolean completedSuccessfully = false;
// Clone the batch and remove the records that have been successfully processed.
// Move to the next batch once this list is empty.
List<ChangeEvent<Object, Object>> clonedBatch = batch.stream().collect(Collectors.toList());
// As long as we failed to execute the current batch to the stream, we should retry if the reason was either a connection error or OOM in Redis.
while (!completedSuccessfully) {
if (client == null) {
// Try to reconnect
try {
connect();
continue; // Managed to establish a new connection to Redis, avoid a redundant retry
}
catch (Exception e) {
close();
LOGGER.error("Can't connect to Redis", e);
}
}
else {
Pipeline pipeline;
try {
LOGGER.trace("Preparing a Redis Pipeline of {} records", clonedBatch.size());
// Make sure the connection is still alive before creating the pipeline
// to reduce the chance of ending up with duplicate records
client.ping();
pipeline = client.pipelined();
// Add the batch records to the stream(s) via Pipeline
for (ChangeEvent<Object, Object> record : clonedBatch) {
String destination = streamNameMapper.map(record.destination());
String key = (record.key() != null) ? getString(record.key()) : nullKey;
String value = (record.value() != null) ? getString(record.value()) : nullValue;
// Add the record to the destination stream
pipeline.xadd(destination, StreamEntryID.NEW_ENTRY, Collections.singletonMap(key, value));
}
// Sync the pipeline in Redis and parse the responses (response per command with the same order)
List<Object> responses = pipeline.syncAndReturnAll();
List<ChangeEvent<Object, Object>> processedRecords = new ArrayList<ChangeEvent<Object, Object>>();
int index = 0;
int totalOOMResponses = 0;
for (Object response : responses) {
String message = response.toString();
// When Redis reaches its max memory limitation, an OOM error message will be retrieved.
// In this case, we will retry execute the failed commands, assuming some memory will be freed eventually as result
// of evicting elements from the stream by the target DB.
if (message.contains("OOM command not allowed when used memory > 'maxmemory'")) {
totalOOMResponses++;
}
else {
// Mark the record as processed
ChangeEvent<Object, Object> currentRecord = clonedBatch.get(index);
committer.markProcessed(currentRecord);
processedRecords.add(currentRecord);
}
index++;
}
clonedBatch.removeAll(processedRecords);
if (totalOOMResponses > 0) {
LOGGER.warn("Redis runs OOM, {} command(s) failed", totalOOMResponses);
}
if (clonedBatch.size() == 0) {
completedSuccessfully = true;
}
}
catch (JedisConnectionException jce) {
LOGGER.error("Connection error", jce);
close();
}
catch (JedisDataException jde) {
// When Redis is starting, a JedisDataException will be thrown with this message.
// We will retry communicating with the target DB as once of the Redis is available, this message will be gone.
if (jde.getMessage().equals("LOADING Redis is loading the dataset in memory")) {
LOGGER.error("Redis is starting", jde);
}
else {
LOGGER.error("Unexpected JedisDataException", jde);
throw new DebeziumException(jde);
}
}
catch (Exception e) {
LOGGER.error("Unexpected Exception", e);
throw new DebeziumException(e);
}
}
// Failed to execute the transaction, retry...
delayStrategy.sleepWhen(!completedSuccessfully);
}
});
// Mark the whole batch as finished once the sub batches completed
committer.markBatchFinished();
}
}
|
DBZ-5019 Check if client is not null before closing it
|
debezium-server/debezium-server-redis/src/main/java/io/debezium/server/redis/RedisStreamChangeConsumer.java
|
DBZ-5019 Check if client is not null before closing it
|
<ide><path>ebezium-server/debezium-server-redis/src/main/java/io/debezium/server/redis/RedisStreamChangeConsumer.java
<ide> @PreDestroy
<ide> void close() {
<ide> try {
<del> client.close();
<add> if (client != null) {
<add> client.close();
<add> }
<ide> }
<ide> catch (Exception e) {
<ide> LOGGER.warn("Exception while closing Jedis: {}", client, e);
|
|
Java
|
mit
|
error: pathspec 'app/src/main/java/com/adriencadet/wanderer/models/services/wanderer/jobs/ListPicturesForPlaceJob.java' did not match any file(s) known to git
|
d35f1a42dd1a3c9c86fc508eaa3d2928aebb67c6
| 1 |
acadet/wanderer-android
|
package com.adriencadet.wanderer.models.services.wanderer.jobs;
import com.adriencadet.wanderer.models.services.RetrofitJob;
import com.adriencadet.wanderer.models.services.wanderer.api.IWandererAPI;
import com.adriencadet.wanderer.models.services.wanderer.dto.PictureWandererServerDTO;
import java.util.List;
import retrofit.RetrofitError;
import rx.Observable;
import rx.Subscriber;
import rx.schedulers.Schedulers;
/**
* ListPicturesForPlaceJob
* <p>
*/
public class ListPicturesForPlaceJob extends RetrofitJob {
private Observable<List<PictureWandererServerDTO>> observable;
private int placeID;
ListPicturesForPlaceJob(IWandererAPI api) {
observable = Observable
.create(new Observable.OnSubscribe<List<PictureWandererServerDTO>>() {
@Override
public void call(Subscriber<? super List<PictureWandererServerDTO>> subscriber) {
try {
List<PictureWandererServerDTO> outcome = api.listPicturesForPlace(placeID);
subscriber.onNext(outcome);
subscriber.onCompleted();
} catch (RetrofitError e) {
handleError(e, subscriber);
}
}
})
.subscribeOn(Schedulers.newThread());
}
public Observable<List<PictureWandererServerDTO>> create(int placeID) {
this.placeID = placeID;
return observable;
}
}
|
app/src/main/java/com/adriencadet/wanderer/models/services/wanderer/jobs/ListPicturesForPlaceJob.java
|
Implements ListPicturesForPlaceJob
|
app/src/main/java/com/adriencadet/wanderer/models/services/wanderer/jobs/ListPicturesForPlaceJob.java
|
Implements ListPicturesForPlaceJob
|
<ide><path>pp/src/main/java/com/adriencadet/wanderer/models/services/wanderer/jobs/ListPicturesForPlaceJob.java
<add>package com.adriencadet.wanderer.models.services.wanderer.jobs;
<add>
<add>import com.adriencadet.wanderer.models.services.RetrofitJob;
<add>import com.adriencadet.wanderer.models.services.wanderer.api.IWandererAPI;
<add>import com.adriencadet.wanderer.models.services.wanderer.dto.PictureWandererServerDTO;
<add>
<add>import java.util.List;
<add>
<add>import retrofit.RetrofitError;
<add>import rx.Observable;
<add>import rx.Subscriber;
<add>import rx.schedulers.Schedulers;
<add>
<add>/**
<add> * ListPicturesForPlaceJob
<add> * <p>
<add> */
<add>public class ListPicturesForPlaceJob extends RetrofitJob {
<add> private Observable<List<PictureWandererServerDTO>> observable;
<add>
<add> private int placeID;
<add>
<add> ListPicturesForPlaceJob(IWandererAPI api) {
<add> observable = Observable
<add> .create(new Observable.OnSubscribe<List<PictureWandererServerDTO>>() {
<add> @Override
<add> public void call(Subscriber<? super List<PictureWandererServerDTO>> subscriber) {
<add> try {
<add> List<PictureWandererServerDTO> outcome = api.listPicturesForPlace(placeID);
<add>
<add> subscriber.onNext(outcome);
<add> subscriber.onCompleted();
<add> } catch (RetrofitError e) {
<add> handleError(e, subscriber);
<add> }
<add> }
<add> })
<add> .subscribeOn(Schedulers.newThread());
<add> }
<add>
<add> public Observable<List<PictureWandererServerDTO>> create(int placeID) {
<add> this.placeID = placeID;
<add> return observable;
<add> }
<add>}
|
|
Java
|
epl-1.0
|
5a20dd6e7f1e1db9b97efb8c146ee6d91c82c363
| 0 |
opendaylight/yangtools,opendaylight/yangtools
|
/*
* Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
package org.opendaylight.yangtools.yang.parser.stmt.reactor;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import static java.util.Objects.requireNonNull;
import com.google.common.annotations.Beta;
import com.google.common.base.MoreObjects;
import com.google.common.base.MoreObjects.ToStringHelper;
import com.google.common.collect.ImmutableCollection;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMultimap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Multimap;
import com.google.common.collect.Multimaps;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.EnumMap;
import java.util.EventListener;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import org.eclipse.jdt.annotation.NonNull;
import org.eclipse.jdt.annotation.Nullable;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.common.QNameModule;
import org.opendaylight.yangtools.yang.model.api.YangStmtMapping;
import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
import org.opendaylight.yangtools.yang.model.api.meta.IdentifierNamespace;
import org.opendaylight.yangtools.yang.model.api.meta.StatementDefinition;
import org.opendaylight.yangtools.yang.model.api.meta.StatementSource;
import org.opendaylight.yangtools.yang.model.api.stmt.ConfigStatement;
import org.opendaylight.yangtools.yang.parser.spi.meta.CopyHistory;
import org.opendaylight.yangtools.yang.parser.spi.meta.CopyType;
import org.opendaylight.yangtools.yang.parser.spi.meta.ImplicitParentAwareStatementSupport;
import org.opendaylight.yangtools.yang.parser.spi.meta.InferenceException;
import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder;
import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour;
import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceKeyCriterion;
import org.opendaylight.yangtools.yang.parser.spi.meta.StatementNamespace;
import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupport;
import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext.Mutable;
import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils;
import org.opendaylight.yangtools.yang.parser.spi.source.ImplicitSubstatement;
import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
import org.opendaylight.yangtools.yang.parser.spi.source.StatementSourceReference;
import org.opendaylight.yangtools.yang.parser.spi.source.StatementWriter.ResumedStatement;
import org.opendaylight.yangtools.yang.parser.spi.source.SupportedFeaturesNamespace;
import org.opendaylight.yangtools.yang.parser.spi.source.SupportedFeaturesNamespace.SupportedFeatures;
import org.opendaylight.yangtools.yang.parser.stmt.reactor.NamespaceBehaviourWithListeners.KeyedValueAddedListener;
import org.opendaylight.yangtools.yang.parser.stmt.reactor.NamespaceBehaviourWithListeners.PredicateValueAddedListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public abstract class StatementContextBase<A, D extends DeclaredStatement<A>, E extends EffectiveStatement<A, D>>
extends NamespaceStorageSupport implements Mutable<A, D, E>, ResumedStatement {
/**
* Event listener when an item is added to model namespace.
*/
interface OnNamespaceItemAdded extends EventListener {
/**
* Invoked whenever a new item is added to a namespace.
*/
void namespaceItemAdded(StatementContextBase<?, ?, ?> context, Class<?> namespace, Object key, Object value);
}
/**
* Event listener when a parsing {@link ModelProcessingPhase} is completed.
*/
interface OnPhaseFinished extends EventListener {
/**
* Invoked whenever a processing phase has finished.
*/
boolean phaseFinished(StatementContextBase<?, ?, ?> context, ModelProcessingPhase finishedPhase);
}
/**
* Interface for all mutations within an {@link ModelActionBuilder.InferenceAction}.
*/
interface ContextMutation {
boolean isFinished();
}
private static final Logger LOG = LoggerFactory.getLogger(StatementContextBase.class);
// Flag bit assignments
private static final int IS_SUPPORTED_BY_FEATURES = 0x01;
private static final int HAVE_SUPPORTED_BY_FEATURES = 0x02;
private static final int IS_IGNORE_IF_FEATURE = 0x04;
private static final int HAVE_IGNORE_IF_FEATURE = 0x08;
// Note: these four are related
private static final int IS_IGNORE_CONFIG = 0x10;
private static final int HAVE_IGNORE_CONFIG = 0x20;
private static final int IS_CONFIGURATION = 0x40;
private static final int HAVE_CONFIGURATION = 0x80;
// Have-and-set flag constants, also used as masks
private static final int SET_SUPPORTED_BY_FEATURES = HAVE_SUPPORTED_BY_FEATURES | IS_SUPPORTED_BY_FEATURES;
private static final int SET_CONFIGURATION = HAVE_CONFIGURATION | IS_CONFIGURATION;
// Note: implies SET_CONFIGURATION, allowing fewer bit operations to be performed
private static final int SET_IGNORE_CONFIG = HAVE_IGNORE_CONFIG | IS_IGNORE_CONFIG | SET_CONFIGURATION;
private static final int SET_IGNORE_IF_FEATURE = HAVE_IGNORE_IF_FEATURE | IS_IGNORE_IF_FEATURE;
private final @NonNull StatementDefinitionContext<A, D, E> definition;
private final @NonNull StatementSourceReference statementDeclSource;
private final StmtContext<?, ?, ?> originalCtx;
private final StmtContext<?, ?, ?> prevCopyCtx;
private final CopyHistory copyHistory;
private final String rawArgument;
private Multimap<ModelProcessingPhase, OnPhaseFinished> phaseListeners = ImmutableMultimap.of();
private Multimap<ModelProcessingPhase, ContextMutation> phaseMutation = ImmutableMultimap.of();
private List<Mutable<?, ?, ?>> effective = ImmutableList.of();
private List<StmtContext<?, ?, ?>> effectOfStatement = ImmutableList.of();
private StatementMap substatements = StatementMap.empty();
private @Nullable ModelProcessingPhase completedPhase;
private @Nullable D declaredInstance;
private @Nullable E effectiveInstance;
// Common state bits
private boolean isSupportedToBuildEffective = true;
private boolean fullyDefined;
// Flags for use with SubstatementContext. These are hiding in the alignment shadow created by above booleans and
// hence improve memory layout.
private byte flags;
StatementContextBase(final StatementDefinitionContext<A, D, E> def, final StatementSourceReference ref,
final String rawArgument) {
this.definition = requireNonNull(def);
this.statementDeclSource = requireNonNull(ref);
this.rawArgument = def.internArgument(rawArgument);
this.copyHistory = CopyHistory.original();
this.originalCtx = null;
this.prevCopyCtx = null;
}
StatementContextBase(final StatementDefinitionContext<A, D, E> def, final StatementSourceReference ref,
final String rawArgument, final CopyType copyType) {
this.definition = requireNonNull(def);
this.statementDeclSource = requireNonNull(ref);
this.rawArgument = rawArgument;
this.copyHistory = CopyHistory.of(copyType, CopyHistory.original());
this.originalCtx = null;
this.prevCopyCtx = null;
}
StatementContextBase(final StatementContextBase<A, D, E> original, final CopyType copyType) {
this.definition = original.definition;
this.statementDeclSource = original.statementDeclSource;
this.rawArgument = original.rawArgument;
this.copyHistory = CopyHistory.of(copyType, original.getCopyHistory());
this.originalCtx = original.getOriginalCtx().orElse(original);
this.prevCopyCtx = original;
}
StatementContextBase(final StatementContextBase<A, D, E> original) {
this.definition = original.definition;
this.statementDeclSource = original.statementDeclSource;
this.rawArgument = original.rawArgument;
this.copyHistory = original.getCopyHistory();
this.originalCtx = original.getOriginalCtx().orElse(original);
this.prevCopyCtx = original;
this.substatements = original.substatements;
this.effective = original.effective;
}
@Override
public Collection<? extends StmtContext<?, ?, ?>> getEffectOfStatement() {
return effectOfStatement;
}
@Override
public void addAsEffectOfStatement(final StmtContext<?, ?, ?> ctx) {
if (effectOfStatement.isEmpty()) {
effectOfStatement = new ArrayList<>(1);
}
effectOfStatement.add(ctx);
}
@Override
public void addAsEffectOfStatement(final Collection<? extends StmtContext<?, ?, ?>> ctxs) {
if (ctxs.isEmpty()) {
return;
}
if (effectOfStatement.isEmpty()) {
effectOfStatement = new ArrayList<>(ctxs.size());
}
effectOfStatement.addAll(ctxs);
}
@Override
public boolean isSupportedByFeatures() {
final int fl = flags & SET_SUPPORTED_BY_FEATURES;
if (fl != 0) {
return fl == SET_SUPPORTED_BY_FEATURES;
}
if (isIgnoringIfFeatures()) {
flags |= SET_SUPPORTED_BY_FEATURES;
return true;
}
/*
* If parent is supported, we need to check if-features statements of this context.
*/
if (isParentSupportedByFeatures()) {
// If the set of supported features has not been provided, all features are supported by default.
final Set<QName> supportedFeatures = getFromNamespace(SupportedFeaturesNamespace.class,
SupportedFeatures.SUPPORTED_FEATURES);
if (supportedFeatures == null || StmtContextUtils.checkFeatureSupport(this, supportedFeatures)) {
flags |= SET_SUPPORTED_BY_FEATURES;
return true;
}
}
// Either parent is not supported or this statement is not supported
flags |= HAVE_SUPPORTED_BY_FEATURES;
return false;
}
protected abstract boolean isParentSupportedByFeatures();
@Override
public boolean isSupportedToBuildEffective() {
return isSupportedToBuildEffective;
}
@Override
public void setIsSupportedToBuildEffective(final boolean isSupportedToBuildEffective) {
this.isSupportedToBuildEffective = isSupportedToBuildEffective;
}
@Override
public CopyHistory getCopyHistory() {
return copyHistory;
}
@Override
public Optional<StmtContext<?, ?, ?>> getOriginalCtx() {
return Optional.ofNullable(originalCtx);
}
@Override
public Optional<? extends StmtContext<?, ?, ?>> getPreviousCopyCtx() {
return Optional.ofNullable(prevCopyCtx);
}
@Override
public ModelProcessingPhase getCompletedPhase() {
return completedPhase;
}
@Override
public void setCompletedPhase(final ModelProcessingPhase completedPhase) {
this.completedPhase = completedPhase;
}
@Override
public abstract StatementContextBase<?, ?, ?> getParentContext();
/**
* Returns the model root for this statement.
*
* @return root context of statement
*/
@Override
public abstract RootStatementContext<?, ?, ?> getRoot();
@Override
public StatementSource getStatementSource() {
return statementDeclSource.getStatementSource();
}
@Override
public StatementSourceReference getStatementSourceReference() {
return statementDeclSource;
}
@Override
public final String rawStatementArgument() {
return rawArgument;
}
@Override
public Collection<? extends StmtContext<?, ?, ?>> declaredSubstatements() {
return substatements.values();
}
@Override
public Collection<? extends Mutable<?, ?, ?>> mutableDeclaredSubstatements() {
return substatements.values();
}
@Override
public Collection<? extends StmtContext<?, ?, ?>> effectiveSubstatements() {
return mutableEffectiveSubstatements();
}
@Override
public Collection<? extends Mutable<?, ?, ?>> mutableEffectiveSubstatements() {
if (effective instanceof ImmutableCollection) {
return effective;
}
return Collections.unmodifiableCollection(effective);
}
private void shrinkEffective() {
if (effective.isEmpty()) {
effective = ImmutableList.of();
}
}
public void removeStatementFromEffectiveSubstatements(final StatementDefinition statementDef) {
if (effective.isEmpty()) {
return;
}
final Iterator<? extends StmtContext<?, ?, ?>> iterator = effective.iterator();
while (iterator.hasNext()) {
final StmtContext<?, ?, ?> next = iterator.next();
if (statementDef.equals(next.getPublicDefinition())) {
iterator.remove();
}
}
shrinkEffective();
}
/**
* Removes a statement context from the effective substatements based on its statement definition (i.e statement
* keyword) and raw (in String form) statement argument. The statement context is removed only if both statement
* definition and statement argument match with one of the effective substatements' statement definition
* and argument.
*
* <p>
* If the statementArg parameter is null, the statement context is removed based only on its statement definition.
*
* @param statementDef statement definition of the statement context to remove
* @param statementArg statement argument of the statement context to remove
*/
public void removeStatementFromEffectiveSubstatements(final StatementDefinition statementDef,
final String statementArg) {
if (statementArg == null) {
removeStatementFromEffectiveSubstatements(statementDef);
}
if (effective.isEmpty()) {
return;
}
final Iterator<Mutable<?, ?, ?>> iterator = effective.iterator();
while (iterator.hasNext()) {
final Mutable<?, ?, ?> next = iterator.next();
if (statementDef.equals(next.getPublicDefinition()) && statementArg.equals(next.rawStatementArgument())) {
iterator.remove();
}
}
shrinkEffective();
}
/**
* Adds an effective statement to collection of substatements.
*
* @param substatement substatement
* @throws IllegalStateException
* if added in declared phase
* @throws NullPointerException
* if statement parameter is null
*/
public void addEffectiveSubstatement(final Mutable<?, ?, ?> substatement) {
beforeAddEffectiveStatement(1);
effective.add(substatement);
}
/**
* Adds an effective statement to collection of substatements.
*
* @param statements substatements
* @throws IllegalStateException
* if added in declared phase
* @throws NullPointerException
* if statement parameter is null
*/
public void addEffectiveSubstatements(final Collection<? extends Mutable<?, ?, ?>> statements) {
if (statements.isEmpty()) {
return;
}
statements.forEach(Objects::requireNonNull);
beforeAddEffectiveStatement(statements.size());
effective.addAll(statements);
}
private void beforeAddEffectiveStatement(final int toAdd) {
final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
checkState(inProgressPhase == ModelProcessingPhase.FULL_DECLARATION
|| inProgressPhase == ModelProcessingPhase.EFFECTIVE_MODEL,
"Effective statement cannot be added in declared phase at: %s", getStatementSourceReference());
if (effective.isEmpty()) {
effective = new ArrayList<>(toAdd);
}
}
/**
* Create a new substatement at the specified offset.
*
* @param offset Substatement offset
* @param def definition context
* @param ref source reference
* @param argument statement argument
* @param <X> new substatement argument type
* @param <Y> new substatement declared type
* @param <Z> new substatement effective type
* @return A new substatement
*/
@SuppressWarnings("checkstyle:methodTypeParameterName")
public final <X, Y extends DeclaredStatement<X>, Z extends EffectiveStatement<X, Y>>
StatementContextBase<X, Y, Z> createSubstatement(final int offset,
final StatementDefinitionContext<X, Y, Z> def, final StatementSourceReference ref,
final String argument) {
final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
checkState(inProgressPhase != ModelProcessingPhase.EFFECTIVE_MODEL,
"Declared statement cannot be added in effective phase at: %s", getStatementSourceReference());
final Optional<StatementSupport<?, ?, ?>> implicitParent = definition.getImplicitParentFor(def.getPublicView());
if (implicitParent.isPresent()) {
return createImplicitParent(offset, implicitParent.get(), ref, argument).createSubstatement(offset, def,
ref, argument);
}
final StatementContextBase<X, Y, Z> ret = new SubstatementContext<>(this, def, ref, argument);
substatements = substatements.put(offset, ret);
def.onStatementAdded(ret);
return ret;
}
private StatementContextBase<?, ?, ?> createImplicitParent(final int offset,
final StatementSupport<?, ?, ?> implicitParent, final StatementSourceReference ref, final String argument) {
final StatementDefinitionContext<?, ?, ?> def = new StatementDefinitionContext<>(implicitParent);
return createSubstatement(offset, def, ImplicitSubstatement.of(ref), argument);
}
public void appendImplicitStatement(final StatementSupport<?, ?, ?> statementToAdd) {
createSubstatement(substatements.capacity(), new StatementDefinitionContext<>(statementToAdd),
ImplicitSubstatement.of(getStatementSourceReference()), null);
}
/**
* Lookup substatement by its offset in this statement.
*
* @param offset Substatement offset
* @return Substatement, or null if substatement does not exist.
*/
final StatementContextBase<?, ?, ?> lookupSubstatement(final int offset) {
return substatements.get(offset);
}
final void setFullyDefined() {
this.fullyDefined = true;
}
final void resizeSubstatements(final int expectedSize) {
substatements = substatements.ensureCapacity(expectedSize);
}
final void walkChildren(final ModelProcessingPhase phase) {
checkState(fullyDefined);
substatements.values().forEach(stmt -> {
stmt.walkChildren(phase);
stmt.endDeclared(phase);
});
}
@Override
public D buildDeclared() {
checkArgument(completedPhase == ModelProcessingPhase.FULL_DECLARATION
|| completedPhase == ModelProcessingPhase.EFFECTIVE_MODEL);
if (declaredInstance == null) {
declaredInstance = definition().getFactory().createDeclared(this);
}
return declaredInstance;
}
@Override
public E buildEffective() {
if (effectiveInstance == null) {
effectiveInstance = definition().getFactory().createEffective(this);
}
return effectiveInstance;
}
/**
* tries to execute current {@link ModelProcessingPhase} of source parsing.
*
* @param phase
* to be executed (completed)
* @return if phase was successfully completed
* @throws SourceException
* when an error occurred in source parsing
*/
boolean tryToCompletePhase(final ModelProcessingPhase phase) {
boolean finished = true;
final Collection<ContextMutation> openMutations = phaseMutation.get(phase);
if (!openMutations.isEmpty()) {
final Iterator<ContextMutation> it = openMutations.iterator();
while (it.hasNext()) {
final ContextMutation current = it.next();
if (current.isFinished()) {
it.remove();
} else {
finished = false;
}
}
if (openMutations.isEmpty()) {
phaseMutation.removeAll(phase);
if (phaseMutation.isEmpty()) {
phaseMutation = ImmutableMultimap.of();
}
}
}
for (final StatementContextBase<?, ?, ?> child : substatements.values()) {
finished &= child.tryToCompletePhase(phase);
}
for (final Mutable<?, ?, ?> child : effective) {
if (child instanceof StatementContextBase) {
finished &= ((StatementContextBase<?, ?, ?>) child).tryToCompletePhase(phase);
}
}
if (finished) {
onPhaseCompleted(phase);
return true;
}
return false;
}
/**
* Occurs on end of {@link ModelProcessingPhase} of source parsing.
*
* @param phase
* that was to be completed (finished)
* @throws SourceException
* when an error occurred in source parsing
*/
private void onPhaseCompleted(final ModelProcessingPhase phase) {
completedPhase = phase;
final Collection<OnPhaseFinished> listeners = phaseListeners.get(phase);
if (listeners.isEmpty()) {
return;
}
final Iterator<OnPhaseFinished> listener = listeners.iterator();
while (listener.hasNext()) {
final OnPhaseFinished next = listener.next();
if (next.phaseFinished(this, phase)) {
listener.remove();
}
}
if (listeners.isEmpty()) {
phaseListeners.removeAll(phase);
if (phaseListeners.isEmpty()) {
phaseListeners = ImmutableMultimap.of();
}
}
}
/**
* Ends declared section of current node.
*/
void endDeclared(final ModelProcessingPhase phase) {
definition().onDeclarationFinished(this, phase);
}
/**
* Return the context in which this statement was defined.
*
* @return statement definition
*/
protected final @NonNull StatementDefinitionContext<A, D, E> definition() {
return definition;
}
@Override
protected void checkLocalNamespaceAllowed(final Class<? extends IdentifierNamespace<?, ?>> type) {
definition().checkNamespaceAllowed(type);
}
@Override
protected <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceElementAdded(final Class<N> type, final K key,
final V value) {
// definition().onNamespaceElementAdded(this, type, key, value);
}
final <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceItemAddedAction(final Class<N> type, final K key,
final OnNamespaceItemAdded listener) {
final Object potential = getFromNamespace(type, key);
if (potential != null) {
LOG.trace("Listener on {} key {} satisfied immediately", type, key);
listener.namespaceItemAdded(this, type, key, potential);
return;
}
getBehaviour(type).addListener(new KeyedValueAddedListener<>(this, key) {
@Override
void onValueAdded(final Object value) {
listener.namespaceItemAdded(StatementContextBase.this, type, key, value);
}
});
}
final <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceItemAddedAction(final Class<N> type,
final ModelProcessingPhase phase, final NamespaceKeyCriterion<K> criterion,
final OnNamespaceItemAdded listener) {
final Optional<Entry<K, V>> existing = getFromNamespace(type, criterion);
if (existing.isPresent()) {
final Entry<K, V> entry = existing.get();
LOG.debug("Listener on {} criterion {} found a pre-existing match: {}", type, criterion, entry);
waitForPhase(entry.getValue(), type, phase, criterion, listener);
return;
}
final NamespaceBehaviourWithListeners<K, V, N> behaviour = getBehaviour(type);
behaviour.addListener(new PredicateValueAddedListener<K, V>(this) {
@Override
boolean onValueAdded(final K key, final V value) {
if (criterion.match(key)) {
LOG.debug("Listener on {} criterion {} matched added key {}", type, criterion, key);
waitForPhase(value, type, phase, criterion, listener);
return true;
}
return false;
}
});
}
final <K, V, N extends IdentifierNamespace<K, V>> void selectMatch(final Class<N> type,
final NamespaceKeyCriterion<K> criterion, final OnNamespaceItemAdded listener) {
final Optional<Entry<K, V>> optMatch = getFromNamespace(type, criterion);
checkState(optMatch.isPresent(), "Failed to find a match for criterion %s in namespace %s node %s", criterion,
type, this);
final Entry<K, V> match = optMatch.get();
listener.namespaceItemAdded(StatementContextBase.this, type, match.getKey(), match.getValue());
}
final <K, V, N extends IdentifierNamespace<K, V>> void waitForPhase(final Object value, final Class<N> type,
final ModelProcessingPhase phase, final NamespaceKeyCriterion<K> criterion,
final OnNamespaceItemAdded listener) {
((StatementContextBase<?, ? ,?>) value).addPhaseCompletedListener(phase,
(context, phaseCompleted) -> {
selectMatch(type, criterion, listener);
return true;
});
}
private <K, V, N extends IdentifierNamespace<K, V>> NamespaceBehaviourWithListeners<K, V, N> getBehaviour(
final Class<N> type) {
final NamespaceBehaviour<K, V, N> behaviour = getBehaviourRegistry().getNamespaceBehaviour(type);
checkArgument(behaviour instanceof NamespaceBehaviourWithListeners, "Namespace %s does not support listeners",
type);
return (NamespaceBehaviourWithListeners<K, V, N>) behaviour;
}
@Override
public StatementDefinition getPublicDefinition() {
return definition().getPublicView();
}
@Override
public ModelActionBuilder newInferenceAction(final ModelProcessingPhase phase) {
return getRoot().getSourceContext().newInferenceAction(phase);
}
private static <T> Multimap<ModelProcessingPhase, T> newMultimap() {
return Multimaps.newListMultimap(new EnumMap<>(ModelProcessingPhase.class), () -> new ArrayList<>(1));
}
/**
* Adds {@link OnPhaseFinished} listener for a {@link ModelProcessingPhase} end. If the base has already completed
* the listener is notified immediately.
*
* @param phase requested completion phase
* @param listener listener to invoke
* @throws NullPointerException if any of the arguments is null
*/
void addPhaseCompletedListener(final ModelProcessingPhase phase, final OnPhaseFinished listener) {
checkNotNull(phase, "Statement context processing phase cannot be null at: %s", getStatementSourceReference());
checkNotNull(listener, "Statement context phase listener cannot be null at: %s", getStatementSourceReference());
ModelProcessingPhase finishedPhase = completedPhase;
while (finishedPhase != null) {
if (phase.equals(finishedPhase)) {
listener.phaseFinished(this, finishedPhase);
return;
}
finishedPhase = finishedPhase.getPreviousPhase();
}
if (phaseListeners.isEmpty()) {
phaseListeners = newMultimap();
}
phaseListeners.put(phase, listener);
}
/**
* Adds a {@link ContextMutation} to a {@link ModelProcessingPhase}.
*
* @throws IllegalStateException
* when the mutation was registered after phase was completed
*/
void addMutation(final ModelProcessingPhase phase, final ContextMutation mutation) {
ModelProcessingPhase finishedPhase = completedPhase;
while (finishedPhase != null) {
checkState(!phase.equals(finishedPhase), "Mutation registered after phase was completed at: %s",
getStatementSourceReference());
finishedPhase = finishedPhase.getPreviousPhase();
}
if (phaseMutation.isEmpty()) {
phaseMutation = newMultimap();
}
phaseMutation.put(phase, mutation);
}
@Override
public <K, KT extends K, N extends StatementNamespace<K, ?, ?>> void addContext(final Class<N> namespace,
final KT key,final StmtContext<?, ?, ?> stmt) {
addContextToNamespace(namespace, key, stmt);
}
@Override
public final Mutable<?, ?, ?> childCopyOf(final StmtContext<?, ?, ?> stmt, final CopyType type,
final QNameModule targetModule) {
checkState(stmt.getCompletedPhase() == ModelProcessingPhase.EFFECTIVE_MODEL,
"Attempted to copy statement %s which has completed phase %s", stmt, stmt.getCompletedPhase());
checkArgument(stmt instanceof SubstatementContext, "Unsupported statement %s", stmt);
return childCopyOf((SubstatementContext<?, ?, ?>) stmt, type, targetModule);
}
private <X, Y extends DeclaredStatement<X>, Z extends EffectiveStatement<X, Y>> Mutable<X, Y, Z> childCopyOf(
final SubstatementContext<X, Y, Z> original, final CopyType type, final QNameModule targetModule) {
final Optional<StatementSupport<?, ?, ?>> implicitParent = definition.getImplicitParentFor(
original.getPublicDefinition());
final SubstatementContext<X, Y, Z> result;
final SubstatementContext<X, Y, Z> copy;
if (implicitParent.isPresent()) {
final StatementDefinitionContext<?, ?, ?> def = new StatementDefinitionContext<>(implicitParent.get());
result = new SubstatementContext(this, def, original.getSourceReference(),
original.rawStatementArgument(), original.getStatementArgument(), type);
final CopyType childCopyType;
switch (type) {
case ADDED_BY_AUGMENTATION:
childCopyType = CopyType.ORIGINAL;
break;
case ADDED_BY_USES_AUGMENTATION:
childCopyType = CopyType.ADDED_BY_USES;
break;
case ADDED_BY_USES:
case ORIGINAL:
default:
childCopyType = type;
}
copy = new SubstatementContext<>(original, result, childCopyType, targetModule);
result.addEffectiveSubstatement(copy);
} else {
result = copy = new SubstatementContext<>(original, this, type, targetModule);
}
original.definition().onStatementAdded(copy);
original.copyTo(copy, type, targetModule);
return result;
}
@Override
public @NonNull StatementDefinition getDefinition() {
return getPublicDefinition();
}
@Override
public @NonNull StatementSourceReference getSourceReference() {
return getStatementSourceReference();
}
@Override
public boolean isFullyDefined() {
return fullyDefined;
}
@Beta
public final boolean hasImplicitParentSupport() {
return definition.getFactory() instanceof ImplicitParentAwareStatementSupport;
}
@Beta
public final StatementContextBase<?, ?, ?> wrapWithImplicit(final StatementContextBase<?, ?, ?> original) {
final Optional<StatementSupport<?, ?, ?>> optImplicit = definition.getImplicitParentFor(
original.getPublicDefinition());
if (optImplicit.isEmpty()) {
return original;
}
final StatementDefinitionContext<?, ?, ?> def = new StatementDefinitionContext<>(optImplicit.get());
final CopyType type = original.getCopyHistory().getLastOperation();
final SubstatementContext<?, ?, ?> result = new SubstatementContext(original.getParentContext(), def,
original.getStatementSourceReference(), original.rawStatementArgument(), original.getStatementArgument(),
type);
result.addEffectiveSubstatement(new SubstatementContext<>(original, result));
result.setCompletedPhase(original.getCompletedPhase());
return result;
}
/**
* Config statements are not all that common which means we are performing a recursive search towards the root
* every time {@link #isConfiguration()} is invoked. This is quite expensive because it causes a linear search
* for the (usually non-existent) config statement.
*
* <p>
* This method maintains a resolution cache, so once we have returned a result, we will keep on returning the same
* result without performing any lookups, solely to support {@link SubstatementContext#isConfiguration()}.
*
* <p>
* Note: use of this method implies that {@link #isIgnoringConfig()} is realized with
* {@link #isIgnoringConfig(StatementContextBase)}.
*/
final boolean isConfiguration(final StatementContextBase<?, ?, ?> parent) {
final int fl = flags & SET_CONFIGURATION;
if (fl != 0) {
return fl == SET_CONFIGURATION;
}
if (isIgnoringConfig(parent)) {
// Note: SET_CONFIGURATION has been stored in flags
return true;
}
final StmtContext<Boolean, ?, ?> configStatement = StmtContextUtils.findFirstSubstatement(this,
ConfigStatement.class);
final boolean isConfig;
if (configStatement != null) {
isConfig = configStatement.coerceStatementArgument();
if (isConfig) {
// Validity check: if parent is config=false this cannot be a config=true
InferenceException.throwIf(!parent.isConfiguration(), getStatementSourceReference(),
"Parent node has config=false, this node must not be specifed as config=true");
}
} else {
// If "config" statement is not specified, the default is the same as the parent's "config" value.
isConfig = parent.isConfiguration();
}
// Resolved, make sure we cache this return
flags |= isConfig ? SET_CONFIGURATION : HAVE_CONFIGURATION;
return isConfig;
}
protected abstract boolean isIgnoringConfig();
/**
* This method maintains a resolution cache for ignore config, so once we have returned a result, we will
* keep on returning the same result without performing any lookups. Exists only to support
* {@link SubstatementContext#isIgnoringConfig()}.
*
* <p>
* Note: use of this method implies that {@link #isConfiguration()} is realized with
* {@link #isConfiguration(StatementContextBase)}.
*/
final boolean isIgnoringConfig(final StatementContextBase<?, ?, ?> parent) {
final int fl = flags & SET_IGNORE_CONFIG;
if (fl != 0) {
return fl == SET_IGNORE_CONFIG;
}
if (definition().isIgnoringConfig() || parent.isIgnoringConfig()) {
flags |= SET_IGNORE_CONFIG;
return true;
}
flags |= HAVE_IGNORE_CONFIG;
return false;
}
protected abstract boolean isIgnoringIfFeatures();
/**
* This method maintains a resolution cache for ignore if-feature, so once we have returned a result, we will
* keep on returning the same result without performing any lookups. Exists only to support
* {@link SubstatementContext#isIgnoringIfFeatures()}.
*/
final boolean isIgnoringIfFeatures(final StatementContextBase<?, ?, ?> parent) {
final int fl = flags & SET_IGNORE_IF_FEATURE;
if (fl != 0) {
return fl == SET_IGNORE_IF_FEATURE;
}
if (definition().isIgnoringIfFeatures() || parent.isIgnoringIfFeatures()) {
flags |= SET_IGNORE_IF_FEATURE;
return true;
}
flags |= HAVE_IGNORE_IF_FEATURE;
return false;
}
final void copyTo(final StatementContextBase<?, ?, ?> target, final CopyType typeOfCopy,
@Nullable final QNameModule targetModule) {
final Collection<Mutable<?, ?, ?>> buffer = new ArrayList<>(substatements.size() + effective.size());
for (final Mutable<?, ?, ?> stmtContext : substatements.values()) {
if (stmtContext.isSupportedByFeatures()) {
copySubstatement(stmtContext, target, typeOfCopy, targetModule, buffer);
}
}
for (final Mutable<?, ?, ?> stmtContext : effective) {
copySubstatement(stmtContext, target, typeOfCopy, targetModule, buffer);
}
target.addEffectiveSubstatements(buffer);
}
private void copySubstatement(final Mutable<?, ?, ?> stmtContext, final Mutable<?, ?, ?> target,
final CopyType typeOfCopy, final QNameModule newQNameModule, final Collection<Mutable<?, ?, ?>> buffer) {
if (needToCopyByUses(stmtContext)) {
final Mutable<?, ?, ?> copy = target.childCopyOf(stmtContext, typeOfCopy, newQNameModule);
LOG.debug("Copying substatement {} for {} as {}", stmtContext, this, copy);
buffer.add(copy);
} else if (isReusedByUses(stmtContext)) {
LOG.debug("Reusing substatement {} for {}", stmtContext, this);
buffer.add(stmtContext);
} else {
LOG.debug("Skipping statement {}", stmtContext);
}
}
// FIXME: revise this, as it seems to be wrong
private static final ImmutableSet<YangStmtMapping> NOCOPY_FROM_GROUPING_SET = ImmutableSet.of(
YangStmtMapping.DESCRIPTION,
YangStmtMapping.REFERENCE,
YangStmtMapping.STATUS);
private static final ImmutableSet<YangStmtMapping> REUSED_DEF_SET = ImmutableSet.of(
YangStmtMapping.TYPE,
YangStmtMapping.TYPEDEF,
YangStmtMapping.USES);
private static boolean needToCopyByUses(final StmtContext<?, ?, ?> stmtContext) {
final StatementDefinition def = stmtContext.getPublicDefinition();
if (REUSED_DEF_SET.contains(def)) {
LOG.debug("Will reuse {} statement {}", def, stmtContext);
return false;
}
if (NOCOPY_FROM_GROUPING_SET.contains(def)) {
return !YangStmtMapping.GROUPING.equals(stmtContext.coerceParentContext().getPublicDefinition());
}
LOG.debug("Will copy {} statement {}", def, stmtContext);
return true;
}
private static boolean isReusedByUses(final StmtContext<?, ?, ?> stmtContext) {
return REUSED_DEF_SET.contains(stmtContext.getPublicDefinition());
}
@Override
public final String toString() {
return addToStringAttributes(MoreObjects.toStringHelper(this).omitNullValues()).toString();
}
protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
return toStringHelper.add("definition", definition).add("rawArgument", rawArgument);
}
}
|
yang/yang-parser-reactor/src/main/java/org/opendaylight/yangtools/yang/parser/stmt/reactor/StatementContextBase.java
|
/*
* Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
package org.opendaylight.yangtools.yang.parser.stmt.reactor;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import static java.util.Objects.requireNonNull;
import com.google.common.annotations.Beta;
import com.google.common.base.MoreObjects;
import com.google.common.base.MoreObjects.ToStringHelper;
import com.google.common.collect.ImmutableCollection;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMultimap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Multimap;
import com.google.common.collect.Multimaps;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.EnumMap;
import java.util.EventListener;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import org.eclipse.jdt.annotation.NonNull;
import org.eclipse.jdt.annotation.Nullable;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.common.QNameModule;
import org.opendaylight.yangtools.yang.model.api.YangStmtMapping;
import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
import org.opendaylight.yangtools.yang.model.api.meta.IdentifierNamespace;
import org.opendaylight.yangtools.yang.model.api.meta.StatementDefinition;
import org.opendaylight.yangtools.yang.model.api.meta.StatementSource;
import org.opendaylight.yangtools.yang.model.api.stmt.ConfigStatement;
import org.opendaylight.yangtools.yang.parser.spi.meta.CopyHistory;
import org.opendaylight.yangtools.yang.parser.spi.meta.CopyType;
import org.opendaylight.yangtools.yang.parser.spi.meta.ImplicitParentAwareStatementSupport;
import org.opendaylight.yangtools.yang.parser.spi.meta.InferenceException;
import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder;
import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour;
import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceKeyCriterion;
import org.opendaylight.yangtools.yang.parser.spi.meta.StatementNamespace;
import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupport;
import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext.Mutable;
import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils;
import org.opendaylight.yangtools.yang.parser.spi.source.ImplicitSubstatement;
import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
import org.opendaylight.yangtools.yang.parser.spi.source.StatementSourceReference;
import org.opendaylight.yangtools.yang.parser.spi.source.StatementWriter.ResumedStatement;
import org.opendaylight.yangtools.yang.parser.spi.source.SupportedFeaturesNamespace;
import org.opendaylight.yangtools.yang.parser.spi.source.SupportedFeaturesNamespace.SupportedFeatures;
import org.opendaylight.yangtools.yang.parser.stmt.reactor.NamespaceBehaviourWithListeners.KeyedValueAddedListener;
import org.opendaylight.yangtools.yang.parser.stmt.reactor.NamespaceBehaviourWithListeners.PredicateValueAddedListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public abstract class StatementContextBase<A, D extends DeclaredStatement<A>, E extends EffectiveStatement<A, D>>
extends NamespaceStorageSupport implements Mutable<A, D, E>, ResumedStatement {
/**
* Event listener when an item is added to model namespace.
*/
interface OnNamespaceItemAdded extends EventListener {
/**
* Invoked whenever a new item is added to a namespace.
*/
void namespaceItemAdded(StatementContextBase<?, ?, ?> context, Class<?> namespace, Object key, Object value);
}
/**
* Event listener when a parsing {@link ModelProcessingPhase} is completed.
*/
interface OnPhaseFinished extends EventListener {
/**
* Invoked whenever a processing phase has finished.
*/
boolean phaseFinished(StatementContextBase<?, ?, ?> context, ModelProcessingPhase finishedPhase);
}
/**
* Interface for all mutations within an {@link ModelActionBuilder.InferenceAction}.
*/
interface ContextMutation {
boolean isFinished();
}
private static final Logger LOG = LoggerFactory.getLogger(StatementContextBase.class);
// Flag bit assignments
private static final int IS_SUPPORTED_BY_FEATURES = 0x01;
private static final int HAVE_SUPPORTED_BY_FEATURES = 0x02;
private static final int IS_CONFIGURATION = 0x04;
private static final int HAVE_CONFIGURATION = 0x08;
private static final int IS_IGNORE_CONFIG = 0x10;
private static final int HAVE_IGNORE_CONFIG = 0x20;
private static final int IS_IGNORE_IF_FEATURE = 0x40;
private static final int HAVE_IGNORE_IF_FEATURE = 0x80;
// Have-and-set flag constants, also used as masks
private static final int SET_SUPPORTED_BY_FEATURES = HAVE_SUPPORTED_BY_FEATURES | IS_SUPPORTED_BY_FEATURES;
private static final int SET_CONFIGURATION = HAVE_CONFIGURATION | IS_CONFIGURATION;
private static final int SET_IGNORE_CONFIG = HAVE_IGNORE_CONFIG | IS_IGNORE_CONFIG;
private static final int SET_IGNORE_IF_FEATURE = HAVE_IGNORE_IF_FEATURE | IS_IGNORE_IF_FEATURE;
private final @NonNull StatementDefinitionContext<A, D, E> definition;
private final @NonNull StatementSourceReference statementDeclSource;
private final StmtContext<?, ?, ?> originalCtx;
private final StmtContext<?, ?, ?> prevCopyCtx;
private final CopyHistory copyHistory;
private final String rawArgument;
private Multimap<ModelProcessingPhase, OnPhaseFinished> phaseListeners = ImmutableMultimap.of();
private Multimap<ModelProcessingPhase, ContextMutation> phaseMutation = ImmutableMultimap.of();
private List<Mutable<?, ?, ?>> effective = ImmutableList.of();
private List<StmtContext<?, ?, ?>> effectOfStatement = ImmutableList.of();
private StatementMap substatements = StatementMap.empty();
private @Nullable ModelProcessingPhase completedPhase;
private @Nullable D declaredInstance;
private @Nullable E effectiveInstance;
// Common state bits
private boolean isSupportedToBuildEffective = true;
private boolean fullyDefined;
// Flags for use with SubstatementContext. These are hiding in the alignment shadow created by above booleans and
// hence improve memory layout.
private byte flags;
StatementContextBase(final StatementDefinitionContext<A, D, E> def, final StatementSourceReference ref,
final String rawArgument) {
this.definition = requireNonNull(def);
this.statementDeclSource = requireNonNull(ref);
this.rawArgument = def.internArgument(rawArgument);
this.copyHistory = CopyHistory.original();
this.originalCtx = null;
this.prevCopyCtx = null;
}
StatementContextBase(final StatementDefinitionContext<A, D, E> def, final StatementSourceReference ref,
final String rawArgument, final CopyType copyType) {
this.definition = requireNonNull(def);
this.statementDeclSource = requireNonNull(ref);
this.rawArgument = rawArgument;
this.copyHistory = CopyHistory.of(copyType, CopyHistory.original());
this.originalCtx = null;
this.prevCopyCtx = null;
}
StatementContextBase(final StatementContextBase<A, D, E> original, final CopyType copyType) {
this.definition = original.definition;
this.statementDeclSource = original.statementDeclSource;
this.rawArgument = original.rawArgument;
this.copyHistory = CopyHistory.of(copyType, original.getCopyHistory());
this.originalCtx = original.getOriginalCtx().orElse(original);
this.prevCopyCtx = original;
}
StatementContextBase(final StatementContextBase<A, D, E> original) {
this.definition = original.definition;
this.statementDeclSource = original.statementDeclSource;
this.rawArgument = original.rawArgument;
this.copyHistory = original.getCopyHistory();
this.originalCtx = original.getOriginalCtx().orElse(original);
this.prevCopyCtx = original;
this.substatements = original.substatements;
this.effective = original.effective;
}
@Override
public Collection<? extends StmtContext<?, ?, ?>> getEffectOfStatement() {
return effectOfStatement;
}
@Override
public void addAsEffectOfStatement(final StmtContext<?, ?, ?> ctx) {
if (effectOfStatement.isEmpty()) {
effectOfStatement = new ArrayList<>(1);
}
effectOfStatement.add(ctx);
}
@Override
public void addAsEffectOfStatement(final Collection<? extends StmtContext<?, ?, ?>> ctxs) {
if (ctxs.isEmpty()) {
return;
}
if (effectOfStatement.isEmpty()) {
effectOfStatement = new ArrayList<>(ctxs.size());
}
effectOfStatement.addAll(ctxs);
}
@Override
public boolean isSupportedByFeatures() {
final int fl = flags & SET_SUPPORTED_BY_FEATURES;
if (fl != 0) {
return fl == SET_SUPPORTED_BY_FEATURES;
}
if (isIgnoringIfFeatures()) {
flags |= SET_SUPPORTED_BY_FEATURES;
return true;
}
/*
* If parent is supported, we need to check if-features statements of this context.
*/
if (isParentSupportedByFeatures()) {
// If the set of supported features has not been provided, all features are supported by default.
final Set<QName> supportedFeatures = getFromNamespace(SupportedFeaturesNamespace.class,
SupportedFeatures.SUPPORTED_FEATURES);
if (supportedFeatures == null || StmtContextUtils.checkFeatureSupport(this, supportedFeatures)) {
flags |= SET_SUPPORTED_BY_FEATURES;
return true;
}
}
// Either parent is not supported or this statement is not supported
flags |= HAVE_SUPPORTED_BY_FEATURES;
return false;
}
protected abstract boolean isParentSupportedByFeatures();
@Override
public boolean isSupportedToBuildEffective() {
return isSupportedToBuildEffective;
}
@Override
public void setIsSupportedToBuildEffective(final boolean isSupportedToBuildEffective) {
this.isSupportedToBuildEffective = isSupportedToBuildEffective;
}
@Override
public CopyHistory getCopyHistory() {
return copyHistory;
}
@Override
public Optional<StmtContext<?, ?, ?>> getOriginalCtx() {
return Optional.ofNullable(originalCtx);
}
@Override
public Optional<? extends StmtContext<?, ?, ?>> getPreviousCopyCtx() {
return Optional.ofNullable(prevCopyCtx);
}
@Override
public ModelProcessingPhase getCompletedPhase() {
return completedPhase;
}
@Override
public void setCompletedPhase(final ModelProcessingPhase completedPhase) {
this.completedPhase = completedPhase;
}
@Override
public abstract StatementContextBase<?, ?, ?> getParentContext();
/**
* Returns the model root for this statement.
*
* @return root context of statement
*/
@Override
public abstract RootStatementContext<?, ?, ?> getRoot();
@Override
public StatementSource getStatementSource() {
return statementDeclSource.getStatementSource();
}
@Override
public StatementSourceReference getStatementSourceReference() {
return statementDeclSource;
}
@Override
public final String rawStatementArgument() {
return rawArgument;
}
@Override
public Collection<? extends StmtContext<?, ?, ?>> declaredSubstatements() {
return substatements.values();
}
@Override
public Collection<? extends Mutable<?, ?, ?>> mutableDeclaredSubstatements() {
return substatements.values();
}
@Override
public Collection<? extends StmtContext<?, ?, ?>> effectiveSubstatements() {
return mutableEffectiveSubstatements();
}
@Override
public Collection<? extends Mutable<?, ?, ?>> mutableEffectiveSubstatements() {
if (effective instanceof ImmutableCollection) {
return effective;
}
return Collections.unmodifiableCollection(effective);
}
private void shrinkEffective() {
if (effective.isEmpty()) {
effective = ImmutableList.of();
}
}
public void removeStatementFromEffectiveSubstatements(final StatementDefinition statementDef) {
if (effective.isEmpty()) {
return;
}
final Iterator<? extends StmtContext<?, ?, ?>> iterator = effective.iterator();
while (iterator.hasNext()) {
final StmtContext<?, ?, ?> next = iterator.next();
if (statementDef.equals(next.getPublicDefinition())) {
iterator.remove();
}
}
shrinkEffective();
}
/**
* Removes a statement context from the effective substatements based on its statement definition (i.e statement
* keyword) and raw (in String form) statement argument. The statement context is removed only if both statement
* definition and statement argument match with one of the effective substatements' statement definition
* and argument.
*
* <p>
* If the statementArg parameter is null, the statement context is removed based only on its statement definition.
*
* @param statementDef statement definition of the statement context to remove
* @param statementArg statement argument of the statement context to remove
*/
public void removeStatementFromEffectiveSubstatements(final StatementDefinition statementDef,
final String statementArg) {
if (statementArg == null) {
removeStatementFromEffectiveSubstatements(statementDef);
}
if (effective.isEmpty()) {
return;
}
final Iterator<Mutable<?, ?, ?>> iterator = effective.iterator();
while (iterator.hasNext()) {
final Mutable<?, ?, ?> next = iterator.next();
if (statementDef.equals(next.getPublicDefinition()) && statementArg.equals(next.rawStatementArgument())) {
iterator.remove();
}
}
shrinkEffective();
}
/**
* Adds an effective statement to collection of substatements.
*
* @param substatement substatement
* @throws IllegalStateException
* if added in declared phase
* @throws NullPointerException
* if statement parameter is null
*/
public void addEffectiveSubstatement(final Mutable<?, ?, ?> substatement) {
beforeAddEffectiveStatement(1);
effective.add(substatement);
}
/**
* Adds an effective statement to collection of substatements.
*
* @param statements substatements
* @throws IllegalStateException
* if added in declared phase
* @throws NullPointerException
* if statement parameter is null
*/
public void addEffectiveSubstatements(final Collection<? extends Mutable<?, ?, ?>> statements) {
if (statements.isEmpty()) {
return;
}
statements.forEach(Objects::requireNonNull);
beforeAddEffectiveStatement(statements.size());
effective.addAll(statements);
}
private void beforeAddEffectiveStatement(final int toAdd) {
final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
checkState(inProgressPhase == ModelProcessingPhase.FULL_DECLARATION
|| inProgressPhase == ModelProcessingPhase.EFFECTIVE_MODEL,
"Effective statement cannot be added in declared phase at: %s", getStatementSourceReference());
if (effective.isEmpty()) {
effective = new ArrayList<>(toAdd);
}
}
/**
* Create a new substatement at the specified offset.
*
* @param offset Substatement offset
* @param def definition context
* @param ref source reference
* @param argument statement argument
* @param <X> new substatement argument type
* @param <Y> new substatement declared type
* @param <Z> new substatement effective type
* @return A new substatement
*/
@SuppressWarnings("checkstyle:methodTypeParameterName")
public final <X, Y extends DeclaredStatement<X>, Z extends EffectiveStatement<X, Y>>
StatementContextBase<X, Y, Z> createSubstatement(final int offset,
final StatementDefinitionContext<X, Y, Z> def, final StatementSourceReference ref,
final String argument) {
final ModelProcessingPhase inProgressPhase = getRoot().getSourceContext().getInProgressPhase();
checkState(inProgressPhase != ModelProcessingPhase.EFFECTIVE_MODEL,
"Declared statement cannot be added in effective phase at: %s", getStatementSourceReference());
final Optional<StatementSupport<?, ?, ?>> implicitParent = definition.getImplicitParentFor(def.getPublicView());
if (implicitParent.isPresent()) {
return createImplicitParent(offset, implicitParent.get(), ref, argument).createSubstatement(offset, def,
ref, argument);
}
final StatementContextBase<X, Y, Z> ret = new SubstatementContext<>(this, def, ref, argument);
substatements = substatements.put(offset, ret);
def.onStatementAdded(ret);
return ret;
}
private StatementContextBase<?, ?, ?> createImplicitParent(final int offset,
final StatementSupport<?, ?, ?> implicitParent, final StatementSourceReference ref, final String argument) {
final StatementDefinitionContext<?, ?, ?> def = new StatementDefinitionContext<>(implicitParent);
return createSubstatement(offset, def, ImplicitSubstatement.of(ref), argument);
}
public void appendImplicitStatement(final StatementSupport<?, ?, ?> statementToAdd) {
createSubstatement(substatements.capacity(), new StatementDefinitionContext<>(statementToAdd),
ImplicitSubstatement.of(getStatementSourceReference()), null);
}
/**
* Lookup substatement by its offset in this statement.
*
* @param offset Substatement offset
* @return Substatement, or null if substatement does not exist.
*/
final StatementContextBase<?, ?, ?> lookupSubstatement(final int offset) {
return substatements.get(offset);
}
final void setFullyDefined() {
this.fullyDefined = true;
}
final void resizeSubstatements(final int expectedSize) {
substatements = substatements.ensureCapacity(expectedSize);
}
final void walkChildren(final ModelProcessingPhase phase) {
checkState(fullyDefined);
substatements.values().forEach(stmt -> {
stmt.walkChildren(phase);
stmt.endDeclared(phase);
});
}
@Override
public D buildDeclared() {
checkArgument(completedPhase == ModelProcessingPhase.FULL_DECLARATION
|| completedPhase == ModelProcessingPhase.EFFECTIVE_MODEL);
if (declaredInstance == null) {
declaredInstance = definition().getFactory().createDeclared(this);
}
return declaredInstance;
}
@Override
public E buildEffective() {
if (effectiveInstance == null) {
effectiveInstance = definition().getFactory().createEffective(this);
}
return effectiveInstance;
}
/**
* tries to execute current {@link ModelProcessingPhase} of source parsing.
*
* @param phase
* to be executed (completed)
* @return if phase was successfully completed
* @throws SourceException
* when an error occurred in source parsing
*/
boolean tryToCompletePhase(final ModelProcessingPhase phase) {
boolean finished = true;
final Collection<ContextMutation> openMutations = phaseMutation.get(phase);
if (!openMutations.isEmpty()) {
final Iterator<ContextMutation> it = openMutations.iterator();
while (it.hasNext()) {
final ContextMutation current = it.next();
if (current.isFinished()) {
it.remove();
} else {
finished = false;
}
}
if (openMutations.isEmpty()) {
phaseMutation.removeAll(phase);
if (phaseMutation.isEmpty()) {
phaseMutation = ImmutableMultimap.of();
}
}
}
for (final StatementContextBase<?, ?, ?> child : substatements.values()) {
finished &= child.tryToCompletePhase(phase);
}
for (final Mutable<?, ?, ?> child : effective) {
if (child instanceof StatementContextBase) {
finished &= ((StatementContextBase<?, ?, ?>) child).tryToCompletePhase(phase);
}
}
if (finished) {
onPhaseCompleted(phase);
return true;
}
return false;
}
/**
* Occurs on end of {@link ModelProcessingPhase} of source parsing.
*
* @param phase
* that was to be completed (finished)
* @throws SourceException
* when an error occurred in source parsing
*/
private void onPhaseCompleted(final ModelProcessingPhase phase) {
completedPhase = phase;
final Collection<OnPhaseFinished> listeners = phaseListeners.get(phase);
if (listeners.isEmpty()) {
return;
}
final Iterator<OnPhaseFinished> listener = listeners.iterator();
while (listener.hasNext()) {
final OnPhaseFinished next = listener.next();
if (next.phaseFinished(this, phase)) {
listener.remove();
}
}
if (listeners.isEmpty()) {
phaseListeners.removeAll(phase);
if (phaseListeners.isEmpty()) {
phaseListeners = ImmutableMultimap.of();
}
}
}
/**
* Ends declared section of current node.
*/
void endDeclared(final ModelProcessingPhase phase) {
definition().onDeclarationFinished(this, phase);
}
/**
* Return the context in which this statement was defined.
*
* @return statement definition
*/
protected final @NonNull StatementDefinitionContext<A, D, E> definition() {
return definition;
}
@Override
protected void checkLocalNamespaceAllowed(final Class<? extends IdentifierNamespace<?, ?>> type) {
definition().checkNamespaceAllowed(type);
}
@Override
protected <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceElementAdded(final Class<N> type, final K key,
final V value) {
// definition().onNamespaceElementAdded(this, type, key, value);
}
final <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceItemAddedAction(final Class<N> type, final K key,
final OnNamespaceItemAdded listener) {
final Object potential = getFromNamespace(type, key);
if (potential != null) {
LOG.trace("Listener on {} key {} satisfied immediately", type, key);
listener.namespaceItemAdded(this, type, key, potential);
return;
}
getBehaviour(type).addListener(new KeyedValueAddedListener<>(this, key) {
@Override
void onValueAdded(final Object value) {
listener.namespaceItemAdded(StatementContextBase.this, type, key, value);
}
});
}
final <K, V, N extends IdentifierNamespace<K, V>> void onNamespaceItemAddedAction(final Class<N> type,
final ModelProcessingPhase phase, final NamespaceKeyCriterion<K> criterion,
final OnNamespaceItemAdded listener) {
final Optional<Entry<K, V>> existing = getFromNamespace(type, criterion);
if (existing.isPresent()) {
final Entry<K, V> entry = existing.get();
LOG.debug("Listener on {} criterion {} found a pre-existing match: {}", type, criterion, entry);
waitForPhase(entry.getValue(), type, phase, criterion, listener);
return;
}
final NamespaceBehaviourWithListeners<K, V, N> behaviour = getBehaviour(type);
behaviour.addListener(new PredicateValueAddedListener<K, V>(this) {
@Override
boolean onValueAdded(final K key, final V value) {
if (criterion.match(key)) {
LOG.debug("Listener on {} criterion {} matched added key {}", type, criterion, key);
waitForPhase(value, type, phase, criterion, listener);
return true;
}
return false;
}
});
}
final <K, V, N extends IdentifierNamespace<K, V>> void selectMatch(final Class<N> type,
final NamespaceKeyCriterion<K> criterion, final OnNamespaceItemAdded listener) {
final Optional<Entry<K, V>> optMatch = getFromNamespace(type, criterion);
checkState(optMatch.isPresent(), "Failed to find a match for criterion %s in namespace %s node %s", criterion,
type, this);
final Entry<K, V> match = optMatch.get();
listener.namespaceItemAdded(StatementContextBase.this, type, match.getKey(), match.getValue());
}
final <K, V, N extends IdentifierNamespace<K, V>> void waitForPhase(final Object value, final Class<N> type,
final ModelProcessingPhase phase, final NamespaceKeyCriterion<K> criterion,
final OnNamespaceItemAdded listener) {
((StatementContextBase<?, ? ,?>) value).addPhaseCompletedListener(phase,
(context, phaseCompleted) -> {
selectMatch(type, criterion, listener);
return true;
});
}
private <K, V, N extends IdentifierNamespace<K, V>> NamespaceBehaviourWithListeners<K, V, N> getBehaviour(
final Class<N> type) {
final NamespaceBehaviour<K, V, N> behaviour = getBehaviourRegistry().getNamespaceBehaviour(type);
checkArgument(behaviour instanceof NamespaceBehaviourWithListeners, "Namespace %s does not support listeners",
type);
return (NamespaceBehaviourWithListeners<K, V, N>) behaviour;
}
@Override
public StatementDefinition getPublicDefinition() {
return definition().getPublicView();
}
@Override
public ModelActionBuilder newInferenceAction(final ModelProcessingPhase phase) {
return getRoot().getSourceContext().newInferenceAction(phase);
}
private static <T> Multimap<ModelProcessingPhase, T> newMultimap() {
return Multimaps.newListMultimap(new EnumMap<>(ModelProcessingPhase.class), () -> new ArrayList<>(1));
}
/**
* Adds {@link OnPhaseFinished} listener for a {@link ModelProcessingPhase} end. If the base has already completed
* the listener is notified immediately.
*
* @param phase requested completion phase
* @param listener listener to invoke
* @throws NullPointerException if any of the arguments is null
*/
void addPhaseCompletedListener(final ModelProcessingPhase phase, final OnPhaseFinished listener) {
checkNotNull(phase, "Statement context processing phase cannot be null at: %s", getStatementSourceReference());
checkNotNull(listener, "Statement context phase listener cannot be null at: %s", getStatementSourceReference());
ModelProcessingPhase finishedPhase = completedPhase;
while (finishedPhase != null) {
if (phase.equals(finishedPhase)) {
listener.phaseFinished(this, finishedPhase);
return;
}
finishedPhase = finishedPhase.getPreviousPhase();
}
if (phaseListeners.isEmpty()) {
phaseListeners = newMultimap();
}
phaseListeners.put(phase, listener);
}
/**
* Adds a {@link ContextMutation} to a {@link ModelProcessingPhase}.
*
* @throws IllegalStateException
* when the mutation was registered after phase was completed
*/
void addMutation(final ModelProcessingPhase phase, final ContextMutation mutation) {
ModelProcessingPhase finishedPhase = completedPhase;
while (finishedPhase != null) {
checkState(!phase.equals(finishedPhase), "Mutation registered after phase was completed at: %s",
getStatementSourceReference());
finishedPhase = finishedPhase.getPreviousPhase();
}
if (phaseMutation.isEmpty()) {
phaseMutation = newMultimap();
}
phaseMutation.put(phase, mutation);
}
@Override
public <K, KT extends K, N extends StatementNamespace<K, ?, ?>> void addContext(final Class<N> namespace,
final KT key,final StmtContext<?, ?, ?> stmt) {
addContextToNamespace(namespace, key, stmt);
}
@Override
public final Mutable<?, ?, ?> childCopyOf(final StmtContext<?, ?, ?> stmt, final CopyType type,
final QNameModule targetModule) {
checkState(stmt.getCompletedPhase() == ModelProcessingPhase.EFFECTIVE_MODEL,
"Attempted to copy statement %s which has completed phase %s", stmt, stmt.getCompletedPhase());
checkArgument(stmt instanceof SubstatementContext, "Unsupported statement %s", stmt);
return childCopyOf((SubstatementContext<?, ?, ?>) stmt, type, targetModule);
}
private <X, Y extends DeclaredStatement<X>, Z extends EffectiveStatement<X, Y>> Mutable<X, Y, Z> childCopyOf(
final SubstatementContext<X, Y, Z> original, final CopyType type, final QNameModule targetModule) {
final Optional<StatementSupport<?, ?, ?>> implicitParent = definition.getImplicitParentFor(
original.getPublicDefinition());
final SubstatementContext<X, Y, Z> result;
final SubstatementContext<X, Y, Z> copy;
if (implicitParent.isPresent()) {
final StatementDefinitionContext<?, ?, ?> def = new StatementDefinitionContext<>(implicitParent.get());
result = new SubstatementContext(this, def, original.getSourceReference(),
original.rawStatementArgument(), original.getStatementArgument(), type);
final CopyType childCopyType;
switch (type) {
case ADDED_BY_AUGMENTATION:
childCopyType = CopyType.ORIGINAL;
break;
case ADDED_BY_USES_AUGMENTATION:
childCopyType = CopyType.ADDED_BY_USES;
break;
case ADDED_BY_USES:
case ORIGINAL:
default:
childCopyType = type;
}
copy = new SubstatementContext<>(original, result, childCopyType, targetModule);
result.addEffectiveSubstatement(copy);
} else {
result = copy = new SubstatementContext<>(original, this, type, targetModule);
}
original.definition().onStatementAdded(copy);
original.copyTo(copy, type, targetModule);
return result;
}
@Override
public @NonNull StatementDefinition getDefinition() {
return getPublicDefinition();
}
@Override
public @NonNull StatementSourceReference getSourceReference() {
return getStatementSourceReference();
}
@Override
public boolean isFullyDefined() {
return fullyDefined;
}
@Beta
public final boolean hasImplicitParentSupport() {
return definition.getFactory() instanceof ImplicitParentAwareStatementSupport;
}
@Beta
public final StatementContextBase<?, ?, ?> wrapWithImplicit(final StatementContextBase<?, ?, ?> original) {
final Optional<StatementSupport<?, ?, ?>> optImplicit = definition.getImplicitParentFor(
original.getPublicDefinition());
if (optImplicit.isEmpty()) {
return original;
}
final StatementDefinitionContext<?, ?, ?> def = new StatementDefinitionContext<>(optImplicit.get());
final CopyType type = original.getCopyHistory().getLastOperation();
final SubstatementContext<?, ?, ?> result = new SubstatementContext(original.getParentContext(), def,
original.getStatementSourceReference(), original.rawStatementArgument(), original.getStatementArgument(),
type);
result.addEffectiveSubstatement(new SubstatementContext<>(original, result));
result.setCompletedPhase(original.getCompletedPhase());
return result;
}
/**
* Config statements are not all that common which means we are performing a recursive search towards the root
* every time {@link #isConfiguration()} is invoked. This is quite expensive because it causes a linear search
* for the (usually non-existent) config statement.
*
* <p>
* This method maintains a resolution cache, so once we have returned a result, we will keep on returning the same
* result without performing any lookups, solely to support {@link SubstatementContext#isConfiguration()}.
*/
final boolean isConfiguration(final StatementContextBase<?, ?, ?> parent) {
if (isIgnoringConfig()) {
return true;
}
final int fl = flags & SET_CONFIGURATION;
if (fl != 0) {
return fl == SET_CONFIGURATION;
}
final StmtContext<Boolean, ?, ?> configStatement = StmtContextUtils.findFirstSubstatement(this,
ConfigStatement.class);
final boolean parentIsConfig = parent.isConfiguration();
final boolean isConfig;
if (configStatement != null) {
isConfig = configStatement.coerceStatementArgument();
// Validity check: if parent is config=false this cannot be a config=true
InferenceException.throwIf(isConfig && !parentIsConfig, getStatementSourceReference(),
"Parent node has config=false, this node must not be specifed as config=true");
} else {
// If "config" statement is not specified, the default is the same as the parent's "config" value.
isConfig = parentIsConfig;
}
// Resolved, make sure we cache this return
flags |= isConfig ? SET_CONFIGURATION : HAVE_CONFIGURATION;
return isConfig;
}
protected abstract boolean isIgnoringConfig();
/**
* This method maintains a resolution cache for ignore config, so once we have returned a result, we will
* keep on returning the same result without performing any lookups. Exists only to support
* {@link SubstatementContext#isIgnoringConfig()}.
*/
final boolean isIgnoringConfig(final StatementContextBase<?, ?, ?> parent) {
final int fl = flags & SET_IGNORE_CONFIG;
if (fl != 0) {
return fl == SET_IGNORE_CONFIG;
}
if (definition().isIgnoringConfig() || parent.isIgnoringConfig()) {
flags |= SET_IGNORE_CONFIG;
return true;
}
flags |= HAVE_IGNORE_CONFIG;
return false;
}
protected abstract boolean isIgnoringIfFeatures();
/**
* This method maintains a resolution cache for ignore if-feature, so once we have returned a result, we will
* keep on returning the same result without performing any lookups. Exists only to support
* {@link SubstatementContext#isIgnoringIfFeatures()}.
*/
final boolean isIgnoringIfFeatures(final StatementContextBase<?, ?, ?> parent) {
final int fl = flags & SET_IGNORE_IF_FEATURE;
if (fl != 0) {
return fl == SET_IGNORE_IF_FEATURE;
}
if (definition().isIgnoringIfFeatures() || parent.isIgnoringIfFeatures()) {
flags |= SET_IGNORE_IF_FEATURE;
return true;
}
flags |= HAVE_IGNORE_IF_FEATURE;
return false;
}
final void copyTo(final StatementContextBase<?, ?, ?> target, final CopyType typeOfCopy,
@Nullable final QNameModule targetModule) {
final Collection<Mutable<?, ?, ?>> buffer = new ArrayList<>(substatements.size() + effective.size());
for (final Mutable<?, ?, ?> stmtContext : substatements.values()) {
if (stmtContext.isSupportedByFeatures()) {
copySubstatement(stmtContext, target, typeOfCopy, targetModule, buffer);
}
}
for (final Mutable<?, ?, ?> stmtContext : effective) {
copySubstatement(stmtContext, target, typeOfCopy, targetModule, buffer);
}
target.addEffectiveSubstatements(buffer);
}
private void copySubstatement(final Mutable<?, ?, ?> stmtContext, final Mutable<?, ?, ?> target,
final CopyType typeOfCopy, final QNameModule newQNameModule, final Collection<Mutable<?, ?, ?>> buffer) {
if (needToCopyByUses(stmtContext)) {
final Mutable<?, ?, ?> copy = target.childCopyOf(stmtContext, typeOfCopy, newQNameModule);
LOG.debug("Copying substatement {} for {} as {}", stmtContext, this, copy);
buffer.add(copy);
} else if (isReusedByUses(stmtContext)) {
LOG.debug("Reusing substatement {} for {}", stmtContext, this);
buffer.add(stmtContext);
} else {
LOG.debug("Skipping statement {}", stmtContext);
}
}
// FIXME: revise this, as it seems to be wrong
private static final ImmutableSet<YangStmtMapping> NOCOPY_FROM_GROUPING_SET = ImmutableSet.of(
YangStmtMapping.DESCRIPTION,
YangStmtMapping.REFERENCE,
YangStmtMapping.STATUS);
private static final ImmutableSet<YangStmtMapping> REUSED_DEF_SET = ImmutableSet.of(
YangStmtMapping.TYPE,
YangStmtMapping.TYPEDEF,
YangStmtMapping.USES);
private static boolean needToCopyByUses(final StmtContext<?, ?, ?> stmtContext) {
final StatementDefinition def = stmtContext.getPublicDefinition();
if (REUSED_DEF_SET.contains(def)) {
LOG.debug("Will reuse {} statement {}", def, stmtContext);
return false;
}
if (NOCOPY_FROM_GROUPING_SET.contains(def)) {
return !YangStmtMapping.GROUPING.equals(stmtContext.coerceParentContext().getPublicDefinition());
}
LOG.debug("Will copy {} statement {}", def, stmtContext);
return true;
}
private static boolean isReusedByUses(final StmtContext<?, ?, ?> stmtContext) {
return REUSED_DEF_SET.contains(stmtContext.getPublicDefinition());
}
@Override
public final String toString() {
return addToStringAttributes(MoreObjects.toStringHelper(this).omitNullValues()).toString();
}
protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
return toStringHelper.add("definition", definition).add("rawArgument", rawArgument);
}
}
|
Optimize isConfiguration()/isIgnoringConfig() interplay
Now that we have coalesced these two states into a flag field,
their interplay is more apparent -- isIgnoringConfig() is always
checked before isConfiguration() and if it is set, it also implies
isConfiguration() is also set.
Using flags allows us to express this implication by simply setting
the right bits. This results in fewer flag operations performed and
a more direct dispatch between methods.
isConfiguration() is also improved to access parent.isConfiguration()
only when necessary, improving performance when a config substatement
is present.
JIRA: YANGTOOLS-652
Change-Id: Ifb18ee16e33e93de4300cc80e4ba67a9ae40bbde
Signed-off-by: Robert Varga <[email protected]>
|
yang/yang-parser-reactor/src/main/java/org/opendaylight/yangtools/yang/parser/stmt/reactor/StatementContextBase.java
|
Optimize isConfiguration()/isIgnoringConfig() interplay
|
<ide><path>ang/yang-parser-reactor/src/main/java/org/opendaylight/yangtools/yang/parser/stmt/reactor/StatementContextBase.java
<ide> // Flag bit assignments
<ide> private static final int IS_SUPPORTED_BY_FEATURES = 0x01;
<ide> private static final int HAVE_SUPPORTED_BY_FEATURES = 0x02;
<del> private static final int IS_CONFIGURATION = 0x04;
<del> private static final int HAVE_CONFIGURATION = 0x08;
<add> private static final int IS_IGNORE_IF_FEATURE = 0x04;
<add> private static final int HAVE_IGNORE_IF_FEATURE = 0x08;
<add> // Note: these four are related
<ide> private static final int IS_IGNORE_CONFIG = 0x10;
<ide> private static final int HAVE_IGNORE_CONFIG = 0x20;
<del> private static final int IS_IGNORE_IF_FEATURE = 0x40;
<del> private static final int HAVE_IGNORE_IF_FEATURE = 0x80;
<add> private static final int IS_CONFIGURATION = 0x40;
<add> private static final int HAVE_CONFIGURATION = 0x80;
<ide>
<ide> // Have-and-set flag constants, also used as masks
<ide> private static final int SET_SUPPORTED_BY_FEATURES = HAVE_SUPPORTED_BY_FEATURES | IS_SUPPORTED_BY_FEATURES;
<ide> private static final int SET_CONFIGURATION = HAVE_CONFIGURATION | IS_CONFIGURATION;
<del> private static final int SET_IGNORE_CONFIG = HAVE_IGNORE_CONFIG | IS_IGNORE_CONFIG;
<add> // Note: implies SET_CONFIGURATION, allowing fewer bit operations to be performed
<add> private static final int SET_IGNORE_CONFIG = HAVE_IGNORE_CONFIG | IS_IGNORE_CONFIG | SET_CONFIGURATION;
<ide> private static final int SET_IGNORE_IF_FEATURE = HAVE_IGNORE_IF_FEATURE | IS_IGNORE_IF_FEATURE;
<ide>
<ide> private final @NonNull StatementDefinitionContext<A, D, E> definition;
<ide> * <p>
<ide> * This method maintains a resolution cache, so once we have returned a result, we will keep on returning the same
<ide> * result without performing any lookups, solely to support {@link SubstatementContext#isConfiguration()}.
<add> *
<add> * <p>
<add> * Note: use of this method implies that {@link #isIgnoringConfig()} is realized with
<add> * {@link #isIgnoringConfig(StatementContextBase)}.
<ide> */
<ide> final boolean isConfiguration(final StatementContextBase<?, ?, ?> parent) {
<del> if (isIgnoringConfig()) {
<del> return true;
<del> }
<ide> final int fl = flags & SET_CONFIGURATION;
<ide> if (fl != 0) {
<ide> return fl == SET_CONFIGURATION;
<ide> }
<add> if (isIgnoringConfig(parent)) {
<add> // Note: SET_CONFIGURATION has been stored in flags
<add> return true;
<add> }
<add>
<ide> final StmtContext<Boolean, ?, ?> configStatement = StmtContextUtils.findFirstSubstatement(this,
<ide> ConfigStatement.class);
<del> final boolean parentIsConfig = parent.isConfiguration();
<del>
<ide> final boolean isConfig;
<ide> if (configStatement != null) {
<ide> isConfig = configStatement.coerceStatementArgument();
<del>
<del> // Validity check: if parent is config=false this cannot be a config=true
<del> InferenceException.throwIf(isConfig && !parentIsConfig, getStatementSourceReference(),
<del> "Parent node has config=false, this node must not be specifed as config=true");
<add> if (isConfig) {
<add> // Validity check: if parent is config=false this cannot be a config=true
<add> InferenceException.throwIf(!parent.isConfiguration(), getStatementSourceReference(),
<add> "Parent node has config=false, this node must not be specifed as config=true");
<add> }
<ide> } else {
<ide> // If "config" statement is not specified, the default is the same as the parent's "config" value.
<del> isConfig = parentIsConfig;
<add> isConfig = parent.isConfiguration();
<ide> }
<ide>
<ide> // Resolved, make sure we cache this return
<ide> * This method maintains a resolution cache for ignore config, so once we have returned a result, we will
<ide> * keep on returning the same result without performing any lookups. Exists only to support
<ide> * {@link SubstatementContext#isIgnoringConfig()}.
<add> *
<add> * <p>
<add> * Note: use of this method implies that {@link #isConfiguration()} is realized with
<add> * {@link #isConfiguration(StatementContextBase)}.
<ide> */
<ide> final boolean isIgnoringConfig(final StatementContextBase<?, ?, ?> parent) {
<ide> final int fl = flags & SET_IGNORE_CONFIG;
|
|
JavaScript
|
mit
|
5a6017a8150ec0e77596f9461c3441493f0e611e
| 0 |
TossShinHwa/node-odata
|
export default (req, MongooseModel) => new Promise((resolve, reject) => {
MongooseModel.findById(req.params.id, (err, entity) => {
if (err) {
return reject(err);
}
if (!entity) {
return reject({ status: 404 }, { text: 'Not Found' });
}
return resolve({ entity });
});
});
|
src/rest/get.js
|
export default (req, MongooseModel) => new Promise((resolve, reject) => {
MongooseModel.findById(req.params.id, (err, entity) => {
if (err) {
return reject(err);
}
if (!entity) {
return reject({ status: 404 }, { text: 'Not Found' });
}
return resolve({ entity });
});
});
|
refactor(test): convert CRLF to LF linebreaks.
|
src/rest/get.js
|
refactor(test): convert CRLF to LF linebreaks.
| ||
Java
|
apache-2.0
|
c7550cb6a96927e0ccc540b344263bfdb0dd8655
| 0 |
davidwatkins73/waltz-dev,kamransaleem/waltz,davidwatkins73/waltz-dev,rovats/waltz,davidwatkins73/waltz-dev,khartec/waltz,rovats/waltz,rovats/waltz,khartec/waltz,rovats/waltz,khartec/waltz,kamransaleem/waltz,kamransaleem/waltz,davidwatkins73/waltz-dev,khartec/waltz,kamransaleem/waltz
|
/*
* Waltz - Enterprise Architecture
* Copyright (C) 2016, 2017 Waltz open source project
* See README.md for more information
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.khartec.waltz.model.server_usage;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.khartec.waltz.model.EntityReference;
import com.khartec.waltz.model.LastUpdatedProvider;
import com.khartec.waltz.model.ProvenanceProvider;
import org.immutables.value.Value;
@Value.Immutable
@JsonSerialize(as = ImmutableServerUsage.class)
@JsonDeserialize(as = ImmutableServerUsage.class)
public abstract class ServerUsage implements
LastUpdatedProvider,
ProvenanceProvider {
public abstract long serverId();
public abstract EntityReference entityReference();
}
|
waltz-model/src/main/java/com/khartec/waltz/model/server_usage/ServerUsage.java
|
/*
* Waltz - Enterprise Architecture
* Copyright (C) 2016, 2017 Waltz open source project
* See README.md for more information
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.khartec.waltz.model.server_usage;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.khartec.waltz.model.EntityReference;
import com.khartec.waltz.model.LastUpdatedProvider;
import com.khartec.waltz.model.ProvenanceProvider;
import com.khartec.waltz.model.server_information.ImmutableServerUsage;
import org.immutables.value.Value;
@Value.Immutable
@JsonSerialize(as = ImmutableServerUsage.class)
@JsonDeserialize(as = ImmutableServerUsage.class)
public abstract class ServerUsage implements
LastUpdatedProvider,
ProvenanceProvider {
public abstract long serverId();
public abstract EntityReference entityReference();
}
|
Server Information: migrate asset_code to Server Usage table
#3783
|
waltz-model/src/main/java/com/khartec/waltz/model/server_usage/ServerUsage.java
|
Server Information: migrate asset_code to Server Usage table
|
<ide><path>altz-model/src/main/java/com/khartec/waltz/model/server_usage/ServerUsage.java
<ide> import com.khartec.waltz.model.EntityReference;
<ide> import com.khartec.waltz.model.LastUpdatedProvider;
<ide> import com.khartec.waltz.model.ProvenanceProvider;
<del>import com.khartec.waltz.model.server_information.ImmutableServerUsage;
<ide> import org.immutables.value.Value;
<ide>
<ide>
|
|
Java
|
bsd-3-clause
|
3caea0b9b571396e5f35390eb15a677c63492618
| 0 |
burtcorp/jmespath-java
|
package io.burt.jmespath.jcf;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.Collection;
import java.util.Collections;
import io.burt.jmespath.BaseRuntime;
import io.burt.jmespath.JmesPathType;
import io.burt.jmespath.function.FunctionRegistry;
import static io.burt.jmespath.JmesPathType.*;
public class JcfRuntime extends BaseRuntime<Object> {
public JcfRuntime() {
super();
}
public JcfRuntime(FunctionRegistry functionRegistry) {
super(functionRegistry);
}
@Override
public Object parseString(String string) {
return JsonParser.fromString(string, this);
}
@Override
@SuppressWarnings("unchecked")
public List<Object> toList(Object value) {
switch (typeOf(value)) {
case ARRAY:
if (value instanceof List) {
return (List<Object>) value;
} else {
return new ArrayList<>((Collection<Object>) value);
}
case OBJECT:
Map<Object, Object> object = (Map<Object, Object>) value;
return new ArrayList<>(object.values());
default:
return Collections.emptyList();
}
}
@Override
public String toString(Object str) {
if (typeOf(str) == STRING) {
return (String) str;
} else {
return unparse(str);
}
}
@Override
public Number toNumber(Object n) {
if (typeOf(n) == NUMBER) {
return (Number) n;
} else {
return null;
}
}
@Override
public JmesPathType typeOf(Object value) {
if (value == null) {
return NULL;
} else if (value instanceof Boolean) {
return BOOLEAN;
} else if (value instanceof Number) {
return NUMBER;
} else if (value instanceof Map) {
return OBJECT;
} else if (value instanceof Collection) {
return ARRAY;
} else if (value instanceof String) {
return STRING;
} else {
throw new IllegalStateException(String.format("Unknown node type encountered: %s", value.getClass().getName()));
}
}
@Override
@SuppressWarnings("unchecked")
public boolean isTruthy(Object value) {
switch (typeOf(value)) {
case NULL:
return false;
case NUMBER:
return true;
case BOOLEAN:
return ((Boolean)value).booleanValue();
case ARRAY:
return !((Collection<Object>) value).isEmpty();
case OBJECT:
return !((Map<Object,Object>) value).isEmpty();
case STRING:
return !((String) value).isEmpty();
default:
throw new IllegalStateException(String.format("Unknown node type encountered: %s", value.getClass().getName()));
}
}
@Override
@SuppressWarnings("unchecked")
public Object getProperty(Object value, Object name) {
if (typeOf(value) == OBJECT) {
return ((Map<Object, Object>) value).get(name);
} else {
return null;
}
}
@Override
@SuppressWarnings("unchecked")
public Collection<Object> getPropertyNames(Object value) {
if (typeOf(value) == OBJECT) {
return ((Map<Object, Object>) value).keySet();
} else {
return Collections.emptyList();
}
}
@Override
public Object createNull() {
return null;
}
@Override
public Object createArray(Collection<Object> elements) {
if (elements instanceof List) {
return elements;
} else {
return new ArrayList<>(elements);
}
}
@Override
public Object createString(String str) {
return str;
}
@Override
public Object createBoolean(boolean b) {
return Boolean.valueOf(b);
}
@Override
public Object createObject(Map<Object, Object> obj) {
return obj;
}
@Override
public Object createNumber(double n) {
return n;
}
@Override
public Object createNumber(long n) {
return n;
}
}
|
jmespath-core/src/main/java/io/burt/jmespath/jcf/JcfRuntime.java
|
package io.burt.jmespath.jcf;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.Collection;
import java.util.Collections;
import io.burt.jmespath.BaseRuntime;
import io.burt.jmespath.JmesPathType;
import io.burt.jmespath.function.FunctionRegistry;
import static io.burt.jmespath.JmesPathType.*;
public class JcfRuntime extends BaseRuntime<Object> {
public JcfRuntime() {
super();
}
public JcfRuntime(FunctionRegistry functionRegistry) {
super(functionRegistry);
}
@Override
public Object parseString(String string) {
return JsonParser.fromString(string, this);
}
@Override
@SuppressWarnings("unchecked")
public List<Object> toList(Object value) {
switch (typeOf(value)) {
case ARRAY:
if (value instanceof List) {
return (List<Object>) value;
} else {
return new ArrayList<>((Collection<Object>) value);
}
case OBJECT:
Map<Object, Object> object = (Map<Object, Object>) value;
return new ArrayList<>(object.values());
default:
return Collections.emptyList();
}
}
@Override
public String toString(Object str) {
if (typeOf(str) == STRING) {
return (String) str;
} else {
return unparse(str);
}
}
@Override
public Number toNumber(Object n) {
if (typeOf(n) == NUMBER) {
return (Number) n;
} else {
return null;
}
}
@Override
public JmesPathType typeOf(Object value) {
if (value == null) {
return NULL;
} else if (value instanceof Boolean) {
return BOOLEAN;
} else if (value instanceof Number) {
return NUMBER;
} else if (value instanceof Map) {
return OBJECT;
} else if (value instanceof Collection) {
return ARRAY;
} else if (value instanceof String) {
return STRING;
} else {
throw new IllegalStateException(String.format("Unknown node type encountered: %s", value.getClass().getName()));
}
}
@Override
@SuppressWarnings("unchecked")
public boolean isTruthy(Object value) {
switch (typeOf(value)) {
case NULL:
return false;
case NUMBER:
return true;
case BOOLEAN:
return ((Boolean)value).booleanValue();
case ARRAY:
return !((Collection<Object>) value).isEmpty();
case OBJECT:
return !((Map<Object,Object>) value).isEmpty();
case STRING:
return !((String) value).isEmpty();
default:
throw new IllegalStateException(String.format("Unknown node type encountered: %s", value.getClass().getName()));
}
}
@Override
public Object getProperty(Object value, Object name) {
if (typeOf(value) == OBJECT) {
return ((Map<Object, Object>) value).get(name);
} else {
return null;
}
}
@Override
@SuppressWarnings("unchecked")
public Collection<Object> getPropertyNames(Object value) {
if (typeOf(value) == OBJECT) {
return ((Map<Object, Object>) value).keySet();
} else {
return Collections.emptyList();
}
}
@Override
public Object createNull() {
return null;
}
@Override
public Object createArray(Collection<Object> elements) {
if (elements instanceof List) {
return elements;
} else {
return new ArrayList<>(elements);
}
}
@Override
public Object createString(String str) {
return str;
}
@Override
public Object createBoolean(boolean b) {
return Boolean.valueOf(b);
}
@Override
public Object createObject(Map<Object, Object> obj) {
return obj;
}
@Override
public Object createNumber(double n) {
return n;
}
@Override
public Object createNumber(long n) {
return n;
}
}
|
Suppress an unsafe cast warning
|
jmespath-core/src/main/java/io/burt/jmespath/jcf/JcfRuntime.java
|
Suppress an unsafe cast warning
|
<ide><path>mespath-core/src/main/java/io/burt/jmespath/jcf/JcfRuntime.java
<ide> }
<ide>
<ide> @Override
<add> @SuppressWarnings("unchecked")
<ide> public Object getProperty(Object value, Object name) {
<ide> if (typeOf(value) == OBJECT) {
<ide> return ((Map<Object, Object>) value).get(name);
|
|
JavaScript
|
agpl-3.0
|
b65950bb2e12eaafb1c5419737af7e1f94d901f4
| 0 |
KnzkDev/mastodon,imas/mastodon,anon5r/mastonon,abcang/mastodon,PlantsNetwork/mastodon,Chronister/mastodon,Arukas/mastodon,Arukas/mastodon,pfm-eyesightjp/mastodon,rutan/mastodon,Nyoho/mastodon,KnzkDev/mastodon,Craftodon/Craftodon,5thfloor/ichiji-social,blackle/mastodon,RobertRence/Mastodon,primenumber/mastodon,mhffdq/mastodon,theoria24/mastodon,ambition-vietnam/mastodon,blackle/mastodon,Nyoho/mastodon,danhunsaker/mastodon,rekif/mastodon,Chronister/mastodon,TootCat/mastodon,vahnj/mastodon,ykzts/mastodon,lynlynlynx/mastodon,TheInventrix/mastodon,hugogameiro/mastodon,codl/mastodon,tri-star/mastodon,h3zjp/mastodon,honpya/taketodon,unarist/mastodon,Craftodon/Craftodon,d6rkaiz/mastodon,mimumemo/mastodon,musashino205/mastodon,Toootim/mastodon,PlantsNetwork/mastodon,kirakiratter/mastodon,kagucho/mastodon,Ryanaka/mastodon,imomix/mastodon,esetomo/mastodon,WitchesTown/mastodon,amazedkoumei/mastodon,WitchesTown/mastodon,tootsuite/mastodon,MastodonCloud/mastodon,Kirishima21/mastodon,im-in-space/mastodon,riku6460/chikuwagoddon,Ryanaka/mastodon,NS-Kazuki/mastodon,maa123/mastodon,mecab/mastodon,3846masa/mastodon,Craftodon/Craftodon,tri-star/mastodon,corzntin/mastodon,verniy6462/mastodon,masto-donte-com-br/mastodon,pointlessone/mastodon,foozmeat/mastodon,esetomo/mastodon,cobodo/mastodon,corzntin/mastodon,verniy6462/mastodon,SerCom-KC/mastodon,tootcafe/mastodon,imomix/mastodon,mstdn-jp/mastodon,esetomo/mastodon,maa123/mastodon,5thfloor/ichiji-social,cybrespace/mastodon,narabo/mastodon,increments/mastodon,res-ac/mstdn.res.ac,koba-lab/mastodon,yi0713/mastodon,ebihara99999/mastodon,yukimochi/mastodon,TootCat/mastodon,pointlessone/mastodon,masto-donte-com-br/mastodon,tri-star/mastodon,WitchesTown/mastodon,primenumber/mastodon,5thfloor/ichiji-social,kazh98/social.arnip.org,rutan/mastodon,ambition-vietnam/mastodon,gol-cha/mastodon,masto-donte-com-br/mastodon,rutan/mastodon,imomix/mastodon,Nyoho/mastodon,danhunsaker/mastodon,TheInventrix/mastodon,lindwurm/mastodon,narabo/mastodon,clworld/mastodon,corzntin/mastodon,koba-lab/mastodon,maa123/mastodon,dunn/mastodon,tri-star/mastodon,rainyday/mastodon,pso2club/mastodon,mimumemo/mastodon,salvadorpla/mastodon,clworld/mastodon,alarky/mastodon,haleyashleypraesent/ProjectPrionosuchus,foozmeat/mastodon,tootsuite/mastodon,pfm-eyesightjp/mastodon,tootsuite/mastodon,h-izumi/mastodon,primenumber/mastodon,masarakki/mastodon,d6rkaiz/mastodon,TheInventrix/mastodon,vahnj/mastodon,dwango/mastodon,Ryanaka/mastodon,kazh98/social.arnip.org,TheInventrix/mastodon,nonoz/mastodon,mstdn-jp/mastodon,rekif/mastodon,h3zjp/mastodon,mstdn-jp/mastodon,rutan/mastodon,MastodonCloud/mastodon,imas/mastodon,foozmeat/mastodon,Arukas/mastodon,hugogameiro/mastodon,kazh98/social.arnip.org,SerCom-KC/mastodon,mosaxiv/mastodon,gol-cha/mastodon,hyuki0000/mastodon,ikuradon/mastodon,yukimochi/mastodon,abcang/mastodon,Arukas/mastodon,gol-cha/mastodon,mosaxiv/mastodon,narabo/mastodon,anon5r/mastonon,unarist/mastodon,ykzts/mastodon,maa123/mastodon,palon7/mastodon,koba-lab/mastodon,nonoz/mastodon,gol-cha/mastodon,codl/mastodon,tootcafe/mastodon,h-izumi/mastodon,summoners-riftodon/mastodon,mhffdq/mastodon,haleyashleypraesent/ProjectPrionosuchus,d6rkaiz/mastodon,NS-Kazuki/mastodon,dunn/mastodon,abcang/mastodon,pfm-eyesightjp/mastodon,RobertRence/Mastodon,masarakki/mastodon,MastodonCloud/mastodon,tateisu/mastodon,8796n/mastodon,riku6460/chikuwagoddon,dwango/mastodon,tateisu/mastodon,narabo/mastodon,codl/mastodon,amazedkoumei/mastodon,rekif/mastodon,mimumemo/mastodon,theoria24/mastodon,vahnj/mastodon,res-ac/mstdn.res.ac,vahnj/mastodon,yukimochi/mastodon,kazh98/social.arnip.org,Toootim/mastodon,Chronister/mastodon,SerCom-KC/mastodon,yukimochi/mastodon,pfm-eyesightjp/mastodon,pixiv/mastodon,pso2club/mastodon,PlantsNetwork/mastodon,mecab/mastodon,res-ac/mstdn.res.ac,KnzkDev/mastodon,primenumber/mastodon,summoners-riftodon/mastodon,imas/mastodon,corzntin/mastodon,yi0713/mastodon,res-ac/mstdn.res.ac,MitarashiDango/mastodon,8796n/mastodon,riku6460/chikuwagoddon,verniy6462/mastodon,increments/mastodon,blackle/mastodon,pixiv/mastodon,cobodo/mastodon,honpya/taketodon,imomix/mastodon,Chronister/mastodon,dunn/mastodon,mimumemo/mastodon,MitarashiDango/mastodon,hugogameiro/mastodon,kirakiratter/mastodon,cybrespace/mastodon,lynlynlynx/mastodon,kagucho/mastodon,glitch-soc/mastodon,mosaxiv/mastodon,masarakki/mastodon,Nyoho/mastodon,summoners-riftodon/mastodon,hugogameiro/mastodon,ebihara99999/mastodon,hyuki0000/mastodon,sylph-sin-tyaku/mastodon,rainyday/mastodon,MitarashiDango/mastodon,danhunsaker/mastodon,RobertRence/Mastodon,salvadorpla/mastodon,cybrespace/mastodon,mhffdq/mastodon,imas/mastodon,codl/mastodon,pixiv/mastodon,alarky/mastodon,im-in-space/mastodon,ykzts/mastodon,masarakki/mastodon,TootCat/mastodon,TheInventrix/mastodon,amazedkoumei/mastodon,tootcafe/mastodon,increments/mastodon,palon7/mastodon,musashino205/mastodon,h-izumi/mastodon,5thfloor/ichiji-social,KnzkDev/mastodon,im-in-space/mastodon,riku6460/chikuwagoddon,sylph-sin-tyaku/mastodon,cybrespace/mastodon,ikuradon/mastodon,pointlessone/mastodon,anon5r/mastonon,nonoz/mastodon,Kirishima21/mastodon,cobodo/mastodon,pointlessone/mastodon,koba-lab/mastodon,ambition-vietnam/mastodon,vahnj/mastodon,ebihara99999/mastodon,ambition-vietnam/mastodon,pinfort/mastodon,glitch-soc/mastodon,d6rkaiz/mastodon,mhffdq/mastodon,mosaxiv/mastodon,nonoz/mastodon,glitch-soc/mastodon,kirakiratter/mastodon,kagucho/mastodon,h-izumi/mastodon,pinfort/mastodon,Kirishima21/mastodon,8796n/mastodon,esetomo/mastodon,blackle/mastodon,RobertRence/Mastodon,SerCom-KC/mastodon,mstdn-jp/mastodon,musashino205/mastodon,ykzts/mastodon,WitchesTown/mastodon,Kirishima21/mastodon,palon7/mastodon,dwango/mastodon,verniy6462/mastodon,ikuradon/mastodon,mecab/mastodon,pixiv/mastodon,danhunsaker/mastodon,3846masa/mastodon,NS-Kazuki/mastodon,PlantsNetwork/mastodon,clworld/mastodon,lynlynlynx/mastodon,summoners-riftodon/mastodon,salvadorpla/mastodon,theoria24/mastodon,pinfort/mastodon,palon7/mastodon,sylph-sin-tyaku/mastodon,increments/mastodon,tateisu/mastodon,MitarashiDango/mastodon,mecab/mastodon,tateisu/mastodon,musashino205/mastodon,h3zjp/mastodon,alarky/mastodon,ikuradon/mastodon,unarist/mastodon,dwango/mastodon,abcang/mastodon,rainyday/mastodon,amazedkoumei/mastodon,salvadorpla/mastodon,haleyashleypraesent/ProjectPrionosuchus,Ryanaka/mastodon,Toootim/mastodon,kirakiratter/mastodon,kagucho/mastodon,tootsuite/mastodon,yi0713/mastodon,theoria24/mastodon,haleyashleypraesent/ProjectPrionosuchus,foozmeat/mastodon,masto-donte-com-br/mastodon,h3zjp/mastodon,ebihara99999/mastodon,honpya/taketodon,clworld/mastodon,pinfort/mastodon,yi0713/mastodon,Craftodon/Craftodon,unarist/mastodon,hyuki0000/mastodon,pso2club/mastodon,NS-Kazuki/mastodon,3846masa/mastodon,im-in-space/mastodon,rainyday/mastodon,rekif/mastodon,pso2club/mastodon,Toootim/mastodon,honpya/taketodon,cobodo/mastodon,sylph-sin-tyaku/mastodon,anon5r/mastonon,lindwurm/mastodon,hyuki0000/mastodon,dunn/mastodon,lindwurm/mastodon,3846masa/mastodon,MastodonCloud/mastodon,tootcafe/mastodon,lynlynlynx/mastodon,lindwurm/mastodon,glitch-soc/mastodon,alarky/mastodon,TootCat/mastodon
|
import React from 'react';
import ImmutablePropTypes from 'react-immutable-proptypes';
import PropTypes from 'prop-types';
import IconButton from './icon_button';
import { defineMessages, injectIntl, FormattedMessage } from 'react-intl';
import { isIOS } from '../is_mobile';
const messages = defineMessages({
toggle_visible: { id: 'media_gallery.toggle_visible', defaultMessage: 'Toggle visibility' }
});
class Item extends React.PureComponent {
static propTypes = {
attachment: ImmutablePropTypes.map.isRequired,
index: PropTypes.number.isRequired,
size: PropTypes.number.isRequired,
onClick: PropTypes.func.isRequired,
autoPlayGif: PropTypes.bool.isRequired
};
handleClick = (e) => {
const { index, onClick } = this.props;
if (e.button === 0) {
e.preventDefault();
onClick(index);
}
e.stopPropagation();
}
render () {
const { attachment, index, size } = this.props;
let width = 50;
let height = 100;
let top = 'auto';
let left = 'auto';
let bottom = 'auto';
let right = 'auto';
if (size === 1) {
width = 100;
}
if (size === 4 || (size === 3 && index > 0)) {
height = 50;
}
if (size === 2) {
if (index === 0) {
right = '2px';
} else {
left = '2px';
}
} else if (size === 3) {
if (index === 0) {
right = '2px';
} else if (index > 0) {
left = '2px';
}
if (index === 1) {
bottom = '2px';
} else if (index > 1) {
top = '2px';
}
} else if (size === 4) {
if (index === 0 || index === 2) {
right = '2px';
}
if (index === 1 || index === 3) {
left = '2px';
}
if (index < 2) {
bottom = '2px';
} else {
top = '2px';
}
}
let thumbnail = '';
if (attachment.get('type') === 'image') {
thumbnail = (
<a
className='media-gallery__item-thumbnail'
href={attachment.get('remote_url') || attachment.get('url')}
onClick={this.handleClick}
target='_blank'
style={{ backgroundImage: `url(${attachment.get('preview_url')})` }}
/>
);
} else if (attachment.get('type') === 'gifv') {
const autoPlay = !isIOS() && this.props.autoPlayGif;
thumbnail = (
<div className={`media-gallery__gifv ${autoPlay ? 'autoplay' : ''}`}>
<video
className='media-gallery__item-gifv-thumbnail'
role='application'
src={attachment.get('url')}
onClick={this.handleClick}
autoPlay={autoPlay}
loop={true}
muted={true}
/>
<span className='media-gallery__gifv__label'>GIF</span>
</div>
);
}
return (
<div className='media-gallery__item' key={attachment.get('id')} style={{ left: left, top: top, right: right, bottom: bottom, width: `${width}%`, height: `${height}%` }}>
{thumbnail}
</div>
);
}
}
class MediaGallery extends React.PureComponent {
static propTypes = {
sensitive: PropTypes.bool,
media: ImmutablePropTypes.list.isRequired,
height: PropTypes.number.isRequired,
onOpenMedia: PropTypes.func.isRequired,
intl: PropTypes.object.isRequired,
autoPlayGif: PropTypes.bool.isRequired
};
state = {
visible: !this.props.sensitive
};
handleOpen = (e) => {
this.setState({ visible: !this.state.visible });
}
handleClick = (index) => {
this.props.onOpenMedia(this.props.media, index);
}
render () {
const { media, intl, sensitive } = this.props;
let children;
if (!this.state.visible) {
let warning;
if (sensitive) {
warning = <FormattedMessage id='status.sensitive_warning' defaultMessage='Sensitive content' />;
} else {
warning = <FormattedMessage id='status.media_hidden' defaultMessage='Media hidden' />;
}
children = (
<div role='button' tabIndex='0' className='media-spoiler' onClick={this.handleOpen}>
<span className='media-spoiler__warning'>{warning}</span>
<span className='media-spoiler__trigger'><FormattedMessage id='status.sensitive_toggle' defaultMessage='Click to view' /></span>
</div>
);
} else {
const size = media.take(4).size;
children = media.take(4).map((attachment, i) => <Item key={attachment.get('id')} onClick={this.handleClick} attachment={attachment} autoPlayGif={this.props.autoPlayGif} index={i} size={size} />);
}
return (
<div className='media-gallery' style={{ height: `${this.props.height}px` }}>
<div className='spoiler-button' style={{ display: !this.state.visible ? 'none' : 'block' }}>
<IconButton title={intl.formatMessage(messages.toggle_visible)} icon={this.state.visible ? 'eye' : 'eye-slash'} overlay onClick={this.handleOpen} />
</div>
{children}
</div>
);
}
}
export default injectIntl(MediaGallery);
|
app/javascript/mastodon/components/media_gallery.js
|
import React from 'react';
import ImmutablePropTypes from 'react-immutable-proptypes';
import PropTypes from 'prop-types';
import IconButton from './icon_button';
import { defineMessages, injectIntl, FormattedMessage } from 'react-intl';
import { isIOS } from '../is_mobile';
const messages = defineMessages({
toggle_visible: { id: 'media_gallery.toggle_visible', defaultMessage: 'Toggle visibility' }
});
class Item extends React.PureComponent {
static propTypes = {
attachment: ImmutablePropTypes.map.isRequired,
index: PropTypes.number.isRequired,
size: PropTypes.number.isRequired,
onClick: PropTypes.func.isRequired,
autoPlayGif: PropTypes.bool.isRequired
};
handleClick = (e) => {
const { index, onClick } = this.props;
if (e.button === 0) {
e.preventDefault();
onClick(index);
}
e.stopPropagation();
}
render () {
const { attachment, index, size } = this.props;
let width = 50;
let height = 100;
let top = 'auto';
let left = 'auto';
let bottom = 'auto';
let right = 'auto';
if (size === 1) {
width = 100;
}
if (size === 4 || (size === 3 && index > 0)) {
height = 50;
}
if (size === 2) {
if (index === 0) {
right = '2px';
} else {
left = '2px';
}
} else if (size === 3) {
if (index === 0) {
right = '2px';
} else if (index > 0) {
left = '2px';
}
if (index === 1) {
bottom = '2px';
} else if (index > 1) {
top = '2px';
}
} else if (size === 4) {
if (index === 0 || index === 2) {
right = '2px';
}
if (index === 1 || index === 3) {
left = '2px';
}
if (index < 2) {
bottom = '2px';
} else {
top = '2px';
}
}
let thumbnail = '';
if (attachment.get('type') === 'image') {
thumbnail = (
<a
className='media-gallery__item-thumbnail'
href={attachment.get('remote_url') || attachment.get('url')}
onClick={this.handleClick}
target='_blank'
style={{ backgroundImage: `url(${attachment.get('preview_url')})` }}
/>
);
} else if (attachment.get('type') === 'gifv') {
const autoPlay = !isIOS() && this.props.autoPlayGif;
thumbnail = (
<div className={`media-gallery__gifv ${autoPlay ? 'autoplay' : ''}`}>
<video
className='media-gallery__item-gifv-thumbnail'
role='application'
src={attachment.get('url')}
onClick={this.handleClick}
autoPlay={autoPlay}
loop={true}
muted={true}
/>
<span className='media-gallery__gifv__label'>GIF</span>
</div>
);
}
return (
<div className='media-gallery__item' key={attachment.get('id')} style={{ left: left, top: top, right: right, bottom: bottom, width: `${width}%`, height: `${height}%` }}>
{thumbnail}
</div>
);
}
}
class MediaGallery extends React.PureComponent {
static propTypes = {
sensitive: PropTypes.bool,
media: ImmutablePropTypes.list.isRequired,
height: PropTypes.number.isRequired,
onOpenMedia: PropTypes.func.isRequired,
intl: PropTypes.object.isRequired,
autoPlayGif: PropTypes.bool.isRequired
};
state = {
visible: !props.sensitive
};
handleOpen = (e) => {
this.setState({ visible: !this.state.visible });
}
handleClick = (index) => {
this.props.onOpenMedia(this.props.media, index);
}
render () {
const { media, intl, sensitive } = this.props;
let children;
if (!this.state.visible) {
let warning;
if (sensitive) {
warning = <FormattedMessage id='status.sensitive_warning' defaultMessage='Sensitive content' />;
} else {
warning = <FormattedMessage id='status.media_hidden' defaultMessage='Media hidden' />;
}
children = (
<div role='button' tabIndex='0' className='media-spoiler' onClick={this.handleOpen}>
<span className='media-spoiler__warning'>{warning}</span>
<span className='media-spoiler__trigger'><FormattedMessage id='status.sensitive_toggle' defaultMessage='Click to view' /></span>
</div>
);
} else {
const size = media.take(4).size;
children = media.take(4).map((attachment, i) => <Item key={attachment.get('id')} onClick={this.handleClick} attachment={attachment} autoPlayGif={this.props.autoPlayGif} index={i} size={size} />);
}
return (
<div className='media-gallery' style={{ height: `${this.props.height}px` }}>
<div className='spoiler-button' style={{ display: !this.state.visible ? 'none' : 'block' }}>
<IconButton title={intl.formatMessage(messages.toggle_visible)} icon={this.state.visible ? 'eye' : 'eye-slash'} overlay onClick={this.handleOpen} />
</div>
{children}
</div>
);
}
}
export default injectIntl(MediaGallery);
|
fix #3008 : props was not defined (#3022)
|
app/javascript/mastodon/components/media_gallery.js
|
fix #3008 : props was not defined (#3022)
|
<ide><path>pp/javascript/mastodon/components/media_gallery.js
<ide> };
<ide>
<ide> state = {
<del> visible: !props.sensitive
<add> visible: !this.props.sensitive
<ide> };
<ide>
<ide> handleOpen = (e) => {
|
|
Java
|
epl-1.0
|
error: pathspec 'src/main/java/org/jtrfp/trcl/shell/GameCampaignData.java' did not match any file(s) known to git
|
8fb1d88dd118f86bc5c0330fab28698a3e3727c8
| 1 |
jtrfp/terminal-recall,jtrfp/terminal-recall,jtrfp/terminal-recall
|
/*******************************************************************************
* This file is part of TERMINAL RECALL
* Copyright (c) 2022 Chuck Ritola
* Part of the jTRFP.org project
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Public License v3.0
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/gpl.html
*
* Contributors:
* chuck - initial API and implementation
******************************************************************************/
package org.jtrfp.trcl.shell;
import java.util.ArrayList;
import java.util.Collection;
import org.jtrfp.trcl.conf.ui.ConfigByUI;
import org.jtrfp.trcl.conf.ui.EnumComboBoxUI;
import org.jtrfp.trcl.conf.ui.TextFieldUI;
import org.jtrfp.trcl.flow.GameVersion;
import lombok.Getter;
@Getter
public class GameCampaignData {
private String name = "[no name]";
private Collection<String> podURIs = new ArrayList<>();
private String voxURI;
private GameVersion gameVersion = GameVersion.TV;
@ConfigByUI(editorClass = TextFieldUI.class)
public void setName(String name) {
this.name = name;
}
@ConfigByUI(editorClass = PODListUI.class)
public void setPodURIs(Collection<String> podURIs) {
this.podURIs = podURIs;
}
@ConfigByUI(editorClass = TextFieldUI.class)
public void setVoxURI(String voxURI) {
this.voxURI = voxURI;
}
@ConfigByUI(editorClass = EnumComboBoxUI.class)
public void setGameVersion(GameVersion gameVersion) {
this.gameVersion = gameVersion;
}
@Override
public String toString() {
return name;
}
}//end GameCampaignData
|
src/main/java/org/jtrfp/trcl/shell/GameCampaignData.java
|
⟴GameCampaignData.
|
src/main/java/org/jtrfp/trcl/shell/GameCampaignData.java
|
⟴GameCampaignData.
|
<ide><path>rc/main/java/org/jtrfp/trcl/shell/GameCampaignData.java
<add>/*******************************************************************************
<add> * This file is part of TERMINAL RECALL
<add> * Copyright (c) 2022 Chuck Ritola
<add> * Part of the jTRFP.org project
<add> * All rights reserved. This program and the accompanying materials
<add> * are made available under the terms of the GNU Public License v3.0
<add> * which accompanies this distribution, and is available at
<add> * http://www.gnu.org/licenses/gpl.html
<add> *
<add> * Contributors:
<add> * chuck - initial API and implementation
<add> ******************************************************************************/
<add>
<add>package org.jtrfp.trcl.shell;
<add>
<add>import java.util.ArrayList;
<add>import java.util.Collection;
<add>
<add>import org.jtrfp.trcl.conf.ui.ConfigByUI;
<add>import org.jtrfp.trcl.conf.ui.EnumComboBoxUI;
<add>import org.jtrfp.trcl.conf.ui.TextFieldUI;
<add>import org.jtrfp.trcl.flow.GameVersion;
<add>
<add>import lombok.Getter;
<add>
<add>@Getter
<add>public class GameCampaignData {
<add> private String name = "[no name]";
<add> private Collection<String> podURIs = new ArrayList<>();
<add> private String voxURI;
<add> private GameVersion gameVersion = GameVersion.TV;
<add>
<add> @ConfigByUI(editorClass = TextFieldUI.class)
<add> public void setName(String name) {
<add> this.name = name;
<add> }
<add> @ConfigByUI(editorClass = PODListUI.class)
<add> public void setPodURIs(Collection<String> podURIs) {
<add> this.podURIs = podURIs;
<add> }
<add> @ConfigByUI(editorClass = TextFieldUI.class)
<add> public void setVoxURI(String voxURI) {
<add> this.voxURI = voxURI;
<add> }
<add> @ConfigByUI(editorClass = EnumComboBoxUI.class)
<add> public void setGameVersion(GameVersion gameVersion) {
<add> this.gameVersion = gameVersion;
<add> }
<add> @Override
<add> public String toString() {
<add> return name;
<add> }
<add>}//end GameCampaignData
|
|
Java
|
bsd-3-clause
|
error: pathspec 'core/src/test/java/de/holisticon/util/tracee/ThreadLocalHashSetTest.java' did not match any file(s) known to git
|
11e6c5ea03b2d775d5ef83b416f2a981c8af6f43
| 1 |
danielwegener/tracee,Hippoom/tracee,SvenBunge/tracee,hypery2k/tracee,tracee/tracee
|
package de.holisticon.util.tracee;
import org.junit.Test;
import static org.hamcrest.Matchers.notNullValue;
import static org.junit.Assert.assertThat;
/**
* @author Daniel Wegener (Holisticon AG)
*/
public class ThreadLocalHashSetTest {
private final ThreadLocalHashSet<String> unit = new ThreadLocalHashSet<String>();
@Test
public void testGetInitialValue() {
assertThat(unit.get(), notNullValue());
}
}
|
core/src/test/java/de/holisticon/util/tracee/ThreadLocalHashSetTest.java
|
#5: add ThreadLocalHashSet unit test
|
core/src/test/java/de/holisticon/util/tracee/ThreadLocalHashSetTest.java
|
#5: add ThreadLocalHashSet unit test
|
<ide><path>ore/src/test/java/de/holisticon/util/tracee/ThreadLocalHashSetTest.java
<add>package de.holisticon.util.tracee;
<add>
<add>import org.junit.Test;
<add>
<add>import static org.hamcrest.Matchers.notNullValue;
<add>import static org.junit.Assert.assertThat;
<add>
<add>/**
<add> * @author Daniel Wegener (Holisticon AG)
<add> */
<add>public class ThreadLocalHashSetTest {
<add>
<add> private final ThreadLocalHashSet<String> unit = new ThreadLocalHashSet<String>();
<add>
<add> @Test
<add> public void testGetInitialValue() {
<add> assertThat(unit.get(), notNullValue());
<add> }
<add>
<add>}
|
|
Java
|
apache-2.0
|
e217ab28c5eb98f9c308e543f2a0d4e14f83b7df
| 0 |
awesome-niu/crosswalk-cordova-android,vionescu/cordova-android,alsorokin/cordova-android,adobe-marketing-cloud-mobile/aemm-android,thedracle/cordova-android-chromeview,thedracle/cordova-android-chromeview,corimf/cordova-android,alpache/cordova-android,ttiurani/cordova-android,hgl888/cordova-android,bso-intel/cordova-android,macdonst/cordova-android,alpache/cordova-android,mokelab/cordova-android,honger05/cordova-android,CloudCom/cordova-android,vionescu/cordova-android,bso-intel/cordova-android,hgl888/crosswalk-cordova-android,egirshov/cordova-android,hgl888/cordova-android-chromeview,corimf/cordova-android,net19880504/cordova-android,mmig/cordova-android,tony--/cordova-android,xandroidx/cordova-android,chengxiaole/crosswalk-cordova-android,forcedotcom/incubator-cordova-android,hgl888/cordova-android-chromeview,adobe-marketing-cloud-mobile/aemm-android,matb33/cordova-android,corimf/cordova-android,alsorokin/cordova-android,ogoguel/cordova-android,rohngonnarock/cordova-android,archananaik/cordova-amazon-fireos-old,0359xiaodong/cordova-android,cesine/cordova-android,cesine/cordova-android,hgl888/cordova-android-chromeview,jasongin/cordova-android,grigorkh/cordova-android,filmaj/cordova-android,lybvinci/cordova-android,devgeeks/cordova-android,askyheller/testgithub,rakuco/crosswalk-cordova-android,revolunet/cordova-android,sxagan/cordova-android,synaptek/cordova-android,honger05/cordova-android,rakuco/crosswalk-cordova-android,vionescu/cordova-android,CrandellWS/cordova-android,synaptek/cordova-android,dpogue/cordova-android,askyheller/testgithub,manuelbrand/cordova-android,apache/cordova-android,chengxiaole/crosswalk-cordova-android,rakuco/crosswalk-cordova-android,chengxiaole/crosswalk-cordova-android,jfrumar/cordova-android,ttiurani/cordova-android,crosswalk-project/crosswalk-cordova-android,Icenium/cordova-android,ogoguel/cordova-android,GroupAhead/cordova-android,synaptek/cordova-android,mokelab/cordova-android,leixinstar/cordova-android,CrandellWS/cordova-android,polyvi/xface-android,macdonst/cordova-android,lybvinci/cordova-android,net19880504/cordova-android,alpache/cordova-android,ecit241/cordova-android,lvrookie/cordova-android,sxagan/cordova-android,xandroidx/cordova-android,lybvinci/cordova-android,filmaj/cordova-android,mmig/cordova-android,Icenium/cordova-android,manuelbrand/cordova-android,tony--/cordova-android,mleoking/cordova-android,hgl888/crosswalk-cordova-android,matb33/cordova-android,macdonst/cordova-android,lvrookie/cordova-android,revolunet/cordova-android,jfrumar/cordova-android,GroupAhead/cordova-android,alsorokin/cordova-android,apache/cordova-android,jasongin/cordova-android,tony--/cordova-android,mokelab/cordova-android,csantanapr/cordova-android,ecit241/cordova-android,xandroidx/cordova-android,crosswalk-project/crosswalk-cordova-android,hgl888/crosswalk-cordova-android,0359xiaodong/cordova-android,infil00p/cordova-android,hgl888/cordova-android,dpogue/cordova-android,crosswalk-project/crosswalk-cordova-android,forcedotcom/incubator-cordova-android,sxagan/cordova-android,ogoguel/cordova-android,leixinstar/cordova-android,mleoking/cordova-android,archananaik/cordova-amazon-fireos-old,infil00p/cordova-android,CrandellWS/cordova-android,polyvi/xface-android,rohngonnarock/cordova-android,Icenium/cordova-android,infil00p/cordova-android,matb33/cordova-android,hgl888/cordova-android-chromeview,MetSystem/cordova-android,grigorkh/cordova-android,devgeeks/cordova-android,awesome-niu/crosswalk-cordova-android,honger05/cordova-android,jasongin/cordova-android,MetSystem/cordova-android,0359xiaodong/cordova-android,awesome-niu/crosswalk-cordova-android,grigorkh/cordova-android,archananaik/cordova-amazon-fireos-old,CloudCom/cordova-android,cesine/cordova-android,grigorkh/cordova-android,GroupAhead/cordova-android,dpogue/cordova-android,csantanapr/cordova-android,filmaj/cordova-android,mmig/cordova-android,lvrookie/cordova-android,mleoking/cordova-android,rohngonnarock/cordova-android,manuelbrand/cordova-android,askyheller/testgithub,apache/cordova-android,egirshov/cordova-android,forcedotcom/incubator-cordova-android,thedracle/cordova-android-chromeview,net19880504/cordova-android,devgeeks/cordova-android,csantanapr/cordova-android,bso-intel/cordova-android,hgl888/cordova-android,polyvi/xface-android,CloudCom/cordova-android,ttiurani/cordova-android,jfrumar/cordova-android,adobe-marketing-cloud-mobile/aemm-android,MetSystem/cordova-android,leixinstar/cordova-android,ecit241/cordova-android,egirshov/cordova-android,revolunet/cordova-android
|
/*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
package org.apache.cordova;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.content.ContentProviderOperation;
import android.content.ContentProviderResult;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.OperationApplicationException;
import android.database.Cursor;
import android.net.Uri;
import android.os.Debug;
import android.os.RemoteException;
import android.provider.ContactsContract;
import android.util.Log;
import android.webkit.WebView;
import org.apache.cordova.api.CordovaInterface;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
//import android.app.Activity;
//import android.content.Context;
/**
* An implementation of {@link ContactAccessor} that uses current Contacts API.
* This class should be used on Eclair or beyond, but would not work on any earlier
* release of Android. As a matter of fact, it could not even be loaded.
* <p>
* This implementation has several advantages:
* <ul>
* <li>It sees contacts from multiple accounts.
* <li>It works with aggregated contacts. So for example, if the contact is the result
* of aggregation of two raw contacts from different accounts, it may return the name from
* one and the phone number from the other.
* <li>It is efficient because it uses the more efficient current API.
* <li>Not obvious in this particular example, but it has access to new kinds
* of data available exclusively through the new APIs. Exercise for the reader: add support
* for nickname (see {@link android.provider.ContactsContract.CommonDataKinds.Nickname}) or
* social status updates (see {@link android.provider.ContactsContract.StatusUpdates}).
* </ul>
*/
public class ContactAccessorSdk5 extends ContactAccessor {
/**
* Keep the photo size under the 1 MB blog limit.
*/
private static final long MAX_PHOTO_SIZE = 1048576;
private static final String EMAIL_REGEXP = ".+@.+\\.+.+"; /* <anything>@<anything>.<anything>*/
/**
* A static map that converts the JavaScript property name to Android database column name.
*/
private static final Map<String, String> dbMap = new HashMap<String, String>();
static {
dbMap.put("id", ContactsContract.Data.CONTACT_ID);
dbMap.put("displayName", ContactsContract.Contacts.DISPLAY_NAME);
dbMap.put("name", ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME);
dbMap.put("name.formatted", ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME);
dbMap.put("name.familyName", ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME);
dbMap.put("name.givenName", ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME);
dbMap.put("name.middleName", ContactsContract.CommonDataKinds.StructuredName.MIDDLE_NAME);
dbMap.put("name.honorificPrefix", ContactsContract.CommonDataKinds.StructuredName.PREFIX);
dbMap.put("name.honorificSuffix", ContactsContract.CommonDataKinds.StructuredName.SUFFIX);
dbMap.put("nickname", ContactsContract.CommonDataKinds.Nickname.NAME);
dbMap.put("phoneNumbers", ContactsContract.CommonDataKinds.Phone.NUMBER);
dbMap.put("phoneNumbers.value", ContactsContract.CommonDataKinds.Phone.NUMBER);
dbMap.put("emails", ContactsContract.CommonDataKinds.Email.DATA);
dbMap.put("emails.value", ContactsContract.CommonDataKinds.Email.DATA);
dbMap.put("addresses", ContactsContract.CommonDataKinds.StructuredPostal.FORMATTED_ADDRESS);
dbMap.put("addresses.formatted", ContactsContract.CommonDataKinds.StructuredPostal.FORMATTED_ADDRESS);
dbMap.put("addresses.streetAddress", ContactsContract.CommonDataKinds.StructuredPostal.STREET);
dbMap.put("addresses.locality", ContactsContract.CommonDataKinds.StructuredPostal.CITY);
dbMap.put("addresses.region", ContactsContract.CommonDataKinds.StructuredPostal.REGION);
dbMap.put("addresses.postalCode", ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE);
dbMap.put("addresses.country", ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY);
dbMap.put("ims", ContactsContract.CommonDataKinds.Im.DATA);
dbMap.put("ims.value", ContactsContract.CommonDataKinds.Im.DATA);
dbMap.put("organizations", ContactsContract.CommonDataKinds.Organization.COMPANY);
dbMap.put("organizations.name", ContactsContract.CommonDataKinds.Organization.COMPANY);
dbMap.put("organizations.department", ContactsContract.CommonDataKinds.Organization.DEPARTMENT);
dbMap.put("organizations.title", ContactsContract.CommonDataKinds.Organization.TITLE);
dbMap.put("birthday", ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE);
dbMap.put("note", ContactsContract.CommonDataKinds.Note.NOTE);
dbMap.put("photos.value", ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE);
//dbMap.put("categories.value", null);
dbMap.put("urls", ContactsContract.CommonDataKinds.Website.URL);
dbMap.put("urls.value", ContactsContract.CommonDataKinds.Website.URL);
}
/**
* Create an contact accessor.
*/
public ContactAccessorSdk5(WebView view, CordovaInterface context) {
mApp = context;
mView = view;
}
/**
* This method takes the fields required and search options in order to produce an
* array of contacts that matches the criteria provided.
* @param fields an array of items to be used as search criteria
* @param options that can be applied to contact searching
* @return an array of contacts
*/
@Override
public JSONArray search(JSONArray fields, JSONObject options) {
// Get the find options
String searchTerm = "";
int limit = Integer.MAX_VALUE;
boolean multiple = true;
if (options != null) {
searchTerm = options.optString("filter");
if (searchTerm.length() == 0) {
searchTerm = "%";
}
else {
searchTerm = "%" + searchTerm + "%";
}
try {
multiple = options.getBoolean("multiple");
if (!multiple) {
limit = 1;
}
} catch (JSONException e) {
// Multiple was not specified so we assume the default is true.
}
}
else {
searchTerm = "%";
}
//Log.d(LOG_TAG, "Search Term = " + searchTerm);
//Log.d(LOG_TAG, "Field Length = " + fields.length());
//Log.d(LOG_TAG, "Fields = " + fields.toString());
// Loop through the fields the user provided to see what data should be returned.
HashMap<String, Boolean> populate = buildPopulationSet(fields);
// Build the ugly where clause and where arguments for one big query.
WhereOptions whereOptions = buildWhereClause(fields, searchTerm);
// Get all the id's where the search term matches the fields passed in.
Cursor idCursor = mApp.getActivity().getContentResolver().query(ContactsContract.Data.CONTENT_URI,
new String[] { ContactsContract.Data.CONTACT_ID },
whereOptions.getWhere(),
whereOptions.getWhereArgs(),
ContactsContract.Data.CONTACT_ID + " ASC");
// Create a set of unique ids
Set<String> contactIds = new HashSet<String>();
int idColumn = -1;
while (idCursor.moveToNext()) {
if (idColumn < 0) {
idColumn = idCursor.getColumnIndex(ContactsContract.Data.CONTACT_ID);
}
contactIds.add(idCursor.getString(idColumn));
}
idCursor.close();
// Build a query that only looks at ids
WhereOptions idOptions = buildIdClause(contactIds, searchTerm);
// Determine which columns we should be fetching.
HashSet<String> columnsToFetch = new HashSet<String>();
columnsToFetch.add(ContactsContract.Data.CONTACT_ID);
columnsToFetch.add(ContactsContract.Data.RAW_CONTACT_ID);
columnsToFetch.add(ContactsContract.Data.MIMETYPE);
if (isRequired("displayName", populate)) {
columnsToFetch.add(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME);
}
if (isRequired("name", populate)) {
columnsToFetch.add(ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME);
columnsToFetch.add(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME);
columnsToFetch.add(ContactsContract.CommonDataKinds.StructuredName.MIDDLE_NAME);
columnsToFetch.add(ContactsContract.CommonDataKinds.StructuredName.PREFIX);
columnsToFetch.add(ContactsContract.CommonDataKinds.StructuredName.SUFFIX);
}
if (isRequired("phoneNumbers", populate)) {
columnsToFetch.add(ContactsContract.CommonDataKinds.Phone._ID);
columnsToFetch.add(ContactsContract.CommonDataKinds.Phone.NUMBER);
columnsToFetch.add(ContactsContract.CommonDataKinds.Phone.TYPE);
}
if (isRequired("emails", populate)) {
columnsToFetch.add(ContactsContract.CommonDataKinds.Email.DATA);
columnsToFetch.add(ContactsContract.CommonDataKinds.Email.TYPE);
}
if (isRequired("addresses", populate)) {
columnsToFetch.add(ContactsContract.CommonDataKinds.StructuredPostal._ID);
columnsToFetch.add(ContactsContract.CommonDataKinds.Organization.TYPE);
columnsToFetch.add(ContactsContract.CommonDataKinds.StructuredPostal.FORMATTED_ADDRESS);
columnsToFetch.add(ContactsContract.CommonDataKinds.StructuredPostal.STREET);
columnsToFetch.add(ContactsContract.CommonDataKinds.StructuredPostal.CITY);
columnsToFetch.add(ContactsContract.CommonDataKinds.StructuredPostal.REGION);
columnsToFetch.add(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE);
columnsToFetch.add(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY);
}
if (isRequired("organizations", populate)) {
columnsToFetch.add(ContactsContract.CommonDataKinds.Organization._ID);
columnsToFetch.add(ContactsContract.CommonDataKinds.Organization.TYPE);
columnsToFetch.add(ContactsContract.CommonDataKinds.Organization.DEPARTMENT);
columnsToFetch.add(ContactsContract.CommonDataKinds.Organization.COMPANY);
columnsToFetch.add(ContactsContract.CommonDataKinds.Organization.TITLE);
}
if (isRequired("ims", populate)) {
columnsToFetch.add(ContactsContract.CommonDataKinds.Im._ID);
columnsToFetch.add(ContactsContract.CommonDataKinds.Im.DATA);
columnsToFetch.add(ContactsContract.CommonDataKinds.Im.TYPE);
}
if (isRequired("note", populate)) {
columnsToFetch.add(ContactsContract.CommonDataKinds.Note.NOTE);
}
if (isRequired("nickname", populate)) {
columnsToFetch.add(ContactsContract.CommonDataKinds.Nickname.NAME);
}
if (isRequired("urls", populate)) {
columnsToFetch.add(ContactsContract.CommonDataKinds.Website._ID);
columnsToFetch.add(ContactsContract.CommonDataKinds.Website.URL);
columnsToFetch.add(ContactsContract.CommonDataKinds.Website.TYPE);
}
if (isRequired("birthday", populate)) {
columnsToFetch.add(ContactsContract.CommonDataKinds.Event.START_DATE);
columnsToFetch.add(ContactsContract.CommonDataKinds.Event.TYPE);
}
if (isRequired("photos", populate)) {
columnsToFetch.add(ContactsContract.CommonDataKinds.Photo._ID);
}
// Do the id query
Cursor c = mApp.getActivity().getContentResolver().query(ContactsContract.Data.CONTENT_URI,
columnsToFetch.toArray(new String[] {}),
idOptions.getWhere(),
idOptions.getWhereArgs(),
ContactsContract.Data.CONTACT_ID + " ASC");
JSONArray contacts = populateContactArray(limit, populate, c);
return contacts;
}
/**
* A special search that finds one contact by id
*
* @param id contact to find by id
* @return a JSONObject representing the contact
* @throws JSONException
*/
public JSONObject getContactById(String id) throws JSONException {
// Do the id query
Cursor c = mApp.getActivity().getContentResolver().query(ContactsContract.Data.CONTENT_URI,
null,
ContactsContract.Data.CONTACT_ID + " = ? ",
new String[] { id },
ContactsContract.Data.CONTACT_ID + " ASC");
JSONArray fields = new JSONArray();
fields.put("*");
HashMap<String, Boolean> populate = buildPopulationSet(fields);
JSONArray contacts = populateContactArray(1, populate, c);
if (contacts.length() == 1) {
return contacts.getJSONObject(0);
} else {
return null;
}
}
/**
* Creates an array of contacts from the cursor you pass in
*
* @param limit max number of contacts for the array
* @param populate whether or not you should populate a certain value
* @param c the cursor
* @return a JSONArray of contacts
*/
private JSONArray populateContactArray(int limit,
HashMap<String, Boolean> populate, Cursor c) {
String contactId = "";
String rawId = "";
String oldContactId = "";
boolean newContact = true;
String mimetype = "";
JSONArray contacts = new JSONArray();
JSONObject contact = new JSONObject();
JSONArray organizations = new JSONArray();
JSONArray addresses = new JSONArray();
JSONArray phones = new JSONArray();
JSONArray emails = new JSONArray();
JSONArray ims = new JSONArray();
JSONArray websites = new JSONArray();
JSONArray photos = new JSONArray();
ArrayList<String> names = new ArrayList<String>();
// Column indices
int colContactId = c.getColumnIndex(ContactsContract.Data.CONTACT_ID);
int colRawContactId = c.getColumnIndex(ContactsContract.Data.RAW_CONTACT_ID);
int colMimetype = c.getColumnIndex(ContactsContract.Data.MIMETYPE);
int colDisplayName = c.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME);
int colNote = c.getColumnIndex(ContactsContract.CommonDataKinds.Note.NOTE);
int colNickname = c.getColumnIndex(ContactsContract.CommonDataKinds.Nickname.NAME);
int colBirthday = c.getColumnIndex(ContactsContract.CommonDataKinds.Event.START_DATE);
int colEventType = c.getColumnIndex(ContactsContract.CommonDataKinds.Event.TYPE);
if (c.getCount() > 0) {
while (c.moveToNext() && (contacts.length() <= (limit - 1))) {
try {
contactId = c.getString(colContactId);
rawId = c.getString(colRawContactId);
// If we are in the first row set the oldContactId
if (c.getPosition() == 0) {
oldContactId = contactId;
}
// When the contact ID changes we need to push the Contact object
// to the array of contacts and create new objects.
if (!oldContactId.equals(contactId)) {
// Populate the Contact object with it's arrays
// and push the contact into the contacts array
contacts.put(populateContact(contact, organizations, addresses, phones,
emails, ims, websites, photos));
// Clean up the objects
contact = new JSONObject();
organizations = new JSONArray();
addresses = new JSONArray();
phones = new JSONArray();
emails = new JSONArray();
ims = new JSONArray();
websites = new JSONArray();
photos = new JSONArray();
// Set newContact to true as we are starting to populate a new contact
newContact = true;
}
// When we detect a new contact set the ID and display name.
// These fields are available in every row in the result set returned.
if (newContact) {
newContact = false;
contact.put("id", contactId);
contact.put("rawId", rawId);
}
// Grab the mimetype of the current row as it will be used in a lot of comparisons
mimetype = c.getString(colMimetype);
if (mimetype.equals(ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)) {
contact.put("displayName", c.getString(colDisplayName));
}
if (mimetype.equals(ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
&& isRequired("name", populate)) {
contact.put("name", nameQuery(c));
}
else if (mimetype.equals(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
&& isRequired("phoneNumbers", populate)) {
phones.put(phoneQuery(c));
}
else if (mimetype.equals(ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)
&& isRequired("emails", populate)) {
emails.put(emailQuery(c));
}
else if (mimetype.equals(ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE)
&& isRequired("addresses", populate)) {
addresses.put(addressQuery(c));
}
else if (mimetype.equals(ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE)
&& isRequired("organizations", populate)) {
organizations.put(organizationQuery(c));
}
else if (mimetype.equals(ContactsContract.CommonDataKinds.Im.CONTENT_ITEM_TYPE)
&& isRequired("ims", populate)) {
ims.put(imQuery(c));
}
else if (mimetype.equals(ContactsContract.CommonDataKinds.Note.CONTENT_ITEM_TYPE)
&& isRequired("note", populate)) {
contact.put("note", c.getString(colNote));
}
else if (mimetype.equals(ContactsContract.CommonDataKinds.Nickname.CONTENT_ITEM_TYPE)
&& isRequired("nickname", populate)) {
contact.put("nickname", c.getString(colNickname));
}
else if (mimetype.equals(ContactsContract.CommonDataKinds.Website.CONTENT_ITEM_TYPE)
&& isRequired("urls", populate)) {
websites.put(websiteQuery(c));
}
else if (mimetype.equals(ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE)) {
if (isRequired("birthday", populate) &&
ContactsContract.CommonDataKinds.Event.TYPE_BIRTHDAY == c.getInt(colEventType)) {
contact.put("birthday", c.getString(colBirthday));
}
}
else if (mimetype.equals(ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE)
&& isRequired("photos", populate)) {
photos.put(photoQuery(c, contactId));
}
} catch (JSONException e) {
Log.e(LOG_TAG, e.getMessage(), e);
}
// Set the old contact ID
oldContactId = contactId;
}
// Push the last contact into the contacts array
if (contacts.length() < limit) {
contacts.put(populateContact(contact, organizations, addresses, phones,
emails, ims, websites, photos));
}
}
c.close();
return contacts;
}
/**
* Builds a where clause all all the ids passed into the method
* @param contactIds a set of unique contact ids
* @param searchTerm what to search for
* @return an object containing the selection and selection args
*/
private WhereOptions buildIdClause(Set<String> contactIds, String searchTerm) {
WhereOptions options = new WhereOptions();
// If the user is searching for every contact then short circuit the method
// and return a shorter where clause to be searched.
if (searchTerm.equals("%")) {
options.setWhere("(" + ContactsContract.Data.CONTACT_ID + " LIKE ? )");
options.setWhereArgs(new String[] { searchTerm });
return options;
}
// This clause means that there are specific ID's to be populated
Iterator<String> it = contactIds.iterator();
StringBuffer buffer = new StringBuffer("(");
while (it.hasNext()) {
buffer.append("'" + it.next() + "'");
if (it.hasNext()) {
buffer.append(",");
}
}
buffer.append(")");
options.setWhere(ContactsContract.Data.CONTACT_ID + " IN " + buffer.toString());
options.setWhereArgs(null);
return options;
}
/**
* Create a new contact using a JSONObject to hold all the data.
* @param contact
* @param organizations array of organizations
* @param addresses array of addresses
* @param phones array of phones
* @param emails array of emails
* @param ims array of instant messenger addresses
* @param websites array of websites
* @param photos
* @return
*/
private JSONObject populateContact(JSONObject contact, JSONArray organizations,
JSONArray addresses, JSONArray phones, JSONArray emails,
JSONArray ims, JSONArray websites, JSONArray photos) {
try {
// Only return the array if it has at least one entry
if (organizations.length() > 0) {
contact.put("organizations", organizations);
}
if (addresses.length() > 0) {
contact.put("addresses", addresses);
}
if (phones.length() > 0) {
contact.put("phoneNumbers", phones);
}
if (emails.length() > 0) {
contact.put("emails", emails);
}
if (ims.length() > 0) {
contact.put("ims", ims);
}
if (websites.length() > 0) {
contact.put("urls", websites);
}
if (photos.length() > 0) {
contact.put("photos", photos);
}
} catch (JSONException e) {
Log.e(LOG_TAG, e.getMessage(), e);
}
return contact;
}
/**
* Take the search criteria passed into the method and create a SQL WHERE clause.
* @param fields the properties to search against
* @param searchTerm the string to search for
* @return an object containing the selection and selection args
*/
private WhereOptions buildWhereClause(JSONArray fields, String searchTerm) {
ArrayList<String> where = new ArrayList<String>();
ArrayList<String> whereArgs = new ArrayList<String>();
WhereOptions options = new WhereOptions();
/*
* Special case where the user wants all fields returned
*/
if (isWildCardSearch(fields)) {
// Get all contacts with all properties
if ("%".equals(searchTerm)) {
options.setWhere("(" + ContactsContract.Contacts.DISPLAY_NAME + " LIKE ? )");
options.setWhereArgs(new String[] { searchTerm });
return options;
} else {
// Get all contacts that match the filter but return all properties
where.add("(" + dbMap.get("displayName") + " LIKE ? )");
whereArgs.add(searchTerm);
where.add("(" + dbMap.get("name") + " LIKE ? AND "
+ ContactsContract.Data.MIMETYPE + " = ? )");
whereArgs.add(searchTerm);
whereArgs.add(ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE);
where.add("(" + dbMap.get("nickname") + " LIKE ? AND "
+ ContactsContract.Data.MIMETYPE + " = ? )");
whereArgs.add(searchTerm);
whereArgs.add(ContactsContract.CommonDataKinds.Nickname.CONTENT_ITEM_TYPE);
where.add("(" + dbMap.get("phoneNumbers") + " LIKE ? AND "
+ ContactsContract.Data.MIMETYPE + " = ? )");
whereArgs.add(searchTerm);
whereArgs.add(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
where.add("(" + dbMap.get("emails") + " LIKE ? AND "
+ ContactsContract.Data.MIMETYPE + " = ? )");
whereArgs.add(searchTerm);
whereArgs.add(ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE);
where.add("(" + dbMap.get("addresses") + " LIKE ? AND "
+ ContactsContract.Data.MIMETYPE + " = ? )");
whereArgs.add(searchTerm);
whereArgs.add(ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE);
where.add("(" + dbMap.get("ims") + " LIKE ? AND "
+ ContactsContract.Data.MIMETYPE + " = ? )");
whereArgs.add(searchTerm);
whereArgs.add(ContactsContract.CommonDataKinds.Im.CONTENT_ITEM_TYPE);
where.add("(" + dbMap.get("organizations") + " LIKE ? AND "
+ ContactsContract.Data.MIMETYPE + " = ? )");
whereArgs.add(searchTerm);
whereArgs.add(ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE);
where.add("(" + dbMap.get("note") + " LIKE ? AND "
+ ContactsContract.Data.MIMETYPE + " = ? )");
whereArgs.add(searchTerm);
whereArgs.add(ContactsContract.CommonDataKinds.Note.CONTENT_ITEM_TYPE);
where.add("(" + dbMap.get("urls") + " LIKE ? AND "
+ ContactsContract.Data.MIMETYPE + " = ? )");
whereArgs.add(searchTerm);
whereArgs.add(ContactsContract.CommonDataKinds.Website.CONTENT_ITEM_TYPE);
}
}
/*
* Special case for when the user wants all the contacts but
*/
if ("%".equals(searchTerm)) {
options.setWhere("(" + ContactsContract.Contacts.DISPLAY_NAME + " LIKE ? )");
options.setWhereArgs(new String[] { searchTerm });
return options;
}
String key;
try {
//Log.d(LOG_TAG, "How many fields do we have = " + fields.length());
for (int i = 0; i < fields.length(); i++) {
key = fields.getString(i);
if (key.equals("id")) {
where.add("(" + dbMap.get(key) + " = ? )");
whereArgs.add(searchTerm.substring(1, searchTerm.length() - 1));
}
else if (key.startsWith("displayName")) {
where.add("(" + dbMap.get(key) + " LIKE ? )");
whereArgs.add(searchTerm);
}
else if (key.startsWith("name")) {
where.add("(" + dbMap.get(key) + " LIKE ? AND "
+ ContactsContract.Data.MIMETYPE + " = ? )");
whereArgs.add(searchTerm);
whereArgs.add(ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE);
}
else if (key.startsWith("nickname")) {
where.add("(" + dbMap.get(key) + " LIKE ? AND "
+ ContactsContract.Data.MIMETYPE + " = ? )");
whereArgs.add(searchTerm);
whereArgs.add(ContactsContract.CommonDataKinds.Nickname.CONTENT_ITEM_TYPE);
}
else if (key.startsWith("phoneNumbers")) {
where.add("(" + dbMap.get(key) + " LIKE ? AND "
+ ContactsContract.Data.MIMETYPE + " = ? )");
whereArgs.add(searchTerm);
whereArgs.add(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
}
else if (key.startsWith("emails")) {
where.add("(" + dbMap.get(key) + " LIKE ? AND "
+ ContactsContract.Data.MIMETYPE + " = ? )");
whereArgs.add(searchTerm);
whereArgs.add(ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE);
}
else if (key.startsWith("addresses")) {
where.add("(" + dbMap.get(key) + " LIKE ? AND "
+ ContactsContract.Data.MIMETYPE + " = ? )");
whereArgs.add(searchTerm);
whereArgs.add(ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE);
}
else if (key.startsWith("ims")) {
where.add("(" + dbMap.get(key) + " LIKE ? AND "
+ ContactsContract.Data.MIMETYPE + " = ? )");
whereArgs.add(searchTerm);
whereArgs.add(ContactsContract.CommonDataKinds.Im.CONTENT_ITEM_TYPE);
}
else if (key.startsWith("organizations")) {
where.add("(" + dbMap.get(key) + " LIKE ? AND "
+ ContactsContract.Data.MIMETYPE + " = ? )");
whereArgs.add(searchTerm);
whereArgs.add(ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE);
}
// else if (key.startsWith("birthday")) {
// where.add("(" + dbMap.get(key) + " LIKE ? AND "
// + ContactsContract.Data.MIMETYPE + " = ? )");
// }
else if (key.startsWith("note")) {
where.add("(" + dbMap.get(key) + " LIKE ? AND "
+ ContactsContract.Data.MIMETYPE + " = ? )");
whereArgs.add(searchTerm);
whereArgs.add(ContactsContract.CommonDataKinds.Note.CONTENT_ITEM_TYPE);
}
else if (key.startsWith("urls")) {
where.add("(" + dbMap.get(key) + " LIKE ? AND "
+ ContactsContract.Data.MIMETYPE + " = ? )");
whereArgs.add(searchTerm);
whereArgs.add(ContactsContract.CommonDataKinds.Website.CONTENT_ITEM_TYPE);
}
}
} catch (JSONException e) {
Log.e(LOG_TAG, e.getMessage(), e);
}
// Creating the where string
StringBuffer selection = new StringBuffer();
for (int i = 0; i < where.size(); i++) {
selection.append(where.get(i));
if (i != (where.size() - 1)) {
selection.append(" OR ");
}
}
options.setWhere(selection.toString());
// Creating the where args array
String[] selectionArgs = new String[whereArgs.size()];
for (int i = 0; i < whereArgs.size(); i++) {
selectionArgs[i] = whereArgs.get(i);
}
options.setWhereArgs(selectionArgs);
return options;
}
/**
* If the user passes in the '*' wildcard character for search then they want all fields for each contact
*
* @param fields
* @return true if wildcard search requested, false otherwise
*/
private boolean isWildCardSearch(JSONArray fields) {
// Only do a wildcard search if we are passed ["*"]
if (fields.length() == 1) {
try {
if ("*".equals(fields.getString(0))) {
return true;
}
} catch (JSONException e) {
return false;
}
}
return false;
}
/**
* Create a ContactOrganization JSONObject
* @param cursor the current database row
* @return a JSONObject representing a ContactOrganization
*/
private JSONObject organizationQuery(Cursor cursor) {
JSONObject organization = new JSONObject();
try {
organization.put("id", cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Organization._ID)));
organization.put("pref", false); // Android does not store pref attribute
organization.put("type", getOrgType(cursor.getInt(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Organization.TYPE))));
organization.put("department", cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Organization.DEPARTMENT)));
organization.put("name", cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Organization.COMPANY)));
organization.put("title", cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Organization.TITLE)));
} catch (JSONException e) {
Log.e(LOG_TAG, e.getMessage(), e);
}
return organization;
}
/**
* Create a ContactAddress JSONObject
* @param cursor the current database row
* @return a JSONObject representing a ContactAddress
*/
private JSONObject addressQuery(Cursor cursor) {
JSONObject address = new JSONObject();
try {
address.put("id", cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal._ID)));
address.put("pref", false); // Android does not store pref attribute
address.put("type", getAddressType(cursor.getInt(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Organization.TYPE))));
address.put("formatted", cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.FORMATTED_ADDRESS)));
address.put("streetAddress", cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.STREET)));
address.put("locality", cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.CITY)));
address.put("region", cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.REGION)));
address.put("postalCode", cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE)));
address.put("country", cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY)));
} catch (JSONException e) {
Log.e(LOG_TAG, e.getMessage(), e);
}
return address;
}
/**
* Create a ContactName JSONObject
* @param cursor the current database row
* @return a JSONObject representing a ContactName
*/
private JSONObject nameQuery(Cursor cursor) {
JSONObject contactName = new JSONObject();
try {
String familyName = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME));
String givenName = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME));
String middleName = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.MIDDLE_NAME));
String honorificPrefix = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.PREFIX));
String honorificSuffix = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.SUFFIX));
// Create the formatted name
StringBuffer formatted = new StringBuffer("");
if (honorificPrefix != null) {
formatted.append(honorificPrefix + " ");
}
if (givenName != null) {
formatted.append(givenName + " ");
}
if (middleName != null) {
formatted.append(middleName + " ");
}
if (familyName != null) {
formatted.append(familyName + " ");
}
if (honorificSuffix != null) {
formatted.append(honorificSuffix + " ");
}
contactName.put("familyName", familyName);
contactName.put("givenName", givenName);
contactName.put("middleName", middleName);
contactName.put("honorificPrefix", honorificPrefix);
contactName.put("honorificSuffix", honorificSuffix);
contactName.put("formatted", formatted);
} catch (JSONException e) {
Log.e(LOG_TAG, e.getMessage(), e);
}
return contactName;
}
/**
* Create a ContactField JSONObject
* @param cursor the current database row
* @return a JSONObject representing a ContactField
*/
private JSONObject phoneQuery(Cursor cursor) {
JSONObject phoneNumber = new JSONObject();
try {
phoneNumber.put("id", cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone._ID)));
phoneNumber.put("pref", false); // Android does not store pref attribute
phoneNumber.put("value", cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)));
phoneNumber.put("type", getPhoneType(cursor.getInt(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE))));
} catch (JSONException e) {
Log.e(LOG_TAG, e.getMessage(), e);
} catch (Exception excp) {
Log.e(LOG_TAG, excp.getMessage(), excp);
}
return phoneNumber;
}
/**
* Create a ContactField JSONObject
* @param cursor the current database row
* @return a JSONObject representing a ContactField
*/
private JSONObject emailQuery(Cursor cursor) {
JSONObject email = new JSONObject();
try {
email.put("id", cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Email._ID)));
email.put("pref", false); // Android does not store pref attribute
email.put("value", cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA)));
email.put("type", getContactType(cursor.getInt(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE))));
} catch (JSONException e) {
Log.e(LOG_TAG, e.getMessage(), e);
}
return email;
}
/**
* Create a ContactField JSONObject
* @param cursor the current database row
* @return a JSONObject representing a ContactField
*/
private JSONObject imQuery(Cursor cursor) {
JSONObject im = new JSONObject();
try {
im.put("id", cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Im._ID)));
im.put("pref", false); // Android does not store pref attribute
im.put("value", cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Im.DATA)));
im.put("type", getContactType(cursor.getInt(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Im.TYPE))));
} catch (JSONException e) {
Log.e(LOG_TAG, e.getMessage(), e);
}
return im;
}
/**
* Create a ContactField JSONObject
* @param cursor the current database row
* @return a JSONObject representing a ContactField
*/
private JSONObject websiteQuery(Cursor cursor) {
JSONObject website = new JSONObject();
try {
website.put("id", cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Website._ID)));
website.put("pref", false); // Android does not store pref attribute
website.put("value", cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Website.URL)));
website.put("type", getContactType(cursor.getInt(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Website.TYPE))));
} catch (JSONException e) {
Log.e(LOG_TAG, e.getMessage(), e);
}
return website;
}
/**
* Create a ContactField JSONObject
* @param contactId
* @return a JSONObject representing a ContactField
*/
private JSONObject photoQuery(Cursor cursor, String contactId) {
JSONObject photo = new JSONObject();
try {
photo.put("id", cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Photo._ID)));
photo.put("pref", false);
photo.put("type", "url");
Uri person = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, (new Long(contactId)));
Uri photoUri = Uri.withAppendedPath(person, ContactsContract.Contacts.Photo.CONTENT_DIRECTORY);
photo.put("value", photoUri.toString());
} catch (JSONException e) {
Log.e(LOG_TAG, e.getMessage(), e);
}
return photo;
}
@Override
/**
* This method will save a contact object into the devices contacts database.
*
* @param contact the contact to be saved.
* @returns the id if the contact is successfully saved, null otherwise.
*/
public String save(JSONObject contact) {
AccountManager mgr = AccountManager.get(mApp.getActivity());
Account[] accounts = mgr.getAccounts();
String accountName = null;
String accountType = null;
if (accounts.length == 1) {
accountName = accounts[0].name;
accountType = accounts[0].type;
}
else if (accounts.length > 1) {
for (Account a : accounts) {
if (a.type.contains("eas") && a.name.matches(EMAIL_REGEXP)) /*Exchange ActiveSync*/{
accountName = a.name;
accountType = a.type;
break;
}
}
if (accountName == null) {
for (Account a : accounts) {
if (a.type.contains("com.google") && a.name.matches(EMAIL_REGEXP)) /*Google sync provider*/{
accountName = a.name;
accountType = a.type;
break;
}
}
}
if (accountName == null) {
for (Account a : accounts) {
if (a.name.matches(EMAIL_REGEXP)) /*Last resort, just look for an email address...*/{
accountName = a.name;
accountType = a.type;
break;
}
}
}
}
String id = getJsonString(contact, "id");
// Create new contact
if (id == null) {
return createNewContact(contact, accountType, accountName);
}
// Modify existing contact
else {
return modifyContact(id, contact, accountType, accountName);
}
}
/**
* Creates a new contact and stores it in the database
*
* @param id the raw contact id which is required for linking items to the contact
* @param contact the contact to be saved
* @param account the account to be saved under
*/
private String modifyContact(String id, JSONObject contact, String accountType, String accountName) {
// Get the RAW_CONTACT_ID which is needed to insert new values in an already existing contact.
// But not needed to update existing values.
int rawId = (new Integer(getJsonString(contact, "rawId"))).intValue();
// Create a list of attributes to add to the contact database
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
//Add contact type
ops.add(ContentProviderOperation.newUpdate(ContactsContract.RawContacts.CONTENT_URI)
.withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, accountType)
.withValue(ContactsContract.RawContacts.ACCOUNT_NAME, accountName)
.build());
// Modify name
JSONObject name;
try {
String displayName = getJsonString(contact, "displayName");
name = contact.getJSONObject("name");
if (displayName != null || name != null) {
ContentProviderOperation.Builder builder = ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
.withSelection(ContactsContract.Data.CONTACT_ID + "=? AND " +
ContactsContract.Data.MIMETYPE + "=?",
new String[] { id, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE });
if (displayName != null) {
builder.withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, displayName);
}
String familyName = getJsonString(name, "familyName");
if (familyName != null) {
builder.withValue(ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME, familyName);
}
String middleName = getJsonString(name, "middleName");
if (middleName != null) {
builder.withValue(ContactsContract.CommonDataKinds.StructuredName.MIDDLE_NAME, middleName);
}
String givenName = getJsonString(name, "givenName");
if (givenName != null) {
builder.withValue(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME, givenName);
}
String honorificPrefix = getJsonString(name, "honorificPrefix");
if (honorificPrefix != null) {
builder.withValue(ContactsContract.CommonDataKinds.StructuredName.PREFIX, honorificPrefix);
}
String honorificSuffix = getJsonString(name, "honorificSuffix");
if (honorificSuffix != null) {
builder.withValue(ContactsContract.CommonDataKinds.StructuredName.SUFFIX, honorificSuffix);
}
ops.add(builder.build());
}
} catch (JSONException e1) {
Log.d(LOG_TAG, "Could not get name");
}
// Modify phone numbers
JSONArray phones = null;
try {
phones = contact.getJSONArray("phoneNumbers");
if (phones != null) {
// Delete all the phones
if (phones.length() == 0) {
ops.add(ContentProviderOperation.newDelete(ContactsContract.Data.CONTENT_URI)
.withSelection(ContactsContract.Data.RAW_CONTACT_ID + "=? AND " +
ContactsContract.Data.MIMETYPE + "=?",
new String[] { "" + rawId, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE })
.build());
}
// Modify or add a phone
else {
for (int i = 0; i < phones.length(); i++) {
JSONObject phone = (JSONObject) phones.get(i);
String phoneId = getJsonString(phone, "id");
// This is a new phone so do a DB insert
if (phoneId == null) {
ContentValues contentValues = new ContentValues();
contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, rawId);
contentValues.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
contentValues.put(ContactsContract.CommonDataKinds.Phone.NUMBER, getJsonString(phone, "value"));
contentValues.put(ContactsContract.CommonDataKinds.Phone.TYPE, getPhoneType(getJsonString(phone, "type")));
ops.add(ContentProviderOperation.newInsert(
ContactsContract.Data.CONTENT_URI).withValues(contentValues).build());
}
// This is an existing phone so do a DB update
else {
ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
.withSelection(ContactsContract.CommonDataKinds.Phone._ID + "=? AND " +
ContactsContract.Data.MIMETYPE + "=?",
new String[] { phoneId, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE })
.withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, getJsonString(phone, "value"))
.withValue(ContactsContract.CommonDataKinds.Phone.TYPE, getPhoneType(getJsonString(phone, "type")))
.build());
}
}
}
}
} catch (JSONException e) {
Log.d(LOG_TAG, "Could not get phone numbers");
}
// Modify emails
JSONArray emails = null;
try {
emails = contact.getJSONArray("emails");
if (emails != null) {
// Delete all the emails
if (emails.length() == 0) {
ops.add(ContentProviderOperation.newDelete(ContactsContract.Data.CONTENT_URI)
.withSelection(ContactsContract.Data.RAW_CONTACT_ID + "=? AND " +
ContactsContract.Data.MIMETYPE + "=?",
new String[] { "" + rawId, ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE })
.build());
}
// Modify or add a email
else {
for (int i = 0; i < emails.length(); i++) {
JSONObject email = (JSONObject) emails.get(i);
String emailId = getJsonString(email, "id");
// This is a new email so do a DB insert
if (emailId == null) {
ContentValues contentValues = new ContentValues();
contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, rawId);
contentValues.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE);
contentValues.put(ContactsContract.CommonDataKinds.Email.DATA, getJsonString(email, "value"));
contentValues.put(ContactsContract.CommonDataKinds.Email.TYPE, getContactType(getJsonString(email, "type")));
ops.add(ContentProviderOperation.newInsert(
ContactsContract.Data.CONTENT_URI).withValues(contentValues).build());
}
// This is an existing email so do a DB update
else {
ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
.withSelection(ContactsContract.CommonDataKinds.Email._ID + "=? AND " +
ContactsContract.Data.MIMETYPE + "=?",
new String[] { emailId, ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE })
.withValue(ContactsContract.CommonDataKinds.Email.DATA, getJsonString(email, "value"))
.withValue(ContactsContract.CommonDataKinds.Email.TYPE, getContactType(getJsonString(email, "type")))
.build());
}
}
}
}
} catch (JSONException e) {
Log.d(LOG_TAG, "Could not get emails");
}
// Modify addresses
JSONArray addresses = null;
try {
addresses = contact.getJSONArray("addresses");
if (addresses != null) {
// Delete all the addresses
if (addresses.length() == 0) {
ops.add(ContentProviderOperation.newDelete(ContactsContract.Data.CONTENT_URI)
.withSelection(ContactsContract.Data.RAW_CONTACT_ID + "=? AND " +
ContactsContract.Data.MIMETYPE + "=?",
new String[] { "" + rawId, ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE })
.build());
}
// Modify or add a address
else {
for (int i = 0; i < addresses.length(); i++) {
JSONObject address = (JSONObject) addresses.get(i);
String addressId = getJsonString(address, "id");
// This is a new address so do a DB insert
if (addressId == null) {
ContentValues contentValues = new ContentValues();
contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, rawId);
contentValues.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE);
contentValues.put(ContactsContract.CommonDataKinds.StructuredPostal.TYPE, getAddressType(getJsonString(address, "type")));
contentValues.put(ContactsContract.CommonDataKinds.StructuredPostal.FORMATTED_ADDRESS, getJsonString(address, "formatted"));
contentValues.put(ContactsContract.CommonDataKinds.StructuredPostal.STREET, getJsonString(address, "streetAddress"));
contentValues.put(ContactsContract.CommonDataKinds.StructuredPostal.CITY, getJsonString(address, "locality"));
contentValues.put(ContactsContract.CommonDataKinds.StructuredPostal.REGION, getJsonString(address, "region"));
contentValues.put(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE, getJsonString(address, "postalCode"));
contentValues.put(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY, getJsonString(address, "country"));
ops.add(ContentProviderOperation.newInsert(
ContactsContract.Data.CONTENT_URI).withValues(contentValues).build());
}
// This is an existing address so do a DB update
else {
ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
.withSelection(ContactsContract.CommonDataKinds.StructuredPostal._ID + "=? AND " +
ContactsContract.Data.MIMETYPE + "=?",
new String[] { addressId, ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE })
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.TYPE, getAddressType(getJsonString(address, "type")))
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.FORMATTED_ADDRESS, getJsonString(address, "formatted"))
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.STREET, getJsonString(address, "streetAddress"))
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.CITY, getJsonString(address, "locality"))
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.REGION, getJsonString(address, "region"))
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE, getJsonString(address, "postalCode"))
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY, getJsonString(address, "country"))
.build());
}
}
}
}
} catch (JSONException e) {
Log.d(LOG_TAG, "Could not get addresses");
}
// Modify organizations
JSONArray organizations = null;
try {
organizations = contact.getJSONArray("organizations");
if (organizations != null) {
// Delete all the organizations
if (organizations.length() == 0) {
ops.add(ContentProviderOperation.newDelete(ContactsContract.Data.CONTENT_URI)
.withSelection(ContactsContract.Data.RAW_CONTACT_ID + "=? AND " +
ContactsContract.Data.MIMETYPE + "=?",
new String[] { "" + rawId, ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE })
.build());
}
// Modify or add a organization
else {
for (int i = 0; i < organizations.length(); i++) {
JSONObject org = (JSONObject) organizations.get(i);
String orgId = getJsonString(org, "id");
// This is a new organization so do a DB insert
if (orgId == null) {
ContentValues contentValues = new ContentValues();
contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, rawId);
contentValues.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE);
contentValues.put(ContactsContract.CommonDataKinds.Organization.TYPE, getOrgType(getJsonString(org, "type")));
contentValues.put(ContactsContract.CommonDataKinds.Organization.DEPARTMENT, getJsonString(org, "department"));
contentValues.put(ContactsContract.CommonDataKinds.Organization.COMPANY, getJsonString(org, "name"));
contentValues.put(ContactsContract.CommonDataKinds.Organization.TITLE, getJsonString(org, "title"));
ops.add(ContentProviderOperation.newInsert(
ContactsContract.Data.CONTENT_URI).withValues(contentValues).build());
}
// This is an existing organization so do a DB update
else {
ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
.withSelection(ContactsContract.CommonDataKinds.Organization._ID + "=? AND " +
ContactsContract.Data.MIMETYPE + "=?",
new String[] { orgId, ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE })
.withValue(ContactsContract.CommonDataKinds.Organization.TYPE, getOrgType(getJsonString(org, "type")))
.withValue(ContactsContract.CommonDataKinds.Organization.DEPARTMENT, getJsonString(org, "department"))
.withValue(ContactsContract.CommonDataKinds.Organization.COMPANY, getJsonString(org, "name"))
.withValue(ContactsContract.CommonDataKinds.Organization.TITLE, getJsonString(org, "title"))
.build());
}
}
}
}
} catch (JSONException e) {
Log.d(LOG_TAG, "Could not get organizations");
}
// Modify IMs
JSONArray ims = null;
try {
ims = contact.getJSONArray("ims");
if (ims != null) {
// Delete all the ims
if (ims.length() == 0) {
ops.add(ContentProviderOperation.newDelete(ContactsContract.Data.CONTENT_URI)
.withSelection(ContactsContract.Data.RAW_CONTACT_ID + "=? AND " +
ContactsContract.Data.MIMETYPE + "=?",
new String[] { "" + rawId, ContactsContract.CommonDataKinds.Im.CONTENT_ITEM_TYPE })
.build());
}
// Modify or add a im
else {
for (int i = 0; i < ims.length(); i++) {
JSONObject im = (JSONObject) ims.get(i);
String imId = getJsonString(im, "id");
// This is a new IM so do a DB insert
if (imId == null) {
ContentValues contentValues = new ContentValues();
contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, rawId);
contentValues.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Im.CONTENT_ITEM_TYPE);
contentValues.put(ContactsContract.CommonDataKinds.Im.DATA, getJsonString(im, "value"));
contentValues.put(ContactsContract.CommonDataKinds.Im.TYPE, getContactType(getJsonString(im, "type")));
ops.add(ContentProviderOperation.newInsert(
ContactsContract.Data.CONTENT_URI).withValues(contentValues).build());
}
// This is an existing IM so do a DB update
else {
ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
.withSelection(ContactsContract.CommonDataKinds.Im._ID + "=? AND " +
ContactsContract.Data.MIMETYPE + "=?",
new String[] { imId, ContactsContract.CommonDataKinds.Im.CONTENT_ITEM_TYPE })
.withValue(ContactsContract.CommonDataKinds.Im.DATA, getJsonString(im, "value"))
.withValue(ContactsContract.CommonDataKinds.Im.TYPE, getContactType(getJsonString(im, "type")))
.build());
}
}
}
}
} catch (JSONException e) {
Log.d(LOG_TAG, "Could not get emails");
}
// Modify note
String note = getJsonString(contact, "note");
ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
.withSelection(ContactsContract.Data.CONTACT_ID + "=? AND " +
ContactsContract.Data.MIMETYPE + "=?",
new String[] { id, ContactsContract.CommonDataKinds.Note.CONTENT_ITEM_TYPE })
.withValue(ContactsContract.CommonDataKinds.Note.NOTE, note)
.build());
// Modify nickname
String nickname = getJsonString(contact, "nickname");
if (nickname != null) {
ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
.withSelection(ContactsContract.Data.CONTACT_ID + "=? AND " +
ContactsContract.Data.MIMETYPE + "=?",
new String[] { id, ContactsContract.CommonDataKinds.Nickname.CONTENT_ITEM_TYPE })
.withValue(ContactsContract.CommonDataKinds.Nickname.NAME, nickname)
.build());
}
// Modify urls
JSONArray websites = null;
try {
websites = contact.getJSONArray("urls");
if (websites != null) {
// Delete all the websites
if (websites.length() == 0) {
Log.d(LOG_TAG, "This means we should be deleting all the phone numbers.");
ops.add(ContentProviderOperation.newDelete(ContactsContract.Data.CONTENT_URI)
.withSelection(ContactsContract.Data.RAW_CONTACT_ID + "=? AND " +
ContactsContract.Data.MIMETYPE + "=?",
new String[] { "" + rawId, ContactsContract.CommonDataKinds.Website.CONTENT_ITEM_TYPE })
.build());
}
// Modify or add a website
else {
for (int i = 0; i < websites.length(); i++) {
JSONObject website = (JSONObject) websites.get(i);
String websiteId = getJsonString(website, "id");
// This is a new website so do a DB insert
if (websiteId == null) {
ContentValues contentValues = new ContentValues();
contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, rawId);
contentValues.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Website.CONTENT_ITEM_TYPE);
contentValues.put(ContactsContract.CommonDataKinds.Website.DATA, getJsonString(website, "value"));
contentValues.put(ContactsContract.CommonDataKinds.Website.TYPE, getContactType(getJsonString(website, "type")));
ops.add(ContentProviderOperation.newInsert(
ContactsContract.Data.CONTENT_URI).withValues(contentValues).build());
}
// This is an existing website so do a DB update
else {
ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
.withSelection(ContactsContract.CommonDataKinds.Website._ID + "=? AND " +
ContactsContract.Data.MIMETYPE + "=?",
new String[] { websiteId, ContactsContract.CommonDataKinds.Website.CONTENT_ITEM_TYPE })
.withValue(ContactsContract.CommonDataKinds.Website.DATA, getJsonString(website, "value"))
.withValue(ContactsContract.CommonDataKinds.Website.TYPE, getContactType(getJsonString(website, "type")))
.build());
}
}
}
}
} catch (JSONException e) {
Log.d(LOG_TAG, "Could not get websites");
}
// Modify birthday
String birthday = getJsonString(contact, "birthday");
if (birthday != null) {
ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
.withSelection(ContactsContract.Data.CONTACT_ID + "=? AND " +
ContactsContract.Data.MIMETYPE + "=? AND " +
ContactsContract.CommonDataKinds.Event.TYPE + "=?",
new String[] { id, ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE, new String("" + ContactsContract.CommonDataKinds.Event.TYPE_BIRTHDAY) })
.withValue(ContactsContract.CommonDataKinds.Event.TYPE, ContactsContract.CommonDataKinds.Event.TYPE_BIRTHDAY)
.withValue(ContactsContract.CommonDataKinds.Event.START_DATE, birthday)
.build());
}
// Modify photos
JSONArray photos = null;
try {
photos = contact.getJSONArray("photos");
if (photos != null) {
// Delete all the photos
if (photos.length() == 0) {
ops.add(ContentProviderOperation.newDelete(ContactsContract.Data.CONTENT_URI)
.withSelection(ContactsContract.Data.RAW_CONTACT_ID + "=? AND " +
ContactsContract.Data.MIMETYPE + "=?",
new String[] { "" + rawId, ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE })
.build());
}
// Modify or add a photo
else {
for (int i = 0; i < photos.length(); i++) {
JSONObject photo = (JSONObject) photos.get(i);
String photoId = getJsonString(photo, "id");
byte[] bytes = getPhotoBytes(getJsonString(photo, "value"));
// This is a new photo so do a DB insert
if (photoId == null) {
ContentValues contentValues = new ContentValues();
contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, rawId);
contentValues.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE);
contentValues.put(ContactsContract.Data.IS_SUPER_PRIMARY, 1);
contentValues.put(ContactsContract.CommonDataKinds.Photo.PHOTO, bytes);
ops.add(ContentProviderOperation.newInsert(
ContactsContract.Data.CONTENT_URI).withValues(contentValues).build());
}
// This is an existing photo so do a DB update
else {
ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
.withSelection(ContactsContract.CommonDataKinds.Photo._ID + "=? AND " +
ContactsContract.Data.MIMETYPE + "=?",
new String[] { photoId, ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE })
.withValue(ContactsContract.Data.IS_SUPER_PRIMARY, 1)
.withValue(ContactsContract.CommonDataKinds.Photo.PHOTO, bytes)
.build());
}
}
}
}
} catch (JSONException e) {
Log.d(LOG_TAG, "Could not get photos");
}
boolean retVal = true;
//Modify contact
try {
mApp.getActivity().getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
} catch (RemoteException e) {
Log.e(LOG_TAG, e.getMessage(), e);
Log.e(LOG_TAG, Log.getStackTraceString(e), e);
retVal = false;
} catch (OperationApplicationException e) {
Log.e(LOG_TAG, e.getMessage(), e);
Log.e(LOG_TAG, Log.getStackTraceString(e), e);
retVal = false;
}
// if the save was a success return the contact ID
if (retVal) {
return id;
} else {
return null;
}
}
/**
* Add a website to a list of database actions to be performed
*
* @param ops the list of database actions
* @param website the item to be inserted
*/
private void insertWebsite(ArrayList<ContentProviderOperation> ops,
JSONObject website) {
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Website.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.Website.DATA, getJsonString(website, "value"))
.withValue(ContactsContract.CommonDataKinds.Website.TYPE, getContactType(getJsonString(website, "type")))
.build());
}
/**
* Add an im to a list of database actions to be performed
*
* @param ops the list of database actions
* @param im the item to be inserted
*/
private void insertIm(ArrayList<ContentProviderOperation> ops, JSONObject im) {
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Im.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.Im.DATA, getJsonString(im, "value"))
.withValue(ContactsContract.CommonDataKinds.Im.TYPE, getContactType(getJsonString(im, "type")))
.build());
}
/**
* Add an organization to a list of database actions to be performed
*
* @param ops the list of database actions
* @param org the item to be inserted
*/
private void insertOrganization(ArrayList<ContentProviderOperation> ops,
JSONObject org) {
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.Organization.TYPE, getOrgType(getJsonString(org, "type")))
.withValue(ContactsContract.CommonDataKinds.Organization.DEPARTMENT, getJsonString(org, "department"))
.withValue(ContactsContract.CommonDataKinds.Organization.COMPANY, getJsonString(org, "name"))
.withValue(ContactsContract.CommonDataKinds.Organization.TITLE, getJsonString(org, "title"))
.build());
}
/**
* Add an address to a list of database actions to be performed
*
* @param ops the list of database actions
* @param address the item to be inserted
*/
private void insertAddress(ArrayList<ContentProviderOperation> ops,
JSONObject address) {
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.TYPE, getAddressType(getJsonString(address, "type")))
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.FORMATTED_ADDRESS, getJsonString(address, "formatted"))
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.STREET, getJsonString(address, "streetAddress"))
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.CITY, getJsonString(address, "locality"))
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.REGION, getJsonString(address, "region"))
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE, getJsonString(address, "postalCode"))
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY, getJsonString(address, "country"))
.build());
}
/**
* Add an email to a list of database actions to be performed
*
* @param ops the list of database actions
* @param email the item to be inserted
*/
private void insertEmail(ArrayList<ContentProviderOperation> ops,
JSONObject email) {
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.Email.DATA, getJsonString(email, "value"))
.withValue(ContactsContract.CommonDataKinds.Email.TYPE, getPhoneType(getJsonString(email, "type")))
.build());
}
/**
* Add a phone to a list of database actions to be performed
*
* @param ops the list of database actions
* @param phone the item to be inserted
*/
private void insertPhone(ArrayList<ContentProviderOperation> ops,
JSONObject phone) {
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, getJsonString(phone, "value"))
.withValue(ContactsContract.CommonDataKinds.Phone.TYPE, getPhoneType(getJsonString(phone, "type")))
.build());
}
/**
* Add a phone to a list of database actions to be performed
*
* @param ops the list of database actions
* @param phone the item to be inserted
*/
private void insertPhoto(ArrayList<ContentProviderOperation> ops,
JSONObject photo) {
byte[] bytes = getPhotoBytes(getJsonString(photo, "value"));
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
.withValue(ContactsContract.Data.IS_SUPER_PRIMARY, 1)
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.Photo.PHOTO, bytes)
.build());
}
/**
* Gets the raw bytes from the supplied filename
*
* @param filename the file to read the bytes from
* @return a byte array
* @throws IOException
*/
private byte[] getPhotoBytes(String filename) {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
try {
int bytesRead = 0;
long totalBytesRead = 0;
byte[] data = new byte[8192];
InputStream in = getPathFromUri(filename);
while ((bytesRead = in.read(data, 0, data.length)) != -1 && totalBytesRead <= MAX_PHOTO_SIZE) {
buffer.write(data, 0, bytesRead);
totalBytesRead += bytesRead;
}
in.close();
buffer.flush();
} catch (FileNotFoundException e) {
Log.e(LOG_TAG, e.getMessage(), e);
} catch (IOException e) {
Log.e(LOG_TAG, e.getMessage(), e);
}
return buffer.toByteArray();
}
/**
* Get an input stream based on file path or uri content://, http://, file://
*
* @param path
* @return an input stream
* @throws IOException
*/
private InputStream getPathFromUri(String path) throws IOException {
if (path.startsWith("content:")) {
Uri uri = Uri.parse(path);
return mApp.getActivity().getContentResolver().openInputStream(uri);
}
if (path.startsWith("http:") || path.startsWith("file:")) {
URL url = new URL(path);
return url.openStream();
}
else {
return new FileInputStream(path);
}
}
/**
* Creates a new contact and stores it in the database
*
* @param contact the contact to be saved
* @param account the account to be saved under
*/
private String createNewContact(JSONObject contact, String accountType, String accountName) {
// Create a list of attributes to add to the contact database
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
//Add contact type
ops.add(ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI)
.withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, accountType)
.withValue(ContactsContract.RawContacts.ACCOUNT_NAME, accountName)
.build());
// Add name
try {
JSONObject name = contact.optJSONObject("name");
String displayName = contact.getString("displayName");
if (displayName != null || name != null) {
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, displayName)
.withValue(ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME, getJsonString(name, "familyName"))
.withValue(ContactsContract.CommonDataKinds.StructuredName.MIDDLE_NAME, getJsonString(name, "middleName"))
.withValue(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME, getJsonString(name, "givenName"))
.withValue(ContactsContract.CommonDataKinds.StructuredName.PREFIX, getJsonString(name, "honorificPrefix"))
.withValue(ContactsContract.CommonDataKinds.StructuredName.SUFFIX, getJsonString(name, "honorificSuffix"))
.build());
}
} catch (JSONException e) {
Log.d(LOG_TAG, "Could not get name object");
}
//Add phone numbers
JSONArray phones = null;
try {
phones = contact.getJSONArray("phoneNumbers");
if (phones != null) {
for (int i = 0; i < phones.length(); i++) {
JSONObject phone = (JSONObject) phones.get(i);
insertPhone(ops, phone);
}
}
} catch (JSONException e) {
Log.d(LOG_TAG, "Could not get phone numbers");
}
// Add emails
JSONArray emails = null;
try {
emails = contact.getJSONArray("emails");
if (emails != null) {
for (int i = 0; i < emails.length(); i++) {
JSONObject email = (JSONObject) emails.get(i);
insertEmail(ops, email);
}
}
} catch (JSONException e) {
Log.d(LOG_TAG, "Could not get emails");
}
// Add addresses
JSONArray addresses = null;
try {
addresses = contact.getJSONArray("addresses");
if (addresses != null) {
for (int i = 0; i < addresses.length(); i++) {
JSONObject address = (JSONObject) addresses.get(i);
insertAddress(ops, address);
}
}
} catch (JSONException e) {
Log.d(LOG_TAG, "Could not get addresses");
}
// Add organizations
JSONArray organizations = null;
try {
organizations = contact.getJSONArray("organizations");
if (organizations != null) {
for (int i = 0; i < organizations.length(); i++) {
JSONObject org = (JSONObject) organizations.get(i);
insertOrganization(ops, org);
}
}
} catch (JSONException e) {
Log.d(LOG_TAG, "Could not get organizations");
}
// Add IMs
JSONArray ims = null;
try {
ims = contact.getJSONArray("ims");
if (ims != null) {
for (int i = 0; i < ims.length(); i++) {
JSONObject im = (JSONObject) ims.get(i);
insertIm(ops, im);
}
}
} catch (JSONException e) {
Log.d(LOG_TAG, "Could not get emails");
}
// Add note
String note = getJsonString(contact, "note");
if (note != null) {
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Note.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.Note.NOTE, note)
.build());
}
// Add nickname
String nickname = getJsonString(contact, "nickname");
if (nickname != null) {
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Nickname.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.Nickname.NAME, nickname)
.build());
}
// Add urls
JSONArray websites = null;
try {
websites = contact.getJSONArray("urls");
if (websites != null) {
for (int i = 0; i < websites.length(); i++) {
JSONObject website = (JSONObject) websites.get(i);
insertWebsite(ops, website);
}
}
} catch (JSONException e) {
Log.d(LOG_TAG, "Could not get websites");
}
// Add birthday
String birthday = getJsonString(contact, "birthday");
if (birthday != null) {
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.Event.TYPE, ContactsContract.CommonDataKinds.Event.TYPE_BIRTHDAY)
.withValue(ContactsContract.CommonDataKinds.Event.START_DATE, birthday)
.build());
}
// Add photos
JSONArray photos = null;
try {
photos = contact.getJSONArray("photos");
if (photos != null) {
for (int i = 0; i < photos.length(); i++) {
JSONObject photo = (JSONObject) photos.get(i);
insertPhoto(ops, photo);
}
}
} catch (JSONException e) {
Log.d(LOG_TAG, "Could not get photos");
}
String newId = null;
//Add contact
try {
ContentProviderResult[] cpResults = mApp.getActivity().getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
if (cpResults.length >= 0) {
newId = cpResults[0].uri.getLastPathSegment();
}
} catch (RemoteException e) {
Log.e(LOG_TAG, e.getMessage(), e);
} catch (OperationApplicationException e) {
Log.e(LOG_TAG, e.getMessage(), e);
}
return newId;
}
@Override
/**
* This method will remove a Contact from the database based on ID.
* @param id the unique ID of the contact to remove
*/
public boolean remove(String id) {
int result = 0;
Cursor cursor = mApp.getActivity().getContentResolver().query(ContactsContract.Contacts.CONTENT_URI,
null,
ContactsContract.Contacts._ID + " = ?",
new String[] { id }, null);
if (cursor.getCount() == 1) {
cursor.moveToFirst();
String lookupKey = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_LOOKUP_URI, lookupKey);
result = mApp.getActivity().getContentResolver().delete(uri, null, null);
} else {
Log.d(LOG_TAG, "Could not find contact with ID");
}
return (result > 0) ? true : false;
}
/**************************************************************************
*
* All methods below this comment are used to convert from JavaScript
* text types to Android integer types and vice versa.
*
*************************************************************************/
/**
* Converts a string from the W3C Contact API to it's Android int value.
* @param string
* @return Android int value
*/
private int getPhoneType(String string) {
int type = ContactsContract.CommonDataKinds.Phone.TYPE_OTHER;
if (string != null) {
if ("home".equals(string.toLowerCase())) {
return ContactsContract.CommonDataKinds.Phone.TYPE_HOME;
}
else if ("mobile".equals(string.toLowerCase())) {
return ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE;
}
else if ("work".equals(string.toLowerCase())) {
return ContactsContract.CommonDataKinds.Phone.TYPE_WORK;
}
else if ("work fax".equals(string.toLowerCase())) {
return ContactsContract.CommonDataKinds.Phone.TYPE_FAX_WORK;
}
else if ("home fax".equals(string.toLowerCase())) {
return ContactsContract.CommonDataKinds.Phone.TYPE_FAX_HOME;
}
else if ("fax".equals(string.toLowerCase())) {
return ContactsContract.CommonDataKinds.Phone.TYPE_FAX_WORK;
}
else if ("pager".equals(string.toLowerCase())) {
return ContactsContract.CommonDataKinds.Phone.TYPE_PAGER;
}
else if ("other".equals(string.toLowerCase())) {
return ContactsContract.CommonDataKinds.Phone.TYPE_OTHER;
}
else if ("car".equals(string.toLowerCase())) {
return ContactsContract.CommonDataKinds.Phone.TYPE_CAR;
}
else if ("company main".equals(string.toLowerCase())) {
return ContactsContract.CommonDataKinds.Phone.TYPE_COMPANY_MAIN;
}
else if ("isdn".equals(string.toLowerCase())) {
return ContactsContract.CommonDataKinds.Phone.TYPE_ISDN;
}
else if ("main".equals(string.toLowerCase())) {
return ContactsContract.CommonDataKinds.Phone.TYPE_MAIN;
}
else if ("other fax".equals(string.toLowerCase())) {
return ContactsContract.CommonDataKinds.Phone.TYPE_OTHER_FAX;
}
else if ("radio".equals(string.toLowerCase())) {
return ContactsContract.CommonDataKinds.Phone.TYPE_RADIO;
}
else if ("telex".equals(string.toLowerCase())) {
return ContactsContract.CommonDataKinds.Phone.TYPE_TELEX;
}
else if ("work mobile".equals(string.toLowerCase())) {
return ContactsContract.CommonDataKinds.Phone.TYPE_WORK_MOBILE;
}
else if ("work pager".equals(string.toLowerCase())) {
return ContactsContract.CommonDataKinds.Phone.TYPE_WORK_PAGER;
}
else if ("assistant".equals(string.toLowerCase())) {
return ContactsContract.CommonDataKinds.Phone.TYPE_ASSISTANT;
}
else if ("mms".equals(string.toLowerCase())) {
return ContactsContract.CommonDataKinds.Phone.TYPE_MMS;
}
else if ("callback".equals(string.toLowerCase())) {
return ContactsContract.CommonDataKinds.Phone.TYPE_CALLBACK;
}
else if ("tty ttd".equals(string.toLowerCase())) {
return ContactsContract.CommonDataKinds.Phone.TYPE_TTY_TDD;
}
else if ("custom".equals(string.toLowerCase())) {
return ContactsContract.CommonDataKinds.Phone.TYPE_CUSTOM;
}
}
return type;
}
/**
* getPhoneType converts an Android phone type into a string
* @param type
* @return phone type as string.
*/
private String getPhoneType(int type) {
String stringType;
switch (type) {
case ContactsContract.CommonDataKinds.Phone.TYPE_CUSTOM:
stringType = "custom";
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_FAX_HOME:
stringType = "home fax";
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_FAX_WORK:
stringType = "work fax";
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_HOME:
stringType = "home";
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE:
stringType = "mobile";
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_PAGER:
stringType = "pager";
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_WORK:
stringType = "work";
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_CALLBACK:
stringType = "callback";
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_CAR:
stringType = "car";
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_COMPANY_MAIN:
stringType = "company main";
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_OTHER_FAX:
stringType = "other fax";
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_RADIO:
stringType = "radio";
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_TELEX:
stringType = "telex";
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_TTY_TDD:
stringType = "tty tdd";
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_WORK_MOBILE:
stringType = "work mobile";
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_WORK_PAGER:
stringType = "work pager";
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_ASSISTANT:
stringType = "assistant";
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_MMS:
stringType = "mms";
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_ISDN:
stringType = "isdn";
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_OTHER:
default:
stringType = "other";
break;
}
return stringType;
}
/**
* Converts a string from the W3C Contact API to it's Android int value.
* @param string
* @return Android int value
*/
private int getContactType(String string) {
int type = ContactsContract.CommonDataKinds.Email.TYPE_OTHER;
if (string != null) {
if ("home".equals(string.toLowerCase())) {
return ContactsContract.CommonDataKinds.Email.TYPE_HOME;
}
else if ("work".equals(string.toLowerCase())) {
return ContactsContract.CommonDataKinds.Email.TYPE_WORK;
}
else if ("other".equals(string.toLowerCase())) {
return ContactsContract.CommonDataKinds.Email.TYPE_OTHER;
}
else if ("mobile".equals(string.toLowerCase())) {
return ContactsContract.CommonDataKinds.Email.TYPE_MOBILE;
}
else if ("custom".equals(string.toLowerCase())) {
return ContactsContract.CommonDataKinds.Email.TYPE_CUSTOM;
}
}
return type;
}
/**
* getPhoneType converts an Android phone type into a string
* @param type
* @return phone type as string.
*/
private String getContactType(int type) {
String stringType;
switch (type) {
case ContactsContract.CommonDataKinds.Email.TYPE_CUSTOM:
stringType = "custom";
break;
case ContactsContract.CommonDataKinds.Email.TYPE_HOME:
stringType = "home";
break;
case ContactsContract.CommonDataKinds.Email.TYPE_WORK:
stringType = "work";
break;
case ContactsContract.CommonDataKinds.Email.TYPE_MOBILE:
stringType = "mobile";
break;
case ContactsContract.CommonDataKinds.Email.TYPE_OTHER:
default:
stringType = "other";
break;
}
return stringType;
}
/**
* Converts a string from the W3C Contact API to it's Android int value.
* @param string
* @return Android int value
*/
private int getOrgType(String string) {
int type = ContactsContract.CommonDataKinds.Organization.TYPE_OTHER;
if (string != null) {
if ("work".equals(string.toLowerCase())) {
return ContactsContract.CommonDataKinds.Organization.TYPE_WORK;
}
else if ("other".equals(string.toLowerCase())) {
return ContactsContract.CommonDataKinds.Organization.TYPE_OTHER;
}
else if ("custom".equals(string.toLowerCase())) {
return ContactsContract.CommonDataKinds.Organization.TYPE_CUSTOM;
}
}
return type;
}
/**
* getPhoneType converts an Android phone type into a string
* @param type
* @return phone type as string.
*/
private String getOrgType(int type) {
String stringType;
switch (type) {
case ContactsContract.CommonDataKinds.Organization.TYPE_CUSTOM:
stringType = "custom";
break;
case ContactsContract.CommonDataKinds.Organization.TYPE_WORK:
stringType = "work";
break;
case ContactsContract.CommonDataKinds.Organization.TYPE_OTHER:
default:
stringType = "other";
break;
}
return stringType;
}
/**
* Converts a string from the W3C Contact API to it's Android int value.
* @param string
* @return Android int value
*/
private int getAddressType(String string) {
int type = ContactsContract.CommonDataKinds.StructuredPostal.TYPE_OTHER;
if (string != null) {
if ("work".equals(string.toLowerCase())) {
return ContactsContract.CommonDataKinds.StructuredPostal.TYPE_WORK;
}
else if ("other".equals(string.toLowerCase())) {
return ContactsContract.CommonDataKinds.StructuredPostal.TYPE_OTHER;
}
else if ("home".equals(string.toLowerCase())) {
return ContactsContract.CommonDataKinds.StructuredPostal.TYPE_HOME;
}
}
return type;
}
/**
* getPhoneType converts an Android phone type into a string
* @param type
* @return phone type as string.
*/
private String getAddressType(int type) {
String stringType;
switch (type) {
case ContactsContract.CommonDataKinds.StructuredPostal.TYPE_HOME:
stringType = "home";
break;
case ContactsContract.CommonDataKinds.StructuredPostal.TYPE_WORK:
stringType = "work";
break;
case ContactsContract.CommonDataKinds.StructuredPostal.TYPE_OTHER:
default:
stringType = "other";
break;
}
return stringType;
}
}
|
framework/src/org/apache/cordova/ContactAccessorSdk5.java
|
/*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
package org.apache.cordova;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.content.ContentProviderOperation;
import android.content.ContentProviderResult;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.OperationApplicationException;
import android.database.Cursor;
import android.net.Uri;
import android.os.Debug;
import android.os.RemoteException;
import android.provider.ContactsContract;
import android.util.Log;
import android.webkit.WebView;
import org.apache.cordova.api.CordovaInterface;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
//import android.app.Activity;
//import android.content.Context;
/**
* An implementation of {@link ContactAccessor} that uses current Contacts API.
* This class should be used on Eclair or beyond, but would not work on any earlier
* release of Android. As a matter of fact, it could not even be loaded.
* <p>
* This implementation has several advantages:
* <ul>
* <li>It sees contacts from multiple accounts.
* <li>It works with aggregated contacts. So for example, if the contact is the result
* of aggregation of two raw contacts from different accounts, it may return the name from
* one and the phone number from the other.
* <li>It is efficient because it uses the more efficient current API.
* <li>Not obvious in this particular example, but it has access to new kinds
* of data available exclusively through the new APIs. Exercise for the reader: add support
* for nickname (see {@link android.provider.ContactsContract.CommonDataKinds.Nickname}) or
* social status updates (see {@link android.provider.ContactsContract.StatusUpdates}).
* </ul>
*/
public class ContactAccessorSdk5 extends ContactAccessor {
/**
* Keep the photo size under the 1 MB blog limit.
*/
private static final long MAX_PHOTO_SIZE = 1048576;
private static final String EMAIL_REGEXP = ".+@.+\\.+.+"; /* <anything>@<anything>.<anything>*/
/**
* A static map that converts the JavaScript property name to Android database column name.
*/
private static final Map<String, String> dbMap = new HashMap<String, String>();
static {
dbMap.put("id", ContactsContract.Data.CONTACT_ID);
dbMap.put("displayName", ContactsContract.Contacts.DISPLAY_NAME);
dbMap.put("name", ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME);
dbMap.put("name.formatted", ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME);
dbMap.put("name.familyName", ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME);
dbMap.put("name.givenName", ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME);
dbMap.put("name.middleName", ContactsContract.CommonDataKinds.StructuredName.MIDDLE_NAME);
dbMap.put("name.honorificPrefix", ContactsContract.CommonDataKinds.StructuredName.PREFIX);
dbMap.put("name.honorificSuffix", ContactsContract.CommonDataKinds.StructuredName.SUFFIX);
dbMap.put("nickname", ContactsContract.CommonDataKinds.Nickname.NAME);
dbMap.put("phoneNumbers", ContactsContract.CommonDataKinds.Phone.NUMBER);
dbMap.put("phoneNumbers.value", ContactsContract.CommonDataKinds.Phone.NUMBER);
dbMap.put("emails", ContactsContract.CommonDataKinds.Email.DATA);
dbMap.put("emails.value", ContactsContract.CommonDataKinds.Email.DATA);
dbMap.put("addresses", ContactsContract.CommonDataKinds.StructuredPostal.FORMATTED_ADDRESS);
dbMap.put("addresses.formatted", ContactsContract.CommonDataKinds.StructuredPostal.FORMATTED_ADDRESS);
dbMap.put("addresses.streetAddress", ContactsContract.CommonDataKinds.StructuredPostal.STREET);
dbMap.put("addresses.locality", ContactsContract.CommonDataKinds.StructuredPostal.CITY);
dbMap.put("addresses.region", ContactsContract.CommonDataKinds.StructuredPostal.REGION);
dbMap.put("addresses.postalCode", ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE);
dbMap.put("addresses.country", ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY);
dbMap.put("ims", ContactsContract.CommonDataKinds.Im.DATA);
dbMap.put("ims.value", ContactsContract.CommonDataKinds.Im.DATA);
dbMap.put("organizations", ContactsContract.CommonDataKinds.Organization.COMPANY);
dbMap.put("organizations.name", ContactsContract.CommonDataKinds.Organization.COMPANY);
dbMap.put("organizations.department", ContactsContract.CommonDataKinds.Organization.DEPARTMENT);
dbMap.put("organizations.title", ContactsContract.CommonDataKinds.Organization.TITLE);
dbMap.put("birthday", ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE);
dbMap.put("note", ContactsContract.CommonDataKinds.Note.NOTE);
dbMap.put("photos.value", ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE);
//dbMap.put("categories.value", null);
dbMap.put("urls", ContactsContract.CommonDataKinds.Website.URL);
dbMap.put("urls.value", ContactsContract.CommonDataKinds.Website.URL);
}
/**
* Create an contact accessor.
*/
public ContactAccessorSdk5(WebView view, CordovaInterface context) {
mApp = context;
mView = view;
}
/**
* This method takes the fields required and search options in order to produce an
* array of contacts that matches the criteria provided.
* @param fields an array of items to be used as search criteria
* @param options that can be applied to contact searching
* @return an array of contacts
*/
@Override
public JSONArray search(JSONArray fields, JSONObject options) {
// Get the find options
String searchTerm = "";
int limit = Integer.MAX_VALUE;
boolean multiple = true;
if (options != null) {
searchTerm = options.optString("filter");
if (searchTerm.length() == 0) {
searchTerm = "%";
}
else {
searchTerm = "%" + searchTerm + "%";
}
try {
multiple = options.getBoolean("multiple");
if (!multiple) {
limit = 1;
}
} catch (JSONException e) {
// Multiple was not specified so we assume the default is true.
}
}
else {
searchTerm = "%";
}
//Log.d(LOG_TAG, "Search Term = " + searchTerm);
//Log.d(LOG_TAG, "Field Length = " + fields.length());
//Log.d(LOG_TAG, "Fields = " + fields.toString());
// Loop through the fields the user provided to see what data should be returned.
HashMap<String, Boolean> populate = buildPopulationSet(fields);
// Build the ugly where clause and where arguments for one big query.
WhereOptions whereOptions = buildWhereClause(fields, searchTerm);
// Get all the id's where the search term matches the fields passed in.
Cursor idCursor = mApp.getActivity().getContentResolver().query(ContactsContract.Data.CONTENT_URI,
new String[] { ContactsContract.Data.CONTACT_ID },
whereOptions.getWhere(),
whereOptions.getWhereArgs(),
ContactsContract.Data.CONTACT_ID + " ASC");
// Create a set of unique ids
Set<String> contactIds = new HashSet<String>();
int idColumn = -1;
while (idCursor.moveToNext()) {
if (idColumn < 0) {
idColumn = idCursor.getColumnIndex(ContactsContract.Data.CONTACT_ID);
}
contactIds.add(idCursor.getString(idColumn));
}
idCursor.close();
// Build a query that only looks at ids
WhereOptions idOptions = buildIdClause(contactIds, searchTerm);
// Determine which columns we should be fetching.
HashSet<String> columnsToFetch = new HashSet<String>();
columnsToFetch.add(ContactsContract.Data.CONTACT_ID);
columnsToFetch.add(ContactsContract.Data.RAW_CONTACT_ID);
columnsToFetch.add(ContactsContract.Data.MIMETYPE);
if (isRequired("displayName", populate)) {
columnsToFetch.add(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME);
}
if (isRequired("name", populate)) {
columnsToFetch.add(ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME);
columnsToFetch.add(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME);
columnsToFetch.add(ContactsContract.CommonDataKinds.StructuredName.MIDDLE_NAME);
columnsToFetch.add(ContactsContract.CommonDataKinds.StructuredName.PREFIX);
columnsToFetch.add(ContactsContract.CommonDataKinds.StructuredName.SUFFIX);
}
if (isRequired("phoneNumbers", populate)) {
columnsToFetch.add(ContactsContract.CommonDataKinds.Phone._ID);
columnsToFetch.add(ContactsContract.CommonDataKinds.Phone.NUMBER);
columnsToFetch.add(ContactsContract.CommonDataKinds.Phone.TYPE);
}
if (isRequired("emails", populate)) {
columnsToFetch.add(ContactsContract.CommonDataKinds.Email.DATA);
columnsToFetch.add(ContactsContract.CommonDataKinds.Email.TYPE);
}
if (isRequired("addresses", populate)) {
columnsToFetch.add(ContactsContract.CommonDataKinds.StructuredPostal._ID);
columnsToFetch.add(ContactsContract.CommonDataKinds.Organization.TYPE);
columnsToFetch.add(ContactsContract.CommonDataKinds.StructuredPostal.FORMATTED_ADDRESS);
columnsToFetch.add(ContactsContract.CommonDataKinds.StructuredPostal.STREET);
columnsToFetch.add(ContactsContract.CommonDataKinds.StructuredPostal.CITY);
columnsToFetch.add(ContactsContract.CommonDataKinds.StructuredPostal.REGION);
columnsToFetch.add(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE);
columnsToFetch.add(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY);
}
if (isRequired("organizations", populate)) {
columnsToFetch.add(ContactsContract.CommonDataKinds.Organization._ID);
columnsToFetch.add(ContactsContract.CommonDataKinds.Organization.TYPE);
columnsToFetch.add(ContactsContract.CommonDataKinds.Organization.DEPARTMENT);
columnsToFetch.add(ContactsContract.CommonDataKinds.Organization.COMPANY);
columnsToFetch.add(ContactsContract.CommonDataKinds.Organization.TITLE);
}
if (isRequired("ims", populate)) {
columnsToFetch.add(ContactsContract.CommonDataKinds.Im._ID);
columnsToFetch.add(ContactsContract.CommonDataKinds.Im.DATA);
columnsToFetch.add(ContactsContract.CommonDataKinds.Im.TYPE);
}
if (isRequired("note", populate)) {
columnsToFetch.add(ContactsContract.CommonDataKinds.Note.NOTE);
}
if (isRequired("nickname", populate)) {
columnsToFetch.add(ContactsContract.CommonDataKinds.Nickname.NAME);
}
if (isRequired("urls", populate)) {
columnsToFetch.add(ContactsContract.CommonDataKinds.Website._ID);
columnsToFetch.add(ContactsContract.CommonDataKinds.Website.URL);
columnsToFetch.add(ContactsContract.CommonDataKinds.Website.TYPE);
}
if (isRequired("birthday", populate)) {
columnsToFetch.add(ContactsContract.CommonDataKinds.Event.START_DATE);
columnsToFetch.add(ContactsContract.CommonDataKinds.Event.TYPE);
}
if (isRequired("photos", populate)) {
columnsToFetch.add(ContactsContract.CommonDataKinds.Photo._ID);
}
// Do the id query
Cursor c = mApp.getActivity().getContentResolver().query(ContactsContract.Data.CONTENT_URI,
columnsToFetch.toArray(new String[] {}),
idOptions.getWhere(),
idOptions.getWhereArgs(),
ContactsContract.Data.CONTACT_ID + " ASC");
JSONArray contacts = populateContactArray(limit, populate, c);
return contacts;
}
/**
* A special search that finds one contact by id
*
* @param id contact to find by id
* @return a JSONObject representing the contact
* @throws JSONException
*/
public JSONObject getContactById(String id) throws JSONException {
// Do the id query
Cursor c = mApp.getActivity().getContentResolver().query(ContactsContract.Data.CONTENT_URI,
null,
ContactsContract.Data.CONTACT_ID + " = ? ",
new String[] { id },
ContactsContract.Data.CONTACT_ID + " ASC");
JSONArray fields = new JSONArray();
fields.put("*");
HashMap<String, Boolean> populate = buildPopulationSet(fields);
JSONArray contacts = populateContactArray(1, populate, c);
if (contacts.length() == 1) {
return contacts.getJSONObject(0);
} else {
return null;
}
}
/**
* Creates an array of contacts from the cursor you pass in
*
* @param limit max number of contacts for the array
* @param populate whether or not you should populate a certain value
* @param c the cursor
* @return a JSONArray of contacts
*/
private JSONArray populateContactArray(int limit,
HashMap<String, Boolean> populate, Cursor c) {
String contactId = "";
String rawId = "";
String oldContactId = "";
boolean newContact = true;
String mimetype = "";
JSONArray contacts = new JSONArray();
JSONObject contact = new JSONObject();
JSONArray organizations = new JSONArray();
JSONArray addresses = new JSONArray();
JSONArray phones = new JSONArray();
JSONArray emails = new JSONArray();
JSONArray ims = new JSONArray();
JSONArray websites = new JSONArray();
JSONArray photos = new JSONArray();
ArrayList<String> names = new ArrayList<String>();
// Column indices
int colContactId = c.getColumnIndex(ContactsContract.Data.CONTACT_ID);
int colRawContactId = c.getColumnIndex(ContactsContract.Data.RAW_CONTACT_ID);
int colMimetype = c.getColumnIndex(ContactsContract.Data.MIMETYPE);
int colDisplayName = c.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME);
int colNote = c.getColumnIndex(ContactsContract.CommonDataKinds.Note.NOTE);
int colNickname = c.getColumnIndex(ContactsContract.CommonDataKinds.Nickname.NAME);
int colBirthday = c.getColumnIndex(ContactsContract.CommonDataKinds.Event.START_DATE);
int colEventType = c.getColumnIndex(ContactsContract.CommonDataKinds.Event.TYPE);
if (c.getCount() > 0) {
while (c.moveToNext() && (contacts.length() <= (limit - 1))) {
try {
contactId = c.getString(colContactId);
rawId = c.getString(colRawContactId);
// If we are in the first row set the oldContactId
if (c.getPosition() == 0) {
oldContactId = contactId;
}
// When the contact ID changes we need to push the Contact object
// to the array of contacts and create new objects.
if (!oldContactId.equals(contactId)) {
// Populate the Contact object with it's arrays
// and push the contact into the contacts array
contacts.put(populateContact(contact, organizations, addresses, phones,
emails, ims, websites, photos));
// Clean up the objects
contact = new JSONObject();
organizations = new JSONArray();
addresses = new JSONArray();
phones = new JSONArray();
emails = new JSONArray();
ims = new JSONArray();
websites = new JSONArray();
photos = new JSONArray();
// Set newContact to true as we are starting to populate a new contact
newContact = true;
}
// When we detect a new contact set the ID and display name.
// These fields are available in every row in the result set returned.
if (newContact) {
newContact = false;
contact.put("id", contactId);
contact.put("rawId", rawId);
}
// Grab the mimetype of the current row as it will be used in a lot of comparisons
mimetype = c.getString(colMimetype);
if (mimetype.equals(ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)) {
contact.put("displayName", c.getString(colDisplayName));
}
if (mimetype.equals(ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
&& isRequired("name", populate)) {
contact.put("name", nameQuery(c));
}
else if (mimetype.equals(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
&& isRequired("phoneNumbers", populate)) {
phones.put(phoneQuery(c));
}
else if (mimetype.equals(ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)
&& isRequired("emails", populate)) {
emails.put(emailQuery(c));
}
else if (mimetype.equals(ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE)
&& isRequired("addresses", populate)) {
addresses.put(addressQuery(c));
}
else if (mimetype.equals(ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE)
&& isRequired("organizations", populate)) {
organizations.put(organizationQuery(c));
}
else if (mimetype.equals(ContactsContract.CommonDataKinds.Im.CONTENT_ITEM_TYPE)
&& isRequired("ims", populate)) {
ims.put(imQuery(c));
}
else if (mimetype.equals(ContactsContract.CommonDataKinds.Note.CONTENT_ITEM_TYPE)
&& isRequired("note", populate)) {
contact.put("note", c.getString(colNote));
}
else if (mimetype.equals(ContactsContract.CommonDataKinds.Nickname.CONTENT_ITEM_TYPE)
&& isRequired("nickname", populate)) {
contact.put("nickname", c.getString(colNickname));
}
else if (mimetype.equals(ContactsContract.CommonDataKinds.Website.CONTENT_ITEM_TYPE)
&& isRequired("urls", populate)) {
websites.put(websiteQuery(c));
}
else if (mimetype.equals(ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE)) {
if (isRequired("birthday", populate) &&
ContactsContract.CommonDataKinds.Event.TYPE_BIRTHDAY == c.getInt(colEventType)) {
contact.put("birthday", c.getString(colBirthday));
}
}
else if (mimetype.equals(ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE)
&& isRequired("photos", populate)) {
photos.put(photoQuery(c, contactId));
}
} catch (JSONException e) {
Log.e(LOG_TAG, e.getMessage(), e);
}
// Set the old contact ID
oldContactId = contactId;
}
// Push the last contact into the contacts array
if (contacts.length() < limit) {
contacts.put(populateContact(contact, organizations, addresses, phones,
emails, ims, websites, photos));
}
}
c.close();
return contacts;
}
/**
* Builds a where clause all all the ids passed into the method
* @param contactIds a set of unique contact ids
* @param searchTerm what to search for
* @return an object containing the selection and selection args
*/
private WhereOptions buildIdClause(Set<String> contactIds, String searchTerm) {
WhereOptions options = new WhereOptions();
// If the user is searching for every contact then short circuit the method
// and return a shorter where clause to be searched.
if (searchTerm.equals("%")) {
options.setWhere("(" + ContactsContract.Data.CONTACT_ID + " LIKE ? )");
options.setWhereArgs(new String[] { searchTerm });
return options;
}
// This clause means that there are specific ID's to be populated
Iterator<String> it = contactIds.iterator();
StringBuffer buffer = new StringBuffer("(");
while (it.hasNext()) {
buffer.append("'" + it.next() + "'");
if (it.hasNext()) {
buffer.append(",");
}
}
buffer.append(")");
options.setWhere(ContactsContract.Data.CONTACT_ID + " IN " + buffer.toString());
options.setWhereArgs(null);
return options;
}
/**
* Create a new contact using a JSONObject to hold all the data.
* @param contact
* @param organizations array of organizations
* @param addresses array of addresses
* @param phones array of phones
* @param emails array of emails
* @param ims array of instant messenger addresses
* @param websites array of websites
* @param photos
* @return
*/
private JSONObject populateContact(JSONObject contact, JSONArray organizations,
JSONArray addresses, JSONArray phones, JSONArray emails,
JSONArray ims, JSONArray websites, JSONArray photos) {
try {
// Only return the array if it has at least one entry
if (organizations.length() > 0) {
contact.put("organizations", organizations);
}
if (addresses.length() > 0) {
contact.put("addresses", addresses);
}
if (phones.length() > 0) {
contact.put("phoneNumbers", phones);
}
if (emails.length() > 0) {
contact.put("emails", emails);
}
if (ims.length() > 0) {
contact.put("ims", ims);
}
if (websites.length() > 0) {
contact.put("urls", websites);
}
if (photos.length() > 0) {
contact.put("photos", photos);
}
} catch (JSONException e) {
Log.e(LOG_TAG, e.getMessage(), e);
}
return contact;
}
/**
* Take the search criteria passed into the method and create a SQL WHERE clause.
* @param fields the properties to search against
* @param searchTerm the string to search for
* @return an object containing the selection and selection args
*/
private WhereOptions buildWhereClause(JSONArray fields, String searchTerm) {
ArrayList<String> where = new ArrayList<String>();
ArrayList<String> whereArgs = new ArrayList<String>();
WhereOptions options = new WhereOptions();
/*
* Special case where the user wants all fields returned
*/
if (isWildCardSearch(fields)) {
// Get all contacts with all properties
if ("%".equals(searchTerm)) {
options.setWhere("(" + ContactsContract.Contacts.DISPLAY_NAME + " LIKE ? )");
options.setWhereArgs(new String[] { searchTerm });
return options;
} else {
// Get all contacts that match the filter but return all properties
where.add("(" + dbMap.get("displayName") + " LIKE ? )");
whereArgs.add(searchTerm);
where.add("(" + dbMap.get("name") + " LIKE ? AND "
+ ContactsContract.Data.MIMETYPE + " = ? )");
whereArgs.add(searchTerm);
whereArgs.add(ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE);
where.add("(" + dbMap.get("nickname") + " LIKE ? AND "
+ ContactsContract.Data.MIMETYPE + " = ? )");
whereArgs.add(searchTerm);
whereArgs.add(ContactsContract.CommonDataKinds.Nickname.CONTENT_ITEM_TYPE);
where.add("(" + dbMap.get("phoneNumbers") + " LIKE ? AND "
+ ContactsContract.Data.MIMETYPE + " = ? )");
whereArgs.add(searchTerm);
whereArgs.add(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
where.add("(" + dbMap.get("emails") + " LIKE ? AND "
+ ContactsContract.Data.MIMETYPE + " = ? )");
whereArgs.add(searchTerm);
whereArgs.add(ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE);
where.add("(" + dbMap.get("addresses") + " LIKE ? AND "
+ ContactsContract.Data.MIMETYPE + " = ? )");
whereArgs.add(searchTerm);
whereArgs.add(ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE);
where.add("(" + dbMap.get("ims") + " LIKE ? AND "
+ ContactsContract.Data.MIMETYPE + " = ? )");
whereArgs.add(searchTerm);
whereArgs.add(ContactsContract.CommonDataKinds.Im.CONTENT_ITEM_TYPE);
where.add("(" + dbMap.get("organizations") + " LIKE ? AND "
+ ContactsContract.Data.MIMETYPE + " = ? )");
whereArgs.add(searchTerm);
whereArgs.add(ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE);
where.add("(" + dbMap.get("note") + " LIKE ? AND "
+ ContactsContract.Data.MIMETYPE + " = ? )");
whereArgs.add(searchTerm);
whereArgs.add(ContactsContract.CommonDataKinds.Note.CONTENT_ITEM_TYPE);
where.add("(" + dbMap.get("urls") + " LIKE ? AND "
+ ContactsContract.Data.MIMETYPE + " = ? )");
whereArgs.add(searchTerm);
whereArgs.add(ContactsContract.CommonDataKinds.Website.CONTENT_ITEM_TYPE);
}
}
/*
* Special case for when the user wants all the contacts but
*/
if ("%".equals(searchTerm)) {
options.setWhere("(" + ContactsContract.Contacts.DISPLAY_NAME + " LIKE ? )");
options.setWhereArgs(new String[] { searchTerm });
return options;
}
String key;
try {
//Log.d(LOG_TAG, "How many fields do we have = " + fields.length());
for (int i = 0; i < fields.length(); i++) {
key = fields.getString(i);
if (key.equals("id")) {
where.add("(" + dbMap.get(key) + " = ? )");
whereArgs.add(searchTerm.substring(1, searchTerm.length() - 1));
}
else if (key.startsWith("displayName")) {
where.add("(" + dbMap.get(key) + " LIKE ? )");
whereArgs.add(searchTerm);
}
else if (key.startsWith("name")) {
where.add("(" + dbMap.get(key) + " LIKE ? AND "
+ ContactsContract.Data.MIMETYPE + " = ? )");
whereArgs.add(searchTerm);
whereArgs.add(ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE);
}
else if (key.startsWith("nickname")) {
where.add("(" + dbMap.get(key) + " LIKE ? AND "
+ ContactsContract.Data.MIMETYPE + " = ? )");
whereArgs.add(searchTerm);
whereArgs.add(ContactsContract.CommonDataKinds.Nickname.CONTENT_ITEM_TYPE);
}
else if (key.startsWith("phoneNumbers")) {
where.add("(" + dbMap.get(key) + " LIKE ? AND "
+ ContactsContract.Data.MIMETYPE + " = ? )");
whereArgs.add(searchTerm);
whereArgs.add(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
}
else if (key.startsWith("emails")) {
where.add("(" + dbMap.get(key) + " LIKE ? AND "
+ ContactsContract.Data.MIMETYPE + " = ? )");
whereArgs.add(searchTerm);
whereArgs.add(ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE);
}
else if (key.startsWith("addresses")) {
where.add("(" + dbMap.get(key) + " LIKE ? AND "
+ ContactsContract.Data.MIMETYPE + " = ? )");
whereArgs.add(searchTerm);
whereArgs.add(ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE);
}
else if (key.startsWith("ims")) {
where.add("(" + dbMap.get(key) + " LIKE ? AND "
+ ContactsContract.Data.MIMETYPE + " = ? )");
whereArgs.add(searchTerm);
whereArgs.add(ContactsContract.CommonDataKinds.Im.CONTENT_ITEM_TYPE);
}
else if (key.startsWith("organizations")) {
where.add("(" + dbMap.get(key) + " LIKE ? AND "
+ ContactsContract.Data.MIMETYPE + " = ? )");
whereArgs.add(searchTerm);
whereArgs.add(ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE);
}
// else if (key.startsWith("birthday")) {
// where.add("(" + dbMap.get(key) + " LIKE ? AND "
// + ContactsContract.Data.MIMETYPE + " = ? )");
// }
else if (key.startsWith("note")) {
where.add("(" + dbMap.get(key) + " LIKE ? AND "
+ ContactsContract.Data.MIMETYPE + " = ? )");
whereArgs.add(searchTerm);
whereArgs.add(ContactsContract.CommonDataKinds.Note.CONTENT_ITEM_TYPE);
}
else if (key.startsWith("urls")) {
where.add("(" + dbMap.get(key) + " LIKE ? AND "
+ ContactsContract.Data.MIMETYPE + " = ? )");
whereArgs.add(searchTerm);
whereArgs.add(ContactsContract.CommonDataKinds.Website.CONTENT_ITEM_TYPE);
}
}
} catch (JSONException e) {
Log.e(LOG_TAG, e.getMessage(), e);
}
// Creating the where string
StringBuffer selection = new StringBuffer();
for (int i = 0; i < where.size(); i++) {
selection.append(where.get(i));
if (i != (where.size() - 1)) {
selection.append(" OR ");
}
}
options.setWhere(selection.toString());
// Creating the where args array
String[] selectionArgs = new String[whereArgs.size()];
for (int i = 0; i < whereArgs.size(); i++) {
selectionArgs[i] = whereArgs.get(i);
}
options.setWhereArgs(selectionArgs);
return options;
}
/**
* If the user passes in the '*' wildcard character for search then they want all fields for each contact
*
* @param fields
* @return true if wildcard search requested, false otherwise
*/
private boolean isWildCardSearch(JSONArray fields) {
// Only do a wildcard search if we are passed ["*"]
if (fields.length() == 1) {
try {
if ("*".equals(fields.getString(0))) {
return true;
}
} catch (JSONException e) {
return false;
}
}
return false;
}
/**
* Create a ContactOrganization JSONObject
* @param cursor the current database row
* @return a JSONObject representing a ContactOrganization
*/
private JSONObject organizationQuery(Cursor cursor) {
JSONObject organization = new JSONObject();
try {
organization.put("id", cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Organization._ID)));
organization.put("pref", false); // Android does not store pref attribute
organization.put("type", getOrgType(cursor.getInt(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Organization.TYPE))));
organization.put("department", cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Organization.DEPARTMENT)));
organization.put("name", cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Organization.COMPANY)));
organization.put("title", cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Organization.TITLE)));
} catch (JSONException e) {
Log.e(LOG_TAG, e.getMessage(), e);
}
return organization;
}
/**
* Create a ContactAddress JSONObject
* @param cursor the current database row
* @return a JSONObject representing a ContactAddress
*/
private JSONObject addressQuery(Cursor cursor) {
JSONObject address = new JSONObject();
try {
address.put("id", cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal._ID)));
address.put("pref", false); // Android does not store pref attribute
address.put("type", getAddressType(cursor.getInt(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Organization.TYPE))));
address.put("formatted", cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.FORMATTED_ADDRESS)));
address.put("streetAddress", cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.STREET)));
address.put("locality", cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.CITY)));
address.put("region", cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.REGION)));
address.put("postalCode", cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE)));
address.put("country", cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY)));
} catch (JSONException e) {
Log.e(LOG_TAG, e.getMessage(), e);
}
return address;
}
/**
* Create a ContactName JSONObject
* @param cursor the current database row
* @return a JSONObject representing a ContactName
*/
private JSONObject nameQuery(Cursor cursor) {
JSONObject contactName = new JSONObject();
try {
String familyName = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME));
String givenName = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME));
String middleName = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.MIDDLE_NAME));
String honorificPrefix = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.PREFIX));
String honorificSuffix = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.SUFFIX));
// Create the formatted name
StringBuffer formatted = new StringBuffer("");
if (honorificPrefix != null) {
formatted.append(honorificPrefix + " ");
}
if (givenName != null) {
formatted.append(givenName + " ");
}
if (middleName != null) {
formatted.append(middleName + " ");
}
if (familyName != null) {
formatted.append(familyName + " ");
}
if (honorificSuffix != null) {
formatted.append(honorificSuffix + " ");
}
contactName.put("familyName", familyName);
contactName.put("givenName", givenName);
contactName.put("middleName", middleName);
contactName.put("honorificPrefix", honorificPrefix);
contactName.put("honorificSuffix", honorificSuffix);
contactName.put("formatted", formatted);
} catch (JSONException e) {
Log.e(LOG_TAG, e.getMessage(), e);
}
return contactName;
}
/**
* Create a ContactField JSONObject
* @param cursor the current database row
* @return a JSONObject representing a ContactField
*/
private JSONObject phoneQuery(Cursor cursor) {
JSONObject phoneNumber = new JSONObject();
try {
phoneNumber.put("id", cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone._ID)));
phoneNumber.put("pref", false); // Android does not store pref attribute
phoneNumber.put("value", cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)));
phoneNumber.put("type", getPhoneType(cursor.getInt(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE))));
} catch (JSONException e) {
Log.e(LOG_TAG, e.getMessage(), e);
} catch (Exception excp) {
Log.e(LOG_TAG, excp.getMessage(), excp);
}
return phoneNumber;
}
/**
* Create a ContactField JSONObject
* @param cursor the current database row
* @return a JSONObject representing a ContactField
*/
private JSONObject emailQuery(Cursor cursor) {
JSONObject email = new JSONObject();
try {
email.put("id", cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Email._ID)));
email.put("pref", false); // Android does not store pref attribute
email.put("value", cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA)));
email.put("type", getContactType(cursor.getInt(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE))));
} catch (JSONException e) {
Log.e(LOG_TAG, e.getMessage(), e);
}
return email;
}
/**
* Create a ContactField JSONObject
* @param cursor the current database row
* @return a JSONObject representing a ContactField
*/
private JSONObject imQuery(Cursor cursor) {
JSONObject im = new JSONObject();
try {
im.put("id", cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Im._ID)));
im.put("pref", false); // Android does not store pref attribute
im.put("value", cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Im.DATA)));
im.put("type", getContactType(cursor.getInt(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Im.TYPE))));
} catch (JSONException e) {
Log.e(LOG_TAG, e.getMessage(), e);
}
return im;
}
/**
* Create a ContactField JSONObject
* @param cursor the current database row
* @return a JSONObject representing a ContactField
*/
private JSONObject websiteQuery(Cursor cursor) {
JSONObject website = new JSONObject();
try {
website.put("id", cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Website._ID)));
website.put("pref", false); // Android does not store pref attribute
website.put("value", cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Website.URL)));
website.put("type", getContactType(cursor.getInt(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Website.TYPE))));
} catch (JSONException e) {
Log.e(LOG_TAG, e.getMessage(), e);
}
return website;
}
/**
* Create a ContactField JSONObject
* @param contactId
* @return a JSONObject representing a ContactField
*/
private JSONObject photoQuery(Cursor cursor, String contactId) {
JSONObject photo = new JSONObject();
try {
photo.put("id", cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Photo._ID)));
photo.put("pref", false);
photo.put("type", "url");
Uri person = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, (new Long(contactId)));
Uri photoUri = Uri.withAppendedPath(person, ContactsContract.Contacts.Photo.CONTENT_DIRECTORY);
photo.put("value", photoUri.toString());
} catch (JSONException e) {
Log.e(LOG_TAG, e.getMessage(), e);
}
return photo;
}
@Override
/**
* This method will save a contact object into the devices contacts database.
*
* @param contact the contact to be saved.
* @returns the id if the contact is successfully saved, null otherwise.
*/
public String save(JSONObject contact) {
AccountManager mgr = AccountManager.get(mApp.getActivity());
Account[] accounts = mgr.getAccounts();
String accountName = null;
String accountType = null;
if (accounts.length == 1) {
accountName = accounts[0].name;
accountType = accounts[0].type;
}
else if (accounts.length > 1) {
for (Account a : accounts) {
if (a.type.contains("eas") && a.name.matches(EMAIL_REGEXP)) /*Exchange ActiveSync*/{
accountName = a.name;
accountType = a.type;
break;
}
}
if (accountName == null) {
for (Account a : accounts) {
if (a.type.contains("com.google") && a.name.matches(EMAIL_REGEXP)) /*Google sync provider*/{
accountName = a.name;
accountType = a.type;
break;
}
}
}
if (accountName == null) {
for (Account a : accounts) {
if (a.name.matches(EMAIL_REGEXP)) /*Last resort, just look for an email address...*/{
accountName = a.name;
accountType = a.type;
break;
}
}
}
}
String id = getJsonString(contact, "id");
// Create new contact
if (id == null) {
return createNewContact(contact, accountType, accountName);
}
// Modify existing contact
else {
return modifyContact(id, contact, accountType, accountName);
}
}
/**
* Creates a new contact and stores it in the database
*
* @param id the raw contact id which is required for linking items to the contact
* @param contact the contact to be saved
* @param account the account to be saved under
*/
private String modifyContact(String id, JSONObject contact, String accountType, String accountName) {
// Get the RAW_CONTACT_ID which is needed to insert new values in an already existing contact.
// But not needed to update existing values.
int rawId = (new Integer(getJsonString(contact, "rawId"))).intValue();
// Create a list of attributes to add to the contact database
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
//Add contact type
ops.add(ContentProviderOperation.newUpdate(ContactsContract.RawContacts.CONTENT_URI)
.withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, accountType)
.withValue(ContactsContract.RawContacts.ACCOUNT_NAME, accountName)
.build());
// Modify name
JSONObject name;
try {
String displayName = getJsonString(contact, "displayName");
name = contact.getJSONObject("name");
if (displayName != null || name != null) {
ContentProviderOperation.Builder builder = ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
.withSelection(ContactsContract.Data.CONTACT_ID + "=? AND " +
ContactsContract.Data.MIMETYPE + "=?",
new String[] { id, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE });
if (displayName != null) {
builder.withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, displayName);
}
String familyName = getJsonString(name, "familyName");
if (familyName != null) {
builder.withValue(ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME, familyName);
}
String middleName = getJsonString(name, "middleName");
if (middleName != null) {
builder.withValue(ContactsContract.CommonDataKinds.StructuredName.MIDDLE_NAME, middleName);
}
String givenName = getJsonString(name, "givenName");
if (givenName != null) {
builder.withValue(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME, givenName);
}
String honorificPrefix = getJsonString(name, "honorificPrefix");
if (honorificPrefix != null) {
builder.withValue(ContactsContract.CommonDataKinds.StructuredName.PREFIX, honorificPrefix);
}
String honorificSuffix = getJsonString(name, "honorificSuffix");
if (honorificSuffix != null) {
builder.withValue(ContactsContract.CommonDataKinds.StructuredName.SUFFIX, honorificSuffix);
}
ops.add(builder.build());
}
} catch (JSONException e1) {
Log.d(LOG_TAG, "Could not get name");
}
// Modify phone numbers
JSONArray phones = null;
try {
phones = contact.getJSONArray("phoneNumbers");
if (phones != null) {
// Delete all the phones
if (phones.length() == 0) {
ops.add(ContentProviderOperation.newDelete(ContactsContract.Data.CONTENT_URI)
.withSelection(ContactsContract.Data.RAW_CONTACT_ID + "=? AND " +
ContactsContract.Data.MIMETYPE + "=?",
new String[] { "" + rawId, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE })
.build());
}
// Modify or add a phone
else {
for (int i = 0; i < phones.length(); i++) {
JSONObject phone = (JSONObject) phones.get(i);
String phoneId = getJsonString(phone, "id");
// This is a new phone so do a DB insert
if (phoneId == null) {
ContentValues contentValues = new ContentValues();
contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, rawId);
contentValues.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
contentValues.put(ContactsContract.CommonDataKinds.Phone.NUMBER, getJsonString(phone, "value"));
contentValues.put(ContactsContract.CommonDataKinds.Phone.TYPE, getPhoneType(getJsonString(phone, "type")));
ops.add(ContentProviderOperation.newInsert(
ContactsContract.Data.CONTENT_URI).withValues(contentValues).build());
}
// This is an existing phone so do a DB update
else {
ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
.withSelection(ContactsContract.CommonDataKinds.Phone._ID + "=? AND " +
ContactsContract.Data.MIMETYPE + "=?",
new String[] { phoneId, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE })
.withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, getJsonString(phone, "value"))
.withValue(ContactsContract.CommonDataKinds.Phone.TYPE, getPhoneType(getJsonString(phone, "type")))
.build());
}
}
}
}
} catch (JSONException e) {
Log.d(LOG_TAG, "Could not get phone numbers");
}
// Modify emails
JSONArray emails = null;
try {
emails = contact.getJSONArray("emails");
if (emails != null) {
// Delete all the emails
if (emails.length() == 0) {
ops.add(ContentProviderOperation.newDelete(ContactsContract.Data.CONTENT_URI)
.withSelection(ContactsContract.Data.RAW_CONTACT_ID + "=? AND " +
ContactsContract.Data.MIMETYPE + "=?",
new String[] { "" + rawId, ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE })
.build());
}
// Modify or add a email
else {
for (int i = 0; i < emails.length(); i++) {
JSONObject email = (JSONObject) emails.get(i);
String emailId = getJsonString(email, "id");
// This is a new email so do a DB insert
if (emailId == null) {
ContentValues contentValues = new ContentValues();
contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, rawId);
contentValues.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE);
contentValues.put(ContactsContract.CommonDataKinds.Email.DATA, getJsonString(email, "value"));
contentValues.put(ContactsContract.CommonDataKinds.Email.TYPE, getContactType(getJsonString(email, "type")));
ops.add(ContentProviderOperation.newInsert(
ContactsContract.Data.CONTENT_URI).withValues(contentValues).build());
}
// This is an existing email so do a DB update
else {
ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
.withSelection(ContactsContract.CommonDataKinds.Email._ID + "=? AND " +
ContactsContract.Data.MIMETYPE + "=?",
new String[] { emailId, ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE })
.withValue(ContactsContract.CommonDataKinds.Email.DATA, getJsonString(email, "value"))
.withValue(ContactsContract.CommonDataKinds.Email.TYPE, getContactType(getJsonString(email, "type")))
.build());
}
}
}
}
} catch (JSONException e) {
Log.d(LOG_TAG, "Could not get emails");
}
// Modify addresses
JSONArray addresses = null;
try {
addresses = contact.getJSONArray("addresses");
if (addresses != null) {
// Delete all the addresses
if (addresses.length() == 0) {
ops.add(ContentProviderOperation.newDelete(ContactsContract.Data.CONTENT_URI)
.withSelection(ContactsContract.Data.RAW_CONTACT_ID + "=? AND " +
ContactsContract.Data.MIMETYPE + "=?",
new String[] { "" + rawId, ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE })
.build());
}
// Modify or add a address
else {
for (int i = 0; i < addresses.length(); i++) {
JSONObject address = (JSONObject) addresses.get(i);
String addressId = getJsonString(address, "id");
// This is a new address so do a DB insert
if (addressId == null) {
ContentValues contentValues = new ContentValues();
contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, rawId);
contentValues.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE);
contentValues.put(ContactsContract.CommonDataKinds.StructuredPostal.TYPE, getAddressType(getJsonString(address, "type")));
contentValues.put(ContactsContract.CommonDataKinds.StructuredPostal.FORMATTED_ADDRESS, getJsonString(address, "formatted"));
contentValues.put(ContactsContract.CommonDataKinds.StructuredPostal.STREET, getJsonString(address, "streetAddress"));
contentValues.put(ContactsContract.CommonDataKinds.StructuredPostal.CITY, getJsonString(address, "locality"));
contentValues.put(ContactsContract.CommonDataKinds.StructuredPostal.REGION, getJsonString(address, "region"));
contentValues.put(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE, getJsonString(address, "postalCode"));
contentValues.put(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY, getJsonString(address, "country"));
ops.add(ContentProviderOperation.newInsert(
ContactsContract.Data.CONTENT_URI).withValues(contentValues).build());
}
// This is an existing address so do a DB update
else {
ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
.withSelection(ContactsContract.CommonDataKinds.StructuredPostal._ID + "=? AND " +
ContactsContract.Data.MIMETYPE + "=?",
new String[] { addressId, ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE })
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.TYPE, getAddressType(getJsonString(address, "type")))
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.FORMATTED_ADDRESS, getJsonString(address, "formatted"))
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.STREET, getJsonString(address, "streetAddress"))
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.CITY, getJsonString(address, "locality"))
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.REGION, getJsonString(address, "region"))
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE, getJsonString(address, "postalCode"))
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY, getJsonString(address, "country"))
.build());
}
}
}
}
} catch (JSONException e) {
Log.d(LOG_TAG, "Could not get addresses");
}
// Modify organizations
JSONArray organizations = null;
try {
organizations = contact.getJSONArray("organizations");
if (organizations != null) {
// Delete all the organizations
if (organizations.length() == 0) {
ops.add(ContentProviderOperation.newDelete(ContactsContract.Data.CONTENT_URI)
.withSelection(ContactsContract.Data.RAW_CONTACT_ID + "=? AND " +
ContactsContract.Data.MIMETYPE + "=?",
new String[] { "" + rawId, ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE })
.build());
}
// Modify or add a organization
else {
for (int i = 0; i < organizations.length(); i++) {
JSONObject org = (JSONObject) organizations.get(i);
String orgId = getJsonString(org, "id");
// This is a new organization so do a DB insert
if (orgId == null) {
ContentValues contentValues = new ContentValues();
contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, rawId);
contentValues.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE);
contentValues.put(ContactsContract.CommonDataKinds.Organization.TYPE, getOrgType(getJsonString(org, "type")));
contentValues.put(ContactsContract.CommonDataKinds.Organization.DEPARTMENT, getJsonString(org, "department"));
contentValues.put(ContactsContract.CommonDataKinds.Organization.COMPANY, getJsonString(org, "name"));
contentValues.put(ContactsContract.CommonDataKinds.Organization.TITLE, getJsonString(org, "title"));
ops.add(ContentProviderOperation.newInsert(
ContactsContract.Data.CONTENT_URI).withValues(contentValues).build());
}
// This is an existing organization so do a DB update
else {
ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
.withSelection(ContactsContract.CommonDataKinds.Organization._ID + "=? AND " +
ContactsContract.Data.MIMETYPE + "=?",
new String[] { orgId, ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE })
.withValue(ContactsContract.CommonDataKinds.Organization.TYPE, getOrgType(getJsonString(org, "type")))
.withValue(ContactsContract.CommonDataKinds.Organization.DEPARTMENT, getJsonString(org, "department"))
.withValue(ContactsContract.CommonDataKinds.Organization.COMPANY, getJsonString(org, "name"))
.withValue(ContactsContract.CommonDataKinds.Organization.TITLE, getJsonString(org, "title"))
.build());
}
}
}
}
} catch (JSONException e) {
Log.d(LOG_TAG, "Could not get organizations");
}
// Modify IMs
JSONArray ims = null;
try {
ims = contact.getJSONArray("ims");
if (ims != null) {
// Delete all the ims
if (ims.length() == 0) {
ops.add(ContentProviderOperation.newDelete(ContactsContract.Data.CONTENT_URI)
.withSelection(ContactsContract.Data.RAW_CONTACT_ID + "=? AND " +
ContactsContract.Data.MIMETYPE + "=?",
new String[] { "" + rawId, ContactsContract.CommonDataKinds.Im.CONTENT_ITEM_TYPE })
.build());
}
// Modify or add a im
else {
for (int i = 0; i < ims.length(); i++) {
JSONObject im = (JSONObject) ims.get(i);
String imId = getJsonString(im, "id");
// This is a new IM so do a DB insert
if (imId == null) {
ContentValues contentValues = new ContentValues();
contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, rawId);
contentValues.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Im.CONTENT_ITEM_TYPE);
contentValues.put(ContactsContract.CommonDataKinds.Im.DATA, getJsonString(im, "value"));
contentValues.put(ContactsContract.CommonDataKinds.Im.TYPE, getContactType(getJsonString(im, "type")));
ops.add(ContentProviderOperation.newInsert(
ContactsContract.Data.CONTENT_URI).withValues(contentValues).build());
}
// This is an existing IM so do a DB update
else {
ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
.withSelection(ContactsContract.CommonDataKinds.Im._ID + "=? AND " +
ContactsContract.Data.MIMETYPE + "=?",
new String[] { imId, ContactsContract.CommonDataKinds.Im.CONTENT_ITEM_TYPE })
.withValue(ContactsContract.CommonDataKinds.Im.DATA, getJsonString(im, "value"))
.withValue(ContactsContract.CommonDataKinds.Im.TYPE, getContactType(getJsonString(im, "type")))
.build());
}
}
}
}
} catch (JSONException e) {
Log.d(LOG_TAG, "Could not get emails");
}
// Modify note
String note = getJsonString(contact, "note");
ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
.withSelection(ContactsContract.Data.CONTACT_ID + "=? AND " +
ContactsContract.Data.MIMETYPE + "=?",
new String[] { id, ContactsContract.CommonDataKinds.Note.CONTENT_ITEM_TYPE })
.withValue(ContactsContract.CommonDataKinds.Note.NOTE, note)
.build());
// Modify nickname
String nickname = getJsonString(contact, "nickname");
if (nickname != null) {
ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
.withSelection(ContactsContract.Data.CONTACT_ID + "=? AND " +
ContactsContract.Data.MIMETYPE + "=?",
new String[] { id, ContactsContract.CommonDataKinds.Nickname.CONTENT_ITEM_TYPE })
.withValue(ContactsContract.CommonDataKinds.Nickname.NAME, nickname)
.build());
}
// Modify urls
JSONArray websites = null;
try {
websites = contact.getJSONArray("urls");
if (websites != null) {
// Delete all the websites
if (websites.length() == 0) {
Log.d(LOG_TAG, "This means we should be deleting all the phone numbers.");
ops.add(ContentProviderOperation.newDelete(ContactsContract.Data.CONTENT_URI)
.withSelection(ContactsContract.Data.RAW_CONTACT_ID + "=? AND " +
ContactsContract.Data.MIMETYPE + "=?",
new String[] { "" + rawId, ContactsContract.CommonDataKinds.Website.CONTENT_ITEM_TYPE })
.build());
}
// Modify or add a website
else {
for (int i = 0; i < websites.length(); i++) {
JSONObject website = (JSONObject) websites.get(i);
String websiteId = getJsonString(website, "id");
// This is a new website so do a DB insert
if (websiteId == null) {
ContentValues contentValues = new ContentValues();
contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, rawId);
contentValues.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Website.CONTENT_ITEM_TYPE);
contentValues.put(ContactsContract.CommonDataKinds.Website.DATA, getJsonString(website, "value"));
contentValues.put(ContactsContract.CommonDataKinds.Website.TYPE, getContactType(getJsonString(website, "type")));
ops.add(ContentProviderOperation.newInsert(
ContactsContract.Data.CONTENT_URI).withValues(contentValues).build());
}
// This is an existing website so do a DB update
else {
ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
.withSelection(ContactsContract.CommonDataKinds.Website._ID + "=? AND " +
ContactsContract.Data.MIMETYPE + "=?",
new String[] { websiteId, ContactsContract.CommonDataKinds.Website.CONTENT_ITEM_TYPE })
.withValue(ContactsContract.CommonDataKinds.Website.DATA, getJsonString(website, "value"))
.withValue(ContactsContract.CommonDataKinds.Website.TYPE, getContactType(getJsonString(website, "type")))
.build());
}
}
}
}
} catch (JSONException e) {
Log.d(LOG_TAG, "Could not get websites");
}
// Modify birthday
String birthday = getJsonString(contact, "birthday");
if (birthday != null) {
ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
.withSelection(ContactsContract.Data.CONTACT_ID + "=? AND " +
ContactsContract.Data.MIMETYPE + "=? AND " +
ContactsContract.CommonDataKinds.Event.TYPE + "=?",
new String[] { id, ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE, new String("" + ContactsContract.CommonDataKinds.Event.TYPE_BIRTHDAY) })
.withValue(ContactsContract.CommonDataKinds.Event.TYPE, ContactsContract.CommonDataKinds.Event.TYPE_BIRTHDAY)
.withValue(ContactsContract.CommonDataKinds.Event.START_DATE, birthday)
.build());
}
// Modify photos
JSONArray photos = null;
try {
photos = contact.getJSONArray("photos");
if (photos != null) {
// Delete all the photos
if (photos.length() == 0) {
ops.add(ContentProviderOperation.newDelete(ContactsContract.Data.CONTENT_URI)
.withSelection(ContactsContract.Data.RAW_CONTACT_ID + "=? AND " +
ContactsContract.Data.MIMETYPE + "=?",
new String[] { "" + rawId, ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE })
.build());
}
// Modify or add a photo
else {
for (int i = 0; i < photos.length(); i++) {
JSONObject photo = (JSONObject) photos.get(i);
String photoId = getJsonString(photo, "id");
byte[] bytes = getPhotoBytes(getJsonString(photo, "value"));
// This is a new photo so do a DB insert
if (photoId == null) {
ContentValues contentValues = new ContentValues();
contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, rawId);
contentValues.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE);
contentValues.put(ContactsContract.Data.IS_SUPER_PRIMARY, 1);
contentValues.put(ContactsContract.CommonDataKinds.Photo.PHOTO, bytes);
ops.add(ContentProviderOperation.newInsert(
ContactsContract.Data.CONTENT_URI).withValues(contentValues).build());
}
// This is an existing photo so do a DB update
else {
ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
.withSelection(ContactsContract.CommonDataKinds.Photo._ID + "=? AND " +
ContactsContract.Data.MIMETYPE + "=?",
new String[] { photoId, ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE })
.withValue(ContactsContract.Data.IS_SUPER_PRIMARY, 1)
.withValue(ContactsContract.CommonDataKinds.Photo.PHOTO, bytes)
.build());
}
}
}
}
} catch (JSONException e) {
Log.d(LOG_TAG, "Could not get photos");
}
boolean retVal = true;
//Modify contact
try {
mApp.getActivity().getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
} catch (RemoteException e) {
Log.e(LOG_TAG, e.getMessage(), e);
Log.e(LOG_TAG, Log.getStackTraceString(e), e);
retVal = false;
} catch (OperationApplicationException e) {
Log.e(LOG_TAG, e.getMessage(), e);
Log.e(LOG_TAG, Log.getStackTraceString(e), e);
retVal = false;
}
// if the save was a succes return the contact ID
if (retVal) {
return id;
} else {
return null;
}
}
/**
* Add a website to a list of database actions to be performed
*
* @param ops the list of database actions
* @param website the item to be inserted
*/
private void insertWebsite(ArrayList<ContentProviderOperation> ops,
JSONObject website) {
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Website.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.Website.DATA, getJsonString(website, "value"))
.withValue(ContactsContract.CommonDataKinds.Website.TYPE, getContactType(getJsonString(website, "type")))
.build());
}
/**
* Add an im to a list of database actions to be performed
*
* @param ops the list of database actions
* @param im the item to be inserted
*/
private void insertIm(ArrayList<ContentProviderOperation> ops, JSONObject im) {
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Im.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.Im.DATA, getJsonString(im, "value"))
.withValue(ContactsContract.CommonDataKinds.Im.TYPE, getContactType(getJsonString(im, "type")))
.build());
}
/**
* Add an organization to a list of database actions to be performed
*
* @param ops the list of database actions
* @param org the item to be inserted
*/
private void insertOrganization(ArrayList<ContentProviderOperation> ops,
JSONObject org) {
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.Organization.TYPE, getOrgType(getJsonString(org, "type")))
.withValue(ContactsContract.CommonDataKinds.Organization.DEPARTMENT, getJsonString(org, "department"))
.withValue(ContactsContract.CommonDataKinds.Organization.COMPANY, getJsonString(org, "name"))
.withValue(ContactsContract.CommonDataKinds.Organization.TITLE, getJsonString(org, "title"))
.build());
}
/**
* Add an address to a list of database actions to be performed
*
* @param ops the list of database actions
* @param address the item to be inserted
*/
private void insertAddress(ArrayList<ContentProviderOperation> ops,
JSONObject address) {
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.TYPE, getAddressType(getJsonString(address, "type")))
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.FORMATTED_ADDRESS, getJsonString(address, "formatted"))
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.STREET, getJsonString(address, "streetAddress"))
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.CITY, getJsonString(address, "locality"))
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.REGION, getJsonString(address, "region"))
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE, getJsonString(address, "postalCode"))
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY, getJsonString(address, "country"))
.build());
}
/**
* Add an email to a list of database actions to be performed
*
* @param ops the list of database actions
* @param email the item to be inserted
*/
private void insertEmail(ArrayList<ContentProviderOperation> ops,
JSONObject email) {
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.Email.DATA, getJsonString(email, "value"))
.withValue(ContactsContract.CommonDataKinds.Email.TYPE, getPhoneType(getJsonString(email, "type")))
.build());
}
/**
* Add a phone to a list of database actions to be performed
*
* @param ops the list of database actions
* @param phone the item to be inserted
*/
private void insertPhone(ArrayList<ContentProviderOperation> ops,
JSONObject phone) {
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, getJsonString(phone, "value"))
.withValue(ContactsContract.CommonDataKinds.Phone.TYPE, getPhoneType(getJsonString(phone, "type")))
.build());
}
/**
* Add a phone to a list of database actions to be performed
*
* @param ops the list of database actions
* @param phone the item to be inserted
*/
private void insertPhoto(ArrayList<ContentProviderOperation> ops,
JSONObject photo) {
byte[] bytes = getPhotoBytes(getJsonString(photo, "value"));
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
.withValue(ContactsContract.Data.IS_SUPER_PRIMARY, 1)
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.Photo.PHOTO, bytes)
.build());
}
/**
* Gets the raw bytes from the supplied filename
*
* @param filename the file to read the bytes from
* @return a byte array
* @throws IOException
*/
private byte[] getPhotoBytes(String filename) {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
try {
int bytesRead = 0;
long totalBytesRead = 0;
byte[] data = new byte[8192];
InputStream in = getPathFromUri(filename);
while ((bytesRead = in.read(data, 0, data.length)) != -1 && totalBytesRead <= MAX_PHOTO_SIZE) {
buffer.write(data, 0, bytesRead);
totalBytesRead += bytesRead;
}
in.close();
buffer.flush();
} catch (FileNotFoundException e) {
Log.e(LOG_TAG, e.getMessage(), e);
} catch (IOException e) {
Log.e(LOG_TAG, e.getMessage(), e);
}
return buffer.toByteArray();
}
/**
* Get an input stream based on file path or uri content://, http://, file://
*
* @param path
* @return an input stream
* @throws IOException
*/
private InputStream getPathFromUri(String path) throws IOException {
if (path.startsWith("content:")) {
Uri uri = Uri.parse(path);
return mApp.getActivity().getContentResolver().openInputStream(uri);
}
if (path.startsWith("http:") || path.startsWith("file:")) {
URL url = new URL(path);
return url.openStream();
}
else {
return new FileInputStream(path);
}
}
/**
* Creates a new contact and stores it in the database
*
* @param contact the contact to be saved
* @param account the account to be saved under
*/
private String createNewContact(JSONObject contact, String accountType, String accountName) {
// Create a list of attributes to add to the contact database
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
//Add contact type
ops.add(ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI)
.withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, accountType)
.withValue(ContactsContract.RawContacts.ACCOUNT_NAME, accountName)
.build());
// Add name
try {
JSONObject name = contact.optJSONObject("name");
String displayName = contact.getString("displayName");
if (displayName != null || name != null) {
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, displayName)
.withValue(ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME, getJsonString(name, "familyName"))
.withValue(ContactsContract.CommonDataKinds.StructuredName.MIDDLE_NAME, getJsonString(name, "middleName"))
.withValue(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME, getJsonString(name, "givenName"))
.withValue(ContactsContract.CommonDataKinds.StructuredName.PREFIX, getJsonString(name, "honorificPrefix"))
.withValue(ContactsContract.CommonDataKinds.StructuredName.SUFFIX, getJsonString(name, "honorificSuffix"))
.build());
}
} catch (JSONException e) {
Log.d(LOG_TAG, "Could not get name object");
}
//Add phone numbers
JSONArray phones = null;
try {
phones = contact.getJSONArray("phoneNumbers");
if (phones != null) {
for (int i = 0; i < phones.length(); i++) {
JSONObject phone = (JSONObject) phones.get(i);
insertPhone(ops, phone);
}
}
} catch (JSONException e) {
Log.d(LOG_TAG, "Could not get phone numbers");
}
// Add emails
JSONArray emails = null;
try {
emails = contact.getJSONArray("emails");
if (emails != null) {
for (int i = 0; i < emails.length(); i++) {
JSONObject email = (JSONObject) emails.get(i);
insertEmail(ops, email);
}
}
} catch (JSONException e) {
Log.d(LOG_TAG, "Could not get emails");
}
// Add addresses
JSONArray addresses = null;
try {
addresses = contact.getJSONArray("addresses");
if (addresses != null) {
for (int i = 0; i < addresses.length(); i++) {
JSONObject address = (JSONObject) addresses.get(i);
insertAddress(ops, address);
}
}
} catch (JSONException e) {
Log.d(LOG_TAG, "Could not get addresses");
}
// Add organizations
JSONArray organizations = null;
try {
organizations = contact.getJSONArray("organizations");
if (organizations != null) {
for (int i = 0; i < organizations.length(); i++) {
JSONObject org = (JSONObject) organizations.get(i);
insertOrganization(ops, org);
}
}
} catch (JSONException e) {
Log.d(LOG_TAG, "Could not get organizations");
}
// Add IMs
JSONArray ims = null;
try {
ims = contact.getJSONArray("ims");
if (ims != null) {
for (int i = 0; i < ims.length(); i++) {
JSONObject im = (JSONObject) ims.get(i);
insertIm(ops, im);
}
}
} catch (JSONException e) {
Log.d(LOG_TAG, "Could not get emails");
}
// Add note
String note = getJsonString(contact, "note");
if (note != null) {
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Note.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.Note.NOTE, note)
.build());
}
// Add nickname
String nickname = getJsonString(contact, "nickname");
if (nickname != null) {
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Nickname.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.Nickname.NAME, nickname)
.build());
}
// Add urls
JSONArray websites = null;
try {
websites = contact.getJSONArray("urls");
if (websites != null) {
for (int i = 0; i < websites.length(); i++) {
JSONObject website = (JSONObject) websites.get(i);
insertWebsite(ops, website);
}
}
} catch (JSONException e) {
Log.d(LOG_TAG, "Could not get websites");
}
// Add birthday
String birthday = getJsonString(contact, "birthday");
if (birthday != null) {
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.Event.TYPE, ContactsContract.CommonDataKinds.Event.TYPE_BIRTHDAY)
.withValue(ContactsContract.CommonDataKinds.Event.START_DATE, birthday)
.build());
}
// Add photos
JSONArray photos = null;
try {
photos = contact.getJSONArray("photos");
if (photos != null) {
for (int i = 0; i < photos.length(); i++) {
JSONObject photo = (JSONObject) photos.get(i);
insertPhoto(ops, photo);
}
}
} catch (JSONException e) {
Log.d(LOG_TAG, "Could not get photos");
}
String newId = null;
//Add contact
try {
ContentProviderResult[] cpResults = mApp.getActivity().getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
if (cpResults.length >= 0) {
newId = cpResults[0].uri.getLastPathSegment();
}
} catch (RemoteException e) {
Log.e(LOG_TAG, e.getMessage(), e);
} catch (OperationApplicationException e) {
Log.e(LOG_TAG, e.getMessage(), e);
}
return newId;
}
@Override
/**
* This method will remove a Contact from the database based on ID.
* @param id the unique ID of the contact to remove
*/
public boolean remove(String id) {
int result = 0;
Cursor cursor = mApp.getActivity().getContentResolver().query(ContactsContract.Contacts.CONTENT_URI,
null,
ContactsContract.Contacts._ID + " = ?",
new String[] { id }, null);
if (cursor.getCount() == 1) {
cursor.moveToFirst();
String lookupKey = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_LOOKUP_URI, lookupKey);
result = mApp.getActivity().getContentResolver().delete(uri, null, null);
} else {
Log.d(LOG_TAG, "Could not find contact with ID");
}
return (result > 0) ? true : false;
}
/**************************************************************************
*
* All methods below this comment are used to convert from JavaScript
* text types to Android integer types and vice versa.
*
*************************************************************************/
/**
* Converts a string from the W3C Contact API to it's Android int value.
* @param string
* @return Android int value
*/
private int getPhoneType(String string) {
int type = ContactsContract.CommonDataKinds.Phone.TYPE_OTHER;
if (string != null) {
if ("home".equals(string.toLowerCase())) {
return ContactsContract.CommonDataKinds.Phone.TYPE_HOME;
}
else if ("mobile".equals(string.toLowerCase())) {
return ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE;
}
else if ("work".equals(string.toLowerCase())) {
return ContactsContract.CommonDataKinds.Phone.TYPE_WORK;
}
else if ("work fax".equals(string.toLowerCase())) {
return ContactsContract.CommonDataKinds.Phone.TYPE_FAX_WORK;
}
else if ("home fax".equals(string.toLowerCase())) {
return ContactsContract.CommonDataKinds.Phone.TYPE_FAX_HOME;
}
else if ("fax".equals(string.toLowerCase())) {
return ContactsContract.CommonDataKinds.Phone.TYPE_FAX_WORK;
}
else if ("pager".equals(string.toLowerCase())) {
return ContactsContract.CommonDataKinds.Phone.TYPE_PAGER;
}
else if ("other".equals(string.toLowerCase())) {
return ContactsContract.CommonDataKinds.Phone.TYPE_OTHER;
}
else if ("car".equals(string.toLowerCase())) {
return ContactsContract.CommonDataKinds.Phone.TYPE_CAR;
}
else if ("company main".equals(string.toLowerCase())) {
return ContactsContract.CommonDataKinds.Phone.TYPE_COMPANY_MAIN;
}
else if ("isdn".equals(string.toLowerCase())) {
return ContactsContract.CommonDataKinds.Phone.TYPE_ISDN;
}
else if ("main".equals(string.toLowerCase())) {
return ContactsContract.CommonDataKinds.Phone.TYPE_MAIN;
}
else if ("other fax".equals(string.toLowerCase())) {
return ContactsContract.CommonDataKinds.Phone.TYPE_OTHER_FAX;
}
else if ("radio".equals(string.toLowerCase())) {
return ContactsContract.CommonDataKinds.Phone.TYPE_RADIO;
}
else if ("telex".equals(string.toLowerCase())) {
return ContactsContract.CommonDataKinds.Phone.TYPE_TELEX;
}
else if ("work mobile".equals(string.toLowerCase())) {
return ContactsContract.CommonDataKinds.Phone.TYPE_WORK_MOBILE;
}
else if ("work pager".equals(string.toLowerCase())) {
return ContactsContract.CommonDataKinds.Phone.TYPE_WORK_PAGER;
}
else if ("assistant".equals(string.toLowerCase())) {
return ContactsContract.CommonDataKinds.Phone.TYPE_ASSISTANT;
}
else if ("mms".equals(string.toLowerCase())) {
return ContactsContract.CommonDataKinds.Phone.TYPE_MMS;
}
else if ("callback".equals(string.toLowerCase())) {
return ContactsContract.CommonDataKinds.Phone.TYPE_CALLBACK;
}
else if ("tty ttd".equals(string.toLowerCase())) {
return ContactsContract.CommonDataKinds.Phone.TYPE_TTY_TDD;
}
else if ("custom".equals(string.toLowerCase())) {
return ContactsContract.CommonDataKinds.Phone.TYPE_CUSTOM;
}
}
return type;
}
/**
* getPhoneType converts an Android phone type into a string
* @param type
* @return phone type as string.
*/
private String getPhoneType(int type) {
String stringType;
switch (type) {
case ContactsContract.CommonDataKinds.Phone.TYPE_CUSTOM:
stringType = "custom";
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_FAX_HOME:
stringType = "home fax";
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_FAX_WORK:
stringType = "work fax";
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_HOME:
stringType = "home";
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE:
stringType = "mobile";
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_PAGER:
stringType = "pager";
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_WORK:
stringType = "work";
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_CALLBACK:
stringType = "callback";
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_CAR:
stringType = "car";
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_COMPANY_MAIN:
stringType = "company main";
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_OTHER_FAX:
stringType = "other fax";
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_RADIO:
stringType = "radio";
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_TELEX:
stringType = "telex";
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_TTY_TDD:
stringType = "tty tdd";
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_WORK_MOBILE:
stringType = "work mobile";
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_WORK_PAGER:
stringType = "work pager";
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_ASSISTANT:
stringType = "assistant";
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_MMS:
stringType = "mms";
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_ISDN:
stringType = "isdn";
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_OTHER:
default:
stringType = "other";
break;
}
return stringType;
}
/**
* Converts a string from the W3C Contact API to it's Android int value.
* @param string
* @return Android int value
*/
private int getContactType(String string) {
int type = ContactsContract.CommonDataKinds.Email.TYPE_OTHER;
if (string != null) {
if ("home".equals(string.toLowerCase())) {
return ContactsContract.CommonDataKinds.Email.TYPE_HOME;
}
else if ("work".equals(string.toLowerCase())) {
return ContactsContract.CommonDataKinds.Email.TYPE_WORK;
}
else if ("other".equals(string.toLowerCase())) {
return ContactsContract.CommonDataKinds.Email.TYPE_OTHER;
}
else if ("mobile".equals(string.toLowerCase())) {
return ContactsContract.CommonDataKinds.Email.TYPE_MOBILE;
}
else if ("custom".equals(string.toLowerCase())) {
return ContactsContract.CommonDataKinds.Email.TYPE_CUSTOM;
}
}
return type;
}
/**
* getPhoneType converts an Android phone type into a string
* @param type
* @return phone type as string.
*/
private String getContactType(int type) {
String stringType;
switch (type) {
case ContactsContract.CommonDataKinds.Email.TYPE_CUSTOM:
stringType = "custom";
break;
case ContactsContract.CommonDataKinds.Email.TYPE_HOME:
stringType = "home";
break;
case ContactsContract.CommonDataKinds.Email.TYPE_WORK:
stringType = "work";
break;
case ContactsContract.CommonDataKinds.Email.TYPE_MOBILE:
stringType = "mobile";
break;
case ContactsContract.CommonDataKinds.Email.TYPE_OTHER:
default:
stringType = "other";
break;
}
return stringType;
}
/**
* Converts a string from the W3C Contact API to it's Android int value.
* @param string
* @return Android int value
*/
private int getOrgType(String string) {
int type = ContactsContract.CommonDataKinds.Organization.TYPE_OTHER;
if (string != null) {
if ("work".equals(string.toLowerCase())) {
return ContactsContract.CommonDataKinds.Organization.TYPE_WORK;
}
else if ("other".equals(string.toLowerCase())) {
return ContactsContract.CommonDataKinds.Organization.TYPE_OTHER;
}
else if ("custom".equals(string.toLowerCase())) {
return ContactsContract.CommonDataKinds.Organization.TYPE_CUSTOM;
}
}
return type;
}
/**
* getPhoneType converts an Android phone type into a string
* @param type
* @return phone type as string.
*/
private String getOrgType(int type) {
String stringType;
switch (type) {
case ContactsContract.CommonDataKinds.Organization.TYPE_CUSTOM:
stringType = "custom";
break;
case ContactsContract.CommonDataKinds.Organization.TYPE_WORK:
stringType = "work";
break;
case ContactsContract.CommonDataKinds.Organization.TYPE_OTHER:
default:
stringType = "other";
break;
}
return stringType;
}
/**
* Converts a string from the W3C Contact API to it's Android int value.
* @param string
* @return Android int value
*/
private int getAddressType(String string) {
int type = ContactsContract.CommonDataKinds.StructuredPostal.TYPE_OTHER;
if (string != null) {
if ("work".equals(string.toLowerCase())) {
return ContactsContract.CommonDataKinds.StructuredPostal.TYPE_WORK;
}
else if ("other".equals(string.toLowerCase())) {
return ContactsContract.CommonDataKinds.StructuredPostal.TYPE_OTHER;
}
else if ("home".equals(string.toLowerCase())) {
return ContactsContract.CommonDataKinds.StructuredPostal.TYPE_HOME;
}
}
return type;
}
/**
* getPhoneType converts an Android phone type into a string
* @param type
* @return phone type as string.
*/
private String getAddressType(int type) {
String stringType;
switch (type) {
case ContactsContract.CommonDataKinds.StructuredPostal.TYPE_HOME:
stringType = "home";
break;
case ContactsContract.CommonDataKinds.StructuredPostal.TYPE_WORK:
stringType = "work";
break;
case ContactsContract.CommonDataKinds.StructuredPostal.TYPE_OTHER:
default:
stringType = "other";
break;
}
return stringType;
}
}
|
Spelling: success
|
framework/src/org/apache/cordova/ContactAccessorSdk5.java
|
Spelling: success
|
<ide><path>ramework/src/org/apache/cordova/ContactAccessorSdk5.java
<ide> retVal = false;
<ide> }
<ide>
<del> // if the save was a succes return the contact ID
<add> // if the save was a success return the contact ID
<ide> if (retVal) {
<ide> return id;
<ide> } else {
|
|
Java
|
apache-2.0
|
252798ccb9cc6835879b248f5c9cdff6494c6638
| 0 |
AndrewKhitrin/dbeaver,AndrewKhitrin/dbeaver,liuyuanyuan/dbeaver,liuyuanyuan/dbeaver,liuyuanyuan/dbeaver,liuyuanyuan/dbeaver,liuyuanyuan/dbeaver,AndrewKhitrin/dbeaver,AndrewKhitrin/dbeaver
|
/*
* DBeaver - Universal Database Manager
* Copyright (C) 2010-2017 Serge Rider ([email protected])
* Copyright (C) 2011-2012 Eugene Fradkin ([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jkiss.dbeaver.ui.preferences;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.*;
import org.jkiss.dbeaver.model.DBPDataSourceContainer;
import org.jkiss.dbeaver.model.preferences.DBPPreferenceStore;
import org.jkiss.dbeaver.ui.UIUtils;
import org.jkiss.dbeaver.ui.editors.sql.SQLPreferenceConstants;
import org.jkiss.dbeaver.utils.PrefUtils;
import org.jkiss.dbeaver.core.CoreMessages;
/**
* PrefPageSQLEditor
*/
public class PrefPageSQLCompletion extends TargetPrefPage
{
public static final String PAGE_ID = "org.jkiss.dbeaver.preferences.main.sql.completion"; //$NON-NLS-1$
private Button csAutoActivationCheck;
private Spinner csAutoActivationDelaySpinner;
private Button csAutoActivateOnKeystroke;
private Button csAutoInsertCheck;
private Combo csInsertCase;
private Button csHideDuplicates;
private Button csShortName;
private Button csInsertSpace;
private Button csUseGlobalSearch;
private Button csFoldingEnabled;
public PrefPageSQLCompletion()
{
super();
}
@Override
protected boolean hasDataSourceSpecificOptions(DBPDataSourceContainer dataSourceDescriptor)
{
DBPPreferenceStore store = dataSourceDescriptor.getPreferenceStore();
return
store.contains(SQLPreferenceConstants.ENABLE_AUTO_ACTIVATION) ||
store.contains(SQLPreferenceConstants.AUTO_ACTIVATION_DELAY) ||
store.contains(SQLPreferenceConstants.ENABLE_KEYSTROKE_ACTIVATION) ||
store.contains(SQLPreferenceConstants.INSERT_SINGLE_PROPOSALS_AUTO) ||
store.contains(SQLPreferenceConstants.PROPOSAL_INSERT_CASE) ||
store.contains(SQLPreferenceConstants.HIDE_DUPLICATE_PROPOSALS) ||
store.contains(SQLPreferenceConstants.PROPOSAL_SHORT_NAME) ||
store.contains(SQLPreferenceConstants.INSERT_SPACE_AFTER_PROPOSALS) ||
store.contains(SQLPreferenceConstants.USE_GLOBAL_ASSISTANT) ||
store.contains(SQLPreferenceConstants.FOLDING_ENABLED)
;
}
@Override
protected boolean supportsDataSourceSpecificOptions()
{
return true;
}
@Override
protected Control createPreferenceContent(Composite parent)
{
Composite composite = UIUtils.createPlaceholder(parent, 1);
// Content assistant
{
Composite assistGroup = UIUtils.createControlGroup(composite, CoreMessages.pref_page_sql_completion_group_sql_assistant, 2, GridData.FILL_HORIZONTAL, 0);
csAutoActivationCheck = UIUtils.createCheckbox(assistGroup, CoreMessages.pref_page_sql_completion_label_enable_auto_activation, CoreMessages.pref_page_sql_completion_label_enable_auto_activation_tip, false, 2);
UIUtils.createControlLabel(assistGroup, CoreMessages.pref_page_sql_completion_label_auto_activation_delay);
csAutoActivationDelaySpinner = new Spinner(assistGroup, SWT.BORDER);
csAutoActivationDelaySpinner.setSelection(0);
csAutoActivationDelaySpinner.setDigits(0);
csAutoActivationDelaySpinner.setIncrement(50);
csAutoActivationDelaySpinner.setMinimum(0);
csAutoActivationDelaySpinner.setMaximum(1000000);
csAutoActivationDelaySpinner.setToolTipText(CoreMessages.pref_page_sql_completion_label_set_auto_activation_delay_tip);
csAutoActivateOnKeystroke = UIUtils.createCheckbox(
assistGroup,
CoreMessages.pref_page_sql_completion_label_activate_on_typing,
CoreMessages.pref_page_sql_completion_label_activate_on_typing_tip,
false, 2);
csAutoInsertCheck = UIUtils.createCheckbox(
assistGroup,
CoreMessages.pref_page_sql_completion_label_auto_insert_proposal,
CoreMessages.pref_page_sql_completion_label_auto_insert_proposal_tip,
false, 2);
UIUtils.createControlLabel(assistGroup, CoreMessages.pref_page_sql_completion_label_insert_case);
csInsertCase = new Combo(assistGroup, SWT.BORDER | SWT.DROP_DOWN | SWT.READ_ONLY);
csInsertCase.add("Default");
csInsertCase.add("Upper case");
csInsertCase.add("Lower case");
csHideDuplicates = UIUtils.createCheckbox(assistGroup, CoreMessages.pref_page_sql_completion_label_hide_duplicate_names, null, false, 2);
csShortName = UIUtils.createCheckbox(assistGroup, CoreMessages.pref_page_sql_completion_label_use_short_names, null, false, 2);
csInsertSpace = UIUtils.createCheckbox(assistGroup, CoreMessages.pref_page_sql_completion_label_insert_space, null, false, 2);
csUseGlobalSearch = UIUtils.createCheckbox(assistGroup, CoreMessages.pref_page_sql_completion_label_use_global_search, CoreMessages.pref_page_sql_completion_label_use_global_search_tip, false, 2);
}
// Content assistant
{
Composite foldingGroup = UIUtils.createControlGroup(composite, CoreMessages.pref_page_sql_completion_group_folding, 2, GridData.FILL_HORIZONTAL, 0);
csFoldingEnabled = UIUtils.createCheckbox(foldingGroup, CoreMessages.pref_page_sql_completion_label_folding_enabled, CoreMessages.pref_page_sql_completion_label_folding_enabled_tip, false, 2);
}
return composite;
}
@Override
protected void loadPreferences(DBPPreferenceStore store)
{
try {
csAutoActivationCheck.setSelection(store.getBoolean(SQLPreferenceConstants.ENABLE_AUTO_ACTIVATION));
csAutoActivationDelaySpinner.setSelection(store.getInt(SQLPreferenceConstants.AUTO_ACTIVATION_DELAY));
csAutoActivateOnKeystroke.setSelection(store.getBoolean(SQLPreferenceConstants.ENABLE_KEYSTROKE_ACTIVATION));
csAutoInsertCheck.setSelection(store.getBoolean(SQLPreferenceConstants.INSERT_SINGLE_PROPOSALS_AUTO));
csInsertCase.select(store.getInt(SQLPreferenceConstants.PROPOSAL_INSERT_CASE));
csHideDuplicates.setSelection(store.getBoolean(SQLPreferenceConstants.HIDE_DUPLICATE_PROPOSALS));
csShortName.setSelection(store.getBoolean(SQLPreferenceConstants.PROPOSAL_SHORT_NAME));
csInsertSpace.setSelection(store.getBoolean(SQLPreferenceConstants.INSERT_SPACE_AFTER_PROPOSALS));
csUseGlobalSearch.setSelection(store.getBoolean(SQLPreferenceConstants.USE_GLOBAL_ASSISTANT));
csFoldingEnabled.setSelection(store.getBoolean(SQLPreferenceConstants.FOLDING_ENABLED));
} catch (Exception e) {
log.warn(e);
}
}
@Override
protected void savePreferences(DBPPreferenceStore store)
{
try {
store.setValue(SQLPreferenceConstants.ENABLE_AUTO_ACTIVATION, csAutoActivationCheck.getSelection());
store.setValue(SQLPreferenceConstants.AUTO_ACTIVATION_DELAY, csAutoActivationDelaySpinner.getSelection());
store.setValue(SQLPreferenceConstants.ENABLE_KEYSTROKE_ACTIVATION, csAutoActivateOnKeystroke.getSelection());
store.setValue(SQLPreferenceConstants.INSERT_SINGLE_PROPOSALS_AUTO, csAutoInsertCheck.getSelection());
store.setValue(SQLPreferenceConstants.PROPOSAL_INSERT_CASE, csInsertCase.getSelectionIndex());
store.setValue(SQLPreferenceConstants.HIDE_DUPLICATE_PROPOSALS, csHideDuplicates.getSelection());
store.setValue(SQLPreferenceConstants.PROPOSAL_SHORT_NAME, csShortName.getSelection());
store.setValue(SQLPreferenceConstants.INSERT_SPACE_AFTER_PROPOSALS, csInsertSpace.getSelection());
store.setValue(SQLPreferenceConstants.USE_GLOBAL_ASSISTANT, csUseGlobalSearch.getSelection());
store.setValue(SQLPreferenceConstants.FOLDING_ENABLED, csFoldingEnabled.getSelection());
} catch (Exception e) {
log.warn(e);
}
PrefUtils.savePreferenceStore(store);
}
@Override
protected void clearPreferences(DBPPreferenceStore store)
{
store.setToDefault(SQLPreferenceConstants.ENABLE_AUTO_ACTIVATION);
store.setToDefault(SQLPreferenceConstants.AUTO_ACTIVATION_DELAY);
store.setToDefault(SQLPreferenceConstants.ENABLE_KEYSTROKE_ACTIVATION);
store.setToDefault(SQLPreferenceConstants.INSERT_SINGLE_PROPOSALS_AUTO);
store.setToDefault(SQLPreferenceConstants.PROPOSAL_INSERT_CASE);
store.setToDefault(SQLPreferenceConstants.HIDE_DUPLICATE_PROPOSALS);
store.setToDefault(SQLPreferenceConstants.PROPOSAL_SHORT_NAME);
store.setToDefault(SQLPreferenceConstants.INSERT_SPACE_AFTER_PROPOSALS);
store.setToDefault(SQLPreferenceConstants.USE_GLOBAL_ASSISTANT);
store.setToDefault(SQLPreferenceConstants.FOLDING_ENABLED);
}
@Override
protected String getPropertyPageID()
{
return PAGE_ID;
}
}
|
plugins/org.jkiss.dbeaver.core/src/org/jkiss/dbeaver/ui/preferences/PrefPageSQLCompletion.java
|
/*
* DBeaver - Universal Database Manager
* Copyright (C) 2010-2017 Serge Rider ([email protected])
* Copyright (C) 2011-2012 Eugene Fradkin ([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jkiss.dbeaver.ui.preferences;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.*;
import org.jkiss.dbeaver.model.DBPDataSourceContainer;
import org.jkiss.dbeaver.model.preferences.DBPPreferenceStore;
import org.jkiss.dbeaver.ui.UIUtils;
import org.jkiss.dbeaver.ui.editors.sql.SQLPreferenceConstants;
import org.jkiss.dbeaver.utils.PrefUtils;
/**
* PrefPageSQLEditor
*/
public class PrefPageSQLCompletion extends TargetPrefPage
{
public static final String PAGE_ID = "org.jkiss.dbeaver.preferences.main.sql.completion"; //$NON-NLS-1$
private Button csAutoActivationCheck;
private Spinner csAutoActivationDelaySpinner;
private Button csAutoActivateOnKeystroke;
private Button csAutoInsertCheck;
private Combo csInsertCase;
private Button csHideDuplicates;
private Button csShortName;
private Button csInsertSpace;
private Button csUseGlobalSearch;
private Button csFoldingEnabled;
public PrefPageSQLCompletion()
{
super();
}
@Override
protected boolean hasDataSourceSpecificOptions(DBPDataSourceContainer dataSourceDescriptor)
{
DBPPreferenceStore store = dataSourceDescriptor.getPreferenceStore();
return
store.contains(SQLPreferenceConstants.ENABLE_AUTO_ACTIVATION) ||
store.contains(SQLPreferenceConstants.AUTO_ACTIVATION_DELAY) ||
store.contains(SQLPreferenceConstants.ENABLE_KEYSTROKE_ACTIVATION) ||
store.contains(SQLPreferenceConstants.INSERT_SINGLE_PROPOSALS_AUTO) ||
store.contains(SQLPreferenceConstants.PROPOSAL_INSERT_CASE) ||
store.contains(SQLPreferenceConstants.HIDE_DUPLICATE_PROPOSALS) ||
store.contains(SQLPreferenceConstants.PROPOSAL_SHORT_NAME) ||
store.contains(SQLPreferenceConstants.INSERT_SPACE_AFTER_PROPOSALS) ||
store.contains(SQLPreferenceConstants.USE_GLOBAL_ASSISTANT) ||
store.contains(SQLPreferenceConstants.FOLDING_ENABLED)
;
}
@Override
protected boolean supportsDataSourceSpecificOptions()
{
return true;
}
@Override
protected Control createPreferenceContent(Composite parent)
{
Composite composite = UIUtils.createPlaceholder(parent, 1);
// Content assistant
{
Composite assistGroup = UIUtils.createControlGroup(composite, "SQL assistant/completion", 2, GridData.FILL_HORIZONTAL, 0);
csAutoActivationCheck = UIUtils.createCheckbox(assistGroup, "Enable auto activation", "Enables content assistant auto activation (on text typing)", false, 2);
UIUtils.createControlLabel(assistGroup, "Auto activation delay");
csAutoActivationDelaySpinner = new Spinner(assistGroup, SWT.BORDER);
csAutoActivationDelaySpinner.setSelection(0);
csAutoActivationDelaySpinner.setDigits(0);
csAutoActivationDelaySpinner.setIncrement(50);
csAutoActivationDelaySpinner.setMinimum(0);
csAutoActivationDelaySpinner.setMaximum(1000000);
csAutoActivationDelaySpinner.setToolTipText("Delay before content assistant will run after typing trigger key");
csAutoActivateOnKeystroke = UIUtils.createCheckbox(
assistGroup,
"Activate on typing",
"Activate completion proposals on any letter typing.",
false, 2);
csAutoInsertCheck = UIUtils.createCheckbox(
assistGroup,
"Auto-insert proposal",
"Enables the content assistant's auto insertion mode.\nIf enabled, the content assistant inserts a proposal automatically if it is the only proposal.\nIn the case of ambiguities, the user must make the choice.",
false, 2);
UIUtils.createControlLabel(assistGroup, "Insert case");
csInsertCase = new Combo(assistGroup, SWT.BORDER | SWT.DROP_DOWN | SWT.READ_ONLY);
csInsertCase.add("Default");
csInsertCase.add("Upper case");
csInsertCase.add("Lower case");
csHideDuplicates = UIUtils.createCheckbox(assistGroup, "Hide duplicate names from non-active schemas", null, false, 2);
csShortName = UIUtils.createCheckbox(assistGroup, "Use short object names (omit schema/catalog)", null, false, 2);
csInsertSpace = UIUtils.createCheckbox(assistGroup, "Insert space after table/column names", null, false, 2);
csUseGlobalSearch = UIUtils.createCheckbox(assistGroup, "Use global search (in all schemas)", "Search for objects in all schemas. Otherwise search only in current/system schemas.", false, 2);
}
// Content assistant
{
Composite foldingGroup = UIUtils.createControlGroup(composite, "Folding", 2, GridData.FILL_HORIZONTAL, 0);
csFoldingEnabled = UIUtils.createCheckbox(foldingGroup, "Folding enabled", "Use folding in SQL scripts.", false, 2);
}
return composite;
}
@Override
protected void loadPreferences(DBPPreferenceStore store)
{
try {
csAutoActivationCheck.setSelection(store.getBoolean(SQLPreferenceConstants.ENABLE_AUTO_ACTIVATION));
csAutoActivationDelaySpinner.setSelection(store.getInt(SQLPreferenceConstants.AUTO_ACTIVATION_DELAY));
csAutoActivateOnKeystroke.setSelection(store.getBoolean(SQLPreferenceConstants.ENABLE_KEYSTROKE_ACTIVATION));
csAutoInsertCheck.setSelection(store.getBoolean(SQLPreferenceConstants.INSERT_SINGLE_PROPOSALS_AUTO));
csInsertCase.select(store.getInt(SQLPreferenceConstants.PROPOSAL_INSERT_CASE));
csHideDuplicates.setSelection(store.getBoolean(SQLPreferenceConstants.HIDE_DUPLICATE_PROPOSALS));
csShortName.setSelection(store.getBoolean(SQLPreferenceConstants.PROPOSAL_SHORT_NAME));
csInsertSpace.setSelection(store.getBoolean(SQLPreferenceConstants.INSERT_SPACE_AFTER_PROPOSALS));
csUseGlobalSearch.setSelection(store.getBoolean(SQLPreferenceConstants.USE_GLOBAL_ASSISTANT));
csFoldingEnabled.setSelection(store.getBoolean(SQLPreferenceConstants.FOLDING_ENABLED));
} catch (Exception e) {
log.warn(e);
}
}
@Override
protected void savePreferences(DBPPreferenceStore store)
{
try {
store.setValue(SQLPreferenceConstants.ENABLE_AUTO_ACTIVATION, csAutoActivationCheck.getSelection());
store.setValue(SQLPreferenceConstants.AUTO_ACTIVATION_DELAY, csAutoActivationDelaySpinner.getSelection());
store.setValue(SQLPreferenceConstants.ENABLE_KEYSTROKE_ACTIVATION, csAutoActivateOnKeystroke.getSelection());
store.setValue(SQLPreferenceConstants.INSERT_SINGLE_PROPOSALS_AUTO, csAutoInsertCheck.getSelection());
store.setValue(SQLPreferenceConstants.PROPOSAL_INSERT_CASE, csInsertCase.getSelectionIndex());
store.setValue(SQLPreferenceConstants.HIDE_DUPLICATE_PROPOSALS, csHideDuplicates.getSelection());
store.setValue(SQLPreferenceConstants.PROPOSAL_SHORT_NAME, csShortName.getSelection());
store.setValue(SQLPreferenceConstants.INSERT_SPACE_AFTER_PROPOSALS, csInsertSpace.getSelection());
store.setValue(SQLPreferenceConstants.USE_GLOBAL_ASSISTANT, csUseGlobalSearch.getSelection());
store.setValue(SQLPreferenceConstants.FOLDING_ENABLED, csFoldingEnabled.getSelection());
} catch (Exception e) {
log.warn(e);
}
PrefUtils.savePreferenceStore(store);
}
@Override
protected void clearPreferences(DBPPreferenceStore store)
{
store.setToDefault(SQLPreferenceConstants.ENABLE_AUTO_ACTIVATION);
store.setToDefault(SQLPreferenceConstants.AUTO_ACTIVATION_DELAY);
store.setToDefault(SQLPreferenceConstants.ENABLE_KEYSTROKE_ACTIVATION);
store.setToDefault(SQLPreferenceConstants.INSERT_SINGLE_PROPOSALS_AUTO);
store.setToDefault(SQLPreferenceConstants.PROPOSAL_INSERT_CASE);
store.setToDefault(SQLPreferenceConstants.HIDE_DUPLICATE_PROPOSALS);
store.setToDefault(SQLPreferenceConstants.PROPOSAL_SHORT_NAME);
store.setToDefault(SQLPreferenceConstants.INSERT_SPACE_AFTER_PROPOSALS);
store.setToDefault(SQLPreferenceConstants.USE_GLOBAL_ASSISTANT);
store.setToDefault(SQLPreferenceConstants.FOLDING_ENABLED);
}
@Override
protected String getPropertyPageID()
{
return PAGE_ID;
}
}
|
Update PrefPageSQLCompletion.java
|
plugins/org.jkiss.dbeaver.core/src/org/jkiss/dbeaver/ui/preferences/PrefPageSQLCompletion.java
|
Update PrefPageSQLCompletion.java
|
<ide><path>lugins/org.jkiss.dbeaver.core/src/org/jkiss/dbeaver/ui/preferences/PrefPageSQLCompletion.java
<ide> import org.jkiss.dbeaver.ui.UIUtils;
<ide> import org.jkiss.dbeaver.ui.editors.sql.SQLPreferenceConstants;
<ide> import org.jkiss.dbeaver.utils.PrefUtils;
<add>import org.jkiss.dbeaver.core.CoreMessages;
<ide>
<ide> /**
<ide> * PrefPageSQLEditor
<ide>
<ide> // Content assistant
<ide> {
<del> Composite assistGroup = UIUtils.createControlGroup(composite, "SQL assistant/completion", 2, GridData.FILL_HORIZONTAL, 0);
<add> Composite assistGroup = UIUtils.createControlGroup(composite, CoreMessages.pref_page_sql_completion_group_sql_assistant, 2, GridData.FILL_HORIZONTAL, 0);
<ide>
<del> csAutoActivationCheck = UIUtils.createCheckbox(assistGroup, "Enable auto activation", "Enables content assistant auto activation (on text typing)", false, 2);
<add> csAutoActivationCheck = UIUtils.createCheckbox(assistGroup, CoreMessages.pref_page_sql_completion_label_enable_auto_activation, CoreMessages.pref_page_sql_completion_label_enable_auto_activation_tip, false, 2);
<ide>
<del> UIUtils.createControlLabel(assistGroup, "Auto activation delay");
<add> UIUtils.createControlLabel(assistGroup, CoreMessages.pref_page_sql_completion_label_auto_activation_delay);
<ide> csAutoActivationDelaySpinner = new Spinner(assistGroup, SWT.BORDER);
<ide> csAutoActivationDelaySpinner.setSelection(0);
<ide> csAutoActivationDelaySpinner.setDigits(0);
<ide> csAutoActivationDelaySpinner.setIncrement(50);
<ide> csAutoActivationDelaySpinner.setMinimum(0);
<ide> csAutoActivationDelaySpinner.setMaximum(1000000);
<del> csAutoActivationDelaySpinner.setToolTipText("Delay before content assistant will run after typing trigger key");
<add> csAutoActivationDelaySpinner.setToolTipText(CoreMessages.pref_page_sql_completion_label_set_auto_activation_delay_tip);
<ide>
<ide> csAutoActivateOnKeystroke = UIUtils.createCheckbox(
<ide> assistGroup,
<del> "Activate on typing",
<del> "Activate completion proposals on any letter typing.",
<add> CoreMessages.pref_page_sql_completion_label_activate_on_typing,
<add> CoreMessages.pref_page_sql_completion_label_activate_on_typing_tip,
<ide> false, 2);
<ide> csAutoInsertCheck = UIUtils.createCheckbox(
<ide> assistGroup,
<del> "Auto-insert proposal",
<del> "Enables the content assistant's auto insertion mode.\nIf enabled, the content assistant inserts a proposal automatically if it is the only proposal.\nIn the case of ambiguities, the user must make the choice.",
<add> CoreMessages.pref_page_sql_completion_label_auto_insert_proposal,
<add> CoreMessages.pref_page_sql_completion_label_auto_insert_proposal_tip,
<ide> false, 2);
<ide>
<del> UIUtils.createControlLabel(assistGroup, "Insert case");
<add> UIUtils.createControlLabel(assistGroup, CoreMessages.pref_page_sql_completion_label_insert_case);
<ide> csInsertCase = new Combo(assistGroup, SWT.BORDER | SWT.DROP_DOWN | SWT.READ_ONLY);
<ide> csInsertCase.add("Default");
<ide> csInsertCase.add("Upper case");
<ide> csInsertCase.add("Lower case");
<ide>
<del> csHideDuplicates = UIUtils.createCheckbox(assistGroup, "Hide duplicate names from non-active schemas", null, false, 2);
<del> csShortName = UIUtils.createCheckbox(assistGroup, "Use short object names (omit schema/catalog)", null, false, 2);
<del> csInsertSpace = UIUtils.createCheckbox(assistGroup, "Insert space after table/column names", null, false, 2);
<del> csUseGlobalSearch = UIUtils.createCheckbox(assistGroup, "Use global search (in all schemas)", "Search for objects in all schemas. Otherwise search only in current/system schemas.", false, 2);
<add> csHideDuplicates = UIUtils.createCheckbox(assistGroup, CoreMessages.pref_page_sql_completion_label_hide_duplicate_names, null, false, 2);
<add> csShortName = UIUtils.createCheckbox(assistGroup, CoreMessages.pref_page_sql_completion_label_use_short_names, null, false, 2);
<add> csInsertSpace = UIUtils.createCheckbox(assistGroup, CoreMessages.pref_page_sql_completion_label_insert_space, null, false, 2);
<add> csUseGlobalSearch = UIUtils.createCheckbox(assistGroup, CoreMessages.pref_page_sql_completion_label_use_global_search, CoreMessages.pref_page_sql_completion_label_use_global_search_tip, false, 2);
<ide> }
<ide>
<ide> // Content assistant
<ide> {
<del> Composite foldingGroup = UIUtils.createControlGroup(composite, "Folding", 2, GridData.FILL_HORIZONTAL, 0);
<add> Composite foldingGroup = UIUtils.createControlGroup(composite, CoreMessages.pref_page_sql_completion_group_folding, 2, GridData.FILL_HORIZONTAL, 0);
<ide>
<del> csFoldingEnabled = UIUtils.createCheckbox(foldingGroup, "Folding enabled", "Use folding in SQL scripts.", false, 2);
<add> csFoldingEnabled = UIUtils.createCheckbox(foldingGroup, CoreMessages.pref_page_sql_completion_label_folding_enabled, CoreMessages.pref_page_sql_completion_label_folding_enabled_tip, false, 2);
<ide> }
<ide> return composite;
<ide> }
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.