gt stringclasses 1
value | context stringlengths 2.05k 161k |
|---|---|
package controller;
import View.MyStage;
import View.TabAdminView;
import View.TabUserView;
import javafx.animation.*;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.ScatterChart;
import javafx.scene.chart.XYChart;
import javafx.scene.control.*;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import javafx.util.Duration;
import model.LinearRegression;
import model.Postgresql;
import java.util.ArrayList;
import java.util.List;
public class Form {
StackPane stackPane;
TabUserView tabUser;
TabAdminView tabAdmin;
public MyStage stage;
int xSize = 500;
int ySize = 400;
int inputHeight=170;
int inputWeight=60;
int ennustus =0;
String inputName;
int id=0;
Postgresql sql = new Postgresql();
LinearRegression linearRegression = new LinearRegression();
public Form() {
tabAdmin = new TabAdminView("Admin");//create admin tab
tabUser = new TabUserView("User",inputHeight, inputWeight, xSize);//create user tab
stage = new MyStage( tabUser, tabAdmin, xSize, ySize);//put tabs together into stage
addListeners(); //add listeners to form objects
}
public void addListeners(){ //events and listeners for buttons and sliders with corresponding functions
tabAdmin.buttonDeleteWorkTable.setOnAction(event -> {
adminButtonDeleteWorkTable();
});
tabAdmin.buttonRePopulateWorkTable.setOnAction(event -> {
adminButtonRePopulateWorkTable();
});
tabUser.buttonSave.setOnAction(event -> {
userButtonSave();
});
tabUser.buttonPredict.setOnAction(event -> {
userButtonPredict();
});
tabUser.buttonNew.setOnAction(event -> {
userButtonNew();
});
tabUser.buttonOpenChart.setOnAction(event -> {
userButtonOpenChart();
});
tabUser.buttonCloseChart.setOnAction(event -> {
userButtonCloseChart();
});
tabUser.sliderInputHeight.valueProperty().addListener((observable, vanaVaartus, uusVaartus) -> {
//http://i200.itcollege.ee/javafx-Slider
inputHeight = uusVaartus.intValue();
tabUser.labelInputHeight.setText("Sinu pikkus sentimeetrites: " + inputHeight);
tabUser.buttonSave.setClickedEnable();
});
tabUser.sliderInputWeight.valueProperty().addListener((observable, vanaVaartus, uusVaartus) -> {
//http://i200.itcollege.ee/javafx-Slider
inputWeight = uusVaartus.intValue();
tabUser.labelInputWeight.setText("Sinu kaal kilogrammides: " +inputWeight);
tabUser.buttonSave.setDisable(false);
tabUser.buttonSave.setClickedEnable();
});
}
//button functions
private void adminButtonDeleteWorkTable(){
String query = new String("delete from height_weight;");
System.out.println(query);
sql.execute_query(query);
tabAdmin.labelComments.setText("height_weight tabelis on ridasid:" + sql.select("Select count(id) from height_weight;"));
}
private void adminButtonRePopulateWorkTable() {
String query = new String("INSERT INTO height_weight SELECT id, height, weight, username, insertdate FROM height_weight_orig;");
System.out.println(query);
sql.execute_query(query);
tabAdmin.labelComments.setText("height_weight tabelis on ridasid:" + sql.select("Select count(id) from height_weight;"));
}
private void userButtonSave(){
inputName = tabUser.fieldInputName.getText();
String query = new String("INSERT INTO height_weight (height, weight, username) VALUES ("+inputHeight + "," +inputWeight +",'" + inputName+"' ) ;");
System.out.println(query);
sql.execute_query(query);
query = "Select max(id), count(id) from height_weight;";
System.out.println(query);
id = Integer.parseInt((String) sql.select(query).get(0).get(0));
int dbCount =Integer.parseInt((String) sql.select(query).get(0).get(1));
tabUser.labelComments.setText("Salvestati " + inputHeight + "cm ja " + inputWeight + "kg. " + "Andmebaasis on ridasid: " + dbCount) ;
tabUser.buttonSave.setClickedDisable();
tabUser.buttonPredict.setClickedEnable();
}
private void userButtonPredict(){
if (id==0){
tabUser.labelComments.setText("Enne joonistamist salvesta enda andmed");
} else {
double[] coefs = (linearRegression.calc_coefs(id));
ennustus = (int) (coefs[0] + coefs[1] * inputHeight);
System.out.println(coefs[0] + "," + coefs[1]);
tabUser.labelComments.setText("Sinu ennustatav kaal on:" + String.format("%.2g", coefs[0]) + "+" + String.format("%.2g", coefs[1]) + "*" + inputHeight + "=" + ennustus);
tabUser.buttonOpenChart.setClickedEnable();
tabUser.buttonPredict.setClickedDisable();
}
}
private void userButtonNew() {
inputHeight= 170;
inputWeight= 60;
inputName= "";
id= 0;
ennustus =0;
tabUser.labelHello.setText("Tere");
tabUser.fieldInputName.setText("Priit");
tabUser.labelInputHeight.setText("Sinu pikkus sentimeetrites: "+inputHeight);
tabUser.labelInputWeight.setText("Sinu kaal kilogrammides: "+inputWeight);
tabUser.sliderInputHeight.setValue(inputHeight);
tabUser.sliderInputWeight.setValue(inputWeight);
tabUser.labelComments.setText("");
tabUser.buttonCloseChart.fire(); //sulgeb joonise
tabUser.buttonSave.setClickedEnable();
tabUser.buttonOpenChart.setClickedDisable();
tabUser.buttonPredict.setClickedDisable();
}
private void userButtonOpenChart(){
if (id==0){
tabUser.labelComments.setText("Enne joonistamist salvesta enda andmed");
} else {
roomForChartAnimation(ySize + 400);
tabUser.borderPane.setBottom(drawChart());
}
tabUser.buttonCloseChart.setClicked();
tabUser.buttonOpenChart.setClicked();
}
private void userButtonCloseChart() {
roomForChartAnimation(ySize);
tabUser.buttonCloseChart.setClicked();
tabUser.buttonOpenChart.setClicked();
}
//build scatterchart
public ScatterChart<Number,Number> drawChart(){
//get max and min for x axis length
String query = new String("select max(height), min(height) from height_weight;");
System.out.println(query);
ArrayList<List> maxData = new ArrayList(sql.select(query)) ;
int minAxisValue = model.helpers.roundUpDown(Integer.parseInt((String) (maxData.get(0).get(1))), -10);
int maxAxisValue = model.helpers.roundUpDown(Integer.parseInt((String) (maxData.get(0).get(0))), 10);
final NumberAxis xAxis = new NumberAxis(minAxisValue, maxAxisValue, 10);
//get max and min for y axis lengths
query = ("select max(weight), min(weight) from height_weight;");
System.out.println(query);
maxData = (sql.select(query)) ;
minAxisValue = model.helpers.roundUpDown(Integer.parseInt((String) (maxData.get(0).get(1))), -10);
maxAxisValue = model.helpers.roundUpDown(Integer.parseInt((String)(maxData.get(0).get(0)) ),10);
final NumberAxis yAxis = new NumberAxis(minAxisValue, maxAxisValue, 10); //add maxmin to axis
//format scatter chart
xAxis.setLabel("Pikkus cm");
yAxis.setLabel("Kaal kg");
final ScatterChart<Number,Number> sc = new ScatterChart<Number,Number>(xAxis,yAxis);
sc.setTitle("Pikkuse ja kaalu seos");
//get train data and add to Series1
query = ("Select height, weight from height_weight where id != "+id+";");
System.out.println(query);
ArrayList<List> chartData = new ArrayList(sql.select(query)) ;
XYChart.Series series1 = new XYChart.Series();
series1.setName("train data");
XYChart.Series series2 = new XYChart.Series();
series2.setName(inputName+ " tegelik");
for (int i = 0; i < chartData.size(); i++) {
series1.getData().add(new XYChart.Data(Integer.parseInt((String) chartData.get(i).get(0))+Math.random()/2,
Integer.parseInt((String) chartData.get(i).get(1))+Math.random()/2));
}
//get real height and weight data and add to series2
query = "Select height, weight from height_weight where id = "+id+";";
chartData =sql.select(query);
series2.getData().add(new XYChart.Data(Integer.parseInt((String) chartData.get(0).get(0)), Integer.parseInt((String) chartData.get(0).get(1))));
//add prediction to series3
if (ennustus!=0) {
XYChart.Series series3 = new XYChart.Series();
series3.setName(inputName + " ennustus");
series3.getData().add(new XYChart.Data(inputHeight, ennustus));
sc.getData().addAll(series1, series2, series3);
} else {
sc.getData().addAll(series1, series2);
}
return sc;
}
private void roomForChartAnimation(int heightInput){
//http://www.java2s.com/Tutorials/Java/JavaFX/1010__JavaFX_Timeline_Animation.htm
//http://docs.oracle.com/javafx/2/animations/basics.htm
Timeline timeline;
//create a timeline for moving the circle
timeline = new Timeline();
timeline.setCycleCount(1);
timeline.setAutoReverse(true);
//create a keyValue with factory: scaling the circle 2times
KeyValue keyValueX1 = new KeyValue(stage.minHeightProperty(), heightInput, Interpolator.EASE_OUT);
KeyValue keyValueX2 = new KeyValue(stage.maxHeightProperty(), heightInput, Interpolator.EASE_OUT);
//create a keyFrame, the keyValue is reached at time 2s
Duration duration = Duration.millis(1000);
//one can add a specific action when the keyframe is reached
EventHandler onFinished = new EventHandler<ActionEvent>() {
public void handle(ActionEvent t) {
//reset counter
// i = 0;
}
};
KeyFrame keyFrame = new KeyFrame(duration, onFinished,keyValueX1,keyValueX2 );
//add the keyframe to the timeline
timeline.getKeyFrames().add(keyFrame);
timeline.play();
}
}
| |
/*
* Copyright (c) 2016, Salesforce.com, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. 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.
*
* 3. Neither the name of Salesforce.com 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 HOLDER 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 com.salesforce.dva.argus.service.metric.transform;
import com.salesforce.dva.argus.entity.Metric;
import org.junit.Test;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.assertEquals;
public class MovingTransformTest {
private static final String TEST_SCOPE = "test-scope";
private static final String TEST_METRIC = "test-metric";
@Test
public void testMovingDefaultTransformWithTimeInterval() {
Transform movingTransform = new MetricMappingTransform(new MovingValueMapping());
Map<Long, Double> datapoints = new HashMap<Long, Double>();
datapoints.put(1000L, 1.0);
datapoints.put(2000L, 2.0);
datapoints.put(3000L, 3.0);
datapoints.put(5000L, 10.0);
datapoints.put(6000L, 2.0);
datapoints.put(7000L, 3.0);
datapoints.put(10000L, 15.0);
Map<Long, Double> actual = new HashMap<Long, Double>();
actual.put(1000L, 1.0);
actual.put(2000L, 1.5);
actual.put(3000L, 2.5);
actual.put(5000L, 10.0);
actual.put(6000L, 6.0);
actual.put(7000L, 2.5);
actual.put(10000L, 15.0);
Metric metric = new Metric(TEST_SCOPE, TEST_METRIC);
metric.setDatapoints(datapoints);
List<Metric> metrics = new ArrayList<Metric>();
metrics.add(metric);
List<String> constants = new ArrayList<String>(1);
constants.add("2s");
List<Metric> result = movingTransform.transform(metrics, constants);
assertEquals(result.get(0).getDatapoints().size(), actual.size());
assertEquals(result.get(0).getDatapoints(), actual);
}
@Test
public void testMovingMedianTransformWithTimeInterval() {
Transform movingTransform = new MetricMappingTransform(new MovingValueMapping());
Map<Long, Double> datapoints = new HashMap<Long, Double>();
datapoints.put(1000L, 1.0);
datapoints.put(2000L, 2.0);
datapoints.put(3000L, 3.0);
datapoints.put(5000L, 10.0);
datapoints.put(6000L, 2.0);
datapoints.put(7000L, 3.0);
datapoints.put(10000L, 15.0);
Map<Long, Double> actual = new HashMap<Long, Double>();
actual.put(1000L, 1.0);
actual.put(2000L, 1.5);
actual.put(3000L, 2.5);
actual.put(5000L, 10.0);
actual.put(6000L, 6.0);
actual.put(7000L, 2.5);
actual.put(10000L, 15.0);
Metric metric = new Metric(TEST_SCOPE, TEST_METRIC);
metric.setDatapoints(datapoints);
List<Metric> metrics = new ArrayList<Metric>();
metrics.add(metric);
List<String> constants = new ArrayList<String>(1);
constants.add("2s");
constants.add("median");
List<Metric> result = movingTransform.transform(metrics, constants);
assertEquals(result.get(0).getDatapoints().size(), actual.size());
assertEquals(result.get(0).getDatapoints(), actual);
}
@Test
public void testMovingSumTransformWithTimeInterval() {
Transform movingTransform = new MetricMappingTransform(new MovingValueMapping());
Map<Long, Double> datapoints = new HashMap<Long, Double>();
datapoints.put(1000L, 1.0);
datapoints.put(2000L, 2.0);
datapoints.put(3000L, 3.0);
datapoints.put(5000L, 10.0);
datapoints.put(6000L, 2.0);
datapoints.put(7000L, 3.0);
datapoints.put(10000L, 15.0);
Map<Long, Double> actual = new HashMap<Long, Double>();
actual.put(1000L, 1.0);
actual.put(2000L, 3.0);
actual.put(3000L, 5.0);
actual.put(5000L, 10.0);
actual.put(6000L, 12.0);
actual.put(7000L, 5.0);
actual.put(10000L, 15.0);
Metric metric = new Metric(TEST_SCOPE, TEST_METRIC);
metric.setDatapoints(datapoints);
List<Metric> metrics = new ArrayList<Metric>();
metrics.add(metric);
List<String> constants = new ArrayList<String>(1);
constants.add("2s");
constants.add("sum");
List<Metric> result = movingTransform.transform(metrics, constants);
assertEquals(result.get(0).getDatapoints().size(), actual.size());
assertEquals(result.get(0).getDatapoints(), actual);
}
@Test
public void testMovingAvgTransformWithTimeIntervalHasNullValue() {
Transform movingTransform = new MetricMappingTransform(new MovingValueMapping());
Map<Long, Double> datapoints = new HashMap<>();
datapoints.put(1000L, null);
datapoints.put(2000L, null);
datapoints.put(3000L, null);
datapoints.put(5000L, 10.0);
datapoints.put(6000L, 2.0);
datapoints.put(7000L, 3.0);
datapoints.put(10000L, 15.0);
Map<Long, Double> actual = new HashMap<>();
actual.put(1000L, 0.0);
actual.put(2000L, 0.0);
actual.put(3000L, 0.0);
actual.put(5000L, 10.0);
actual.put(6000L, 6.0);
actual.put(7000L, 2.5);
actual.put(10000L, 15.0);
Metric metric = new Metric(TEST_SCOPE, TEST_METRIC);
metric.setDatapoints(datapoints);
List<Metric> metrics = new ArrayList<Metric>();
metrics.add(metric);
List<String> constants = new ArrayList<String>(1);
constants.add("2s");
constants.add("avg");
List<Metric> result = movingTransform.transform(metrics, constants);
assertEquals(result.get(0).getDatapoints().size(), actual.size());
assertEquals(result.get(0).getDatapoints(), actual);
}
@Test
public void testMovingMedianTransformWithTimeIntervalHasNullValue() {
Transform movingTransform = new MetricMappingTransform(new MovingValueMapping());
Map<Long, Double> datapoints = new HashMap<>();
datapoints.put(1000L, null);
datapoints.put(2000L, 2.0);
datapoints.put(3000L, 4.0);
datapoints.put(5000L, 10.0);
datapoints.put(6000L, 2.0);
datapoints.put(7000L, 3.0);
datapoints.put(10000L, 15.0);
Map<Long, Double> actual = new HashMap<Long, Double>();
actual.put(1000L, 0.0);
actual.put(2000L, 1.0);
actual.put(3000L, 3.0);
actual.put(5000L, 10.0);
actual.put(6000L, 6.0);
actual.put(7000L, 2.5);
actual.put(10000L, 15.0);
Metric metric = new Metric(TEST_SCOPE, TEST_METRIC);
metric.setDatapoints(datapoints);
List<Metric> metrics = new ArrayList<Metric>();
metrics.add(metric);
List<String> constants = new ArrayList<String>(1);
constants.add("2s");
constants.add("median");
List<Metric> result = movingTransform.transform(metrics, constants);
assertEquals(result.get(0).getDatapoints().size(), actual.size());
assertEquals(result.get(0).getDatapoints(), actual);
}
@Test
public void movingRunOutOfPointsBeforeHittingwindow() {
Transform movingTransform = new MetricMappingTransform(new MovingValueMapping());
Map<Long, Double> datapoints = new HashMap<Long, Double>();
datapoints.put(0L, 3.0);
datapoints.put(60000L, 6.0);
datapoints.put(120000L, 9.0);
Map<Long, Double> actual = new HashMap<Long, Double>();
actual.put(0L, 3.0);
actual.put(60000L, 4.5);
actual.put(120000L, 7.5);
Metric metric = new Metric(TEST_SCOPE, TEST_METRIC);
metric.setDatapoints(datapoints);
List<Metric> metrics = new ArrayList<Metric>();
metrics.add(metric);
List<String> constants = new ArrayList<String>(1);
constants.add("120s");
constants.add("avg");
List<Metric> result = movingTransform.transform(metrics, constants);
assertEquals(result.get(0).getDatapoints().size(), 3);
assertEquals(result.get(0).getDatapoints(), actual);
}
@Test
public void movingWithOnlyOnePoint() {
Transform movingTransform = new MetricMappingTransform(new MovingValueMapping());
Map<Long, Double> datapoints = new HashMap<Long, Double>();
datapoints.put(0L, 3.0);
Map<Long, Double> actual = new HashMap<Long, Double>();
actual.put(0L, 3.0);
Metric metric = new Metric(TEST_SCOPE, TEST_METRIC);
metric.setDatapoints(datapoints);
List<Metric> metrics = new ArrayList<Metric>();
metrics.add(metric);
List<String> constants = new ArrayList<String>(1);
constants.add("120s");
constants.add("avg");
List<Metric> result = movingTransform.transform(metrics, constants);
assertEquals(result.get(0).getDatapoints().size(), 1);
assertEquals(result.get(0).getDatapoints(), actual);
}
@Test(expected = UnsupportedOperationException.class)
public void transform_ShouldThrowUnsupportedOperationExceptionWhenNoConstantsAreSpecified() {
List<Metric> metrics = new ArrayList<Metric>();
metrics.add(new Metric(TEST_SCOPE, TEST_METRIC));
Transform movingTransform = new MetricMappingTransform(new MovingValueMapping());
movingTransform.transform(metrics);
}
@Test(expected = IllegalArgumentException.class)
public void transform_ShouldThrowIllegalArgumentExceptionWhenNoWindowSizeIsSpecified() {
List<Metric> metrics = new ArrayList<Metric>();
metrics.add(new Metric(TEST_SCOPE, TEST_METRIC));
Transform movingTransform = new MetricMappingTransform(new MovingValueMapping());
List<String> constants = new ArrayList<String>(1);
movingTransform.transform(metrics, constants);
}
@Test(expected = IllegalArgumentException.class)
public void transform_ShouldThrowIllegalArgumentExceptionWhenTypeIsInvalid() {
List<Metric> metrics = new ArrayList<Metric>();
metrics.add(new Metric(TEST_SCOPE, TEST_METRIC));
Transform movingTransform = new MetricMappingTransform(new MovingValueMapping());
List<String> constants = new ArrayList<String>();
constants.add("2");
constants.add("foobar");
movingTransform.transform(metrics, constants);
}
@Test
public void testMovingAvgTransformScopeName() {
Transform movingAvgTransform = new MetricMappingTransform(new MovingValueMapping());
assertEquals("MOVING", movingAvgTransform.getResultScopeName());
}
}
/* Copyright (c) 2016, Salesforce.com, Inc. All rights reserved. */
| |
/*
* Copyright (C) 2017 Beijing Didi Infinity Technology and Development Co.,Ltd. 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.didi.virtualapk.internal;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ActivityThread;
import android.app.LoadedApk;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.res.AssetManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.content.res.ResourcesImpl;
import android.content.res.ResourcesKey;
import android.os.Build;
import android.util.ArrayMap;
import android.util.DisplayMetrics;
import android.util.Log;
import com.didi.virtualapk.PluginManager;
import com.didi.virtualapk.utils.Reflector;
import java.io.File;
import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
/**
* Created by renyugang on 16/8/9.
*/
class ResourcesManager {
public static final String TAG = Constants.TAG_PREFIX + "LoadedPlugin";
private static Configuration mDefaultConfiguration;
public static synchronized Resources createResources(Context hostContext, String packageName, File apk) throws Exception {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
return createResourcesForN(hostContext, packageName, apk);
}
Resources resources = ResourcesManager.createResourcesSimple(hostContext, apk.getAbsolutePath());
ResourcesManager.hookResources(hostContext, resources);
return resources;
}
private static Resources createResourcesSimple(Context hostContext, String apk) throws Exception {
Resources hostResources = hostContext.getResources();
Resources newResources = null;
AssetManager assetManager;
Reflector reflector = Reflector.on(AssetManager.class).method("addAssetPath", String.class);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
assetManager = AssetManager.class.newInstance();
reflector.bind(assetManager);
final int cookie1 = reflector.call(hostContext.getApplicationInfo().sourceDir);;
if (cookie1 == 0) {
throw new RuntimeException("createResources failed, can't addAssetPath for " + hostContext.getApplicationInfo().sourceDir);
}
} else {
assetManager = hostResources.getAssets();
reflector.bind(assetManager);
}
final int cookie2 = reflector.call(apk);
if (cookie2 == 0) {
throw new RuntimeException("createResources failed, can't addAssetPath for " + apk);
}
List<LoadedPlugin> pluginList = PluginManager.getInstance(hostContext).getAllLoadedPlugins();
for (LoadedPlugin plugin : pluginList) {
final int cookie3 = reflector.call(plugin.getLocation());
if (cookie3 == 0) {
throw new RuntimeException("createResources failed, can't addAssetPath for " + plugin.getLocation());
}
}
if (isMiUi(hostResources)) {
newResources = MiUiResourcesCompat.createResources(hostResources, assetManager);
} else if (isVivo(hostResources)) {
newResources = VivoResourcesCompat.createResources(hostContext, hostResources, assetManager);
} else if (isNubia(hostResources)) {
newResources = NubiaResourcesCompat.createResources(hostResources, assetManager);
} else if (isNotRawResources(hostResources)) {
newResources = AdaptationResourcesCompat.createResources(hostResources, assetManager);
} else {
// is raw android resources
newResources = new Resources(assetManager, hostResources.getDisplayMetrics(), hostResources.getConfiguration());
}
// lastly, sync all LoadedPlugin to newResources
for (LoadedPlugin plugin : pluginList) {
plugin.updateResources(newResources);
}
return newResources;
}
public static void hookResources(Context base, Resources resources) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
return;
}
try {
Reflector reflector = Reflector.with(base);
reflector.field("mResources").set(resources);
Object loadedApk = reflector.field("mPackageInfo").get();
Reflector.with(loadedApk).field("mResources").set(resources);
Object activityThread = ActivityThread.currentActivityThread();
Object resManager;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
resManager = android.app.ResourcesManager.getInstance();
} else {
resManager = Reflector.with(activityThread).field("mResourcesManager").get();
}
Map<Object, WeakReference<Resources>> map = Reflector.with(resManager).field("mActiveResources").get();
Object key = map.keySet().iterator().next();
map.put(key, new WeakReference<>(resources));
} catch (Exception e) {
Log.w(TAG, e);
}
}
/**
* Use System Apis to update all existing resources.
* <br/>
* 1. Update ApplicationInfo.splitSourceDirs and LoadedApk.mSplitResDirs
* <br/>
* 2. Replace all keys of ResourcesManager.mResourceImpls to new ResourcesKey
* <br/>
* 3. Use ResourcesManager.appendLibAssetForMainAssetPath(appInfo.publicSourceDir, "${packageName}.vastub") to update all existing resources.
* <br/>
*
* see android.webkit.WebViewDelegate.addWebViewAssetPath(Context)
*/
@TargetApi(Build.VERSION_CODES.N)
private static Resources createResourcesForN(Context context, String packageName, File apk) throws Exception {
long startTime = System.currentTimeMillis();
String newAssetPath = apk.getAbsolutePath();
ApplicationInfo info = context.getApplicationInfo();
String baseResDir = info.publicSourceDir;
info.splitSourceDirs = append(info.splitSourceDirs, newAssetPath);
LoadedApk loadedApk = Reflector.with(context).field("mPackageInfo").get();
Reflector rLoadedApk = Reflector.with(loadedApk).field("mSplitResDirs");
String[] splitResDirs = rLoadedApk.get();
rLoadedApk.set(append(splitResDirs, newAssetPath));
final android.app.ResourcesManager resourcesManager = android.app.ResourcesManager.getInstance();
ArrayMap<ResourcesKey, WeakReference<ResourcesImpl>> originalMap = Reflector.with(resourcesManager).field("mResourceImpls").get();
synchronized (resourcesManager) {
HashMap<ResourcesKey, WeakReference<ResourcesImpl>> resolvedMap = new HashMap<>();
if (Build.VERSION.SDK_INT >= 28
|| (Build.VERSION.SDK_INT == 27 && Build.VERSION.PREVIEW_SDK_INT != 0)) { // P Preview
ResourcesManagerCompatForP.resolveResourcesImplMap(originalMap, resolvedMap, context, loadedApk);
} else {
ResourcesManagerCompatForN.resolveResourcesImplMap(originalMap, resolvedMap, baseResDir, newAssetPath);
}
originalMap.clear();
originalMap.putAll(resolvedMap);
}
android.app.ResourcesManager.getInstance().appendLibAssetForMainAssetPath(baseResDir, packageName + ".vastub");
Resources newResources = context.getResources();
// lastly, sync all LoadedPlugin to newResources
for (LoadedPlugin plugin : PluginManager.getInstance(context).getAllLoadedPlugins()) {
plugin.updateResources(newResources);
}
Log.d(TAG, "createResourcesForN cost time: +" + (System.currentTimeMillis() - startTime) + "ms");
return newResources;
}
private static String[] append(String[] paths, String newPath) {
if (contains(paths, newPath)) {
return paths;
}
final int newPathsCount = 1 + (paths != null ? paths.length : 0);
final String[] newPaths = new String[newPathsCount];
if (paths != null) {
System.arraycopy(paths, 0, newPaths, 0, paths.length);
}
newPaths[newPathsCount - 1] = newPath;
return newPaths;
}
@TargetApi(Build.VERSION_CODES.KITKAT)
private static boolean contains(String[] array, String value) {
if (array == null) {
return false;
}
for (int i = 0; i < array.length; i++) {
if (Objects.equals(array[i], value)) {
return true;
}
}
return false;
}
private static boolean isMiUi(Resources resources) {
return resources.getClass().getName().equals("android.content.res.MiuiResources");
}
private static boolean isVivo(Resources resources) {
return resources.getClass().getName().equals("android.content.res.VivoResources");
}
private static boolean isNubia(Resources resources) {
return resources.getClass().getName().equals("android.content.res.NubiaResources");
}
private static boolean isNotRawResources(Resources resources) {
return !resources.getClass().getName().equals("android.content.res.Resources");
}
private static final class MiUiResourcesCompat {
private static Resources createResources(Resources hostResources, AssetManager assetManager) throws Exception {
Reflector reflector = Reflector.on("android.content.res.MiuiResources");
Resources newResources = reflector.constructor(AssetManager.class, DisplayMetrics.class, Configuration.class)
.newInstance(assetManager, hostResources.getDisplayMetrics(), hostResources.getConfiguration());
return newResources;
}
}
private static final class VivoResourcesCompat {
private static Resources createResources(Context hostContext, Resources hostResources, AssetManager assetManager) throws Exception {
Reflector reflector = Reflector.on("android.content.res.VivoResources");
Resources newResources = reflector.constructor(AssetManager.class, DisplayMetrics.class, Configuration.class)
.newInstance(assetManager, hostResources.getDisplayMetrics(), hostResources.getConfiguration());
reflector.method("init", String.class).callByCaller(newResources, hostContext.getPackageName());
reflector.field("mThemeValues");
reflector.set(newResources, reflector.get(hostResources));
return newResources;
}
}
private static final class NubiaResourcesCompat {
private static Resources createResources(Resources hostResources, AssetManager assetManager) throws Exception {
Reflector reflector = Reflector.on("android.content.res.NubiaResources");
Resources newResources = reflector.constructor(AssetManager.class, DisplayMetrics.class, Configuration.class)
.newInstance(assetManager, hostResources.getDisplayMetrics(), hostResources.getConfiguration());
return newResources;
}
}
private static final class AdaptationResourcesCompat {
private static Resources createResources(Resources hostResources, AssetManager assetManager) throws Exception {
Resources newResources;
try {
Reflector reflector = Reflector.with(hostResources);
newResources = reflector.constructor(AssetManager.class, DisplayMetrics.class, Configuration.class)
.newInstance(assetManager, hostResources.getDisplayMetrics(), hostResources.getConfiguration());
} catch (Exception e) {
newResources = new Resources(assetManager, hostResources.getDisplayMetrics(), hostResources.getConfiguration());
}
return newResources;
}
}
private static final class ResourcesManagerCompatForN {
@TargetApi(Build.VERSION_CODES.KITKAT)
public static void resolveResourcesImplMap(Map<ResourcesKey, WeakReference<ResourcesImpl>> originalMap, Map<ResourcesKey, WeakReference<ResourcesImpl>> resolvedMap, String baseResDir, String newAssetPath) throws Exception {
for (Map.Entry<ResourcesKey, WeakReference<ResourcesImpl>> entry : originalMap.entrySet()) {
ResourcesKey key = entry.getKey();
if (Objects.equals(key.mResDir, baseResDir)) {
resolvedMap.put(new ResourcesKey(key.mResDir,
append(key.mSplitResDirs, newAssetPath),
key.mOverlayDirs,
key.mLibDirs,
key.mDisplayId,
key.mOverrideConfiguration,
key.mCompatInfo), entry.getValue());
} else {
resolvedMap.put(key, entry.getValue());
}
}
}
}
private static final class ResourcesManagerCompatForP {
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
public static void resolveResourcesImplMap(Map<ResourcesKey, WeakReference<ResourcesImpl>> originalMap, Map<ResourcesKey, WeakReference<ResourcesImpl>> resolvedMap, Context context, LoadedApk loadedApk) throws Exception {
HashMap<ResourcesImpl, Context> newResImplMap = new HashMap<>();
Map<ResourcesImpl, ResourcesKey> resKeyMap = new HashMap<>();
Resources newRes;
// Recreate the resImpl of the context
// See LoadedApk.getResources()
if (mDefaultConfiguration == null) {
mDefaultConfiguration = new Configuration();
}
newRes = context.createConfigurationContext(mDefaultConfiguration).getResources();
newResImplMap.put(newRes.getImpl(), context);
// Recreate the ResImpl of the activity
for (WeakReference<Activity> ref : PluginManager.getInstance(context).getInstrumentation().getActivities()) {
Activity activity = ref.get();
if (activity != null) {
newRes = activity.createConfigurationContext(activity.getResources().getConfiguration()).getResources();
newResImplMap.put(newRes.getImpl(), activity);
}
}
// Mapping all resKey and resImpl
for (Map.Entry<ResourcesKey, WeakReference<ResourcesImpl>> entry : originalMap.entrySet()) {
ResourcesImpl resImpl = entry.getValue().get();
if (resImpl != null) {
resKeyMap.put(resImpl, entry.getKey());
}
resolvedMap.put(entry.getKey(), entry.getValue());
}
// Replace the resImpl to the new resKey and remove the origin resKey
for (Map.Entry<ResourcesImpl, Context> entry : newResImplMap.entrySet()) {
ResourcesKey newKey = resKeyMap.get(entry.getKey());
ResourcesImpl originResImpl = entry.getValue().getResources().getImpl();
resolvedMap.put(newKey, new WeakReference<>(originResImpl));
resolvedMap.remove(resKeyMap.get(originResImpl));
}
}
}
}
| |
/**
* 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.hadoop.hdfs.server.datanode;
import java.io.File;
import java.io.DataInputStream;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.EOFException;
import java.io.RandomAccessFile;
import java.io.ByteArrayInputStream;
import java.io.DataOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.classification.InterfaceStability;
import org.apache.hadoop.hdfs.DFSUtil;
import org.apache.hadoop.hdfs.HdfsConfiguration;
import org.apache.hadoop.io.AltFileInputStream;
import org.apache.hadoop.io.IOUtils;
import org.apache.hadoop.util.DataChecksum;
import com.google.common.annotations.VisibleForTesting;
/**
* BlockMetadataHeader manages metadata for data blocks on Datanodes.
* This is not related to the Block related functionality in Namenode.
* The biggest part of data block metadata is CRC for the block.
*/
@InterfaceAudience.Private
@InterfaceStability.Evolving
public class BlockMetadataHeader {
private static final Log LOG = LogFactory.getLog(BlockMetadataHeader.class);
public static final short VERSION = 1;
/**
* Header includes everything except the checksum(s) themselves.
* Version is two bytes. Following it is the DataChecksum
* that occupies 5 bytes.
*/
private final short version;
private DataChecksum checksum = null;
private static final HdfsConfiguration conf = new HdfsConfiguration();
@VisibleForTesting
public BlockMetadataHeader(short version, DataChecksum checksum) {
this.checksum = checksum;
this.version = version;
}
/** Get the version */
public short getVersion() {
return version;
}
/** Get the checksum */
public DataChecksum getChecksum() {
return checksum;
}
/**
* Read the checksum header from the meta file.
* @return the data checksum obtained from the header.
*/
public static DataChecksum readDataChecksum(File metaFile) throws IOException {
DataInputStream in = null;
try {
in = new DataInputStream(new BufferedInputStream(
new AltFileInputStream(metaFile), DFSUtil.getIoFileBufferSize(conf)));
return readDataChecksum(in, metaFile);
} finally {
IOUtils.closeStream(in);
}
}
/**
* Read the checksum header from the meta input stream.
* @return the data checksum obtained from the header.
*/
public static DataChecksum readDataChecksum(final DataInputStream metaIn,
final Object name) throws IOException {
// read and handle the common header here. For now just a version
final BlockMetadataHeader header = readHeader(metaIn);
if (header.getVersion() != VERSION) {
LOG.warn("Unexpected meta-file version for " + name
+ ": version in file is " + header.getVersion()
+ " but expected version is " + VERSION);
}
return header.getChecksum();
}
/**
* Read the header without changing the position of the FileChannel.
*
* @param fc The FileChannel to read.
* @return the Metadata Header.
* @throws IOException on error.
*/
public static BlockMetadataHeader preadHeader(FileChannel fc)
throws IOException {
final byte arr[] = new byte[getHeaderSize()];
ByteBuffer buf = ByteBuffer.wrap(arr);
while (buf.hasRemaining()) {
if (fc.read(buf, 0) <= 0) {
throw new EOFException("unexpected EOF while reading " +
"metadata file header");
}
}
short version = (short)((arr[0] << 8) | (arr[1] & 0xff));
DataChecksum dataChecksum = DataChecksum.newDataChecksum(arr, 2);
return new BlockMetadataHeader(version, dataChecksum);
}
/**
* This reads all the fields till the beginning of checksum.
* @return Metadata Header
* @throws IOException
*/
public static BlockMetadataHeader readHeader(DataInputStream in) throws IOException {
return readHeader(in.readShort(), in);
}
/**
* Reads header at the top of metadata file and returns the header.
*
* @return metadata header for the block
* @throws IOException
*/
public static BlockMetadataHeader readHeader(File file) throws IOException {
DataInputStream in = null;
try {
in = new DataInputStream(new BufferedInputStream(
new AltFileInputStream(file)));
return readHeader(in);
} finally {
IOUtils.closeStream(in);
}
}
/**
* Read the header at the beginning of the given block meta file.
* The current file position will be altered by this method.
* If an error occurs, the file is <em>not</em> closed.
*/
public static BlockMetadataHeader readHeader(RandomAccessFile raf) throws IOException {
byte[] buf = new byte[getHeaderSize()];
raf.seek(0);
raf.readFully(buf, 0, buf.length);
return readHeader(new DataInputStream(new ByteArrayInputStream(buf)));
}
// Version is already read.
private static BlockMetadataHeader readHeader(short version, DataInputStream in)
throws IOException {
DataChecksum checksum = DataChecksum.newDataChecksum(in);
return new BlockMetadataHeader(version, checksum);
}
/**
* This writes all the fields till the beginning of checksum.
* @param out DataOutputStream
* @throws IOException
*/
@VisibleForTesting
public static void writeHeader(DataOutputStream out,
BlockMetadataHeader header)
throws IOException {
out.writeShort(header.getVersion());
header.getChecksum().writeHeader(out);
}
/**
* Writes all the fields till the beginning of checksum.
* @throws IOException on error
*/
public static void writeHeader(DataOutputStream out, DataChecksum checksum)
throws IOException {
writeHeader(out, new BlockMetadataHeader(VERSION, checksum));
}
/**
* Returns the size of the header
*/
public static int getHeaderSize() {
return Short.SIZE/Byte.SIZE + DataChecksum.getChecksumHeaderSize();
}
}
| |
/**
* Copyright (c) 2012, Ben Fortuna
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* o Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* o 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.
*
* o Neither the name of Ben Fortuna nor the names of any other 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 net.fortuna.ical4j.model;
import java.io.IOException;
import java.net.URISyntaxException;
import java.text.ParseException;
import net.fortuna.ical4j.model.property.Action;
import net.fortuna.ical4j.model.property.Attach;
import net.fortuna.ical4j.model.property.Attendee;
import net.fortuna.ical4j.model.property.CalScale;
import net.fortuna.ical4j.model.property.Categories;
import net.fortuna.ical4j.model.property.Clazz;
import net.fortuna.ical4j.model.property.Comment;
import net.fortuna.ical4j.model.property.Completed;
import net.fortuna.ical4j.model.property.Contact;
import net.fortuna.ical4j.model.property.Country;
import net.fortuna.ical4j.model.property.Created;
import net.fortuna.ical4j.model.property.Description;
import net.fortuna.ical4j.model.property.DtEnd;
import net.fortuna.ical4j.model.property.DtStamp;
import net.fortuna.ical4j.model.property.DtStart;
import net.fortuna.ical4j.model.property.Due;
import net.fortuna.ical4j.model.property.Duration;
import net.fortuna.ical4j.model.property.ExDate;
import net.fortuna.ical4j.model.property.ExRule;
import net.fortuna.ical4j.model.property.ExtendedAddress;
import net.fortuna.ical4j.model.property.FreeBusy;
import net.fortuna.ical4j.model.property.Geo;
import net.fortuna.ical4j.model.property.LastModified;
import net.fortuna.ical4j.model.property.Locality;
import net.fortuna.ical4j.model.property.Location;
import net.fortuna.ical4j.model.property.LocationType;
import net.fortuna.ical4j.model.property.Method;
import net.fortuna.ical4j.model.property.Name;
import net.fortuna.ical4j.model.property.Organizer;
import net.fortuna.ical4j.model.property.PercentComplete;
import net.fortuna.ical4j.model.property.Postalcode;
import net.fortuna.ical4j.model.property.Priority;
import net.fortuna.ical4j.model.property.ProdId;
import net.fortuna.ical4j.model.property.RDate;
import net.fortuna.ical4j.model.property.RRule;
import net.fortuna.ical4j.model.property.RecurrenceId;
import net.fortuna.ical4j.model.property.Region;
import net.fortuna.ical4j.model.property.RelatedTo;
import net.fortuna.ical4j.model.property.Repeat;
import net.fortuna.ical4j.model.property.RequestStatus;
import net.fortuna.ical4j.model.property.Resources;
import net.fortuna.ical4j.model.property.Sequence;
import net.fortuna.ical4j.model.property.Status;
import net.fortuna.ical4j.model.property.StreetAddress;
import net.fortuna.ical4j.model.property.Summary;
import net.fortuna.ical4j.model.property.Tel;
import net.fortuna.ical4j.model.property.Transp;
import net.fortuna.ical4j.model.property.Trigger;
import net.fortuna.ical4j.model.property.TzId;
import net.fortuna.ical4j.model.property.TzName;
import net.fortuna.ical4j.model.property.TzOffsetFrom;
import net.fortuna.ical4j.model.property.TzOffsetTo;
import net.fortuna.ical4j.model.property.TzUrl;
import net.fortuna.ical4j.model.property.Uid;
import net.fortuna.ical4j.model.property.Url;
import net.fortuna.ical4j.model.property.Version;
import net.fortuna.ical4j.model.property.XProperty;
/**
* A factory for creating iCalendar properties. Note that if relaxed parsing is enabled (via specifying the system
* property: icalj.parsing.relaxed=true) illegal property names are allowed.
*
* @author Ben Fortuna
*
* $Id$ [05-Apr-2004]
*/
public class PropertyFactoryImpl extends AbstractContentFactory implements PropertyFactory {
private static final long serialVersionUID = -7174232004486979641L;
private static PropertyFactoryImpl instance = new PropertyFactoryImpl();
/**
* Constructor made private to prevent instantiation.
*/
protected PropertyFactoryImpl() {
registerDefaultFactory(Property.ACTION, new ActionFactory());
registerDefaultFactory(Property.ATTACH, new AttachFactory());
registerDefaultFactory(Property.ATTENDEE, new AttendeeFactory());
registerDefaultFactory(Property.CALSCALE, new CalScaleFactory());
registerDefaultFactory(Property.CATEGORIES, new CategoriesFactory());
registerDefaultFactory(Property.CLASS, new ClazzFactory());
registerDefaultFactory(Property.COMMENT, new CommentFactory());
registerDefaultFactory(Property.COMPLETED, new CompletedFactory());
registerDefaultFactory(Property.CONTACT, new ContactFactory());
registerDefaultFactory(Property.COUNTRY, new CountryFactory());
registerDefaultFactory(Property.CREATED, new CreatedFactory());
registerDefaultFactory(Property.DESCRIPTION, new DescriptionFactory());
registerDefaultFactory(Property.DTEND, new DtEndFactory());
registerDefaultFactory(Property.DTSTAMP, new DtStampFactory());
registerDefaultFactory(Property.DTSTART, new DtStartFactory());
registerDefaultFactory(Property.DUE, new DueFactory());
registerDefaultFactory(Property.DURATION, new DurationFactory());
registerDefaultFactory(Property.EXDATE, new ExDateFactory());
registerDefaultFactory(Property.EXRULE, new ExRuleFactory());
registerDefaultFactory(Property.EXTENDED_ADDRESS, new ExtendedAddressFactory());
registerDefaultFactory(Property.FREEBUSY, new FreeBusyFactory());
registerDefaultFactory(Property.GEO, new GeoFactory());
registerDefaultFactory(Property.LAST_MODIFIED, new LastModifiedFactory());
registerDefaultFactory(Property.LOCALITY, new LocalityFactory());
registerDefaultFactory(Property.LOCATION, new LocationFactory());
registerDefaultFactory(Property.LOCATION_TYPE, new LocationTypeFactory());
registerDefaultFactory(Property.METHOD, new MethodFactory());
registerDefaultFactory(Property.NAME, new NameFactory());
registerDefaultFactory(Property.ORGANIZER, new OrganizerFactory());
registerDefaultFactory(Property.PERCENT_COMPLETE, new PercentCompleteFactory());
registerDefaultFactory(Property.POSTALCODE, new PostalcodeFactory());
registerDefaultFactory(Property.PRIORITY, new PriorityFactory());
registerDefaultFactory(Property.PRODID, new ProdIdFactory());
registerDefaultFactory(Property.RDATE, new RDateFactory());
registerDefaultFactory(Property.RECURRENCE_ID, new RecurrenceIdFactory());
registerDefaultFactory(Property.REGION, new RegionFactory());
registerDefaultFactory(Property.RELATED_TO, new RelatedToFactory());
registerDefaultFactory(Property.REPEAT, new RepeatFactory());
registerDefaultFactory(Property.REQUEST_STATUS, new RequestStatusFactory());
registerDefaultFactory(Property.RESOURCES, new ResourcesFactory());
registerDefaultFactory(Property.RRULE, new RRuleFactory());
registerDefaultFactory(Property.SEQUENCE, new SequenceFactory());
registerDefaultFactory(Property.STATUS, new StatusFactory());
registerDefaultFactory(Property.STREET_ADDRESS, new StreetAddressFactory());
registerDefaultFactory(Property.SUMMARY, new SummaryFactory());
registerDefaultFactory(Property.TEL, new TelFactory());
registerDefaultFactory(Property.TRANSP, new TranspFactory());
registerDefaultFactory(Property.TRIGGER, new TriggerFactory());
registerDefaultFactory(Property.TZID, new TzIdFactory());
registerDefaultFactory(Property.TZNAME, new TzNameFactory());
registerDefaultFactory(Property.TZOFFSETFROM, new TzOffsetFromFactory());
registerDefaultFactory(Property.TZOFFSETTO, new TzOffsetToFactory());
registerDefaultFactory(Property.TZURL, new TzUrlFactory());
registerDefaultFactory(Property.UID, new UidFactory());
registerDefaultFactory(Property.URL, new UrlFactory());
registerDefaultFactory(Property.VERSION, new VersionFactory());
}
private static class ActionFactory implements PropertyFactory {
private static final long serialVersionUID = 1L;
public Property createProperty(final String name,
final ParameterList parameters, final String value)
throws IOException, URISyntaxException, ParseException {
return new Action(parameters, value);
}
public Property createProperty(final String name) {
return new Action();
}
}
private static class AttachFactory implements PropertyFactory {
private static final long serialVersionUID = 1L;
public Property createProperty(final String name,
final ParameterList parameters, final String value)
throws IOException, URISyntaxException, ParseException {
return new Attach(parameters, value);
}
public Property createProperty(final String name) {
return new Attach();
}
}
private static class AttendeeFactory implements PropertyFactory {
private static final long serialVersionUID = 1L;
public Property createProperty(final String name,
final ParameterList parameters, final String value)
throws IOException, URISyntaxException, ParseException {
return new Attendee(parameters, value);
}
public Property createProperty(final String name) {
return new Attendee();
}
}
private static class CalScaleFactory implements PropertyFactory {
private static final long serialVersionUID = 1L;
public Property createProperty(final String name,
final ParameterList parameters, final String value)
throws IOException, URISyntaxException, ParseException {
return new CalScale(parameters, value);
}
public Property createProperty(final String name) {
return new CalScale();
}
}
private static class CategoriesFactory implements PropertyFactory {
private static final long serialVersionUID = 1L;
public Property createProperty(final String name,
final ParameterList parameters, final String value)
throws IOException, URISyntaxException, ParseException {
return new Categories(parameters, value);
}
public Property createProperty(final String name) {
return new Categories();
}
}
private static class ClazzFactory implements PropertyFactory {
private static final long serialVersionUID = 1L;
public Property createProperty(final String name,
final ParameterList parameters, final String value)
throws IOException, URISyntaxException, ParseException {
return new Clazz(parameters, value);
}
public Property createProperty(final String name) {
return new Clazz();
}
}
private static class CommentFactory implements PropertyFactory {
private static final long serialVersionUID = 1L;
public Property createProperty(final String name,
final ParameterList parameters, final String value)
throws IOException, URISyntaxException, ParseException {
return new Comment(parameters, value);
}
public Property createProperty(final String name) {
return new Comment();
}
}
private static class CompletedFactory implements PropertyFactory {
private static final long serialVersionUID = 1L;
public Property createProperty(final String name,
final ParameterList parameters, final String value)
throws IOException, URISyntaxException, ParseException {
return new Completed(parameters, value);
}
public Property createProperty(final String name) {
return new Completed();
}
}
private static class ContactFactory implements PropertyFactory {
private static final long serialVersionUID = 1L;
public Property createProperty(final String name,
final ParameterList parameters, final String value)
throws IOException, URISyntaxException, ParseException {
return new Contact(parameters, value);
}
public Property createProperty(final String name) {
return new Contact();
}
}
private static class CountryFactory implements PropertyFactory {
private static final long serialVersionUID = 1L;
public Property createProperty(final String name,
final ParameterList parameters, final String value)
throws IOException, URISyntaxException, ParseException {
return new Country(parameters, value);
}
public Property createProperty(final String name) {
return new Country();
}
}
private static class CreatedFactory implements PropertyFactory {
private static final long serialVersionUID = 1L;
public Property createProperty(final String name,
final ParameterList parameters, final String value)
throws IOException, URISyntaxException, ParseException {
return new Created(parameters, value);
}
public Property createProperty(final String name) {
return new Created();
}
}
private static class DescriptionFactory implements PropertyFactory {
private static final long serialVersionUID = 1L;
public Property createProperty(final String name,
final ParameterList parameters, final String value)
throws IOException, URISyntaxException, ParseException {
return new Description(parameters, value);
}
public Property createProperty(final String name) {
return new Description();
}
}
private static class DtEndFactory implements PropertyFactory {
private static final long serialVersionUID = 1L;
public Property createProperty(final String name,
final ParameterList parameters, final String value)
throws IOException, URISyntaxException, ParseException {
return new DtEnd(parameters, value);
}
public Property createProperty(final String name) {
return new DtEnd();
}
}
private static class DtStampFactory implements PropertyFactory {
private static final long serialVersionUID = 1L;
public Property createProperty(final String name,
final ParameterList parameters, final String value)
throws IOException, URISyntaxException, ParseException {
return new DtStamp(parameters, value);
}
public Property createProperty(final String name) {
return new DtStamp();
}
}
private static class DtStartFactory implements PropertyFactory {
private static final long serialVersionUID = 1L;
public Property createProperty(final String name,
final ParameterList parameters, final String value)
throws IOException, URISyntaxException, ParseException {
return new DtStart(parameters, value);
}
public Property createProperty(final String name) {
return new DtStart();
}
}
private static class DueFactory implements PropertyFactory {
private static final long serialVersionUID = 1L;
public Property createProperty(final String name,
final ParameterList parameters, final String value)
throws IOException, URISyntaxException, ParseException {
return new Due(parameters, value);
}
public Property createProperty(final String name) {
return new Due();
}
}
private static class DurationFactory implements PropertyFactory {
private static final long serialVersionUID = 1L;
public Property createProperty(final String name,
final ParameterList parameters, final String value)
throws IOException, URISyntaxException, ParseException {
return new Duration(parameters, value);
}
public Property createProperty(final String name) {
return new Duration();
}
}
private static class ExDateFactory implements PropertyFactory {
private static final long serialVersionUID = 1L;
public Property createProperty(final String name,
final ParameterList parameters, final String value)
throws IOException, URISyntaxException, ParseException {
return new ExDate(parameters, value);
}
public Property createProperty(final String name) {
return new ExDate();
}
}
private static class ExRuleFactory implements PropertyFactory {
private static final long serialVersionUID = 1L;
public Property createProperty(final String name,
final ParameterList parameters, final String value)
throws IOException, URISyntaxException, ParseException {
return new ExRule(parameters, value);
}
public Property createProperty(final String name) {
return new ExRule();
}
}
private static class ExtendedAddressFactory implements PropertyFactory {
private static final long serialVersionUID = 1L;
public Property createProperty(final String name,
final ParameterList parameters, final String value)
throws IOException, URISyntaxException, ParseException {
return new ExtendedAddress(parameters, value);
}
public Property createProperty(final String name) {
return new ExtendedAddress();
}
}
private static class FreeBusyFactory implements PropertyFactory {
private static final long serialVersionUID = 1L;
public Property createProperty(final String name,
final ParameterList parameters, final String value)
throws IOException, URISyntaxException, ParseException {
return new FreeBusy(parameters, value);
}
public Property createProperty(final String name) {
return new FreeBusy();
}
}
private static class GeoFactory implements PropertyFactory {
private static final long serialVersionUID = 1L;
public Property createProperty(final String name,
final ParameterList parameters, final String value)
throws IOException, URISyntaxException, ParseException {
return new Geo(parameters, value);
}
public Property createProperty(final String name) {
return new Geo();
}
}
private static class LastModifiedFactory implements PropertyFactory {
private static final long serialVersionUID = 1L;
public Property createProperty(final String name,
final ParameterList parameters, final String value)
throws IOException, URISyntaxException, ParseException {
return new LastModified(parameters, value);
}
public Property createProperty(final String name) {
return new LastModified();
}
}
private static class LocalityFactory implements PropertyFactory {
private static final long serialVersionUID = 1L;
public Property createProperty(final String name,
final ParameterList parameters, final String value)
throws IOException, URISyntaxException, ParseException {
return new Locality(parameters, value);
}
public Property createProperty(final String name) {
return new Locality();
}
}
private static class LocationFactory implements PropertyFactory {
private static final long serialVersionUID = 1L;
public Property createProperty(final String name,
final ParameterList parameters, final String value)
throws IOException, URISyntaxException, ParseException {
return new Location(parameters, value);
}
public Property createProperty(final String name) {
return new Location();
}
}
private static class LocationTypeFactory implements PropertyFactory {
private static final long serialVersionUID = 1L;
public Property createProperty(final String name,
final ParameterList parameters, final String value)
throws IOException, URISyntaxException, ParseException {
return new LocationType(parameters, value);
}
public Property createProperty(final String name) {
return new LocationType();
}
}
private static class MethodFactory implements PropertyFactory {
private static final long serialVersionUID = 1L;
public Property createProperty(final String name,
final ParameterList parameters, final String value)
throws IOException, URISyntaxException, ParseException {
return new Method(parameters, value);
}
public Property createProperty(final String name) {
return new Method();
}
}
private static class NameFactory implements PropertyFactory {
private static final long serialVersionUID = 1L;
public Property createProperty(final String name,
final ParameterList parameters, final String value)
throws IOException, URISyntaxException, ParseException {
return new Name(parameters, value);
}
public Property createProperty(final String name) {
return new Name();
}
}
private static class OrganizerFactory implements PropertyFactory {
private static final long serialVersionUID = 1L;
public Property createProperty(final String name,
final ParameterList parameters, final String value)
throws IOException, URISyntaxException, ParseException {
return new Organizer(parameters, value);
}
public Property createProperty(final String name) {
return new Organizer();
}
}
private static class PercentCompleteFactory implements PropertyFactory {
private static final long serialVersionUID = 1L;
public Property createProperty(final String name,
final ParameterList parameters, final String value)
throws IOException, URISyntaxException, ParseException {
return new PercentComplete(parameters, value);
}
public Property createProperty(final String name) {
return new PercentComplete();
}
}
private static class PostalcodeFactory implements PropertyFactory {
private static final long serialVersionUID = 1L;
public Property createProperty(final String name,
final ParameterList parameters, final String value)
throws IOException, URISyntaxException, ParseException {
return new Postalcode(parameters, value);
}
public Property createProperty(final String name) {
return new Postalcode();
}
}
private static class PriorityFactory implements PropertyFactory {
private static final long serialVersionUID = 1L;
public Property createProperty(final String name,
final ParameterList parameters, final String value)
throws IOException, URISyntaxException, ParseException {
return new Priority(parameters, value);
}
public Property createProperty(final String name) {
return new Priority();
}
}
private static class ProdIdFactory implements PropertyFactory {
private static final long serialVersionUID = 1L;
public Property createProperty(final String name,
final ParameterList parameters, final String value)
throws IOException, URISyntaxException, ParseException {
return new ProdId(parameters, value);
}
public Property createProperty(final String name) {
return new ProdId();
}
}
private static class RDateFactory implements PropertyFactory {
private static final long serialVersionUID = 1L;
public Property createProperty(final String name,
final ParameterList parameters, final String value)
throws IOException, URISyntaxException, ParseException {
return new RDate(parameters, value);
}
public Property createProperty(final String name) {
return new RDate();
}
}
private static class RecurrenceIdFactory implements PropertyFactory {
private static final long serialVersionUID = 1L;
public Property createProperty(final String name,
final ParameterList parameters, final String value)
throws IOException, URISyntaxException, ParseException {
return new RecurrenceId(parameters, value);
}
public Property createProperty(final String name) {
return new RecurrenceId();
}
}
private static class RegionFactory implements PropertyFactory {
private static final long serialVersionUID = 1L;
public Property createProperty(final String name,
final ParameterList parameters, final String value)
throws IOException, URISyntaxException, ParseException {
return new Region(parameters, value);
}
public Property createProperty(final String name) {
return new Region();
}
}
private static class RelatedToFactory implements PropertyFactory {
private static final long serialVersionUID = 1L;
public Property createProperty(final String name,
final ParameterList parameters, final String value)
throws IOException, URISyntaxException, ParseException {
return new RelatedTo(parameters, value);
}
public Property createProperty(final String name) {
return new RelatedTo();
}
}
private static class RepeatFactory implements PropertyFactory {
private static final long serialVersionUID = 1L;
public Property createProperty(final String name,
final ParameterList parameters, final String value)
throws IOException, URISyntaxException, ParseException {
return new Repeat(parameters, value);
}
public Property createProperty(final String name) {
return new Repeat();
}
}
private static class RequestStatusFactory implements PropertyFactory {
private static final long serialVersionUID = 1L;
public Property createProperty(final String name,
final ParameterList parameters, final String value)
throws IOException, URISyntaxException, ParseException {
return new RequestStatus(parameters, value);
}
public Property createProperty(final String name) {
return new RequestStatus();
}
}
private static class ResourcesFactory implements PropertyFactory {
private static final long serialVersionUID = 1L;
public Property createProperty(final String name,
final ParameterList parameters, final String value)
throws IOException, URISyntaxException, ParseException {
return new Resources(parameters, value);
}
public Property createProperty(final String name) {
return new Resources();
}
}
private static class RRuleFactory implements PropertyFactory {
private static final long serialVersionUID = 1L;
public Property createProperty(final String name,
final ParameterList parameters, final String value)
throws IOException, URISyntaxException, ParseException {
return new RRule(parameters, value);
}
public Property createProperty(final String name) {
return new RRule();
}
}
private static class SequenceFactory implements PropertyFactory {
private static final long serialVersionUID = 1L;
public Property createProperty(final String name,
final ParameterList parameters, final String value)
throws IOException, URISyntaxException, ParseException {
return new Sequence(parameters, value);
}
public Property createProperty(final String name) {
return new Sequence();
}
}
private static class StatusFactory implements PropertyFactory {
private static final long serialVersionUID = 1L;
public Property createProperty(final String name,
final ParameterList parameters, final String value)
throws IOException, URISyntaxException, ParseException {
return new Status(parameters, value);
}
public Property createProperty(final String name) {
return new Status();
}
}
private static class StreetAddressFactory implements PropertyFactory {
private static final long serialVersionUID = 1L;
public Property createProperty(final String name,
final ParameterList parameters, final String value)
throws IOException, URISyntaxException, ParseException {
return new StreetAddress(parameters, value);
}
public Property createProperty(final String name) {
return new StreetAddress();
}
}
private static class SummaryFactory implements PropertyFactory {
private static final long serialVersionUID = 1L;
public Property createProperty(final String name,
final ParameterList parameters, final String value)
throws IOException, URISyntaxException, ParseException {
return new Summary(parameters, value);
}
public Property createProperty(final String name) {
return new Summary();
}
}
private static class TelFactory implements PropertyFactory {
private static final long serialVersionUID = 1L;
public Property createProperty(final String name,
final ParameterList parameters, final String value)
throws IOException, URISyntaxException, ParseException {
return new Tel(parameters, value);
}
public Property createProperty(final String name) {
return new Tel();
}
}
private static class TranspFactory implements PropertyFactory {
private static final long serialVersionUID = 1L;
public Property createProperty(final String name,
final ParameterList parameters, final String value)
throws IOException, URISyntaxException, ParseException {
return new Transp(parameters, value);
}
public Property createProperty(final String name) {
return new Transp();
}
}
private static class TriggerFactory implements PropertyFactory {
private static final long serialVersionUID = 1L;
public Property createProperty(final String name,
final ParameterList parameters, final String value)
throws IOException, URISyntaxException, ParseException {
return new Trigger(parameters, value);
}
public Property createProperty(final String name) {
return new Trigger();
}
}
private static class TzIdFactory implements PropertyFactory {
private static final long serialVersionUID = 1L;
public Property createProperty(final String name,
final ParameterList parameters, final String value)
throws IOException, URISyntaxException, ParseException {
return new TzId(parameters, value);
}
public Property createProperty(final String name) {
return new TzId();
}
}
private static class TzNameFactory implements PropertyFactory {
private static final long serialVersionUID = 1L;
public Property createProperty(final String name,
final ParameterList parameters, final String value)
throws IOException, URISyntaxException, ParseException {
return new TzName(parameters, value);
}
public Property createProperty(final String name) {
return new TzName();
}
}
private static class TzOffsetFromFactory implements PropertyFactory {
private static final long serialVersionUID = 1L;
public Property createProperty(final String name,
final ParameterList parameters, final String value)
throws IOException, URISyntaxException, ParseException {
return new TzOffsetFrom(parameters, value);
}
public Property createProperty(final String name) {
return new TzOffsetFrom();
}
}
private static class TzOffsetToFactory implements PropertyFactory {
private static final long serialVersionUID = 1L;
public Property createProperty(final String name,
final ParameterList parameters, final String value)
throws IOException, URISyntaxException, ParseException {
return new TzOffsetTo(parameters, value);
}
public Property createProperty(final String name) {
return new TzOffsetTo();
}
}
private static class TzUrlFactory implements PropertyFactory {
private static final long serialVersionUID = 1L;
public Property createProperty(final String name,
final ParameterList parameters, final String value)
throws IOException, URISyntaxException, ParseException {
return new TzUrl(parameters, value);
}
public Property createProperty(final String name) {
return new TzUrl();
}
}
private static class UidFactory implements PropertyFactory {
private static final long serialVersionUID = 1L;
public Property createProperty(final String name,
final ParameterList parameters, final String value)
throws IOException, URISyntaxException, ParseException {
return new Uid(parameters, value);
}
public Property createProperty(final String name) {
return new Uid();
}
}
private static class UrlFactory implements PropertyFactory {
private static final long serialVersionUID = 1L;
public Property createProperty(final String name,
final ParameterList parameters, final String value)
throws IOException, URISyntaxException, ParseException {
return new Url(parameters, value);
}
public Property createProperty(final String name) {
return new Url();
}
}
private static class VersionFactory implements PropertyFactory {
private static final long serialVersionUID = 1L;
public Property createProperty(final String name,
final ParameterList parameters, final String value)
throws IOException, URISyntaxException, ParseException {
return new Version(parameters, value);
}
public Property createProperty(final String name) {
return new Version();
}
}
/**
* @return Returns the instance.
*/
public static PropertyFactoryImpl getInstance() {
return instance;
}
/**
* {@inheritDoc}
*/
public Property createProperty(final String name) {
final PropertyFactory factory = (PropertyFactory) getFactory(name);
if (factory != null) {
return factory.createProperty(name);
}
else if (isExperimentalName(name)) {
return new XProperty(name);
}
else if (allowIllegalNames()) {
return new XProperty(name);
}
else {
throw new IllegalArgumentException("Illegal property [" + name
+ "]");
}
}
/**
* {@inheritDoc}
*/
public Property createProperty(final String name,
final ParameterList parameters, final String value)
throws IOException, URISyntaxException, ParseException {
final PropertyFactory factory = (PropertyFactory) getFactory(name);
if (factory != null) {
return factory.createProperty(name, parameters, value);
}
else if (isExperimentalName(name)) {
return new XProperty(name, parameters, value);
}
else if (allowIllegalNames()) {
return new XProperty(name, parameters, value);
}
else {
throw new IllegalArgumentException("Illegal property [" + name
+ "]");
}
}
/**
* @param name
* @return
*/
private boolean isExperimentalName(final String name) {
return name.startsWith(Property.EXPERIMENTAL_PREFIX)
&& name.length() > Property.EXPERIMENTAL_PREFIX.length();
}
}
| |
package com.google.api.ads.adwords.jaxws.v201509.express;
import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for CurrencyCode.
*
* <p>The following schema fragment specifies the expected content contained within this class.
* <p>
* <pre>
* <simpleType name="CurrencyCode">
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <enumeration value="ADP"/>
* <enumeration value="AED"/>
* <enumeration value="AFA"/>
* <enumeration value="AFN"/>
* <enumeration value="ALK"/>
* <enumeration value="ALL"/>
* <enumeration value="AMD"/>
* <enumeration value="ANG"/>
* <enumeration value="AOA"/>
* <enumeration value="AOK"/>
* <enumeration value="AON"/>
* <enumeration value="AOR"/>
* <enumeration value="ARA"/>
* <enumeration value="ARL"/>
* <enumeration value="ARM"/>
* <enumeration value="ARP"/>
* <enumeration value="ARS"/>
* <enumeration value="ATS"/>
* <enumeration value="AUD"/>
* <enumeration value="AWG"/>
* <enumeration value="AZM"/>
* <enumeration value="AZN"/>
* <enumeration value="BAD"/>
* <enumeration value="BAM"/>
* <enumeration value="BAN"/>
* <enumeration value="BBD"/>
* <enumeration value="BDT"/>
* <enumeration value="BEF"/>
* <enumeration value="BGL"/>
* <enumeration value="BGM"/>
* <enumeration value="BGN"/>
* <enumeration value="BGO"/>
* <enumeration value="BHD"/>
* <enumeration value="BIF"/>
* <enumeration value="BMD"/>
* <enumeration value="BND"/>
* <enumeration value="BOB"/>
* <enumeration value="BOL"/>
* <enumeration value="BOP"/>
* <enumeration value="BRB"/>
* <enumeration value="BRC"/>
* <enumeration value="BRE"/>
* <enumeration value="BRL"/>
* <enumeration value="BRN"/>
* <enumeration value="BRR"/>
* <enumeration value="BRZ"/>
* <enumeration value="BSD"/>
* <enumeration value="BTN"/>
* <enumeration value="BUK"/>
* <enumeration value="BWP"/>
* <enumeration value="BYB"/>
* <enumeration value="BYR"/>
* <enumeration value="BZD"/>
* <enumeration value="CAD"/>
* <enumeration value="CDF"/>
* <enumeration value="CHF"/>
* <enumeration value="CLE"/>
* <enumeration value="CLF"/>
* <enumeration value="CLP"/>
* <enumeration value="CNY"/>
* <enumeration value="COP"/>
* <enumeration value="CRC"/>
* <enumeration value="CSD"/>
* <enumeration value="CSK"/>
* <enumeration value="CUC"/>
* <enumeration value="CUP"/>
* <enumeration value="CVE"/>
* <enumeration value="CYP"/>
* <enumeration value="CZK"/>
* <enumeration value="DDM"/>
* <enumeration value="DEM"/>
* <enumeration value="DJF"/>
* <enumeration value="DKK"/>
* <enumeration value="DOP"/>
* <enumeration value="DZD"/>
* <enumeration value="ECS"/>
* <enumeration value="EEK"/>
* <enumeration value="EGP"/>
* <enumeration value="ERN"/>
* <enumeration value="ESP"/>
* <enumeration value="ETB"/>
* <enumeration value="EUR"/>
* <enumeration value="FIM"/>
* <enumeration value="FJD"/>
* <enumeration value="FKP"/>
* <enumeration value="FRF"/>
* <enumeration value="GBP"/>
* <enumeration value="GEK"/>
* <enumeration value="GEL"/>
* <enumeration value="GHC"/>
* <enumeration value="GHP"/>
* <enumeration value="GHS"/>
* <enumeration value="GIP"/>
* <enumeration value="GMD"/>
* <enumeration value="GNF"/>
* <enumeration value="GNS"/>
* <enumeration value="GQE"/>
* <enumeration value="GRD"/>
* <enumeration value="GTQ"/>
* <enumeration value="GWE"/>
* <enumeration value="GWP"/>
* <enumeration value="GYD"/>
* <enumeration value="HKD"/>
* <enumeration value="HNL"/>
* <enumeration value="HRD"/>
* <enumeration value="HRK"/>
* <enumeration value="HTG"/>
* <enumeration value="HUF"/>
* <enumeration value="IDR"/>
* <enumeration value="IEP"/>
* <enumeration value="ILP"/>
* <enumeration value="ILR"/>
* <enumeration value="ILS"/>
* <enumeration value="INR"/>
* <enumeration value="IQD"/>
* <enumeration value="IRR"/>
* <enumeration value="ISJ"/>
* <enumeration value="ISK"/>
* <enumeration value="ITL"/>
* <enumeration value="JMD"/>
* <enumeration value="JOD"/>
* <enumeration value="JPY"/>
* <enumeration value="KES"/>
* <enumeration value="KGS"/>
* <enumeration value="KHR"/>
* <enumeration value="KMF"/>
* <enumeration value="KPW"/>
* <enumeration value="KRH"/>
* <enumeration value="KRO"/>
* <enumeration value="KRW"/>
* <enumeration value="KWD"/>
* <enumeration value="KYD"/>
* <enumeration value="KZT"/>
* <enumeration value="LAK"/>
* <enumeration value="LBP"/>
* <enumeration value="LKR"/>
* <enumeration value="LRD"/>
* <enumeration value="LSL"/>
* <enumeration value="LTL"/>
* <enumeration value="LTT"/>
* <enumeration value="LUF"/>
* <enumeration value="LVL"/>
* <enumeration value="LVR"/>
* <enumeration value="LYD"/>
* <enumeration value="MAD"/>
* <enumeration value="MAF"/>
* <enumeration value="MCF"/>
* <enumeration value="MDC"/>
* <enumeration value="MDL"/>
* <enumeration value="MGA"/>
* <enumeration value="MGF"/>
* <enumeration value="MKD"/>
* <enumeration value="MKN"/>
* <enumeration value="MLF"/>
* <enumeration value="MMK"/>
* <enumeration value="MNT"/>
* <enumeration value="MOP"/>
* <enumeration value="MRO"/>
* <enumeration value="MTL"/>
* <enumeration value="MTP"/>
* <enumeration value="MUR"/>
* <enumeration value="MVR"/>
* <enumeration value="MWK"/>
* <enumeration value="MXN"/>
* <enumeration value="MXP"/>
* <enumeration value="MYR"/>
* <enumeration value="MZE"/>
* <enumeration value="MZM"/>
* <enumeration value="MZN"/>
* <enumeration value="NAD"/>
* <enumeration value="NGN"/>
* <enumeration value="NIC"/>
* <enumeration value="NIO"/>
* <enumeration value="NLG"/>
* <enumeration value="NOK"/>
* <enumeration value="NPR"/>
* <enumeration value="NZD"/>
* <enumeration value="OMR"/>
* <enumeration value="PAB"/>
* <enumeration value="PEI"/>
* <enumeration value="PEN"/>
* <enumeration value="PES"/>
* <enumeration value="PGK"/>
* <enumeration value="PHP"/>
* <enumeration value="PKR"/>
* <enumeration value="PLN"/>
* <enumeration value="PLZ"/>
* <enumeration value="PTE"/>
* <enumeration value="PYG"/>
* <enumeration value="QAR"/>
* <enumeration value="RHD"/>
* <enumeration value="ROL"/>
* <enumeration value="RON"/>
* <enumeration value="RSD"/>
* <enumeration value="RUB"/>
* <enumeration value="RUR"/>
* <enumeration value="RWF"/>
* <enumeration value="SAR"/>
* <enumeration value="SBD"/>
* <enumeration value="SCR"/>
* <enumeration value="SDD"/>
* <enumeration value="SDG"/>
* <enumeration value="SDP"/>
* <enumeration value="SEK"/>
* <enumeration value="SGD"/>
* <enumeration value="SHP"/>
* <enumeration value="SIT"/>
* <enumeration value="SKK"/>
* <enumeration value="SLL"/>
* <enumeration value="SOS"/>
* <enumeration value="SRD"/>
* <enumeration value="SRG"/>
* <enumeration value="SSP"/>
* <enumeration value="STD"/>
* <enumeration value="SUR"/>
* <enumeration value="SVC"/>
* <enumeration value="SYP"/>
* <enumeration value="SZL"/>
* <enumeration value="THB"/>
* <enumeration value="TJR"/>
* <enumeration value="TJS"/>
* <enumeration value="TMM"/>
* <enumeration value="TMT"/>
* <enumeration value="TND"/>
* <enumeration value="TOP"/>
* <enumeration value="TPE"/>
* <enumeration value="TRL"/>
* <enumeration value="TRY"/>
* <enumeration value="TTD"/>
* <enumeration value="TWD"/>
* <enumeration value="TZS"/>
* <enumeration value="UAH"/>
* <enumeration value="UAK"/>
* <enumeration value="UGS"/>
* <enumeration value="UGX"/>
* <enumeration value="USD"/>
* <enumeration value="UYP"/>
* <enumeration value="UYU"/>
* <enumeration value="UZS"/>
* <enumeration value="VEB"/>
* <enumeration value="VEF"/>
* <enumeration value="VND"/>
* <enumeration value="VNN"/>
* <enumeration value="VUV"/>
* <enumeration value="WST"/>
* <enumeration value="XAF"/>
* <enumeration value="XCD"/>
* <enumeration value="XOF"/>
* <enumeration value="XPF"/>
* <enumeration value="XXX"/>
* <enumeration value="YDD"/>
* <enumeration value="YER"/>
* <enumeration value="YUD"/>
* <enumeration value="YUM"/>
* <enumeration value="YUN"/>
* <enumeration value="YUR"/>
* <enumeration value="ZAR"/>
* <enumeration value="ZMK"/>
* <enumeration value="ZMW"/>
* <enumeration value="ZRN"/>
* <enumeration value="ZRZ"/>
* <enumeration value="ZWD"/>
* <enumeration value="ZWL"/>
* <enumeration value="ZWR"/>
* </restriction>
* </simpleType>
* </pre>
*
*/
@XmlType(name = "CurrencyCode")
@XmlEnum
public enum CurrencyCode {
/**
*
* Andorran Peseta
*
*
*/
ADP,
/**
*
* United Arab Emirates Dirham
*
*
*/
AED,
/**
*
* Afghan Afghani (1927?2002)
*
*
*/
AFA,
/**
*
* Afghan Afghani
*
*
*/
AFN,
/**
*
* Albanian Lek (1946?1965)
*
*
*/
ALK,
/**
*
* Albanian Lek
*
*
*/
ALL,
/**
*
* Armenian Dram
*
*
*/
AMD,
/**
*
* Netherlands Antillean Guilder
*
*
*/
ANG,
/**
*
* Angolan Kwanza
*
*
*/
AOA,
/**
*
* Angolan Kwanza (1977?1991)
*
*
*/
AOK,
/**
*
* Angolan New Kwanza (1990?2000)
*
*
*/
AON,
/**
*
* Angolan Readjusted Kwanza (1995?1999)
*
*
*/
AOR,
/**
*
* Argentine Austral
*
*
*/
ARA,
/**
*
* Argentine Peso Ley (1970?1983)
*
*
*/
ARL,
/**
*
* Argentine Peso (1881?1970)
*
*
*/
ARM,
/**
*
* Argentine Peso (1983?1985)
*
*
*/
ARP,
/**
*
* Argentine Peso
*
*
*/
ARS,
/**
*
* Austrian Schilling
*
*
*/
ATS,
/**
*
* Australian Dollar
*
*
*/
AUD,
/**
*
* Aruban Florin
*
*
*/
AWG,
/**
*
* Azerbaijani Manat (1993?2006)
*
*
*/
AZM,
/**
*
* Azerbaijani Manat
*
*
*/
AZN,
/**
*
* Bosnia-Herzegovina Dinar (1992?1994)
*
*
*/
BAD,
/**
*
* Bosnia-Herzegovina Convertible Mark
*
*
*/
BAM,
/**
*
* Bosnia-Herzegovina New Dinar (1994?1997)
*
*
*/
BAN,
/**
*
* Barbadian Dollar
*
*
*/
BBD,
/**
*
* Bangladeshi Taka
*
*
*/
BDT,
/**
*
* Belgian Franc
*
*
*/
BEF,
/**
*
* Bulgarian Hard Lev
*
*
*/
BGL,
/**
*
* Bulgarian Socialist Lev
*
*
*/
BGM,
/**
*
* Bulgarian Lev
*
*
*/
BGN,
/**
*
* Bulgarian Lev (1879?1952)
*
*
*/
BGO,
/**
*
* Bahraini Dinar
*
*
*/
BHD,
/**
*
* Burundian Franc
*
*
*/
BIF,
/**
*
* Bermudan Dollar
*
*
*/
BMD,
/**
*
* Brunei Dollar
*
*
*/
BND,
/**
*
* Bolivian Boliviano
*
*
*/
BOB,
/**
*
* Bolivian Boliviano (1863?1963)
*
*
*/
BOL,
/**
*
* Bolivian Peso
*
*
*/
BOP,
/**
*
* Brazilian New Cruzeiro (1967?1986)
*
*
*/
BRB,
/**
*
* Brazilian Cruzado (1986?1989)
*
*
*/
BRC,
/**
*
* Brazilian Cruzeiro (1990?1993)
*
*
*/
BRE,
/**
*
* Brazilian Real
*
*
*/
BRL,
/**
*
* Brazilian New Cruzado (1989?1990)
*
*
*/
BRN,
/**
*
* Brazilian Cruzeiro (1993?1994)
*
*
*/
BRR,
/**
*
* Brazilian Cruzeiro (1942?1967)
*
*
*/
BRZ,
/**
*
* Bahamian Dollar
*
*
*/
BSD,
/**
*
* Bhutanese Ngultrum
*
*
*/
BTN,
/**
*
* Burmese Kyat
*
*
*/
BUK,
/**
*
* Botswanan Pula
*
*
*/
BWP,
/**
*
* Belarusian New Ruble (1994?1999)
*
*
*/
BYB,
/**
*
* Belarusian Ruble
*
*
*/
BYR,
/**
*
* Belize Dollar
*
*
*/
BZD,
/**
*
* Canadian Dollar
*
*
*/
CAD,
/**
*
* Congolese Franc
*
*
*/
CDF,
/**
*
* Swiss Franc
*
*
*/
CHF,
/**
*
* Chilean Escudo
*
*
*/
CLE,
/**
*
* Chilean Unit of Account - fund code (backward compatible)
*
*
*/
CLF,
/**
*
* Chilean Peso
*
*
*/
CLP,
/**
*
* Chinese Yuan
*
*
*/
CNY,
/**
*
* Colombian Peso
*
*
*/
COP,
/**
*
* Costa Rican Col?n
*
*
*/
CRC,
/**
*
* Serbian Dinar (2002?2006)
*
*
*/
CSD,
/**
*
* Czechoslovak Hard Koruna
*
*
*/
CSK,
/**
*
* Cuban Convertible Peso
*
*
*/
CUC,
/**
*
* Cuban Peso
*
*
*/
CUP,
/**
*
* Cape Verdean Escudo
*
*
*/
CVE,
/**
*
* Cypriot Pound
*
*
*/
CYP,
/**
*
* Czech Republic Koruna
*
*
*/
CZK,
/**
*
* East German Mark
*
*
*/
DDM,
/**
*
* German Mark
*
*
*/
DEM,
/**
*
* Djiboutian Franc
*
*
*/
DJF,
/**
*
* Danish Krone
*
*
*/
DKK,
/**
*
* Dominican Peso
*
*
*/
DOP,
/**
*
* Algerian Dinar
*
*
*/
DZD,
/**
*
* Ecuadorian Sucre
*
*
*/
ECS,
/**
*
* Estonian Kroon
*
*
*/
EEK,
/**
*
* Egyptian Pound
*
*
*/
EGP,
/**
*
* Eritrean Nakfa
*
*
*/
ERN,
/**
*
* Spanish Peseta
*
*
*/
ESP,
/**
*
* Ethiopian Birr
*
*
*/
ETB,
/**
*
* Euro
*
*
*/
EUR,
/**
*
* Finnish Markka
*
*
*/
FIM,
/**
*
* Fijian Dollar
*
*
*/
FJD,
/**
*
* Falkland Islands Pound
*
*
*/
FKP,
/**
*
* French Franc
*
*
*/
FRF,
/**
*
* British Pound
*
*
*/
GBP,
/**
*
* Georgian Kupon Larit
*
*
*/
GEK,
/**
*
* Georgian Lari
*
*
*/
GEL,
/**
*
* Ghanaian Cedi (1979?2007)
*
*
*/
GHC,
/**
*
* Ghana Cedi (2007 mistake) - grandfathered non-tender
*
*
*/
GHP,
/**
*
* Ghanaian Cedi
*
*
*/
GHS,
/**
*
* Gibraltar Pound
*
*
*/
GIP,
/**
*
* Gambian Dalasi
*
*
*/
GMD,
/**
*
* Guinean Franc
*
*
*/
GNF,
/**
*
* Guinean Syli
*
*
*/
GNS,
/**
*
* Equatorial Guinean Ekwele
*
*
*/
GQE,
/**
*
* Greek Drachma
*
*
*/
GRD,
/**
*
* Guatemalan Quetzal
*
*
*/
GTQ,
/**
*
* Portuguese Guinea Escudo
*
*
*/
GWE,
/**
*
* Guinea-Bissau Peso
*
*
*/
GWP,
/**
*
* Guyanaese Dollar
*
*
*/
GYD,
/**
*
* Hong Kong Dollar
*
*
*/
HKD,
/**
*
* Honduran Lempira
*
*
*/
HNL,
/**
*
* Croatian Dinar
*
*
*/
HRD,
/**
*
* Croatian Kuna
*
*
*/
HRK,
/**
*
* Haitian Gourde
*
*
*/
HTG,
/**
*
* Hungarian Forint
*
*
*/
HUF,
/**
*
* Indonesian Rupiah
*
*
*/
IDR,
/**
*
* Irish Pound
*
*
*/
IEP,
/**
*
* Israeli Pound
*
*
*/
ILP,
/**
*
* Israeli Sheqel (1980?1985)
*
*
*/
ILR,
/**
*
* Israeli New Sheqel
*
*
*/
ILS,
/**
*
* Indian Rupee
*
*
*/
INR,
/**
*
* Iraqi Dinar
*
*
*/
IQD,
/**
*
* Iranian Rial
*
*
*/
IRR,
/**
*
* Icelandic Kr?na (1918?1981)
*
*
*/
ISJ,
/**
*
* Icelandic Kr?na
*
*
*/
ISK,
/**
*
* Italian Lira
*
*
*/
ITL,
/**
*
* Jamaican Dollar
*
*
*/
JMD,
/**
*
* Jordanian Dinar
*
*
*/
JOD,
/**
*
* Japanese Yen
*
*
*/
JPY,
/**
*
* Kenyan Shilling
*
*
*/
KES,
/**
*
* Kyrgystani Som
*
*
*/
KGS,
/**
*
* Cambodian Riel
*
*
*/
KHR,
/**
*
* Comorian Franc
*
*
*/
KMF,
/**
*
* North Korean Won
*
*
*/
KPW,
/**
*
* South Korean Hwan (1953?1962)
*
*
*/
KRH,
/**
*
* South Korean Won (1945?1953)
*
*
*/
KRO,
/**
*
* South Korean Won
*
*
*/
KRW,
/**
*
* Kuwaiti Dinar
*
*
*/
KWD,
/**
*
* Cayman Islands Dollar
*
*
*/
KYD,
/**
*
* Kazakhstani Tenge
*
*
*/
KZT,
/**
*
* Laotian Kip
*
*
*/
LAK,
/**
*
* Lebanese Pound
*
*
*/
LBP,
/**
*
* Sri Lankan Rupee
*
*
*/
LKR,
/**
*
* Liberian Dollar
*
*
*/
LRD,
/**
*
* Lesotho Loti
*
*
*/
LSL,
/**
*
* Lithuanian Litas
*
*
*/
LTL,
/**
*
* Lithuanian Talonas
*
*
*/
LTT,
/**
*
* Luxembourgian Franc
*
*
*/
LUF,
/**
*
* Latvian Lats
*
*
*/
LVL,
/**
*
* Latvian Ruble
*
*
*/
LVR,
/**
*
* Libyan Dinar
*
*
*/
LYD,
/**
*
* Moroccan Dirham
*
*
*/
MAD,
/**
*
* Moroccan Franc
*
*
*/
MAF,
/**
*
* Monegasque Franc
*
*
*/
MCF,
/**
*
* Moldovan Cupon
*
*
*/
MDC,
/**
*
* Moldovan Leu
*
*
*/
MDL,
/**
*
* Malagasy Ariary
*
*
*/
MGA,
/**
*
* Malagasy Franc
*
*
*/
MGF,
/**
*
* Macedonian Denar
*
*
*/
MKD,
/**
*
* Macedonian Denar (1992?1993)
*
*
*/
MKN,
/**
*
* Malian Franc
*
*
*/
MLF,
/**
*
* Myanmar Kyat
*
*
*/
MMK,
/**
*
* Mongolian Tugrik
*
*
*/
MNT,
/**
*
* Macanese Pataca
*
*
*/
MOP,
/**
*
* Mauritanian Ouguiya
*
*
*/
MRO,
/**
*
* Maltese Lira
*
*
*/
MTL,
/**
*
* Maltese Pound
*
*
*/
MTP,
/**
*
* Mauritian Rupee
*
*
*/
MUR,
/**
*
* Maldivian Rufiyaa
*
*
*/
MVR,
/**
*
* Malawian Kwacha
*
*
*/
MWK,
/**
*
* Mexican Peso
*
*
*/
MXN,
/**
*
* Mexican Silver Peso (1861?1992)
*
*
*/
MXP,
/**
*
* Malaysian Ringgit
*
*
*/
MYR,
/**
*
* Mozambican Escudo
*
*
*/
MZE,
/**
*
* Mozambican Metical (1980?2006)
*
*
*/
MZM,
/**
*
* Mozambican Metical
*
*
*/
MZN,
/**
*
* Namibian Dollar
*
*
*/
NAD,
/**
*
* Nigerian Naira
*
*
*/
NGN,
/**
*
* Nicaraguan C?rdoba (1988?1991)
*
*
*/
NIC,
/**
*
* Nicaraguan C?rdoba
*
*
*/
NIO,
/**
*
* Dutch Guilder
*
*
*/
NLG,
/**
*
* Norwegian Krone
*
*
*/
NOK,
/**
*
* Nepalese Rupee
*
*
*/
NPR,
/**
*
* New Zealand Dollar
*
*
*/
NZD,
/**
*
* Omani Rial
*
*
*/
OMR,
/**
*
* Panamanian Balboa
*
*
*/
PAB,
/**
*
* Peruvian Inti
*
*
*/
PEI,
/**
*
* Peruvian Nuevo Sol
*
*
*/
PEN,
/**
*
* Peruvian Sol (1863?1965)
*
*
*/
PES,
/**
*
* Papua New Guinean Kina
*
*
*/
PGK,
/**
*
* Philippine Peso
*
*
*/
PHP,
/**
*
* Pakistani Rupee
*
*
*/
PKR,
/**
*
* Polish Zloty
*
*
*/
PLN,
/**
*
* Polish Zloty (1950?1995)
*
*
*/
PLZ,
/**
*
* Portuguese Escudo
*
*
*/
PTE,
/**
*
* Paraguayan Guarani
*
*
*/
PYG,
/**
*
* Qatari Rial
*
*
*/
QAR,
/**
*
* Rhodesian Dollar
*
*
*/
RHD,
/**
*
* Romanian Leu (1952?2006)
*
*
*/
ROL,
/**
*
* Romanian Leu
*
*
*/
RON,
/**
*
* Serbian Dinar
*
*
*/
RSD,
/**
*
* Russian Ruble
*
*
*/
RUB,
/**
*
* Russian Ruble (1991?1998)
*
*
*/
RUR,
/**
*
* Rwandan Franc
*
*
*/
RWF,
/**
*
* Saudi Riyal
*
*
*/
SAR,
/**
*
* Solomon Islands Dollar
*
*
*/
SBD,
/**
*
* Seychellois Rupee
*
*
*/
SCR,
/**
*
* Sudanese Dinar (1992?2007)
*
*
*/
SDD,
/**
*
* Sudanese Pound
*
*
*/
SDG,
/**
*
* Sudanese Pound (1957?1998)
*
*
*/
SDP,
/**
*
* Swedish Krona
*
*
*/
SEK,
/**
*
* Singapore Dollar
*
*
*/
SGD,
/**
*
* St. Helena Pound
*
*
*/
SHP,
/**
*
* Slovenian Tolar
*
*
*/
SIT,
/**
*
* Slovak Koruna
*
*
*/
SKK,
/**
*
* Sierra Leonean Leone
*
*
*/
SLL,
/**
*
* Somali Shilling
*
*
*/
SOS,
/**
*
* Surinamese Dollar
*
*
*/
SRD,
/**
*
* Surinamese Guilder
*
*
*/
SRG,
/**
*
* South Sudanese Pound
*
*
*/
SSP,
/**
*
* S?o Tom? & Pr?ncipe Dobra
*
*
*/
STD,
/**
*
* Soviet Rouble
*
*
*/
SUR,
/**
*
* Salvadoran Col?n
*
*
*/
SVC,
/**
*
* Syrian Pound
*
*
*/
SYP,
/**
*
* Swazi Lilangeni
*
*
*/
SZL,
/**
*
* Thai Baht
*
*
*/
THB,
/**
*
* Tajikistani Ruble
*
*
*/
TJR,
/**
*
* Tajikistani Somoni
*
*
*/
TJS,
/**
*
* Turkmenistani Manat (1993?2009)
*
*
*/
TMM,
/**
*
* Turkmenistani Manat
*
*
*/
TMT,
/**
*
* Tunisian Dinar
*
*
*/
TND,
/**
*
* Tongan Pa?anga
*
*
*/
TOP,
/**
*
* Timorese Escudo
*
*
*/
TPE,
/**
*
* Turkish Lira (1922?2005)
*
*
*/
TRL,
/**
*
* Turkish Lira
*
*
*/
TRY,
/**
*
* Trinidad & Tobago Dollar
*
*
*/
TTD,
/**
*
* New Taiwan Dollar
*
*
*/
TWD,
/**
*
* Tanzanian Shilling
*
*
*/
TZS,
/**
*
* Ukrainian Hryvnia
*
*
*/
UAH,
/**
*
* Ukrainian Karbovanets
*
*
*/
UAK,
/**
*
* Ugandan Shilling (1966?1987)
*
*
*/
UGS,
/**
*
* Ugandan Shilling
*
*
*/
UGX,
/**
*
* US Dollar
*
*
*/
USD,
/**
*
* Uruguayan Peso (1975?1993)
*
*
*/
UYP,
/**
*
* Uruguayan Peso
*
*
*/
UYU,
/**
*
* Uzbekistani Som
*
*
*/
UZS,
/**
*
* Venezuelan Bol?var (1871?2008)
*
*
*/
VEB,
/**
*
* Venezuelan Bol?var
*
*
*/
VEF,
/**
*
* Vietnamese Dong
*
*
*/
VND,
/**
*
* Vietnamese Dong (1978?1985)
*
*
*/
VNN,
/**
*
* Vanuatu Vatu
*
*
*/
VUV,
/**
*
* Samoan Tala
*
*
*/
WST,
/**
*
* Central African CFA Franc
*
*
*/
XAF,
/**
*
* East Caribbean Dollar
*
*
*/
XCD,
/**
*
* West African CFA Franc
*
*
*/
XOF,
/**
*
* CFP Franc
*
*
*/
XPF,
/**
*
* Unknown Currency
*
*
*/
XXX,
/**
*
* Yemeni Dinar
*
*
*/
YDD,
/**
*
* Yemeni Rial
*
*
*/
YER,
/**
*
* Yugoslavian Hard Dinar (1966?1990)
*
*
*/
YUD,
/**
*
* Yugoslavian New Dinar (1994?2002)
*
*
*/
YUM,
/**
*
* Yugoslavian Convertible Dinar (1990?1992)
*
*
*/
YUN,
/**
*
* Yugoslavian Reformed Dinar (1992?1993)
*
*
*/
YUR,
/**
*
* South African Rand
*
*
*/
ZAR,
/**
*
* Zambian Kwacha (1968?2012)
*
*
*/
ZMK,
/**
*
* Zambian Kwacha
*
*
*/
ZMW,
/**
*
* Zairean New Zaire (1993?1998)
*
*
*/
ZRN,
/**
*
* Zairean Zaire (1971?1993)
*
*
*/
ZRZ,
/**
*
* Zimbabwean Dollar (1980?2008)
*
*
*/
ZWD,
/**
*
* Zimbabwean Dollar (2009)
*
*
*/
ZWL,
/**
*
* Zimbabwean Dollar (2008)
*
*
*/
ZWR;
public String value() {
return name();
}
public static CurrencyCode fromValue(String v) {
return valueOf(v);
}
}
| |
/*******************************************************************************
* Copyright 2014 Celartem, Inc., dba LizardTech
*
* 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.lizardtech.expresszip.vaadin;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.io.FileUtils;
import org.geotools.referencing.CRS;
import org.opengis.referencing.FactoryException;
import org.opengis.referencing.NoSuchAuthorityCodeException;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import com.lizardtech.expresszip.model.BackgroundExecutor;
import com.lizardtech.expresszip.model.ExecutorListener;
import com.lizardtech.expresszip.model.ExportProps;
import com.lizardtech.expresszip.model.ExportProps.OutputPackageFormat;
import com.lizardtech.expresszip.model.GriddingOptions;
import com.lizardtech.expresszip.ui.ExportOptionsView;
import com.lizardtech.expresszip.vaadin.ExpressZipButton.Style;
import com.vaadin.data.Property.ValueChangeEvent;
import com.vaadin.data.Property.ValueChangeListener;
import com.vaadin.data.Validator.InvalidValueException;
import com.vaadin.data.validator.AbstractStringValidator;
import com.vaadin.data.validator.DoubleValidator;
import com.vaadin.data.validator.EmailValidator;
import com.vaadin.data.validator.IntegerValidator;
import com.vaadin.data.validator.RegexpValidator;
import com.vaadin.terminal.ThemeResource;
import com.vaadin.terminal.UserError;
import com.vaadin.ui.AbstractComponent;
import com.vaadin.ui.Accordion;
import com.vaadin.ui.Alignment;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Button.ClickListener;
import com.vaadin.ui.CheckBox;
import com.vaadin.ui.ComboBox;
import com.vaadin.ui.Component;
import com.vaadin.ui.CustomComponent;
import com.vaadin.ui.Embedded;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Label;
import com.vaadin.ui.OptionGroup;
import com.vaadin.ui.Panel;
import com.vaadin.ui.TextField;
import com.vaadin.ui.VerticalLayout;
@SuppressWarnings("serial")
public class ExportOptionsViewComponent extends CustomComponent implements ExportOptionsView, ExecutorListener {
private static final String PACKAGE = "Packaging options";
private static final String GRID_THE_RESULT = "Tile the result";
private static final String HEIGHT = "Height";
private static final String WIDTH = "Width";
private static final String EXPORT_CONFIGURATION = "Export resolution";
private static final String DIMENSIONS = "Dimensions";
private static final String TILING = "Tiling";
private static final String FORMAT_OPTIONS = "Format options";
private static final String OUTPUT_FORMAT = "Tile output format";
private static final String JOB_NAME = "Job name";
private static final String JOB_USER_NOTATION = "User name";
private static final String EMAIL_ADDRESS = "Email address";
private static final String JOB_DETAILS = "Job details";
private static final String GRID_TILE_DIMENSIONS = "Tile by pixel area";
private static final String GRID_GROUND_DISTANCE = "Tile by ground distance";
private static final String GRID_NUM_TILES = "Divide into tiles";
private static final List<String> GRIDDING_METHOD = Arrays.asList(new String[] { GRID_TILE_DIMENSIONS, GRID_GROUND_DISTANCE,
GRID_NUM_TILES });
private static final String NUMBER_OF_TILES = "Number of tiles: ";
private static final String DISK_ESTIMATE = "Disk usage estimate: ";
private Accordion accordian;
VerticalLayout jobDetailsLayout;
VerticalLayout griddingLayout;
VerticalLayout formatOptionsLayout;
VerticalLayout vrtOutputResolution;
VerticalLayout outputDetails;
private OptionGroup optGridOpt = new OptionGroup(null, GRIDDING_METHOD);
private CheckBox gridCheckbox = new CheckBox(GRID_THE_RESULT);
private TextField xTilesTextBox = new TextField();
private TextField yTilesTextBox = new TextField();
private TextField xPixelsTextBox = new TextField();
private TextField yPixelsTextBox = new TextField();
private TextField xDistanceTextBox = new TextField();
private TextField yDistanceTextBox = new TextField();
private ComboBox packageComboBox = new ComboBox(PACKAGE);
private ExpressZipButton backButton;
private ExpressZipButton submitButton;
private TextField txtGroundResolution = new TextField("PLACEHOLDER");
private TextField txtDimWidth = new TextField(WIDTH);
private TextField txtDimHeight = new TextField(HEIGHT);
// Format Option panel
private static final String JPEG = "JPEG";
private static final String PNG = "PNG";
private static final String TIFF = "TIFF";
private static final String GIF = "GIF";
private static final String BMP = "BMP";
private static final List<String> OUTPUT_FORMATS = Arrays.asList(new String[] { JPEG, PNG, TIFF, GIF, BMP });
private ComboBox outputFormatComboBox;
// Job option panel
private TextField txtJobName;
private TextField txtEmail;
private TextField txtUserNotation;
private List<ExportOptionsViewListener> listeners;
private Label numTilesLabel;
private Label exportSizeEstimate;
private boolean griddingDrawEnabled;
private ExportProps exportProps;
private ValueChangeListener griddingValuesChangeListener = new ValueChangeListener() {
@Override
public void valueChange(ValueChangeEvent event) {
if (updateGriddingValidity())
configureGridding();
updateSubmitEnabledState();
}
};
private ValueChangeListener resolutionValuesChangeListener = new ValueChangeListener() {
@Override
public void valueChange(ValueChangeEvent event) {
updateSubmitEnabledState();
}
};
private ValueChangeListener griddingModeChangeListener = new ValueChangeListener() {
@Override
public void valueChange(ValueChangeEvent event) {
updateGriddingEnabledState();
}
};
private ValueChangeListener widthValChangeListener = new ValueChangeListener() {
@Override
public void valueChange(ValueChangeEvent event) {
if (txtDimWidth.isValid()) {
for (ExportOptionsViewListener listener : listeners)
listener.updateHeightAndResFromWidth(getDimensionWidth());
if (forceGriddingCheck())
configureGridding();
}
updateSubmitEnabledState();
}
};
private ValueChangeListener heightValChangeListener = new ValueChangeListener() {
@Override
public void valueChange(ValueChangeEvent event) {
if (txtDimHeight.isValid()) {
for (ExportOptionsViewListener listener : listeners)
listener.updateWidthAndResFromHeight(getDimensionHeight());
if (forceGriddingCheck())
configureGridding();
}
updateSubmitEnabledState();
}
};
private ValueChangeListener groundResValChangeListener = new ValueChangeListener() {
@Override
public void valueChange(ValueChangeEvent event) {
if (txtGroundResolution.isValid()) {
for (ExportOptionsViewListener listener : listeners)
listener.updateWidthAndHeightFromRes(getGroundResolution());
if (forceGriddingCheck())
configureGridding();
}
updateSubmitEnabledState();
}
};
private double maximumResolution = 1.0d;
private static final String SMALL = "Small";
private static final String MEDIUM = "Medium";
private static final String LARGE = "Large";
private static final String NATIVE = "Native resolution";
private static final String CUSTOM = "Custom";
private static final List<String> exportSizes = Arrays.asList(new String[] { SMALL, MEDIUM, LARGE, NATIVE, CUSTOM });
private ComboBox exportSizeComboBox;
public ExportOptionsViewComponent(ExportProps exportProps) {
this.exportProps = exportProps;
listeners = new ArrayList<ExportOptionsViewListener>();
txtJobName = new TextField(JOB_NAME);
txtEmail = new TextField(EMAIL_ADDRESS);
txtUserNotation = new TextField(JOB_USER_NOTATION);
numTilesLabel = new Label();
exportSizeEstimate = new Label();
outputFormatComboBox = new ComboBox(OUTPUT_FORMAT, OUTPUT_FORMATS);
outputFormatComboBox.setTextInputAllowed(false);
outputFormatComboBox.addListener(griddingValuesChangeListener);
setSizeFull();
/**
* Setup output resolution
*/
exportSizeComboBox = new ComboBox(null, exportSizes);
exportSizeComboBox.setNullSelectionAllowed(false);
exportSizeComboBox.setNewItemsAllowed(false);
exportSizeComboBox.setTextInputAllowed(false);
exportSizeComboBox.setImmediate(true);
exportSizeComboBox.addListener(new ValueChangeListener() {
@Override
public void valueChange(ValueChangeEvent event) {
Object choice = event.getProperty().getValue();
String value = "";
if (SMALL.equals(choice)) {
gridCheckbox.setValue(Boolean.FALSE);
gridCheckbox.setEnabled(false);
value = "512";
} else if (MEDIUM.equals(choice)) {
gridCheckbox.setValue(Boolean.FALSE);
gridCheckbox.setEnabled(false);
value = "1280";
} else if (LARGE.equals(choice)) {
gridCheckbox.setValue(Boolean.FALSE);
gridCheckbox.setEnabled(false);
value = "5000";
}
boolean custom = CUSTOM.equals(choice);
if (!custom) {
if (NATIVE.equals(choice)) {
txtGroundResolution.setValue(Double.toString(maximumResolution));
} else {
if (getExportProps().getAspectRatio() > 1.0d) {
txtDimHeight.setValue(value);
} else
txtDimWidth.setValue(value);
}
}
txtDimWidth.setEnabled(custom);
txtDimHeight.setEnabled(custom);
txtGroundResolution.setEnabled(custom);
}
});
// Add Output Resolution to view
HorizontalLayout dimensionsLayout = new HorizontalLayout();
dimensionsLayout.addComponent(txtDimWidth);
dimensionsLayout.addComponent(txtDimHeight);
dimensionsLayout.setSpacing(true);
dimensionsLayout.setWidth("100%");
// Format dimensions layout
txtDimHeight.setMaxLength(10);
txtDimHeight.setWidth("100%");
txtDimHeight.setImmediate(true);
txtDimHeight.addListener(heightValChangeListener);
txtDimHeight.setRequired(true);
txtDimHeight.addValidator(new WidthHeightValidator());
txtDimWidth.setMaxLength(10);
txtDimWidth.setWidth("100%");
txtDimWidth.setImmediate(true);
txtDimWidth.addListener(widthValChangeListener);
txtDimWidth.setRequired(true);
txtDimWidth.addValidator(new WidthHeightValidator());
// Format Ground Resolution layout
txtGroundResolution.setValue("0");
txtGroundResolution.setImmediate(true);
txtGroundResolution.addListener(groundResValChangeListener);
txtGroundResolution.setRequired(true);
txtGroundResolution.addValidator(new GroundResolutionValidator());
vrtOutputResolution = new VerticalLayout();
vrtOutputResolution.setSpacing(true);
vrtOutputResolution.addComponent(exportSizeComboBox);
vrtOutputResolution.addComponent(dimensionsLayout);
txtGroundResolution.setWidth("75%");
vrtOutputResolution.addComponent(txtGroundResolution);
vrtOutputResolution.setComponentAlignment(txtGroundResolution, Alignment.BOTTOM_CENTER);
/**
* Setup Gridding options
*/
// Add Gridding option to view
griddingLayout = new VerticalLayout();
griddingLayout.setSpacing(true);
// Format GridCheckbox layout
griddingLayout.addComponent(gridCheckbox);
gridCheckbox.setImmediate(true);
gridCheckbox.setValue(false);
gridCheckbox.addListener(griddingModeChangeListener);
xPixelsTextBox.setWidth("100%");
xPixelsTextBox.setImmediate(true);
xPixelsTextBox.addValidator(new TileWidthValidator());
xPixelsTextBox.addListener(griddingValuesChangeListener);
yPixelsTextBox.setWidth("100%");
yPixelsTextBox.setImmediate(true);
yPixelsTextBox.addValidator(new TileHeightValidator());
yPixelsTextBox.addListener(griddingValuesChangeListener);
xDistanceTextBox.setWidth("100%");
xDistanceTextBox.setImmediate(true);
xDistanceTextBox.addValidator(new TileGeoXValidator());
xDistanceTextBox.addListener(griddingValuesChangeListener);
yDistanceTextBox.setWidth("100%");
yDistanceTextBox.setImmediate(true);
yDistanceTextBox.addValidator(new TileGeoYValidator());
yDistanceTextBox.addListener(griddingValuesChangeListener);
// Format gridding options
xTilesTextBox.setWidth("100%");
xTilesTextBox.setImmediate(true);
xTilesTextBox.addValidator(new TileXDivisorValidator());
xTilesTextBox.addListener(griddingValuesChangeListener);
yTilesTextBox.setWidth("100%");
yTilesTextBox.setImmediate(true);
yTilesTextBox.addValidator(new TileYDivisorValidator());
yTilesTextBox.addListener(griddingValuesChangeListener);
optGridOpt.setValue(GRID_TILE_DIMENSIONS);
optGridOpt.setImmediate(true);
optGridOpt.addListener(griddingModeChangeListener);
HorizontalLayout hznGridOptions = new HorizontalLayout();
griddingLayout.addComponent(hznGridOptions);
hznGridOptions.setWidth("100%");
hznGridOptions.setSpacing(true);
hznGridOptions.addComponent(optGridOpt);
VerticalLayout vrtGridComboFields = new VerticalLayout();
hznGridOptions.addComponent(vrtGridComboFields);
vrtGridComboFields.setWidth("100%");
hznGridOptions.setExpandRatio(vrtGridComboFields, 1.0f);
HorizontalLayout hznTileDim = new HorizontalLayout();
hznTileDim.setWidth("100%");
vrtGridComboFields.addComponent(hznTileDim);
hznTileDim.addComponent(xPixelsTextBox);
hznTileDim.addComponent(yPixelsTextBox);
HorizontalLayout hznDistanceDim = new HorizontalLayout();
hznDistanceDim.setWidth("100%");
vrtGridComboFields.addComponent(hznDistanceDim);
hznDistanceDim.addComponent(xDistanceTextBox);
hznDistanceDim.addComponent(yDistanceTextBox);
HorizontalLayout hznDivideGrid = new HorizontalLayout();
hznDivideGrid.setWidth("100%");
vrtGridComboFields.addComponent(hznDivideGrid);
hznDivideGrid.addComponent(xTilesTextBox);
hznDivideGrid.addComponent(yTilesTextBox);
hznDivideGrid.setSpacing(true);
hznTileDim.setSpacing(true);
hznDistanceDim.setSpacing(true);
/**
* Format options panel
*/
// Add Format options to view
formatOptionsLayout = new VerticalLayout();
formatOptionsLayout.setWidth("100%");
formatOptionsLayout.setSpacing(true);
formatOptionsLayout.setMargin(true);
// Format outputformat
formatOptionsLayout.addComponent(outputFormatComboBox);
outputFormatComboBox.setNullSelectionAllowed(false);
formatOptionsLayout.addComponent(packageComboBox);
packageComboBox.addItem(ExportProps.OutputPackageFormat.TAR);
packageComboBox.addItem(ExportProps.OutputPackageFormat.ZIP);
packageComboBox.setNullSelectionAllowed(false);
packageComboBox.setTextInputAllowed(false);
packageComboBox.setValue(ExportProps.OutputPackageFormat.ZIP);
/**
* Job Details
*/
// Set Jobname panel
jobDetailsLayout = new VerticalLayout();
jobDetailsLayout.setSpacing(true);
jobDetailsLayout.setMargin(true);
jobDetailsLayout.addComponent(txtJobName);
txtJobName.setRequired(true);
txtJobName.setRequiredError("Please enter a job name.");
txtJobName.setWidth("100%");
txtJobName.setImmediate(true);
String jobname_regexp = "^[ A-Za-z0-9._-]{1,128}$";
txtJobName.addValidator(new RegexpValidator(jobname_regexp,
"Job names should be alpha-numeric, less than 128 characters and may include spaces, dashes and underscores"));
txtJobName
.addValidator(new JobNameUniqueValidator("A job by that name already exists in your configured export directory"));
txtJobName.addListener(resolutionValuesChangeListener);
jobDetailsLayout.addComponent(txtUserNotation);
txtUserNotation.setWidth("100%");
txtUserNotation.setImmediate(true);
String usernotation_regexp = "^[ A-Za-z0-9_-]{0,32}$";
txtUserNotation.addValidator(new RegexpValidator(usernotation_regexp,
"User names should be alpha-numeric, less than 32 characters and may include spaces, dashes and underscores"));
txtUserNotation.addListener(resolutionValuesChangeListener);
// Format Email
boolean enableEmail = new BackgroundExecutor.Factory().getBackgroundExecutor().getMailServices().isValidEmailConfig();
txtEmail.setEnabled(enableEmail);
if (enableEmail) {
jobDetailsLayout.addComponent(txtEmail);
txtEmail.setWidth("100%");
txtEmail.setInputPrompt("enter your email address");
txtEmail.setImmediate(true);
txtEmail.addValidator(new EmailValidator("Invalid format for email address."));
txtEmail.addListener(new ValueChangeListener() {
@Override
public void valueChange(ValueChangeEvent event) {
updateSubmitEnabledState();
}
});
}
VerticalLayout exportSummary = new VerticalLayout();
exportSummary.addComponent(numTilesLabel);
exportSummary.addComponent(exportSizeEstimate);
jobDetailsLayout.addComponent(new Panel(("Export summary"), exportSummary));
// Set submit and back buttons
// Add listeners to all fields
backButton = new ExpressZipButton("Back", Style.STEP);
backButton.addListener(new ClickListener() {
@Override
public void buttonClick(ClickEvent event) {
((ExpressZipWindow) getApplication().getMainWindow()).regressToPrev();
}
});
submitButton = new ExpressZipButton("Submit", Style.STEP);
submitButton.addListener(new ClickListener() {
@Override
public void buttonClick(ClickEvent event) {
try {
txtJobName.validate();
} catch (InvalidValueException e) {
txtJobName.requestRepaint();
updateSubmitEnabledState();
return;
}
for (ExportOptionsViewListener listener : listeners) {
listener.submitJobEvent(getExportProps());
}
}
});
accordian = new Accordion();
accordian.addStyleName("expresszip");
accordian.setImmediate(true);
accordian.addTab(jobDetailsLayout, JOB_DETAILS);
accordian.addTab(formatOptionsLayout, FORMAT_OPTIONS);
accordian.setSizeFull();
outputDetails = new VerticalLayout();
outputDetails.setMargin(true);
outputDetails.setSpacing(true);
outputDetails.addComponent(new Panel(DIMENSIONS, vrtOutputResolution));
outputDetails.addComponent(new Panel(TILING, griddingLayout));
accordian.addTab(outputDetails, EXPORT_CONFIGURATION);
HorizontalLayout backSubmitLayout = new HorizontalLayout();
backSubmitLayout.setWidth("100%");
backSubmitLayout.addComponent(backButton);
backSubmitLayout.addComponent(submitButton);
backSubmitLayout.setComponentAlignment(backButton, Alignment.BOTTOM_LEFT);
backSubmitLayout.setComponentAlignment(submitButton, Alignment.BOTTOM_RIGHT);
VerticalLayout navLayout = new VerticalLayout();
navLayout.addComponent(backSubmitLayout);
navLayout.setSpacing(true);
ThemeResource banner = new ThemeResource("img/ProgressBar3.png");
navLayout.addComponent(new Embedded(null,banner));
// add scrollbars around formLayout
VerticalLayout layout = new VerticalLayout();
layout.setMargin(true);
layout.setSizeFull();
layout.setSpacing(true);
Label step = new Label("Step 3: Configure Export Options");
step.addStyleName("step");
layout.addComponent(step);
layout.addComponent(accordian);
layout.setExpandRatio(accordian, 1.0f);
layout.addComponent(navLayout);
layout.setComponentAlignment(navLayout, Alignment.BOTTOM_CENTER);
setCompositionRoot(layout);
outputFormatComboBox.select(OUTPUT_FORMATS.get(0));
forceGriddingCheck();
updateGriddingEnabledState();
}
private boolean updateGriddingFieldValidity(TextField f, String method) {
if (f == null)
return false;
boolean fieldActive = gridCheckbox.booleanValue();
try {
fieldActive &= ((String) optGridOpt.getValue()).equals(method);
f.setComponentError(null);
f.setValidationVisible(fieldActive);
f.setRequired(fieldActive);
if (fieldActive)
f.validate();
} catch (Exception e) {
return false;
}
return true;
}
private boolean updateGriddingValidity() {
boolean valid = true;
valid = updateGriddingFieldValidity(xPixelsTextBox, GRID_TILE_DIMENSIONS) && valid;
valid = updateGriddingFieldValidity(yPixelsTextBox, GRID_TILE_DIMENSIONS) && valid;
valid = updateGriddingFieldValidity(xDistanceTextBox, GRID_GROUND_DISTANCE) && valid;
valid = updateGriddingFieldValidity(yDistanceTextBox, GRID_GROUND_DISTANCE) && valid;
valid = updateGriddingFieldValidity(xTilesTextBox, GRID_NUM_TILES) && valid;
valid = updateGriddingFieldValidity(yTilesTextBox, GRID_NUM_TILES) && valid;
return valid;
}
public void updateUI() {
forceGriddingCheck();
StringBuilder groundResCaption = new StringBuilder("Ground resolution: (");
String currentUoM = "unknown";
try {
CoordinateReferenceSystem crs = CRS.getAuthorityFactory(true).createCoordinateReferenceSystem(
exportProps.getMapProjection());
Pattern pattern = Pattern.compile("UoM: ([a-zA-Z]*)");
Matcher matcher = pattern.matcher(crs.getCoordinateSystem().getName().getCode());
currentUoM = matcher.find() ? matcher.group(1) : "unkown";
groundResCaption.append(currentUoM);
groundResCaption.append("/px)");
} catch (NoSuchAuthorityCodeException e) {
e.printStackTrace();
} catch (FactoryException e) {
e.printStackTrace();
}
txtGroundResolution.setCaption(groundResCaption.toString());
optGridOpt.setItemCaption(GRID_GROUND_DISTANCE, "Tile by " + currentUoM);
}
public void paneEntered() {
exportSizeComboBox.select(CUSTOM);
updateUI();
updateGriddingEnabledState();
exportSizeComboBox.select(MEDIUM); // reset to medium
}
private void configureGridding() {
GriddingOptions griddingOptions = new GriddingOptions();
ExportProps props = getExportProps();
griddingOptions.setExportWidth(props.getWidth());
griddingOptions.setExportHeight(props.getHeight());
griddingOptions.setGridding(gridCheckbox.booleanValue() && griddingDrawEnabled);
if (griddingOptions.isGridding()) {
if ((String) optGridOpt.getValue() == GRID_NUM_TILES) {
griddingOptions.setGridMode(GriddingOptions.GridMode.DIVISION);
int divX = Integer.parseInt(xTilesTextBox.getValue().toString());
int divY = Integer.parseInt(yTilesTextBox.getValue().toString());
griddingOptions.setDivX(divX > 0 ? divX : griddingOptions.getDivX());
griddingOptions.setDivY(divY > 0 ? divY : griddingOptions.getDivY());
} else { // GRID_TILE_DIMENSIONS or GRID_GROUND_DISTANCE
griddingOptions.setGridMode(GriddingOptions.GridMode.METERS);
if ((String) optGridOpt.getValue() == GRID_GROUND_DISTANCE) {
Double groundResolution = getGroundResolution();
griddingOptions.setTileSizeX((int) (Double.parseDouble(getDistance_X()) / groundResolution));
griddingOptions.setTileSizeY((int) (Double.parseDouble(getDistance_Y()) / groundResolution));
} else {
griddingOptions.setTileSizeX(Integer.parseInt(getTile_X()));
griddingOptions.setTileSizeY(Integer.parseInt(getTile_Y()));
}
}
}
getExportProps().setGriddingOptions(griddingOptions);
// update job summary text
numTilesLabel.setValue(NUMBER_OF_TILES + griddingOptions.getNumTiles());
BigInteger size = griddingOptions.getExportSize();
String format = getImageFormat();
if (format.equals(PNG))
size = size.multiply(BigInteger.valueOf(85)).divide(BigInteger.valueOf(100));
else if (format.equals(JPEG))
size = size.divide(BigInteger.valueOf(15));
else if (format.equals(GIF))
size = size.multiply(BigInteger.valueOf(15)).divide(BigInteger.valueOf(100));
else if (format.equals(BMP))
size = size.multiply(BigInteger.valueOf(85)).divide(BigInteger.valueOf(100));
exportSizeEstimate.setValue(DISK_ESTIMATE + FileUtils.byteCountToDisplaySize(size));
for (ExportOptionsViewListener listener : listeners)
listener.updateGridding(getExportProps());
}
private void constrainTileDimension(TextField f, int constraint) {
int v = -1;
if (f.getValue() != null) {
try {
v = Integer.parseInt((String) f.getValue());
} catch (NumberFormatException e) {
}
}
if (f.getValue() == null || v > constraint || v < 1)
f.setValue(Integer.toString(constraint));
}
// returns true if gridding parameters are valid
private boolean forceGriddingCheck() {
if (getDimensionWidth() > ExportProps.MAX_TILE_WIDTH || getDimensionHeight() > ExportProps.MAX_TILE_HEIGHT) {
gridCheckbox.setValue(true);
gridCheckbox.setEnabled(false);
getExportProps().setTileOutput(true);
// since we are forcing, let's make sure we pick valid tiling parameters
constrainTileDimension(xPixelsTextBox, Math.min(getDimensionWidth(), ExportProps.MAX_TILE_WIDTH));
constrainTileDimension(yPixelsTextBox, Math.min(getDimensionHeight(), ExportProps.MAX_TILE_HEIGHT));
} else {
gridCheckbox.setEnabled(true);
}
return updateGriddingValidity();
}
private void updateGriddingEnabledState() {
boolean griddingChecked = gridCheckbox.booleanValue();
String gridMode = (String) optGridOpt.getValue();
getExportProps().setTileOutput(griddingChecked);
optGridOpt.setEnabled(griddingChecked);
xPixelsTextBox.setEnabled(griddingChecked && gridMode.equals(GRID_TILE_DIMENSIONS));
yPixelsTextBox.setEnabled(griddingChecked && gridMode.equals(GRID_TILE_DIMENSIONS));
xDistanceTextBox.setEnabled(griddingChecked && gridMode.equals(GRID_GROUND_DISTANCE));
yDistanceTextBox.setEnabled(griddingChecked && gridMode.equals(GRID_GROUND_DISTANCE));
xTilesTextBox.setEnabled(griddingChecked && gridMode.equals(GRID_NUM_TILES));
yTilesTextBox.setEnabled(griddingChecked && gridMode.equals(GRID_NUM_TILES));
if (updateGriddingValidity())
configureGridding();
updateSubmitEnabledState();
}
@Override
public void addListener(ExportOptionsViewListener listener) {
listeners.add(listener);
}
/**
* Display errorMessage on to screen.
*
* @param errorMessage
*/
public void setErrorMessage(String errorMessage) {
((ExpressZipWindow) getApplication().getMainWindow()).showNotification(errorMessage);
}
public String getEmail() {
if (txtEmail.isEnabled())
return txtEmail.getValue().toString();
return null;
}
public String getUserNotation() {
return txtUserNotation.getValue().toString();
}
public String getImageFormat() {
return outputFormatComboBox.getValue().toString();
}
public OutputPackageFormat getPackageFormat() {
OutputPackageFormat fmt = OutputPackageFormat.valueOf(packageComboBox.getValue().toString());
return fmt;
}
public String getTile_X() {
return xPixelsTextBox.getValue().toString();
}
public String getTile_Y() {
return yPixelsTextBox.getValue().toString();
}
public String getDistance_X() {
return xDistanceTextBox.getValue().toString();
}
public String getDistance_Y() {
return yDistanceTextBox.getValue().toString();
}
public String getJobName() {
return txtJobName.getValue().toString();
}
private void updateSubmitEnabledState() {
boolean jobDetailsValid = txtJobName.isValid() && (getUserNotation().isEmpty() || txtUserNotation.isValid());
if (txtEmail.isEnabled()) {
if (!txtEmail.getValue().toString().isEmpty()) {
jobDetailsValid &= txtEmail.isValid();
}
}
boolean outputValid = txtDimHeight.isValid() && txtDimWidth.isValid();
if (gridCheckbox.booleanValue()) {
String gridOpt = (String) optGridOpt.getValue();
if (gridOpt.equals(GRID_TILE_DIMENSIONS)) {
outputValid &= xPixelsTextBox.isValid() && yPixelsTextBox.isValid();
} else if (gridOpt.equals(GRID_NUM_TILES)) {
outputValid &= xTilesTextBox.isValid() && yTilesTextBox.isValid();
} else if (gridOpt.equals(GRID_GROUND_DISTANCE)) {
outputValid &= xDistanceTextBox.isValid() && yDistanceTextBox.isValid();
}
}
accordian.getTab(jobDetailsLayout).setIcon(jobDetailsValid ? null : new ThemeResource("img/error.png"));
accordian.getTab(outputDetails).setIcon(outputValid ? null : new ThemeResource("img/error.png"));
submitButton.setEnabled(jobDetailsValid && outputValid);
}
public int getDimensionHeight() {
String strval = (String) txtDimHeight.getValue();
if (strval.isEmpty())
return 0;
return Integer.parseInt(strval);
}
public int getDimensionWidth() {
String strval = (String) txtDimWidth.getValue();
if (strval.isEmpty())
return 0;
return Integer.parseInt(strval);
}
public Double getGroundResolution() {
Double groundResolution;
try {
groundResolution = Double.parseDouble(txtGroundResolution.getValue().toString());
} catch (NumberFormatException e) {
// just return 1.0 when not initialized yet
groundResolution = 1.0;
}
return groundResolution;
}
// Vaadin doesn't support turning off events, so remove the
// listener/re-add it to prevent update cycles
public void setTxtDimensionHeight(int height) {
txtDimHeight.removeListener(heightValChangeListener);
txtDimHeight.setValue(Integer.toString(height));
getExportProps().setHeight(height);
txtDimHeight.addListener(heightValChangeListener);
}
public void setTxtDimensionWidth(int width) {
txtDimWidth.removeListener(widthValChangeListener);
txtDimWidth.setValue(Integer.toString(width));
getExportProps().setWidth(width);
txtDimWidth.addListener(widthValChangeListener);
}
public void setGroundResolution(double groundResolution) {
txtGroundResolution.removeListener(groundResValChangeListener);
txtGroundResolution.setValue(Double.toString(groundResolution));
txtGroundResolution.addListener(groundResValChangeListener);
}
public void setMaximumResolution(double resolution) {
maximumResolution = resolution;
}
public void setTxtDistanceX(int x) {
xDistanceTextBox.setValue(Integer.toString(x));
}
public void setTxtDistanceY(int y) {
yDistanceTextBox.setValue(Integer.toString(y));
}
public AbstractComponent getTxtWidth() {
return txtDimWidth;
}
public void setComponentErrorMessage(AbstractComponent c, String message) {
c.setComponentError(new UserError(message));
}
public void clearComponentErrorMessage(AbstractComponent c) {
c.setComponentError(null);
}
public AbstractComponent getTxtHeight() {
return txtDimHeight;
}
public ExportProps getExportProps() {
return exportProps;
}
public class TileByPixelDimensionValidator extends IntegerValidator {
private String dimensionName;
public TileByPixelDimensionValidator(String dimensionName) {
super(new String("Tile " + dimensionName + " must be a positive integer."));
this.dimensionName = dimensionName;
}
protected Integer getValidDimension(TileByPixelDimensionValidator vtor, String value, int tilemax, int jobmax) {
Integer ivalue = null;
try {
ivalue = new Integer(Integer.parseInt(value));
if (ivalue > tilemax) {
if (vtor != null)
vtor.setErrorMessage("{0} exceeds the maximum allowable tile " + dimensionName + " (" + tilemax + ").");
return null;
}
if (ivalue > jobmax) {
if (vtor != null)
vtor.setErrorMessage("{0} exceeds the " + dimensionName + " of the total job.");
return null;
}
if (ivalue <= 0) {
if (vtor != null)
vtor.setErrorMessage("{0} is not a positive integer.");
return null;
}
} catch (NumberFormatException e) {
if (vtor != null)
vtor.setErrorMessage("{0} is not a positive integer.");
return null;
}
return ivalue;
}
protected boolean checkNumTiles(TileByPixelDimensionValidator vtor, int tilewidth, int tileheight) {
long tileswide = ((getDimensionWidth() - 1) / tilewidth) + 1;
long tileshigh = ((getDimensionHeight() - 1) / tileheight) + 1;
if (tileswide > ExportProps.MAX_TILES_PER_JOB || tileshigh > ExportProps.MAX_TILES_PER_JOB
|| tileswide * tileshigh > ExportProps.MAX_TILES_PER_JOB) {
if (vtor != null)
this.setErrorMessage(tilewidth + " x " + tileheight
+ " tiles are too small and will exceed the maximum number allowed per job ("
+ ExportProps.MAX_TILES_PER_JOB + ").");
return false;
}
return true;
}
}
public class TileWidthValidator extends TileByPixelDimensionValidator {
public TileWidthValidator() {
super("width");
}
@Override
protected boolean isValidString(String value) {
Integer wvalue = getValidDimension(this, value, ExportProps.MAX_TILE_WIDTH, getDimensionWidth());
if (wvalue == null)
return false;
if (yPixelsTextBox.getValue() != null) {
Integer hvalue = getValidDimension(null, yPixelsTextBox.getValue().toString(), ExportProps.MAX_TILE_HEIGHT,
getDimensionHeight());
if (hvalue != null)
return checkNumTiles(this, wvalue.intValue(), hvalue.intValue());
}
return true;
}
}
public class TileHeightValidator extends TileByPixelDimensionValidator {
public TileHeightValidator() {
super("height");
}
@Override
protected boolean isValidString(String value) {
Integer hvalue = getValidDimension(this, value, ExportProps.MAX_TILE_HEIGHT, getDimensionHeight());
if (hvalue == null)
return false;
if (xPixelsTextBox.getValue() != null) {
Integer wvalue = getValidDimension(null, xPixelsTextBox.getValue().toString(), ExportProps.MAX_TILE_WIDTH,
getDimensionWidth());
if (wvalue != null)
return checkNumTiles(this, wvalue.intValue(), hvalue.intValue());
}
return true;
}
}
public class TileByGeoDimensionValidator extends DoubleValidator {
private String dimensionName;
public TileByGeoDimensionValidator(String dimensionName) {
super(new String("Tile " + dimensionName + " must be a positive decimal number."));
this.dimensionName = dimensionName;
}
protected Double getValidDimension(TileByGeoDimensionValidator vtor, String value, int tilemax, int jobmax) {
Double dvalue = null;
try {
dvalue = new Double(Double.parseDouble(value));
double dmax = tilemax * getGroundResolution();
if (dvalue > dmax) {
this.setErrorMessage("{0} exceeds the maximum allowable tile " + dimensionName + " at this resolution (" + dmax
+ ").");
return null;
}
double djob = jobmax * getGroundResolution();
if (dvalue > djob) {
this.setErrorMessage("{0} exceeds the " + dimensionName + " of the total job at this resolution (" + djob + ".");
return null;
}
if (dvalue <= 0.0) {
this.setErrorMessage("{0} is not a positive decimal number");
return null;
}
} catch (NumberFormatException e) {
this.setErrorMessage("{0} is not a positive decimal number.");
return null;
}
return dvalue;
}
protected boolean checkNumTiles(TileByGeoDimensionValidator vtor, double tilewidth, double tileheight) {
long tileswide = (long) Math.ceil(getDimensionWidth() * getGroundResolution() / tilewidth);
long tileshigh = (long) Math.ceil(getDimensionHeight() * getGroundResolution() / tileheight);
if (tileswide > ExportProps.MAX_TILES_PER_JOB || tileshigh > ExportProps.MAX_TILES_PER_JOB
|| tileswide * tileshigh > ExportProps.MAX_TILES_PER_JOB) {
if (vtor != null)
vtor.setErrorMessage(tilewidth + " x " + tileheight
+ " tiles are too small and will exceed the maximum number allowed per job ("
+ ExportProps.MAX_TILES_PER_JOB + ").");
return false;
}
return true;
}
}
public class TileGeoXValidator extends TileByGeoDimensionValidator {
public TileGeoXValidator() {
super("width");
}
@Override
protected boolean isValidString(String value) {
Double wvalue = getValidDimension(this, value, ExportProps.MAX_TILE_WIDTH, getDimensionWidth());
if (wvalue == null)
return false;
if (yDistanceTextBox.getValue() != null) {
Double hvalue = getValidDimension(null, yDistanceTextBox.getValue().toString(), ExportProps.MAX_TILE_HEIGHT,
getDimensionHeight());
if (hvalue != null)
return checkNumTiles(this, wvalue.doubleValue(), hvalue.doubleValue());
}
return true;
}
}
public class TileGeoYValidator extends TileByGeoDimensionValidator {
public TileGeoYValidator() {
super("height");
}
@Override
protected boolean isValidString(String value) {
Double hvalue = getValidDimension(this, value, ExportProps.MAX_TILE_HEIGHT, getDimensionHeight());
if (hvalue == null)
return false;
if (xDistanceTextBox.getValue() != null) {
Double wvalue = getValidDimension(null, xDistanceTextBox.getValue().toString(), ExportProps.MAX_TILE_WIDTH,
getDimensionWidth());
if (wvalue != null)
return checkNumTiles(this, wvalue.doubleValue(), hvalue.doubleValue());
}
return true;
}
}
public class TileByDivisionValidator extends IntegerValidator {
private String dimensionName;
private String spanName;
public TileByDivisionValidator(String dimensionName, String spanName) {
super("Tile divisor must be a positive integer.");
this.dimensionName = dimensionName;
this.spanName = spanName;
}
protected Integer getValidDivisor(TileByDivisionValidator vtor, String value, int tilemax, int jobmax) {
Integer ivalue = null;
try {
ivalue = new Integer(Integer.parseInt(value));
if (ivalue <= 0) {
this.setErrorMessage("{0} is not a positive integer");
return null;
}
if (((jobmax - 1) / ivalue) + 1 > tilemax) {
this.setErrorMessage("Dividing into {0} tile " + spanName
+ "s produces tiles that exceed the maximum allowable tile " + dimensionName + " (" + tilemax + ").");
return null;
}
} catch (NumberFormatException e) {
this.setErrorMessage("{0} is not a positive integer.");
return null;
}
return ivalue;
}
protected boolean checkNumTiles(TileByDivisionValidator vtor, int columns, int rows) {
long tileswide = columns;
long tileshigh = rows;
if (tileswide > ExportProps.MAX_TILES_PER_JOB || tileshigh > ExportProps.MAX_TILES_PER_JOB
|| tileswide * tileshigh > ExportProps.MAX_TILES_PER_JOB) {
if (vtor != null)
vtor.setErrorMessage(columns + " x " + rows + " exceeds the maximum number of tiles allowed per job ("
+ ExportProps.MAX_TILES_PER_JOB + ").");
return false;
}
return true;
}
}
public class TileXDivisorValidator extends TileByDivisionValidator {
public TileXDivisorValidator() {
super("width", "column");
}
@Override
protected boolean isValidString(String value) {
Integer wvalue = getValidDivisor(this, value, ExportProps.MAX_TILE_WIDTH, getDimensionWidth());
if (wvalue == null)
return false;
if (yTilesTextBox.getValue() != null) {
Integer hvalue = getValidDivisor(null, yTilesTextBox.getValue().toString(), ExportProps.MAX_TILE_HEIGHT,
getDimensionHeight());
if (hvalue != null)
return checkNumTiles(this, wvalue.intValue(), hvalue.intValue());
}
return true;
}
}
public class TileYDivisorValidator extends TileByDivisionValidator {
public TileYDivisorValidator() {
super("height", "row");
}
@Override
protected boolean isValidString(String value) {
Integer hvalue = getValidDivisor(this, value, ExportProps.MAX_TILE_HEIGHT, getDimensionHeight());
if (hvalue == null)
return false;
if (xTilesTextBox.getValue() != null) {
Integer wvalue = getValidDivisor(null, xTilesTextBox.getValue().toString(), ExportProps.MAX_TILE_WIDTH,
getDimensionWidth());
if (wvalue != null)
return checkNumTiles(this, wvalue.intValue(), hvalue.intValue());
}
return true;
}
}
public class WidthHeightValidator extends IntegerValidator {
public WidthHeightValidator() {
super(new String("Must be a positive integer less than " + Integer.MAX_VALUE));
}
@Override
protected boolean isValidString(String value) {
try {
int val = Integer.parseInt(value);
return val > 0;
} catch (Exception e) {
return false;
}
}
}
public class GroundResolutionValidator extends DoubleValidator {
public GroundResolutionValidator() {
super(new String("Must be a positive floating point number."));
}
@Override
protected boolean isValidString(String value) {
try {
double val = Double.parseDouble(value);
return val > 0;
} catch (Exception e) {
return false;
}
}
}
private class JobNameUniqueValidator extends AbstractStringValidator {
public JobNameUniqueValidator(String errorMessage) {
super(errorMessage);
}
@Override
protected boolean isValidString(String value) {
return ExportProps.jobNameIsUnique(value);
}
}
@Override
public void taskFinished(Runnable r) {
}
@Override
public void taskRunning(Runnable r) {
}
@Override
public void taskQueued(Runnable r) {
((ExpressZipWindow) getApplication().getMainWindow()).showNotification(String.format("Job \"%s\" Queued", r.toString()));
}
@Override
public void taskError(Runnable r, Throwable e) {
}
public void setGriddingDrawEnabled(boolean griddingDrawEnabled) {
this.griddingDrawEnabled = griddingDrawEnabled;
updateGriddingEnabledState();
}
public static Panel getScrollableComponent(Component form) {
VerticalLayout vl = new VerticalLayout();
vl.addComponent(form);
Panel panel = new Panel();
panel.setContent(vl);
return panel;
}
}
| |
/*
* 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.phoenix.end2end;
import static org.apache.phoenix.util.TestUtil.A_VALUE;
import static org.apache.phoenix.util.TestUtil.B_VALUE;
import static org.apache.phoenix.util.TestUtil.C_VALUE;
import static org.apache.phoenix.util.TestUtil.E_VALUE;
import static org.apache.phoenix.util.TestUtil.ROW1;
import static org.apache.phoenix.util.TestUtil.ROW2;
import static org.apache.phoenix.util.TestUtil.ROW3;
import static org.apache.phoenix.util.TestUtil.ROW4;
import static org.apache.phoenix.util.TestUtil.ROW5;
import static org.apache.phoenix.util.TestUtil.ROW6;
import static org.apache.phoenix.util.TestUtil.ROW7;
import static org.apache.phoenix.util.TestUtil.ROW8;
import static org.apache.phoenix.util.TestUtil.ROW9;
import static org.apache.phoenix.util.TestUtil.TEST_PROPERTIES;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.sql.Array;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Collection;
import java.util.List;
import java.util.Properties;
import org.apache.phoenix.util.PhoenixRuntime;
import org.apache.phoenix.util.PropertiesUtil;
import org.apache.phoenix.util.QueryUtil;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import com.google.common.collect.Lists;
@RunWith(Parameterized.class)
public class DerivedTableIT extends BaseClientManagedTimeIT {
private static final String tenantId = getOrganizationId();
private long ts;
private String[] indexDDL;
private String[] plans;
public DerivedTableIT(String[] indexDDL, String[] plans) {
this.indexDDL = indexDDL;
this.plans = plans;
}
@Before
public void initTable() throws Exception {
ts = nextTimestamp();
initATableValues(tenantId, getDefaultSplits(tenantId), null, ts);
if (indexDDL != null && indexDDL.length > 0) {
Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts));
Connection conn = DriverManager.getConnection(getUrl(), props);
for (String ddl : indexDDL) {
conn.createStatement().execute(ddl);
}
}
}
@Parameters(name="{0}")
public static Collection<Object> data() {
List<Object> testCases = Lists.newArrayList();
testCases.add(new String[][] {
{
"CREATE INDEX ATABLE_DERIVED_IDX ON aTable (a_byte) INCLUDE (A_STRING, B_STRING)"
}, {
"CLIENT PARALLEL 1-WAY FULL SCAN OVER ATABLE_DERIVED_IDX\n" +
" SERVER AGGREGATE INTO DISTINCT ROWS BY [A_STRING, B_STRING]\n" +
"CLIENT MERGE SORT\n" +
"CLIENT SORTED BY [B_STRING]\n" +
"CLIENT SORTED BY [A]\n" +
"CLIENT AGGREGATE INTO DISTINCT ROWS BY [A]\n" +
"CLIENT SORTED BY [A DESC]",
"CLIENT PARALLEL 1-WAY FULL SCAN OVER ATABLE_DERIVED_IDX\n" +
" SERVER AGGREGATE INTO DISTINCT ROWS BY [A_STRING, B_STRING]\n" +
"CLIENT MERGE SORT\n" +
"CLIENT AGGREGATE INTO DISTINCT ROWS BY [A]\n" +
"CLIENT DISTINCT ON [COLLECTDISTINCT(B)]"}});
testCases.add(new String[][] {
{}, {
"CLIENT PARALLEL 4-WAY FULL SCAN OVER ATABLE\n" +
" SERVER AGGREGATE INTO DISTINCT ROWS BY [A_STRING, B_STRING]\n" +
"CLIENT MERGE SORT\n" +
"CLIENT SORTED BY [B_STRING]\n" +
"CLIENT SORTED BY [A]\n" +
"CLIENT AGGREGATE INTO DISTINCT ROWS BY [A]\n" +
"CLIENT SORTED BY [A DESC]",
"CLIENT PARALLEL 4-WAY FULL SCAN OVER ATABLE\n" +
" SERVER AGGREGATE INTO DISTINCT ROWS BY [A_STRING, B_STRING]\n" +
"CLIENT MERGE SORT\n" +
"CLIENT AGGREGATE INTO DISTINCT ROWS BY [A]\n" +
"CLIENT DISTINCT ON [COLLECTDISTINCT(B)]"}});
return testCases;
}
@Test
public void testDerivedTableWithWhere() throws Exception {
long ts = nextTimestamp();
Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 1));
Connection conn = DriverManager.getConnection(getUrl(), props);
try {
// (where)
String query = "SELECT t.eid, t.x + 9 FROM (SELECT entity_id eid, b_string b, a_byte + 1 x FROM aTable WHERE a_byte + 1 < 9) AS t";
PreparedStatement statement = conn.prepareStatement(query);
ResultSet rs = statement.executeQuery();
assertTrue (rs.next());
assertEquals(ROW1,rs.getString(1));
assertEquals(11,rs.getInt(2));
assertTrue (rs.next());
assertEquals(ROW2,rs.getString(1));
assertEquals(12,rs.getInt(2));
assertTrue (rs.next());
assertEquals(ROW3,rs.getString(1));
assertEquals(13,rs.getInt(2));
assertTrue (rs.next());
assertEquals(ROW4,rs.getString(1));
assertEquals(14,rs.getInt(2));
assertTrue (rs.next());
assertEquals(ROW5,rs.getString(1));
assertEquals(15,rs.getInt(2));
assertTrue (rs.next());
assertEquals(ROW6,rs.getString(1));
assertEquals(16,rs.getInt(2));
assertTrue (rs.next());
assertEquals(ROW7,rs.getString(1));
assertEquals(17,rs.getInt(2));
assertFalse(rs.next());
// () where
query = "SELECT t.eid, t.x + 9 FROM (SELECT entity_id eid, b_string b, a_byte + 1 x FROM aTable) AS t WHERE t.b = '" + C_VALUE + "'";
statement = conn.prepareStatement(query);
rs = statement.executeQuery();
assertTrue (rs.next());
assertEquals(ROW2,rs.getString(1));
assertEquals(12,rs.getInt(2));
assertTrue (rs.next());
assertEquals(ROW5,rs.getString(1));
assertEquals(15,rs.getInt(2));
assertTrue (rs.next());
assertEquals(ROW8,rs.getString(1));
assertEquals(18,rs.getInt(2));
assertFalse(rs.next());
// (where) where
query = "SELECT t.eid, t.x + 9 FROM (SELECT entity_id eid, b_string b, a_byte + 1 x FROM aTable WHERE a_byte + 1 < 9) AS t WHERE t.b = '" + C_VALUE + "'";
statement = conn.prepareStatement(query);
rs = statement.executeQuery();
assertTrue (rs.next());
assertEquals(ROW2,rs.getString(1));
assertEquals(12,rs.getInt(2));
assertTrue (rs.next());
assertEquals(ROW5,rs.getString(1));
assertEquals(15,rs.getInt(2));
assertFalse(rs.next());
// (groupby where) where
query = "SELECT t.a, t.c, t.m FROM (SELECT a_string a, count(*) c, max(a_byte) m FROM aTable WHERE a_byte != 8 GROUP BY a_string) AS t WHERE t.c > 1";
statement = conn.prepareStatement(query);
rs = statement.executeQuery();
assertTrue (rs.next());
assertEquals(A_VALUE,rs.getString(1));
assertEquals(4,rs.getInt(2));
assertEquals(4,rs.getInt(3));
assertTrue (rs.next());
assertEquals(B_VALUE,rs.getString(1));
assertEquals(3,rs.getInt(2));
assertEquals(7,rs.getInt(3));
assertFalse(rs.next());
// (groupby having where) where
query = "SELECT t.a, t.c, t.m FROM (SELECT a_string a, count(*) c, max(a_byte) m FROM aTable WHERE a_byte != 8 GROUP BY a_string HAVING count(*) >= 2) AS t WHERE t.a != '" + A_VALUE + "'";
statement = conn.prepareStatement(query);
rs = statement.executeQuery();
assertTrue (rs.next());
assertEquals(B_VALUE,rs.getString(1));
assertEquals(3,rs.getInt(2));
assertEquals(7,rs.getInt(3));
assertFalse(rs.next());
// (limit) where
query = "SELECT t.eid FROM (SELECT entity_id eid, b_string b FROM aTable LIMIT 2) AS t WHERE t.b = '" + C_VALUE + "'";
statement = conn.prepareStatement(query);
rs = statement.executeQuery();
assertTrue (rs.next());
assertEquals(ROW2,rs.getString(1));
assertFalse(rs.next());
// (count) where
query = "SELECT t.c FROM (SELECT count(*) c FROM aTable) AS t WHERE t.c > 0";
statement = conn.prepareStatement(query);
rs = statement.executeQuery();
assertTrue (rs.next());
assertEquals(9,rs.getInt(1));
assertFalse(rs.next());
} finally {
conn.close();
}
}
@Test
public void testDerivedTableWithGroupBy() throws Exception {
long ts = nextTimestamp();
Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 1));
Connection conn = DriverManager.getConnection(getUrl(), props);
try {
// () groupby having
String query = "SELECT t.a, count(*), max(t.s) FROM (SELECT a_string a, a_byte s FROM aTable WHERE a_byte != 8) AS t GROUP BY t.a HAVING count(*) > 1";
PreparedStatement statement = conn.prepareStatement(query);
ResultSet rs = statement.executeQuery();
assertTrue (rs.next());
assertEquals(A_VALUE,rs.getString(1));
assertEquals(4,rs.getInt(2));
assertEquals(4,rs.getInt(3));
assertTrue (rs.next());
assertEquals(B_VALUE,rs.getString(1));
assertEquals(3,rs.getInt(2));
assertEquals(7,rs.getInt(3));
assertFalse(rs.next());
// (groupby) groupby
query = "SELECT t.c, count(*) FROM (SELECT count(*) c FROM aTable GROUP BY a_string) AS t GROUP BY t.c";
statement = conn.prepareStatement(query);
rs = statement.executeQuery();
assertTrue (rs.next());
assertEquals(1,rs.getInt(1));
assertEquals(1,rs.getInt(2));
assertTrue (rs.next());
assertEquals(4,rs.getInt(1));
assertEquals(2,rs.getInt(2));
assertFalse(rs.next());
// (groupby) groupby orderby
query = "SELECT t.c, count(*) FROM (SELECT count(*) c FROM aTable GROUP BY a_string) AS t GROUP BY t.c ORDER BY count(*) DESC";
statement = conn.prepareStatement(query);
rs = statement.executeQuery();
assertTrue (rs.next());
assertEquals(4,rs.getInt(1));
assertEquals(2,rs.getInt(2));
assertTrue (rs.next());
assertEquals(1,rs.getInt(1));
assertEquals(1,rs.getInt(2));
assertFalse(rs.next());
// (groupby a, b orderby b) groupby a orderby a
query = "SELECT t.a, COLLECTDISTINCT(t.b) FROM (SELECT b_string b, a_string a FROM aTable GROUP BY a_string, b_string ORDER BY b_string) AS t GROUP BY t.a ORDER BY t.a DESC";
statement = conn.prepareStatement(query);
rs = statement.executeQuery();
assertTrue (rs.next());
assertEquals(C_VALUE,rs.getString(1));
String[] b = new String[1];
b[0] = E_VALUE;
Array array = conn.createArrayOf("VARCHAR", b);
assertEquals(array,rs.getArray(2));
assertTrue (rs.next());
assertEquals(B_VALUE,rs.getString(1));
b = new String[3];
b[0] = B_VALUE;
b[1] = C_VALUE;
b[2] = E_VALUE;
array = conn.createArrayOf("VARCHAR", b);
assertEquals(array,rs.getArray(2));
assertTrue (rs.next());
assertEquals(A_VALUE,rs.getString(1));
assertEquals(array,rs.getArray(2));
assertFalse(rs.next());
rs = conn.createStatement().executeQuery("EXPLAIN " + query);
assertEquals(plans[0], QueryUtil.getExplainPlan(rs));
// distinct b (groupby b, a) groupby a
query = "SELECT DISTINCT COLLECTDISTINCT(t.b) FROM (SELECT b_string b, a_string a FROM aTable GROUP BY b_string, a_string) AS t GROUP BY t.a";
statement = conn.prepareStatement(query);
rs = statement.executeQuery();
assertTrue (rs.next());
b = new String[1];
b[0] = E_VALUE;
array = conn.createArrayOf("VARCHAR", b);
assertEquals(array,rs.getArray(1));
assertTrue (rs.next());
b = new String[3];
b[0] = B_VALUE;
b[1] = C_VALUE;
b[2] = E_VALUE;
array = conn.createArrayOf("VARCHAR", b);
assertEquals(array,rs.getArray(1));
assertFalse(rs.next());
rs = conn.createStatement().executeQuery("EXPLAIN " + query);
assertEquals(plans[1], QueryUtil.getExplainPlan(rs));
} finally {
conn.close();
}
}
@Test
public void testDerivedTableWithOrderBy() throws Exception {
long ts = nextTimestamp();
Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 1));
Connection conn = DriverManager.getConnection(getUrl(), props);
try {
// (orderby)
String query = "SELECT t.eid FROM (SELECT entity_id eid, b_string b FROM aTable ORDER BY b, eid) AS t";
PreparedStatement statement = conn.prepareStatement(query);
ResultSet rs = statement.executeQuery();
assertTrue (rs.next());
assertEquals(ROW1,rs.getString(1));
assertTrue (rs.next());
assertEquals(ROW4,rs.getString(1));
assertTrue (rs.next());
assertEquals(ROW7,rs.getString(1));
assertTrue (rs.next());
assertEquals(ROW2,rs.getString(1));
assertTrue (rs.next());
assertEquals(ROW5,rs.getString(1));
assertTrue (rs.next());
assertEquals(ROW8,rs.getString(1));
assertTrue (rs.next());
assertEquals(ROW3,rs.getString(1));
assertTrue (rs.next());
assertEquals(ROW6,rs.getString(1));
assertTrue (rs.next());
assertEquals(ROW9,rs.getString(1));
assertFalse(rs.next());
// () orderby
query = "SELECT t.eid FROM (SELECT entity_id eid, b_string b FROM aTable) AS t ORDER BY t.b, t.eid";
statement = conn.prepareStatement(query);
rs = statement.executeQuery();
assertTrue (rs.next());
assertEquals(ROW1,rs.getString(1));
assertTrue (rs.next());
assertEquals(ROW4,rs.getString(1));
assertTrue (rs.next());
assertEquals(ROW7,rs.getString(1));
assertTrue (rs.next());
assertEquals(ROW2,rs.getString(1));
assertTrue (rs.next());
assertEquals(ROW5,rs.getString(1));
assertTrue (rs.next());
assertEquals(ROW8,rs.getString(1));
assertTrue (rs.next());
assertEquals(ROW3,rs.getString(1));
assertTrue (rs.next());
assertEquals(ROW6,rs.getString(1));
assertTrue (rs.next());
assertEquals(ROW9,rs.getString(1));
assertFalse(rs.next());
// (orderby) orderby
query = "SELECT t.eid FROM (SELECT entity_id eid, b_string b FROM aTable ORDER BY b, eid) AS t ORDER BY t.b DESC, t.eid DESC";
statement = conn.prepareStatement(query);
rs = statement.executeQuery();
assertTrue (rs.next());
assertEquals(ROW9,rs.getString(1));
assertTrue (rs.next());
assertEquals(ROW6,rs.getString(1));
assertTrue (rs.next());
assertEquals(ROW3,rs.getString(1));
assertTrue (rs.next());
assertEquals(ROW8,rs.getString(1));
assertTrue (rs.next());
assertEquals(ROW5,rs.getString(1));
assertTrue (rs.next());
assertEquals(ROW2,rs.getString(1));
assertTrue (rs.next());
assertEquals(ROW7,rs.getString(1));
assertTrue (rs.next());
assertEquals(ROW4,rs.getString(1));
assertTrue (rs.next());
assertEquals(ROW1,rs.getString(1));
assertFalse(rs.next());
// (limit) orderby
query = "SELECT t.eid FROM (SELECT entity_id eid, b_string b FROM aTable LIMIT 2) AS t ORDER BY t.b DESC, t.eid";
statement = conn.prepareStatement(query);
rs = statement.executeQuery();
assertTrue (rs.next());
assertEquals(ROW2,rs.getString(1));
assertTrue (rs.next());
assertEquals(ROW1,rs.getString(1));
assertFalse(rs.next());
} finally {
conn.close();
}
}
@Test
public void testDerivedTableWithLimit() throws Exception {
long ts = nextTimestamp();
Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 1));
Connection conn = DriverManager.getConnection(getUrl(), props);
try {
// (limit)
String query = "SELECT t.eid FROM (SELECT entity_id eid FROM aTable LIMIT 2) AS t";
PreparedStatement statement = conn.prepareStatement(query);
ResultSet rs = statement.executeQuery();
assertTrue (rs.next());
assertEquals(ROW1,rs.getString(1));
assertTrue (rs.next());
assertEquals(ROW2,rs.getString(1));
assertFalse(rs.next());
// () limit
query = "SELECT t.eid FROM (SELECT entity_id eid FROM aTable) AS t LIMIT 2";
statement = conn.prepareStatement(query);
rs = statement.executeQuery();
assertTrue (rs.next());
assertEquals(ROW1,rs.getString(1));
assertTrue (rs.next());
assertEquals(ROW2,rs.getString(1));
assertFalse(rs.next());
// (limit 2) limit 4
query = "SELECT t.eid FROM (SELECT entity_id eid FROM aTable LIMIT 2) AS t LIMIT 4";
statement = conn.prepareStatement(query);
rs = statement.executeQuery();
assertTrue (rs.next());
assertEquals(ROW1,rs.getString(1));
assertTrue (rs.next());
assertEquals(ROW2,rs.getString(1));
assertFalse(rs.next());
// (limit 4) limit 2
query = "SELECT t.eid FROM (SELECT entity_id eid FROM aTable LIMIT 4) AS t LIMIT 2";
statement = conn.prepareStatement(query);
rs = statement.executeQuery();
assertTrue (rs.next());
assertEquals(ROW1,rs.getString(1));
assertTrue (rs.next());
assertEquals(ROW2,rs.getString(1));
assertFalse(rs.next());
// limit ? limit ?
query = "SELECT t.eid FROM (SELECT entity_id eid FROM aTable LIMIT ?) AS t LIMIT ?";
statement = conn.prepareStatement(query);
statement.setInt(1, 4);
statement.setInt(2, 2);
rs = statement.executeQuery();
assertTrue (rs.next());
assertEquals(ROW1,rs.getString(1));
assertTrue (rs.next());
assertEquals(ROW2,rs.getString(1));
assertFalse(rs.next());
// (groupby orderby) limit
query = "SELECT a, s FROM (SELECT a_string a, sum(a_byte) s FROM aTable GROUP BY a_string ORDER BY sum(a_byte)) LIMIT 2";
statement = conn.prepareStatement(query);
rs = statement.executeQuery();
assertTrue (rs.next());
assertEquals(C_VALUE,rs.getString(1));
assertEquals(9,rs.getInt(2));
assertTrue (rs.next());
assertEquals(A_VALUE,rs.getString(1));
assertEquals(10,rs.getInt(2));
assertFalse(rs.next());
} finally {
conn.close();
}
}
@Test
public void testDerivedTableWithDistinct() throws Exception {
long ts = nextTimestamp();
Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 1));
Connection conn = DriverManager.getConnection(getUrl(), props);
try {
// (distinct)
String query = "SELECT * FROM (SELECT DISTINCT a_string, b_string FROM aTable) AS t WHERE t.b_string != '" + C_VALUE + "' ORDER BY t.b_string, t.a_string";
PreparedStatement statement = conn.prepareStatement(query);
ResultSet rs = statement.executeQuery();
assertTrue (rs.next());
assertEquals(A_VALUE,rs.getString(1));
assertEquals(B_VALUE,rs.getString(2));
assertTrue (rs.next());
assertEquals(B_VALUE,rs.getString(1));
assertEquals(B_VALUE,rs.getString(2));
assertTrue (rs.next());
assertEquals(A_VALUE,rs.getString(1));
assertEquals(E_VALUE,rs.getString(2));
assertTrue (rs.next());
assertEquals(B_VALUE,rs.getString(1));
assertEquals(E_VALUE,rs.getString(2));
assertTrue (rs.next());
assertEquals(C_VALUE,rs.getString(1));
assertEquals(E_VALUE,rs.getString(2));
assertFalse(rs.next());
// distinct ()
query = "SELECT DISTINCT t.a, t.b FROM (SELECT a_string a, b_string b FROM aTable) AS t WHERE t.b != '" + C_VALUE + "' ORDER BY t.b, t.a";
statement = conn.prepareStatement(query);
rs = statement.executeQuery();
assertTrue (rs.next());
assertEquals(A_VALUE,rs.getString(1));
assertEquals(B_VALUE,rs.getString(2));
assertTrue (rs.next());
assertEquals(B_VALUE,rs.getString(1));
assertEquals(B_VALUE,rs.getString(2));
assertTrue (rs.next());
assertEquals(A_VALUE,rs.getString(1));
assertEquals(E_VALUE,rs.getString(2));
assertTrue (rs.next());
assertEquals(B_VALUE,rs.getString(1));
assertEquals(E_VALUE,rs.getString(2));
assertTrue (rs.next());
assertEquals(C_VALUE,rs.getString(1));
assertEquals(E_VALUE,rs.getString(2));
assertFalse(rs.next());
// distinct (distinct)
query = "SELECT DISTINCT t.a FROM (SELECT DISTINCT a_string a, b_string b FROM aTable) AS t";
statement = conn.prepareStatement(query);
rs = statement.executeQuery();
assertTrue (rs.next());
assertEquals(A_VALUE,rs.getString(1));
assertTrue (rs.next());
assertEquals(B_VALUE,rs.getString(1));
assertTrue (rs.next());
assertEquals(C_VALUE,rs.getString(1));
assertFalse(rs.next());
// distinct (groupby)
query = "SELECT distinct t.c FROM (SELECT count(*) c FROM aTable GROUP BY a_string) AS t";
statement = conn.prepareStatement(query);
rs = statement.executeQuery();
assertTrue (rs.next());
assertEquals(1,rs.getInt(1));
assertTrue (rs.next());
assertEquals(4,rs.getInt(1));
assertFalse(rs.next());
// distinct (groupby) orderby
query = "SELECT distinct t.c FROM (SELECT count(*) c FROM aTable GROUP BY a_string) AS t ORDER BY t.c DESC";
statement = conn.prepareStatement(query);
rs = statement.executeQuery();
assertTrue (rs.next());
assertEquals(4,rs.getInt(1));
assertTrue (rs.next());
assertEquals(1,rs.getInt(1));
assertFalse(rs.next());
// distinct (limit)
query = "SELECT DISTINCT t.a, t.b FROM (SELECT a_string a, b_string b FROM aTable LIMIT 2) AS t";
statement = conn.prepareStatement(query);
rs = statement.executeQuery();
assertTrue (rs.next());
assertEquals(A_VALUE,rs.getString(1));
assertEquals(B_VALUE,rs.getString(2));
assertTrue (rs.next());
assertEquals(A_VALUE,rs.getString(1));
assertEquals(C_VALUE,rs.getString(2));
assertFalse(rs.next());
} finally {
conn.close();
}
}
@Test
public void testDerivedTableWithAggregate() throws Exception {
long ts = nextTimestamp();
Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 1));
Connection conn = DriverManager.getConnection(getUrl(), props);
try {
// (count)
String query = "SELECT * FROM (SELECT count(*) FROM aTable WHERE a_byte != 8) AS t";
PreparedStatement statement = conn.prepareStatement(query);
ResultSet rs = statement.executeQuery();
assertTrue (rs.next());
assertEquals(8,rs.getInt(1));
assertFalse(rs.next());
// count ()
query = "SELECT count(*) FROM (SELECT a_byte FROM aTable) AS t WHERE t.a_byte != 8";
statement = conn.prepareStatement(query);
rs = statement.executeQuery();
assertTrue (rs.next());
assertEquals(8,rs.getInt(1));
assertFalse(rs.next());
// count (distinct)
query = "SELECT count(*) FROM (SELECT DISTINCT a_string FROM aTable) AS t";
statement = conn.prepareStatement(query);
rs = statement.executeQuery();
assertTrue (rs.next());
assertEquals(3,rs.getInt(1));
assertFalse(rs.next());
// count (groupby)
query = "SELECT count(*) FROM (SELECT count(*) c FROM aTable GROUP BY a_string) AS t";
statement = conn.prepareStatement(query);
rs = statement.executeQuery();
assertTrue (rs.next());
assertEquals(3,rs.getInt(1));
assertFalse(rs.next());
// count (limit)
query = "SELECT count(*) FROM (SELECT entity_id FROM aTable LIMIT 2) AS t";
statement = conn.prepareStatement(query);
rs = statement.executeQuery();
assertTrue (rs.next());
assertEquals(2,rs.getInt(1));
assertFalse(rs.next());
} finally {
conn.close();
}
}
@Test
public void testDerivedTableWithJoin() throws Exception {
long ts = nextTimestamp();
Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 1));
Connection conn = DriverManager.getConnection(getUrl(), props);
try {
// groupby (join)
String query = "SELECT q.id1, count(q.id2) FROM (SELECT t1.entity_id id1, t2.entity_id id2, t2.a_byte b2"
+ " FROM aTable t1 JOIN aTable t2 ON t1.a_string = t2.b_string"
+ " WHERE t1.a_byte >= 8) AS q WHERE q.b2 != 5 GROUP BY q.id1";
PreparedStatement statement = conn.prepareStatement(query);
ResultSet rs = statement.executeQuery();
assertTrue (rs.next());
assertEquals(ROW8,rs.getString(1));
assertEquals(3,rs.getInt(2));
assertTrue (rs.next());
assertEquals(ROW9,rs.getString(1));
assertEquals(2,rs.getInt(2));
assertFalse(rs.next());
// distinct (join)
query = "SELECT DISTINCT q.id1 FROM (SELECT t1.entity_id id1, t2.a_byte b2"
+ " FROM aTable t1 JOIN aTable t2 ON t1.a_string = t2.b_string"
+ " WHERE t1.a_byte >= 8) AS q WHERE q.b2 != 5";
statement = conn.prepareStatement(query);
rs = statement.executeQuery();
assertTrue (rs.next());
assertEquals(ROW8,rs.getString(1));
assertTrue (rs.next());
assertEquals(ROW9,rs.getString(1));
assertFalse(rs.next());
// count (join)
query = "SELECT COUNT(*) FROM (SELECT t2.a_byte b2"
+ " FROM aTable t1 JOIN aTable t2 ON t1.a_string = t2.b_string"
+ " WHERE t1.a_byte >= 8) AS q WHERE q.b2 != 5";
statement = conn.prepareStatement(query);
rs = statement.executeQuery();
assertTrue (rs.next());
assertEquals(5,rs.getInt(1));
assertFalse(rs.next());
} finally {
conn.close();
}
}
@Test
public void testNestedDerivedTable() throws Exception {
long ts = nextTimestamp();
Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 1));
Connection conn = DriverManager.getConnection(getUrl(), props);
try {
// select(select(select))
String query = "SELECT q.id, q.x10 * 10 FROM (SELECT t.eid id, t.x + 9 x10, t.astr a, t.bstr b FROM (SELECT entity_id eid, a_string astr, b_string bstr, a_byte + 1 x FROM aTable WHERE a_byte + 1 < ?) AS t ORDER BY b, id) AS q WHERE q.a = ? OR q.b = ? OR q.b = ?";
PreparedStatement statement = conn.prepareStatement(query);
statement.setInt(1, 9);
statement.setString(2, A_VALUE);
statement.setString(3, C_VALUE);
statement.setString(4, E_VALUE);
ResultSet rs = statement.executeQuery();
assertTrue (rs.next());
assertEquals(ROW1,rs.getString(1));
assertEquals(110,rs.getInt(2));
assertTrue (rs.next());
assertEquals(ROW4,rs.getString(1));
assertEquals(140,rs.getInt(2));
assertTrue (rs.next());
assertEquals(ROW2,rs.getString(1));
assertEquals(120,rs.getInt(2));
assertTrue (rs.next());
assertEquals(ROW5,rs.getString(1));
assertEquals(150,rs.getInt(2));
assertTrue (rs.next());
assertEquals(ROW3,rs.getString(1));
assertEquals(130,rs.getInt(2));
assertTrue (rs.next());
assertEquals(ROW6,rs.getString(1));
assertEquals(160,rs.getInt(2));
assertFalse(rs.next());
// select(select(select) join (select(select)))
query = "SELECT q1.id, q2.id FROM (SELECT t.eid id, t.astr a, t.bstr b FROM (SELECT entity_id eid, a_string astr, b_string bstr, a_byte abyte FROM aTable) AS t WHERE t.abyte >= ?) AS q1"
+ " JOIN (SELECT t.eid id, t.astr a, t.bstr b, t.abyte x FROM (SELECT entity_id eid, a_string astr, b_string bstr, a_byte abyte FROM aTable) AS t) AS q2 ON q1.a = q2.b"
+ " WHERE q2.x != ? ORDER BY q1.id, q2.id DESC";
statement = conn.prepareStatement(query);
statement.setInt(1, 8);
statement.setInt(2, 5);
rs = statement.executeQuery();
assertTrue (rs.next());
assertEquals(ROW8,rs.getString(1));
assertEquals(ROW7,rs.getString(2));
assertTrue (rs.next());
assertEquals(ROW8,rs.getString(1));
assertEquals(ROW4,rs.getString(2));
assertTrue (rs.next());
assertEquals(ROW8,rs.getString(1));
assertEquals(ROW1,rs.getString(2));
assertTrue (rs.next());
assertEquals(ROW9,rs.getString(1));
assertEquals(ROW8,rs.getString(2));
assertTrue (rs.next());
assertEquals(ROW9,rs.getString(1));
assertEquals(ROW2,rs.getString(2));
assertFalse(rs.next());
} finally {
conn.close();
}
}
}
| |
package test.gov.nih.nci.security.threadsafe;
import gov.nih.nci.security.AuthorizationManager;
import gov.nih.nci.security.SecurityServiceProvider;
/**
*
* CSMAPI MySQL Deadlock Issue Test.
* - Use PrimeCSMData.java to prime the database for this Test.
*
* @author Vijay
*
*/
public class CSMAPIMySQLDeadLockTest {
String sessionName;
int innerLoopCount = 5;
int outerLoopCount = 10;
boolean showAllLogs = false;
AuthorizationManager am = null;
RandomIntGenerator randomUser = new RandomIntGenerator(2, 11);
RandomIntGenerator randomUser2 = new RandomIntGenerator(2, 11);
RandomIntGenerator randomGroup = new RandomIntGenerator(2, 10);
RandomIntGenerator randomProtectionElement = new RandomIntGenerator(2, 10);
RandomIntGenerator randomProtectionGroup= new RandomIntGenerator(2, 10);
RandomIntGenerator randomPrivilege = new RandomIntGenerator(2, 12);
RandomIntGenerator randomRole= new RandomIntGenerator(2, 5);
public CSMAPIMySQLDeadLockTest(String sessionName) {
this.sessionName = sessionName;
}
public static void main(String[] args) {
CSMAPIMySQLDeadLockTest sc = new CSMAPIMySQLDeadLockTest(
"TestSession");
sc.doWork();
}
public void startSession() {
try {
System.out.println(this.sessionName +": StartSession: Sesion is starting");
am = SecurityServiceProvider.getAuthorizationManager("security");
if (am == null) {
throw new Exception();
}
am = (AuthorizationManager) am;
System.out.println(this.sessionName + ": StartSession: Got Managers");
} catch (Exception ex) {
System.out.println(this.sessionName + " StartSession: Could not initialize the managers");
ex.printStackTrace();
System.exit(0);
}
}
public void doWork() {
startSession();
/*
* The Goal of this test is to do manipulations that include a assigning
* or associating User/PE/PGs etc to verify if there are any Deadlock
* issues with MySQL.
*
* Below are some associations and manipulations. They should be in any order or
* fashion.
*
*/
System.out.println(" assignGroupRoleToProtectionGroup");
// assignGroupRoleToProtectionGroup();
System.out.println(" addGroupRoleToProtectionGroup");
addGroupRoleToProtectionGroup();
System.out.println(" assignGroupsToUser");
// assignGroupsToUser();
System.out.println(" addGroupsToUser");
addGroupsToUser();
System.out.println(" assignOwners");
// assignOwners();
System.out.println(" addOwners");
addOwners();
System.out.println(" assignParentProtectionGroup");
// assignParentProtectionGroup() ;
System.out.println(" assignPrivilegesToRole");
// assignPrivilegesToRole();
System.out.println(" addPrivilegesToRole");
addPrivilegesToRole();
System.out.println(" assignProtectionElement");
assignProtectionElement();
System.out.println(" assignProtectionElements");
// assignProtectionElements();
System.out.println(" assignProtectionElements");
addProtectionElements();
System.out.println(" assignToProtectionGroups");
// assignToProtectionGroups();
System.out.println(" addToProtectionGroups");
addToProtectionGroups();
System.out.println(" assignUserRoleToProtectionGroup");
// assignUserRoleToProtectionGroup();
System.out.println(" addUserRoleToProtectionGroup");
addUserRoleToProtectionGroup();
System.out.println(" assignUsersToGroup");
// assignUsersToGroup();
System.out.println(" addUsersToGroup");
addUsersToGroup();
System.out.println(" assignUserToGroup");
assignUserToGroup();
}
private void assignGroupRoleToProtectionGroup() {
String pgId = String.valueOf(randomProtectionGroup.draw());
String groupId = String.valueOf(randomGroup.draw());
String roleId = String.valueOf(randomRole.draw());
try {
for (int loopCount = 0; loopCount < innerLoopCount; loopCount++) {
String[] roleIds = new String[1];
for (int count = 0; count < outerLoopCount; count++) {
pgId = String.valueOf(randomProtectionGroup.draw() - 1);
groupId = String.valueOf(randomGroup.draw() - 1);
roleId = String.valueOf(randomRole.draw() - 1);
roleIds[0]=roleId;
am.assignGroupRoleToProtectionGroup(pgId, groupId, roleIds);
}
}
} catch (Exception e) {
e.printStackTrace(); }
}
private void addGroupRoleToProtectionGroup() {
String pgId = String.valueOf(randomProtectionGroup.draw());
String groupId = String.valueOf(randomGroup.draw());
String roleId = String.valueOf(randomRole.draw());
try {
for (int loopCount = 0; loopCount < innerLoopCount; loopCount++) {
String[] roleIds = new String[1];
for (int count = 0; count < outerLoopCount; count++) {
pgId = String.valueOf(randomProtectionGroup.draw() - 1);
groupId = String.valueOf(randomGroup.draw() - 1);
roleId = String.valueOf(randomRole.draw() - 1);
roleIds[0]=roleId;
am.addGroupRoleToProtectionGroup(pgId, groupId, roleIds);
}
}
} catch (Exception e) {
e.printStackTrace(); }
}
private void assignGroupsToUser() {
String userId = String.valueOf(randomUser.draw());
String groupId = String.valueOf(randomGroup.draw());
try {
for (int loopCount = 0; loopCount < innerLoopCount; loopCount++) {
String[] groupIds = new String[1];
for (int count = 0; count < outerLoopCount; count++) {
userId = String.valueOf(randomUser.draw() - 1);
groupId = String.valueOf(randomGroup.draw() - 1);
groupIds[0] = groupId;
am.assignGroupsToUser(userId, groupIds);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void addGroupsToUser() {
String userId = String.valueOf(randomUser.draw());
String groupId = String.valueOf(randomGroup.draw());
try {
for (int loopCount = 0; loopCount < innerLoopCount; loopCount++) {
String[] groupIds = new String[1];
for (int count = 0; count < outerLoopCount; count++) {
userId = String.valueOf(randomUser.draw() - 1);
groupId = String.valueOf(randomGroup.draw() - 1);
groupIds[0] = groupId;
am.addGroupsToUser(userId, groupIds);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void assignUserToGroup() {
String userId = String.valueOf(randomProtectionElement.draw() );
String gId = String.valueOf(randomProtectionElement.draw() );
try {
for (int loopCount = 0; loopCount < innerLoopCount; loopCount++) {
String[] pgIds = new String[1];
for (int count = 0; count < outerLoopCount; count++) {
userId = String.valueOf(randomUser.draw()-2 );
gId = String.valueOf(randomGroup.draw()-1 );
am.assignUserToGroup("TestUserLoginName"+userId, "TestGroupName"+gId);
}
}
} catch (Exception e) {
e.printStackTrace(); }
}
private void assignUserRoleToProtectionGroup() {
String userId = String.valueOf(randomUser.draw() );
String pgId = String.valueOf(randomProtectionGroup.draw() );
String roleId = String.valueOf(randomRole.draw() );
try {
for (int loopCount = 0; loopCount < innerLoopCount; loopCount++) {
String[] roleIds = new String[1];
for (int count = 0; count < outerLoopCount; count++) {
userId = String.valueOf(randomUser.draw() - 1);
pgId = String.valueOf(randomProtectionGroup.draw() - 1);
roleId = String.valueOf(randomRole.draw() - 1);
roleIds[0]=roleId;
am.assignUserRoleToProtectionGroup(userId,roleIds, pgId);
}
}
} catch (Exception e) {
e.printStackTrace(); }
}
private void addUserRoleToProtectionGroup() {
String userId = String.valueOf(randomUser.draw() );
String pgId = String.valueOf(randomProtectionGroup.draw() );
String roleId = String.valueOf(randomRole.draw() );
try {
for (int loopCount = 0; loopCount < innerLoopCount; loopCount++) {
String[] roleIds = new String[1];
for (int count = 0; count < outerLoopCount; count++) {
userId = String.valueOf(randomUser.draw() - 1);
pgId = String.valueOf(randomProtectionGroup.draw() - 1);
roleId = String.valueOf(randomRole.draw() - 1);
roleIds[0]=roleId;
am.addUserRoleToProtectionGroup(userId,roleIds, pgId);
}
}
} catch (Exception e) {
e.printStackTrace(); }
}
private void assignToProtectionGroups() {
String pgId = String.valueOf(randomProtectionElement.draw() );
String peId = String.valueOf(randomProtectionGroup.draw() );
try {
for (int loopCount = 0; loopCount < innerLoopCount; loopCount++) {
String[] pgIds = new String[1];
for (int count = 0; count < outerLoopCount; count++) {
pgId = String.valueOf(randomProtectionGroup.draw() - 1);
peId = String.valueOf(randomProtectionElement.draw() - 1);
pgIds[0]=pgId;
am.assignToProtectionGroups(peId, pgIds);
}
}
} catch (Exception e) {
e.printStackTrace(); }
}
private void addToProtectionGroups() {
String pgId = String.valueOf(randomProtectionElement.draw() );
String peId = String.valueOf(randomProtectionGroup.draw() );
try {
for (int loopCount = 0; loopCount < innerLoopCount; loopCount++) {
String[] pgIds = new String[1];
for (int count = 0; count < outerLoopCount; count++) {
pgId = String.valueOf(randomProtectionGroup.draw() - 1);
peId = String.valueOf(randomProtectionElement.draw() - 1);
pgIds[0]=pgId;
am.addToProtectionGroups(peId, pgIds);
}
}
} catch (Exception e) {
e.printStackTrace(); }
}
private void assignProtectionElements() {
String pgId = String.valueOf(randomProtectionGroup.draw());
String peId = String.valueOf(randomProtectionElement.draw());
try {
for (int loopCount = 0; loopCount < innerLoopCount; loopCount++) {
String[] peIds = new String[1];
for (int count = 0; count < outerLoopCount; count++) {
pgId = String.valueOf(randomProtectionGroup.draw() - 2);
peId = String.valueOf(randomProtectionElement.draw() - 1);
peIds[0]=peId;
am.assignProtectionElements(pgId, peIds);
}
}
} catch (Exception e) {
e.printStackTrace(); }
}
private void addProtectionElements() {
String pgId = String.valueOf(randomProtectionGroup.draw());
String peId = String.valueOf(randomProtectionElement.draw());
try {
for (int loopCount = 0; loopCount < innerLoopCount; loopCount++) {
String[] peIds = new String[1];
for (int count = 0; count < outerLoopCount; count++) {
pgId = String.valueOf(randomProtectionGroup.draw() - 1);
peId = String.valueOf(randomProtectionElement.draw() - 1);
peIds[0]=peId;
am.addProtectionElements(pgId, peIds);
}
}
} catch (Exception e) {
// e.printStackTrace();
}
}
private void assignProtectionElement() {
String pgId = String.valueOf(randomProtectionGroup.draw());
String peId = String.valueOf(randomProtectionElement.draw());
for (int loopCount = 0; loopCount < innerLoopCount; loopCount++) {
for (int count = 0; count < outerLoopCount; count++) {
pgId = String.valueOf(randomProtectionGroup.draw() - 2);
peId = String.valueOf(randomProtectionElement.draw() - 1);
try {
am.assignProtectionElement("TestProtectionGroupName"+pgId, "TestProtectionElementObjectID"+peId);
} catch (Exception e) {
//e.printStackTrace();
}
}
}
}
private void assignParentProtectionGroup() {
String pgId = String.valueOf(randomRole.draw());
String parentPgId = String.valueOf(randomProtectionElement.draw());
try {
for (int loopCount = 0; loopCount < innerLoopCount; loopCount++) {
for (int count = 0; count < outerLoopCount; count++) {
pgId = String.valueOf(randomProtectionGroup.draw() );
parentPgId = String.valueOf(randomProtectionGroup.draw());
am.assignParentProtectionGroup(pgId, parentPgId);
}
}
} catch (Exception e) {
e.printStackTrace(); }
}
private void assignPrivilegesToRole() {
String roleId = String.valueOf(randomRole.draw());
String privId = String.valueOf(randomProtectionElement.draw());
try {
for (int loopCount = 0; loopCount < innerLoopCount; loopCount++) {
String[] privIds = new String[1];
for (int count = 0; count < outerLoopCount; count++) {
roleId = String.valueOf(randomRole.draw() - 1);
privId = String.valueOf(randomPrivilege.draw() - 1);
privIds[0] = privId;
am.assignPrivilegesToRole(roleId, privIds);
}
}
} catch (Exception e) {
e.printStackTrace(); }
}
private void addPrivilegesToRole() {
String roleId = String.valueOf(randomRole.draw());
String privId = String.valueOf(randomProtectionElement.draw());
try {
for (int loopCount = 0; loopCount < innerLoopCount; loopCount++) {
String[] privIds = new String[1];
for (int count = 0; count < outerLoopCount; count++) {
roleId = String.valueOf(randomRole.draw() - 1);
privId = String.valueOf(randomPrivilege.draw() - 1);
privIds[0] = privId;
am.addPrivilegesToRole(roleId, privIds);
}
}
} catch (Exception e) {
e.printStackTrace(); }
}
private void assignOwners() {
String userId = String.valueOf(randomUser.draw());
String peId = String.valueOf(randomProtectionElement.draw());
try {
for (int loopCount = 0; loopCount < innerLoopCount; loopCount++) {
String[] userIds = new String[1];
for (int count = 0; count < outerLoopCount; count++) {
userId = String.valueOf(randomUser.draw() - 1);
userIds[0] = userId;
peId = String.valueOf(randomProtectionElement.draw() - 1);
am.assignOwners(peId, userIds);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void addOwners() {
String userId = String.valueOf(randomUser.draw());
String peId = String.valueOf(randomProtectionElement.draw());
try {
for (int loopCount = 0; loopCount < innerLoopCount; loopCount++) {
String[] userIds = new String[1];
for (int count = 0; count < outerLoopCount; count++) {
userId = String.valueOf(randomUser.draw() - 1);
userIds[0] = userId;
peId = String.valueOf(randomProtectionElement.draw() - 1);
am.addOwners(peId, userIds);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void assignUsersToGroup() {
String userId = String.valueOf(randomUser.draw());
String groupId = String.valueOf(randomGroup.draw());
try {
for (int loopCount = 0; loopCount < innerLoopCount; loopCount++) {
String[] userIds = new String[1];
for (int count = 0; count < outerLoopCount; count++) {
userId = String.valueOf(randomUser.draw() - 1);
groupId = String.valueOf(randomGroup.draw() - 1);
userIds[0] = userId;
am.assignUsersToGroup(groupId, userIds);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void addUsersToGroup() {
String userId = String.valueOf(randomUser.draw());
String groupId = String.valueOf(randomGroup.draw());
try {
for (int loopCount = 0; loopCount < innerLoopCount; loopCount++) {
String[] userIds = new String[1];
for (int count = 0; count < outerLoopCount; count++) {
userId = String.valueOf(randomUser.draw() - 1);
groupId = String.valueOf(randomGroup.draw() - 1);
userIds[0] = userId;
am.addUsersToGroup(groupId, userIds);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void removeOwnerForProtectionElement() {
String userId = String.valueOf(randomUser.draw());
String peId = String.valueOf(randomProtectionElement.draw());
try {
for (int loopCount = 0; loopCount < innerLoopCount; loopCount++) {
String[] userIds = new String[1];
for (int count = 0; count < outerLoopCount; count++) {
userId = String.valueOf(randomUser.draw() - 1);
userIds[0] = userId;
peId = String.valueOf(randomProtectionElement.draw() - 1);
am.removeOwnerForProtectionElement(peId, userIds);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
| |
/*
* 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.jmeter.threads.gui;
import static org.apache.jmeter.util.JMeterUtils.labelFor;
import java.awt.BorderLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.BorderFactory;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import org.apache.jmeter.control.LoopController;
import org.apache.jmeter.control.gui.LoopControlPanel;
import org.apache.jmeter.gui.TestElementMetadata;
import org.apache.jmeter.testelement.TestElement;
import org.apache.jmeter.testelement.property.BooleanProperty;
import org.apache.jmeter.threads.AbstractThreadGroup;
import org.apache.jmeter.threads.ThreadGroup;
import org.apache.jmeter.util.JMeterUtils;
import net.miginfocom.swing.MigLayout;
@TestElementMetadata(labelResource = "threadgroup")
public class ThreadGroupGui extends AbstractThreadGroupGui implements ItemListener {
private static final long serialVersionUID = 240L;
private LoopControlPanel loopPanel;
private static final String THREAD_NAME = "Thread Field";
private static final String RAMP_NAME = "Ramp Up Field";
private final JTextField threadInput = new JTextField();
private final JTextField rampInput = new JTextField();
private final boolean showDelayedStart;
private JCheckBox delayedStart;
private final JCheckBox scheduler = new JCheckBox(JMeterUtils.getResString("scheduler"));
private final JTextField duration = new JTextField();
private final JLabel durationLabel = labelFor(duration, "duration");
private final JTextField delay = new JTextField(); // Relative start-up time
private final JLabel delayLabel = labelFor(delay, "delay");
private final JCheckBox sameUserBox =
new JCheckBox(JMeterUtils.getResString("threadgroup_same_user"));
public ThreadGroupGui() {
this(true);
}
public ThreadGroupGui(boolean showDelayedStart) {
super();
this.showDelayedStart = showDelayedStart;
init();
initGui();
}
@Override
public TestElement createTestElement() {
ThreadGroup tg = new ThreadGroup();
modifyTestElement(tg);
return tg;
}
/**
* Modifies a given TestElement to mirror the data in the gui components.
*
* @see org.apache.jmeter.gui.JMeterGUIComponent#modifyTestElement(TestElement)
*/
@Override
public void modifyTestElement(TestElement tg) {
super.configureTestElement(tg);
if (tg instanceof AbstractThreadGroup) {
((AbstractThreadGroup) tg).setSamplerController((LoopController) loopPanel.createTestElement());
}
tg.setProperty(AbstractThreadGroup.NUM_THREADS, threadInput.getText());
tg.setProperty(ThreadGroup.RAMP_TIME, rampInput.getText());
if (showDelayedStart) {
tg.setProperty(ThreadGroup.DELAYED_START, delayedStart.isSelected(), false);
}
tg.setProperty(new BooleanProperty(ThreadGroup.SCHEDULER, scheduler.isSelected()));
tg.setProperty(ThreadGroup.DURATION, duration.getText());
tg.setProperty(ThreadGroup.DELAY, delay.getText());
tg.setProperty(AbstractThreadGroup.IS_SAME_USER_ON_NEXT_ITERATION,sameUserBox.isSelected());
}
@Override
public void configure(TestElement tg) {
super.configure(tg);
threadInput.setText(tg.getPropertyAsString(AbstractThreadGroup.NUM_THREADS));
rampInput.setText(tg.getPropertyAsString(ThreadGroup.RAMP_TIME));
loopPanel.configure((TestElement) tg.getProperty(AbstractThreadGroup.MAIN_CONTROLLER).getObjectValue());
if (showDelayedStart) {
delayedStart.setSelected(tg.getPropertyAsBoolean(ThreadGroup.DELAYED_START));
}
scheduler.setSelected(tg.getPropertyAsBoolean(ThreadGroup.SCHEDULER));
toggleSchedulerFields(scheduler.isSelected());
duration.setText(tg.getPropertyAsString(ThreadGroup.DURATION));
delay.setText(tg.getPropertyAsString(ThreadGroup.DELAY));
final boolean isSameUser = tg.getPropertyAsBoolean(AbstractThreadGroup.IS_SAME_USER_ON_NEXT_ITERATION, true);
sameUserBox.setSelected(isSameUser);
}
@Override
public void itemStateChanged(ItemEvent ie) {
if (ie.getItem().equals(scheduler)) {
toggleSchedulerFields(scheduler.isSelected());
}
}
/**
* @param enable boolean used to enable/disable fields related to scheduler
*/
private void toggleSchedulerFields(boolean enable) {
duration.setEnabled(enable);
durationLabel.setEnabled(enable);
delay.setEnabled(enable);
delayLabel.setEnabled(enable);
}
private JPanel createControllerPanel() {
loopPanel = new LoopControlPanel(false);
LoopController looper = (LoopController) loopPanel.createTestElement();
looper.setLoops(1);
loopPanel.configure(looper);
return loopPanel;
}
@Override
public String getLabelResource() {
return "threadgroup"; // $NON-NLS-1$
}
@Override
public void clearGui(){
super.clearGui();
initGui();
}
// Initialise the gui field values
private void initGui(){
threadInput.setText("1"); // $NON-NLS-1$
rampInput.setText("1"); // $NON-NLS-1$
loopPanel.clearGui();
if (showDelayedStart) {
delayedStart.setSelected(false);
}
scheduler.setSelected(false);
delay.setText(""); // $NON-NLS-1$
duration.setText(""); // $NON-NLS-1$
sameUserBox.setSelected(true);
}
private void init() { // WARNING: called from ctor so must not be overridden (i.e. must be private or final)
// THREAD PROPERTIES
JPanel threadPropsPanel = new JPanel(new MigLayout("fillx, wrap 2", "[][fill,grow]"));
threadPropsPanel.setBorder(BorderFactory.createTitledBorder(
JMeterUtils.getResString("thread_properties"))); // $NON-NLS-1$
// NUMBER OF THREADS
threadPropsPanel.add(labelFor(threadInput, "number_of_threads")); // $NON-NLS-1$
threadInput.setName(THREAD_NAME);
threadPropsPanel.add(threadInput);
// RAMP-UP
threadPropsPanel.add(labelFor(rampInput, "ramp_up"));
rampInput.setName(RAMP_NAME);
threadPropsPanel.add(rampInput);
// LOOP COUNT
LoopControlPanel loopController = (LoopControlPanel) createControllerPanel();
threadPropsPanel.add(loopController.getLoopsLabel(), "split 2");
threadPropsPanel.add(loopController.getInfinite(), "gapleft push");
threadPropsPanel.add(loopController.getLoops());
threadPropsPanel.add(sameUserBox, "span 2");
if (showDelayedStart) {
delayedStart = new JCheckBox(JMeterUtils.getResString("delayed_start")); // $NON-NLS-1$
threadPropsPanel.add(delayedStart, "span 2");
}
scheduler.addItemListener(this);
threadPropsPanel.add(scheduler, "span 2");
threadPropsPanel.add(durationLabel);
threadPropsPanel.add(duration);
threadPropsPanel.add(delayLabel);
threadPropsPanel.add(delay);
add(threadPropsPanel, BorderLayout.CENTER);
}
}
| |
/**
* Copyright (c) 2014,
* Charles Prud'homme (TASC, INRIA Rennes, LINA CNRS UMR 6241),
* Jean-Guillaume Fages (COSLING S.A.S.).
* 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 the <organization> 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 <COPYRIGHT HOLDER> 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 org.chocosolver.util.objects.graphs;
import gnu.trove.map.hash.THashMap;
import org.chocosolver.solver.Solver;
import org.chocosolver.util.objects.setDataStructures.ISet;
import org.chocosolver.util.objects.setDataStructures.SetFactory;
import org.chocosolver.util.objects.setDataStructures.SetType;
/**
* Directed graph implementation : arcs are indexed per endpoints
* @author Jean-Guillaume Fages, Xavier Lorca
*/
public class DirectedGraph implements IGraph {
//***********************************************************************************
// VARIABLES
//***********************************************************************************
ISet[] successors;
ISet[] predecessors;
ISet nodes;
int n;
SetType type;
//***********************************************************************************
// CONSTRUCTORS
//***********************************************************************************
/**
* Creates an empty graph.
* Allocates memory for n nodes (but they should then be added explicitly,
* unless allNodes is true).
*
* @param n maximum number of nodes
* @param type data structure to use for representing node successors and predecessors
* @param allNodes true iff all nodes must always remain present in the graph.
* i.e. The node set is fixed to [0,n-1] and will never change
*/
public DirectedGraph(int n, SetType type, boolean allNodes) {
this.type = type;
this.n = n;
predecessors = new ISet[n];
successors = new ISet[n];
for (int i = 0; i < n; i++) {
predecessors[i] = SetFactory.makeSet(type, n);
successors[i] = SetFactory.makeSet(type, n);
}
if (allNodes) {
this.nodes = SetFactory.makeFullSet(n);
} else {
this.nodes = SetFactory.makeBitSet(n);
}
}
/**
* Creates an empty backtrable graph of n nodes
* Allocates memory for n nodes (but they should then be added explicitly,
* unless allNodes is true).
*
* @param solver solver providing the backtracking environment
* @param n maximum number of nodes
* @param type data structure to use for representing node successors and predecessors
* @param allNodes true iff all nodes must always remain present in the graph
*/
public DirectedGraph(Solver solver, int n, SetType type, boolean allNodes) {
this.n = n;
this.type = type;
predecessors = new ISet[n];
successors = new ISet[n];
for (int i = 0; i < n; i++) {
predecessors[i] = SetFactory.makeStoredSet(type, n, solver);
successors[i] = SetFactory.makeStoredSet(type, n, solver);
}
if (allNodes) {
this.nodes = SetFactory.makeFullSet(n);
} else {
this.nodes = SetFactory.makeStoredSet(SetType.BITSET, n, solver);
}
}
//***********************************************************************************
// METHODS
//***********************************************************************************
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("nodes : \n").append(nodes).append("\n");
sb.append("successors : \n");
for (int i = nodes.getFirstElement(); i >= 0; i = nodes.getNextElement()) {
sb.append(i).append(" -> {");
for (int j = successors[i].getFirstElement(); j >= 0; j = successors[i].getNextElement()) {
sb.append(j).append(" ");
}
sb.append("}\n");
}
return sb.toString();
}
@Override
public int getNbMaxNodes() {
return n;
}
@Override
public ISet getNodes() {
return nodes;
}
@Override
public SetType getType() {
return type;
}
@Override
public boolean addNode(int x) {
return !nodes.contain(x) && nodes.add(x);
}
@Override
public boolean removeNode(int x) {
if (nodes.remove(x)) {
for (int j = successors[x].getFirstElement(); j >= 0; j = successors[x].getNextElement()) {
predecessors[j].remove(x);
}
successors[x].clear();
for (int j = predecessors[x].getFirstElement(); j >= 0; j = predecessors[x].getNextElement()) {
successors[j].remove(x);
}
predecessors[x].clear();
return true;
}
assert (predecessors[x].getSize() == 0) : "incoherent directed graph";
assert (successors[x].getSize() == 0) : "incoherent directed graph";
return false;
}
/**
* remove arc (from,to) from the graph
*
* @param from a node index
* @param to a node index
* @return true iff arc (from,to) was in the graph
*/
public boolean removeArc(int from, int to) {
if (successors[from].contain(to)) {
assert (predecessors[to].contain(from)) : "incoherent directed graph";
successors[from].remove(to);
predecessors[to].remove(from);
return true;
}
return false;
}
/**
* Test whether arc (from,to) exists or not in the graph
*
* @param from a node index
* @param to a node index
* @return true iff arc (from,to) exists in the graph
*/
public boolean arcExists(int from, int to) {
if (successors[from].contain(to)) {
assert (predecessors[to].contain(from)) : "incoherent directed graph";
return true;
}
return false;
}
@Override
public boolean isArcOrEdge(int from, int to) {
return arcExists(from, to);
}
@Override
public boolean isDirected() {
return true;
}
/**
* add arc (from,to) to the graph
*
* @param from a node index
* @param to a node index
* @return true iff arc (from,to) was not already in the graph
*/
public boolean addArc(int from, int to) {
addNode(from);
addNode(to);
if (!successors[from].contain(to)) {
assert (!predecessors[to].contain(from)) : "incoherent directed graph";
successors[from].add(to);
predecessors[to].add(from);
return true;
}
return false;
}
/**
* Get successors of node x
*
* @param x node index
* @return successors of x
*/
public ISet getSuccOf(int x) {
return successors[x];
}
@Override
public ISet getSuccOrNeighOf(int x) {
return successors[x];
}
/**
* Get predecessors of node x
*
* @param x node index
* @return predecessors of x
*/
public ISet getPredOf(int x) {
return predecessors[x];
}
@Override
public ISet getPredOrNeighOf(int x) {
return predecessors[x];
}
@Override
public void duplicate(Solver solver, THashMap<Object, Object> identitymap) {
throw new UnsupportedOperationException("Cannot duplicate DirectedGraph yet");
}
}
| |
/*
* Copyright 2016 Attribyte, 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.attribyte.relay.wp;
import com.google.common.base.Charsets;
import com.google.common.base.MoreObjects;
import com.google.common.base.Strings;
import com.google.common.hash.HashCode;
import com.google.common.hash.HashFunction;
import com.google.common.hash.Hasher;
import com.google.common.hash.Hashing;
import com.google.common.primitives.Longs;
import com.google.protobuf.ByteString;
import org.attribyte.wp.model.Meta;
import org.attribyte.wp.model.Post;
import org.joda.time.DateTimeZone;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.ISODateTimeFormat;
import java.io.IOException;
import java.util.Comparator;
/**
* Post metadata (id, timestamp) for serializing state.
*/
public class PostMeta {
/**
* Post metadata that represents zero time.
*/
public static final PostMeta ZERO = new PostMeta(0L, 0L);
/**
* Creates post metadata with no fingerprint.
* @param id The post id.
* @param lastModifiedMillis The last modified timestamp.
*/
public PostMeta(final long id, final long lastModifiedMillis) {
this.id = id;
this.lastModifiedMillis = lastModifiedMillis;
this.fingerprint = null;
}
/**
* Creates post metadata with a fingerprint.
* @param id The post id.
* @param lastModifiedMillis The last modified timestamp.
* @param fingerprint The fingerprint.
*/
public PostMeta(final long id, final long lastModifiedMillis, final HashCode fingerprint) {
this.id = id;
this.lastModifiedMillis = lastModifiedMillis;
this.fingerprint = fingerprint;
}
/**
* Creates post metadata with a fingerprint from a post.
* @param post The post.
*/
public PostMeta(final Post post) {
this(post.id, post.modifiedTimestamp, fingerprint(post));
}
/**
* @return Does this metadata hava a modified time in the future?
*/
public final boolean isFutureModified() {
return lastModifiedMillis > System.currentTimeMillis();
}
/**
* Creates a copy of this post meta with the modified timestamp set
* to the current time.
* @return The new post meta.
*/
public PostMeta withCurrentModifiedTime() {
return new PostMeta(id, System.currentTimeMillis(), fingerprint);
}
/**
* The post id.
*/
public final long id;
/**
* The last modified timestamp.
*/
public final long lastModifiedMillis;
/**
* A hash 'fingerprint' for detecting changes.
*/
public final HashCode fingerprint;
@Override
public String toString() {
return MoreObjects.toStringHelper(this.getClass())
.add("id", id)
.add("lastModifiedMillis",lastModifiedMillis)
.add("lastModifiedHuman", ISODateTimeFormat.basicDateTime().withZone(DateTimeZone.getDefault()).print(lastModifiedMillis))
.add("lastModifiedHumanUTC", ISODateTimeFormat.basicDateTime().withZoneUTC().print(lastModifiedMillis))
.add("fingerprint", fingerprint)
.toString();
}
/**
* Converts this metadata to a byte string (for saving state).
* @return The byte string.
*/
public ByteString toBytes() {
if(fingerprint == null) {
return ByteString.copyFromUtf8(id + "," + lastModifiedMillis);
} else {
return ByteString.copyFromUtf8(id + "," + lastModifiedMillis + "," + fingerprint.toString() + "," +
ISODateTimeFormat.basicDateTime().withZoneUTC().print(lastModifiedMillis)
);
}
}
/**
* Creates an instance from previously stored bytes.
* @param bytes The stored bytes.
* @return The metadata.
* @throws IOException on invalid format.
*/
public static PostMeta fromBytes(final ByteString bytes) throws IOException {
String[] components = bytes.toStringUtf8().split(",");
if(components.length < 2) {
throw new IOException(String.format("Invalid state: '%s'", bytes.toStringUtf8()));
}
Long id = Longs.tryParse(components[0].trim());
if(id == null) {
throw new IOException(String.format("Invalid state: '%s'", bytes.toStringUtf8()));
}
Long lastModifiedMillis = Longs.tryParse(components[1].trim());
if(lastModifiedMillis == null) {
throw new IOException(String.format("Invalid state: '%s'", bytes.toStringUtf8()));
}
if(components.length >= 3) {
return new PostMeta(id, lastModifiedMillis, HashCode.fromString(components[2].trim()));
} else {
return new PostMeta(id, lastModifiedMillis);
}
}
/**
* Creates a unique fingerprint for a post using the default hasher.
* @param post The post.
* @return The fingerprint.
*/
public static final HashCode fingerprint(final Post post) {
Hasher hasher = hashFunction.newHasher();
fingerprint(post, hasher);
return hasher.hash();
}
/**
* Creates a unique fingerprint for a post.
* @param post The post.
* @param hasher The hasher.
*/
public static final void fingerprint(final Post post, final Hasher hasher) {
if(post == null) {
return;
}
hasher.putString(Strings.nullToEmpty(post.slug), Charsets.UTF_8);
hasher.putString(Strings.nullToEmpty(post.title), Charsets.UTF_8);
hasher.putString(Strings.nullToEmpty(post.excerpt), Charsets.UTF_8);
hasher.putString(Strings.nullToEmpty(post.content), Charsets.UTF_8);
hasher.putLong(post.authorId);
hasher.putLong(post.publishTimestamp);
hasher.putString(post.status != null ? post.status.toString() : "", Charsets.UTF_8);
hasher.putString(Strings.nullToEmpty(post.guid), Charsets.UTF_8);
post.metadata.stream().sorted(Comparator.comparing(o -> o.key)).forEach(meta -> {
hasher.putString(meta.key, Charsets.UTF_8).putString(Strings.nullToEmpty(meta.value), Charsets.UTF_8);
});
hasher.putString(post.type != null ? post.type.toString() : "", Charsets.UTF_8);
hasher.putString(Strings.nullToEmpty(post.mimeType), Charsets.UTF_8);
post.tags().stream().sorted(Comparator.comparing(o -> o.term.name)).forEach(term -> {
hasher.putString(term.term.name, Charsets.UTF_8);
});
post.categories().stream().sorted(Comparator.comparing(o -> o.term.name)).forEach(term -> {
hasher.putString(term.term.name, Charsets.UTF_8);
});
post.children.forEach(childPost -> fingerprint(childPost, hasher));
}
/**
* The hash function.
*/
public static final HashFunction hashFunction = Hashing.sha256();
}
| |
/*
* Copyright (c) 2014 Spotify AB.
*
* 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.spotify.helios.common.descriptors;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.io.BaseEncoding;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.spotify.helios.common.Hash;
import com.spotify.helios.common.Json;
import org.junit.Test;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static com.google.common.base.Charsets.UTF_8;
import static com.google.common.base.Preconditions.checkArgument;
import static com.spotify.helios.common.descriptors.Descriptor.parse;
import static java.util.Arrays.asList;
import static org.hamcrest.Matchers.hasEntry;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;
public class JobTest {
private Map<String, Object> map(final Object... objects) {
final ImmutableMap.Builder<String, Object> builder = ImmutableMap.builder();
checkArgument(objects.length % 2 == 0);
for (int i = 0; i < objects.length; i += 2) {
builder.put((String) objects[i], objects[i + 1]);
}
return builder.build();
}
@Test
public void testNormalizedExcludesEmptyStrings() throws Exception {
final Job j = Job.newBuilder().setName("x").setImage("x").setVersion("x")
.setRegistrationDomain("").build();
assertFalse(Json.asNormalizedString(j).contains("registrationDomain"));
}
@Test
public void verifyBuilder() throws Exception {
final Job.Builder builder = Job.newBuilder();
// Input to setXXX
final String setName = "set_name";
final String setVersion = "set_version";
final String setImage = "set_image";
final String setHostname = "set_hostname";
final List<String> setCommand = asList("set", "command");
final Map<String, String> setEnv = ImmutableMap.of("set", "env");
final Map<String, PortMapping> setPorts = ImmutableMap.of("set_ports", PortMapping.of(1234));
final ImmutableMap.Builder<String, ServicePortParameters> setServicePortsBuilder =
ImmutableMap.builder();
setServicePortsBuilder.put("set_ports1", new ServicePortParameters(
ImmutableList.of("tag1", "tag2")));
setServicePortsBuilder.put("set_ports2", new ServicePortParameters(
ImmutableList.of("tag3", "tag4")));
final ServicePorts setServicePorts = new ServicePorts(setServicePortsBuilder.build());
final Map<ServiceEndpoint, ServicePorts> setRegistration = ImmutableMap.of(
ServiceEndpoint.of("set_service", "set_proto"), setServicePorts);
final Integer setGracePeriod = 120;
final Map<String, String> setVolumes = ImmutableMap.of("/set", "/volume");
final Date setExpires = new Date();
final String setRegistrationDomain = "my.domain";
final String setCreatingUser = "username";
final Resources setResources = new Resources(10485760L, 10485761L, 4L, "1");
final HealthCheck setHealthCheck = HealthCheck.newHttpHealthCheck()
.setPath("/healthcheck")
.setPort("set_ports")
.build();
final List<String> setSecurityOpt = Lists.newArrayList("label:user:dxia", "apparmor:foo");
final String setNetworkMode = "host";
final Map<String, String> setMetadata = ImmutableMap.of("set_metadata_key", "set_metadata_val");
final Set<String> setAddCapabilities = ImmutableSet.of("set_cap_add1", "set_cap_add2");
final Set<String> setDropCapabilities = ImmutableSet.of("set_cap_drop1", "set_cap_drop2");
// Input to addXXX
final Map<String, String> addEnv = ImmutableMap.of("add", "env");
final Map<String, PortMapping> addPorts = ImmutableMap.of("add_ports", PortMapping.of(4711));
final ImmutableMap.Builder<String, ServicePortParameters> addServicePortsBuilder =
ImmutableMap.builder();
addServicePortsBuilder.put("add_ports1", new ServicePortParameters(
ImmutableList.of("tag1", "tag2")));
addServicePortsBuilder.put("add_ports2", new ServicePortParameters(
ImmutableList.of("tag3", "tag4")));
final ServicePorts addServicePorts = new ServicePorts(addServicePortsBuilder.build());
final Map<ServiceEndpoint, ServicePorts> addRegistration = ImmutableMap.of(
ServiceEndpoint.of("add_service", "add_proto"), addServicePorts);
final Map<String, String> addVolumes = ImmutableMap.of("/add", "/volume");
final Map<String, String> addMetadata = ImmutableMap.of("add_metadata_key", "add_metadata_val");
// Expected output from getXXX
final String expectedName = setName;
final String expectedVersion = setVersion;
final String expectedImage = setImage;
final String expectedHostname = setHostname;
final List<String> expectedCommand = setCommand;
final Map<String, String> expectedEnv = concat(setEnv, addEnv);
final Map<String, PortMapping> expectedPorts = concat(setPorts, addPorts);
final Map<ServiceEndpoint, ServicePorts> expectedRegistration =
concat(setRegistration, addRegistration);
final Integer expectedGracePeriod = setGracePeriod;
final Map<String, String> expectedVolumes = concat(setVolumes, addVolumes);
final Date expectedExpires = setExpires;
final String expectedRegistrationDomain = setRegistrationDomain;
final String expectedCreatingUser = setCreatingUser;
final Resources expectedResources = setResources;
final HealthCheck expectedHealthCheck = setHealthCheck;
final List<String> expectedSecurityOpt = setSecurityOpt;
final String expectedNetworkMode = setNetworkMode;
final Map<String, String> expectedMetadata = concat(setMetadata, addMetadata);
final Set<String> expectedAddCapabilities = setAddCapabilities;
final Set<String> expectedDropCapabilities = setDropCapabilities;
// Check setXXX methods
builder.setName(setName);
builder.setVersion(setVersion);
builder.setImage(setImage);
builder.setHostname(setHostname);
builder.setCommand(setCommand);
builder.setEnv(setEnv);
builder.setPorts(setPorts);
builder.setRegistration(setRegistration);
builder.setGracePeriod(setGracePeriod);
builder.setVolumes(setVolumes);
builder.setExpires(setExpires);
builder.setRegistrationDomain(setRegistrationDomain);
builder.setCreatingUser(setCreatingUser);
builder.setResources(setResources);
builder.setHealthCheck(setHealthCheck);
builder.setSecurityOpt(setSecurityOpt);
builder.setNetworkMode(setNetworkMode);
builder.setMetadata(setMetadata);
builder.setAddCapabilities(setAddCapabilities);
builder.setDropCapabilities(setDropCapabilities);
// Check addXXX methods
for (final Map.Entry<String, String> entry : addEnv.entrySet()) {
builder.addEnv(entry.getKey(), entry.getValue());
}
for (final Map.Entry<String, PortMapping> entry : addPorts.entrySet()) {
builder.addPort(entry.getKey(), entry.getValue());
}
for (final Map.Entry<ServiceEndpoint, ServicePorts> entry : addRegistration.entrySet()) {
builder.addRegistration(entry.getKey(), entry.getValue());
}
for (final Map.Entry<String, String> entry : addVolumes.entrySet()) {
builder.addVolume(entry.getKey(), entry.getValue());
}
for (final Map.Entry<String, String> entry : addMetadata.entrySet()) {
builder.addMetadata(entry.getKey(), entry.getValue());
}
assertEquals("name", expectedName, builder.getName());
assertEquals("version", expectedVersion, builder.getVersion());
assertEquals("image", expectedImage, builder.getImage());
assertEquals("hostname", expectedHostname, builder.getHostname());
assertEquals("command", expectedCommand, builder.getCommand());
assertEquals("env", expectedEnv, builder.getEnv());
assertEquals("ports", expectedPorts, builder.getPorts());
assertEquals("registration", expectedRegistration, builder.getRegistration());
assertEquals("gracePeriod", expectedGracePeriod, builder.getGracePeriod());
assertEquals("volumes", expectedVolumes, builder.getVolumes());
assertEquals("expires", expectedExpires, builder.getExpires());
assertEquals("registrationDomain", expectedRegistrationDomain, builder.getRegistrationDomain());
assertEquals("creatingUser", expectedCreatingUser, builder.getCreatingUser());
assertEquals("resources", expectedResources, builder.getResources());
assertEquals("healthCheck", expectedHealthCheck, builder.getHealthCheck());
assertEquals("securityOpt", expectedSecurityOpt, builder.getSecurityOpt());
assertEquals("networkMode", expectedNetworkMode, builder.getNetworkMode());
assertEquals("metadata", expectedMetadata, builder.getMetadata());
assertEquals("addCapabilities", expectedAddCapabilities, builder.getAddCapabilities());
assertEquals("dropCapabilities", expectedDropCapabilities,
builder.getDropCapabilities());
// Check final output
final Job job = builder.build();
assertEquals("name", expectedName, job.getId().getName());
assertEquals("version", expectedVersion, job.getId().getVersion());
assertEquals("image", expectedImage, job.getImage());
assertEquals("hostname", expectedHostname, job.getHostname());
assertEquals("command", expectedCommand, job.getCommand());
assertEquals("env", expectedEnv, job.getEnv());
assertEquals("ports", expectedPorts, job.getPorts());
assertEquals("registration", expectedRegistration, job.getRegistration());
assertEquals("gracePeriod", expectedGracePeriod, job.getGracePeriod());
assertEquals("volumes", expectedVolumes, job.getVolumes());
assertEquals("expires", expectedExpires, job.getExpires());
assertEquals("registrationDomain", expectedRegistrationDomain, job.getRegistrationDomain());
assertEquals("creatingUser", expectedCreatingUser, job.getCreatingUser());
assertEquals("resources", expectedResources, job.getResources());
assertEquals("healthCheck", expectedHealthCheck, job.getHealthCheck());
assertEquals("securityOpt", expectedSecurityOpt, job.getSecurityOpt());
assertEquals("networkMode", expectedNetworkMode, job.getNetworkMode());
assertEquals("metadata", expectedMetadata, job.getMetadata());
assertEquals("addCapabilities", expectedAddCapabilities, job.getAddCapabilities());
assertEquals("dropCapabilities", expectedDropCapabilities, job.getDropCapabilities());
// Check toBuilder
final Job.Builder rebuilder = job.toBuilder();
assertEquals("name", expectedName, rebuilder.getName());
assertEquals("version", expectedVersion, rebuilder.getVersion());
assertEquals("image", expectedImage, rebuilder.getImage());
assertEquals("hostname", expectedHostname, rebuilder.getHostname());
assertEquals("command", expectedCommand, rebuilder.getCommand());
assertEquals("env", expectedEnv, rebuilder.getEnv());
assertEquals("ports", expectedPorts, rebuilder.getPorts());
assertEquals("registration", expectedRegistration, rebuilder.getRegistration());
assertEquals("gracePeriod", expectedGracePeriod, rebuilder.getGracePeriod());
assertEquals("volumes", expectedVolumes, rebuilder.getVolumes());
assertEquals("expires", expectedExpires, rebuilder.getExpires());
assertEquals("registrationDomain", expectedRegistrationDomain,
rebuilder.getRegistrationDomain());
assertEquals("creatingUser", expectedCreatingUser, rebuilder.getCreatingUser());
assertEquals("resources", expectedResources, rebuilder.getResources());
assertEquals("healthCheck", expectedHealthCheck, rebuilder.getHealthCheck());
assertEquals("securityOpt", expectedSecurityOpt, rebuilder.getSecurityOpt());
assertEquals("networkMode", expectedNetworkMode, rebuilder.getNetworkMode());
assertEquals("metadata", expectedMetadata, rebuilder.getMetadata());
assertEquals("addCapabilities", expectedAddCapabilities, rebuilder.getAddCapabilities());
assertEquals("dropCapabilities", expectedDropCapabilities,
rebuilder.getDropCapabilities());
// Check clone
final Job.Builder cloned = builder.clone();
assertEquals("name", expectedName, cloned.getName());
assertEquals("version", expectedVersion, cloned.getVersion());
assertEquals("image", expectedImage, cloned.getImage());
assertEquals("hostname", expectedHostname, cloned.getHostname());
assertEquals("command", expectedCommand, cloned.getCommand());
assertEquals("env", expectedEnv, cloned.getEnv());
assertEquals("ports", expectedPorts, cloned.getPorts());
assertEquals("registration", expectedRegistration, cloned.getRegistration());
assertEquals("gracePeriod", expectedGracePeriod, cloned.getGracePeriod());
assertEquals("volumes", expectedVolumes, cloned.getVolumes());
assertEquals("expires", expectedExpires, cloned.getExpires());
assertEquals("registrationDomain", expectedRegistrationDomain,
cloned.getRegistrationDomain());
assertEquals("creatingUser", expectedCreatingUser, cloned.getCreatingUser());
assertEquals("resources", expectedResources, cloned.getResources());
assertEquals("healthCheck", expectedHealthCheck, cloned.getHealthCheck());
assertEquals("securityOpt", expectedSecurityOpt, cloned.getSecurityOpt());
assertEquals("networkMode", expectedNetworkMode, cloned.getNetworkMode());
assertEquals("metadata", expectedMetadata, cloned.getMetadata());
assertEquals("addCapabilities", expectedAddCapabilities, cloned.getAddCapabilities());
assertEquals("dropCapabilities", expectedDropCapabilities,
cloned.getDropCapabilities());
final Job clonedJob = cloned.build();
assertEquals("name", expectedName, clonedJob.getId().getName());
assertEquals("version", expectedVersion, clonedJob.getId().getVersion());
assertEquals("image", expectedImage, clonedJob.getImage());
assertEquals("hostname", expectedHostname, clonedJob.getHostname());
assertEquals("command", expectedCommand, clonedJob.getCommand());
assertEquals("env", expectedEnv, clonedJob.getEnv());
assertEquals("ports", expectedPorts, clonedJob.getPorts());
assertEquals("registration", expectedRegistration, clonedJob.getRegistration());
assertEquals("gracePeriod", expectedGracePeriod, clonedJob.getGracePeriod());
assertEquals("volumes", expectedVolumes, clonedJob.getVolumes());
assertEquals("expires", expectedExpires, clonedJob.getExpires());
assertEquals("registrationDomain", expectedRegistrationDomain,
clonedJob.getRegistrationDomain());
assertEquals("creatingUser", expectedCreatingUser, clonedJob.getCreatingUser());
assertEquals("resources", expectedResources, clonedJob.getResources());
assertEquals("healthCheck", expectedHealthCheck, clonedJob.getHealthCheck());
assertEquals("securityOpt", expectedSecurityOpt, clonedJob.getSecurityOpt());
assertEquals("networkMode", expectedNetworkMode, clonedJob.getNetworkMode());
assertEquals("metadata", expectedMetadata, clonedJob.getMetadata());
assertEquals("addCapabilities", expectedAddCapabilities, clonedJob.getAddCapabilities());
assertEquals("dropCapabilities", expectedDropCapabilities,
clonedJob.getDropCapabilities());
}
@SafeVarargs
private final <K, V> Map<K, V> concat(final Map<K, V>... maps) {
final ImmutableMap.Builder<K, V> b = ImmutableMap.builder();
for (final Map<K, V> map : maps) {
b.putAll(map);
}
return b.build();
}
/** Verify the Builder allows calling addFoo() before setFoo() for collection types. */
@Test
public void testBuilderAddBeforeSet() throws Exception {
final Job job = Job.newBuilder()
.addEnv("env", "var")
.addMetadata("meta", "data")
.addPort("http", PortMapping.of(80, 8000))
.addRegistration(ServiceEndpoint.of("foo", "http"), ServicePorts.of("http"))
.addVolume("/foo", "/bar")
.build();
assertThat(job.getEnv(), hasEntry("env", "var"));
assertThat(job.getMetadata(), hasEntry("meta", "data"));
assertThat(job.getPorts(), hasEntry("http", PortMapping.of(80, 8000)));
assertThat(job.getRegistration(),
hasEntry(ServiceEndpoint.of("foo", "http"), ServicePorts.of("http")));
assertThat(job.getVolumes(), hasEntry("/foo", "/bar"));
}
@Test
public void verifySha1ID() throws IOException {
final Map<String, Object> expectedConfig = map("command", asList("foo", "bar"),
"image", "foobar:4711",
"name", "foozbarz",
"version", "17");
final String expectedInput = "foozbarz:17:" + hex(Json.sha1digest(expectedConfig));
final String expectedDigest = hex(Hash.sha1digest(expectedInput.getBytes(UTF_8)));
final JobId expectedId = JobId.fromString("foozbarz:17:" + expectedDigest);
final Job job = Job.newBuilder()
.setCommand(asList("foo", "bar"))
.setImage("foobar:4711")
.setName("foozbarz")
.setVersion("17")
.build();
assertEquals(expectedId, job.getId());
}
@Test
public void verifySha1IDWithEnv() throws IOException {
final Map<String, String> env = ImmutableMap.of("FOO", "BAR");
final Map<String, Object> expectedConfig = map("command", asList("foo", "bar"),
"image", "foobar:4711",
"name", "foozbarz",
"version", "17",
"env", env);
final String expectedInput = "foozbarz:17:" + hex(Json.sha1digest(expectedConfig));
final String expectedDigest = hex(Hash.sha1digest(expectedInput.getBytes(UTF_8)));
final JobId expectedId = JobId.fromString("foozbarz:17:" + expectedDigest);
final Job job = Job.newBuilder()
.setCommand(asList("foo", "bar"))
.setImage("foobar:4711")
.setName("foozbarz")
.setVersion("17")
.setEnv(env)
.build();
assertEquals(expectedId, job.getId());
}
private String hex(final byte[] bytes) {
return BaseEncoding.base16().lowerCase().encode(bytes);
}
@Test
public void verifyCanParseJobWithUnknownFields() throws Exception {
final Job job = Job.newBuilder()
.setCommand(asList("foo", "bar"))
.setImage("foobar:4711")
.setName("foozbarz")
.setVersion("17")
.build();
final String jobJson = job.toJsonString();
final ObjectMapper objectMapper = new ObjectMapper();
final Map<String, Object> fields = objectMapper.readValue(
jobJson, new TypeReference<Map<String, Object>>() {});
fields.put("UNKNOWN_FIELD", "FOOBAR");
final String modifiedJobJson = objectMapper.writeValueAsString(fields);
final Job parsedJob = parse(modifiedJobJson, Job.class);
assertEquals(job, parsedJob);
}
@Test
public void verifyCanParseJobWithMissingEnv() throws Exception {
final Job job = Job.newBuilder()
.setCommand(asList("foo", "bar"))
.setImage("foobar:4711")
.setName("foozbarz")
.setVersion("17")
.build();
removeFieldAndParse(job, "env");
}
@Test
public void verifyCanParseJobWithMissingMetadata() throws Exception {
final Job job = Job.newBuilder()
.setCommand(asList("foo", "bar"))
.setImage("foobar:4711")
.setName("foozbarz")
.setVersion("17")
.build();
removeFieldAndParse(job, "metadata");
}
private static void removeFieldAndParse(final Job job, final String... fieldNames)
throws Exception {
final String jobJson = job.toJsonString();
final ObjectMapper objectMapper = new ObjectMapper();
final Map<String, Object> fields = objectMapper.readValue(
jobJson, new TypeReference<Map<String, Object>>() {});
for (final String field : fieldNames) {
fields.remove(field);
}
final String modifiedJobJson = objectMapper.writeValueAsString(fields);
final Job parsedJob = parse(modifiedJobJson, Job.class);
assertEquals(job, parsedJob);
}
@Test
public void verifyJobIsImmutable() {
final List<String> expectedCommand = ImmutableList.of("foo");
final Map<String, String> expectedEnv = ImmutableMap.of("e1", "1");
final Map<String, String> expectedMetadata = ImmutableMap.of("foo", "bar");
final Map<String, PortMapping> expectedPorts = ImmutableMap.of("p1", PortMapping.of(1, 2));
final Map<ServiceEndpoint, ServicePorts> expectedRegistration =
ImmutableMap.of(ServiceEndpoint.of("foo", "tcp"), ServicePorts.of("p1"));
final Integer expectedGracePeriod = 240;
final List<String> mutableCommand = Lists.newArrayList(expectedCommand);
final Map<String, String> mutableEnv = Maps.newHashMap(expectedEnv);
final Map<String, String> mutableMetadata = Maps.newHashMap(expectedMetadata);
final Map<String, PortMapping> mutablePorts = Maps.newHashMap(expectedPorts);
final Map<ServiceEndpoint, ServicePorts> mutableRegistration =
Maps.newHashMap(expectedRegistration);
final Job.Builder builder = Job.newBuilder()
.setCommand(mutableCommand)
.setEnv(mutableEnv)
.setMetadata(mutableMetadata)
.setPorts(mutablePorts)
.setImage("foobar:4711")
.setName("foozbarz")
.setVersion("17")
.setRegistration(mutableRegistration)
.setGracePeriod(expectedGracePeriod);
final Job job = builder.build();
mutableCommand.add("bar");
mutableEnv.put("e2", "2");
mutableMetadata.put("some", "thing");
mutablePorts.put("p2", PortMapping.of(3, 4));
mutableRegistration.put(ServiceEndpoint.of("bar", "udp"), ServicePorts.of("p2"));
builder.addEnv("added_env", "FOO");
builder.addMetadata("added", "data");
builder.addPort("added_port", PortMapping.of(4711));
builder.addRegistration(ServiceEndpoint.of("added_reg", "added_proto"),
ServicePorts.of("added_port"));
builder.setGracePeriod(480);
assertEquals(expectedCommand, job.getCommand());
assertEquals(expectedEnv, job.getEnv());
assertEquals(expectedMetadata, job.getMetadata());
assertEquals(expectedPorts, job.getPorts());
assertEquals(expectedRegistration, job.getRegistration());
assertEquals(expectedGracePeriod, job.getGracePeriod());
}
@Test
public void testChangingPortTagsChangesJobHash() {
final Job j = Job.newBuilder().setName("foo").setVersion("1").setImage("foobar").build();
final Job.Builder builder = j.toBuilder();
final Map<String, PortMapping> ports = ImmutableMap.of("add_ports1", PortMapping.of(1234),
"add_ports2", PortMapping.of(2345));
final ImmutableMap.Builder<String, ServicePortParameters> servicePortsBuilder =
ImmutableMap.builder();
servicePortsBuilder.put("add_ports1", new ServicePortParameters(
ImmutableList.of("tag1", "tag2")));
servicePortsBuilder.put("add_ports2", new ServicePortParameters(
ImmutableList.of("tag3", "tag4")));
final ServicePorts servicePorts = new ServicePorts(servicePortsBuilder.build());
final Map<ServiceEndpoint, ServicePorts> oldRegistration = ImmutableMap.of(
ServiceEndpoint.of("add_service", "add_proto"), servicePorts);
final Job job = builder.setPorts(ports).setRegistration(oldRegistration).build();
final ImmutableMap.Builder<String, ServicePortParameters> newServicePortsBuilder =
ImmutableMap.builder();
newServicePortsBuilder.put("add_ports1", new ServicePortParameters(
ImmutableList.of("tag1", "newtag")));
newServicePortsBuilder.put("add_ports2", new ServicePortParameters(
ImmutableList.of("tag3", "tag4")));
final ServicePorts newServicePorts = new ServicePorts(newServicePortsBuilder.build());
final Map<ServiceEndpoint, ServicePorts> newRegistration = ImmutableMap.of(
ServiceEndpoint.of("add_service", "add_proto"), newServicePorts);
final Job newJob = builder.setRegistration(newRegistration).build();
assertNotEquals(job.getId().getHash(), newJob.getId().getHash());
}
@Test
public void testBuildWithoutHash() {
final Job.Builder builder = Job.newBuilder()
.setCommand(asList("foo", "bar"))
.setImage("foobar:4711")
.setName("foozbarz")
.setVersion("17");
assertNull(builder.buildWithoutHash().getId().getHash());
assertNotNull(builder.build().getId().getHash());
}
}
| |
/* 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.activiti.engine.impl;
import java.io.InputStream;
import java.util.Date;
import java.util.List;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.impl.cmd.ActivateProcessDefinitionCmd;
import org.activiti.engine.impl.cmd.AddEditorSourceExtraForModelCmd;
import org.activiti.engine.impl.cmd.AddEditorSourceForModelCmd;
import org.activiti.engine.impl.cmd.AddIdentityLinkForProcessDefinitionCmd;
import org.activiti.engine.impl.cmd.ChangeDeploymentTenantIdCmd;
import org.activiti.engine.impl.cmd.CreateModelCmd;
import org.activiti.engine.impl.cmd.DeleteDeploymentCmd;
import org.activiti.engine.impl.cmd.DeleteIdentityLinkForProcessDefinitionCmd;
import org.activiti.engine.impl.cmd.DeleteModelCmd;
import org.activiti.engine.impl.cmd.DeployCmd;
import org.activiti.engine.impl.cmd.GetBpmnModelCmd;
import org.activiti.engine.impl.cmd.GetDeploymentProcessDefinitionCmd;
import org.activiti.engine.impl.cmd.GetDeploymentProcessDiagramCmd;
import org.activiti.engine.impl.cmd.GetDeploymentProcessDiagramLayoutCmd;
import org.activiti.engine.impl.cmd.GetDeploymentProcessModelCmd;
import org.activiti.engine.impl.cmd.GetDeploymentResourceCmd;
import org.activiti.engine.impl.cmd.GetDeploymentResourceNamesCmd;
import org.activiti.engine.impl.cmd.GetIdentityLinksForProcessDefinitionCmd;
import org.activiti.engine.impl.cmd.GetModelCmd;
import org.activiti.engine.impl.cmd.GetModelEditorSourceCmd;
import org.activiti.engine.impl.cmd.GetModelEditorSourceExtraCmd;
import org.activiti.engine.impl.cmd.IsActiviti5ProcessDefinitionCmd;
import org.activiti.engine.impl.cmd.IsProcessDefinitionSuspendedCmd;
import org.activiti.engine.impl.cmd.SaveModelCmd;
import org.activiti.engine.impl.cmd.SetDeploymentCategoryCmd;
import org.activiti.engine.impl.cmd.SetDeploymentKeyCmd;
import org.activiti.engine.impl.cmd.SetProcessDefinitionCategoryCmd;
import org.activiti.engine.impl.cmd.SuspendProcessDefinitionCmd;
import org.activiti.engine.impl.cmd.ValidateBpmnModelCmd;
import org.activiti.engine.impl.interceptor.Command;
import org.activiti.engine.impl.interceptor.CommandContext;
import org.activiti.engine.impl.persistence.entity.ModelEntity;
import org.activiti.engine.impl.repository.DeploymentBuilderImpl;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.DeploymentBuilder;
import org.activiti.engine.repository.DeploymentQuery;
import org.activiti.engine.repository.DiagramLayout;
import org.activiti.engine.repository.Model;
import org.activiti.engine.repository.ModelQuery;
import org.activiti.engine.repository.NativeDeploymentQuery;
import org.activiti.engine.repository.NativeModelQuery;
import org.activiti.engine.repository.NativeProcessDefinitionQuery;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.repository.ProcessDefinitionQuery;
import org.activiti.engine.task.IdentityLink;
import org.activiti.validation.ValidationError;
/**
* @author Tom Baeyens
* @author Falko Menge
* @author Joram Barrez
*/
public class RepositoryServiceImpl extends ServiceImpl implements RepositoryService {
public DeploymentBuilder createDeployment() {
return commandExecutor.execute(new Command<DeploymentBuilder>() {
@Override
public DeploymentBuilder execute(CommandContext commandContext) {
return new DeploymentBuilderImpl(RepositoryServiceImpl.this);
}
});
}
public Deployment deploy(DeploymentBuilderImpl deploymentBuilder) {
return commandExecutor.execute(new DeployCmd<Deployment>(deploymentBuilder));
}
public void deleteDeployment(String deploymentId) {
commandExecutor.execute(new DeleteDeploymentCmd(deploymentId, false));
}
public void deleteDeploymentCascade(String deploymentId) {
commandExecutor.execute(new DeleteDeploymentCmd(deploymentId, true));
}
public void deleteDeployment(String deploymentId, boolean cascade) {
commandExecutor.execute(new DeleteDeploymentCmd(deploymentId, cascade));
}
public void setDeploymentCategory(String deploymentId, String category) {
commandExecutor.execute(new SetDeploymentCategoryCmd(deploymentId, category));
}
public void setDeploymentKey(String deploymentId, String key) {
commandExecutor.execute(new SetDeploymentKeyCmd(deploymentId, key));
}
public ProcessDefinitionQuery createProcessDefinitionQuery() {
return new ProcessDefinitionQueryImpl(commandExecutor);
}
@Override
public NativeProcessDefinitionQuery createNativeProcessDefinitionQuery() {
return new NativeProcessDefinitionQueryImpl(commandExecutor);
}
@SuppressWarnings("unchecked")
public List<String> getDeploymentResourceNames(String deploymentId) {
return commandExecutor.execute(new GetDeploymentResourceNamesCmd(deploymentId));
}
public InputStream getResourceAsStream(String deploymentId, String resourceName) {
return commandExecutor.execute(new GetDeploymentResourceCmd(deploymentId, resourceName));
}
@Override
public void changeDeploymentTenantId(String deploymentId, String newTenantId) {
commandExecutor.execute(new ChangeDeploymentTenantIdCmd(deploymentId, newTenantId));
}
public DeploymentQuery createDeploymentQuery() {
return new DeploymentQueryImpl(commandExecutor);
}
@Override
public NativeDeploymentQuery createNativeDeploymentQuery() {
return new NativeDeploymentQueryImpl(commandExecutor);
}
public ProcessDefinition getProcessDefinition(String processDefinitionId) {
return commandExecutor.execute(new GetDeploymentProcessDefinitionCmd(processDefinitionId));
}
public Boolean isActiviti5ProcessDefinition(String processDefinitionId) {
return commandExecutor.execute(new IsActiviti5ProcessDefinitionCmd(processDefinitionId));
}
public BpmnModel getBpmnModel(String processDefinitionId) {
return commandExecutor.execute(new GetBpmnModelCmd(processDefinitionId));
}
public ProcessDefinition getDeployedProcessDefinition(String processDefinitionId) {
return commandExecutor.execute(new GetDeploymentProcessDefinitionCmd(processDefinitionId));
}
public boolean isProcessDefinitionSuspended(String processDefinitionId) {
return commandExecutor.execute(new IsProcessDefinitionSuspendedCmd(processDefinitionId));
}
public void suspendProcessDefinitionById(String processDefinitionId) {
commandExecutor.execute(new SuspendProcessDefinitionCmd(processDefinitionId, null, false, null, null));
}
public void suspendProcessDefinitionById(String processDefinitionId, boolean suspendProcessInstances, Date suspensionDate) {
commandExecutor.execute(new SuspendProcessDefinitionCmd(processDefinitionId, null, suspendProcessInstances, suspensionDate, null));
}
public void suspendProcessDefinitionByKey(String processDefinitionKey) {
commandExecutor.execute(new SuspendProcessDefinitionCmd(null, processDefinitionKey, false, null, null));
}
public void suspendProcessDefinitionByKey(String processDefinitionKey, boolean suspendProcessInstances, Date suspensionDate) {
commandExecutor.execute(new SuspendProcessDefinitionCmd(null, processDefinitionKey, suspendProcessInstances, suspensionDate, null));
}
public void suspendProcessDefinitionByKey(String processDefinitionKey, String tenantId) {
commandExecutor.execute(new SuspendProcessDefinitionCmd(null, processDefinitionKey, false, null, tenantId));
}
public void suspendProcessDefinitionByKey(String processDefinitionKey, boolean suspendProcessInstances, Date suspensionDate, String tenantId) {
commandExecutor.execute(new SuspendProcessDefinitionCmd(null, processDefinitionKey, suspendProcessInstances, suspensionDate, tenantId));
}
public void activateProcessDefinitionById(String processDefinitionId) {
commandExecutor.execute(new ActivateProcessDefinitionCmd(processDefinitionId, null, false, null, null));
}
public void activateProcessDefinitionById(String processDefinitionId, boolean activateProcessInstances, Date activationDate) {
commandExecutor.execute(new ActivateProcessDefinitionCmd(processDefinitionId, null, activateProcessInstances, activationDate, null));
}
public void activateProcessDefinitionByKey(String processDefinitionKey) {
commandExecutor.execute(new ActivateProcessDefinitionCmd(null, processDefinitionKey, false, null, null));
}
public void activateProcessDefinitionByKey(String processDefinitionKey, boolean activateProcessInstances, Date activationDate) {
commandExecutor.execute(new ActivateProcessDefinitionCmd(null, processDefinitionKey, activateProcessInstances, activationDate, null));
}
public void activateProcessDefinitionByKey(String processDefinitionKey, String tenantId) {
commandExecutor.execute(new ActivateProcessDefinitionCmd(null, processDefinitionKey, false, null, tenantId));
}
public void activateProcessDefinitionByKey(String processDefinitionKey, boolean activateProcessInstances, Date activationDate, String tenantId) {
commandExecutor.execute(new ActivateProcessDefinitionCmd(null, processDefinitionKey, activateProcessInstances, activationDate, tenantId));
}
public void setProcessDefinitionCategory(String processDefinitionId, String category) {
commandExecutor.execute(new SetProcessDefinitionCategoryCmd(processDefinitionId, category));
}
public InputStream getProcessModel(String processDefinitionId) {
return commandExecutor.execute(new GetDeploymentProcessModelCmd(processDefinitionId));
}
public InputStream getProcessDiagram(String processDefinitionId) {
return commandExecutor.execute(new GetDeploymentProcessDiagramCmd(processDefinitionId));
}
public DiagramLayout getProcessDiagramLayout(String processDefinitionId) {
return commandExecutor.execute(new GetDeploymentProcessDiagramLayoutCmd(processDefinitionId));
}
public Model newModel() {
return commandExecutor.execute(new CreateModelCmd());
}
public void saveModel(Model model) {
commandExecutor.execute(new SaveModelCmd((ModelEntity) model));
}
public void deleteModel(String modelId) {
commandExecutor.execute(new DeleteModelCmd(modelId));
}
public void addModelEditorSource(String modelId, byte[] bytes) {
commandExecutor.execute(new AddEditorSourceForModelCmd(modelId, bytes));
}
public void addModelEditorSourceExtra(String modelId, byte[] bytes) {
commandExecutor.execute(new AddEditorSourceExtraForModelCmd(modelId, bytes));
}
public ModelQuery createModelQuery() {
return new ModelQueryImpl(commandExecutor);
}
@Override
public NativeModelQuery createNativeModelQuery() {
return new NativeModelQueryImpl(commandExecutor);
}
public Model getModel(String modelId) {
return commandExecutor.execute(new GetModelCmd(modelId));
}
public byte[] getModelEditorSource(String modelId) {
return commandExecutor.execute(new GetModelEditorSourceCmd(modelId));
}
public byte[] getModelEditorSourceExtra(String modelId) {
return commandExecutor.execute(new GetModelEditorSourceExtraCmd(modelId));
}
public void addCandidateStarterUser(String processDefinitionId, String userId) {
commandExecutor.execute(new AddIdentityLinkForProcessDefinitionCmd(processDefinitionId, userId, null));
}
public void addCandidateStarterGroup(String processDefinitionId, String groupId) {
commandExecutor.execute(new AddIdentityLinkForProcessDefinitionCmd(processDefinitionId, null, groupId));
}
public void deleteCandidateStarterGroup(String processDefinitionId, String groupId) {
commandExecutor.execute(new DeleteIdentityLinkForProcessDefinitionCmd(processDefinitionId, null, groupId));
}
public void deleteCandidateStarterUser(String processDefinitionId, String userId) {
commandExecutor.execute(new DeleteIdentityLinkForProcessDefinitionCmd(processDefinitionId, userId, null));
}
public List<IdentityLink> getIdentityLinksForProcessDefinition(String processDefinitionId) {
return commandExecutor.execute(new GetIdentityLinksForProcessDefinitionCmd(processDefinitionId));
}
public List<ValidationError> validateProcess(BpmnModel bpmnModel) {
return commandExecutor.execute(new ValidateBpmnModelCmd(bpmnModel));
}
}
| |
//
// Copyright 2011 Kuali Foundation, Inc. Licensed under the
// Educational Community 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.opensource.org/licenses/ecl2.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.continuity.admin.action;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.kuali.continuity.action.BaseActionSupport;
import org.kuali.continuity.action.dto.SessionKey;
import org.kuali.continuity.action.dto.SessionValue;
import org.kuali.continuity.admin.domain.SystemDomainCentralApplicationCriticalityLevel;
import org.kuali.continuity.admin.domain.SystemDomainCriticalFunctionCriticalityLevel;
import org.kuali.continuity.admin.domain.SystemDomainCriticalityLevel;
import org.kuali.continuity.admin.service.SystemDomainCriticalityLevelService;
import org.kuali.continuity.domain.CentralApplicationCriticalityLevel;
import org.kuali.continuity.domain.CriticalFunctionCriticalityLevel;
import org.kuali.continuity.domain.CriticalityLevel;
import org.kuali.continuity.domain.CriticalityLevelEnum;
import org.kuali.continuity.domain.SystemCriticalityLevel;
import org.kuali.continuity.plan.action.dto.SystemDomainCriticalityLevelDTO;
@SuppressWarnings("serial")
public class SystemDomainCriticalityLevelAction extends BaseActionSupport {
private SystemDomainCriticalityLevelService systemDomainCriticalityLevelService;
private Map<String, SystemDomainCriticalityLevelDTO> clFuncMap;
private Map<String, SystemDomainCriticalityLevelDTO> clApplMap;
private String clType;
private String clEnum;
public class TmpSessionValue implements SessionValue {
private Map<SystemDomainCriticalityLevelDTO.LevelType, Map<String, SystemDomainCriticalityLevelDTO>> sessionValue
= new HashMap<SystemDomainCriticalityLevelDTO.LevelType, Map<String, SystemDomainCriticalityLevelDTO>>();
public Map<SystemDomainCriticalityLevelDTO.LevelType, Map<String, SystemDomainCriticalityLevelDTO>> getSessionValue() {
return this.sessionValue;
}
public void setSessionValue(Map<SystemDomainCriticalityLevelDTO.LevelType, Map<String, SystemDomainCriticalityLevelDTO>> sessionValue) {
this.sessionValue = sessionValue;
}
public Map<String, SystemDomainCriticalityLevelDTO> getFromSessionCLMap(SystemDomainCriticalityLevelDTO.LevelType levelType) {
return this.sessionValue.get(levelType);
}
public void putInSessionCLMap(SystemDomainCriticalityLevelDTO.LevelType levelType, Map<String, SystemDomainCriticalityLevelDTO> clMap) {
this.sessionValue.put(levelType, clMap);
}
}
public SystemDomainCriticalityLevelAction(
SystemDomainCriticalityLevelService systemDomainCriticalityLevelService) {
this.systemDomainCriticalityLevelService = systemDomainCriticalityLevelService;
}
@SuppressWarnings("unchecked")
public String execute() {
TmpSessionValue tmpSessionValue = (TmpSessionValue) this.getSessionValue(SessionKey.tmpKey);
if (tmpSessionValue != null) {
this.clFuncMap = tmpSessionValue.getFromSessionCLMap(SystemDomainCriticalityLevelDTO.LevelType.FUNC);
this.clApplMap = tmpSessionValue.getFromSessionCLMap(SystemDomainCriticalityLevelDTO.LevelType.APPL);
this.removeFromSession(SessionKey.tmpKey);
return SUCCESS;
}
// get func map
this.clFuncMap = new HashMap<String, SystemDomainCriticalityLevelDTO>();
Map<CriticalityLevelEnum, CriticalFunctionCriticalityLevel> fmap =
(Map<CriticalityLevelEnum, CriticalFunctionCriticalityLevel>)
this.systemDomainCriticalityLevelService.getListByOwnerId(SystemDomainCriticalFunctionCriticalityLevel.class, this.getSessionSystemDomain().id);
// iterate
if (fmap != null && !fmap.isEmpty()) {
Set<CriticalityLevelEnum> keySet = fmap.keySet();
for (CriticalityLevelEnum key : keySet) {
CriticalityLevel cLevel = (CriticalityLevel) fmap.get(key);
if (cLevel instanceof SystemCriticalityLevel) cLevel.setId(0);
this.clFuncMap.put(key.name(), new SystemDomainCriticalityLevelDTO(cLevel));
}
}
// get appl map
this.clApplMap = new HashMap<String, SystemDomainCriticalityLevelDTO>();
Map<CriticalityLevelEnum, CentralApplicationCriticalityLevel> amap =
(Map<CriticalityLevelEnum, CentralApplicationCriticalityLevel>)
this.systemDomainCriticalityLevelService.getListByOwnerId(SystemDomainCentralApplicationCriticalityLevel.class, this.getSessionSystemDomain().id);
// iterate
if (amap != null && !amap.isEmpty()) {
Set<CriticalityLevelEnum> keySet = amap.keySet();
for (CriticalityLevelEnum key : keySet) {
CriticalityLevel cLevel = (CriticalityLevel) amap.get(key);
if (cLevel instanceof SystemCriticalityLevel) cLevel.setId(0);
this.clApplMap.put(key.name(), new SystemDomainCriticalityLevelDTO(cLevel));
}
}
// put in session?
// return
return SUCCESS;
}
public String installText() {
// put in session
this.putInSessionTmp();
// get level
CriticalityLevelEnum levelEnum = CriticalityLevelEnum.valueOf(clEnum);
SystemDomainCriticalityLevelDTO.LevelType levelType = SystemDomainCriticalityLevelDTO.LevelType.valueOf(clType);
if (levelEnum == CriticalityLevelEnum.LEVEL0) return this.updateCFDesc(false);
// get type
SystemDomainCriticalityLevelDTO dto =
(levelType == SystemDomainCriticalityLevelDTO.LevelType.FUNC ?
this.clFuncMap.get(this.clEnum) :
this.clApplMap.get(this.clEnum));
// get default level
SystemCriticalityLevel defLevel = this.systemDomainCriticalityLevelService
.getDefaultByLevelEnum(levelType == SystemDomainCriticalityLevelDTO.LevelType.FUNC ?
SystemDomainCriticalFunctionCriticalityLevel.class : SystemDomainCentralApplicationCriticalityLevel.class,
levelEnum);
// set to default if null
if (dto == null) {
dto = new SystemDomainCriticalityLevelDTO((CriticalityLevel) defLevel);
dto.id = 0;
} else if (dto.name == null || dto.name.trim().length() == 0) {
dto.name = defLevel.getName();
} else if (dto.longDescription == null || dto.longDescription.trim().length() == 0) {
dto.longDescription = defLevel.getLongDescription();
}
dto.levelType = levelType;
dto.systemDomainId = this.getSessionSystemDomain().id;
// set original description
SystemDomainCriticalityLevel cl = dto.getDomainObject();
cl.setDescription(dto.origDescription);
// install text
this.systemDomainCriticalityLevelService.update(cl);
return SUCCESS;
}
public String restoreText() {
// put in session
this.putInSessionTmp();
// get level
CriticalityLevelEnum levelEnum = CriticalityLevelEnum.valueOf(clEnum);
SystemDomainCriticalityLevelDTO.LevelType levelType = SystemDomainCriticalityLevelDTO.LevelType.valueOf(clType);
if (levelEnum == CriticalityLevelEnum.LEVEL0) return this.updateCFDesc(true);
// get type
SystemDomainCriticalityLevelDTO dto =
(levelType == SystemDomainCriticalityLevelDTO.LevelType.FUNC ?
this.clFuncMap.get(this.clEnum) :
this.clApplMap.get(this.clEnum));
// get default level
SystemCriticalityLevel defLevel = this.systemDomainCriticalityLevelService
.getDefaultByLevelEnum(levelType == SystemDomainCriticalityLevelDTO.LevelType.FUNC ?
SystemDomainCriticalFunctionCriticalityLevel.class : SystemDomainCentralApplicationCriticalityLevel.class,
levelEnum);
// set to default
if (dto == null) {
dto = new SystemDomainCriticalityLevelDTO((CriticalityLevel) defLevel);
dto.id = 0;
} else {
dto.name = defLevel.getName();
dto.longDescription = defLevel.getLongDescription();
}
dto.levelType = levelType;
dto.systemDomainId = this.getSessionSystemDomain().id;
// set original description
SystemDomainCriticalityLevel cl = dto.getDomainObject();
cl.setDescription(dto.origDescription);
// restore text
this.systemDomainCriticalityLevelService.update(cl);
return SUCCESS;
}
private void putInSessionTmp() {
TmpSessionValue tmpSessionValue = new TmpSessionValue();
tmpSessionValue.putInSessionCLMap(SystemDomainCriticalityLevelDTO.LevelType.FUNC, this.clFuncMap);
tmpSessionValue.putInSessionCLMap(SystemDomainCriticalityLevelDTO.LevelType.APPL, this.clApplMap);
this.putInSession(SessionKey.tmpKey, tmpSessionValue);
}
private String updateCFDesc(boolean isRestore) {
List<SystemDomainCriticalityLevel> dObjList = new ArrayList<SystemDomainCriticalityLevel>();
Set<String> keys = this.clFuncMap.keySet();
for (String key : keys) {
SystemDomainCriticalityLevelDTO dto = this.clFuncMap.get(key);
if (isRestore || dto.description == null || dto.description.trim().length() == 0) {
SystemCriticalityLevel defLevel = this.systemDomainCriticalityLevelService
.getDefaultByLevelEnum(SystemDomainCriticalFunctionCriticalityLevel.class, CriticalityLevelEnum.valueOf(key));
dto.description = defLevel.getDescription();
}
dto.levelType = SystemDomainCriticalityLevelDTO.LevelType.FUNC;
dto.systemDomainId = this.getSessionSystemDomain().id;
dto.origDescription = dto.description;
dObjList.add(dto.getDomainObject());
}
this.systemDomainCriticalityLevelService.updateAllDescriptions(dObjList);
return SUCCESS;
}
public Map<String, SystemDomainCriticalityLevelDTO> getClFuncMap() {
return this.clFuncMap;
}
public void setClFuncMap(Map<String, SystemDomainCriticalityLevelDTO> clFuncMap) {
this.clFuncMap = clFuncMap;
}
public Map<String, SystemDomainCriticalityLevelDTO> getClApplMap() {
return this.clApplMap;
}
public void setClApplMap(Map<String, SystemDomainCriticalityLevelDTO> clApplMap) {
this.clApplMap = clApplMap;
}
public String getClType() {
return this.clType;
}
public void setClType(String clType) {
this.clType = clType;
}
public String getClEnum() {
return this.clEnum;
}
public void setClEnum(String clEnum) {
this.clEnum = clEnum;
}
@Override
public void prepare() throws Exception {
}
}
| |
/*
* Copyright (c) 2015, Andrey Lavrov <lavroff@gmail.com>
* 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.
*
* 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 HOLDER 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 cy.alavrov.jminerguide.data.ship;
import cy.alavrov.jminerguide.data.character.EVECharacter;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
/**
* Ship hulls.
* @author Andrey Lavrov <lavroff@gmail.com>
*/
public enum Hull {
VENTURE("Venture",
32880, 2, false, 1, 3, false, 5000, 100, 100, 0, 10, new BonusCalculator() {
@Override
public BonusCalculationResult calculate(EVECharacter pilot) {
float yieldmod = 1f + 0.05f * pilot.getSkillLevel(EVECharacter.SKILL_MINING_FRIGATE);
float cyclemod = 1f - 0.05f * pilot.getSkillLevel(EVECharacter.SKILL_MINING_FRIGATE);
return new BonusCalculationResult(yieldmod, cyclemod, 1, 1, 1);
}
}),
PROSPECT("Prospect",
33697, 2, false, 4, 2, false, 10000, 100, 100, 0, 0, new BonusCalculator() {
@Override
public BonusCalculationResult calculate(EVECharacter pilot) {
float yieldmod = (1f + 0.05f * pilot.getSkillLevel(EVECharacter.SKILL_MINING_FRIGATE))
*(1f + 0.05f * pilot.getSkillLevel(EVECharacter.SKILL_EXPEDITION_FRIGATES));
float cyclemod = 1f - 0.05f * pilot.getSkillLevel(EVECharacter.SKILL_MINING_FRIGATE);
return new BonusCalculationResult(yieldmod, cyclemod, 1, 1, 1);
}
}),
PROCURER("Procurer",
17480, 1, true, 2, 3, true, 12000, 150, 0, 60, 25, new BonusCalculator() {
@Override
public BonusCalculationResult calculate(EVECharacter pilot) {
float durmod = 1f - 0.02f * pilot.getSkillLevel(EVECharacter.SKILL_MINING_BARGE);
return new BonusCalculationResult(1, 1, durmod, 1, 1);
}
}),
RETRIEVER("Retriever",
17478, 2, true, 3, 3, true, 22000, 25, 0, 20, 25, new BonusCalculator() {
@Override
public BonusCalculationResult calculate(EVECharacter pilot) {
float durmod = 1f - 0.02f * pilot.getSkillLevel(EVECharacter.SKILL_MINING_BARGE);
float cargomod = 1f + 0.05f * pilot.getSkillLevel(EVECharacter.SKILL_MINING_BARGE);
return new BonusCalculationResult(1, 1, durmod, cargomod, 1);
}
}),
COVETOR("Covetor",
17476, 3, true, 2, 3, true, 7000, 0, 0, 0, 50, new BonusCalculator() {
@Override
public BonusCalculationResult calculate(EVECharacter pilot) {
float durmod = 1f - 0.04f * pilot.getSkillLevel(EVECharacter.SKILL_MINING_BARGE);
float distmod = 1f + 0.05f * pilot.getSkillLevel(EVECharacter.SKILL_MINING_BARGE);
return new BonusCalculationResult(1, 1, durmod, 1, distmod);
}
}),
SKIFF("Skiff",
22546, 1, true, 3, 2, true, 15000, 150, 0, 60, 50, new BonusCalculator() {
@Override
public BonusCalculationResult calculate(EVECharacter pilot) {
float durmod = (1f - 0.02f * pilot.getSkillLevel(EVECharacter.SKILL_MINING_BARGE))*
(1f - 0.02f * pilot.getSkillLevel(EVECharacter.SKILL_EXHUMERS));
return new BonusCalculationResult(1, 1, durmod, 1, 1);
}
}),
MACKINAW("Mackinaw",
22548, 2, true, 3, 2, true, 28000, 25, 0, 20, 50, new BonusCalculator() {
@Override
public BonusCalculationResult calculate(EVECharacter pilot) {
float durmod = (1f - 0.02f * pilot.getSkillLevel(EVECharacter.SKILL_MINING_BARGE))*
(1f - 0.02f * pilot.getSkillLevel(EVECharacter.SKILL_EXHUMERS));
float cargomod = 1f + 0.05f * pilot.getSkillLevel(EVECharacter.SKILL_MINING_BARGE);
return new BonusCalculationResult(1, 1, durmod, cargomod, 1);
}
}),
HULK("Hulk",
22544, 3, true, 2, 2, true, 8500, 0, 0, 0, 50, new BonusCalculator() {
@Override
public BonusCalculationResult calculate(EVECharacter pilot) {
float durmod = (1f - 0.04f * pilot.getSkillLevel(EVECharacter.SKILL_MINING_BARGE))*
(1f - 0.03f * pilot.getSkillLevel(EVECharacter.SKILL_EXHUMERS));
float distmod = 1f + 0.05f * pilot.getSkillLevel(EVECharacter.SKILL_MINING_BARGE);
return new BonusCalculationResult(1, 1, durmod, 1, distmod);
}
}),
GENERIC("Generic hull",
1, 8, false, 8, 3, false, 500, 0, 0, 0, 50, new BonusCalculator() {
@Override
public BonusCalculationResult calculate(EVECharacter pilot) {
return new BonusCalculationResult(1, 1, 1, 1, 1);
}
}),
GENERICMEDIUM("Generic medium hull",
2, 8, false, 8, 3, true, 500, 0, 0, 0, 50, new BonusCalculator() {
@Override
public BonusCalculationResult calculate(EVECharacter pilot) {
return new BonusCalculationResult(1, 1, 1, 1, 1);
}
});
public final static Map<Integer, Hull> hullsMap;
static {
Map<Integer, Hull> hulls = new HashMap<>();
for (Hull hull : Hull.values()) {
hulls.put(hull.id, hull);
}
hullsMap = Collections.unmodifiableMap(hulls);
}
private final String name;
private final int id;
private final int maxTurrets;
private final boolean stripMiners;
private final int maxUpgrades;
private final int rigSlots;
private final boolean mediumHull;
private final int oreHold;
private final int roleMiningYieldBonus;
private final int roleGasYieldBonus;
private final int roleIceCycleBonus;
private final int droneBandwidth;
private final BonusCalculator calculator;
private Hull(String name, int id, int maxTurrets, boolean stripMiners,
int maxUpgrades, int rigSlots, boolean mediumHull, int oreHold,
int roleMiningYieldBonus, int roleGasYieldBonus, int roleIceCycleBonus,
int droneBandwidth, BonusCalculator calculator) {
this.name = name;
this.id = id;
this.maxTurrets = maxTurrets;
this.stripMiners = stripMiners;
this.maxUpgrades = maxUpgrades;
this.rigSlots = rigSlots;
this.mediumHull = mediumHull;
this.oreHold = oreHold;
this.roleMiningYieldBonus = roleMiningYieldBonus;
this.roleGasYieldBonus = roleGasYieldBonus;
this.roleIceCycleBonus = roleIceCycleBonus;
this.droneBandwidth = droneBandwidth;
this.calculator = calculator;
}
/**
* Returns hull name - just as you see it ingame.
* @return
*/
public String getName() {
return name;
}
/**
* Returns internal hull's id.
* @return
*/
public int getID() {
return id;
}
/**
* How many mining turrets can be fitted on?
* @return
*/
public int getMaxTurrets() {
return maxTurrets;
}
/**
* Returns true, if strip miners and ice harvesters can be fitted on.
* @return
*/
public boolean isUsingStripMiners() {
return stripMiners;
}
/**
* How many harvesting upgrades can be fitted on?
* @return
*/
public int getMaxUpgrades() {
return maxUpgrades;
}
/**
* How many rig slots are there?
* @return
*/
public int getRigSlots() {
return rigSlots;
}
/**
* Returns true, if hull size is medium.
* Availability of some rigs depend on this.
* @return
*/
public boolean isMediumHull() {
return mediumHull;
}
/**
* Returns ore hold volume, in cubic metres.
* @return
*/
public int getOreHold() {
return oreHold;
}
/**
* Returns mining yield bonus, granted by hull's role, in percents.
* @return
*/
public int getRoleMiningYieldBonus() {
return roleMiningYieldBonus;
}
/**
* Returns gas yield bonus, granted by hull's role, in percents.
* @return
*/
public int getRoleGasYieldBonus() {
return roleGasYieldBonus;
}
/**
* Returns various bonus modificators, granted by relevant ship skills on a pilot.
* @param pilot
* @return
*/
public BonusCalculationResult calculateSkillBonusModificators(EVECharacter pilot) {
return calculator.calculate(pilot);
}
/**
* Returns ice harvester cycle bonus, granted by hull's role, in percents.
* @return
*/
public int getRoleIceCycleBonus() {
return roleIceCycleBonus;
}
/**
* Returns ice harvester cycle bonus, granted by hull's role, in percents.
* @return
*/
public int getDroneBandwidth() {
return droneBandwidth;
}
@Override
public String toString() {
return name;
}
private interface BonusCalculator {
BonusCalculationResult calculate(EVECharacter pilot);
}
public static class BonusCalculationResult {
public final float miningYieldMod;
public final float gasCycleMod;
public final float stripCycleMod;
public final float oreHoldMod;
public final float stripOptimalMod;
protected BonusCalculationResult(float miningYieldMod, float gasCycleMod,
float stripCycleMod, float oreHoldMod, float stripOptimalMod) {
this.miningYieldMod = miningYieldMod;
this.gasCycleMod = gasCycleMod;
this.stripCycleMod = stripCycleMod;
this.oreHoldMod = oreHoldMod;
this.stripOptimalMod = stripOptimalMod;
}
}
}
| |
package org.spongycastle.crypto.macs;
import org.spongycastle.crypto.CipherParameters;
import org.spongycastle.crypto.DataLengthException;
import org.spongycastle.crypto.Mac;
import org.spongycastle.crypto.params.KeyParameter;
import org.spongycastle.crypto.params.ParametersWithSBox;
/**
* implementation of GOST 28147-89 MAC
*/
public class GOST28147Mac
implements Mac
{
private int blockSize = 8;
private int macSize = 4;
private int bufOff;
private byte[] buf;
private byte[] mac;
private boolean firstStep = true;
private int[] workingKey = null;
//
// This is default S-box - E_A.
private byte S[] = {
0x9,0x6,0x3,0x2,0x8,0xB,0x1,0x7,0xA,0x4,0xE,0xF,0xC,0x0,0xD,0x5,
0x3,0x7,0xE,0x9,0x8,0xA,0xF,0x0,0x5,0x2,0x6,0xC,0xB,0x4,0xD,0x1,
0xE,0x4,0x6,0x2,0xB,0x3,0xD,0x8,0xC,0xF,0x5,0xA,0x0,0x7,0x1,0x9,
0xE,0x7,0xA,0xC,0xD,0x1,0x3,0x9,0x0,0x2,0xB,0x4,0xF,0x8,0x5,0x6,
0xB,0x5,0x1,0x9,0x8,0xD,0xF,0x0,0xE,0x4,0x2,0x3,0xC,0x7,0xA,0x6,
0x3,0xA,0xD,0xC,0x1,0x2,0x0,0xB,0x7,0x5,0x9,0x4,0x8,0xF,0xE,0x6,
0x1,0xD,0x2,0x9,0x7,0xA,0x6,0x0,0x8,0xC,0x4,0x5,0xF,0x3,0xB,0xE,
0xB,0xA,0xF,0x5,0x0,0xC,0xE,0x8,0x6,0x2,0x3,0x9,0x1,0x7,0xD,0x4
};
public GOST28147Mac()
{
mac = new byte[blockSize];
buf = new byte[blockSize];
bufOff = 0;
}
private int[] generateWorkingKey(
byte[] userKey)
{
if (userKey.length != 32)
{
throw new IllegalArgumentException("Key length invalid. Key needs to be 32 byte - 256 bit!!!");
}
int key[] = new int[8];
for(int i=0; i!=8; i++)
{
key[i] = bytesToint(userKey,i*4);
}
return key;
}
public void init(
CipherParameters params)
throws IllegalArgumentException
{
reset();
buf = new byte[blockSize];
if (params instanceof ParametersWithSBox)
{
ParametersWithSBox param = (ParametersWithSBox)params;
//
// Set the S-Box
//
System.arraycopy(param.getSBox(), 0, this.S, 0, param.getSBox().length);
//
// set key if there is one
//
if (param.getParameters() != null)
{
workingKey = generateWorkingKey(((KeyParameter)param.getParameters()).getKey());
}
}
else if (params instanceof KeyParameter)
{
workingKey = generateWorkingKey(((KeyParameter)params).getKey());
}
else
{
throw new IllegalArgumentException("invalid parameter passed to GOST28147 init - " + params.getClass().getName());
}
}
public String getAlgorithmName()
{
return "GOST28147Mac";
}
public int getMacSize()
{
return macSize;
}
private int gost28147_mainStep(int n1, int key)
{
int cm = (key + n1); // CM1
// S-box replacing
int om = S[ 0 + ((cm >> (0 * 4)) & 0xF)] << (0 * 4);
om += S[ 16 + ((cm >> (1 * 4)) & 0xF)] << (1 * 4);
om += S[ 32 + ((cm >> (2 * 4)) & 0xF)] << (2 * 4);
om += S[ 48 + ((cm >> (3 * 4)) & 0xF)] << (3 * 4);
om += S[ 64 + ((cm >> (4 * 4)) & 0xF)] << (4 * 4);
om += S[ 80 + ((cm >> (5 * 4)) & 0xF)] << (5 * 4);
om += S[ 96 + ((cm >> (6 * 4)) & 0xF)] << (6 * 4);
om += S[112 + ((cm >> (7 * 4)) & 0xF)] << (7 * 4);
return om << 11 | om >>> (32-11); // 11-leftshift
}
private void gost28147MacFunc(
int[] workingKey,
byte[] in,
int inOff,
byte[] out,
int outOff)
{
int N1, N2, tmp; //tmp -> for saving N1
N1 = bytesToint(in, inOff);
N2 = bytesToint(in, inOff + 4);
for(int k = 0; k < 2; k++) // 1-16 steps
{
for(int j = 0; j < 8; j++)
{
tmp = N1;
N1 = N2 ^ gost28147_mainStep(N1, workingKey[j]); // CM2
N2 = tmp;
}
}
intTobytes(N1, out, outOff);
intTobytes(N2, out, outOff + 4);
}
//array of bytes to type int
private int bytesToint(
byte[] in,
int inOff)
{
return ((in[inOff + 3] << 24) & 0xff000000) + ((in[inOff + 2] << 16) & 0xff0000) +
((in[inOff + 1] << 8) & 0xff00) + (in[inOff] & 0xff);
}
//int to array of bytes
private void intTobytes(
int num,
byte[] out,
int outOff)
{
out[outOff + 3] = (byte)(num >>> 24);
out[outOff + 2] = (byte)(num >>> 16);
out[outOff + 1] = (byte)(num >>> 8);
out[outOff] = (byte)num;
}
private byte[] CM5func(byte[] buf, int bufOff, byte[] mac)
{
byte[] sum = new byte[buf.length - bufOff];
System.arraycopy(buf, bufOff, sum, 0, mac.length);
for (int i = 0; i != mac.length; i++)
{
sum[i] = (byte)(sum[i] ^ mac[i]);
}
return sum;
}
public void update(byte in)
throws IllegalStateException
{
if (bufOff == buf.length)
{
byte[] sumbuf = new byte[buf.length];
System.arraycopy(buf, 0, sumbuf, 0, mac.length);
if (firstStep)
{
firstStep = false;
}
else
{
sumbuf = CM5func(buf, 0, mac);
}
gost28147MacFunc(workingKey, sumbuf, 0, mac, 0);
bufOff = 0;
}
buf[bufOff++] = in;
}
public void update(byte[] in, int inOff, int len)
throws DataLengthException, IllegalStateException
{
if (len < 0)
{
throw new IllegalArgumentException("Can't have a negative input length!");
}
int gapLen = blockSize - bufOff;
if (len > gapLen)
{
System.arraycopy(in, inOff, buf, bufOff, gapLen);
byte[] sumbuf = new byte[buf.length];
System.arraycopy(buf, 0, sumbuf, 0, mac.length);
if (firstStep)
{
firstStep = false;
}
else
{
sumbuf = CM5func(buf, 0, mac);
}
gost28147MacFunc(workingKey, sumbuf, 0, mac, 0);
bufOff = 0;
len -= gapLen;
inOff += gapLen;
while (len > blockSize)
{
sumbuf = CM5func(in, inOff, mac);
gost28147MacFunc(workingKey, sumbuf, 0, mac, 0);
len -= blockSize;
inOff += blockSize;
}
}
System.arraycopy(in, inOff, buf, bufOff, len);
bufOff += len;
}
public int doFinal(byte[] out, int outOff)
throws DataLengthException, IllegalStateException
{
//padding with zero
while (bufOff < blockSize)
{
buf[bufOff] = 0;
bufOff++;
}
byte[] sumbuf = new byte[buf.length];
System.arraycopy(buf, 0, sumbuf, 0, mac.length);
if (firstStep)
{
firstStep = false;
}
else
{
sumbuf = CM5func(buf, 0, mac);
}
gost28147MacFunc(workingKey, sumbuf, 0, mac, 0);
System.arraycopy(mac, (mac.length/2)-macSize, out, outOff, macSize);
reset();
return macSize;
}
public void reset()
{
/*
* clean the buffer.
*/
for (int i = 0; i < buf.length; i++)
{
buf[i] = 0;
}
bufOff = 0;
firstStep = true;
}
}
| |
/*
* Copyright (c) Corporation for National Research Initiatives
* Copyright (c) Jython Developers
*/
package org.python.core;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.concurrent.Callable;
import org.python.core.finalization.FinalizableBuiltin;
import org.python.core.finalization.FinalizeTrigger;
import org.python.core.io.BinaryIOWrapper;
import org.python.core.io.BufferedIOBase;
import org.python.core.io.BufferedRandom;
import org.python.core.io.BufferedReader;
import org.python.core.io.BufferedWriter;
import org.python.core.io.FileIO;
import org.python.core.io.IOBase;
import org.python.core.io.LineBufferedRandom;
import org.python.core.io.LineBufferedWriter;
import org.python.core.io.RawIOBase;
import org.python.core.io.StreamIO;
import org.python.core.io.TextIOBase;
import org.python.core.io.TextIOWrapper;
import org.python.core.io.UniversalIOWrapper;
import org.python.expose.ExposedDelete;
import org.python.expose.ExposedGet;
import org.python.expose.ExposedMethod;
import org.python.expose.ExposedNew;
import org.python.expose.ExposedSet;
import org.python.expose.ExposedType;
/**
* The Python file type. Wraps an {@link TextIOBase} object.
*/
@ExposedType(name = "file", doc = BuiltinDocs.file_doc)
public class PyFile extends PyObject implements FinalizableBuiltin, Traverseproc {
public static final PyType TYPE = PyType.fromClass(PyFile.class);
/** The filename */
@ExposedGet(doc = BuiltinDocs.file_name_doc)
public PyObject name;
/** The mode string */
@ExposedGet(doc = BuiltinDocs.file_mode_doc)
public String mode;
@ExposedGet(doc = BuiltinDocs.file_encoding_doc)
public String encoding;
@ExposedGet(doc = BuiltinDocs.file_errors_doc)
public String errors;
/** Indicator dictating whether a space should be written to this
* file on the next print statement (not currently implemented in
* print ) */
public boolean softspace = false;
/** Whether this file is opened for reading */
private boolean reading = false;
/** Whether this file is opened for writing */
private boolean writing = false;
/** Whether this file is opened in appending mode */
private boolean appending = false;
/** Whether this file is opened for updating */
private boolean updating = false;
/** Whether this file is opened in binary mode */
private boolean binary = false;
/** Whether this file is opened in universal newlines mode */
private boolean universal = false;
/** The underlying IO object */
private TextIOBase file;
/** The file's closer object; ensures the file is closed at
* shutdown */
private Closer closer;
public PyFile() {FinalizeTrigger.ensureFinalizer(this);}
public PyFile(PyType subType) {
super(subType);
FinalizeTrigger.ensureFinalizer(this);
}
public PyFile(RawIOBase raw, String name, String mode, int bufsize) {
parseMode(mode);
file___init__(raw, name, mode, bufsize);
FinalizeTrigger.ensureFinalizer(this);
}
public PyFile(InputStream istream, String name, String mode, int bufsize, boolean closefd) {
parseMode(mode);
file___init__(new StreamIO(istream, closefd), name, mode, bufsize);
FinalizeTrigger.ensureFinalizer(this);
}
/**
* Creates a file object wrapping the given <code>InputStream</code>. The builtin
* method <code>file</code> doesn't expose this functionality (<code>open</code> does
* albeit deprecated) as it isn't available to regular Python code. To wrap an
* InputStream in a file from Python, use
* {@link org.python.core.util.FileUtil#wrap(InputStream, String, int)}
* {@link org.python.core.util.FileUtil#wrap(InputStream, String)}
* {@link org.python.core.util.FileUtil#wrap(InputStream, int)}
* {@link org.python.core.util.FileUtil#wrap(InputStream)}
*/
public PyFile(InputStream istream, String mode, int bufsize) {
this(istream, "<Java InputStream '" + istream + "' as file>", mode, bufsize, true);
}
public PyFile(InputStream istream, String mode) {
this(istream, mode, -1);
}
public PyFile(InputStream istream, int bufsize) {
this(istream, "r", bufsize);
}
public PyFile(InputStream istream) {
this(istream, -1);
}
public PyFile(OutputStream ostream, String name, String mode, int bufsize, boolean closefd) {
parseMode(mode);
file___init__(new StreamIO(ostream, closefd), name, mode, bufsize);
FinalizeTrigger.ensureFinalizer(this);
}
/**
* Creates a file object wrapping the given <code>OutputStream</code>. The builtin
* method <code>file</code> doesn't expose this functionality (<code>open</code> does
* albeit deprecated) as it isn't available to regular Python code. To wrap an
* OutputStream in a file from Python, use
* {@link org.python.core.util.FileUtil#wrap(OutputStream, String, int)}
* {@link org.python.core.util.FileUtil#wrap(OutputStream, String)}
* {@link org.python.core.util.FileUtil#wrap(OutputStream, int)}
* {@link org.python.core.util.FileUtil#wrap(OutputStream)}
*/
public PyFile(OutputStream ostream, String mode, int bufsize) {
this(ostream, "<Java OutputStream '" + ostream + "' as file>", mode, bufsize, true);
}
public PyFile(OutputStream ostream, int bufsize) {
this(ostream, "w", bufsize);
}
public PyFile(OutputStream ostream) {
this(ostream, -1);
}
public PyFile(String name, String mode, int bufsize) {
file___init__(new FileIO(name, parseMode(mode)), name, mode, bufsize);
FinalizeTrigger.ensureFinalizer(this);
}
@ExposedNew
@ExposedMethod(doc = BuiltinDocs.file___init___doc)
final void file___init__(PyObject[] args, String[] kwds) {
ArgParser ap = new ArgParser("file", args, kwds, new String[] {"name", "mode", "buffering"},
1);
PyObject name = ap.getPyObject(0);
if (!(name instanceof PyString)) {
throw Py.TypeError("coercing to Unicode: need string, '" + name.getType().fastGetName()
+ "' type found");
}
String mode = ap.getString(1, "r");
int bufsize = ap.getInt(2, -1);
file___init__(new FileIO((PyString) name, parseMode(mode)), name, mode, bufsize);
closer = new Closer(file, Py.getSystemState());
}
private void file___init__(RawIOBase raw, String name, String mode, int bufsize) {
file___init__(raw, new PyString(name), mode, bufsize);
}
private void file___init__(RawIOBase raw, PyObject name, String mode, int bufsize) {
this.name = name;
this.mode = mode;
BufferedIOBase buffer = createBuffer(raw, bufsize);
if (universal) {
this.file = new UniversalIOWrapper(buffer);
} else if (!binary) {
this.file = new TextIOWrapper(buffer);
} else {
this.file = new BinaryIOWrapper(buffer);
}
}
/**
* Set the strings defining the encoding and error handling policy. Setting these strings
* affects behaviour of the {@link #writelines(PyObject)} when passed a {@link PyUnicode} value.
*
* @param encoding the <code>encoding</code> property of <code>file</code>.
* @param errors the <code>errors</code> property of <code>file</code> (or <code>null</code>).
*/
void setEncoding(String encoding, String errors) {
this.encoding = encoding;
this.errors = errors;
}
/**
* Wrap the given RawIOBase with a BufferedIOBase according to the
* mode and given bufsize.
*
* @param raw a RawIOBase value
* @param bufsize an int size of the buffer
* @return a BufferedIOBase wrapper
*/
private BufferedIOBase createBuffer(RawIOBase raw, int bufsize) {
if (bufsize < 0) {
bufsize = IOBase.DEFAULT_BUFFER_SIZE;
}
boolean lineBuffered = bufsize == 1;
BufferedIOBase buffer;
if (updating) {
buffer = lineBuffered ? new LineBufferedRandom(raw) : new BufferedRandom(raw, bufsize);
} else if (writing || appending) {
buffer = lineBuffered ? new LineBufferedWriter(raw) : new BufferedWriter(raw, bufsize);
} else if (reading) {
// Line buffering is for output only
buffer = new BufferedReader(raw, lineBuffered ? IOBase.DEFAULT_BUFFER_SIZE : bufsize);
} else {
// Should never happen
throw Py.ValueError("unknown mode: '" + mode + "'");
}
return buffer;
}
/**
* Parse and validate the python file mode, returning a cleaned file mode suitable for FileIO.
*
* @param mode a python file mode String
* @return a RandomAccessFile mode String
*/
private String parseMode(String mode) {
String message = null;
boolean duplicate = false, invalid = false, text_intent = false;
int n = mode.length();
// Convert the letters to booleans, noticing duplicates
for (int i = 0; i < n; i++) {
char c = mode.charAt(i);
switch (c) {
case 'r':
duplicate = reading;
reading = true;
break;
case 'w':
duplicate = writing;
writing = true;
break;
case 'a':
duplicate = appending;
appending = true;
break;
case '+':
duplicate = updating;
updating = true;
break;
case 'b':
duplicate = binary;
binary = true;
break;
case 't':
duplicate = text_intent;
text_intent = true;
binary = false;
break;
case 'U':
duplicate = universal;
universal = true;
break;
default:
invalid = true;
}
// duplicate is set iff c was encountered previously */
if (duplicate) {
invalid = true;
break;
}
}
// Implications
reading |= universal;
binary |= universal;
// Standard tests and the mode for FileIO
StringBuilder fileioMode = new StringBuilder();
if (!invalid) {
if (universal && (writing || appending)) {
// Not quite true, consider 'Ub', but it's what CPython says:
message = "universal newline mode can only be used with modes starting with 'r'";
} else {
// Build the FileIO mode string
if (reading) {
fileioMode.append('r');
}
if (writing) {
fileioMode.append('w');
}
if (appending) {
fileioMode.append('a');
}
if (fileioMode.length() != 1) {
// We should only have added one of the above
message = "mode string must begin with one of 'r', 'w', 'a' or 'U', not '" //
+ mode + "'";
}
if (updating) {
fileioMode.append('+');
}
}
invalid |= (message != null);
}
// Finally, if invalid, report this as an error
if (invalid) {
if (message == null) {
// Duplicates discovered or invalid symbols
message = String.format("invalid mode: '%.20s'", mode);
}
throw Py.ValueError(message);
}
return fileioMode.toString();
}
@ExposedMethod(defaults = {"-1"}, doc = BuiltinDocs.file_read_doc)
final synchronized PyString file_read(int size) {
checkClosed();
return new PyString(file.read(size));
}
public PyString read(int size) {
return file_read(size);
}
public PyString read() {
return file_read(-1);
}
@ExposedMethod(doc = BuiltinDocs.file_readinto_doc)
final synchronized int file_readinto(PyObject buf) {
checkClosed();
return file.readinto(buf);
}
public int readinto(PyObject buf) {
return file_readinto(buf);
}
@ExposedMethod(defaults = {"-1"}, doc = BuiltinDocs.file_readline_doc)
final synchronized PyString file_readline(int max) {
checkClosed();
return new PyString(file.readline(max));
}
public PyString readline(int max) {
return file_readline(max);
}
public PyString readline() {
return file_readline(-1);
}
@ExposedMethod(defaults = {"0"}, doc = BuiltinDocs.file_readlines_doc)
final synchronized PyObject file_readlines(int sizehint) {
checkClosed();
PyList list = new PyList();
int count = 0;
do {
String line = file.readline(-1);
int len = line.length();
if (len == 0) {
// EOF
break;
}
count += len;
list.append(new PyString(line));
} while (sizehint <= 0 || count < sizehint);
return list;
}
public PyObject readlines(int sizehint) {
return file_readlines(sizehint);
}
public PyObject readlines() {
return file_readlines(0);
}
@Override
public PyObject __iternext__() {
return file___iternext__();
}
final synchronized PyObject file___iternext__() {
checkClosed();
String next = file.readline(-1);
if (next.length() == 0) {
return null;
}
return new PyString(next);
}
@ExposedMethod(doc = BuiltinDocs.file_next_doc)
final PyObject file_next() {
PyObject ret = file___iternext__();
if (ret == null) {
throw Py.StopIteration("");
}
return ret;
}
public PyObject next() {
return file_next();
}
@ExposedMethod(names = {"__enter__", "__iter__", "xreadlines"},
doc = BuiltinDocs.file___iter___doc)
final PyObject file_self() {
checkClosed();
return this;
}
public PyObject __enter__() {
return file_self();
}
@Override
public PyObject __iter__() {
return file_self();
}
public PyObject xreadlines() {
return file_self();
}
@ExposedMethod(doc = BuiltinDocs.file_write_doc)
final void file_write(PyObject obj) {
file_write(asWritable(obj, null));
}
final synchronized void file_write(String string) {
checkClosed();
softspace = false;
file.write(string);
}
public void write(String string) {
file_write(string);
}
@ExposedMethod(doc = BuiltinDocs.file_writelines_doc)
final synchronized void file_writelines(PyObject lines) {
checkClosed();
PyObject iter = Py.iter(lines, "writelines() requires an iterable argument");
for (PyObject item = null; (item = iter.__iternext__()) != null;) {
checkClosed(); // ... in case a nasty iterable closed this file
softspace = false;
file.write(asWritable(item, "writelines() argument must be a sequence of strings"));
}
}
public void writelines(PyObject lines) {
file_writelines(lines);
}
/**
* Return a String for writing to the underlying file from obj. This is a helper for {@link file_write}
* and {@link file_writelines}.
*
* @param obj to write
* @param message for TypeError if raised (or null for default message)
* @return bytes representing the value (as a String in the Jython convention)
*/
private String asWritable(PyObject obj, String message) {
if (obj instanceof PyUnicode) {
// Unicode must be encoded into bytes (null arguments here invoke the default values)
return ((PyUnicode)obj).encode(encoding, errors);
} else if (obj instanceof PyString) {
// Take a short cut
return ((PyString)obj).getString();
} else if (obj instanceof PyArray && !binary) {
// Fall through to TypeError. (If binary, BufferProtocol takes care of PyArray.)
} else if (obj instanceof BufferProtocol) {
// Try to get a byte-oriented buffer
try (PyBuffer buf = ((BufferProtocol)obj).getBuffer(PyBUF.FULL_RO)) {
// ... and treat those bytes as a String
return buf.toString();
}
}
if (message == null) {
// Messages differ for text or binary streams (CPython) but we always add the type
String.format("%s buffer, not %.200s", (binary ? "must be string or"
: "expected a character"), obj.getType().fastGetName());
}
throw Py.TypeError(message);
}
@ExposedMethod(doc = BuiltinDocs.file_tell_doc)
final synchronized long file_tell() {
checkClosed();
return file.tell();
}
public long tell() {
return file_tell();
}
@ExposedMethod(defaults = {"0"}, doc = BuiltinDocs.file_seek_doc)
final synchronized void file_seek(long pos, int how) {
checkClosed();
file.seek(pos, how);
}
public void seek(long pos, int how) {
file_seek(pos, how);
}
public void seek(long pos) {
file_seek(pos, 0);
}
@ExposedMethod(doc = BuiltinDocs.file_flush_doc)
final synchronized void file_flush() {
checkClosed();
file.flush();
}
public void flush() {
file_flush();
}
@ExposedMethod(doc = BuiltinDocs.file_close_doc)
final synchronized void file_close() {
if (closer != null) {
closer.close();
closer = null;
} else {
file.close();
}
}
public void close() {
file_close();
}
@ExposedMethod(doc = BuiltinDocs.file___exit___doc)
final void file___exit__(PyObject type, PyObject value, PyObject traceback) {
close();
}
public void __exit__(PyObject type, PyObject value, PyObject traceback) {
file___exit__(type, value, traceback);
}
@ExposedMethod(defaults = {"null"}, doc = BuiltinDocs.file_truncate_doc)
final void file_truncate(PyObject position) {
if (position == null) {
file_truncate();
return;
}
file_truncate(position.asLong());
}
final synchronized void file_truncate(long position) {
file.truncate(position);
}
public void truncate(long position) {
file_truncate(position);
}
final synchronized void file_truncate() {
file.truncate(file.tell());
}
public void truncate() {
file_truncate();
}
public boolean isatty() {
return file_isatty();
}
@ExposedMethod(doc = BuiltinDocs.file_isatty_doc)
final boolean file_isatty() {
return file.isatty();
}
public PyObject fileno() {
return file_fileno();
}
@ExposedMethod(doc = BuiltinDocs.file_fileno_doc)
final PyObject file_fileno() {
return PyJavaType.wrapJavaObject(file.fileno());
}
@ExposedMethod(names = {"__str__", "__repr__"}, doc = BuiltinDocs.file___str___doc)
final String file_toString() {
String state = file.closed() ? "closed" : "open";
String id = Py.idstr(this);
String escapedName;
if (name instanceof PyUnicode) {
// unicode: always uses the format u'%s', and the escaped value thus:
escapedName = "u'"+PyString.encode_UnicodeEscape(name.toString(), false)+"'";
} else {
// anything else: uses repr(), which for str (common case) is smartly quoted
escapedName = name.__repr__().getString();
}
return String.format("<%s file %s, mode '%s' at %s>", state, escapedName, mode, id);
}
@Override
public String toString() {
return file_toString();
}
private void checkClosed() {
file.checkClosed();
}
@ExposedGet(name = "closed", doc = BuiltinDocs.file_closed_doc)
public boolean getClosed() {
return file.closed();
}
@ExposedGet(name = "newlines", doc = BuiltinDocs.file_newlines_doc)
public PyObject getNewlines() {
return file.getNewlines();
}
@ExposedGet(name = "softspace", doc = BuiltinDocs.file_softspace_doc)
public PyObject getSoftspace() {
// NOTE: not actual bools because CPython is this way
return softspace ? Py.One : Py.Zero;
}
@ExposedSet(name = "softspace")
public void setSoftspace(PyObject obj) {
softspace = obj.__nonzero__();
}
@ExposedDelete(name = "softspace")
public void delSoftspace() {
throw Py.TypeError("can't delete numeric/char attribute");
}
@Override
public Object __tojava__(Class<?> cls) {
Object obj = null;
if (InputStream.class.isAssignableFrom(cls)) {
obj = file.asInputStream();
} else if (OutputStream.class.isAssignableFrom(cls)) {
obj = file.asOutputStream();
}
if (obj == null) {
obj = super.__tojava__(cls);
}
return obj;
}
@Override
public void __del_builtin__() {
if (closer != null) {
closer.close();
}
}
/**
* XXX update docs - A mechanism to make sure PyFiles are closed on exit. On creation Closer adds itself
* to a list of Closers that will be run by PyFileCloser on JVM shutdown. When a
* PyFile's close or finalize methods are called, PyFile calls its Closer.close which
* clears Closer out of the shutdown queue.
*
* We use a regular object here rather than WeakReferences and their ilk as they may
* be collected before the shutdown hook runs. There's no guarantee that finalize will
* be called during shutdown, so we can't use it. It's vital that this Closer has no
* reference to the PyFile it's closing so the PyFile remains garbage collectable.
*/
private static class Closer implements Callable<Void> {
/**
* The underlying file
*/
private final TextIOBase file;
private PySystemState sys;
public Closer(TextIOBase file, PySystemState sys) {
this.file = file;
this.sys = sys;
sys.registerCloser(this);
}
/** For closing directly */
public void close() {
sys.unregisterCloser(this);
file.close();
sys = null;
}
/** For closing as part of a shutdown process */
@Override
public Void call() {
file.close();
sys = null;
return null;
}
}
/* Traverseproc implementation */
@Override
public int traverse(Visitproc visit, Object arg) {
return name == null ? 0 : visit.visit(name, arg);
}
@Override
public boolean refersDirectlyTo(PyObject ob) {
return ob != null && ob == name;
}
}
| |
package com.compomics.util.experiment.biology.enzymes;
import com.compomics.util.experiment.biology.aminoacids.AminoAcid;
import com.compomics.util.experiment.personalization.ExperimentObject;
import com.compomics.util.pride.CvTerm;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.stream.Collectors;
/**
* This class models an enzyme.
*
* @author Marc Vaudel
* @author Harald Barsnes
*/
public class Enzyme extends ExperimentObject {
/*
* The enzyme name.
*/
private final String name;
/*
* The amino acids before cleavage.
*/
private final HashSet<Character> aminoAcidBefore = new HashSet<>(0);
/*
* The amino acids after cleavage.
*/
private final HashSet<Character> aminoAcidAfter = new HashSet<>(0);
/*
* The restriction amino acids before cleavage.
*/
private final HashSet<Character> restrictionBefore = new HashSet<>(0);
/*
* The restriction amino acids after cleavage.
*/
private final HashSet<Character> restrictionAfter = new HashSet<>(0);
/**
* The CV term associated to this enzyme.
*/
private CvTerm cvTerm;
/**
* Empty default constructor.
*/
public Enzyme() {
name = "";
}
/**
* Constructor for an Enzyme.
*
* @param name the name of the enzyme
*/
public Enzyme(String name) {
this.name = name;
}
/**
* Get the enzyme name.
*
* @return the enzyme name as String
*/
public String getName() {
return name;
}
/**
* Adds an amino acid to the list of allowed amino acids after the cleavage
* site.
*
* @param aminoAcid an amino acid represented by its single amino acid code.
*/
public void addAminoAcidAfter(Character aminoAcid) {
aminoAcidAfter.add(aminoAcid);
}
/**
* Getter for the amino acids potentially following the cleavage. Null if
* none.
*
* @return the amino acids potentially following the cleavage
*/
public HashSet<Character> getAminoAcidAfter() {
return aminoAcidAfter;
}
/**
* Adds an amino acid to the list of allowed amino acids before the cleavage
* site.
*
* @param aminoAcid an amino acid represented by its single amino acid code.
*/
public void addAminoAcidBefore(Character aminoAcid) {
aminoAcidBefore.add(aminoAcid);
}
/**
* Getter for the amino acids potentially preceding the cleavage. Null if
* none.
*
* @return the amino acids potentially preceding the cleavage
*/
public HashSet<Character> getAminoAcidBefore() {
return aminoAcidBefore;
}
/**
* Adds an amino acid to the list of forbidden amino acids after the
* cleavage site.
*
* @param aminoAcid an amino acid represented by its single amino acid code.
*/
public void addRestrictionAfter(Character aminoAcid) {
restrictionAfter.add(aminoAcid);
}
/**
* Getter for the amino acids restricting when following the cleavage. Null
* if none.
*
* @return the amino acids restricting when following the cleavage
*/
public HashSet<Character> getRestrictionAfter() {
return restrictionAfter;
}
/**
* Adds an amino acid to the list of forbidden amino acids before the
* cleavage site.
*
* @param aminoAcid an amino acid represented by its single amino acid code.
*/
public void addRestrictionBefore(Character aminoAcid) {
restrictionBefore.add(aminoAcid);
}
/**
* Getter for the amino acids restricting when preceding the cleavage. Null
* if none.
*
* @return the amino acids restricting when preceding the cleavage
*/
public HashSet<Character> getRestrictionBefore() {
return restrictionBefore;
}
/**
* Returns a boolean indicating whether the given amino acids represent a
* cleavage site. Trypsin example: (D, E) returns false (R, D) returns true
* Note: returns false if no cleavage site is implemented.
*
* @param aaBefore the amino acid before the cleavage site
* @param aaAfter the amino acid after the cleavage site
*
* @return true if the amino acid combination can represent a cleavage site
*/
public boolean isCleavageSite(String aaBefore, String aaAfter) {
if (aaBefore.length() == 0 || aaAfter.length() == 0) {
return true;
}
return isCleavageSite(aaBefore.charAt(aaBefore.length() - 1), aaAfter.charAt(0));
}
/**
* Returns a boolean indicating whether the given amino acids represent a
* cleavage site. Amino acid combinations are extended to find possible
* restrictions or cleavage sites. Trypsin example: (D, E) returns false (R,
* D) returns true Note: returns false if no cleavage site is implemented.
*
* @param aaBefore the amino acid before the cleavage site
* @param aaAfter the amino acid after the cleavage site
*
* @return true if the amino acid combination can represent a cleavage site
*/
public boolean isCleavageSite(char aaBefore, char aaAfter) {
AminoAcid aminoAcid1 = AminoAcid.getAminoAcid(aaBefore);
AminoAcid aminoAcid2 = AminoAcid.getAminoAcid(aaAfter);
for (char possibleAaBefore : aminoAcid1.getSubAminoAcids()) {
if (aminoAcidBefore.contains(possibleAaBefore)) {
boolean restriction = false;
for (char possibleAaAfter : aminoAcid2.getSubAminoAcids()) {
if (restrictionAfter.contains(possibleAaAfter)) {
restriction = true;
break;
}
}
if (!restriction) {
return true;
}
}
}
for (char possibleAaAfter : aminoAcid2.getSubAminoAcids()) {
if (aminoAcidAfter.contains(possibleAaAfter)) {
boolean restriction = false;
for (char possibleAaBefore : aminoAcid1.getSubAminoAcids()) {
if (restrictionBefore.contains(possibleAaBefore)) {
restriction = true;
break;
}
}
if (!restriction) {
return true;
}
}
}
return false;
}
/**
* Returns a boolean indicating whether the given amino acids represent a
* cleavage site. This method does not support amino acid combinations.
* Trypsin example: (D, E) returns false (R, D) returns true Note: returns
* false if no cleavage site is implemented.
*
* @param aaBefore the amino acid before the cleavage site
* @param aaAfter the amino acid after the cleavage site
*
* @return true if the amino acid combination can represent a cleavage site
*/
public boolean isCleavageSiteNoCombination(Character aaBefore, Character aaAfter) {
return aminoAcidBefore.contains(aaBefore) && !restrictionAfter.contains(aaAfter)
|| aminoAcidAfter.contains(aaAfter) && !restrictionBefore.contains(aaBefore);
}
/**
* Returns the number of missed cleavages in an amino acid sequence.
*
* @param sequence the amino acid sequence as a string.
*
* @return the number of missed cleavages
*/
public int getNmissedCleavages(String sequence) {
int result = 0;
if (sequence.length() > 1) {
for (int i = 0; i < sequence.length() - 1; i++) {
if (isCleavageSite(sequence.charAt(i), sequence.charAt(i + 1))) {
result++;
}
}
}
return result;
}
/**
* Digests a protein sequence in a list of expected peptide sequences.
*
* @param sequence the protein sequence
* @param nMissedCleavages the maximum number of missed cleavages
* @param nMin the minimal size for a peptide (inclusive, ignored if null)
* @param nMax the maximal size for a peptide (inclusive, ignored if null)
*
* @return a list of expected peptide sequences
*/
public HashSet<String> digest(String sequence, int nMissedCleavages, Integer nMin, Integer nMax) {
char aa, aaBefore;
char aaAfter = sequence.charAt(0);
StringBuilder currentPeptide = new StringBuilder();
currentPeptide.append(aaAfter);
HashSet<String> results = new HashSet<>();
HashMap<Integer, ArrayList<String>> mc = new HashMap<>();
for (int i = 1; i <= nMissedCleavages; i++) {
mc.put(i, new ArrayList<>(nMissedCleavages));
}
for (int i = 1; i < sequence.length(); i++) {
aa = sequence.charAt(i);
aaBefore = aaAfter;
aaAfter = aa;
if (isCleavageSite(aaBefore, aaAfter) && currentPeptide.length() != 0) {
String currentPeptideString = currentPeptide.toString();
if ((nMin == null || currentPeptide.length() >= nMin) && (nMax == null || currentPeptide.length() <= nMax)) {
results.add(currentPeptideString);
}
for (int nMc : mc.keySet()) {
mc.get(nMc).add(currentPeptideString);
while (mc.get(nMc).size() > nMc + 1) {
mc.get(nMc).remove(0);
}
StringBuilder mcSequence = new StringBuilder();
for (String subPeptide : mc.get(nMc)) {
mcSequence.append(subPeptide);
}
if ((nMin == null || mcSequence.length() >= nMin) && (nMax == null || mcSequence.length() <= nMax)) {
results.add(mcSequence.toString());
}
}
currentPeptide = new StringBuilder();
}
currentPeptide.append(aa);
}
String currentPeptideString = currentPeptide.toString();
if ((nMin == null || currentPeptide.length() >= nMin) && (nMax == null || currentPeptide.length() <= nMax)) {
results.add(currentPeptideString);
}
for (int nMc : mc.keySet()) {
mc.get(nMc).add(currentPeptideString);
while (mc.get(nMc).size() > nMc + 1) {
mc.get(nMc).remove(0);
}
StringBuilder mcSequence = new StringBuilder();
for (String subPeptide : mc.get(nMc)) {
mcSequence.append(subPeptide);
}
if ((nMin == null || mcSequence.length() >= nMin) && (nMax == null || mcSequence.length() <= nMax)) {
results.add(mcSequence.toString());
}
}
return results;
}
/**
* Digests a protein sequence in a list of expected peptide sequences.
*
* @param sequence the protein sequence
* @param nMissedCleavages the maximum number of missed cleavages
* @param massMin the minimal mass for a peptide (inclusive)
* @param massMax the maximal mass for a peptide (inclusive)
*
* @return a list of expected peptide sequences
*/
public HashSet<String> digest(String sequence, int nMissedCleavages, Double massMin, Double massMax) {
char aa, aaBefore;
char aaAfter = sequence.charAt(0);
StringBuilder currentPeptide = new StringBuilder();
currentPeptide.append(aaAfter);
Double currentMass = AminoAcid.getAminoAcid(aaAfter).getMonoisotopicMass();
HashSet<String> results = new HashSet<>();
HashMap<Integer, ArrayList<String>> mc = new HashMap<>();
for (int i = 1; i <= nMissedCleavages; i++) {
mc.put(i, new ArrayList<>(nMissedCleavages));
}
HashMap<String, Double> peptideMasses = new HashMap<>();
for (int i = 1; i < sequence.length(); i++) {
aa = sequence.charAt(i);
aaBefore = aaAfter;
aaAfter = aa;
if (isCleavageSite(aaBefore, aaAfter) && currentPeptide.length() > 0) {
String currentPeptideString = currentPeptide.toString();
if ((massMin == null || currentMass >= massMin) && (massMax == null || currentMass <= massMax)) {
results.add(currentPeptideString);
}
for (int nMc : mc.keySet()) {
mc.get(nMc).add(currentPeptideString);
peptideMasses.put(currentPeptideString, currentMass);
while (mc.get(nMc).size() > nMc + 1) {
mc.get(nMc).remove(0);
}
StringBuilder mcSequence = new StringBuilder();
double mcMass = 0.0;
for (String subPeptide : mc.get(nMc)) {
mcSequence.append(subPeptide);
mcMass += peptideMasses.get(subPeptide);
}
if ((massMin == null || mcMass >= massMin) && (massMax == null || mcMass <= massMax)) {
results.add(mcSequence.toString());
}
}
currentPeptide = new StringBuilder();
}
currentPeptide.append(aa);
currentMass += AminoAcid.getAminoAcid(aa).getMonoisotopicMass();
}
String currentPeptideString = currentPeptide.toString();
if ((massMin == null || currentMass >= massMin) && (massMax == null || currentMass <= massMax)) {
results.add(currentPeptideString);
}
for (int nMc : mc.keySet()) {
mc.get(nMc).add(currentPeptideString);
peptideMasses.put(currentPeptideString, currentMass);
while (mc.get(nMc).size() > nMc + 1) {
mc.get(nMc).remove(0);
}
StringBuilder mcSequence = new StringBuilder();
double mcMass = 0.0;
for (String subPeptide : mc.get(nMc)) {
mcSequence.append(subPeptide);
mcMass += peptideMasses.get(subPeptide);
}
if ((massMin == null || mcMass >= massMin) && (massMax == null || mcMass <= massMax)) {
results.add(mcSequence.toString());
}
}
return results;
}
/**
* Returns true of the two enzymes are identical.
*
* @param otherEnzyme the enzyme to compare against.
* @return true of the two enzymes are identical
*/
public boolean equals(Enzyme otherEnzyme) {
if (otherEnzyme == null) {
return false;
}
if (!this.getName().equalsIgnoreCase(otherEnzyme.getName())) {
return false;
}
if (!this.getAminoAcidBefore().equals(otherEnzyme.getAminoAcidBefore())) {
return false;
}
if (!this.getRestrictionBefore().equals(otherEnzyme.getRestrictionBefore())) {
return false;
}
if (!this.getAminoAcidAfter().equals(otherEnzyme.getAminoAcidAfter())) {
return false;
}
if (!this.getRestrictionAfter().equals(otherEnzyme.getRestrictionAfter())) {
return false;
}
return true;
}
/**
* Returns the description of the cleavage of this enzyme.
*
* @return the description of the cleavage of this enzyme
*/
public String getDescription() {
StringBuilder description = new StringBuilder();
description.append("Cleaves ");
if (!getAminoAcidBefore().isEmpty()) {
description.append("after ");
description.append(
getAminoAcidBefore().stream()
.sorted()
.map(aa -> aa.toString())
.collect(Collectors.joining()));
if (!getAminoAcidAfter().isEmpty()) {
description.append(" and ");
}
}
if (!getAminoAcidAfter().isEmpty()) {
description.append("before ");
description.append(
getAminoAcidAfter().stream()
.sorted()
.map(aa -> aa.toString())
.collect(Collectors.joining()));
}
if (!getRestrictionBefore().isEmpty()) {
description.append(" not preceeded by ");
description.append(
getRestrictionBefore().stream()
.sorted()
.map(aa -> aa.toString())
.collect(Collectors.joining()));
if (!getRestrictionAfter().isEmpty()) {
description.append(" and ");
}
}
if (!getRestrictionAfter().isEmpty()) {
description.append(" not followed by ");
description.append(
getRestrictionAfter().stream()
.sorted()
.map(aa -> aa.toString())
.collect(Collectors.joining()));
}
return description.toString();
}
/**
* Returns the CV term associated with this enzyme.
*
* @return the CV term associated with this enzyme
*/
public CvTerm getCvTerm() {
return cvTerm;
}
/**
* Sets the CV term associated with this enzyme.
*
* @param cvTerm the CV term associated with this enzyme
*/
public void setCvTerm(CvTerm cvTerm) {
this.cvTerm = cvTerm;
}
}
| |
package analyzer.level1;
import analyzer.level1.storage.UnitStore;
import analyzer.level1.storage.UnitStore.Element;
import soot.ArrayType;
import soot.Body;
import soot.IntType;
import soot.Local;
import soot.RefType;
import soot.Scene;
import soot.SootClass;
import soot.SootField;
import soot.SootMethod;
import soot.Type;
import soot.Unit;
import soot.Value;
import soot.VoidType;
import soot.jimple.ArrayRef;
import soot.jimple.ClassConstant;
import soot.jimple.Expr;
import soot.jimple.IdentityStmt;
import soot.jimple.InstanceFieldRef;
import soot.jimple.IntConstant;
import soot.jimple.Jimple;
import soot.jimple.StaticFieldRef;
import soot.jimple.Stmt;
import soot.jimple.StringConstant;
import soot.jimple.ThisRef;
import soot.util.Chain;
import utils.dominator.DominatorFinder;
import utils.exceptions.InternalAnalyzerException;
import utils.logging.L1Logger;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.sun.org.apache.bcel.internal.generic.ObjectType;
/**
* JimpleInjector is called by the AnnotatorStmtSwitch and AnnotatorValueSwitch.
* Inserts additional statements into a methods body.
* @author Regina Koenig (2015)
*/
public class JimpleInjector {
/**
* String for the HandleStmt class.
*/
private static final String HANDLE_CLASS = "analyzer.level2.HandleStmt";
/**
* The body of the actually analyzed method.
*/
static Body b = Jimple.v().newBody();
/**
* Chain with all units in the actual method-body.
*/
static Chain<Unit> units = b.getUnits();
/**
* Chain with all locals in the actual method-body.
*/
static Chain<Local> locals = b.getLocals();
/**
* Chain containing all new units which have to be set
* after a given position.
*/
static UnitStore unitStore_After = new UnitStore("UnitStore_After");
/**
* Chain containing all new units which have to be set
* before a given position.
*/
static UnitStore unitStore_Before = new UnitStore("UnitStore_Before");
/**
* Local which holds the object of HandleStmt.
*/
static Local hs = Jimple.v().newLocal("hs", RefType.v(HANDLE_CLASS));
/**
* Boolean to check whether the extra locals had already been added.
*/
static boolean extralocals = false;
/**
* Local wto store String values.
*/
static Local local_for_Strings = Jimple.v().newLocal(
"local_for_Strings", RefType.v("java.lang.String"));
/**
* This local is needed for methods
* with more than two arguments.
*/
static Local local_for_Strings2 = Jimple.v().newLocal(
"local_for_Strings2", RefType.v("java.lang.String"));
/**
* This locals is needed for methods
* with more than two arguments.
*/
static Local local_for_Strings3 = Jimple.v().newLocal(
"local_for_Strings3", RefType.v("java.lang.String"));
/**
* Local where String arrays can be stored. Needed to store arguments for injected methods.
*/
static Local local_for_String_Arrays = Jimple.v().newLocal(
"local_for_String_Arrays", ArrayType.v(RefType.v("java.lang.String"), 1));
/**
* Local where Objects can be stored as arguments for injected methods.
*/
static Local local_for_Objects = Jimple.v().newLocal(
"local_for_Objects", RefType.v("java.lang.Object"));
/**
* Logger.
*/
static Logger logger = L1Logger.getLogger();
/**
* Stores the position of the last unit which was analyzed in the unit chain or the last
* inserted unit. Is needed for further units,
* which have to be inserted after the last position.
*/
static Unit lastPos;
/**
* Initialization of JimpleInjector. Set all needed variables
* and compute the start position for inserting new units.
* @param body The body of the analyzed method.
*/
public static void setBody(Body body) {
b = body;
units = b.getUnits();
locals = b.getLocals();
extralocals = false;
// Insert after the setting of all arguments and the @this-reference,
// since Jimple would otherwise complain.
int startPos = getStartPos(body);
Iterator<Unit> uIt = units.iterator();
for (int i = 0; i <= startPos; i++) {
lastPos = uIt.next();
}
logger.info("Start position is " + lastPos.toString());
}
/**
* Add "hs = new HandleStmt()" expression to Jimplecode.
*/
public static void invokeHS() {
logger.log(Level.INFO, "Invoke HandleStmt in method {0}", b.getMethod().getName());
locals.add(hs);
Unit in = Jimple.v().newAssignStmt(hs, Jimple.v().newNewExpr(
RefType.v(HANDLE_CLASS)));
ArrayList<Type> paramTypes = new ArrayList<Type>();
Expr specialIn = Jimple.v().newSpecialInvokeExpr(
hs, Scene.v().makeConstructorRef(
Scene.v().getSootClass(HANDLE_CLASS), paramTypes));
Unit inv = Jimple.v().newInvokeStmt(specialIn);
unitStore_Before.insertElement(unitStore_Before.new Element(inv, lastPos));
unitStore_Before.insertElement(unitStore_Before.new Element(in, inv));
lastPos = inv;
}
/**
* Injects the constructor call of HandleStmt into the analyzed method.
*/
public static void initHS() {
logger.log(Level.INFO, "Initialize HandleStmt in method {0}",
b.getMethod().getName());
ArrayList<Type> paramTypes = new ArrayList<Type>();
Expr invokeInit = Jimple.v().newStaticInvokeExpr(
Scene.v().makeMethodRef(Scene.v().getSootClass(HANDLE_CLASS),
"init", paramTypes, VoidType.v(), true));
Unit init = Jimple.v().newInvokeStmt(invokeInit);
unitStore_After.insertElement(unitStore_After.new Element(init, lastPos));
lastPos = init;
}
/**
* Injects the HandleStmt.close() method. This method should be injected at the
* end of every analyzed method.
*/
public static void closeHS() {
logger.log(Level.INFO, "Close HandleStmt in method {0} {1}",
new Object[] {b.getMethod().getName(),
System.getProperty("line.separator")});
ArrayList<Type> paramTypes = new ArrayList<Type>();
Expr invokeClose = Jimple.v().newVirtualInvokeExpr(
hs, Scene.v().makeMethodRef(Scene.v().getSootClass(HANDLE_CLASS),
"close", paramTypes, VoidType.v(), false));
units.insertBefore(Jimple.v().newInvokeStmt(invokeClose), units.getLast());
}
/*
* Adding Elements to map
*/
/**
* Add a new local.
* @param local The Local
*/
public static void addLocal(Local local) {
logger.log(Level.INFO, "Add Local {0} in method {1}",new Object[] {
getSignatureForLocal(local), b.getMethod().getName()});
ArrayList<Type> paramTypes = new ArrayList<Type>();
paramTypes.add(RefType.v("java.lang.String"));
String signature = getSignatureForLocal(local);
Stmt sig = Jimple.v().newAssignStmt(local_for_Strings, StringConstant.v(signature));
Expr invokeAddLocal = Jimple.v().newVirtualInvokeExpr(
hs, Scene.v().makeMethodRef(Scene.v().getSootClass(HANDLE_CLASS),
"addLocal", paramTypes, VoidType.v(), false), local_for_Strings);
Unit ass = Jimple.v().newInvokeStmt(invokeAddLocal);
unitStore_After.insertElement(unitStore_After.new Element(sig, lastPos));
unitStore_After.insertElement(unitStore_After.new Element(ass, sig));
lastPos = ass;
}
/**
* Add the instance of the actual class-object to the object map.
* This is only done in "init".
*/
public static void addInstanceObjectToObjectMap() {
// Check if the first unit is a reference to the actual object
if (!(units.getFirst() instanceof IdentityStmt)
|| !(units.getFirst().getUseBoxes().get(0).getValue()
instanceof ThisRef)) {
throw new InternalAnalyzerException("Expected @this reference");
}
String thisObj = units.getFirst().getUseBoxes().get(0).getValue().toString();
logger.log(Level.INFO, "Add object {0} to ObjectMap in method {1}",
new Object[] {thisObj, b.getMethod().getName()} );
ArrayList<Type> parameterTypes = new ArrayList<Type>();
parameterTypes.add(RefType.v("java.lang.Object"));
Expr addObj = Jimple.v().newVirtualInvokeExpr(
hs, Scene.v().makeMethodRef(
Scene.v().getSootClass(HANDLE_CLASS), "addObjectToObjectMap",
parameterTypes, VoidType.v(), false),
units.getFirst().getDefBoxes().get(0).getValue());
Unit assignExpr = Jimple.v().newInvokeStmt(addObj);
unitStore_After.insertElement(unitStore_After.new Element(assignExpr, lastPos));
lastPos = assignExpr;
}
/**
* Add a class object. Needed for static fields.
* @param sc SootClass.
*/
public static void addClassObjectToObjectMap(SootClass sc) {
logger.log(Level.INFO, "Add object {0} to ObjectMap in method {1}",
new Object[] {sc.getName(), b.getMethod().getName()} );
ArrayList<Type> parameterTypes = new ArrayList<Type>();
parameterTypes.add(RefType.v("java.lang.Object"));
System.out.println("Adding class Object:" + sc.getName().replace(".", "/"));
ClassConstant cc = ClassConstant.v(sc.getName().replace(".", "/"));
System.out.println("Value: " + cc.value);
Expr addObj = Jimple.v().newVirtualInvokeExpr(
hs, Scene.v().makeMethodRef(
Scene.v().getSootClass(HANDLE_CLASS), "addObjectToObjectMap",
parameterTypes, VoidType.v(), false),
ClassConstant.v(sc.getName().replace(".", "/")));
Unit assignExpr = Jimple.v().newInvokeStmt(addObj);
unitStore_After.insertElement(unitStore_After.new Element(assignExpr, lastPos));
lastPos = assignExpr;
}
/**
* Add a field to the object map.
* @param field the SootField.
*/
public static void addInstanceFieldToObjectMap(SootField field) {
logger.log(Level.INFO, "Adding field {0} to ObjectMap in method {1}",
new Object[] { field.getSignature() ,b.getMethod().getName()});
if (!(units.getFirst() instanceof IdentityStmt)
|| !(units.getFirst().getUseBoxes().get(0).getValue()
instanceof ThisRef)) {
throw new InternalAnalyzerException("Expected @this reference");
}
String fieldSignature = getSignatureForField(field);
ArrayList<Type> parameterTypes = new ArrayList<Type>();
parameterTypes.add(RefType.v("java.lang.Object"));
parameterTypes.add(RefType.v("java.lang.String"));
Local tmpLocal = (Local) units.getFirst().getDefBoxes().get(0).getValue();
Unit assignSignature = Jimple.v().newAssignStmt(local_for_Strings,
StringConstant.v(fieldSignature));
Expr addObj = Jimple.v().newVirtualInvokeExpr(
hs, Scene.v().makeMethodRef(
Scene.v().getSootClass(HANDLE_CLASS), "addFieldToObjectMap",
parameterTypes, Scene.v().getObjectType(), false),
tmpLocal, local_for_Strings);
Unit assignExpr = Jimple.v().newInvokeStmt(addObj);
unitStore_After.insertElement(
unitStore_After.new Element(assignSignature, lastPos));
unitStore_After.insertElement(
unitStore_After.new Element(assignExpr, assignSignature));
lastPos = assignExpr;
}
/**
* Add a static field. This field is added to its corresponding class object.
* @param field SootField
*/
public static void addStaticFieldToObjectMap(SootField field) {
logger.info( "Adding static Field " + field.toString() + " to Object Map");
String signature = getSignatureForField(field);
ArrayList<Type> parameterTypes = new ArrayList<Type>();
parameterTypes.add(RefType.v("java.lang.Object"));
parameterTypes.add(RefType.v("java.lang.String"));
SootClass sc = field.getDeclaringClass();
Unit assignDeclaringClass = Jimple.v().newAssignStmt(
local_for_Objects, ClassConstant.v(sc.getName().replace(".", "/")));
Unit assignSignature = Jimple.v().newAssignStmt(
local_for_Strings, StringConstant.v(signature));
Expr addObj = Jimple.v().newVirtualInvokeExpr(
hs, Scene.v().makeMethodRef(Scene.v().getSootClass(HANDLE_CLASS),
"addFieldToObjectMap", parameterTypes,
Scene.v().getObjectType(), false),
local_for_Objects, local_for_Strings);
Unit assignExpr = Jimple.v().newInvokeStmt(addObj);
unitStore_After.insertElement(
unitStore_After.new Element(assignDeclaringClass, lastPos));
unitStore_After.insertElement(
unitStore_After.new Element(assignSignature, assignDeclaringClass));
unitStore_After.insertElement(
unitStore_After.new Element(assignExpr, assignSignature));
lastPos = assignExpr;
}
/**
* Add a new array to objectMap.
* @param a The Local where the array is stored.
* @param pos Unit where the array occurs.
*/
public static void addArrayToObjectMap(Local a, Unit pos) {
logger.log(Level.INFO, "Add array {0} to ObjectMap in method {1}",
new Object[] {a, b.getMethod().getName()} );
logger.log(Level.INFO, "Object type of array: " + a.getType()
+ " and type " + a.getClass());
logger.log(Level.FINEST, "at position {0}", pos.toString());
ArrayList<Type> parameterTypes = new ArrayList<Type>();
parameterTypes.add(ArrayType.v(
RefType.v("java.lang.Object"), 1));
Expr addObj = Jimple.v().newVirtualInvokeExpr(
hs, Scene.v().makeMethodRef(
Scene.v().getSootClass(HANDLE_CLASS),"addArrayToObjectMap",
parameterTypes, VoidType.v(), false), a);
Unit assignExpr = Jimple.v().newInvokeStmt(addObj);
unitStore_After.insertElement(unitStore_After.new Element(assignExpr, pos));
lastPos = assignExpr;
}
/*
* Change level of elements
*/
/**
* Set the security-level of a local to HIGH.
* @param local Local
* @param pos Unit where this local occurs
*/
public static void makeLocalHigh(Local local, Unit pos) {
logger.log(Level.INFO, "Make Local {0} high in method {1}",
new Object[] {getSignatureForLocal(local), b.getMethod().getName()});
ArrayList<Type> paramTypes = new ArrayList<Type>();
paramTypes.add(RefType.v("java.lang.String"));
String signature = getSignatureForLocal(local);
Stmt sig = Jimple.v().newAssignStmt(local_for_Strings, StringConstant.v(signature));
Expr invokeAddLocal = Jimple.v().newVirtualInvokeExpr(
hs, Scene.v().makeMethodRef(Scene.v().getSootClass(HANDLE_CLASS),
"makeLocalHigh", paramTypes, VoidType.v(),false),
local_for_Strings);
Unit ass = Jimple.v().newInvokeStmt(invokeAddLocal);
unitStore_After.insertElement(unitStore_After.new Element(sig, pos));
unitStore_After.insertElement(unitStore_After.new Element(ass, sig));
lastPos = ass;
}
/**
* Set the security-level of a local to LOW.
* @param local Local
* @param pos Unit where this local occurs
*/
public static void makeLocalLow(Local local, Unit pos) {
logger.log(Level.INFO, "Make Local {0} low in method {1}",
new Object[] {getSignatureForLocal(local), b.getMethod().getName()});
ArrayList<Type> paramTypes = new ArrayList<Type>();
paramTypes.add(RefType.v("java.lang.String"));
String signature = getSignatureForLocal(local);
Stmt sig = Jimple.v().newAssignStmt(local_for_Strings, StringConstant.v(signature));
Expr invokeAddLocal = Jimple.v().newVirtualInvokeExpr(
hs, Scene.v().makeMethodRef(Scene.v().getSootClass(HANDLE_CLASS),
"makeLocalLow", paramTypes, VoidType.v(),false), local_for_Strings);
Unit ass = Jimple.v().newInvokeStmt(invokeAddLocal);
unitStore_After.insertElement(unitStore_After.new Element(sig, pos));
unitStore_After.insertElement(unitStore_After.new Element(ass, sig));
lastPos = ass;
}
/**
* Add the level of a local on the right side of an assign statement.
* @param local Local
* @param pos Unit where the local occurs
*/
public static void addLevelInAssignStmt(Local local, Unit pos) {
logger.info("Adding level in assign statement");
ArrayList<Type> paramTypes = new ArrayList<Type>();
paramTypes.add(RefType.v("java.lang.String"));
String signature = getSignatureForLocal(local);
Stmt assignSignature = Jimple.v().newAssignStmt(
local_for_Strings, StringConstant.v(signature));
Expr invokeAddLevel = Jimple.v().newVirtualInvokeExpr(
hs, Scene.v().makeMethodRef(Scene.v().getSootClass(HANDLE_CLASS),
"joinLevelOfLocalAndAssignmentLevel", paramTypes,
Scene.v().getObjectType(),
false), local_for_Strings);
Unit invoke = Jimple.v().newInvokeStmt(invokeAddLevel);
unitStore_Before.insertElement(unitStore_Before.new Element(assignSignature, pos));
unitStore_Before.insertElement(unitStore_Before.new Element(invoke, pos));
lastPos = pos;
}
/*******************************************************************************************
* AssignStmt Functions.
******************************************************************************************/
/**
* Add the level of a field of an object. It can be the field of the actually
* analyzed object or the field
* @param f Reference to the instance field
* @param pos The statement where this field occurs
*/
public static void addLevelInAssignStmt(InstanceFieldRef f, Unit pos) {
logger.log(Level.INFO, "Adding level of field {0} in assignStmt in method {1}",
new Object[] {f.getField().getSignature(),b.getMethod().getName()});
String fieldSignature = getSignatureForField(f.getField());
ArrayList<Type> parameterTypes = new ArrayList<Type>();
parameterTypes.add(RefType.v("java.lang.Object"));
parameterTypes.add(RefType.v("java.lang.String"));
// units.getFirst is already a reference to @this
// Local tmpLocal = (Local) units.getFirst().getDefBoxes().get(0).getValue();
Unit assignBase = Jimple.v().newAssignStmt(local_for_Objects, f.getBase());
System.out.println("Base " + f.getBase());
Unit assignSignature = Jimple.v().newAssignStmt(
local_for_Strings, StringConstant.v(fieldSignature));
Expr addObj = Jimple.v().newVirtualInvokeExpr(
hs, Scene.v().makeMethodRef(
Scene.v().getSootClass(HANDLE_CLASS), "joinLevelOfFieldAndAssignmentLevel",
parameterTypes, Scene.v().getObjectType(), false),
local_for_Objects, local_for_Strings);
Unit assignExpr = Jimple.v().newInvokeStmt(addObj);
unitStore_Before.insertElement(unitStore_Before.new Element(assignBase, pos));
unitStore_Before.insertElement(unitStore_Before.new Element(assignSignature, pos));
unitStore_Before.insertElement(unitStore_Before.new Element(assignExpr, pos));
lastPos = pos;
}
/**
* @param f
* @param pos
*/
public static void addLevelInAssignStmt(StaticFieldRef f, Unit pos) {
logger.info( "Adding Level of static Field " + f.toString() + " in assign stmt");
SootField field = f.getField();
String signature = getSignatureForField(field);
ArrayList<Type> parameterTypes = new ArrayList<Type>();
parameterTypes.add(RefType.v("java.lang.Object"));
parameterTypes.add(RefType.v("java.lang.String"));
SootClass sc = field.getDeclaringClass();
Unit assignDeclaringClass = Jimple.v().newAssignStmt(
local_for_Objects, ClassConstant.v(sc.getName().replace(".", "/")));
Unit assignSignature = Jimple.v().newAssignStmt(
local_for_Strings, StringConstant.v(signature));
Expr addObj = Jimple.v().newVirtualInvokeExpr(
hs, Scene.v().makeMethodRef(Scene.v().getSootClass(HANDLE_CLASS),
"joinLevelOfFieldAndAssignmentLevel", parameterTypes,
Scene.v().getObjectType(), false),
local_for_Objects, local_for_Strings);
Unit assignExpr = Jimple.v().newInvokeStmt(addObj);
unitStore_Before.insertElement(
unitStore_Before.new Element(assignDeclaringClass, pos));
unitStore_Before.insertElement(unitStore_Before.new Element(assignSignature, pos));
unitStore_Before.insertElement(unitStore_Before.new Element(assignExpr, pos));
lastPos = pos;
}
/**
* Add the level of a read array field to the security-level-list.
* @param a -ArrayRef- The referenced array field
* @param pos -Unit- The position where this reference occurs
*/
public static void addLevelInAssignStmt(ArrayRef a, Unit pos) {
logger.info( "Add Level of Array " + a.toString() + " in assign stmt");
ArrayList<Type> parameterTypes = new ArrayList<Type>();
parameterTypes.add(RefType.v("java.lang.Object"));
parameterTypes.add(RefType.v("java.lang.String"));
String signature = getSignatureForArrayField(a);
Unit assignSignature = Jimple.v().newAssignStmt(
local_for_Strings, StringConstant.v(signature));
unitStore_Before.insertElement(unitStore_Before.new Element(assignSignature, pos));
lastPos = assignSignature;
Expr addObj = Jimple.v().newVirtualInvokeExpr(
hs, Scene.v().makeMethodRef(Scene.v().getSootClass(HANDLE_CLASS),
"joinLevelOfArrayFieldAndAssignmentLevel", parameterTypes,
Scene.v().getObjectType(), false),
a.getBase(), local_for_Strings);
Unit assignExpr = Jimple.v().newInvokeStmt(addObj);
unitStore_Before.insertElement(unitStore_Before.new Element(assignExpr, pos));
lastPos = pos;
}
/**
* @param l
* @param pos
*/
public static void setLevelOfAssignStmt(Local l, Unit pos) {
logger.info("Setting level in assign statement");
ArrayList<Type> paramTypes = new ArrayList<Type>();
paramTypes.add(RefType.v("java.lang.String"));
String signature = getSignatureForLocal(l);
Stmt assignSignature = Jimple.v().newAssignStmt(
local_for_Strings, StringConstant.v(signature));
// insert setLevelOfLOcal
Expr invokeSetLevel = Jimple.v().newVirtualInvokeExpr(
hs, Scene.v().makeMethodRef(Scene.v().getSootClass(HANDLE_CLASS),
"setLevelOfLocal", paramTypes,
Scene.v().getObjectType(),
false), local_for_Strings);
Unit invoke = Jimple.v().newInvokeStmt(invokeSetLevel);
// insert checkLocalPC
Expr checkLocalPC = Jimple.v().newVirtualInvokeExpr(
hs, Scene.v().makeMethodRef(Scene.v().getSootClass(HANDLE_CLASS),
"checkLocalPC", paramTypes,
VoidType.v(),
false), local_for_Strings);
Unit checkLocalPCExpr = Jimple.v().newInvokeStmt(checkLocalPC);
unitStore_Before.insertElement(unitStore_Before.new Element(assignSignature, pos));
unitStore_Before.insertElement(unitStore_Before.new Element(checkLocalPCExpr, pos));
unitStore_Before.insertElement(unitStore_Before.new Element(invoke, pos));
lastPos = pos;
}
/**
* Set the level of a field of an object. It can be the field of the actually
* analyzed object or the field
* @param f Reference to the instance field
* @param pos The statement where this field occurs
*/
public static void setLevelOfAssignStmt(InstanceFieldRef f, Unit pos) {
logger.log(Level.INFO, "Set level to field {0} in assignStmt in method {1}",
new Object[] {f.getField().getSignature(),b.getMethod().getName()});
// if (!(units.getFirst() instanceof IdentityStmt)
// || !(units.getFirst().getUseBoxes().get(0).getValue()
// instanceof ThisRef)) {
// System.out.println(units.getFirst().getUseBoxes().toString());
// throw new InternalAnalyzerException("Expected @this reference");
// }
String fieldSignature = getSignatureForField(f.getField());
ArrayList<Type> parameterTypes = new ArrayList<Type>();
parameterTypes.add(RefType.v("java.lang.Object"));
parameterTypes.add(RefType.v("java.lang.String"));
// units.getFirst is already a reference to @this
// Local tmpLocal = (Local) units.getFirst().getDefBoxes().get(0).getValue();
// Retrieve the object it belongs to
Local tmpLocal = (Local) f.getBase();
Unit assignSignature = Jimple.v().newAssignStmt(
local_for_Strings, StringConstant.v(fieldSignature));
// insert: checkGlobalPC(Object, String)
Expr checkGlobalPC = Jimple.v().newVirtualInvokeExpr(
hs, Scene.v().makeMethodRef(
Scene.v().getSootClass(HANDLE_CLASS), "checkGlobalPC",
parameterTypes, VoidType.v(), false),
tmpLocal, local_for_Strings);
Unit checkGlobalPCExpr = Jimple.v().newInvokeStmt(checkGlobalPC);
// insert setLevelOfField
Expr addObj = Jimple.v().newVirtualInvokeExpr(
hs, Scene.v().makeMethodRef(
Scene.v().getSootClass(HANDLE_CLASS), "setLevelOfField",
parameterTypes, Scene.v().getObjectType(), false),
tmpLocal, local_for_Strings);
Unit assignExpr = Jimple.v().newInvokeStmt(addObj);
unitStore_Before.insertElement(unitStore_After.new Element(checkGlobalPCExpr, pos));
unitStore_Before.insertElement(unitStore_Before.new Element(assignSignature, pos));
unitStore_Before.insertElement(unitStore_After.new Element(assignExpr, pos));
lastPos = pos;
}
/**
* @param f
* @param pos
*/
public static void setLevelOfAssignStmt(StaticFieldRef f, Unit pos) {
logger.info( "Set Level of static Field " + f.toString() + " in assign stmt");
SootField field = f.getField();
String signature = getSignatureForField(field);
System.out.println("Signature of static field in jimple injector " + signature);
ArrayList<Type> parameterTypes = new ArrayList<Type>();
parameterTypes.add(RefType.v("java.lang.Object"));
parameterTypes.add(RefType.v("java.lang.String"));
SootClass sc = field.getDeclaringClass();
Unit assignDeclaringClass = Jimple.v().newAssignStmt(
local_for_Objects, ClassConstant.v(sc.getName().replace(".", "/")));
Unit assignSignature = Jimple.v().newAssignStmt(
local_for_Strings, StringConstant.v(signature));
// insert: checkGlobalPC(Object, String)
Expr checkGlobalPC = Jimple.v().newVirtualInvokeExpr(
hs, Scene.v().makeMethodRef(
Scene.v().getSootClass(HANDLE_CLASS), "checkGlobalPC",
parameterTypes, VoidType.v(), false),
local_for_Objects, local_for_Strings);
Unit checkGlobalPCExpr = Jimple.v().newInvokeStmt(checkGlobalPC);
// Add setLevelOfField
Expr addObj = Jimple.v().newVirtualInvokeExpr(
hs, Scene.v().makeMethodRef(Scene.v().getSootClass(HANDLE_CLASS),
"setLevelOfField", parameterTypes,
Scene.v().getObjectType(), false),
local_for_Objects, local_for_Strings);
Unit assignExpr = Jimple.v().newInvokeStmt(addObj);
unitStore_Before.insertElement(
unitStore_Before.new Element(assignDeclaringClass, pos));
unitStore_Before.insertElement(unitStore_Before.new Element(assignSignature, pos));
unitStore_Before.insertElement(unitStore_Before.new Element(checkGlobalPCExpr, pos));
unitStore_Before.insertElement(unitStore_Before.new Element(assignExpr, pos));
lastPos = pos;
}
/**
* Inject a method of HandleStmt to set the level of an array-field. This method
* distinguishes two cases, one case where the index of the referenced array-field
* is a constant number and the other case, where the index is stored in a local variable.
* In the second case, the signature of the local variable also must be passed as an
* argument to {@link analyzer.level2.HandleStmt
* #setLevelOfArrayField(Object o, int field, String localForObject,
* String localForIndex)} .
* @param a -ArrayRef. The reference to the array-field
* @param pos -Unit- The assignStmt in the analyzed methods body, where this
* reference appears.
*/
public static void setLevelOfAssignStmt(ArrayRef a, Unit pos) {
logger.info( "Set level of array " + a.toString() + " in assign stmt");
// Add extra locals for arguments
if (!extralocals) {
locals.add(local_for_Strings2);
locals.add(local_for_Strings3);
extralocals = true;
}
// Define the types of the arguments for HandleStmt.setLevelOfArrayField()
ArrayList<Type> parameterTypes = new ArrayList<Type>();
parameterTypes.add(RefType.v("java.lang.Object")); // for Object o
parameterTypes.add(RefType.v("java.lang.String")); // for String field
parameterTypes.add(RefType.v("java.lang.String")); // for String localForObject
Value objectO = a.getBase();
String signatureForField = getSignatureForArrayField(a);
String signatureForObjectLocal = getSignatureForLocal((Local) a.getBase());
// List for the arguments for HandleStmt.setLevelOfArrayField()
List<Value> args = new ArrayList<Value>();
args.add(objectO);
// Store all string-arguments in locals for strings and assign the locals to the
// argument list.
Unit assignFieldSignature = Jimple.v().newAssignStmt(
local_for_Strings, StringConstant.v(signatureForField));
Unit assignObjectSignature = Jimple.v().newAssignStmt(local_for_Strings2,
StringConstant.v(signatureForObjectLocal));
args.add(local_for_Strings);
args.add(local_for_Strings2);
if (!(a.getIndex() instanceof Local)) {
// Case where the index is a constant.
// The needed arguments are "Object o, String field, String localForObject".
logger.fine("Index value for the array field is a constant value");
} else if (a.getIndex() instanceof Local) {
// The index is a local and must be given as a parameter.
// The needed arguments are
// "Object o, String field, String localForObject, String localForIndex".
logger.fine("Index value for the array field is stored in a local");
// add a further parameter type for String localForIndex and
// add it to the arguments-list.
parameterTypes.add(RefType.v("java.lang.String"));
String localSignature = getSignatureForLocal((Local) a.getIndex());
Unit assignIndexSignature = Jimple.v().newAssignStmt(local_for_Strings3,
StringConstant.v(localSignature));
args.add(local_for_Strings3);
unitStore_Before.insertElement(unitStore_Before.new Element(
assignIndexSignature, pos));
}
// checkArrayWithGlobalPC
Expr checkArrayGlobalPC = Jimple.v().newVirtualInvokeExpr(
hs, Scene.v().makeMethodRef(Scene.v().getSootClass(HANDLE_CLASS),
"checkArrayWithGlobalPC", parameterTypes,
VoidType.v(), false), args);
Unit checkArrayGlobalPCExpr = Jimple.v().newInvokeStmt(checkArrayGlobalPC);
// setLevelOfArrayField
Expr addObj = Jimple.v().newVirtualInvokeExpr(
hs, Scene.v().makeMethodRef(Scene.v().getSootClass(HANDLE_CLASS),
"setLevelOfArrayField", parameterTypes,
Scene.v().getObjectType(), false), args);
Unit assignExpr = Jimple.v().newInvokeStmt(addObj);
unitStore_Before.insertElement(
unitStore_Before.new Element(assignFieldSignature, pos));
unitStore_Before.insertElement(
unitStore_Before.new Element(assignObjectSignature, pos));
unitStore_Before.insertElement(
unitStore_Before.new Element(checkArrayGlobalPCExpr, pos));
unitStore_Before.insertElement(
unitStore_Before.new Element(assignExpr, pos));
lastPos = pos;
}
/**
* @param l
* @param pos
*/
public static void assignReturnLevelToLocal(Local l, Unit pos) {
logger.log(Level.INFO, "Assign return level of invoked method to local {0}",
getSignatureForLocal(l));
ArrayList<Type> parameterTypes = new ArrayList<Type>();
parameterTypes.add(RefType.v("java.lang.String"));
Expr assignRet = Jimple.v().newVirtualInvokeExpr(
hs, Scene.v().makeMethodRef(
Scene.v().getSootClass(HANDLE_CLASS), "assignReturnLevelToLocal",
parameterTypes , VoidType.v(), false),
StringConstant.v(getSignatureForLocal(l)));
Unit assignExpr = Jimple.v().newInvokeStmt(assignRet);
unitStore_After.insertElement(unitStore_After.new Element(assignExpr, pos));
lastPos = assignExpr;
}
/**
* @param posInArgList
* @param local
* @param actualPos
*/
public static void assignArgumentToLocal(int posInArgList, Local local, Unit actualPos) {
logger.log(Level.INFO, "Assign argument level to local " + local.toString());
ArrayList<Type> parameterTypes = new ArrayList<Type>();
parameterTypes.add(IntType.v());
parameterTypes.add(RefType.v("java.lang.String"));
Expr assignArg = Jimple.v().newVirtualInvokeExpr(
hs, Scene.v().makeMethodRef(
Scene.v().getSootClass(HANDLE_CLASS), "assignArgumentToLocal",
parameterTypes, Scene.v().getObjectType(), false),
IntConstant.v(posInArgList),
StringConstant.v(getSignatureForLocal(local))
);
Unit assignExpr = Jimple.v().newInvokeStmt(assignArg);
unitStore_After.insertElement(unitStore_After.new Element(assignExpr, lastPos));
lastPos = assignExpr;
}
/*******************************************************************************************
* Inter-scope functions.
******************************************************************************************/
/**
* @param retStmt
*/
public static void returnConstant(Unit retStmt) {
logger.log(Level.INFO, "Return a constant value");
ArrayList<Type> parameterTypes = new ArrayList<Type>();
Expr returnConst = Jimple.v().newVirtualInvokeExpr(hs, Scene.v().makeMethodRef(
Scene.v().getSootClass(HANDLE_CLASS), "returnConstant",
parameterTypes, VoidType.v(), false));
unitStore_Before.insertElement(unitStore_Before.new Element(
Jimple.v().newInvokeStmt(returnConst), retStmt));
}
/**
* @param l
* @param pos
*/
public static void returnLocal(Local l, Unit pos) {
logger.log(Level.INFO, "Return Local {0}", getSignatureForLocal(l));
ArrayList<Type> parameterTypes = new ArrayList<Type>();
parameterTypes.add(RefType.v("java.lang.String"));
Stmt sig = Jimple.v().newAssignStmt(
local_for_Strings, StringConstant.v(getSignatureForLocal(l)));
Expr returnLocal = Jimple.v().newVirtualInvokeExpr(hs, Scene.v().makeMethodRef(
Scene.v().getSootClass(HANDLE_CLASS), "returnLocal", parameterTypes,
VoidType.v(), false), local_for_Strings);
Stmt returnL = Jimple.v().newInvokeStmt(returnLocal);
unitStore_Before.insertElement(unitStore_Before.new Element(sig, pos));
unitStore_Before.insertElement(unitStore_Before.new Element(returnL, pos));
lastPos = pos;
}
/**
* Store the levels of all arguments in a list in ObjectMap. If an
* argument is a constant, then the argument is stored as "DEFAULT_LOW".
* @param pos position of actual statement
* @param lArguments list of arguments
*/
public static void storeArgumentLevels(Unit pos, Local... lArguments) {
logger.log(Level.INFO, "Store Arguments for next method in method {0}",
b.getMethod().getName());
int length = lArguments.length;
ArrayList<Type> parameterTypes = new ArrayList<Type>();
parameterTypes.add(ArrayType.v(RefType.v("java.lang.String"), 1));
Expr paramArray = Jimple.v().newNewArrayExpr(RefType.v(
"java.lang.String"), IntConstant.v(length));
Unit assignNewStringArray = Jimple.v().newAssignStmt(
local_for_String_Arrays, paramArray);
Unit[] tmpUnitArray = new Unit[length];
for (int i = 0; i < length; i++) {
// It's possible to get a null vector as an argument. This happens,
// if a constant is set as argument.
if (lArguments[i] != null) {
String signature = getSignatureForLocal(lArguments[i]);
tmpUnitArray[i] = Jimple.v().newAssignStmt(Jimple.v().newArrayRef(
local_for_String_Arrays, IntConstant.v(i)),
StringConstant.v(signature));
} else {
tmpUnitArray[i] = Jimple.v().newAssignStmt(Jimple.v().newArrayRef(
local_for_String_Arrays, IntConstant.v(i)),
StringConstant.v("DEFAULT_LOW"));
}
}
Expr storeArgs = Jimple.v().newVirtualInvokeExpr(hs, Scene.v().makeMethodRef(
Scene.v().getSootClass(HANDLE_CLASS), "storeArgumentLevels",
parameterTypes, VoidType.v(), false), local_for_String_Arrays);
Stmt invokeStoreArgs = Jimple.v().newInvokeStmt(storeArgs);
unitStore_Before.insertElement(
unitStore_Before.new Element(assignNewStringArray, pos));
for (Unit el : tmpUnitArray) {
unitStore_Before.insertElement(unitStore_Before.new Element(el, pos));
}
unitStore_Before.insertElement(unitStore_Before.new Element(invokeStoreArgs, pos));
lastPos = pos;
}
/**
* Insert the following check: If Local l is high, throw new IFCError
* @param pos
* @param l
*/
public static void checkThatNotHigh(Unit pos, Local l) {
logger.info("Check that " + l + " is not high");
if (l == null) {
throw new InternalAnalyzerException("Argument is null");
}
ArrayList<Type> paramTypes = new ArrayList<Type>();
paramTypes.add(RefType.v("java.lang.String"));
String signature = getSignatureForLocal(l);
Stmt assignSignature = Jimple.v().newAssignStmt(
local_for_Strings, StringConstant.v(signature));
Expr invokeSetLevel = Jimple.v().newVirtualInvokeExpr(
hs, Scene.v().makeMethodRef(Scene.v().getSootClass(HANDLE_CLASS),
"checkThatNotHigh", paramTypes, VoidType.v(), false),
local_for_Strings);
Unit invoke = Jimple.v().newInvokeStmt(invokeSetLevel);
unitStore_Before.insertElement(unitStore_Before.new Element(assignSignature, pos));
unitStore_Before.insertElement(unitStore_Before.new Element(invoke, pos));
lastPos = pos;
}
/**
* Method to check that PC is not high. Called when calling System.out.println(),
* which must always be called in low context because of its side effects.
* @param pos
*/
public static void checkThatPCNotHigh(Unit pos) {
logger.info("Check that context is not high");
if (pos == null) {
throw new InternalAnalyzerException("Position is Null");
}
Expr checkPC = Jimple.v().newVirtualInvokeExpr(
hs, Scene.v().makeMethodRef(Scene.v().getSootClass(HANDLE_CLASS),
"checkThatPCNotHigh", new ArrayList<Type>(), VoidType.v(), false));
Unit invoke = Jimple.v().newInvokeStmt(checkPC);
unitStore_Before.insertElement(unitStore_Before.new Element(invoke, pos));
lastPos = pos;
}
/**
* Check condition of if statements. Needed parameters are all locals (no constants)
* which occur in the if statement. If the result is high, then the lpc of the if-context
* is set to high.
* @param pos Position of the ifStmt in the method body.
* @param locals An array of all locals which appear in the condition.
*/
public static void checkCondition(Unit pos, Local... locals) {
logger.log(Level.INFO, "Check condition in method {0}", b.getMethod());
logger.log(Level.INFO, "IfStmt: {0}", pos.toString());
int numberOfLocals = locals.length;
ArrayList<Type> paramTypes = new ArrayList<Type>();
paramTypes.add(RefType.v("java.lang.String"));
paramTypes.add(ArrayType.v(RefType.v("java.lang.String"), numberOfLocals));
// Add hashvalue for immediate dominator
String domIdentity = DominatorFinder.getImmediateDominatorIdentity(pos);
logger.info("Identity of Dominator of \"" + pos.toString()
+ "\" is " + domIdentity);
Stmt assignHashVal = Jimple.v().newAssignStmt(
local_for_Strings, StringConstant.v(domIdentity));
// Add all locals to string array
Expr newStringArray = Jimple.v().newNewArrayExpr(
RefType.v("java.lang.String"), IntConstant.v(numberOfLocals));
Unit assignNewArray = Jimple.v().newAssignStmt(
local_for_String_Arrays, newStringArray);
ArrayList<Unit> tmpUnitList = new ArrayList<Unit>();
for (int i = 0; i < numberOfLocals; i ++) {
Unit assignSignature = Jimple.v().newAssignStmt(
Jimple.v().newArrayRef(local_for_String_Arrays,
IntConstant.v(i)),
StringConstant.v(getSignatureForLocal(locals[i])));
tmpUnitList.add(assignSignature);
}
// Invoke HandleStmt.checkCondition(String domHash, String... locals)
Expr invokeCheckCondition = Jimple.v().newVirtualInvokeExpr(
hs, Scene.v().makeMethodRef(Scene.v().getSootClass(HANDLE_CLASS),
"checkCondition", paramTypes, VoidType.v(), false),
local_for_Strings, local_for_String_Arrays);
Unit invokeCC = Jimple.v().newInvokeStmt(invokeCheckCondition);
unitStore_Before.insertElement(unitStore_Before.new Element(assignNewArray, pos));
lastPos = assignNewArray;
for (Unit u : tmpUnitList) {
unitStore_After.insertElement(unitStore_After.new Element(u, lastPos));
lastPos = u;
}
unitStore_After.insertElement(unitStore_After.new Element(assignHashVal, lastPos));
lastPos = assignHashVal;
unitStore_After.insertElement(unitStore_After.new Element(invokeCC, lastPos));
lastPos = invokeCC;
}
/**
* If a stmt is a postdominator of an ifStmt then the if-context ends before this stmt.
* The method exitInnerScope pops the localPCs for all ifStmts which end here.
* @param pos The position of this stmt.
*/
public static void exitInnerScope(Unit pos) {
logger.log(Level.INFO, "Exit inner scope in method {0}", b.getMethod().getName());
ArrayList<Type> paramTypes = new ArrayList<Type>();
paramTypes.add(RefType.v("java.lang.String"));
String domIdentity = DominatorFinder.getIdentityForUnit(pos);
logger.info("Dominator \"" + pos.toString()
+ "\" has identity " + domIdentity);
Stmt assignHashVal = Jimple.v().newAssignStmt(
local_for_Strings, StringConstant.v(domIdentity));
Expr specialIn = Jimple.v().newVirtualInvokeExpr(
hs, Scene.v().makeMethodRef(Scene.v().getSootClass(HANDLE_CLASS),
"exitInnerScope", paramTypes, VoidType.v(), false),
local_for_Strings);
Unit inv = Jimple.v().newInvokeStmt(specialIn);
unitStore_Before.insertElement(
unitStore_Before.new Element(assignHashVal, pos));
unitStore_Before.insertElement(unitStore_Before.new Element(inv, pos));
lastPos = pos;
}
/*
* Internal methods
*/
/**
*
*/
protected static void addUnitsToChain() {
// First add all elements from unitStore_Before
Iterator<Element> uIt = unitStore_Before.getElements().iterator();
// If needed for debugging, you can remove the comment
// unitStore_Before.print();
while (uIt.hasNext()) {
Element item = (Element) uIt.next();
if (item.getPosition() == null) {
units.addFirst(item.getUnit());
} else {
// logger.finest("Starting to insert: " + item.getUnit().toString()
// + " after position " + item.getPosition().toString());
units.insertBefore(item.getUnit(), item.getPosition());
// logger.finest("Insertion completed");
}
}
// Now add all elements from unitStore_After
uIt = unitStore_After.getElements().iterator();
// If needed for debugging, you can remove the comment
// unitStore_After.print();
while (uIt.hasNext()) {
Element item = (Element) uIt.next();
if (item.getPosition() == null) {
units.addFirst(item.getUnit());
} else {
// logger.finest("Starting to insert: " + item.getUnit().toString()
// + " after position " + item.getPosition().toString());
units.insertAfter(item.getUnit(), item.getPosition());
// logger.finest("Insertion completed");
}
}
unitStore_After.flush();
unitStore_Before.flush();
// print the units in the right order for debugging.
// printUnits();
b.validate();
}
/**
* Add all locals which are needed from JimpleInjector to store values
* of parameters for invoked methods.
*/
protected static void addNeededLocals() {
locals.add(local_for_Strings);
locals.add(local_for_String_Arrays);
locals.add(local_for_Objects);
b.validate();
}
/**
* @param l
* @return
*/
private static String getSignatureForLocal(Local l) {
return l.getType() + "_" + l.getName();
}
/**
* @param f
* @return
*/
private static String getSignatureForField(SootField f) {
return f.getSignature();
}
/**
* Create the signature of an array-field based on the index.
* It simply returns the int-value as string.
* @param a -ArrayRef-
* @return -String- The signature for the array-field.
*/
private static String getSignatureForArrayField(ArrayRef a) {
logger.fine("Type of index: " + a.getIndex().getType());
String result = "";
if (a.getIndex().getType().toString() == "int") {
result = a.getIndex().toString();
} else {
throw new InternalAnalyzerException("Unexpected type of index");
}
logger.info("Signature of array field in jimple injector is: " + result);
return result;
}
/**
* Method which calculates the start position for inserting further units.
* It depends on the number of arguments and whether it is a static method,
* or not, because there are statements, which shouldn't be preceeded by
* other statements.
* @return the computed start position as int.
*/
private static int getStartPos(Body b) {
int startPos = 0;
SootMethod m = b.getMethod();
// If the method is not static the @this reference must be skipped.
if (!m.isStatic()) {
startPos++;
}
if (m.isConstructor()) {
startPos++;
}
// Skip the @parameter-references
int numOfParams = m.getParameterCount();
startPos += numOfParams;
logger.info("Calculated start position: " + startPos);
return startPos;
}
/**
* This method is only for debugging purposes.
*/
@SuppressWarnings("unused")
private static void printUnits() {
Iterator<Unit> uIt = units.iterator();
int i = 0;
System.out.println("Actual method: " + b.getMethod().toString());
while (uIt.hasNext()) {
System.out.println(i + " " + uIt.next().toString());
i++;
}
}
}
| |
/*******************************************************************************
* Copyright SemanticBits, Northwestern University and Akaza Research
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/caaers/LICENSE.txt for details.
******************************************************************************/
package gov.nih.nci.cabig.caaers.api;
import gov.nih.nci.cabig.caaers.domain.ExpeditedAdverseEventReport;
import gov.nih.nci.cabig.caaers.domain.ReportFormatType;
import gov.nih.nci.cabig.caaers.domain.report.Report;
import gov.nih.nci.cabig.caaers.service.EvaluationService;
import gov.nih.nci.cabig.caaers.utils.XsltTransformer;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* @author Ion C. Olaru
*
* */
public class AdeersReportGenerator extends BasePDFGenerator {
protected final Log log = LogFactory.getLog(getClass());
// TO-DO set in spring config
private String xslFOXsltFile = "xslt/Caaers2Adeers-pdf-AEReport.xslt";
private String xslFOMedWatchXsltFile = "xslt/Caaers2Medwatch-pdf-AEReport.xslt";
private String xslFODCPXsltFile = "xslt/Caaers2DCP-pdf-SAEForm.xslt";
private String xslFOCIOMSTypeFormXsltFile = "xslt/Caaers2CIOMS-pdf-TypeForm.xslt";
private String xslFOCIOMSXsltFile = "xslt/Caaers2CIOMS-pdf.xslt";
private String xslFOCustomXsltFile = "xslt/CaaersCustom.xslt";
private String xslE2BXsltFile = "xslt/CaaersToE2b.xslt";
// private String xslFOCustomXsltFile = "/SB/caAERS/trunk/caAERS/software/core/src/main/resources/xslt/CaaersCustom.xslt";
protected AdverseEventReportSerializer adverseEventReportSerializer;
protected EvaluationService evaluationService;
public void generatePdf(String adverseEventReportXml, String pdfOutFileName) throws Exception {
XsltTransformer xsltTrans = new XsltTransformer();
xsltTrans.toPdf(adverseEventReportXml, pdfOutFileName, xslFOXsltFile);
}
public List<String> generateImage(String adverseEventReportXml, String pngOutFileName) throws Exception {
XsltTransformer xsltTrans = new XsltTransformer();
return xsltTrans.toImage(adverseEventReportXml, pngOutFileName, xslFOXsltFile);
}
public List<String> generateImage(String adverseEventReportXml, String pngOutFileName, Report report) throws Exception {
XsltTransformer xsltTrans = new XsltTransformer();
String xsltFile = getXSLTForReportFormatType(report);
return xsltTrans.toImage(adverseEventReportXml, pngOutFileName, xsltFile);
}
public void generateDcpSaeForm(String adverseEventReportXml, String pdfOutFileName) throws Exception {
XsltTransformer xsltTrans = new XsltTransformer();
xsltTrans.toPdf(adverseEventReportXml, pdfOutFileName, xslFODCPXsltFile);
}
public void generateCIOMSTypeForm(String adverseEventReportXml, String pdfOutFileName) throws Exception {
XsltTransformer xsltTrans = new XsltTransformer();
xsltTrans.toPdf(adverseEventReportXml, pdfOutFileName, xslFOCIOMSTypeFormXsltFile);
}
/*
* This method generated the PDF file based on the given XML & XSL
*
* @author Ion C . Olaru
* @param adverseEventReportXml Serialized xml content
* @param pdfOutFileName The generated PDF file path
*
* */
public void generateCustomPDF(String adverseEventReportXml, String pdfOutFileName) throws Exception {
generatePdf(adverseEventReportXml, pdfOutFileName, xslFOCustomXsltFile);
}
public void generateCIOMS(String adverseEventReportXml, String pdfOutFileName) throws Exception {
XsltTransformer xsltTrans = new XsltTransformer();
xsltTrans.toPdf(adverseEventReportXml, pdfOutFileName, xslFOCIOMSXsltFile);
}
public void generateMedwatchPdf(String adverseEventReportXml, String pdfOutFileName) throws Exception {
XsltTransformer xsltTrans = new XsltTransformer();
xsltTrans.toPdf(adverseEventReportXml, pdfOutFileName, xslFOMedWatchXsltFile);
}
public String generateE2BXml(String adverseEventReportXml) throws Exception {
XsltTransformer xsltTrans = new XsltTransformer();
return xsltTrans.toText(adverseEventReportXml, xslE2BXsltFile);
}
/**
* This method will generate the caAERS internal xml representation of the report.
* @param aeReport - A data collection
* @param report - A report
*/
public String generateCaaersXml(ExpeditedAdverseEventReport aeReport,Report report) throws Exception{
evaluationService.evaluateMandatoryness(aeReport, report);
return adverseEventReportSerializer.serialize(aeReport, report);
}
public String generateCaaersWithdrawXml(ExpeditedAdverseEventReport aeReport,Report report) throws Exception{
return adverseEventReportSerializer.serializeWithdrawXML(aeReport,report );
}
/**
* This method will generate the PDF file and store it in the file system and return its path.
* @param report
* @param caaersXml
* @return
* @throws Exception
*/
public String[] generateExternalReports(Report report, String caaersXml, int reportIdOrReportVersionId) throws Exception {
assert report != null;
ReportFormatType formatType = report.getReportDefinition().getReportFormatType();
String pdfOutFile = System.getProperty("java.io.tmpdir");
switch (formatType) {
case DCPSAEFORM:
pdfOutFile += "/dcpSAEForm-" + reportIdOrReportVersionId + ".pdf";
this.generateDcpSaeForm(caaersXml, pdfOutFile);
break;
case MEDWATCHPDF:
pdfOutFile += "/medWatchReport-" + reportIdOrReportVersionId + ".pdf";
this.generateMedwatchPdf(caaersXml, pdfOutFile);
break;
case CIOMSFORM:
pdfOutFile += "/CIOMSForm-" + reportIdOrReportVersionId + ".pdf";
this.generateCIOMS(caaersXml, pdfOutFile);
break;
case CIOMSSAEFORM:
pdfOutFile += "/CIOMS-SAE-Form-" + reportIdOrReportVersionId + ".pdf";
this.generateCIOMSTypeForm(caaersXml, pdfOutFile);
break;
case CUSTOM_REPORT:
pdfOutFile += "/CustomReport-" + reportIdOrReportVersionId + ".pdf";
this.generateCustomPDF(caaersXml, pdfOutFile);
break;
default: //adders
pdfOutFile += "/expeditedAdverseEventReport-" + reportIdOrReportVersionId + ".pdf";
generatePdf(caaersXml, pdfOutFile);
break;
}
return new String[] { pdfOutFile };
}
public String getXSLTForReportFormatType(Report report) throws Exception {
assert report != null;
ReportFormatType formatType = report.getReportDefinition().getReportFormatType();
String xslTFile = xslFOXsltFile;
switch (formatType) {
case DCPSAEFORM:
xslTFile = xslFODCPXsltFile;
break;
case MEDWATCHPDF:
xslTFile = xslFOMedWatchXsltFile;
break;
case CIOMSFORM:
xslTFile = xslFOCIOMSXsltFile;
break;
case CIOMSSAEFORM:
xslTFile = xslFOCIOMSTypeFormXsltFile;
break;
case CUSTOM_REPORT:
xslTFile = xslFOCustomXsltFile;
break;
case E2BXML:
xslTFile = xslE2BXsltFile;
default: //adders
xslTFile = xslFOXsltFile;
break;
}
return xslTFile;
}
///OBJECT PROPERTIES
public void setAdverseEventReportSerializer(AdverseEventReportSerializer adverseEventReportSerializer) {
this.adverseEventReportSerializer = adverseEventReportSerializer;
}
public void setEvaluationService(EvaluationService evaluationService) {
this.evaluationService = evaluationService;
}
/**
* This method is testting the PDF generation for the given XML & XSL file
*
* @author Ion C. Olaru
* @return generate the File
*/
public static void createCustomPDFTest() {
String XMLFile = "/home/dell/Downloads/expeditedAdverseEventReport-335.xml";
String PDFFile = "/home/dell/Desktop/testAEReport.pdf";
AdeersReportGenerator g = new AdeersReportGenerator();
StringBuffer s = new StringBuffer("");
try {
FileReader input = new FileReader(XMLFile);
BufferedReader bufRead = new BufferedReader(input);
String line = bufRead.readLine();
while (line != null) {
s.append(line);
line = bufRead.readLine();
}
String xml = s.toString();
g.generateCustomPDF(xml, PDFFile);
} catch (Exception e) {
e.printStackTrace();
}
}
}
| |
/*
* 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.facebook.presto.server;
import com.facebook.airlift.concurrent.BoundedExecutor;
import com.facebook.airlift.json.JsonCodec;
import com.facebook.airlift.stats.TimeStat;
import com.facebook.presto.Session;
import com.facebook.presto.common.Page;
import com.facebook.presto.common.io.SerializedPage;
import com.facebook.presto.execution.TaskId;
import com.facebook.presto.execution.TaskInfo;
import com.facebook.presto.execution.TaskManager;
import com.facebook.presto.execution.TaskState;
import com.facebook.presto.execution.TaskStatus;
import com.facebook.presto.execution.buffer.BufferResult;
import com.facebook.presto.execution.buffer.OutputBuffers.OutputBufferId;
import com.facebook.presto.metadata.MetadataUpdates;
import com.facebook.presto.metadata.SessionPropertyManager;
import com.facebook.presto.server.smile.Codec;
import com.facebook.presto.server.smile.SmileCodec;
import com.facebook.presto.sql.planner.PlanFragment;
import com.google.common.collect.ImmutableList;
import com.google.common.reflect.TypeToken;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import io.airlift.units.DataSize;
import io.airlift.units.Duration;
import org.weakref.jmx.Managed;
import org.weakref.jmx.Nested;
import javax.annotation.security.RolesAllowed;
import javax.inject.Inject;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.container.AsyncResponse;
import javax.ws.rs.container.CompletionCallback;
import javax.ws.rs.container.Suspended;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.GenericEntity;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.core.UriInfo;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.ScheduledExecutorService;
import static com.facebook.airlift.concurrent.MoreFutures.addTimeout;
import static com.facebook.airlift.http.server.AsyncResponseHandler.bindAsyncResponse;
import static com.facebook.presto.PrestoMediaTypes.APPLICATION_JACKSON_SMILE;
import static com.facebook.presto.PrestoMediaTypes.PRESTO_PAGES;
import static com.facebook.presto.client.PrestoHeaders.PRESTO_BUFFER_COMPLETE;
import static com.facebook.presto.client.PrestoHeaders.PRESTO_CURRENT_STATE;
import static com.facebook.presto.client.PrestoHeaders.PRESTO_MAX_SIZE;
import static com.facebook.presto.client.PrestoHeaders.PRESTO_MAX_WAIT;
import static com.facebook.presto.client.PrestoHeaders.PRESTO_PAGE_NEXT_TOKEN;
import static com.facebook.presto.client.PrestoHeaders.PRESTO_PAGE_TOKEN;
import static com.facebook.presto.client.PrestoHeaders.PRESTO_TASK_INSTANCE_ID;
import static com.facebook.presto.server.security.RoleType.INTERNAL;
import static com.facebook.presto.server.smile.JsonCodecWrapper.wrapJsonCodec;
import static com.facebook.presto.util.TaskUtils.DEFAULT_MAX_WAIT_TIME;
import static com.facebook.presto.util.TaskUtils.randomizeWaitTime;
import static com.google.common.collect.Iterables.transform;
import static com.google.common.util.concurrent.MoreExecutors.directExecutor;
import static java.util.Objects.requireNonNull;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.concurrent.TimeUnit.SECONDS;
import static javax.ws.rs.core.MediaType.APPLICATION_JSON;
/**
* Manages tasks on this worker node
*/
@Path("/v1/task")
@RolesAllowed(INTERNAL)
public class TaskResource
{
private static final Duration ADDITIONAL_WAIT_TIME = new Duration(5, SECONDS);
private final TaskManager taskManager;
private final SessionPropertyManager sessionPropertyManager;
private final Executor responseExecutor;
private final ScheduledExecutorService timeoutExecutor;
private final TimeStat readFromOutputBufferTime = new TimeStat();
private final TimeStat resultsRequestTime = new TimeStat();
private final Codec<PlanFragment> planFragmentCodec;
@Inject
public TaskResource(
TaskManager taskManager,
SessionPropertyManager sessionPropertyManager,
@ForAsyncRpc BoundedExecutor responseExecutor,
@ForAsyncRpc ScheduledExecutorService timeoutExecutor,
JsonCodec<PlanFragment> planFragmentJsonCodec,
SmileCodec<PlanFragment> planFragmentSmileCodec,
InternalCommunicationConfig communicationConfig)
{
this.taskManager = requireNonNull(taskManager, "taskManager is null");
this.sessionPropertyManager = requireNonNull(sessionPropertyManager, "sessionPropertyManager is null");
this.responseExecutor = requireNonNull(responseExecutor, "responseExecutor is null");
this.timeoutExecutor = requireNonNull(timeoutExecutor, "timeoutExecutor is null");
this.planFragmentCodec = wrapJsonCodec(planFragmentJsonCodec);
}
@GET
@Consumes({APPLICATION_JSON, APPLICATION_JACKSON_SMILE})
@Produces({APPLICATION_JSON, APPLICATION_JACKSON_SMILE})
public List<TaskInfo> getAllTaskInfo(@Context UriInfo uriInfo)
{
List<TaskInfo> allTaskInfo = taskManager.getAllTaskInfo();
if (shouldSummarize(uriInfo)) {
allTaskInfo = ImmutableList.copyOf(transform(allTaskInfo, TaskInfo::summarize));
}
return allTaskInfo;
}
@POST
@Path("{taskId}")
@Consumes({APPLICATION_JSON, APPLICATION_JACKSON_SMILE})
@Produces({APPLICATION_JSON, APPLICATION_JACKSON_SMILE})
public Response createOrUpdateTask(@PathParam("taskId") TaskId taskId, TaskUpdateRequest taskUpdateRequest, @Context UriInfo uriInfo)
{
requireNonNull(taskUpdateRequest, "taskUpdateRequest is null");
Session session = taskUpdateRequest.getSession().toSession(sessionPropertyManager, taskUpdateRequest.getExtraCredentials());
TaskInfo taskInfo = taskManager.updateTask(session,
taskId,
taskUpdateRequest.getFragment().map(planFragmentCodec::fromBytes),
taskUpdateRequest.getSources(),
taskUpdateRequest.getOutputIds(),
taskUpdateRequest.getTableWriteInfo());
if (shouldSummarize(uriInfo)) {
taskInfo = taskInfo.summarize();
}
return Response.ok().entity(taskInfo).build();
}
@GET
@Path("{taskId}")
@Consumes({APPLICATION_JSON, APPLICATION_JACKSON_SMILE})
@Produces({APPLICATION_JSON, APPLICATION_JACKSON_SMILE})
public void getTaskInfo(
@PathParam("taskId") final TaskId taskId,
@HeaderParam(PRESTO_CURRENT_STATE) TaskState currentState,
@HeaderParam(PRESTO_MAX_WAIT) Duration maxWait,
@Context UriInfo uriInfo,
@Suspended AsyncResponse asyncResponse)
{
requireNonNull(taskId, "taskId is null");
if (currentState == null || maxWait == null) {
TaskInfo taskInfo = taskManager.getTaskInfo(taskId);
if (shouldSummarize(uriInfo)) {
taskInfo = taskInfo.summarize();
}
asyncResponse.resume(taskInfo);
return;
}
Duration waitTime = randomizeWaitTime(maxWait);
ListenableFuture<TaskInfo> futureTaskInfo = addTimeout(
taskManager.getTaskInfo(taskId, currentState),
() -> taskManager.getTaskInfo(taskId),
waitTime,
timeoutExecutor);
if (shouldSummarize(uriInfo)) {
futureTaskInfo = Futures.transform(futureTaskInfo, TaskInfo::summarize, directExecutor());
}
// For hard timeout, add an additional time to max wait for thread scheduling contention and GC
Duration timeout = new Duration(waitTime.toMillis() + ADDITIONAL_WAIT_TIME.toMillis(), MILLISECONDS);
bindAsyncResponse(asyncResponse, futureTaskInfo, responseExecutor)
.withTimeout(timeout);
}
@GET
@Path("{taskId}/status")
@Consumes({APPLICATION_JSON, APPLICATION_JACKSON_SMILE})
@Produces({APPLICATION_JSON, APPLICATION_JACKSON_SMILE})
public void getTaskStatus(
@PathParam("taskId") TaskId taskId,
@HeaderParam(PRESTO_CURRENT_STATE) TaskState currentState,
@HeaderParam(PRESTO_MAX_WAIT) Duration maxWait,
@Context UriInfo uriInfo,
@Suspended AsyncResponse asyncResponse)
{
requireNonNull(taskId, "taskId is null");
if (currentState == null || maxWait == null) {
TaskStatus taskStatus = taskManager.getTaskStatus(taskId);
asyncResponse.resume(taskStatus);
return;
}
Duration waitTime = randomizeWaitTime(maxWait);
// TODO: With current implementation, a newly completed driver group won't trigger immediate HTTP response,
// leading to a slight delay of approx 1 second, which is not a major issue for any query that are heavy weight enough
// to justify group-by-group execution. In order to fix this, REST endpoint /v1/{task}/status will need change.
ListenableFuture<TaskStatus> futureTaskStatus = addTimeout(
taskManager.getTaskStatus(taskId, currentState),
() -> taskManager.getTaskStatus(taskId),
waitTime,
timeoutExecutor);
// For hard timeout, add an additional time to max wait for thread scheduling contention and GC
Duration timeout = new Duration(waitTime.toMillis() + ADDITIONAL_WAIT_TIME.toMillis(), MILLISECONDS);
bindAsyncResponse(asyncResponse, futureTaskStatus, responseExecutor)
.withTimeout(timeout);
}
@POST
@Path("{taskId}/metadataresults")
@Consumes({APPLICATION_JSON, APPLICATION_JACKSON_SMILE})
public Response updateMetadataResults(@PathParam("taskId") TaskId taskId, MetadataUpdates metadataUpdates, @Context UriInfo uriInfo)
{
requireNonNull(metadataUpdates, "metadataUpdates is null");
taskManager.updateMetadataResults(taskId, metadataUpdates);
return Response.ok().build();
}
@DELETE
@Path("{taskId}")
@Consumes({APPLICATION_JSON, APPLICATION_JACKSON_SMILE})
@Produces({APPLICATION_JSON, APPLICATION_JACKSON_SMILE})
public TaskInfo deleteTask(
@PathParam("taskId") TaskId taskId,
@QueryParam("abort") @DefaultValue("true") boolean abort,
@Context UriInfo uriInfo)
{
requireNonNull(taskId, "taskId is null");
TaskInfo taskInfo;
if (abort) {
taskInfo = taskManager.abortTask(taskId);
}
else {
taskInfo = taskManager.cancelTask(taskId);
}
if (shouldSummarize(uriInfo)) {
taskInfo = taskInfo.summarize();
}
return taskInfo;
}
@GET
@Path("{taskId}/results/{bufferId}/{token}")
@Produces(PRESTO_PAGES)
public void getResults(
@PathParam("taskId") TaskId taskId,
@PathParam("bufferId") OutputBufferId bufferId,
@PathParam("token") final long token,
@HeaderParam(PRESTO_MAX_SIZE) DataSize maxSize,
@Suspended AsyncResponse asyncResponse)
{
requireNonNull(taskId, "taskId is null");
requireNonNull(bufferId, "bufferId is null");
long start = System.nanoTime();
ListenableFuture<BufferResult> bufferResultFuture = taskManager.getTaskResults(taskId, bufferId, token, maxSize);
Duration waitTime = randomizeWaitTime(DEFAULT_MAX_WAIT_TIME);
bufferResultFuture = addTimeout(
bufferResultFuture,
() -> BufferResult.emptyResults(taskManager.getTaskInstanceId(taskId), token, false),
waitTime,
timeoutExecutor);
ListenableFuture<Response> responseFuture = Futures.transform(bufferResultFuture, result -> {
List<SerializedPage> serializedPages = result.getSerializedPages();
GenericEntity<?> entity = null;
Status status;
if (serializedPages.isEmpty()) {
status = Status.NO_CONTENT;
}
else {
entity = new GenericEntity<>(serializedPages, new TypeToken<List<Page>>() {}.getType());
status = Status.OK;
}
return Response.status(status)
.entity(entity)
.header(PRESTO_TASK_INSTANCE_ID, result.getTaskInstanceId())
.header(PRESTO_PAGE_TOKEN, result.getToken())
.header(PRESTO_PAGE_NEXT_TOKEN, result.getNextToken())
.header(PRESTO_BUFFER_COMPLETE, result.isBufferComplete())
.build();
}, directExecutor());
// For hard timeout, add an additional time to max wait for thread scheduling contention and GC
Duration timeout = new Duration(waitTime.toMillis() + ADDITIONAL_WAIT_TIME.toMillis(), MILLISECONDS);
bindAsyncResponse(asyncResponse, responseFuture, responseExecutor)
.withTimeout(timeout,
Response.status(Status.NO_CONTENT)
.header(PRESTO_TASK_INSTANCE_ID, taskManager.getTaskInstanceId(taskId))
.header(PRESTO_PAGE_TOKEN, token)
.header(PRESTO_PAGE_NEXT_TOKEN, token)
.header(PRESTO_BUFFER_COMPLETE, false)
.build());
responseFuture.addListener(() -> readFromOutputBufferTime.add(Duration.nanosSince(start)), directExecutor());
asyncResponse.register((CompletionCallback) throwable -> resultsRequestTime.add(Duration.nanosSince(start)));
}
@GET
@Path("{taskId}/results/{bufferId}/{token}/acknowledge")
public void acknowledgeResults(
@PathParam("taskId") TaskId taskId,
@PathParam("bufferId") OutputBufferId bufferId,
@PathParam("token") final long token)
{
requireNonNull(taskId, "taskId is null");
requireNonNull(bufferId, "bufferId is null");
taskManager.acknowledgeTaskResults(taskId, bufferId, token);
}
@DELETE
@Path("{taskId}/results/{bufferId}")
@Produces(APPLICATION_JSON)
public void abortResults(@PathParam("taskId") TaskId taskId, @PathParam("bufferId") OutputBufferId bufferId, @Context UriInfo uriInfo)
{
requireNonNull(taskId, "taskId is null");
requireNonNull(bufferId, "bufferId is null");
taskManager.abortTaskResults(taskId, bufferId);
}
@DELETE
@Path("{taskId}/remote-source/{remoteSourceTaskId}")
public void removeRemoteSource(@PathParam("taskId") TaskId taskId, @PathParam("remoteSourceTaskId") TaskId remoteSourceTaskId)
{
requireNonNull(taskId, "taskId is null");
requireNonNull(remoteSourceTaskId, "remoteSourceTaskId is null");
taskManager.removeRemoteSource(taskId, remoteSourceTaskId);
}
@Managed
@Nested
public TimeStat getReadFromOutputBufferTime()
{
return readFromOutputBufferTime;
}
@Managed
@Nested
public TimeStat getResultsRequestTime()
{
return resultsRequestTime;
}
private static boolean shouldSummarize(UriInfo uriInfo)
{
return uriInfo.getQueryParameters().containsKey("summarize");
}
}
| |
/*
* Copyright 2003-2012 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.codehaus.groovy.transform.stc;
import groovy.lang.*;
import org.codehaus.groovy.GroovyBugError;
import org.codehaus.groovy.ast.*;
import org.codehaus.groovy.ast.expr.*;
import org.codehaus.groovy.ast.stmt.EmptyStatement;
import org.codehaus.groovy.classgen.asm.InvocationWriter;
import org.codehaus.groovy.control.CompilationFailedException;
import org.codehaus.groovy.control.CompilationUnit;
import org.codehaus.groovy.control.CompilerConfiguration;
import org.codehaus.groovy.control.customizers.ImportCustomizer;
import org.codehaus.groovy.control.messages.ExceptionMessage;
import org.codehaus.groovy.control.messages.SimpleMessage;
import org.codehaus.groovy.runtime.InvokerHelper;
import org.codehaus.groovy.runtime.InvokerInvocationException;
import org.objectweb.asm.Opcodes;
import java.io.*;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.*;
import java.util.concurrent.Callable;
/**
* Base class for type checking extensions written in Groovy. Compared to its superclass, {@link TypeCheckingExtension},
* this class adds a number of utility methods aimed at leveraging the syntax of the Groovy language to improve
* expressivity and conciseness.
*
* @author Cedric Champeau
* @since 2.1.0
*/
public class GroovyTypeCheckingExtensionSupport extends TypeCheckingExtension {
// method name to DSL name
private final static Map<String, String> METHOD_ALIASES = Collections.unmodifiableMap(
new HashMap<String, String>() {{
put("onMethodSelection", "onMethodSelection");
put("afterMethodCall", "afterMethodCall");
put("beforeMethodCall", "beforeMethodCall");
put("unresolvedVariable", "handleUnresolvedVariableExpression");
put("unresolvedProperty", "handleUnresolvedProperty");
put("unresolvedAttribute", "handleUnresolvedAttribute");
put("methodNotFound", "handleMissingMethod");
put("afterVisitMethod", "afterVisitMethod");
put("beforeVisitMethod", "beforeVisitMethod");
put("afterVisitClass", "afterVisitClass");
put("beforeVisitClass", "beforeVisitClass");
put("incompatibleAssignment", "handleIncompatibleAssignment");
put("setup","setup");
put("finish", "finish");
}}
);
private final Set<MethodNode> generatedMethods = new LinkedHashSet<MethodNode>();
private final LinkedList<TypeCheckingScope> scopeData = new LinkedList<TypeCheckingScope>();
// the following fields are closures executed in event-based methods
private final Map<String, List<Closure>> eventHandlers = new HashMap<String, List<Closure>>();
private final String scriptPath;
private final TypeCheckingContext context;
// this boolean is used through setHandled(boolean)
private boolean handled = false;
private final CompilationUnit compilationUnit;
/**
* Builds a type checking extension relying on a Groovy script (type checking DSL).
*
* @param typeCheckingVisitor the type checking visitor
* @param scriptPath the path to the type checking script (in classpath)
* @param compilationUnit
*/
public GroovyTypeCheckingExtensionSupport(
final StaticTypeCheckingVisitor typeCheckingVisitor,
final String scriptPath, final CompilationUnit compilationUnit) {
super(typeCheckingVisitor);
this.scriptPath = scriptPath;
this.context = typeCheckingVisitor.typeCheckingContext;
this.compilationUnit = compilationUnit;
}
@Override
public void setup() {
CompilerConfiguration config = new CompilerConfiguration();
config.setScriptBaseClass("org.codehaus.groovy.transform.stc.GroovyTypeCheckingExtensionSupport.TypeCheckingDSL");
ImportCustomizer ic = new ImportCustomizer();
ic.addStarImports("org.codehaus.groovy.ast.expr");
ic.addStaticStars("org.codehaus.groovy.ast.ClassHelper");
ic.addStaticStars("org.codehaus.groovy.transform.stc.StaticTypeCheckingSupport");
config.addCompilationCustomizers(ic);
final GroovyClassLoader transformLoader = compilationUnit!=null?compilationUnit.getTransformLoader():typeCheckingVisitor.getSourceUnit().getClassLoader();
ClassLoader cl = typeCheckingVisitor.getSourceUnit().getClassLoader();
// cast to prevent incorrect @since 1.7 warning
InputStream is = ((ClassLoader)transformLoader).getResourceAsStream(scriptPath);
if (is == null) {
// fallback to the source unit classloader
is = cl.getResourceAsStream(scriptPath);
}
if (is == null) {
// fallback to the compiler classloader
cl = GroovyTypeCheckingExtensionSupport.class.getClassLoader();
is = cl.getResourceAsStream(scriptPath);
}
if (is == null) {
// if the input stream is still null, we've not found the extension
context.getErrorCollector().addFatalError(
new SimpleMessage("Static type checking extension '" + scriptPath + "' was not found on the classpath.",
config.getDebug(), typeCheckingVisitor.getSourceUnit()));
}
try {
GroovyShell shell = new GroovyShell(transformLoader, new Binding(), config);
TypeCheckingDSL parse = (TypeCheckingDSL) shell.parse(
new InputStreamReader(is, typeCheckingVisitor.getSourceUnit().getConfiguration().getSourceEncoding())
);
parse.extension = this;
parse.run();
List<Closure> list = eventHandlers.get("setup");
if (list != null) {
for (Closure closure : list) {
safeCall(closure);
}
}
} catch (CompilationFailedException e) {
throw new GroovyBugError("An unexpected error was thrown during custom type checking", e);
} catch (UnsupportedEncodingException e) {
throw new GroovyBugError("Unsupported encoding found in compiler configuration", e);
}
}
@Override
public void finish() {
List<Closure> list = eventHandlers.get("finish");
if (list != null) {
for (Closure closure : list) {
safeCall(closure);
}
}
}
public void setHandled(final boolean handled) {
this.handled = handled;
}
public TypeCheckingScope newScope() {
TypeCheckingScope scope = new TypeCheckingScope(scopeData.peek());
scopeData.addFirst(scope);
return scope;
}
public TypeCheckingScope newScope(Closure code) {
TypeCheckingScope scope = newScope();
Closure callback = code.rehydrate(scope, this, this);
callback.call();
return scope;
}
public TypeCheckingScope scopeExit() {
return scopeData.removeFirst();
}
public TypeCheckingScope getCurrentScope() {
return scopeData.peek();
}
public TypeCheckingScope scopeExit(Closure code) {
TypeCheckingScope scope = scopeData.peek();
Closure copy = code.rehydrate(scope, this, this);
copy.call();
return scopeExit();
}
public boolean isGenerated(MethodNode node) {
return generatedMethods.contains(node);
}
public List<MethodNode> unique(MethodNode node) {
return Collections.singletonList(node);
}
public MethodNode newMethod(final String name, final Class returnType) {
return newMethod(name, ClassHelper.make(returnType));
}
public MethodNode newMethod(final String name, final ClassNode returnType) {
MethodNode node = new MethodNode(name,
Opcodes.ACC_PUBLIC,
returnType,
Parameter.EMPTY_ARRAY,
ClassNode.EMPTY_ARRAY,
EmptyStatement.INSTANCE);
generatedMethods.add(node);
return node;
}
public MethodNode newMethod(final String name,
final Callable<ClassNode> returnType) {
MethodNode node = new MethodNode(name,
Opcodes.ACC_PUBLIC,
ClassHelper.OBJECT_TYPE,
Parameter.EMPTY_ARRAY,
ClassNode.EMPTY_ARRAY,
EmptyStatement.INSTANCE) {
@Override
public ClassNode getReturnType() {
try {
return returnType.call();
} catch (Exception e) {
return super.getReturnType();
}
}
};
generatedMethods.add(node);
return node;
}
public void delegatesTo(ClassNode type) {
delegatesTo(type, Closure.OWNER_FIRST);
}
public void delegatesTo(ClassNode type, int strategy) {
delegatesTo(type, strategy, typeCheckingVisitor.typeCheckingContext.delegationMetadata);
}
public void delegatesTo(ClassNode type, int strategy, DelegationMetadata parent) {
typeCheckingVisitor.typeCheckingContext.delegationMetadata = new DelegationMetadata(type, strategy, parent);
}
public boolean isAnnotatedBy(ASTNode node, Class annotation) {
return isAnnotatedBy(node, ClassHelper.make(annotation));
}
public boolean isAnnotatedBy(ASTNode node, ClassNode annotation) {
return node instanceof AnnotatedNode && !((AnnotatedNode)node).getAnnotations(annotation).isEmpty();
}
public boolean isDynamic(VariableExpression var) {
return var.getAccessedVariable() instanceof DynamicVariable;
}
public boolean isExtensionMethod(MethodNode node) {
return node instanceof ExtensionMethodNode;
}
public ArgumentListExpression getArguments(MethodCall call) {
return InvocationWriter.makeArgumentList(call.getArguments());
}
private Object safeCall(Closure closure, Object... args) {
try {
return closure.call(args);
} catch (Exception err) {
typeCheckingVisitor.getSourceUnit().addException(err);
return null;
}
}
@Override
public void onMethodSelection(final Expression expression, final MethodNode target) {
List<Closure> onMethodSelection = eventHandlers.get("onMethodSelection");
if (onMethodSelection != null) {
for (Closure closure : onMethodSelection) {
safeCall(closure, expression, target);
}
}
}
@Override
public void afterMethodCall(final MethodCall call) {
List<Closure> onMethodSelection = eventHandlers.get("afterMethodCall");
if (onMethodSelection != null) {
for (Closure closure : onMethodSelection) {
safeCall(closure, call);
}
}
}
@Override
public boolean beforeMethodCall(final MethodCall call) {
setHandled(false);
List<Closure> onMethodSelection = eventHandlers.get("beforeMethodCall");
if (onMethodSelection != null) {
for (Closure closure : onMethodSelection) {
safeCall(closure, call);
}
}
return handled;
}
@Override
public boolean handleUnresolvedVariableExpression(final VariableExpression vexp) {
setHandled(false);
List<Closure> onMethodSelection = eventHandlers.get("handleUnresolvedVariableExpression");
if (onMethodSelection != null) {
for (Closure closure : onMethodSelection) {
safeCall(closure, vexp);
}
}
return handled;
}
@Override
public boolean handleUnresolvedProperty(final PropertyExpression pexp) {
setHandled(false);
List<Closure> list = eventHandlers.get("handleUnresolvedProperty");
if (list != null) {
for (Closure closure : list) {
safeCall(closure, pexp);
}
}
return handled;
}
@Override
public boolean handleUnresolvedAttribute(final AttributeExpression aexp) {
setHandled(false);
List<Closure> list = eventHandlers.get("handleUnresolvedAttribute");
if (list != null) {
for (Closure closure : list) {
safeCall(closure, aexp);
}
}
return handled;
}
@Override
public void afterVisitMethod(final MethodNode node) {
List<Closure> list = eventHandlers.get("afterVisitMethod");
if (list != null) {
for (Closure closure : list) {
safeCall(closure, node);
}
}
}
@Override
public boolean beforeVisitClass(final ClassNode node) {
setHandled(false);
List<Closure> list = eventHandlers.get("beforeVisitClass");
if (list != null) {
for (Closure closure : list) {
safeCall(closure, node);
}
}
return handled;
}
@Override
public void afterVisitClass(final ClassNode node) {
List<Closure> list = eventHandlers.get("afterVisitClass");
if (list != null) {
for (Closure closure : list) {
safeCall(closure, node);
}
}
}
@Override
public boolean beforeVisitMethod(final MethodNode node) {
setHandled(false);
List<Closure> list = eventHandlers.get("beforeVisitMethod");
if (list != null) {
for (Closure closure : list) {
safeCall(closure, node);
}
}
return handled;
}
@Override
public boolean handleIncompatibleAssignment(final ClassNode lhsType, final ClassNode rhsType, final Expression assignmentExpression) {
setHandled(false);
List<Closure> list = eventHandlers.get("handleIncompatibleAssignment");
if (list != null) {
for (Closure closure : list) {
safeCall(closure, lhsType, rhsType, assignmentExpression);
}
}
return handled;
}
@Override
@SuppressWarnings("unchecked")
public List<MethodNode> handleMissingMethod(final ClassNode receiver, final String name, final ArgumentListExpression argumentList, final ClassNode[] argumentTypes, final MethodCall call) {
List<Closure> onMethodSelection = eventHandlers.get("handleMissingMethod");
List<MethodNode> methodList = new LinkedList<MethodNode>();
if (onMethodSelection != null) {
for (Closure closure : onMethodSelection) {
Object result = safeCall(closure, receiver, name, argumentList, argumentTypes, call);
if (result != null) {
if (result instanceof MethodNode) {
methodList.add((MethodNode) result);
} else if (result instanceof Collection) {
methodList.addAll((Collection<? extends MethodNode>) result);
} else {
throw new GroovyBugError("Type checking extension returned unexpected method list: " + result);
}
}
}
}
return methodList;
}
public boolean isMethodCall(Object o) {
return o instanceof MethodCallExpression;
}
public boolean argTypesMatches(ClassNode[] argTypes, Class... classes) {
if (classes == null) return argTypes == null || argTypes.length == 0;
if (argTypes.length != classes.length) return false;
boolean match = true;
for (int i = 0; i < argTypes.length && match; i++) {
match = matchWithOrWithourBoxing(argTypes[i], classes[i]);
}
return match;
}
private boolean matchWithOrWithourBoxing(final ClassNode argType, final Class aClass) {
final boolean match;
ClassNode type = ClassHelper.make(aClass);
if (ClassHelper.isPrimitiveType(type) && !ClassHelper.isPrimitiveType(argType)) {
type = ClassHelper.getWrapper(type);
} else if (ClassHelper.isPrimitiveType(argType) && !ClassHelper.isPrimitiveType(type)) {
type = ClassHelper.getUnwrapper(type);
}
match = argType.equals(type);
return match;
}
public boolean argTypesMatches(MethodCall call, Class... classes) {
ArgumentListExpression argumentListExpression = InvocationWriter.makeArgumentList(call.getArguments());
ClassNode[] argumentTypes = typeCheckingVisitor.getArgumentTypes(argumentListExpression);
return argTypesMatches(argumentTypes, classes);
}
public boolean firstArgTypesMatches(ClassNode[] argTypes, Class... classes) {
if (classes == null) return argTypes == null || argTypes.length == 0;
if (argTypes.length<classes.length) return false;
boolean match = true;
for (int i = 0; i < classes.length && match; i++) {
match = matchWithOrWithourBoxing(argTypes[i], classes[i]);
}
return match;
}
public boolean firstArgTypesMatches(MethodCall call, Class... classes) {
ArgumentListExpression argumentListExpression = InvocationWriter.makeArgumentList(call.getArguments());
ClassNode[] argumentTypes = typeCheckingVisitor.getArgumentTypes(argumentListExpression);
return firstArgTypesMatches(argumentTypes, classes);
}
public boolean argTypeMatches(ClassNode[] argTypes, int index, Class clazz) {
if (index >= argTypes.length) return false;
return matchWithOrWithourBoxing(argTypes[index], clazz);
}
public boolean argTypeMatches(MethodCall call, int index, Class clazz) {
ArgumentListExpression argumentListExpression = InvocationWriter.makeArgumentList(call.getArguments());
ClassNode[] argumentTypes = typeCheckingVisitor.getArgumentTypes(argumentListExpression);
return argTypeMatches(argumentTypes, index, clazz);
}
@SuppressWarnings("unchecked")
public <R> R withTypeChecker(Closure<R> code) {
Closure<R> clone = (Closure<R>) code.clone();
clone.setDelegate(typeCheckingVisitor);
clone.setResolveStrategy(Closure.DELEGATE_FIRST);
return clone.call();
}
// -------------------------------------
// delegate to the type checking context
// -------------------------------------
public BinaryExpression getEnclosingBinaryExpression() {
return context.getEnclosingBinaryExpression();
}
public void pushEnclosingBinaryExpression(final BinaryExpression binaryExpression) {
context.pushEnclosingBinaryExpression(binaryExpression);
}
public void pushEnclosingClosureExpression(final ClosureExpression closureExpression) {
context.pushEnclosingClosureExpression(closureExpression);
}
public Expression getEnclosingMethodCall() {
return context.getEnclosingMethodCall();
}
public Expression popEnclosingMethodCall() {
return context.popEnclosingMethodCall();
}
public MethodNode popEnclosingMethod() {
return context.popEnclosingMethod();
}
public ClassNode getEnclosingClassNode() {
return context.getEnclosingClassNode();
}
public List<MethodNode> getEnclosingMethods() {
return context.getEnclosingMethods();
}
public MethodNode getEnclosingMethod() {
return context.getEnclosingMethod();
}
public void popTemporaryTypeInfo() {
context.popTemporaryTypeInfo();
}
public void pushEnclosingClassNode(final ClassNode classNode) {
context.pushEnclosingClassNode(classNode);
}
public BinaryExpression popEnclosingBinaryExpression() {
return context.popEnclosingBinaryExpression();
}
public List<ClassNode> getEnclosingClassNodes() {
return context.getEnclosingClassNodes();
}
public List<TypeCheckingContext.EnclosingClosure> getEnclosingClosureStack() {
return context.getEnclosingClosureStack();
}
public ClassNode popEnclosingClassNode() {
return context.popEnclosingClassNode();
}
public void pushEnclosingMethod(final MethodNode methodNode) {
context.pushEnclosingMethod(methodNode);
}
public List<BinaryExpression> getEnclosingBinaryExpressionStack() {
return context.getEnclosingBinaryExpressionStack();
}
public TypeCheckingContext.EnclosingClosure getEnclosingClosure() {
return context.getEnclosingClosure();
}
public List<Expression> getEnclosingMethodCalls() {
return context.getEnclosingMethodCalls();
}
public void pushEnclosingMethodCall(final Expression call) {
context.pushEnclosingMethodCall(call);
}
public TypeCheckingContext.EnclosingClosure popEnclosingClosure() {
return context.popEnclosingClosure();
}
public void pushTemporaryTypeInfo() {
context.pushTemporaryTypeInfo();
}
// --------------------------------------------
// end of delegate to the type checking context
// --------------------------------------------
private class TypeCheckingScope extends LinkedHashMap<String, Object> {
private final TypeCheckingScope parent;
private TypeCheckingScope(final TypeCheckingScope parentScope) {
this.parent = parentScope;
}
public TypeCheckingScope getParent() {
return parent;
}
}
public abstract static class TypeCheckingDSL extends Script {
private GroovyTypeCheckingExtensionSupport extension;
@Override
public Object getProperty(final String property) {
try {
return InvokerHelper.getProperty(extension, property);
} catch (Exception e) {
return super.getProperty(property);
}
}
@Override
public void setProperty(final String property, final Object newValue) {
try {
InvokerHelper.setProperty(extension, property, newValue);
} catch (Exception e) {
super.setProperty(property, newValue);
}
}
@Override
public Object invokeMethod(final String name, final Object args) {
if (name.startsWith("is") && name.endsWith("Expression") && args instanceof Object[] && ((Object[]) args).length == 1) {
String type = name.substring(2);
Object target = ((Object[]) args)[0];
if (target==null) return false;
try {
Class typeClass = Class.forName("org.codehaus.groovy.ast.expr."+type);
return typeClass.isAssignableFrom(target.getClass());
} catch (ClassNotFoundException e) {
return false;
}
}
if (args instanceof Object[] && ((Object[]) args).length == 1 && ((Object[]) args)[0] instanceof Closure) {
Object[] argsArray = (Object[]) args;
String methodName = METHOD_ALIASES.get(name);
if (methodName == null) {
return InvokerHelper.invokeMethod(extension, name, args);
}
List<Closure> closures = extension.eventHandlers.get(methodName);
if (closures == null) {
closures = new LinkedList<Closure>();
extension.eventHandlers.put(methodName, closures);
}
closures.add((Closure) argsArray[0]);
return null;
} else {
return InvokerHelper.invokeMethod(extension, name, args);
}
}
}
}
| |
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.chrome.browser.layouts.animation;
import static org.chromium.base.ContextUtils.getApplicationContext;
import android.animation.Animator;
import android.animation.TimeInterpolator;
import android.animation.ValueAnimator;
import android.provider.Settings;
import androidx.annotation.IntDef;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.VisibleForTesting;
import org.chromium.base.Log;
import org.chromium.base.ObserverList;
import org.chromium.base.supplier.Supplier;
import org.chromium.components.browser_ui.widget.animation.Interpolators;
import org.chromium.ui.modelutil.PropertyModel;
import org.chromium.ui.modelutil.PropertyModel.WritableFloatPropertyKey;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
/**
* An animator that can be used for animations in the Browser Compositor.
*/
public class CompositorAnimator extends Animator {
private static final String TAG = "CompositorAnimator";
/** The different states that this animator can be in. */
@IntDef({AnimationState.STARTED, AnimationState.RUNNING, AnimationState.CANCELED,
AnimationState.ENDED})
@Retention(RetentionPolicy.SOURCE)
private @interface AnimationState {
int STARTED = 0;
int RUNNING = 1;
int CANCELED = 2;
int ENDED = 3;
}
/**
* The scale honoring Settings.Global.ANIMATOR_DURATION_SCALE. Use static to reduce updating.
* See {@link ValueAnimator}.
**/
@VisibleForTesting
public static float sDurationScale = 1;
/** The {@link CompositorAnimationHandler} running the animation. */
private final WeakReference<CompositorAnimationHandler> mHandler;
/** The list of listeners for events through the life of an animation. */
private final ObserverList<AnimatorListener> mListeners = new ObserverList<>();
/** The list of frame update listeners for this animation. */
private final ArrayList<AnimatorUpdateListener> mAnimatorUpdateListeners = new ArrayList<>();
/**
* A cached copy of the list of {@link AnimatorUpdateListener}s to prevent allocating a new list
* every update.
*/
private final ArrayList<AnimatorUpdateListener> mCachedList = new ArrayList<>();
/** The time interpolator for the animator. */
private TimeInterpolator mTimeInterpolator;
/**
* The amount of time in ms that has passed since the animation has started. This includes any
* delay that was set.
*/
private long mTimeSinceStartMs;
/**
* The fraction that the animation is complete. This number is in the range [0, 1] and accounts
* for the set time interpolator.
*/
private float mAnimatedFraction;
/** The value that the animation should start with (ending at {@link #mEndValue}). */
private Supplier<Float> mStartValue;
/** The value that the animation will transition to (starting at {@link #mStartValue}). */
private Supplier<Float> mEndValue;
/** The duration of the animation in ms. */
private long mDurationMs;
/**
* The animator's start delay in ms. Once {@link #start()} is called, updates are not sent until
* this time has passed.
*/
private long mStartDelayMs;
/** The current state of the animation. */
@AnimationState
private int mAnimationState = AnimationState.ENDED;
/**
* Whether the animation ended because of frame updates. This is used to determine if any
* listeners need to be updated one more time.
*/
private boolean mDidUpdateToCompletion;
/**
* A utility for creating a basic animator.
* @param handler The {@link CompositorAnimationHandler} responsible for running the animation.
* @param startValue The starting animation value.
* @param endValue The end animation value.
* @param durationMs The duration of the animation in ms.
* @param listener An update listener if specific actions need to be performed.
* @return A {@link CompositorAnimator} for the property.
*/
public static CompositorAnimator ofFloat(CompositorAnimationHandler handler, float startValue,
float endValue, long durationMs, @Nullable AnimatorUpdateListener listener) {
CompositorAnimator animator = new CompositorAnimator(handler);
animator.setValues(startValue, endValue);
if (listener != null) animator.addUpdateListener(listener);
animator.setDuration(durationMs);
return animator;
}
/**
* A utility for creating a basic animator.
* @param handler The {@link CompositorAnimationHandler} responsible for running the animation.
* @param target The object to modify.
* @param property The property of the object to modify.
* @param startValue The starting animation value.
* @param endValue The end animation value.
* @param durationMs The duration of the animation in ms.
* @param interpolator The time interpolator for the animation.
* @return A {@link CompositorAnimator} for the property.
*/
public static <T> CompositorAnimator ofFloatProperty(CompositorAnimationHandler handler,
final T target, final FloatProperty<T> property, float startValue, float endValue,
long durationMs, TimeInterpolator interpolator) {
CompositorAnimator animator = new CompositorAnimator(handler);
animator.setValues(startValue, endValue);
animator.setDuration(durationMs);
animator.addUpdateListener(
(CompositorAnimator a) -> property.setValue(target, a.getAnimatedValue()));
animator.setInterpolator(interpolator);
return animator;
}
/**
* A utility for creating a basic animator.
* @param handler The {@link CompositorAnimationHandler} responsible for running the animation.
* @param target The object to modify.
* @param property The property of the object to modify.
* @param startValue The {@link Supplier} of the starting animation value.
* @param endValue The {@link Supplier} of the end animation value.
* @param durationMs The duration of the animation in ms.
* @param interpolator The time interpolator for the animation.
* @return A {@link CompositorAnimator} for the property.
*/
public static <T> CompositorAnimator ofFloatProperty(CompositorAnimationHandler handler,
final T target, final FloatProperty<T> property, Supplier<Float> startValue,
Supplier<Float> endValue, long durationMs, TimeInterpolator interpolator) {
CompositorAnimator animator = new CompositorAnimator(handler);
animator.setValues(startValue, endValue);
animator.setDuration(durationMs);
animator.addUpdateListener(
(CompositorAnimator a) -> property.setValue(target, a.getAnimatedValue()));
animator.setInterpolator(interpolator);
return animator;
}
/**
* A utility for creating a basic animator.
* @param handler The {@link CompositorAnimationHandler} responsible for running the animation.
* @param target The object to modify.
* @param property The property of the object to modify.
* @param startValue The starting animation value.
* @param endValue The end animation value.
* @param durationMs The duration of the animation in ms.
* @return A {@link CompositorAnimator} for the property.
*/
public static <T> CompositorAnimator ofFloatProperty(CompositorAnimationHandler handler,
final T target, final FloatProperty<T> property, float startValue, float endValue,
long durationMs) {
return ofFloatProperty(handler, target, property, startValue, endValue, durationMs,
Interpolators.DECELERATE_INTERPOLATOR);
}
/**
* A utility for creating a basic animator.
* @param handler The {@link CompositorAnimationHandler} responsible for running the animation.
* @param target The object to modify.
* @param property The property of the object to modify.
* @param startValue The {@link Supplier} of the starting animation value.
* @param endValue The {@link Supplier} of the end animation value.
* @param durationMs The duration of the animation in ms.
* @return A {@link CompositorAnimator} for the property.
*/
public static <T> CompositorAnimator ofFloatProperty(CompositorAnimationHandler handler,
final T target, final FloatProperty<T> property, Supplier<Float> startValue,
Supplier<Float> endValue, long durationMs) {
return ofFloatProperty(handler, target, property, startValue, endValue, durationMs,
Interpolators.DECELERATE_INTERPOLATOR);
}
/**
* Create a {@link CompositorAnimator} to animate the {@link WritableFloatPropertyKey}.
* @param handler The {@link CompositorAnimationHandler} responsible for running the animation.
* @param model The {@link PropertyModel} to modify.
* @param key The {@link WritableFloatPropertyKey} in the model to update.
* @param startValue The {@link Supplier} of the starting animation value.
* @param endValue The {@link Supplier} of the end animation value.
* @param durationMs The duration of the animation in ms.
* @param interpolator The time interpolator for the animation.
* @return {@link CompositorAnimator} for animating the {@link WritableFloatPropertyKey}.
*/
public static CompositorAnimator ofWritableFloatPropertyKey(CompositorAnimationHandler handler,
final PropertyModel model, WritableFloatPropertyKey key, Supplier<Float> startValue,
Supplier<Float> endValue, long durationMs, TimeInterpolator interpolator) {
CompositorAnimator animator = new CompositorAnimator(handler);
animator.setValues(startValue, endValue);
animator.setDuration(durationMs);
animator.addUpdateListener((CompositorAnimator a) -> model.set(key, a.getAnimatedValue()));
animator.setInterpolator(interpolator);
return animator;
}
/**
* Create a {@link CompositorAnimator} to animate the {@link WritableFloatPropertyKey}.
* @param handler The {@link CompositorAnimationHandler} responsible for running the animation.
* @param model The {@link PropertyModel} to modify.
* @param key The {@link WritableFloatPropertyKey} in the model to update.
* @param startValue The starting animation value.
* @param endValue The end animation value.
* @param durationMs The duration of the animation in ms.
* @param interpolator The time interpolator for the animation.
* @return {@link CompositorAnimator} for animating the {@link WritableFloatPropertyKey}.
*/
public static CompositorAnimator ofWritableFloatPropertyKey(CompositorAnimationHandler handler,
final PropertyModel model, WritableFloatPropertyKey key, float startValue,
float endValue, long durationMs, TimeInterpolator interpolator) {
return ofWritableFloatPropertyKey(
handler, model, key, () -> startValue, () -> endValue, durationMs, interpolator);
}
/**
* Create a {@link CompositorAnimator} to animate the {@link WritableFloatPropertyKey}.
* @param handler The {@link CompositorAnimationHandler} responsible for running the animation.
* @param model The {@link PropertyModel} to modify.
* @param key The {@link WritableFloatPropertyKey} in the model to update.
* @param startValue The starting animation value.
* @param endValue The end animation value.
* @param durationMs The duration of the animation in ms.
* @return {@link CompositorAnimator} for animating the {@link WritableFloatPropertyKey}.
*/
public static CompositorAnimator ofWritableFloatPropertyKey(CompositorAnimationHandler handler,
final PropertyModel model, WritableFloatPropertyKey key, float startValue,
float endValue, long durationMs) {
return ofWritableFloatPropertyKey(handler, model, key, startValue, endValue, durationMs,
Interpolators.DECELERATE_INTERPOLATOR);
}
/** An interface for listening for frames of an animation. */
public interface AnimatorUpdateListener {
/**
* A notification of the occurrence of another frame of the animation.
* @param animator The animator that was updated.
*/
void onAnimationUpdate(CompositorAnimator animator);
}
/**
* Create a new animator for the current context.
* @param handler The {@link CompositorAnimationHandler} responsible for running the animation.
*/
public CompositorAnimator(@NonNull CompositorAnimationHandler handler) {
mHandler = new WeakReference<>(handler);
// The default interpolator is decelerate; this mimics the existing ChromeAnimation
// behavior.
mTimeInterpolator = Interpolators.DECELERATE_INTERPOLATOR;
// By default, animate for 0 to 1.
setValues(0, 1);
// Try to update from the system setting, but not too frequently.
sDurationScale = Settings.Global.getFloat(getApplicationContext().getContentResolver(),
Settings.Global.ANIMATOR_DURATION_SCALE, sDurationScale);
if (sDurationScale != 1) {
Log.i(TAG, "Settings.Global.ANIMATOR_DURATION_SCALE = %f", sDurationScale);
}
}
private long getScaledDuration() {
return (long) (mDurationMs * sDurationScale);
}
/**
* Push an update to the animation. This should be called while the start delay is active and
* assumes that the animated object is at the starting position when {@link #start} is called.
* @param deltaTimeMs The time since the previous frame.
*/
public void doAnimationFrame(long deltaTimeMs) {
mTimeSinceStartMs += deltaTimeMs;
// Clamp to the animator's duration, taking into account the start delay.
long finalTimeMs = Math.min(
(long) (mTimeSinceStartMs - mStartDelayMs * sDurationScale), getScaledDuration());
// Wait until the start delay has passed.
if (finalTimeMs < 0) return;
// In the case where duration is 0, the animation is complete.
mAnimatedFraction = 1;
if (getScaledDuration() > 0) {
mAnimatedFraction =
mTimeInterpolator.getInterpolation(finalTimeMs / (float) getScaledDuration());
}
// Push update to listeners.
mCachedList.addAll(mAnimatorUpdateListeners);
for (int i = 0; i < mCachedList.size(); i++) mCachedList.get(i).onAnimationUpdate(this);
mCachedList.clear();
if (finalTimeMs == getScaledDuration()) {
mDidUpdateToCompletion = true;
end();
}
}
/**
* @return The animated fraction after being passed through the time interpolator, if set.
*/
@VisibleForTesting
float getAnimatedFraction() {
return mAnimatedFraction;
}
/**
* Add a listener for frame occurrences.
* @param listener The listener to add.
*/
public void addUpdateListener(AnimatorUpdateListener listener) {
mAnimatorUpdateListeners.add(listener);
}
/**
* @return Whether or not the animation has ended after being started. If the animation is
* started after ending, this value will be reset to true.
*/
public boolean hasEnded() {
return mAnimationState == AnimationState.ENDED;
}
/**
* Set the values to animate between.
* @param start The value to begin the animation with.
* @param end The value to end the animation at.
*/
void setValues(float start, float end) {
setValues(() -> start, () -> end);
}
/**
* Set the values to animate between.
* @param start The value to begin the animation with.
* @param end The value to end the animation at.
*/
@VisibleForTesting
void setValues(Supplier<Float> start, Supplier<Float> end) {
mStartValue = start;
mEndValue = end;
}
/**
* @return The current value between the floats set by {@link #setValues(float, float)}.
*/
public float getAnimatedValue() {
return mStartValue.get() + (getAnimatedFraction() * (mEndValue.get() - mStartValue.get()));
}
@Override
public void addListener(AnimatorListener listener) {
mListeners.addObserver(listener);
}
@Override
public void removeListener(AnimatorListener listener) {
mListeners.removeObserver(listener);
}
@Override
public void removeAllListeners() {
mListeners.clear();
mAnimatorUpdateListeners.clear();
}
@Override
@SuppressWarnings("unchecked")
public void start() {
if (mAnimationState != AnimationState.ENDED) return;
super.start();
mAnimationState = AnimationState.RUNNING;
mDidUpdateToCompletion = false;
CompositorAnimationHandler handler = mHandler.get();
if (handler != null) handler.registerAndStartAnimator(this);
mTimeSinceStartMs = 0;
for (AnimatorListener listener : mListeners) listener.onAnimationStart(this);
}
@Override
@SuppressWarnings("unchecked")
public void cancel() {
if (mAnimationState == AnimationState.ENDED) return;
mAnimationState = AnimationState.CANCELED;
super.cancel();
for (AnimatorListener listener : mListeners) listener.onAnimationCancel(this);
end();
}
@Override
@SuppressWarnings("unchecked")
public void end() {
if (mAnimationState == AnimationState.ENDED) return;
super.end();
boolean wasCanceled = mAnimationState == AnimationState.CANCELED;
mAnimationState = AnimationState.ENDED;
// If the animation was ended early but not canceled, push one last update to the listeners.
if (!mDidUpdateToCompletion && !wasCanceled) {
mAnimatedFraction = 1f;
for (AnimatorUpdateListener listener : mAnimatorUpdateListeners) {
listener.onAnimationUpdate(this);
}
}
for (AnimatorListener listener : mListeners) listener.onAnimationEnd(this);
}
@Override
public long getStartDelay() {
return mStartDelayMs;
}
@Override
public void setStartDelay(long startDelayMs) {
if (startDelayMs < 0) startDelayMs = 0;
mStartDelayMs = startDelayMs;
}
@Override
public CompositorAnimator setDuration(long durationMs) {
if (durationMs < 0) durationMs = 0;
mDurationMs = durationMs;
return this;
}
@Override
public long getDuration() {
return mDurationMs;
}
@Override
public void setInterpolator(TimeInterpolator timeInterpolator) {
assert timeInterpolator != null;
mTimeInterpolator = timeInterpolator;
}
@Override
public boolean isRunning() {
return mAnimationState == AnimationState.RUNNING;
}
}
| |
// BSD License (http://lemurproject.org/galago-license)
package org.lemurproject.galago.tupleflow.execution;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import org.lemurproject.galago.tupleflow.Utility;
/**
* A Job object specifies a TupleFlow execution: the objects used, their
* parameters, and how they communicate. A Job can be specified in XML (and
* parsed with JobConstructor), or in code.
*
* Usage: users create these, then run them using the JobExecutor
*
* Possible Improvements: - the ability to branch on some condition - arbitrary
* looping
*
* @author trevor
*/
public class Job implements Serializable {
public TreeMap<String, Stage> stages = new TreeMap<String, Stage>();
public ArrayList<Connection> connections = new ArrayList<Connection>();
public HashMap<String, ConnectionEndPoint> exports = new HashMap<String, ConnectionEndPoint>();
public HashMap<String, String> properties = new HashMap<String, String>();
private String orderString(String[] order) {
StringBuilder builder = new StringBuilder();
for (String o : order) {
if (builder.length() > 0) {
builder.append(" ");
}
builder.append(o);
}
return builder.toString();
}
/**
* Sometimes its convenient to specify a group of stages as its own job, with
* connections that flow between stages specified in the job. The add method
* allows you to add another job to this job. To avoid name conflicts, all
* stages in the job are renamed from <tt>stageName</tt> to
* <tt>jobName.stageName</tt>.
*/
public Job add(String jobName, Job group) {
assert this != group;
for (Stage s : group.stages.values()) {
Stage copy = s.clone();
copy.name = jobName + "." + s.name;
add(copy);
}
for (Connection c : group.connections) {
Connection copy = c.clone();
copy.input.setStageName(jobName + "." + copy.input.getStageName());
for (ConnectionEndPoint output : copy.outputs) {
output.setStageName(jobName + "." + output.getStageName());
}
connections.add(copy);
}
return this;
}
/**
* Adds a stage to the current job.
*/
public Job add(Stage s) {
stages.put(s.name, s);
return this;
}
Map<String, Stage> findStagesWithPrefix(String prefix) {
Map<String, Stage> result;
if (stages.containsKey(prefix)) {
result = new HashMap<String, Stage>();
result.put(prefix, stages.get(prefix));
} else {
result = stages.subMap(prefix + '.', prefix + ('.' + 1));
}
return result;
}
/**
* Add a merge stage to this job that merges the output of stageName called
* pointName.
*
* @param stageName The stage that contains the output that needs merging.
* @param pointName The output point that needs merging in the stage
* stageName.
* @param factor What the reduction factor is for each merger.
*/
public Job addMergeStage(String stageName, String pointName, int factor) {
// find the stage and the point, initialize class/order information
Stage inputStage = this.stages.get(stageName);
StageConnectionPoint inputPoint = inputStage.getConnection(pointName);
String className = inputPoint.getClassName();
String[] typeOrder = inputPoint.getOrder();
String mergedStageName = stageName + "-" + pointName + "-mergeStage";
String mergedPointName = pointName + "-merged";
// if this merge stage has already been added, don't add it again
if (this.stages.containsKey(mergedStageName)) {
return this; // create the stage itself
}
Stage s = new Stage(mergedStageName);
s.add(new StageConnectionPoint(ConnectionPointType.Input,
pointName,
className,
typeOrder));
s.add(new StageConnectionPoint(ConnectionPointType.Output,
pointName + "-merged",
className,
typeOrder));
s.add(new InputStepInformation(pointName));
s.add(new OutputStepInformation(mergedPointName));
this.add(s);
String[] hash = null;
int hashCount = factor;
// run through the connections list, find all inputs for the previous data
for (Connection connection : this.connections) {
if (connection.input.getStageName().equals(stageName)
&& connection.input.getPointName().equals(pointName)) {
if (hash != null && connection.hash != null
&& !Arrays.equals(hash, connection.hash)) {
continue;
}
if (connection.hash != null) {
hash = connection.hash;
connection.hash = null;
}
connection.input.setStageName(mergedStageName);
connection.input.setPointName(mergedPointName);
}
}
// now, add a connection between the producing stage and the merge stage
this.connect(new StagePoint(stageName, pointName),
new StagePoint(mergedStageName, pointName),
ConnectionAssignmentType.Each,
hash,
hashCount);
return this;
}
public static class StagePoint implements Comparable<StagePoint> {
String stageName;
String pointName;
private StageConnectionPoint point;
public StagePoint(String stageName, String pointName) {
this(stageName, pointName, null);
}
public StagePoint(String stageName, String pointName, StageConnectionPoint point) {
this.stageName = stageName;
this.pointName = pointName;
this.point = point;
}
public boolean equals(StagePoint other) {
return stageName.equals(other.stageName) && pointName.equals(other.pointName);
}
public int compareTo(StagePoint other) {
int result = stageName.compareTo(other.stageName);
if (result != 0) {
return result;
}
return pointName.compareTo(other.pointName);
}
@Override
public int hashCode() {
return stageName.hashCode() + pointName.hashCode() * 3;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final StagePoint other = (StagePoint) obj;
if (this.stageName != other.stageName && (this.stageName == null || !this.stageName.equals(other.stageName))) {
return false;
}
if (this.pointName != other.pointName && (this.pointName == null || !this.pointName.equals(other.pointName))) {
return false;
}
return true;
}
public StageConnectionPoint getPoint() {
return point;
}
public void setPoint(StageConnectionPoint point) {
this.point = point;
}
@Override
public String toString() {
return String.format("%s:%s", stageName, pointName);
}
}
HashSet<StagePoint> extractStagePoints(Collection<Stage> allStages, ConnectionPointType type) {
HashSet<StagePoint> result = new HashSet<StagePoint>();
for (Stage s : allStages) {
for (Map.Entry<String, StageConnectionPoint> e : s.connections.entrySet()) {
String pointName = e.getKey();
String stageName = s.name;
if (e.getValue().type == type) {
result.add(new StagePoint(stageName, pointName, e.getValue()));
}
}
}
return result;
}
/**
* Connects outputs from stage sourceName to inputs from stage
* destinationName.
*
* Connect can make connections between any stage with the name sourceName, or
* that starts with sourceName (same goes for destinationName), which makes
* this particularly useful for making connections between sub-jobs.
*/
public Job connect(String sourceName, String destinationName, ConnectionAssignmentType assignment) {
return connect(sourceName, destinationName, assignment, null, -1);
}
public Job connect(String sourceName, String destinationName, ConnectionAssignmentType assignment, int hashCount) {
return connect(sourceName, destinationName, assignment, null, hashCount);
}
public Job connect(String sourceName, String destinationName, ConnectionAssignmentType assignment, String[] hashType) {
return connect(sourceName, destinationName, assignment, hashType, -1);
}
public Job connect(String sourceName, String destinationName, ConnectionAssignmentType assignment, String[] hashType, int hashCount) {
// scan the stages, looking for sources
Map<String, Stage> sources = findStagesWithPrefix(sourceName);
Map<String, Stage> destinations = findStagesWithPrefix(destinationName);
// find all inputs and outputs in these stages
HashSet<StagePoint> outputs = extractStagePoints(sources.values(),
ConnectionPointType.Output);
HashSet<StagePoint> inputs = extractStagePoints(destinations.values(),
ConnectionPointType.Input);
// remove any inputs that are already referenced in job connections
for (Connection c : connections) {
for (ConnectionEndPoint p : c.outputs) {
StagePoint point = new StagePoint(p.getStageName(), p.getPointName());
inputs.remove(point);
}
}
// now we have a list of all dangling inputs. try to match them with outputs
HashMap<String, ArrayList<StagePoint>> outputMap = new HashMap<String, ArrayList<StagePoint>>();
for (StagePoint point : outputs) {
if (!outputMap.containsKey(point.pointName)) {
outputMap.put(point.pointName, new ArrayList<StagePoint>());
}
outputMap.get(point.pointName).add(point);
}
for (StagePoint destinationPoint : inputs) {
if (outputMap.containsKey(destinationPoint.pointName)) {
assert outputMap.get(destinationPoint.pointName).size() == 1;
StagePoint sourcePoint = outputMap.get(destinationPoint.pointName).get(0);
// this is only really applicable when assignment is 'Each'
// - it is ignored in other cases
String[] connectionHashType = null;
if (hashType != null) {
connectionHashType = hashType;
} else {
connectionHashType = sourcePoint.point.getOrder();
}
if (assignment == ConnectionAssignmentType.Combined) {
connectionHashType = null;
}
connect(sourcePoint, destinationPoint, assignment, connectionHashType, hashCount);
}
}
return this;
}
public Job connect(StagePoint source, StagePoint destination, ConnectionAssignmentType assignment, String[] hashType, int hashCount) {
// first, try to find a usable connection
Connection connection = null;
if (source.getPoint() == null) {
Stage sourceStage = stages.get(source.stageName);
StageConnectionPoint sourcePoint = sourceStage.getConnection(source.pointName);
source.setPoint(sourcePoint);
}
for (Connection c : connections) {
ConnectionEndPoint connectionInput = c.input;
if (connectionInput.getPointName().equals(source.pointName)
&& connectionInput.getStageName().equals(source.stageName)) {
connection = c;
break;
}
}
// couldn't find a connection that has this input, so we'll make one
if (connection == null) {
connection = new Connection(source.getPoint(), hashType, hashCount);
ConnectionEndPoint input = new ConnectionEndPoint(
source.stageName,
source.pointName,
ConnectionPointType.Input);
connection.input = input;
connections.add(connection);
}
ConnectionEndPoint output = new ConnectionEndPoint(
destination.stageName,
destination.pointName,
assignment,
ConnectionPointType.Output);
connection.outputs.add(output);
return this;
}
/**
* Returns this job as a graph in the DOT language. This DOT text can be used
* with GraphViz (http://www.graphviz.org) to display a picture of the job.
*/
public String toDotString() {
StringBuilder builder = new StringBuilder();
builder.append("digraph {\n");
for (Connection connection : connections) {
for (ConnectionEndPoint output : connection.outputs) {
String edge = String.format(" %s -> %s [label=\"%s\"];\n",
connection.input.getStageName(), output.getStageName(), connection.getName());
builder.append(edge);
}
}
for (Stage stage : stages.values()) {
builder.append(String.format(" %s;\n", stage.name));
}
builder.append("}\n");
return builder.toString();
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("<job>\n");
// Properties block
for (Map.Entry<String, String> entry : properties.entrySet()) {
builder.append(String.format(" <property name=\"%s\" value=\"%s\" />\n",
entry.getKey(), entry.getValue()));
}
builder.append("\n");
// Connections block
builder.append(" <connections>\n");
for (Connection connection : connections) {
if (connection.getHash() != null) {
String connectionHeader = String.format(
" <connection id=\"%s\" \n"
+ " class=\"%s\" \n"
+ " order=\"%s\" \n"
+ " hash=\"%s\" \n"
+ " hashCount=\"%d\"> \n",
connection.getName(),
connection.getClassName(),
orderString(connection.getOrder()),
orderString(connection.getHash()),
connection.getHashCount());
builder.append(connectionHeader);
} else {
String connectionHeader = String.format(
" <connection id=\"%s\" \n"
+ " class=\"%s\" \n"
+ " order=\"%s\"> \n",
connection.getName(),
connection.getClassName(),
orderString(connection.getOrder()));
builder.append(connectionHeader);
}
String inputEndPointString = String.format(
" <input stage=\"%s\" \n"
+ " endpoint=\"%s\" /> \n",
connection.input.getStageName(),
connection.input.getPointName());
builder.append(inputEndPointString);
for (ConnectionEndPoint point : connection.outputs) {
String endPointString = String.format(
" <output stage=\"%s\" \n"
+ " endpoint=\"%s\" \n"
+ " assignment=\"%s\" /> \n",
point.getStageName(),
point.getPointName(),
point.getAssignment());
builder.append(endPointString);
}
builder.append(" </connection>\n");
}
builder.append(" </connections>\n");
builder.append("\n");
// Stages block
builder.append(" <stages>\n");
for (Stage s : stages.values()) {
String stageHeader =
String.format(" <stage id=\"%s\">\n", s.name);
builder.append(stageHeader);
builder.append(" <connections>\n");
for (StageConnectionPoint point : s.connections.values()) {
String pointString = String.format(
" <%s id=\"%s\" as=\"%s\" class=\"%s\" order=\"%s\" />\n",
point.type, point.externalName, point.internalName, point.getClassName(),
orderString(point.getOrder()));
builder.append(pointString);
}
builder.append(" </connections>\n");
printSteps(builder, s.steps, "steps");
builder.append(" </stage>\n");
}
builder.append(" </stages>\n");
builder.append("</job>\n");
return builder.toString();
}
private void printSteps(final StringBuilder builder, final List<StepInformation> steps, final String tag) {
builder.append(String.format(" <%s>\n", tag));
for (StepInformation step : steps) {
if (step instanceof InputStepInformation) {
InputStepInformation input = (InputStepInformation) step;
String line = String.format(" <input id=\"%s\" />\n", input.getId());
builder.append(line);
} else if (step instanceof MultiInputStepInformation) {
MultiInputStepInformation input = (MultiInputStepInformation) step;
String line = String.format(" <multiinput ids=\"%s\" />\n", Utility.join(input.getIds(), ","));
builder.append(line);
} else if (step instanceof OutputStepInformation) {
OutputStepInformation output = (OutputStepInformation) step;
String line = String.format(" <output id=\"%s\" />\n", output.getId());
builder.append(line);
} else if (step instanceof MultiStepInformation) {
MultiStepInformation multi = (MultiStepInformation) step;
builder.append(" <multi>\n");
for (String name : multi) {
printSteps(builder, multi.getGroup(name), "group");
}
builder.append(" </multi>\n");
} else if (step.getParameters() == null || step.getParameters().isEmpty()) {
String stepHeader = String.format(" <step class=\"%s\" />\n", step.getClassName());
builder.append(stepHeader);
} else {
String stepHeader = String.format(" <step class=\"%s\">\n", step.getClassName());
builder.append(stepHeader);
String parametersString = step.getParameters().toString();
// strip out the beginning and end parts
//int start = parametersString.indexOf("<parameters>") + "<parameters>".length();
//int end = parametersString.lastIndexOf("</parameters>");
//parametersString = parametersString.substring(start, end);
builder.append(parametersString);
builder.append(" </step>\n");
}
}
builder.append(String.format(" </%s>\n", tag));
}
}
| |
/**
* JBoss, Home of Professional Open Source
* Copyright Red Hat, Inc., and 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.aerogear.android.pipe.rest;
import java.net.URL;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Executor;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import org.jboss.aerogear.android.core.Callback;
import org.jboss.aerogear.android.core.ReadFilter;
import org.jboss.aerogear.android.pipe.rest.gson.GsonRequestBuilder;
import org.jboss.aerogear.android.pipe.rest.gson.GsonResponseParser;
import org.jboss.aerogear.android.pipe.http.HeaderAndBody;
import org.jboss.aerogear.android.pipe.Pipe;
import org.jboss.aerogear.android.pipe.PipeHandler;
import org.jboss.aerogear.android.pipe.RequestBuilder;
import org.jboss.aerogear.android.pipe.ResponseParser;
import android.util.Log;
import java.net.URI;
import java.net.URISyntaxException;
import org.jboss.aerogear.android.pipe.paging.WebLink;
import org.jboss.aerogear.android.pipe.paging.WrappingPagedList;
import org.jboss.aerogear.android.core.reflection.Property;
import org.jboss.aerogear.android.core.reflection.Scan;
import org.jboss.aerogear.android.pipe.util.ParseException;
import org.jboss.aerogear.android.pipe.util.WebLinkParser;
import org.jboss.aerogear.android.pipe.paging.PageConfig;
import org.json.JSONObject;
/**
* Rest implementation of {@link Pipe}.
*/
public final class RestAdapter<T> implements Pipe<T> {
private static final String TAG = RestAdapter.class.getSimpleName();
private static final int CORE_POOL_SIZE = 5;
private static final int MAX_POOL_SIZE = 64;
private static final int KEEP_ALIVE = 1;
private static final BlockingQueue<Runnable> WORK_QUEUE = new LinkedBlockingQueue<Runnable>(10);
public static final Executor THREAD_POOL_EXECUTOR = new ThreadPoolExecutor(CORE_POOL_SIZE, MAX_POOL_SIZE, KEEP_ALIVE,
TimeUnit.SECONDS, WORK_QUEUE);
/**
* A class of the Generic type this pipe wraps. This is used by GSON for
* deserializing.
*/
private final Class<T> klass;
private final URL url;
private final PipeHandler<T> restRunner;
private final RequestBuilder<T> requestBuilder;
private final ResponseParser<T> responseParser;
private final PageConfig pageConfig;
/**
* This will configure the Adapter as with sane RESTful defaults.
*
* @param klass The type that this adapter will consume and produce
* @param absoluteURL the RESTful URL endpoint.
*/
public RestAdapter(Class<T> klass, URL absoluteURL) {
this.restRunner = new RestRunner<T>(klass, absoluteURL);
this.klass = klass;
this.url = absoluteURL;
this.pageConfig = null;
this.requestBuilder = new GsonRequestBuilder<T>();
this.responseParser = new GsonResponseParser<T>();
}
/**
* This will build an adapter based on a configuration.
*
* @param klass The type that this adapter will consume and produce
* @param absoluteURL the RESTful URL endpoint.
* @param config A PipeConfig to use. NOTE: the URL's provided in the config
* are ignored in deference to the absoluteURL parameter.
*/
@SuppressWarnings("unchecked")
public RestAdapter(Class<T> klass, URL absoluteURL, RestfulPipeConfiguration config) {
this.klass = klass;
this.url = absoluteURL;
this.pageConfig = config.getPageConfig();
this.requestBuilder = config.getRequestBuilder();
this.responseParser = config.getResponseParser();
if (config.getPipeHandler() != null) {
this.restRunner = (PipeHandler<T>) config.getPipeHandler();
} else {
this.restRunner = new RestRunner<T>(klass, absoluteURL, config);
}
}
/**
* This is package private because the correct method of calling it should be
* from the FactoryClass, PipeModule.
*
* @param configuration the configuration to use.
*/
RestAdapter(Class<T> klass, RestfulPipeConfiguration configuration) {
this.klass = klass;
this.url = configuration.getUrl();
this.pageConfig = configuration.getPageConfig();
this.requestBuilder = configuration.getRequestBuilder();
this.responseParser = configuration.getResponseParser();
this.restRunner = new RestRunner<T>(klass, url, configuration);
}
/**
* {@inheritDoc}
*/
@Override
public URL getUrl() {
return url;
}
@Override
public void read(final String id, final Callback<T> callback) {
THREAD_POOL_EXECUTOR.execute(new Runnable() {
T result = null;
Exception exception = null;
@Override
public void run() {
try {
HeaderAndBody response = restRunner.onRawRead(RestAdapter.this, id);
List<T> resultList = getResponseParser().handleResponse(response, klass);
this.result = resultList.get(0);
} catch (Exception e) {
Log.e(TAG, e.getMessage(), e);
this.exception = e;
}
if (exception == null) {
callback.onSuccess(this.result);
} else {
callback.onFailure(exception);
}
}
});
}
@Override
public void read(ReadFilter filter, final Callback<List<T>> callback) {
if (filter == null) {
filter = new ReadFilter();
}
final ReadFilter innerFilter = filter;
THREAD_POOL_EXECUTOR.execute(new Runnable() {
List<T> result = null;
Exception exception = null;
@Override
public void run() {
try {
HeaderAndBody response = restRunner.onRawReadWithFilter(innerFilter, RestAdapter.this);
this.result = getResponseParser().handleResponse(response, klass);
if (pageConfig != null) {
result = computePagedList(result, response, innerFilter.getWhere(), RestAdapter.this);
}
} catch (Exception e) {
Log.e(TAG, e.getMessage(), e);
this.exception = e;
}
if (exception == null) {
callback.onSuccess(this.result);
} else {
callback.onFailure(exception);
}
}
});
}
/**
* {@inheritDoc}
*/
@Override
public void read(final Callback<List<T>> callback) {
THREAD_POOL_EXECUTOR.execute(new Runnable() {
List<T> result = null;
Exception exception = null;
@Override
public void run() {
try {
this.result = getResponseParser().handleResponse(restRunner.onRawRead(RestAdapter.this), klass);
} catch (Exception e) {
Log.e(TAG, e.getMessage(), e);
this.exception = e;
}
if (exception == null) {
callback.onSuccess(this.result);
} else {
callback.onFailure(exception);
}
}
});
}
@Override
public void save(final T data, final Callback<T> callback) {
THREAD_POOL_EXECUTOR.execute(new Runnable() {
@Override
public void run() {
T result = null;
Exception exception = null;
try {
String id;
String recordIdFieldName = Scan.recordIdFieldNameIn(data.getClass());
Object idObject = new Property(data.getClass(), recordIdFieldName).getValue(data);
id = idObject == null ? null : idObject.toString();
byte[] body = requestBuilder.getBody(data);
HeaderAndBody response = restRunner.onRawSave(id, body);
result = getResponseParser().handleResponse(response, klass).get(0);
} catch (Exception e) {
exception = e;
}
if (exception == null) {
callback.onSuccess(result);
} else {
callback.onFailure(exception);
}
}
});
}
/**
* {@inheritDoc}
*/
@Override
public void remove(final String id, final Callback<Void> callback) {
THREAD_POOL_EXECUTOR.execute(new Runnable() {
Exception exception = null;
@Override
public void run() {
try {
RestAdapter.this.restRunner.onRemove(id);
} catch (Exception e) {
exception = e;
}
if (exception == null) {
callback.onSuccess(null);
} else {
callback.onFailure(exception);
}
}
});
}
@Override
public PipeHandler<T> getHandler() {
return restRunner;
}
@Override
public Class<T> getKlass() {
return klass;
}
@Override
public RequestBuilder<T> getRequestBuilder() {
return this.requestBuilder;
}
@Override
public ResponseParser<T> getResponseParser() {
return this.responseParser;
}
/**
* This method checks for paging information and returns the appropriate
* data
*
* @param result
* @param httpResponse
* @param where
* @return a {@link WrappingPagedList} if there is paging, result if not.
*/
private List<T> computePagedList(List<T> result, HeaderAndBody httpResponse, JSONObject where, Pipe<T> requestingPipe) {
ReadFilter previousRead = null;
ReadFilter nextRead = null;
if (PageConfig.MetadataLocations.WEB_LINKING.equals(pageConfig.getMetadataLocation())) {
String webLinksRaw = "";
final String relHeader = "rel";
final String nextIdentifier = pageConfig.getNextIdentifier();
final String prevIdentifier = pageConfig.getPreviousIdentifier();
try {
webLinksRaw = getWebLinkHeader(httpResponse);
if (webLinksRaw == null) { // no paging, return result
return result;
}
List<WebLink> webLinksParsed = WebLinkParser.parse(webLinksRaw);
for (WebLink link : webLinksParsed) {
if (nextIdentifier.equals(link.getParameters().get(relHeader))) {
nextRead = new ReadFilter();
nextRead.setLinkUri(new URI(link.getUri()));
} else if (prevIdentifier.equals(link.getParameters().get(relHeader))) {
previousRead = new ReadFilter();
previousRead.setLinkUri(new URI(link.getUri()));
}
}
} catch (URISyntaxException ex) {
Log.e(TAG, webLinksRaw + " did not contain a valid context URI", ex);
throw new RuntimeException(ex);
} catch (ParseException ex) {
Log.e(TAG, webLinksRaw + " could not be parsed as a web link header", ex);
throw new RuntimeException(ex);
}
} else if (pageConfig.getMetadataLocation().equals(PageConfig.MetadataLocations.HEADERS)) {
nextRead = pageConfig.getPageParameterExtractor().getNextFilter(httpResponse, RestAdapter.this.pageConfig);
previousRead = pageConfig.getPageParameterExtractor().getPreviousFilter(httpResponse, RestAdapter.this.pageConfig);
} else if (pageConfig.getMetadataLocation().equals(PageConfig.MetadataLocations.BODY)) {
nextRead = pageConfig.getPageParameterExtractor().getNextFilter(httpResponse, RestAdapter.this.pageConfig);
previousRead = pageConfig.getPageParameterExtractor().getPreviousFilter(httpResponse, RestAdapter.this.pageConfig);
} else {
throw new IllegalStateException("Not supported");
}
if (nextRead != null) {
nextRead.setWhere(where);
}
if (previousRead != null) {
previousRead.setWhere(where);
}
return new WrappingPagedList<T>(requestingPipe, result, nextRead, previousRead);
}
private String getWebLinkHeader(HeaderAndBody httpResponse) {
String linkHeaderName = "Link";
Object header = httpResponse.getHeader(linkHeaderName);
if (header != null) {
return header.toString();
}
return null;
}
}
| |
package com.fsck.zywxMailk9.activity.setup;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Vibrator;
import android.preference.CheckBoxPreference;
import android.preference.EditTextPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceScreen;
import android.preference.RingtonePreference;
import android.util.Log;
import com.fsck.zywxMailk9.Account;
import com.fsck.zywxMailk9.K9;
import com.fsck.zywxMailk9.NotificationSetting;
import com.fsck.zywxMailk9.Preferences;
import com.fsck.zywxMailk9.R;
import com.fsck.zywxMailk9.Account.FolderMode;
import com.fsck.zywxMailk9.Account.QuoteStyle;
import com.fsck.zywxMailk9.activity.ChooseFolder;
import com.fsck.zywxMailk9.activity.ChooseIdentity;
import com.fsck.zywxMailk9.activity.ColorPickerDialog;
import com.fsck.zywxMailk9.activity.K9PreferenceActivity;
import com.fsck.zywxMailk9.activity.ManageIdentities;
import com.fsck.zywxMailk9.crypto.Apg;
import com.fsck.zywxMailk9.mail.Folder;
import com.fsck.zywxMailk9.mail.Store;
import com.fsck.zywxMailk9.mail.store.StorageManager;
import com.fsck.zywxMailk9.mail.store.LocalStore.LocalFolder;
import com.fsck.zywxMailk9.service.MailService;
public class AccountSettings extends K9PreferenceActivity {
private static final String EXTRA_ACCOUNT = "account";
private static final int SELECT_AUTO_EXPAND_FOLDER = 1;
private static final int ACTIVITY_MANAGE_IDENTITIES = 2;
private static final String PREFERENCE_SCREEN_COMPOSING = "composing";
private static final String PREFERENCE_SCREEN_INCOMING = "incoming_prefs";
private static final String PREFERENCE_SCREEN_PUSH_ADVANCED = "push_advanced";
private static final String PREFERENCE_DESCRIPTION = "account_description";
private static final String PREFERENCE_MARK_MESSAGE_AS_READ_ON_VIEW = "mark_message_as_read_on_view";
private static final String PREFERENCE_COMPOSITION = "composition";
private static final String PREFERENCE_MANAGE_IDENTITIES = "manage_identities";
private static final String PREFERENCE_FREQUENCY = "account_check_frequency";
private static final String PREFERENCE_DISPLAY_COUNT = "account_display_count";
private static final String PREFERENCE_DEFAULT = "account_default";
private static final String PREFERENCE_SHOW_PICTURES = "show_pictures_enum";
private static final String PREFERENCE_ENABLE_MOVE_BUTTONS = "enable_move_buttons";
private static final String PREFERENCE_NOTIFY = "account_notify";
private static final String PREFERENCE_NOTIFY_SELF = "account_notify_self";
private static final String PREFERENCE_NOTIFY_SYNC = "account_notify_sync";
private static final String PREFERENCE_VIBRATE = "account_vibrate";
private static final String PREFERENCE_VIBRATE_PATTERN = "account_vibrate_pattern";
private static final String PREFERENCE_VIBRATE_TIMES = "account_vibrate_times";
private static final String PREFERENCE_RINGTONE = "account_ringtone";
private static final String PREFERENCE_NOTIFICATION_LED = "account_led";
private static final String PREFERENCE_INCOMING = "incoming";
private static final String PREFERENCE_OUTGOING = "outgoing";
private static final String PREFERENCE_DISPLAY_MODE = "folder_display_mode";
private static final String PREFERENCE_SYNC_MODE = "folder_sync_mode";
private static final String PREFERENCE_PUSH_MODE = "folder_push_mode";
private static final String PREFERENCE_PUSH_POLL_ON_CONNECT = "push_poll_on_connect";
private static final String PREFERENCE_MAX_PUSH_FOLDERS = "max_push_folders";
private static final String PREFERENCE_IDLE_REFRESH_PERIOD = "idle_refresh_period";
private static final String PREFERENCE_TARGET_MODE = "folder_target_mode";
private static final String PREFERENCE_DELETE_POLICY = "delete_policy";
private static final String PREFERENCE_EXPUNGE_POLICY = "expunge_policy";
private static final String PREFERENCE_AUTO_EXPAND_FOLDER = "account_setup_auto_expand_folder";
private static final String PREFERENCE_SEARCHABLE_FOLDERS = "searchable_folders";
private static final String PREFERENCE_CHIP_COLOR = "chip_color";
private static final String PREFERENCE_LED_COLOR = "led_color";
private static final String PREFERENCE_NOTIFICATION_OPENS_UNREAD = "notification_opens_unread";
private static final String PREFERENCE_NOTIFICATION_UNREAD_COUNT = "notification_unread_count";
private static final String PREFERENCE_MESSAGE_AGE = "account_message_age";
private static final String PREFERENCE_MESSAGE_SIZE = "account_autodownload_size";
private static final String PREFERENCE_SAVE_ALL_HEADERS = "account_save_all_headers";
private static final String PREFERENCE_MESSAGE_FORMAT = "message_format";
private static final String PREFERENCE_MESSAGE_READ_RECEIPT = "message_read_receipt";
private static final String PREFERENCE_QUOTE_PREFIX = "account_quote_prefix";
private static final String PREFERENCE_QUOTE_STYLE = "quote_style";
private static final String PREFERENCE_DEFAULT_QUOTED_TEXT_SHOWN = "default_quoted_text_shown";
private static final String PREFERENCE_REPLY_AFTER_QUOTE = "reply_after_quote";
private static final String PREFERENCE_STRIP_SIGNATURE = "strip_signature";
private static final String PREFERENCE_SYNC_REMOTE_DELETIONS = "account_sync_remote_deletetions";
private static final String PREFERENCE_CRYPTO_APP = "crypto_app";
private static final String PREFERENCE_CRYPTO_AUTO_SIGNATURE = "crypto_auto_signature";
private static final String PREFERENCE_CRYPTO_AUTO_ENCRYPT = "crypto_auto_encrypt";
private static final String PREFERENCE_LOCAL_STORAGE_PROVIDER = "local_storage_provider";
private static final String PREFERENCE_CATEGORY_FOLDERS = "folders";
private static final String PREFERENCE_ARCHIVE_FOLDER = "archive_folder";
private static final String PREFERENCE_DRAFTS_FOLDER = "drafts_folder";
private static final String PREFERENCE_SENT_FOLDER = "sent_folder";
private static final String PREFERENCE_SPAM_FOLDER = "spam_folder";
private static final String PREFERENCE_TRASH_FOLDER = "trash_folder";
private Account mAccount;
private boolean mIsMoveCapable = false;
private boolean mIsPushCapable = false;
private boolean mIsExpungeCapable = false;
private PreferenceScreen mComposingScreen;
private EditTextPreference mAccountDescription;
private CheckBoxPreference mMarkMessageAsReadOnView;
private ListPreference mCheckFrequency;
private ListPreference mDisplayCount;
private ListPreference mMessageAge;
private ListPreference mMessageSize;
private CheckBoxPreference mAccountDefault;
private CheckBoxPreference mAccountNotify;
private CheckBoxPreference mAccountNotifySelf;
private ListPreference mAccountShowPictures;
private CheckBoxPreference mAccountEnableMoveButtons;
private CheckBoxPreference mAccountNotifySync;
private CheckBoxPreference mAccountVibrate;
private CheckBoxPreference mAccountLed;
private ListPreference mAccountVibratePattern;
private ListPreference mAccountVibrateTimes;
private RingtonePreference mAccountRingtone;
private ListPreference mDisplayMode;
private ListPreference mSyncMode;
private ListPreference mPushMode;
private ListPreference mTargetMode;
private ListPreference mDeletePolicy;
private ListPreference mExpungePolicy;
private ListPreference mSearchableFolders;
private ListPreference mAutoExpandFolder;
private Preference mChipColor;
private Preference mLedColor;
private boolean mIncomingChanged = false;
private CheckBoxPreference mNotificationOpensUnread;
private CheckBoxPreference mNotificationUnreadCount;
private ListPreference mMessageFormat;
private CheckBoxPreference mMessageReadReceipt;
private ListPreference mQuoteStyle;
private EditTextPreference mAccountQuotePrefix;
private CheckBoxPreference mAccountDefaultQuotedTextShown;
private CheckBoxPreference mReplyAfterQuote;
private CheckBoxPreference mStripSignature;
private CheckBoxPreference mSyncRemoteDeletions;
private CheckBoxPreference mSaveAllHeaders;
private CheckBoxPreference mPushPollOnConnect;
private ListPreference mIdleRefreshPeriod;
private ListPreference mMaxPushFolders;
private ListPreference mCryptoApp;
private CheckBoxPreference mCryptoAutoSignature;
private CheckBoxPreference mCryptoAutoEncrypt;
private ListPreference mLocalStorageProvider;
private ListPreference mArchiveFolder;
private ListPreference mDraftsFolder;
private ListPreference mSentFolder;
private ListPreference mSpamFolder;
private ListPreference mTrashFolder;
public static void actionSettings(Context context, Account account) {
Intent i = new Intent(context, AccountSettings.class);
i.putExtra(EXTRA_ACCOUNT, account.getUuid());
context.startActivity(i);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String accountUuid = getIntent().getStringExtra(EXTRA_ACCOUNT);
mAccount = Preferences.getPreferences(this).getAccount(accountUuid);
try {
final Store store = mAccount.getRemoteStore();
mIsMoveCapable = store.isMoveCapable();
mIsPushCapable = store.isPushCapable();
mIsExpungeCapable = store.isExpungeCapable();
} catch (Exception e) {
Log.e(K9.LOG_TAG, "Could not get remote store", e);
}
addPreferencesFromResource(R.xml.account_settings_preferences);
mAccountDescription = (EditTextPreference) findPreference(PREFERENCE_DESCRIPTION);
mAccountDescription.setSummary(mAccount.getDescription());
mAccountDescription.setText(mAccount.getDescription());
mAccountDescription.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
public boolean onPreferenceChange(Preference preference, Object newValue) {
final String summary = newValue.toString();
mAccountDescription.setSummary(summary);
mAccountDescription.setText(summary);
return false;
}
});
// mMarkMessageAsReadOnView = (CheckBoxPreference) findPreference(PREFERENCE_MARK_MESSAGE_AS_READ_ON_VIEW);
// mMarkMessageAsReadOnView.setChecked(mAccount.isMarkMessageAsReadOnView());
//
// mMessageFormat = (ListPreference) findPreference(PREFERENCE_MESSAGE_FORMAT);
// mMessageFormat.setValue(mAccount.getMessageFormat().name());
// mMessageFormat.setSummary(mMessageFormat.getEntry());
// mMessageFormat.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
// public boolean onPreferenceChange(Preference preference, Object newValue) {
// final String summary = newValue.toString();
// int index = mMessageFormat.findIndexOfValue(summary);
// mMessageFormat.setSummary(mMessageFormat.getEntries()[index]);
// mMessageFormat.setValue(summary);
// return false;
// }
// });
//
// mMessageReadReceipt = (CheckBoxPreference) findPreference(PREFERENCE_MESSAGE_READ_RECEIPT);
// mMessageReadReceipt.setChecked(mAccount.isMessageReadReceiptAlways());
//
// mAccountQuotePrefix = (EditTextPreference) findPreference(PREFERENCE_QUOTE_PREFIX);
// mAccountQuotePrefix.setSummary(mAccount.getQuotePrefix());
// mAccountQuotePrefix.setText(mAccount.getQuotePrefix());
// mAccountQuotePrefix.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
// @Override
// public boolean onPreferenceChange(Preference preference, Object newValue) {
// final String value = newValue.toString();
// mAccountQuotePrefix.setSummary(value);
// mAccountQuotePrefix.setText(value);
// return false;
// }
// });
//
// mAccountDefaultQuotedTextShown = (CheckBoxPreference) findPreference(PREFERENCE_DEFAULT_QUOTED_TEXT_SHOWN);
// mAccountDefaultQuotedTextShown.setChecked(mAccount.isDefaultQuotedTextShown());
//
// mReplyAfterQuote = (CheckBoxPreference) findPreference(PREFERENCE_REPLY_AFTER_QUOTE);
// mReplyAfterQuote.setChecked(mAccount.isReplyAfterQuote());
//
// mStripSignature = (CheckBoxPreference) findPreference(PREFERENCE_STRIP_SIGNATURE);
// mStripSignature.setChecked(mAccount.isStripSignature());
//
// mComposingScreen = (PreferenceScreen) findPreference(PREFERENCE_SCREEN_COMPOSING);
//
// Preference.OnPreferenceChangeListener quoteStyleListener = new Preference.OnPreferenceChangeListener() {
// @Override
// public boolean onPreferenceChange(Preference preference, Object newValue) {
// final QuoteStyle style = QuoteStyle.valueOf(newValue.toString());
// int index = mQuoteStyle.findIndexOfValue(newValue.toString());
// mQuoteStyle.setSummary(mQuoteStyle.getEntries()[index]);
// if (style == QuoteStyle.PREFIX) {
// mComposingScreen.addPreference(mAccountQuotePrefix);
// mComposingScreen.addPreference(mReplyAfterQuote);
// } else if (style == QuoteStyle.HEADER) {
// mComposingScreen.removePreference(mAccountQuotePrefix);
// mComposingScreen.removePreference(mReplyAfterQuote);
// }
// return true;
// }
// };
// mQuoteStyle = (ListPreference) findPreference(PREFERENCE_QUOTE_STYLE);
// mQuoteStyle.setValue(mAccount.getQuoteStyle().name());
// mQuoteStyle.setSummary(mQuoteStyle.getEntry());
// mQuoteStyle.setOnPreferenceChangeListener(quoteStyleListener);
// // Call the onPreferenceChange() handler on startup to update the Preference dialogue based
// // upon the existing quote style setting.
// quoteStyleListener.onPreferenceChange(mQuoteStyle, mAccount.getQuoteStyle().name());
//
// mCheckFrequency = (ListPreference) findPreference(PREFERENCE_FREQUENCY);
// mCheckFrequency.setValue(String.valueOf(mAccount.getAutomaticCheckIntervalMinutes()));
// mCheckFrequency.setSummary(mCheckFrequency.getEntry());
// mCheckFrequency.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
// public boolean onPreferenceChange(Preference preference, Object newValue) {
// final String summary = newValue.toString();
// int index = mCheckFrequency.findIndexOfValue(summary);
// mCheckFrequency.setSummary(mCheckFrequency.getEntries()[index]);
// mCheckFrequency.setValue(summary);
// return false;
// }
// });
//
// mDisplayMode = (ListPreference) findPreference(PREFERENCE_DISPLAY_MODE);
// mDisplayMode.setValue(mAccount.getFolderDisplayMode().name());
// mDisplayMode.setSummary(mDisplayMode.getEntry());
// mDisplayMode.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
// public boolean onPreferenceChange(Preference preference, Object newValue) {
// final String summary = newValue.toString();
// int index = mDisplayMode.findIndexOfValue(summary);
// mDisplayMode.setSummary(mDisplayMode.getEntries()[index]);
// mDisplayMode.setValue(summary);
// return false;
// }
// });
//
// mSyncMode = (ListPreference) findPreference(PREFERENCE_SYNC_MODE);
// mSyncMode.setValue(mAccount.getFolderSyncMode().name());
// mSyncMode.setSummary(mSyncMode.getEntry());
// mSyncMode.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
// public boolean onPreferenceChange(Preference preference, Object newValue) {
// final String summary = newValue.toString();
// int index = mSyncMode.findIndexOfValue(summary);
// mSyncMode.setSummary(mSyncMode.getEntries()[index]);
// mSyncMode.setValue(summary);
// return false;
// }
// });
//
//
// mTargetMode = (ListPreference) findPreference(PREFERENCE_TARGET_MODE);
// mTargetMode.setValue(mAccount.getFolderTargetMode().name());
// mTargetMode.setSummary(mTargetMode.getEntry());
// mTargetMode.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
// public boolean onPreferenceChange(Preference preference, Object newValue) {
// final String summary = newValue.toString();
// int index = mTargetMode.findIndexOfValue(summary);
// mTargetMode.setSummary(mTargetMode.getEntries()[index]);
// mTargetMode.setValue(summary);
// return false;
// }
// });
//
// mDeletePolicy = (ListPreference) findPreference(PREFERENCE_DELETE_POLICY);
// mDeletePolicy.setValue("" + mAccount.getDeletePolicy());
// mDeletePolicy.setSummary(mDeletePolicy.getEntry());
// mDeletePolicy.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
// public boolean onPreferenceChange(Preference preference, Object newValue) {
// final String summary = newValue.toString();
// int index = mDeletePolicy.findIndexOfValue(summary);
// mDeletePolicy.setSummary(mDeletePolicy.getEntries()[index]);
// mDeletePolicy.setValue(summary);
// return false;
// }
// });
//
// mExpungePolicy = (ListPreference) findPreference(PREFERENCE_EXPUNGE_POLICY);
// if (mIsExpungeCapable) {
// mExpungePolicy.setValue(mAccount.getExpungePolicy());
// mExpungePolicy.setSummary(mExpungePolicy.getEntry());
// mExpungePolicy.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
// public boolean onPreferenceChange(Preference preference, Object newValue) {
// final String summary = newValue.toString();
// int index = mExpungePolicy.findIndexOfValue(summary);
// mExpungePolicy.setSummary(mExpungePolicy.getEntries()[index]);
// mExpungePolicy.setValue(summary);
// return false;
// }
// });
// } else {
// ((PreferenceScreen) findPreference(PREFERENCE_SCREEN_INCOMING)).removePreference(mExpungePolicy);
// }
//
// mSyncRemoteDeletions = (CheckBoxPreference) findPreference(PREFERENCE_SYNC_REMOTE_DELETIONS);
// mSyncRemoteDeletions.setChecked(mAccount.syncRemoteDeletions());
//
// mSaveAllHeaders = (CheckBoxPreference) findPreference(PREFERENCE_SAVE_ALL_HEADERS);
// mSaveAllHeaders.setChecked(mAccount.saveAllHeaders());
//
// mSearchableFolders = (ListPreference) findPreference(PREFERENCE_SEARCHABLE_FOLDERS);
// mSearchableFolders.setValue(mAccount.getSearchableFolders().name());
// mSearchableFolders.setSummary(mSearchableFolders.getEntry());
// mSearchableFolders.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
// public boolean onPreferenceChange(Preference preference, Object newValue) {
// final String summary = newValue.toString();
// int index = mSearchableFolders.findIndexOfValue(summary);
// mSearchableFolders.setSummary(mSearchableFolders.getEntries()[index]);
// mSearchableFolders.setValue(summary);
// return false;
// }
// });
//
// mDisplayCount = (ListPreference) findPreference(PREFERENCE_DISPLAY_COUNT);
// mDisplayCount.setValue(String.valueOf(mAccount.getDisplayCount()));
// mDisplayCount.setSummary(mDisplayCount.getEntry());
// mDisplayCount.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
// public boolean onPreferenceChange(Preference preference, Object newValue) {
// final String summary = newValue.toString();
// int index = mDisplayCount.findIndexOfValue(summary);
// mDisplayCount.setSummary(mDisplayCount.getEntries()[index]);
// mDisplayCount.setValue(summary);
// return false;
// }
// });
// mMessageAge = (ListPreference) findPreference(PREFERENCE_MESSAGE_AGE);
// if(!mAccount.isSearchByDateCapable()) {
// ((PreferenceScreen) findPreference(PREFERENCE_SCREEN_INCOMING)).removePreference(mMessageAge);
// }else{
// mMessageAge.setValue(String.valueOf(mAccount.getMaximumPolledMessageAge()));
// mMessageAge.setSummary(mMessageAge.getEntry());
// mMessageAge.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
// public boolean onPreferenceChange(Preference preference, Object newValue) {
// final String summary = newValue.toString();
// int index = mMessageAge.findIndexOfValue(summary);
// mMessageAge.setSummary(mMessageAge.getEntries()[index]);
// mMessageAge.setValue(summary);
// return false;
// }
// });
//
// }
// mMessageSize = (ListPreference) findPreference(PREFERENCE_MESSAGE_SIZE);
// mMessageSize.setValue(String.valueOf(mAccount.getMaximumAutoDownloadMessageSize()));
// mMessageSize.setSummary(mMessageSize.getEntry());
// mMessageSize.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
// public boolean onPreferenceChange(Preference preference, Object newValue) {
// final String summary = newValue.toString();
// int index = mMessageSize.findIndexOfValue(summary);
// mMessageSize.setSummary(mMessageSize.getEntries()[index]);
// mMessageSize.setValue(summary);
// return false;
// }
// });
//
mAccountDefault = (CheckBoxPreference) findPreference(PREFERENCE_DEFAULT);
mAccountDefault.setChecked(
mAccount.equals(Preferences.getPreferences(this).getDefaultAccount()));
//
// mAccountEnableMoveButtons = (CheckBoxPreference) findPreference(PREFERENCE_ENABLE_MOVE_BUTTONS);
// mAccountEnableMoveButtons.setEnabled(mIsMoveCapable);
// mAccountEnableMoveButtons.setChecked(mAccount.getEnableMoveButtons());
//
// mAccountShowPictures = (ListPreference) findPreference(PREFERENCE_SHOW_PICTURES);
// mAccountShowPictures.setValue("" + mAccount.getShowPictures());
// mAccountShowPictures.setSummary(mAccountShowPictures.getEntry());
// mAccountShowPictures.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
// public boolean onPreferenceChange(Preference preference, Object newValue) {
// final String summary = newValue.toString();
// int index = mAccountShowPictures.findIndexOfValue(summary);
// mAccountShowPictures.setSummary(mAccountShowPictures.getEntries()[index]);
// mAccountShowPictures.setValue(summary);
// return false;
// }
// });
//
//
// mLocalStorageProvider = (ListPreference) findPreference(PREFERENCE_LOCAL_STORAGE_PROVIDER);
// {
// final Map<String, String> providers;
// providers = StorageManager.getInstance(K9.app).getAvailableProviders();
// int i = 0;
// final String[] providerLabels = new String[providers.size()];
// final String[] providerIds = new String[providers.size()];
// for (final Map.Entry<String, String> entry : providers.entrySet()) {
// providerIds[i] = entry.getKey();
// providerLabels[i] = entry.getValue();
// i++;
// }
// mLocalStorageProvider.setEntryValues(providerIds);
// mLocalStorageProvider.setEntries(providerLabels);
// mLocalStorageProvider.setValue(mAccount.getLocalStorageProviderId());
// mLocalStorageProvider.setSummary(providers.get(mAccount.getLocalStorageProviderId()));
//
// mLocalStorageProvider.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
// public boolean onPreferenceChange(Preference preference, Object newValue) {
// mLocalStorageProvider.setSummary(providers.get(newValue));
// return true;
// }
// });
// }
// // IMAP-specific preferences
//
// mPushPollOnConnect = (CheckBoxPreference) findPreference(PREFERENCE_PUSH_POLL_ON_CONNECT);
// mIdleRefreshPeriod = (ListPreference) findPreference(PREFERENCE_IDLE_REFRESH_PERIOD);
// mMaxPushFolders = (ListPreference) findPreference(PREFERENCE_MAX_PUSH_FOLDERS);
// if (mIsPushCapable) {
// mPushPollOnConnect.setChecked(mAccount.isPushPollOnConnect());
//
// mIdleRefreshPeriod.setValue(String.valueOf(mAccount.getIdleRefreshMinutes()));
// mIdleRefreshPeriod.setSummary(mIdleRefreshPeriod.getEntry());
// mIdleRefreshPeriod.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
// public boolean onPreferenceChange(Preference preference, Object newValue) {
// final String summary = newValue.toString();
// int index = mIdleRefreshPeriod.findIndexOfValue(summary);
// mIdleRefreshPeriod.setSummary(mIdleRefreshPeriod.getEntries()[index]);
// mIdleRefreshPeriod.setValue(summary);
// return false;
// }
// });
//
// mMaxPushFolders.setValue(String.valueOf(mAccount.getMaxPushFolders()));
// mMaxPushFolders.setSummary(mMaxPushFolders.getEntry());
// mMaxPushFolders.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
// public boolean onPreferenceChange(Preference preference, Object newValue) {
// final String summary = newValue.toString();
// int index = mMaxPushFolders.findIndexOfValue(summary);
// mMaxPushFolders.setSummary(mMaxPushFolders.getEntries()[index]);
// mMaxPushFolders.setValue(summary);
// return false;
// }
// });
// mPushMode = (ListPreference) findPreference(PREFERENCE_PUSH_MODE);
// mPushMode.setValue(mAccount.getFolderPushMode().name());
// mPushMode.setSummary(mPushMode.getEntry());
// mPushMode.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
// public boolean onPreferenceChange(Preference preference, Object newValue) {
// final String summary = newValue.toString();
// int index = mPushMode.findIndexOfValue(summary);
// mPushMode.setSummary(mPushMode.getEntries()[index]);
// mPushMode.setValue(summary);
// return false;
// }
// });
// } else {
// PreferenceScreen incomingPrefs = (PreferenceScreen) findPreference(PREFERENCE_SCREEN_INCOMING);
// incomingPrefs.removePreference( (PreferenceScreen) findPreference(PREFERENCE_SCREEN_PUSH_ADVANCED));
// incomingPrefs.removePreference( (ListPreference) findPreference(PREFERENCE_PUSH_MODE));
// }
//
// mAccountNotify = (CheckBoxPreference) findPreference(PREFERENCE_NOTIFY);
// mAccountNotify.setChecked(mAccount.isNotifyNewMail());
//
// mAccountNotifySelf = (CheckBoxPreference) findPreference(PREFERENCE_NOTIFY_SELF);
// mAccountNotifySelf.setChecked(mAccount.isNotifySelfNewMail());
//
// mAccountNotifySync = (CheckBoxPreference) findPreference(PREFERENCE_NOTIFY_SYNC);
// mAccountNotifySync.setChecked(mAccount.isShowOngoing());
//
// mAccountRingtone = (RingtonePreference) findPreference(PREFERENCE_RINGTONE);
//
// // XXX: The following two lines act as a workaround for the RingtonePreference
// // which does not let us set/get the value programmatically
// SharedPreferences prefs = mAccountRingtone.getPreferenceManager().getSharedPreferences();
// String currentRingtone = (!mAccount.getNotificationSetting().shouldRing() ? null : mAccount.getNotificationSetting().getRingtone());
// prefs.edit().putString(PREFERENCE_RINGTONE, currentRingtone).commit();
//
// mAccountVibrate = (CheckBoxPreference) findPreference(PREFERENCE_VIBRATE);
// mAccountVibrate.setChecked(mAccount.getNotificationSetting().shouldVibrate());
//
// mAccountVibratePattern = (ListPreference) findPreference(PREFERENCE_VIBRATE_PATTERN);
// mAccountVibratePattern.setValue(String.valueOf(mAccount.getNotificationSetting().getVibratePattern()));
// mAccountVibratePattern.setSummary(mAccountVibratePattern.getEntry());
// mAccountVibratePattern.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
// public boolean onPreferenceChange(Preference preference, Object newValue) {
// final String summary = newValue.toString();
// int index = mAccountVibratePattern.findIndexOfValue(summary);
// mAccountVibratePattern.setSummary(mAccountVibratePattern.getEntries()[index]);
// mAccountVibratePattern.setValue(summary);
// doVibrateTest(preference);
// return false;
// }
// });
//
// mAccountVibrateTimes = (ListPreference) findPreference(PREFERENCE_VIBRATE_TIMES);
// mAccountVibrateTimes.setValue(String.valueOf(mAccount.getNotificationSetting().getVibrateTimes()));
// mAccountVibrateTimes.setSummary(String.valueOf(mAccount.getNotificationSetting().getVibrateTimes()));
// mAccountVibrateTimes.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
// @Override
// public boolean onPreferenceChange(Preference preference, Object newValue) {
// final String value = newValue.toString();
// mAccountVibrateTimes.setSummary(value);
// mAccountVibrateTimes.setValue(value);
// doVibrateTest(preference);
// return false;
// }
// });
//
// mAccountLed = (CheckBoxPreference) findPreference(PREFERENCE_NOTIFICATION_LED);
// mAccountLed.setChecked(mAccount.getNotificationSetting().isLed());
//
// mNotificationOpensUnread = (CheckBoxPreference)findPreference(PREFERENCE_NOTIFICATION_OPENS_UNREAD);
// mNotificationOpensUnread.setChecked(mAccount.goToUnreadMessageSearch());
//
// mNotificationUnreadCount = (CheckBoxPreference)findPreference(PREFERENCE_NOTIFICATION_UNREAD_COUNT);
// mNotificationUnreadCount.setChecked(mAccount.isNotificationShowsUnreadCount());
//
// new PopulateFolderPrefsTask().execute();
//
// mChipColor = findPreference(PREFERENCE_CHIP_COLOR);
// mChipColor.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
// public boolean onPreferenceClick(Preference preference) {
// onChooseChipColor();
// return false;
// }
// });
//
// mLedColor = findPreference(PREFERENCE_LED_COLOR);
// mLedColor.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
// public boolean onPreferenceClick(Preference preference) {
// onChooseLedColor();
// return false;
// }
// });
//
// findPreference(PREFERENCE_COMPOSITION).setOnPreferenceClickListener(
// new Preference.OnPreferenceClickListener() {
// public boolean onPreferenceClick(Preference preference) {
// onCompositionSettings();
// return true;
// }
// });
//
// findPreference(PREFERENCE_MANAGE_IDENTITIES).setOnPreferenceClickListener(
// new Preference.OnPreferenceClickListener() {
// public boolean onPreferenceClick(Preference preference) {
// onManageIdentities();
// return true;
// }
// });
//
// findPreference(PREFERENCE_INCOMING).setOnPreferenceClickListener(
// new Preference.OnPreferenceClickListener() {
// public boolean onPreferenceClick(Preference preference) {
// mIncomingChanged = true;
// onIncomingSettings();
// return true;
// }
// });
//
// findPreference(PREFERENCE_OUTGOING).setOnPreferenceClickListener(
// new Preference.OnPreferenceClickListener() {
// public boolean onPreferenceClick(Preference preference) {
// onOutgoingSettings();
// return true;
// }
// });
//
// mCryptoApp = (ListPreference) findPreference(PREFERENCE_CRYPTO_APP);
// CharSequence cryptoAppEntries[] = mCryptoApp.getEntries();
// if (!new Apg().isAvailable(this)) {
// int apgIndex = mCryptoApp.findIndexOfValue(Apg.NAME);
// if (apgIndex >= 0) {
// cryptoAppEntries[apgIndex] = "APG (" + getResources().getString(R.string.account_settings_crypto_app_not_available) + ")";
// mCryptoApp.setEntries(cryptoAppEntries);
// }
// }
// mCryptoApp.setValue(String.valueOf(mAccount.getCryptoApp()));
// mCryptoApp.setSummary(mCryptoApp.getEntry());
// mCryptoApp.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
// public boolean onPreferenceChange(Preference preference, Object newValue) {
// String value = newValue.toString();
// int index = mCryptoApp.findIndexOfValue(value);
// mCryptoApp.setSummary(mCryptoApp.getEntries()[index]);
// mCryptoApp.setValue(value);
// handleCryptoAppDependencies();
// if (Apg.NAME.equals(value)) {
// Apg.createInstance(null).test(AccountSettings.this);
// }
// return false;
// }
// });
//
// mCryptoAutoSignature = (CheckBoxPreference) findPreference(PREFERENCE_CRYPTO_AUTO_SIGNATURE);
// mCryptoAutoSignature.setChecked(mAccount.getCryptoAutoSignature());
//
// mCryptoAutoEncrypt = (CheckBoxPreference) findPreference(PREFERENCE_CRYPTO_AUTO_ENCRYPT);
// mCryptoAutoEncrypt.setChecked(mAccount.isCryptoAutoEncrypt());
// handleCryptoAppDependencies();
}
private void handleCryptoAppDependencies() {
if ("".equals(mCryptoApp.getValue())) {
mCryptoAutoSignature.setEnabled(false);
mCryptoAutoEncrypt.setEnabled(false);
} else {
mCryptoAutoSignature.setEnabled(true);
mCryptoAutoEncrypt.setEnabled(true);
}
}
private void saveSettings() {
if (mAccountDefault != null && mAccountDefault.isChecked()) {
Preferences.getPreferences(this).setDefaultAccount(mAccount);
}
mAccount.setDescription(mAccountDescription.getText());
// mAccount.setMarkMessageAsReadOnView(mMarkMessageAsReadOnView.isChecked());
// mAccount.setNotifyNewMail(mAccountNotify.isChecked());
// mAccount.setNotifySelfNewMail(mAccountNotifySelf.isChecked());
// mAccount.setShowOngoing(mAccountNotifySync.isChecked());
// mAccount.setDisplayCount(Integer.parseInt(mDisplayCount.getValue()));
// mAccount.setMaximumAutoDownloadMessageSize(Integer.parseInt(mMessageSize.getValue()));
// if (mAccount.isSearchByDateCapable()) {
// mAccount.setMaximumPolledMessageAge(Integer.parseInt(mMessageAge.getValue()));
// }
// mAccount.getNotificationSetting().setVibrate(mAccountVibrate.isChecked());
// mAccount.getNotificationSetting().setVibratePattern(Integer.parseInt(mAccountVibratePattern.getValue()));
// mAccount.getNotificationSetting().setVibrateTimes(Integer.parseInt(mAccountVibrateTimes.getValue()));
// mAccount.getNotificationSetting().setLed(mAccountLed.isChecked());
// mAccount.setGoToUnreadMessageSearch(mNotificationOpensUnread.isChecked());
// mAccount.setNotificationShowsUnreadCount(mNotificationUnreadCount.isChecked());
// mAccount.setFolderTargetMode(Account.FolderMode.valueOf(mTargetMode.getValue()));
// mAccount.setDeletePolicy(Integer.parseInt(mDeletePolicy.getValue()));
// if (mIsExpungeCapable) {
// mAccount.setExpungePolicy(mExpungePolicy.getValue());
// }
// mAccount.setSyncRemoteDeletions(mSyncRemoteDeletions.isChecked());
// mAccount.setSaveAllHeaders(mSaveAllHeaders.isChecked());
// mAccount.setSearchableFolders(Account.Searchable.valueOf(mSearchableFolders.getValue()));
// mAccount.setMessageFormat(Account.MessageFormat.valueOf(mMessageFormat.getValue()));
// mAccount.setMessageReadReceipt(mMessageReadReceipt.isChecked());
// mAccount.setQuoteStyle(QuoteStyle.valueOf(mQuoteStyle.getValue()));
// mAccount.setQuotePrefix(mAccountQuotePrefix.getText());
// mAccount.setDefaultQuotedTextShown(mAccountDefaultQuotedTextShown.isChecked());
// mAccount.setReplyAfterQuote(mReplyAfterQuote.isChecked());
// mAccount.setStripSignature(mStripSignature.isChecked());
// mAccount.setCryptoApp(mCryptoApp.getValue());
// mAccount.setCryptoAutoSignature(mCryptoAutoSignature.isChecked());
// mAccount.setCryptoAutoEncrypt(mCryptoAutoEncrypt.isChecked());
// mAccount.setLocalStorageProviderId(mLocalStorageProvider.getValue());
//
// // In webdav account we use the exact folder name also for inbox,
// // since it varies because of internationalization
// if (mAccount.getStoreUri().startsWith("webdav"))
// mAccount.setAutoExpandFolderName(mAutoExpandFolder.getValue());
// else
// mAccount.setAutoExpandFolderName(reverseTranslateFolder(mAutoExpandFolder.getValue()));
//
// if (mIsMoveCapable) {
// mAccount.setArchiveFolderName(mArchiveFolder.getValue());
// mAccount.setDraftsFolderName(mDraftsFolder.getValue());
// mAccount.setSentFolderName(mSentFolder.getValue());
// mAccount.setSpamFolderName(mSpamFolder.getValue());
// mAccount.setTrashFolderName(mTrashFolder.getValue());
// }
//
//
// if (mIsPushCapable) {
// mAccount.setPushPollOnConnect(mPushPollOnConnect.isChecked());
// mAccount.setIdleRefreshMinutes(Integer.parseInt(mIdleRefreshPeriod.getValue()));
// mAccount.setMaxPushFolders(Integer.parseInt(mMaxPushFolders.getValue()));
// }
//
// if (!mIsMoveCapable) {
// mAccount.setEnableMoveButtons(false);
// } else {
// mAccount.setEnableMoveButtons(mAccountEnableMoveButtons.isChecked());
// }
//
// boolean needsRefresh = mAccount.setAutomaticCheckIntervalMinutes(Integer.parseInt(mCheckFrequency.getValue()));
// needsRefresh |= mAccount.setFolderSyncMode(Account.FolderMode.valueOf(mSyncMode.getValue()));
//
// boolean displayModeChanged = mAccount.setFolderDisplayMode(Account.FolderMode.valueOf(mDisplayMode.getValue()));
//
// SharedPreferences prefs = mAccountRingtone.getPreferenceManager().getSharedPreferences();
// String newRingtone = prefs.getString(PREFERENCE_RINGTONE, null);
// if (newRingtone != null) {
// mAccount.getNotificationSetting().setRing(true);
// mAccount.getNotificationSetting().setRingtone(newRingtone);
// } else {
// if (mAccount.getNotificationSetting().shouldRing()) {
// mAccount.getNotificationSetting().setRingtone(null);
// }
// }
//
// mAccount.setShowPictures(Account.ShowPictures.valueOf(mAccountShowPictures.getValue()));
//
// if (mIsPushCapable) {
// boolean needsPushRestart = mAccount.setFolderPushMode(Account.FolderMode.valueOf(mPushMode.getValue()));
// if (mAccount.getFolderPushMode() != FolderMode.NONE) {
// needsPushRestart |= displayModeChanged;
// needsPushRestart |= mIncomingChanged;
// }
//
// if (needsRefresh && needsPushRestart) {
// MailService.actionReset(this, null);
// } else if (needsRefresh) {
// MailService.actionReschedulePoll(this, null);
// } else if (needsPushRestart) {
// MailService.actionRestartPushers(this, null);
// }
// }
// TODO: refresh folder list here
mAccount.save(Preferences.getPreferences(this));
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
switch (requestCode) {
case SELECT_AUTO_EXPAND_FOLDER:
mAutoExpandFolder.setSummary(translateFolder(data.getStringExtra(ChooseFolder.EXTRA_NEW_FOLDER)));
break;
}
}
super.onActivityResult(requestCode, resultCode, data);
}
@Override
protected void onPause() {
saveSettings();
super.onPause();
}
private void onCompositionSettings() {
AccountSetupComposition.actionEditCompositionSettings(this, mAccount);
}
private void onManageIdentities() {
Intent intent = new Intent(this, ManageIdentities.class);
intent.putExtra(ChooseIdentity.EXTRA_ACCOUNT, mAccount.getUuid());
startActivityForResult(intent, ACTIVITY_MANAGE_IDENTITIES);
}
private void onIncomingSettings() {
AccountSetupIncoming.actionEditIncomingSettings(this, mAccount);
}
private void onOutgoingSettings() {
AccountSetupOutgoing.actionEditOutgoingSettings(this, mAccount);
}
public void onChooseChipColor() {
new ColorPickerDialog(this, new ColorPickerDialog.OnColorChangedListener() {
public void colorChanged(int color) {
mAccount.setChipColor(color);
}
},
mAccount.getChipColor()).show();
}
public void onChooseLedColor() {
new ColorPickerDialog(this, new ColorPickerDialog.OnColorChangedListener() {
public void colorChanged(int color) {
mAccount.getNotificationSetting().setLedColor(color);
}
},
mAccount.getNotificationSetting().getLedColor()).show();
}
public void onChooseAutoExpandFolder() {
Intent selectIntent = new Intent(this, ChooseFolder.class);
selectIntent.putExtra(ChooseFolder.EXTRA_ACCOUNT, mAccount.getUuid());
selectIntent.putExtra(ChooseFolder.EXTRA_CUR_FOLDER, mAutoExpandFolder.getSummary());
selectIntent.putExtra(ChooseFolder.EXTRA_SHOW_CURRENT, "yes");
selectIntent.putExtra(ChooseFolder.EXTRA_SHOW_FOLDER_NONE, "yes");
selectIntent.putExtra(ChooseFolder.EXTRA_SHOW_DISPLAYABLE_ONLY, "yes");
startActivityForResult(selectIntent, SELECT_AUTO_EXPAND_FOLDER);
}
private String translateFolder(String in) {
if (mAccount.getInboxFolderName().equalsIgnoreCase(in)) {
return getString(R.string.special_mailbox_name_inbox);
} else {
return in;
}
}
private String reverseTranslateFolder(String in) {
if (getString(R.string.special_mailbox_name_inbox).equals(in)) {
return mAccount.getInboxFolderName();
} else {
return in;
}
}
private void doVibrateTest(Preference preference) {
// Do the vibration to show the user what it's like.
Vibrator vibrate = (Vibrator)preference.getContext().getSystemService(Context.VIBRATOR_SERVICE);
vibrate.vibrate(NotificationSetting.getVibration(
Integer.parseInt(mAccountVibratePattern.getValue()),
Integer.parseInt(mAccountVibrateTimes.getValue())), -1);
}
private class PopulateFolderPrefsTask extends AsyncTask<Void, Void, Void> {
List <? extends Folder > folders = new LinkedList<LocalFolder>();
String[] allFolderValues;
String[] allFolderLabels;
@Override
protected Void doInBackground(Void... params) {
try {
folders = mAccount.getLocalStore().getPersonalNamespaces(false);
} catch (Exception e) {
/// this can't be checked in
}
// TODO: In the future the call above should be changed to only return remote folders.
// For now we just remove the Outbox folder if present.
Iterator <? extends Folder > iter = folders.iterator();
while (iter.hasNext()) {
Folder folder = iter.next();
if (mAccount.getOutboxFolderName().equals(folder.getName())) {
iter.remove();
}
}
allFolderValues = new String[folders.size() + 1];
allFolderLabels = new String[folders.size() + 1];
allFolderValues[0] = K9.FOLDER_NONE;
allFolderLabels[0] = K9.FOLDER_NONE;
int i = 1;
for (Folder folder : folders) {
allFolderLabels[i] = folder.getName();
allFolderValues[i] = folder.getName();
i++;
}
return null;
}
@Override
protected void onPreExecute() {
mAutoExpandFolder = (ListPreference)findPreference(PREFERENCE_AUTO_EXPAND_FOLDER);
mAutoExpandFolder.setEnabled(false);
mArchiveFolder = (ListPreference)findPreference(PREFERENCE_ARCHIVE_FOLDER);
mArchiveFolder.setEnabled(false);
mDraftsFolder = (ListPreference)findPreference(PREFERENCE_DRAFTS_FOLDER);
mDraftsFolder.setEnabled(false);
mSentFolder = (ListPreference)findPreference(PREFERENCE_SENT_FOLDER);
mSentFolder.setEnabled(false);
mSpamFolder = (ListPreference)findPreference(PREFERENCE_SPAM_FOLDER);
mSpamFolder.setEnabled(false);
mTrashFolder = (ListPreference)findPreference(PREFERENCE_TRASH_FOLDER);
mTrashFolder.setEnabled(false);
if (!mIsMoveCapable) {
PreferenceScreen foldersCategory =
(PreferenceScreen) findPreference(PREFERENCE_CATEGORY_FOLDERS);
foldersCategory.removePreference(mArchiveFolder);
foldersCategory.removePreference(mSpamFolder);
foldersCategory.removePreference(mDraftsFolder);
foldersCategory.removePreference(mSentFolder);
foldersCategory.removePreference(mTrashFolder);
}
}
@Override
protected void onPostExecute(Void res) {
initListPreference(mAutoExpandFolder, mAccount.getAutoExpandFolderName(), allFolderLabels, allFolderValues);
mAutoExpandFolder.setEnabled(true);
if (mIsMoveCapable) {
initListPreference(mArchiveFolder, mAccount.getArchiveFolderName(), allFolderLabels, allFolderValues);
initListPreference(mDraftsFolder, mAccount.getDraftsFolderName(), allFolderLabels, allFolderValues);
initListPreference(mSentFolder, mAccount.getSentFolderName(), allFolderLabels, allFolderValues);
initListPreference(mSpamFolder, mAccount.getSpamFolderName(), allFolderLabels, allFolderValues);
initListPreference(mTrashFolder, mAccount.getTrashFolderName(), allFolderLabels, allFolderValues);
mArchiveFolder.setEnabled(true);
mSpamFolder.setEnabled(true);
mDraftsFolder.setEnabled(true);
mSentFolder.setEnabled(true);
mTrashFolder.setEnabled(true);
}
}
}
}
| |
/*
* 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.flink.runtime.jobmanager;
import org.apache.flink.api.common.JobID;
import org.apache.flink.configuration.AkkaOptions;
import org.apache.flink.configuration.CheckpointingOptions;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.configuration.JobManagerOptions;
import org.apache.flink.configuration.TaskManagerOptions;
import org.apache.flink.core.fs.Path;
import org.apache.flink.queryablestate.KvStateID;
import org.apache.flink.runtime.akka.AkkaUtils;
import org.apache.flink.runtime.akka.ListeningBehaviour;
import org.apache.flink.runtime.checkpoint.CheckpointDeclineReason;
import org.apache.flink.runtime.checkpoint.CheckpointMetaData;
import org.apache.flink.runtime.checkpoint.CheckpointMetrics;
import org.apache.flink.runtime.checkpoint.CheckpointOptions;
import org.apache.flink.runtime.checkpoint.CheckpointType;
import org.apache.flink.runtime.checkpoint.CheckpointRetentionPolicy;
import org.apache.flink.runtime.clusterframework.messages.NotifyResourceStarted;
import org.apache.flink.runtime.clusterframework.messages.RegisterResourceManager;
import org.apache.flink.runtime.clusterframework.messages.RegisterResourceManagerSuccessful;
import org.apache.flink.runtime.clusterframework.messages.TriggerRegistrationAtJobManager;
import org.apache.flink.runtime.clusterframework.types.ResourceID;
import org.apache.flink.runtime.execution.Environment;
import org.apache.flink.runtime.execution.ExecutionState;
import org.apache.flink.runtime.executiongraph.ExecutionAttemptID;
import org.apache.flink.runtime.executiongraph.ExecutionGraph;
import org.apache.flink.runtime.executiongraph.ExecutionGraphTestUtils;
import org.apache.flink.runtime.executiongraph.ExecutionVertex;
import org.apache.flink.runtime.executiongraph.IntermediateResultPartition;
import org.apache.flink.runtime.highavailability.HighAvailabilityServices;
import org.apache.flink.runtime.highavailability.nonha.embedded.EmbeddedHaServices;
import org.apache.flink.runtime.instance.ActorGateway;
import org.apache.flink.runtime.instance.AkkaActorGateway;
import org.apache.flink.runtime.instance.HardwareDescription;
import org.apache.flink.runtime.io.network.partition.ResultPartitionID;
import org.apache.flink.runtime.jobgraph.IntermediateDataSetID;
import org.apache.flink.runtime.jobgraph.JobGraph;
import org.apache.flink.runtime.jobgraph.JobStatus;
import org.apache.flink.runtime.jobgraph.JobVertex;
import org.apache.flink.runtime.jobgraph.JobVertexID;
import org.apache.flink.runtime.jobgraph.SavepointRestoreSettings;
import org.apache.flink.runtime.jobgraph.tasks.AbstractInvokable;
import org.apache.flink.runtime.jobgraph.tasks.CheckpointCoordinatorConfiguration;
import org.apache.flink.runtime.jobgraph.tasks.JobCheckpointingSettings;
import org.apache.flink.runtime.jobmanager.JobManagerHARecoveryTest.BlockingStatefulInvokable;
import org.apache.flink.runtime.messages.FlinkJobNotFoundException;
import org.apache.flink.runtime.messages.JobManagerMessages.CancelJob;
import org.apache.flink.runtime.messages.JobManagerMessages.CancellationFailure;
import org.apache.flink.runtime.messages.JobManagerMessages.CancellationResponse;
import org.apache.flink.runtime.messages.JobManagerMessages.CancellationSuccess;
import org.apache.flink.runtime.messages.JobManagerMessages.RequestPartitionProducerState;
import org.apache.flink.runtime.messages.JobManagerMessages.StopJob;
import org.apache.flink.runtime.messages.JobManagerMessages.StoppingFailure;
import org.apache.flink.runtime.messages.JobManagerMessages.StoppingSuccess;
import org.apache.flink.runtime.messages.JobManagerMessages.SubmitJob;
import org.apache.flink.runtime.messages.JobManagerMessages.TriggerSavepoint;
import org.apache.flink.runtime.messages.JobManagerMessages.TriggerSavepointSuccess;
import org.apache.flink.runtime.messages.RegistrationMessages;
import org.apache.flink.runtime.metrics.NoOpMetricRegistry;
import org.apache.flink.runtime.query.KvStateLocation;
import org.apache.flink.runtime.query.KvStateMessage.LookupKvStateLocation;
import org.apache.flink.runtime.query.KvStateMessage.NotifyKvStateRegistered;
import org.apache.flink.runtime.query.KvStateMessage.NotifyKvStateUnregistered;
import org.apache.flink.runtime.query.UnknownKvStateLocation;
import org.apache.flink.runtime.state.KeyGroupRange;
import org.apache.flink.runtime.taskmanager.TaskManager;
import org.apache.flink.runtime.taskmanager.TaskManagerLocation;
import org.apache.flink.runtime.testingUtils.TestingCluster;
import org.apache.flink.runtime.testingUtils.TestingJobManager;
import org.apache.flink.runtime.testingUtils.TestingJobManagerMessages;
import org.apache.flink.runtime.testingUtils.TestingJobManagerMessages.ExecutionGraphFound;
import org.apache.flink.runtime.testingUtils.TestingJobManagerMessages.NotifyWhenJobStatus;
import org.apache.flink.runtime.testingUtils.TestingJobManagerMessages.RequestExecutionGraph;
import org.apache.flink.runtime.testingUtils.TestingJobManagerMessages.WaitForAllVerticesToBeRunning;
import org.apache.flink.runtime.testingUtils.TestingJobManagerMessages.WaitForAllVerticesToBeRunningOrFinished;
import org.apache.flink.runtime.testingUtils.TestingMemoryArchivist;
import org.apache.flink.runtime.testingUtils.TestingTaskManager;
import org.apache.flink.runtime.testingUtils.TestingTaskManagerMessages;
import org.apache.flink.runtime.testingUtils.TestingUtils;
import org.apache.flink.runtime.testtasks.BlockingNoOpInvokable;
import org.apache.flink.runtime.testtasks.NoOpInvokable;
import org.apache.flink.runtime.testutils.StoppableInvokable;
import org.apache.flink.runtime.util.LeaderRetrievalUtils;
import org.apache.flink.util.TestLogger;
import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.actor.PoisonPill;
import akka.actor.Status;
import akka.testkit.JavaTestKit;
import akka.testkit.TestProbe;
import com.typesafe.config.Config;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import java.io.File;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.util.Collections;
import java.util.UUID;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import scala.Option;
import scala.Some;
import scala.Tuple2;
import scala.concurrent.Await;
import scala.concurrent.Future;
import scala.concurrent.duration.Deadline;
import scala.concurrent.duration.FiniteDuration;
import scala.reflect.ClassTag$;
import static org.apache.flink.runtime.io.network.partition.ResultPartitionType.PIPELINED;
import static org.apache.flink.runtime.messages.JobManagerMessages.CancelJobWithSavepoint;
import static org.apache.flink.runtime.messages.JobManagerMessages.JobResultFailure;
import static org.apache.flink.runtime.messages.JobManagerMessages.JobResultSuccess;
import static org.apache.flink.runtime.messages.JobManagerMessages.JobSubmitSuccess;
import static org.apache.flink.runtime.messages.JobManagerMessages.LeaderSessionMessage;
import static org.apache.flink.runtime.testingUtils.TestingJobManagerMessages.AllVerticesRunning;
import static org.apache.flink.runtime.testingUtils.TestingJobManagerMessages.JobStatusIs;
import static org.apache.flink.runtime.testingUtils.TestingJobManagerMessages.NotifyWhenAtLeastNumTaskManagerAreRegistered;
import static org.apache.flink.runtime.testingUtils.TestingUtils.DEFAULT_AKKA_ASK_TIMEOUT;
import static org.apache.flink.runtime.testingUtils.TestingUtils.TESTING_TIMEOUT;
import static org.apache.flink.runtime.testingUtils.TestingUtils.startTestingCluster;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.mock;
public class JobManagerTest extends TestLogger {
@Rule
public final TemporaryFolder tmpFolder = new TemporaryFolder();
private static ActorSystem system;
private HighAvailabilityServices highAvailabilityServices;
@BeforeClass
public static void setup() {
system = AkkaUtils.createLocalActorSystem(new Configuration());
}
@AfterClass
public static void teardown() {
JavaTestKit.shutdownActorSystem(system);
}
@Before
public void setupTest() {
highAvailabilityServices = new EmbeddedHaServices(TestingUtils.defaultExecutor());
}
@After
public void tearDownTest() throws Exception {
highAvailabilityServices.closeAndCleanupAllData();
highAvailabilityServices = null;
}
@Test
public void testNullHostnameGoesToLocalhost() {
try {
Tuple2<String, Object> address = new Tuple2<String, Object>(null, 1772);
Config cfg = AkkaUtils.getAkkaConfig(new Configuration(),
new Some<Tuple2<String, Object>>(address));
String hostname = cfg.getString("akka.remote.netty.tcp.hostname");
assertTrue(InetAddress.getByName(hostname).isLoopbackAddress());
}
catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
}
/**
* Tests responses to partition state requests.
*/
@Test
public void testRequestPartitionState() throws Exception {
new JavaTestKit(system) {{
new Within(duration("15 seconds")) {
@Override
protected void run() {
// Setup
TestingCluster cluster = null;
try {
cluster = startTestingCluster(2, 1, DEFAULT_AKKA_ASK_TIMEOUT());
final IntermediateDataSetID rid = new IntermediateDataSetID();
// Create a task
final JobVertex sender = new JobVertex("Sender");
sender.setParallelism(1);
sender.setInvokableClass(BlockingNoOpInvokable.class); // just block
sender.createAndAddResultDataSet(rid, PIPELINED);
final JobGraph jobGraph = new JobGraph("Blocking test job", sender);
final JobID jid = jobGraph.getJobID();
final ActorGateway jobManagerGateway = cluster.getLeaderGateway(
TestingUtils.TESTING_DURATION());
// we can set the leader session ID to None because we don't use this gateway to send messages
final ActorGateway testActorGateway = new AkkaActorGateway(getTestActor(), HighAvailabilityServices.DEFAULT_LEADER_ID);
// Submit the job and wait for all vertices to be running
jobManagerGateway.tell(
new SubmitJob(
jobGraph,
ListeningBehaviour.EXECUTION_RESULT),
testActorGateway);
expectMsgClass(JobSubmitSuccess.class);
jobManagerGateway.tell(
new WaitForAllVerticesToBeRunningOrFinished(jid),
testActorGateway);
expectMsgClass(AllVerticesRunning.class);
// This is the mock execution ID of the task requesting the state of the partition
final ExecutionAttemptID receiver = new ExecutionAttemptID();
// Request the execution graph to get the runtime info
jobManagerGateway.tell(new RequestExecutionGraph(jid), testActorGateway);
final ExecutionGraph eg = (ExecutionGraph) expectMsgClass(ExecutionGraphFound.class)
.executionGraph();
final ExecutionVertex vertex = eg.getJobVertex(sender.getID())
.getTaskVertices()[0];
final IntermediateResultPartition partition = vertex.getProducedPartitions()
.values().iterator().next();
final ResultPartitionID partitionId = new ResultPartitionID(
partition.getPartitionId(),
vertex.getCurrentExecutionAttempt().getAttemptId());
// - The test ----------------------------------------------------------------------
// 1. All execution states
RequestPartitionProducerState request = new RequestPartitionProducerState(
jid, rid, partitionId);
for (ExecutionState state : ExecutionState.values()) {
ExecutionGraphTestUtils.setVertexState(vertex, state);
Future<ExecutionState> futurePartitionState = jobManagerGateway
.ask(request, getRemainingTime())
.mapTo(ClassTag$.MODULE$.<ExecutionState>apply(ExecutionState.class));
ExecutionState resp = Await.result(futurePartitionState, getRemainingTime());
assertEquals(state, resp);
}
// 2. Non-existing execution
request = new RequestPartitionProducerState(jid, rid, new ResultPartitionID());
Future<?> futurePartitionState = jobManagerGateway.ask(request, getRemainingTime());
try {
Await.result(futurePartitionState, getRemainingTime());
fail("Did not fail with expected RuntimeException");
} catch (RuntimeException e) {
assertEquals(IllegalArgumentException.class, e.getCause().getClass());
}
// 3. Non-existing job
request = new RequestPartitionProducerState(new JobID(), rid, new ResultPartitionID());
futurePartitionState = jobManagerGateway.ask(request, getRemainingTime());
try {
Await.result(futurePartitionState, getRemainingTime());
fail("Did not fail with expected IllegalArgumentException");
} catch (IllegalArgumentException ignored) {
}
} catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
} finally {
if (cluster != null) {
cluster.stop();
}
}
}
};
}};
}
/**
* Tests the JobManager response when the execution is not registered with
* the ExecutionGraph.
*/
@Test
public void testRequestPartitionStateUnregisteredExecution() throws Exception {
new JavaTestKit(system) {{
new Within(duration("15 seconds")) {
@Override
protected void run() {
// Setup
TestingCluster cluster = null;
try {
cluster = startTestingCluster(4, 1, DEFAULT_AKKA_ASK_TIMEOUT());
final IntermediateDataSetID rid = new IntermediateDataSetID();
// Create a task
final JobVertex sender = new JobVertex("Sender");
sender.setParallelism(1);
sender.setInvokableClass(NoOpInvokable.class); // just finish
sender.createAndAddResultDataSet(rid, PIPELINED);
final JobVertex sender2 = new JobVertex("Blocking Sender");
sender2.setParallelism(1);
sender2.setInvokableClass(BlockingNoOpInvokable.class); // just block
sender2.createAndAddResultDataSet(new IntermediateDataSetID(), PIPELINED);
final JobGraph jobGraph = new JobGraph("Fast finishing producer test job", sender, sender2);
final JobID jid = jobGraph.getJobID();
final ActorGateway jobManagerGateway = cluster.getLeaderGateway(
TestingUtils.TESTING_DURATION());
// we can set the leader session ID to None because we don't use this gateway to send messages
final ActorGateway testActorGateway = new AkkaActorGateway(getTestActor(), HighAvailabilityServices.DEFAULT_LEADER_ID);
// Submit the job and wait for all vertices to be running
jobManagerGateway.tell(
new SubmitJob(
jobGraph,
ListeningBehaviour.EXECUTION_RESULT),
testActorGateway);
expectMsgClass(JobSubmitSuccess.class);
jobManagerGateway.tell(
new WaitForAllVerticesToBeRunningOrFinished(jid),
testActorGateway);
expectMsgClass(AllVerticesRunning.class);
Future<Object> egFuture = jobManagerGateway.ask(
new RequestExecutionGraph(jobGraph.getJobID()), remaining());
ExecutionGraphFound egFound = (ExecutionGraphFound) Await.result(egFuture, remaining());
ExecutionGraph eg = (ExecutionGraph) egFound.executionGraph();
ExecutionVertex vertex = eg.getJobVertex(sender.getID()).getTaskVertices()[0];
while (vertex.getExecutionState() != ExecutionState.FINISHED) {
Thread.sleep(1);
}
IntermediateResultPartition partition = vertex.getProducedPartitions()
.values().iterator().next();
ResultPartitionID partitionId = new ResultPartitionID(
partition.getPartitionId(),
vertex.getCurrentExecutionAttempt().getAttemptId());
// Producer finished, request state
Object request = new RequestPartitionProducerState(jid, rid, partitionId);
Future<ExecutionState> producerStateFuture = jobManagerGateway
.ask(request, getRemainingTime())
.mapTo(ClassTag$.MODULE$.<ExecutionState>apply(ExecutionState.class));
assertEquals(ExecutionState.FINISHED, Await.result(producerStateFuture, getRemainingTime()));
} catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
} finally {
if (cluster != null) {
cluster.stop();
}
}
}
};
}};
}
/**
* Tests the JobManager response when the execution is not registered with
* the ExecutionGraph anymore and a new execution attempt is available.
*/
@Test
public void testRequestPartitionStateMoreRecentExecutionAttempt() throws Exception {
new JavaTestKit(system) {{
new Within(duration("15 seconds")) {
@Override
protected void run() {
// Setup
TestingCluster cluster = null;
try {
cluster = startTestingCluster(4, 1, DEFAULT_AKKA_ASK_TIMEOUT());
final IntermediateDataSetID rid = new IntermediateDataSetID();
// Create a task
final JobVertex sender = new JobVertex("Sender");
sender.setParallelism(1);
sender.setInvokableClass(NoOpInvokable.class); // just finish
sender.createAndAddResultDataSet(rid, PIPELINED);
final JobVertex sender2 = new JobVertex("Blocking Sender");
sender2.setParallelism(1);
sender2.setInvokableClass(BlockingNoOpInvokable.class); // just block
sender2.createAndAddResultDataSet(new IntermediateDataSetID(), PIPELINED);
final JobGraph jobGraph = new JobGraph("Fast finishing producer test job", sender, sender2);
final JobID jid = jobGraph.getJobID();
final ActorGateway jobManagerGateway = cluster.getLeaderGateway(
TestingUtils.TESTING_DURATION());
// we can set the leader session ID to None because we don't use this gateway to send messages
final ActorGateway testActorGateway = new AkkaActorGateway(getTestActor(), HighAvailabilityServices.DEFAULT_LEADER_ID);
// Submit the job and wait for all vertices to be running
jobManagerGateway.tell(
new SubmitJob(
jobGraph,
ListeningBehaviour.EXECUTION_RESULT),
testActorGateway);
expectMsgClass(JobSubmitSuccess.class);
jobManagerGateway.tell(
new WaitForAllVerticesToBeRunningOrFinished(jid),
testActorGateway);
expectMsgClass(TestingJobManagerMessages.AllVerticesRunning.class);
Future<Object> egFuture = jobManagerGateway.ask(
new RequestExecutionGraph(jobGraph.getJobID()), remaining());
ExecutionGraphFound egFound = (ExecutionGraphFound) Await.result(egFuture, remaining());
ExecutionGraph eg = (ExecutionGraph) egFound.executionGraph();
ExecutionVertex vertex = eg.getJobVertex(sender.getID()).getTaskVertices()[0];
while (vertex.getExecutionState() != ExecutionState.FINISHED) {
Thread.sleep(1);
}
IntermediateResultPartition partition = vertex.getProducedPartitions()
.values().iterator().next();
ResultPartitionID partitionId = new ResultPartitionID(
partition.getPartitionId(),
vertex.getCurrentExecutionAttempt().getAttemptId());
// Reset execution => new execution attempt
vertex.resetForNewExecution(System.currentTimeMillis(), 1L);
// Producer finished, request state
Object request = new RequestPartitionProducerState(jid, rid, partitionId);
Future<?> producerStateFuture = jobManagerGateway.ask(request, getRemainingTime());
try {
Await.result(producerStateFuture, getRemainingTime());
fail("Did not fail with expected Exception");
} catch (PartitionProducerDisposedException ignored) {
}
} catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
} finally {
if (cluster != null) {
cluster.stop();
}
}
}
};
}};
}
@Test
public void testStopSignal() throws Exception {
new JavaTestKit(system) {{
new Within(duration("15 seconds")) {
@Override
protected void run() {
// Setup
TestingCluster cluster = null;
try {
cluster = startTestingCluster(2, 1, DEFAULT_AKKA_ASK_TIMEOUT());
// Create a task
final JobVertex sender = new JobVertex("Sender");
sender.setParallelism(2);
sender.setInvokableClass(StoppableInvokable.class);
final JobGraph jobGraph = new JobGraph("Stoppable streaming test job", sender);
final JobID jid = jobGraph.getJobID();
final ActorGateway jobManagerGateway = cluster.getLeaderGateway(TestingUtils.TESTING_DURATION());
// we can set the leader session ID to None because we don't use this gateway to send messages
final ActorGateway testActorGateway = new AkkaActorGateway(getTestActor(), HighAvailabilityServices.DEFAULT_LEADER_ID);
// Submit the job and wait for all vertices to be running
jobManagerGateway.tell(
new SubmitJob(
jobGraph,
ListeningBehaviour.EXECUTION_RESULT),
testActorGateway);
expectMsgClass(JobSubmitSuccess.class);
jobManagerGateway.tell(new WaitForAllVerticesToBeRunning(jid), testActorGateway);
expectMsgClass(AllVerticesRunning.class);
jobManagerGateway.tell(new StopJob(jid), testActorGateway);
// - The test ----------------------------------------------------------------------
expectMsgClass(StoppingSuccess.class);
expectMsgClass(JobResultSuccess.class);
} finally {
if (cluster != null) {
cluster.stop();
}
}
}
};
}};
}
@Test
public void testStopSignalFail() throws Exception {
new JavaTestKit(system) {{
new Within(duration("15 seconds")) {
@Override
protected void run() {
// Setup
TestingCluster cluster = null;
try {
cluster = startTestingCluster(2, 1, DEFAULT_AKKA_ASK_TIMEOUT());
// Create a task
final JobVertex sender = new JobVertex("Sender");
sender.setParallelism(1);
sender.setInvokableClass(BlockingNoOpInvokable.class); // just block
final JobGraph jobGraph = new JobGraph("Non-Stoppable batching test job", sender);
final JobID jid = jobGraph.getJobID();
final ActorGateway jobManagerGateway = cluster.getLeaderGateway(TestingUtils.TESTING_DURATION());
// we can set the leader session ID to None because we don't use this gateway to send messages
final ActorGateway testActorGateway = new AkkaActorGateway(getTestActor(), HighAvailabilityServices.DEFAULT_LEADER_ID);
// Submit the job and wait for all vertices to be running
jobManagerGateway.tell(
new SubmitJob(
jobGraph,
ListeningBehaviour.EXECUTION_RESULT),
testActorGateway);
expectMsgClass(JobSubmitSuccess.class);
jobManagerGateway.tell(new WaitForAllVerticesToBeRunning(jid), testActorGateway);
expectMsgClass(AllVerticesRunning.class);
jobManagerGateway.tell(new StopJob(jid), testActorGateway);
// - The test ----------------------------------------------------------------------
expectMsgClass(StoppingFailure.class);
jobManagerGateway.tell(new RequestExecutionGraph(jid), testActorGateway);
expectMsgClass(ExecutionGraphFound.class);
} finally {
if (cluster != null) {
cluster.stop();
}
}
}
};
}};
}
/**
* Tests that the JobManager handles {@link org.apache.flink.runtime.query.KvStateMessage}
* instances as expected.
*/
@Test
public void testKvStateMessages() throws Exception {
Deadline deadline = new FiniteDuration(100, TimeUnit.SECONDS).fromNow();
Configuration config = new Configuration();
config.setString(AkkaOptions.ASK_TIMEOUT, "100ms");
ActorRef jobManagerActor = JobManager.startJobManagerActors(
config,
system,
TestingUtils.defaultExecutor(),
TestingUtils.defaultExecutor(),
highAvailabilityServices,
NoOpMetricRegistry.INSTANCE,
Option.empty(),
TestingJobManager.class,
MemoryArchivist.class)._1();
UUID leaderId = LeaderRetrievalUtils.retrieveLeaderSessionId(
highAvailabilityServices.getJobManagerLeaderRetriever(HighAvailabilityServices.DEFAULT_JOB_ID),
TestingUtils.TESTING_TIMEOUT());
ActorGateway jobManager = new AkkaActorGateway(
jobManagerActor,
leaderId);
Configuration tmConfig = new Configuration();
tmConfig.setString(TaskManagerOptions.MANAGED_MEMORY_SIZE, "4m");
tmConfig.setInteger(TaskManagerOptions.NUM_TASK_SLOTS, 8);
ActorRef taskManager = TaskManager.startTaskManagerComponentsAndActor(
tmConfig,
ResourceID.generate(),
system,
highAvailabilityServices,
NoOpMetricRegistry.INSTANCE,
"localhost",
scala.Option.<String>empty(),
true,
TestingTaskManager.class);
Future<Object> registrationFuture = jobManager
.ask(new NotifyWhenAtLeastNumTaskManagerAreRegistered(1), deadline.timeLeft());
Await.ready(registrationFuture, deadline.timeLeft());
//
// Location lookup
//
LookupKvStateLocation lookupNonExistingJob = new LookupKvStateLocation(
new JobID(),
"any-name");
Future<KvStateLocation> lookupFuture = jobManager
.ask(lookupNonExistingJob, deadline.timeLeft())
.mapTo(ClassTag$.MODULE$.<KvStateLocation>apply(KvStateLocation.class));
try {
Await.result(lookupFuture, deadline.timeLeft());
fail("Did not throw expected Exception");
} catch (FlinkJobNotFoundException ignored) {
// Expected
}
JobGraph jobGraph = new JobGraph("croissant");
JobVertex jobVertex1 = new JobVertex("cappuccino");
jobVertex1.setParallelism(4);
jobVertex1.setMaxParallelism(16);
jobVertex1.setInvokableClass(BlockingNoOpInvokable.class);
JobVertex jobVertex2 = new JobVertex("americano");
jobVertex2.setParallelism(4);
jobVertex2.setMaxParallelism(16);
jobVertex2.setInvokableClass(BlockingNoOpInvokable.class);
jobGraph.addVertex(jobVertex1);
jobGraph.addVertex(jobVertex2);
Future<JobSubmitSuccess> submitFuture = jobManager
.ask(new SubmitJob(jobGraph, ListeningBehaviour.DETACHED), deadline.timeLeft())
.mapTo(ClassTag$.MODULE$.<JobSubmitSuccess>apply(JobSubmitSuccess.class));
Await.result(submitFuture, deadline.timeLeft());
Object lookupUnknownRegistrationName = new LookupKvStateLocation(
jobGraph.getJobID(),
"unknown");
lookupFuture = jobManager
.ask(lookupUnknownRegistrationName, deadline.timeLeft())
.mapTo(ClassTag$.MODULE$.<KvStateLocation>apply(KvStateLocation.class));
try {
Await.result(lookupFuture, deadline.timeLeft());
fail("Did not throw expected Exception");
} catch (UnknownKvStateLocation ignored) {
// Expected
}
//
// Registration
//
NotifyKvStateRegistered registerNonExistingJob = new NotifyKvStateRegistered(
new JobID(),
new JobVertexID(),
new KeyGroupRange(0, 0),
"any-name",
new KvStateID(),
new InetSocketAddress(InetAddress.getLocalHost(), 1233));
jobManager.tell(registerNonExistingJob);
LookupKvStateLocation lookupAfterRegistration = new LookupKvStateLocation(
registerNonExistingJob.getJobId(),
registerNonExistingJob.getRegistrationName());
lookupFuture = jobManager
.ask(lookupAfterRegistration, deadline.timeLeft())
.mapTo(ClassTag$.MODULE$.<KvStateLocation>apply(KvStateLocation.class));
try {
Await.result(lookupFuture, deadline.timeLeft());
fail("Did not throw expected Exception");
} catch (FlinkJobNotFoundException ignored) {
// Expected
}
NotifyKvStateRegistered registerForExistingJob = new NotifyKvStateRegistered(
jobGraph.getJobID(),
jobVertex1.getID(),
new KeyGroupRange(0, 0),
"register-me",
new KvStateID(),
new InetSocketAddress(InetAddress.getLocalHost(), 1293));
jobManager.tell(registerForExistingJob);
lookupAfterRegistration = new LookupKvStateLocation(
registerForExistingJob.getJobId(),
registerForExistingJob.getRegistrationName());
lookupFuture = jobManager
.ask(lookupAfterRegistration, deadline.timeLeft())
.mapTo(ClassTag$.MODULE$.<KvStateLocation>apply(KvStateLocation.class));
KvStateLocation location = Await.result(lookupFuture, deadline.timeLeft());
assertNotNull(location);
assertEquals(jobGraph.getJobID(), location.getJobId());
assertEquals(jobVertex1.getID(), location.getJobVertexId());
assertEquals(jobVertex1.getMaxParallelism(), location.getNumKeyGroups());
assertEquals(1, location.getNumRegisteredKeyGroups());
KeyGroupRange keyGroupRange = registerForExistingJob.getKeyGroupRange();
assertEquals(1, keyGroupRange.getNumberOfKeyGroups());
assertEquals(registerForExistingJob.getKvStateId(), location.getKvStateID(keyGroupRange.getStartKeyGroup()));
assertEquals(registerForExistingJob.getKvStateServerAddress(), location.getKvStateServerAddress(keyGroupRange.getStartKeyGroup()));
//
// Unregistration
//
NotifyKvStateUnregistered unregister = new NotifyKvStateUnregistered(
registerForExistingJob.getJobId(),
registerForExistingJob.getJobVertexId(),
registerForExistingJob.getKeyGroupRange(),
registerForExistingJob.getRegistrationName());
jobManager.tell(unregister);
lookupFuture = jobManager
.ask(lookupAfterRegistration, deadline.timeLeft())
.mapTo(ClassTag$.MODULE$.<KvStateLocation>apply(KvStateLocation.class));
try {
Await.result(lookupFuture, deadline.timeLeft());
fail("Did not throw expected Exception");
} catch (UnknownKvStateLocation ignored) {
// Expected
}
//
// Duplicate registration fails task
//
NotifyKvStateRegistered register = new NotifyKvStateRegistered(
jobGraph.getJobID(),
jobVertex1.getID(),
new KeyGroupRange(0, 0),
"duplicate-me",
new KvStateID(),
new InetSocketAddress(InetAddress.getLocalHost(), 1293));
NotifyKvStateRegistered duplicate = new NotifyKvStateRegistered(
jobGraph.getJobID(),
jobVertex2.getID(), // <--- different operator, but...
new KeyGroupRange(0, 0),
"duplicate-me", // ...same name
new KvStateID(),
new InetSocketAddress(InetAddress.getLocalHost(), 1293));
Future<TestingJobManagerMessages.JobStatusIs> failedFuture = jobManager
.ask(new NotifyWhenJobStatus(jobGraph.getJobID(), JobStatus.FAILED), deadline.timeLeft())
.mapTo(ClassTag$.MODULE$.<JobStatusIs>apply(JobStatusIs.class));
jobManager.tell(register);
jobManager.tell(duplicate);
// Wait for failure
JobStatusIs jobStatus = Await.result(failedFuture, deadline.timeLeft());
assertEquals(JobStatus.FAILED, jobStatus.state());
}
@Test
public void testCancelWithSavepoint() throws Exception {
File defaultSavepointDir = tmpFolder.newFolder();
FiniteDuration timeout = new FiniteDuration(30, TimeUnit.SECONDS);
Configuration config = new Configuration();
config.setString(CheckpointingOptions.SAVEPOINT_DIRECTORY, defaultSavepointDir.toURI().toString());
ActorSystem actorSystem = null;
ActorGateway jobManager = null;
ActorGateway archiver = null;
ActorGateway taskManager = null;
try {
actorSystem = AkkaUtils.createLocalActorSystem(new Configuration());
Tuple2<ActorRef, ActorRef> master = JobManager.startJobManagerActors(
config,
actorSystem,
TestingUtils.defaultExecutor(),
TestingUtils.defaultExecutor(),
highAvailabilityServices,
NoOpMetricRegistry.INSTANCE,
Option.empty(),
Option.apply("jm"),
Option.apply("arch"),
TestingJobManager.class,
TestingMemoryArchivist.class);
UUID leaderId = LeaderRetrievalUtils.retrieveLeaderSessionId(
highAvailabilityServices.getJobManagerLeaderRetriever(HighAvailabilityServices.DEFAULT_JOB_ID),
TestingUtils.TESTING_TIMEOUT());
jobManager = new AkkaActorGateway(master._1(), leaderId);
archiver = new AkkaActorGateway(master._2(), leaderId);
ActorRef taskManagerRef = TaskManager.startTaskManagerComponentsAndActor(
config,
ResourceID.generate(),
actorSystem,
highAvailabilityServices,
NoOpMetricRegistry.INSTANCE,
"localhost",
Option.apply("tm"),
true,
TestingTaskManager.class);
taskManager = new AkkaActorGateway(taskManagerRef, leaderId);
// Wait until connected
Object msg = new TestingTaskManagerMessages.NotifyWhenRegisteredAtJobManager(jobManager.actor());
Await.ready(taskManager.ask(msg, timeout), timeout);
// Create job graph
JobVertex sourceVertex = new JobVertex("Source");
sourceVertex.setInvokableClass(BlockingStatefulInvokable.class);
sourceVertex.setParallelism(1);
JobGraph jobGraph = new JobGraph("TestingJob", sourceVertex);
JobCheckpointingSettings snapshottingSettings = new JobCheckpointingSettings(
Collections.singletonList(sourceVertex.getID()),
Collections.singletonList(sourceVertex.getID()),
Collections.singletonList(sourceVertex.getID()),
new CheckpointCoordinatorConfiguration(
3600000,
3600000,
0,
Integer.MAX_VALUE,
CheckpointRetentionPolicy.NEVER_RETAIN_AFTER_TERMINATION,
true),
null);
jobGraph.setSnapshotSettings(snapshottingSettings);
// Submit job graph
msg = new SubmitJob(jobGraph, ListeningBehaviour.DETACHED);
Await.result(jobManager.ask(msg, timeout), timeout);
// Wait for all tasks to be running
msg = new TestingJobManagerMessages.WaitForAllVerticesToBeRunning(jobGraph.getJobID());
Await.result(jobManager.ask(msg, timeout), timeout);
// Notify when cancelled
msg = new NotifyWhenJobStatus(jobGraph.getJobID(), JobStatus.CANCELED);
Future<Object> cancelled = jobManager.ask(msg, timeout);
// Cancel with savepoint
String savepointPath = null;
for (int i = 0; i < 10; i++) {
msg = new CancelJobWithSavepoint(jobGraph.getJobID(), null);
CancellationResponse cancelResp = (CancellationResponse) Await.result(jobManager.ask(msg, timeout), timeout);
if (cancelResp instanceof CancellationFailure) {
CancellationFailure failure = (CancellationFailure) cancelResp;
if (failure.cause().getMessage().contains(CheckpointDeclineReason.NOT_ALL_REQUIRED_TASKS_RUNNING.message())) {
Thread.sleep(10); // wait and retry
} else {
failure.cause().printStackTrace();
fail("Failed to cancel job: " + failure.cause().getMessage());
}
} else {
savepointPath = ((CancellationSuccess) cancelResp).savepointPath();
break;
}
}
// Verify savepoint path
assertNotNull("Savepoint not triggered", savepointPath);
// Wait for job status change
Await.ready(cancelled, timeout);
File savepointFile = new File(new Path(savepointPath).getPath());
assertTrue(savepointFile.exists());
} finally {
if (actorSystem != null) {
actorSystem.shutdown();
}
if (archiver != null) {
archiver.actor().tell(PoisonPill.getInstance(), ActorRef.noSender());
}
if (jobManager != null) {
jobManager.actor().tell(PoisonPill.getInstance(), ActorRef.noSender());
}
if (taskManager != null) {
taskManager.actor().tell(PoisonPill.getInstance(), ActorRef.noSender());
}
if (actorSystem != null) {
actorSystem.awaitTermination(TESTING_TIMEOUT());
}
}
}
/**
* Tests that a failed savepoint does not cancel the job and new checkpoints are triggered
* after the failed cancel-with-savepoint.
*/
@Test
public void testCancelJobWithSavepointFailurePeriodicCheckpoints() throws Exception {
File savepointTarget = tmpFolder.newFolder();
// A source that declines savepoints, simulating the behaviour of a
// failed savepoint.
JobVertex sourceVertex = new JobVertex("Source");
sourceVertex.setInvokableClass(FailOnSavepointSourceTask.class);
sourceVertex.setParallelism(1);
JobGraph jobGraph = new JobGraph("TestingJob", sourceVertex);
CheckpointCoordinatorConfiguration coordConfig = new CheckpointCoordinatorConfiguration(
50,
3600000,
0,
Integer.MAX_VALUE,
CheckpointRetentionPolicy.NEVER_RETAIN_AFTER_TERMINATION,
true);
JobCheckpointingSettings snapshottingSettings = new JobCheckpointingSettings(
Collections.singletonList(sourceVertex.getID()),
Collections.singletonList(sourceVertex.getID()),
Collections.singletonList(sourceVertex.getID()),
coordConfig,
null);
jobGraph.setSnapshotSettings(snapshottingSettings);
final TestingCluster testingCluster = new TestingCluster(
new Configuration(),
highAvailabilityServices,
true,
false);
try {
testingCluster.start(true);
FiniteDuration askTimeout = new FiniteDuration(30, TimeUnit.SECONDS);
ActorGateway jobManager = testingCluster.getLeaderGateway(askTimeout);
testingCluster.submitJobDetached(jobGraph);
// Wait for the source to be running otherwise the savepoint
// barrier will not reach the task.
Future<Object> allTasksAlive = jobManager.ask(
new WaitForAllVerticesToBeRunning(jobGraph.getJobID()),
askTimeout);
Await.ready(allTasksAlive, askTimeout);
// Cancel with savepoint. The expected outcome is that cancellation
// fails due to a failed savepoint. After this, periodic checkpoints
// should resume.
Future<Object> cancellationFuture = jobManager.ask(
new CancelJobWithSavepoint(jobGraph.getJobID(), savepointTarget.getAbsolutePath()),
askTimeout);
Object cancellationResponse = Await.result(cancellationFuture, askTimeout);
if (cancellationResponse instanceof CancellationFailure) {
if (!FailOnSavepointSourceTask.CHECKPOINT_AFTER_SAVEPOINT_LATCH.await(30, TimeUnit.SECONDS)) {
fail("No checkpoint was triggered after failed savepoint within expected duration");
}
} else {
fail("Unexpected cancellation response from JobManager: " + cancellationResponse);
}
} finally {
testingCluster.stop();
}
}
/**
* Tests that a meaningful exception is returned if no savepoint directory is
* configured.
*/
@Test
public void testCancelWithSavepointNoDirectoriesConfigured() throws Exception {
FiniteDuration timeout = new FiniteDuration(30, TimeUnit.SECONDS);
Configuration config = new Configuration();
ActorSystem actorSystem = null;
ActorGateway jobManager = null;
ActorGateway archiver = null;
ActorGateway taskManager = null;
try {
actorSystem = AkkaUtils.createLocalActorSystem(new Configuration());
Tuple2<ActorRef, ActorRef> master = JobManager.startJobManagerActors(
config,
actorSystem,
TestingUtils.defaultExecutor(),
TestingUtils.defaultExecutor(),
highAvailabilityServices,
NoOpMetricRegistry.INSTANCE,
Option.empty(),
Option.apply("jm"),
Option.apply("arch"),
TestingJobManager.class,
TestingMemoryArchivist.class);
UUID leaderId = LeaderRetrievalUtils.retrieveLeaderSessionId(
highAvailabilityServices.getJobManagerLeaderRetriever(HighAvailabilityServices.DEFAULT_JOB_ID),
TestingUtils.TESTING_TIMEOUT());
jobManager = new AkkaActorGateway(master._1(), leaderId);
archiver = new AkkaActorGateway(master._2(), leaderId);
ActorRef taskManagerRef = TaskManager.startTaskManagerComponentsAndActor(
config,
ResourceID.generate(),
actorSystem,
highAvailabilityServices,
NoOpMetricRegistry.INSTANCE,
"localhost",
Option.apply("tm"),
true,
TestingTaskManager.class);
taskManager = new AkkaActorGateway(taskManagerRef, leaderId);
// Wait until connected
Object msg = new TestingTaskManagerMessages.NotifyWhenRegisteredAtJobManager(jobManager.actor());
Await.ready(taskManager.ask(msg, timeout), timeout);
// Create job graph
JobVertex sourceVertex = new JobVertex("Source");
sourceVertex.setInvokableClass(BlockingStatefulInvokable.class);
sourceVertex.setParallelism(1);
JobGraph jobGraph = new JobGraph("TestingJob", sourceVertex);
JobCheckpointingSettings snapshottingSettings = new JobCheckpointingSettings(
Collections.singletonList(sourceVertex.getID()),
Collections.singletonList(sourceVertex.getID()),
Collections.singletonList(sourceVertex.getID()),
new CheckpointCoordinatorConfiguration(
3600000,
3600000,
0,
Integer.MAX_VALUE,
CheckpointRetentionPolicy.NEVER_RETAIN_AFTER_TERMINATION,
true),
null);
jobGraph.setSnapshotSettings(snapshottingSettings);
// Submit job graph
msg = new SubmitJob(jobGraph, ListeningBehaviour.DETACHED);
Await.result(jobManager.ask(msg, timeout), timeout);
// Wait for all tasks to be running
msg = new TestingJobManagerMessages.WaitForAllVerticesToBeRunning(jobGraph.getJobID());
Await.result(jobManager.ask(msg, timeout), timeout);
// Cancel with savepoint
msg = new CancelJobWithSavepoint(jobGraph.getJobID(), null);
CancellationResponse cancelResp = (CancellationResponse) Await.result(jobManager.ask(msg, timeout), timeout);
if (cancelResp instanceof CancellationFailure) {
CancellationFailure failure = (CancellationFailure) cancelResp;
assertTrue(failure.cause() instanceof IllegalStateException);
assertTrue(failure.cause().getMessage().contains("savepoint directory"));
} else {
fail("Unexpected cancellation response from JobManager: " + cancelResp);
}
} finally {
if (actorSystem != null) {
actorSystem.shutdown();
}
if (archiver != null) {
archiver.actor().tell(PoisonPill.getInstance(), ActorRef.noSender());
}
if (jobManager != null) {
jobManager.actor().tell(PoisonPill.getInstance(), ActorRef.noSender());
}
if (taskManager != null) {
taskManager.actor().tell(PoisonPill.getInstance(), ActorRef.noSender());
}
}
}
/**
* Tests that we can trigger a savepoint when periodic checkpoints are disabled.
*/
@Test
public void testSavepointWithDeactivatedPeriodicCheckpointing() throws Exception {
File defaultSavepointDir = tmpFolder.newFolder();
FiniteDuration timeout = new FiniteDuration(30, TimeUnit.SECONDS);
Configuration config = new Configuration();
config.setString(CheckpointingOptions.SAVEPOINT_DIRECTORY, defaultSavepointDir.toURI().toString());
ActorSystem actorSystem = null;
ActorGateway jobManager = null;
ActorGateway archiver = null;
ActorGateway taskManager = null;
try {
actorSystem = AkkaUtils.createLocalActorSystem(new Configuration());
Tuple2<ActorRef, ActorRef> master = JobManager.startJobManagerActors(
config,
actorSystem,
TestingUtils.defaultExecutor(),
TestingUtils.defaultExecutor(),
highAvailabilityServices,
NoOpMetricRegistry.INSTANCE,
Option.empty(),
Option.apply("jm"),
Option.apply("arch"),
TestingJobManager.class,
TestingMemoryArchivist.class);
UUID leaderId = LeaderRetrievalUtils.retrieveLeaderSessionId(
highAvailabilityServices.getJobManagerLeaderRetriever(HighAvailabilityServices.DEFAULT_JOB_ID),
TestingUtils.TESTING_TIMEOUT());
jobManager = new AkkaActorGateway(master._1(), leaderId);
archiver = new AkkaActorGateway(master._2(), leaderId);
ActorRef taskManagerRef = TaskManager.startTaskManagerComponentsAndActor(
config,
ResourceID.generate(),
actorSystem,
highAvailabilityServices,
NoOpMetricRegistry.INSTANCE,
"localhost",
Option.apply("tm"),
true,
TestingTaskManager.class);
taskManager = new AkkaActorGateway(taskManagerRef, leaderId);
// Wait until connected
Object msg = new TestingTaskManagerMessages.NotifyWhenRegisteredAtJobManager(jobManager.actor());
Await.ready(taskManager.ask(msg, timeout), timeout);
// Create job graph
JobVertex sourceVertex = new JobVertex("Source");
sourceVertex.setInvokableClass(BlockingStatefulInvokable.class);
sourceVertex.setParallelism(1);
JobGraph jobGraph = new JobGraph("TestingJob", sourceVertex);
JobCheckpointingSettings snapshottingSettings = new JobCheckpointingSettings(
Collections.singletonList(sourceVertex.getID()),
Collections.singletonList(sourceVertex.getID()),
Collections.singletonList(sourceVertex.getID()),
new CheckpointCoordinatorConfiguration(
Long.MAX_VALUE, // deactivated checkpointing
360000,
0,
Integer.MAX_VALUE,
CheckpointRetentionPolicy.NEVER_RETAIN_AFTER_TERMINATION,
true),
null);
jobGraph.setSnapshotSettings(snapshottingSettings);
// Submit job graph
msg = new SubmitJob(jobGraph, ListeningBehaviour.DETACHED);
Await.result(jobManager.ask(msg, timeout), timeout);
// Wait for all tasks to be running
msg = new TestingJobManagerMessages.WaitForAllVerticesToBeRunning(jobGraph.getJobID());
Await.result(jobManager.ask(msg, timeout), timeout);
// Cancel with savepoint
File targetDirectory = tmpFolder.newFolder();
msg = new TriggerSavepoint(jobGraph.getJobID(), Option.apply(targetDirectory.getAbsolutePath()));
Future<Object> future = jobManager.ask(msg, timeout);
Object result = Await.result(future, timeout);
assertTrue("Did not trigger savepoint", result instanceof TriggerSavepointSuccess);
assertEquals(1, targetDirectory.listFiles().length);
} finally {
if (actorSystem != null) {
actorSystem.shutdown();
}
if (archiver != null) {
archiver.actor().tell(PoisonPill.getInstance(), ActorRef.noSender());
}
if (jobManager != null) {
jobManager.actor().tell(PoisonPill.getInstance(), ActorRef.noSender());
}
if (taskManager != null) {
taskManager.actor().tell(PoisonPill.getInstance(), ActorRef.noSender());
}
if (actorSystem != null) {
actorSystem.awaitTermination(TestingUtils.TESTING_TIMEOUT());
}
}
}
/**
* Tests that configured {@link SavepointRestoreSettings} are respected.
*/
@Test
public void testSavepointRestoreSettings() throws Exception {
FiniteDuration timeout = new FiniteDuration(30, TimeUnit.SECONDS);
ActorSystem actorSystem = null;
ActorGateway jobManager = null;
ActorGateway archiver = null;
ActorGateway taskManager = null;
try {
actorSystem = AkkaUtils.createLocalActorSystem(new Configuration());
Tuple2<ActorRef, ActorRef> master = JobManager.startJobManagerActors(
new Configuration(),
actorSystem,
TestingUtils.defaultExecutor(),
TestingUtils.defaultExecutor(),
highAvailabilityServices,
NoOpMetricRegistry.INSTANCE,
Option.empty(),
Option.apply("jm"),
Option.apply("arch"),
TestingJobManager.class,
TestingMemoryArchivist.class);
UUID leaderId = LeaderRetrievalUtils.retrieveLeaderSessionId(
highAvailabilityServices.getJobManagerLeaderRetriever(HighAvailabilityServices.DEFAULT_JOB_ID),
TestingUtils.TESTING_TIMEOUT());
jobManager = new AkkaActorGateway(master._1(), leaderId);
archiver = new AkkaActorGateway(master._2(), leaderId);
Configuration tmConfig = new Configuration();
tmConfig.setInteger(TaskManagerOptions.NUM_TASK_SLOTS, 4);
ActorRef taskManagerRef = TaskManager.startTaskManagerComponentsAndActor(
tmConfig,
ResourceID.generate(),
actorSystem,
highAvailabilityServices,
NoOpMetricRegistry.INSTANCE,
"localhost",
Option.apply("tm"),
true,
TestingTaskManager.class);
taskManager = new AkkaActorGateway(taskManagerRef, leaderId);
// Wait until connected
Object msg = new TestingTaskManagerMessages.NotifyWhenRegisteredAtJobManager(jobManager.actor());
Await.ready(taskManager.ask(msg, timeout), timeout);
// Create job graph
JobVertex sourceVertex = new JobVertex("Source");
sourceVertex.setInvokableClass(BlockingStatefulInvokable.class);
sourceVertex.setParallelism(1);
JobGraph jobGraph = new JobGraph("TestingJob", sourceVertex);
JobCheckpointingSettings snapshottingSettings = new JobCheckpointingSettings(
Collections.singletonList(sourceVertex.getID()),
Collections.singletonList(sourceVertex.getID()),
Collections.singletonList(sourceVertex.getID()),
new CheckpointCoordinatorConfiguration(
Long.MAX_VALUE, // deactivated checkpointing
360000,
0,
Integer.MAX_VALUE,
CheckpointRetentionPolicy.NEVER_RETAIN_AFTER_TERMINATION,
true),
null);
jobGraph.setSnapshotSettings(snapshottingSettings);
// Submit job graph
msg = new SubmitJob(jobGraph, ListeningBehaviour.DETACHED);
Await.result(jobManager.ask(msg, timeout), timeout);
// Wait for all tasks to be running
msg = new TestingJobManagerMessages.WaitForAllVerticesToBeRunning(jobGraph.getJobID());
Await.result(jobManager.ask(msg, timeout), timeout);
// Trigger savepoint
File targetDirectory = tmpFolder.newFolder();
msg = new TriggerSavepoint(jobGraph.getJobID(), Option.apply(targetDirectory.getAbsolutePath()));
Future<Object> future = jobManager.ask(msg, timeout);
Object result = Await.result(future, timeout);
String savepointPath = ((TriggerSavepointSuccess) result).savepointPath();
// Cancel because of restarts
msg = new TestingJobManagerMessages.NotifyWhenJobRemoved(jobGraph.getJobID());
Future<?> removedFuture = jobManager.ask(msg, timeout);
Future<?> cancelFuture = jobManager.ask(new CancelJob(jobGraph.getJobID()), timeout);
Object response = Await.result(cancelFuture, timeout);
assertTrue("Unexpected response: " + response, response instanceof CancellationSuccess);
Await.ready(removedFuture, timeout);
// Adjust the job (we need a new operator ID)
JobVertex newSourceVertex = new JobVertex("NewSource");
newSourceVertex.setInvokableClass(BlockingStatefulInvokable.class);
newSourceVertex.setParallelism(1);
JobGraph newJobGraph = new JobGraph("NewTestingJob", newSourceVertex);
JobCheckpointingSettings newSnapshottingSettings = new JobCheckpointingSettings(
Collections.singletonList(newSourceVertex.getID()),
Collections.singletonList(newSourceVertex.getID()),
Collections.singletonList(newSourceVertex.getID()),
new CheckpointCoordinatorConfiguration(
Long.MAX_VALUE, // deactivated checkpointing
360000,
0,
Integer.MAX_VALUE,
CheckpointRetentionPolicy.NEVER_RETAIN_AFTER_TERMINATION,
true),
null);
newJobGraph.setSnapshotSettings(newSnapshottingSettings);
SavepointRestoreSettings restoreSettings = SavepointRestoreSettings.forPath(savepointPath, false);
newJobGraph.setSavepointRestoreSettings(restoreSettings);
msg = new SubmitJob(newJobGraph, ListeningBehaviour.DETACHED);
response = Await.result(jobManager.ask(msg, timeout), timeout);
assertTrue("Unexpected response: " + response, response instanceof JobResultFailure);
JobResultFailure failure = (JobResultFailure) response;
Throwable cause = failure.cause().deserializeError(ClassLoader.getSystemClassLoader());
assertTrue(cause instanceof IllegalStateException);
assertTrue(cause.getMessage().contains("allowNonRestoredState"));
// Wait until removed
msg = new TestingJobManagerMessages.NotifyWhenJobRemoved(newJobGraph.getJobID());
Await.ready(jobManager.ask(msg, timeout), timeout);
// Resubmit, but allow non restored state now
restoreSettings = SavepointRestoreSettings.forPath(savepointPath, true);
newJobGraph.setSavepointRestoreSettings(restoreSettings);
msg = new SubmitJob(newJobGraph, ListeningBehaviour.DETACHED);
response = Await.result(jobManager.ask(msg, timeout), timeout);
assertTrue("Unexpected response: " + response, response instanceof JobSubmitSuccess);
} finally {
if (actorSystem != null) {
actorSystem.shutdown();
}
if (archiver != null) {
archiver.actor().tell(PoisonPill.getInstance(), ActorRef.noSender());
}
if (jobManager != null) {
jobManager.actor().tell(PoisonPill.getInstance(), ActorRef.noSender());
}
if (taskManager != null) {
taskManager.actor().tell(PoisonPill.getInstance(), ActorRef.noSender());
}
if (actorSystem != null) {
actorSystem.awaitTermination(TestingUtils.TESTING_TIMEOUT());
}
}
}
/**
* This tests makes sure that triggering a reconnection from the ResourceManager will stop after a new
* ResourceManager has connected. Furthermore it makes sure that there is not endless loop of reconnection
* commands (see FLINK-6341).
*/
@Test
public void testResourceManagerConnection() throws TimeoutException, InterruptedException {
FiniteDuration testTimeout = new FiniteDuration(30L, TimeUnit.SECONDS);
final long reconnectionInterval = 200L;
final Configuration configuration = new Configuration();
configuration.setLong(JobManagerOptions.RESOURCE_MANAGER_RECONNECT_INTERVAL, reconnectionInterval);
final ActorSystem actorSystem = AkkaUtils.createLocalActorSystem(configuration);
try {
final ActorGateway jmGateway = TestingUtils.createJobManager(
actorSystem,
TestingUtils.defaultExecutor(),
TestingUtils.defaultExecutor(),
configuration,
highAvailabilityServices);
final TestProbe probe = TestProbe.apply(actorSystem);
final AkkaActorGateway rmGateway = new AkkaActorGateway(probe.ref(), HighAvailabilityServices.DEFAULT_LEADER_ID);
// wait for the JobManager to become the leader
Future<?> leaderFuture = jmGateway.ask(TestingJobManagerMessages.getNotifyWhenLeader(), testTimeout);
Await.ready(leaderFuture, testTimeout);
jmGateway.tell(new RegisterResourceManager(probe.ref()), rmGateway);
LeaderSessionMessage leaderSessionMessage = probe.expectMsgClass(LeaderSessionMessage.class);
assertEquals(jmGateway.leaderSessionID(), leaderSessionMessage.leaderSessionID());
assertTrue(leaderSessionMessage.message() instanceof RegisterResourceManagerSuccessful);
jmGateway.tell(
new RegistrationMessages.RegisterTaskManager(
ResourceID.generate(),
mock(TaskManagerLocation.class),
new HardwareDescription(1, 1L, 1L, 1L),
1));
leaderSessionMessage = probe.expectMsgClass(LeaderSessionMessage.class);
assertTrue(leaderSessionMessage.message() instanceof NotifyResourceStarted);
// fail the NotifyResourceStarted so that we trigger the reconnection process on the JobManager's side
probe.lastSender().tell(new Status.Failure(new Exception("Test exception")), ActorRef.noSender());
Deadline reconnectionDeadline = new FiniteDuration(5L * reconnectionInterval, TimeUnit.MILLISECONDS).fromNow();
boolean registered = false;
while (reconnectionDeadline.hasTimeLeft()) {
try {
leaderSessionMessage = probe.expectMsgClass(reconnectionDeadline.timeLeft(), LeaderSessionMessage.class);
} catch (AssertionError ignored) {
// expected timeout after the reconnectionDeadline has been exceeded
continue;
}
if (leaderSessionMessage.message() instanceof TriggerRegistrationAtJobManager) {
if (registered) {
fail("A successful registration should not be followed by another TriggerRegistrationAtJobManager message.");
}
jmGateway.tell(new RegisterResourceManager(probe.ref()), rmGateway);
} else if (leaderSessionMessage.message() instanceof RegisterResourceManagerSuccessful) {
// now we should no longer receive TriggerRegistrationAtJobManager messages
registered = true;
} else {
fail("Received unknown message: " + leaderSessionMessage.message() + '.');
}
}
assertTrue(registered);
} finally {
// cleanup the actor system and with it all of the started actors if not already terminated
actorSystem.shutdown();
actorSystem.awaitTermination();
}
}
/**
* A blocking stateful source task that declines savepoints.
*/
public static class FailOnSavepointSourceTask extends AbstractInvokable {
private static final CountDownLatch CHECKPOINT_AFTER_SAVEPOINT_LATCH = new CountDownLatch(1);
private boolean receivedSavepoint;
/**
* Create an Invokable task and set its environment.
*
* @param environment The environment assigned to this invokable.
*/
public FailOnSavepointSourceTask(Environment environment) {
super(environment);
}
@Override
public void invoke() throws Exception {
new CountDownLatch(1).await();
}
@Override
public boolean triggerCheckpoint(
CheckpointMetaData checkpointMetaData,
CheckpointOptions checkpointOptions) throws Exception {
if (checkpointOptions.getCheckpointType() == CheckpointType.SAVEPOINT) {
receivedSavepoint = true;
return false;
} else if (receivedSavepoint) {
CHECKPOINT_AFTER_SAVEPOINT_LATCH.countDown();
return true;
}
return true;
}
@Override
public void triggerCheckpointOnBarrier(
CheckpointMetaData checkpointMetaData,
CheckpointOptions checkpointOptions,
CheckpointMetrics checkpointMetrics) throws Exception {
throw new UnsupportedOperationException("This is meant to be used as a source");
}
@Override
public void abortCheckpointOnBarrier(long checkpointId, Throwable cause) throws Exception {
}
@Override
public void notifyCheckpointComplete(long checkpointId) throws Exception {
}
}
}
| |
/*
* @(#)ImageInputFormat.java
*
* Copyright (c) 1996-2010 by the original authors of JHotDraw
* and all its contributors.
* All rights reserved.
*
* The copyright of this software is owned by the authors and
* contributors of the JHotDraw project ("the copyright holders").
* You may not use, copy or modify this software, except in
* accordance with the license agreement you entered into with
* the copyright holders. For details see accompanying license terms.
*/
package org.jhotdraw.draw.io;
import org.jhotdraw.draw.*;
import org.jhotdraw.draw.ImageHolderFigure;
import java.awt.*;
import java.awt.datatransfer.*;
import java.awt.geom.*;
import java.awt.image.*;
import java.io.*;
import java.util.*;
import javax.imageio.*;
import javax.swing.*;
import org.jhotdraw.gui.datatransfer.*;
import org.jhotdraw.io.*;
import org.jhotdraw.util.Images;
import static org.jhotdraw.draw.AttributeKeys.*;
/**
* An input format for importing drawings using one of the image formats
* supported by javax.imageio.
* <p>
* This class uses the prototype design pattern. A ImageHolderFigure figure is
* used as a prototype for creating a figure that holds the imported image.
* <p>
* If the drawing is replaced using the loaded image, the size of the
* drawing is set to match the size of the image using the attributes
* {@code AttributeKeys.CANVAS_WIDTH} and {@code AttributeKeys.CANVAS_HEIGHT}.
*
* <hr>
* <b>Design Patterns</b>
*
* <p><em>Prototype</em><br>
* The image input format creates new image holder figures by cloning a prototype figure
* object and assigning an image to it, which was read from data input.
* That's the reason why {@code Figure} extends the {@code Cloneable} interface.
* <br>
* Prototype: {@link org.jhotdraw.draw.ImageHolderFigure}; Client: {@link ImageInputFormat}.
* <hr>
*
* @author Werner Randelshor
* @version $Id: ImageInputFormat.java 604 2010-01-09 12:00:29Z rawcoder $
*/
public class ImageInputFormat implements InputFormat {
/**
* The prototype for creating a figure that holds the imported image.
*/
private ImageHolderFigure prototype;
/**
* Format description used for the file filter.
*/
private String description;
/**
* File name extension used for the file filter.
*/
private String[] fileExtensions;
/**
* Image IO image format name.
*/
private String formatName;
/**
* The mime types which must be matched.
*/
private String[] mimeTypes;
/** Creates a new image input format for all formats supported by
* {@code javax.imageio.ImageIO}. */
public ImageInputFormat(ImageHolderFigure prototype) {
this(prototype, "Image", "Image", ImageIO.getReaderFileSuffixes(), ImageIO.getReaderMIMETypes());
}
/** Creates a new image input format for the specified image format.
*
* @param formatName The format name for the javax.imageio.ImageIO object.
* @param description The format description to be used for the file filter.
* @param fileExtension The file extension to be used for the file filter.
* @param mimeType The mime type used for filtering data flavors from
* Transferable objects.
*/
public ImageInputFormat(ImageHolderFigure prototype, String formatName, String description, String fileExtension,
String mimeType) {
this(prototype, formatName, description, new String[]{fileExtension}, new String[]{mimeType});
}
/** Creates a new image input format for the specified image format.
*
* @param formatName The format name for the javax.imageio.ImageIO object.
* @param description The format description to be used for the file filter.
* @param fileExtensions The file extensions to be used for the file filter.
* @param mimeTypes The mime typse used for filtering data flavors from
* Transferable objects.
*/
public ImageInputFormat(ImageHolderFigure prototype, String formatName, String description, String fileExtensions[], String[] mimeTypes) {
this.prototype = prototype;
this.formatName = formatName;
this.description = description;
this.fileExtensions = fileExtensions;
this.mimeTypes = mimeTypes;
}
public javax.swing.filechooser.FileFilter getFileFilter() {
return new ExtensionFileFilter(description, fileExtensions);
}
public String[] getFileExtensions() {
return fileExtensions;
}
public JComponent getInputFormatAccessory() {
return null;
}
public void read(File file, Drawing drawing, boolean replace) throws IOException {
ImageHolderFigure figure = (ImageHolderFigure) prototype.clone();
figure.loadImage(file);
figure.setBounds(
new Point2D.Double(0, 0),
new Point2D.Double(
figure.getBufferedImage().getWidth(),
figure.getBufferedImage().getHeight()));
if (replace) {
drawing.removeAllChildren();
drawing.set(CANVAS_WIDTH, figure.getBounds().width);
drawing.set(CANVAS_HEIGHT, figure.getBounds().height);
}
drawing.basicAdd(figure);
}
public void read(File file, Drawing drawing) throws IOException {
read(file, drawing, true);
}
public void read(InputStream in, Drawing drawing, boolean replace) throws IOException {
ImageHolderFigure figure = createImageHolder(in);
if (replace) {
drawing.removeAllChildren();
drawing.set(CANVAS_WIDTH, figure.getBounds().width);
drawing.set(CANVAS_HEIGHT, figure.getBounds().height);
}
drawing.basicAdd(figure);
}
public ImageHolderFigure createImageHolder(InputStream in) throws IOException {
ImageHolderFigure figure = (ImageHolderFigure) prototype.clone();
figure.loadImage(in);
figure.setBounds(
new Point2D.Double(0, 0),
new Point2D.Double(
figure.getBufferedImage().getWidth(),
figure.getBufferedImage().getHeight()));
return figure;
}
public boolean isDataFlavorSupported(DataFlavor flavor) {
if (DataFlavor.imageFlavor.match(flavor)) {
return true;
}
for (String mimeType : mimeTypes) {
if (flavor.isMimeTypeEqual(mimeType)) {
return true;
}
}
return false;
}
public void read(Transferable t, Drawing drawing, boolean replace) throws UnsupportedFlavorException, IOException {
DataFlavor importFlavor = null;
SearchLoop:
for (DataFlavor flavor : t.getTransferDataFlavors()) {
if (DataFlavor.imageFlavor.match(flavor)) {
importFlavor = flavor;
break SearchLoop;
}
for (String mimeType : mimeTypes) {
if (flavor.isMimeTypeEqual(mimeType)) {
importFlavor = flavor;
break SearchLoop;
}
}
}
Object data = t.getTransferData(importFlavor);
Image img = null;
if (data instanceof Image) {
img = (Image) data;
} else if (data instanceof InputStream) {
img = ImageIO.read((InputStream) data);
}
if (img == null) {
throw new IOException("Unsupported data format " + importFlavor);
}
ImageHolderFigure figure = (ImageHolderFigure) prototype.clone();
figure.setBufferedImage(Images.toBufferedImage(img));
figure.setBounds(
new Point2D.Double(0, 0),
new Point2D.Double(
figure.getBufferedImage().getWidth(),
figure.getBufferedImage().getHeight()));
LinkedList<Figure> list = new LinkedList<Figure>();
list.add(figure);
if (replace) {
drawing.removeAllChildren();
drawing.set(CANVAS_WIDTH, figure.getBounds().width);
drawing.set(CANVAS_HEIGHT, figure.getBounds().height);
}
drawing.addAll(list);
}
}
| |
/*
* Copyright 2000-2009 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.lang.ant.config.impl.configuration;
import com.intellij.lang.ant.AntBundle;
import com.intellij.lang.ant.config.impl.AntInstallation;
import com.intellij.lang.ant.config.impl.AntReference;
import com.intellij.lang.ant.config.impl.GlobalAntConfiguration;
import com.intellij.openapi.fileChooser.FileChooser;
import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.ui.Splitter;
import com.intellij.openapi.util.Factory;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.config.AbstractProperty;
import com.intellij.util.config.StorageAccessors;
import com.intellij.util.containers.HashMap;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.*;
public class AntSetPanel {
private final Form myForm;
private final GlobalAntConfiguration myAntConfiguration;
public AntSetPanel() {
this(GlobalAntConfiguration.getInstance());
}
AntSetPanel(GlobalAntConfiguration antConfiguration) {
myAntConfiguration = antConfiguration;
myForm = new Form(antConfiguration);
}
@Nullable
public AntInstallation showDialog(JComponent parent) {
final DialogWrapper dialog = new MyDialog(parent);
dialog.show();
if (!dialog.isOK()) {
return null;
}
apply();
return myForm.getSelectedAnt();
}
void reset() {
myForm.setAnts(myAntConfiguration.getConfiguredAnts().values());
}
void apply() {
for (AntInstallation ant : myForm.getRemovedAnts()) {
myAntConfiguration.removeConfiguration(ant);
}
final Map<AntReference, AntInstallation> currentAnts = myAntConfiguration.getConfiguredAnts();
for (AntInstallation installation : currentAnts.values()) {
installation.updateClasspath();
}
for (AntInstallation ant : myForm.getAddedAnts()) {
myAntConfiguration.addConfiguration(ant);
}
myForm.applyModifications();
}
public void setSelection(AntInstallation antInstallation) {
myForm.selectAnt(antInstallation);
}
public JComponent getComponent() {
return myForm.getComponent();
}
private static class Form implements AntUIUtil.PropertiesEditor<AntInstallation> {
private final Splitter mySplitter = new Splitter(false);
private final StorageAccessors myAccessors = StorageAccessors.createGlobal("antConfigurations");
private final RightPanel myRightPanel;
private final AnActionListEditor<AntInstallation> myAnts = new AnActionListEditor<AntInstallation>();
private final UIPropertyBinding.Composite myBinding = new UIPropertyBinding.Composite();
private final EditPropertyContainer myGlobalWorkingProperties;
private final Map<AntInstallation, EditPropertyContainer> myWorkingProperties = new HashMap<AntInstallation, EditPropertyContainer>();
private AntInstallation myCurrent;
private final PropertyChangeListener myImmediateUpdater = new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
myBinding.apply(getProperties(myCurrent));
myAnts.updateItem(myCurrent);
}
};
public Form(final GlobalAntConfiguration antInstallation) {
mySplitter.setProportion(myAccessors.getFloat("splitter", 0.3f));
mySplitter.setShowDividerControls(true);
mySplitter.setFirstComponent(myAnts);
myGlobalWorkingProperties = new EditPropertyContainer(antInstallation.getProperties());
myRightPanel = new RightPanel(myBinding, myImmediateUpdater);
mySplitter.setSecondComponent(myRightPanel.myWholePanel);
myAnts.addAddAction(new NewAntFactory(myAnts));
myAnts.addRemoveButtonForAnt(antInstallation.IS_USER_ANT, AntBundle.message("remove.action.name"));
myAnts.actionsBuilt();
JList list = myAnts.getList();
list.setCellRenderer(new AntUIUtil.AntInstallationRenderer(this));
list.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
if (myCurrent != null) myBinding.apply(getProperties(myCurrent));
myCurrent = myAnts.getSelectedItem();
if (myCurrent == null) {
myBinding.loadValues(AbstractProperty.AbstractPropertyContainer.EMPTY);
myBinding.beDisabled();
}
else {
if (antInstallation.IS_USER_ANT.value(myCurrent)) {
myBinding.beEnabled();
}
else {
myBinding.beDisabled();
}
myBinding.loadValues(getProperties(myCurrent));
}
}
});
}
public JList getAntsList() {
return myAnts.getList();
}
public JComponent getComponent() {
return mySplitter;
}
public AntInstallation getSelectedAnt() {
return myAnts.getSelectedItem();
}
public void setAnts(Collection<AntInstallation> antInstallations) {
myAnts.setItems(antInstallations);
}
public void applyModifications() {
if (myCurrent != null) myBinding.apply(getProperties(myCurrent));
ArrayList<AbstractProperty> properties = new ArrayList<AbstractProperty>();
myBinding.addAllPropertiesTo(properties);
for (AntInstallation ant : myWorkingProperties.keySet()) {
EditPropertyContainer container = myWorkingProperties.get(ant);
container.apply();
}
myGlobalWorkingProperties.apply();
}
public void selectAnt(AntInstallation antInstallation) {
myAnts.setSelection(antInstallation);
}
public ArrayList<AntInstallation> getAddedAnts() {
return myAnts.getAdded();
}
public ArrayList<AntInstallation> getRemovedAnts() {
return myAnts.getRemoved();
}
public EditPropertyContainer getProperties(AntInstallation ant) {
EditPropertyContainer properties = myWorkingProperties.get(ant);
if (properties != null) return properties;
properties = new EditPropertyContainer(myGlobalWorkingProperties, ant.getProperties());
myWorkingProperties.put(ant, properties);
return properties;
}
private static class RightPanel {
private JLabel myNameLabel;
private JLabel myHome;
private JTextField myName;
private AntClasspathEditorPanel myClasspath;
private JPanel myWholePanel;
public RightPanel(UIPropertyBinding.Composite binding, PropertyChangeListener immediateUpdater) {
myNameLabel.setLabelFor(myName);
binding.addBinding(myClasspath.setClasspathProperty(AntInstallation.CLASS_PATH));
binding.bindString(myHome, AntInstallation.HOME_DIR);
binding.bindString(myName, AntInstallation.NAME).addChangeListener(immediateUpdater);
}
}
}
private static class NewAntFactory implements Factory<AntInstallation> {
private final AnActionListEditor<AntInstallation> myParent;
public NewAntFactory(AnActionListEditor<AntInstallation> parent) {
myParent = parent;
}
public AntInstallation create() {
VirtualFile[] files = FileChooser.chooseFiles(myParent, FileChooserDescriptorFactory.createSingleFolderDescriptor());
if (files.length == 0) return null;
VirtualFile homePath = files[0];
try {
final AntInstallation inst = AntInstallation.fromHome(homePath.getPresentableUrl());
adjustName(inst);
return inst;
}
catch (AntInstallation.ConfigurationException e) {
Messages.showErrorDialog(myParent, e.getMessage(), AntBundle.message("ant.setup.dialog.title"));
return null;
}
}
private void adjustName(final AntInstallation justCreated) {
int nameIndex = 0;
String adjustedName = justCreated.getName();
final ListModel model = myParent.getList().getModel();
int idx = 0;
while (idx < model.getSize()) {
final AntInstallation inst = (AntInstallation)model.getElementAt(idx++);
if (adjustedName.equals(inst.getName())) {
adjustedName = justCreated.getName() + " (" + (++nameIndex) + ")";
idx = 0; // search from beginning
}
}
if (!adjustedName.equals(justCreated.getName())) {
justCreated.setName(adjustedName);
}
}
}
private class MyDialog extends DialogWrapper {
public MyDialog(final JComponent parent) {
super(parent, true);
setTitle(AntBundle.message("configure.ant.dialog.title"));
init();
}
@Nullable
protected JComponent createCenterPanel() {
return myForm.getComponent();
}
@NonNls
protected String getDimensionServiceKey() {
return "antSetDialogDimensionKey";
}
public JComponent getPreferredFocusedComponent() {
return myForm.getAntsList();
}
protected void doOKAction() {
final Set<String> names = new HashSet<String>();
final ListModel model = myForm.getAntsList().getModel();
for (int idx = 0; idx < model.getSize(); idx++) {
final AntInstallation inst = (AntInstallation)model.getElementAt(idx);
final String name = AntInstallation.NAME.get(myForm.getProperties(inst));
if (names.contains(name)) {
Messages.showErrorDialog("Duplicate ant installation name: \"" + name+ "\"", getTitle());
return;
}
names.add(name);
}
super.doOKAction();
}
}
}
| |
/*
* Copyright (C) 2014 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.example.android.wearable.datalayer;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.IntentSender;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.data.FreezableUtils;
import com.google.android.gms.wearable.Asset;
import com.google.android.gms.wearable.DataApi;
import com.google.android.gms.wearable.DataApi.DataItemResult;
import com.google.android.gms.wearable.DataEvent;
import com.google.android.gms.wearable.DataEventBuffer;
import com.google.android.gms.wearable.MessageApi;
import com.google.android.gms.wearable.MessageApi.SendMessageResult;
import com.google.android.gms.wearable.MessageEvent;
import com.google.android.gms.wearable.Node;
import com.google.android.gms.wearable.NodeApi;
import com.google.android.gms.wearable.PutDataMapRequest;
import com.google.android.gms.wearable.PutDataRequest;
import com.google.android.gms.wearable.Wearable;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* Receives its own events using a listener API designed for foreground activities. Updates a data
* item every second while it is open. Also allows user to take a photo and send that as an asset
* to the paired wearable.
*/
public class MainActivity extends Activity implements DataApi.DataListener,
MessageApi.MessageListener, NodeApi.NodeListener, ConnectionCallbacks,
OnConnectionFailedListener {
private static final String TAG = "MainActivity";
/**
* Request code for launching the Intent to resolve Google Play services errors.
*/
private static final int REQUEST_RESOLVE_ERROR = 1000;
private static final String START_ACTIVITY_PATH = "/start-activity";
private static final String TEMPERATURE_PATH = "/temperature";
private static final String HUMIDITY_PATH = "/humidity";
private static final String FANSTATE_PATH = "/fanstate";
private static final String COUNT_PATH = "/count";
private static final String IMAGE_PATH = "/image";
private static final String IMAGE_KEY = "photo";
private static final String COUNT_KEY = "count";
private GoogleApiClient mGoogleApiClient;
private boolean mResolvingError = false;
private boolean mCameraSupported = false;
private ListView mDataItemList;
private Button mSendPhotoBtn;
private ImageView mThumbView;
private Bitmap mImageBitmap;
private View mStartActivityBtn;
private DataItemAdapter mDataItemListAdapter;
private Handler mHandler;
// Send DataItems.
private ScheduledExecutorService mGeneratorExecutor;
private ScheduledFuture<?> mDataItemGeneratorFuture;
private String humidity;
private String temperature;
private String fanState;
private String webServer = "http://ph1a5h.asuscomm.com/environment.php";
static final int REQUEST_IMAGE_CAPTURE = 1;
/**
* Retrieves given URL's HTML and then calls parser after
*/
private class getWebsiteDataTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... urls) {
return GET(webServer);
}
// onPostExecute displays the results of the AsyncTask.
@Override
protected void onPostExecute(String result) {
Toast.makeText(getBaseContext(), "Received!", Toast.LENGTH_LONG).show();
((TextView)findViewById(R.id.dataTextView)).setText(result);
((TextView)findViewById(R.id.dataTextView)).setMovementMethod(new ScrollingMovementMethod());
environmentParser(result);
sendEnvironmentData();
mDataItemList.setVisibility(View.INVISIBLE);
}
}
// Parses the HTML by splitting data at specific delimiters
private void environmentParser(String data)
{
TextView dataHolder = ((TextView)findViewById(R.id.dataTextView));
String tempHolder[] = data.split("Temperature</br>");
if(tempHolder.length > 1)
{
tempHolder = tempHolder[1].split("°");
temperature = tempHolder[0].trim();
dataHolder.setText(temperature);
}
String humidHolder[] = data.split("Humidity</br>");
if(humidHolder.length > 1)
{
humidHolder = humidHolder[1].split("%");
humidity = humidHolder[0].trim();
dataHolder.append(humidity);
}
String fanHolder[] = data.split("State</br>");
if(fanHolder.length > 1)
{
fanHolder = fanHolder[1].split("</br");
fanState = fanHolder[0].trim();
dataHolder.append(fanState);
}
}
//Get HTML from given URL
public static String GET(String urlpath){
try{
URL url = new URL(urlpath); // Your given URL.
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.setRequestProperty("Content-length", "0");
c.setUseCaches(false);
c.setAllowUserInteraction(false);
//c.setConnectTimeout(timeout);
//c.setReadTimeout(timeout);
c.connect();
int status = c.getResponseCode();
switch (status) {
case 200:
case 201:
BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
br.close();
return sb.toString();
}
c.disconnect();
} catch (Exception e) {
Log.d("InputStream", "It broke!");
}
return "Failed";
}
@Override
public void onCreate(Bundle b) {
super.onCreate(b);
mHandler = new Handler();
LOGD(TAG, "onCreate");
mCameraSupported = getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA);
setContentView(R.layout.main_activity);
setupViews();
// Stores DataItems received by the local broadcaster or from the paired watch.
mDataItemListAdapter = new DataItemAdapter(this, android.R.layout.simple_list_item_1);
mDataItemList.setAdapter(mDataItemListAdapter);
mGeneratorExecutor = new ScheduledThreadPoolExecutor(1);
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(Wearable.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
mImageBitmap = (Bitmap) extras.get("data");
mThumbView.setImageBitmap(mImageBitmap);
}
}
@Override
protected void onStart() {
super.onStart();
if (!mResolvingError) {
mGoogleApiClient.connect();
}
}
@Override
public void onResume() {
super.onResume();
mDataItemGeneratorFuture = mGeneratorExecutor.scheduleWithFixedDelay(
new DataItemGenerator(), 1, 5, TimeUnit.SECONDS);
}
@Override
public void onPause() {
super.onPause();
mDataItemGeneratorFuture.cancel(true /* mayInterruptIfRunning */);
}
@Override
protected void onStop() {
if (!mResolvingError) {
Wearable.DataApi.removeListener(mGoogleApiClient, this);
Wearable.MessageApi.removeListener(mGoogleApiClient, this);
Wearable.NodeApi.removeListener(mGoogleApiClient, this);
mGoogleApiClient.disconnect();
}
super.onStop();
}
@Override //ConnectionCallbacks
public void onConnected(Bundle connectionHint) {
LOGD(TAG, "Google API Client was connected");
mResolvingError = false;
mStartActivityBtn.setEnabled(true);
mSendPhotoBtn.setEnabled(mCameraSupported);
Wearable.DataApi.addListener(mGoogleApiClient, this);
Wearable.MessageApi.addListener(mGoogleApiClient, this);
Wearable.NodeApi.addListener(mGoogleApiClient, this);
}
@Override //ConnectionCallbacks
public void onConnectionSuspended(int cause) {
LOGD(TAG, "Connection to Google API client was suspended");
mStartActivityBtn.setEnabled(false);
mSendPhotoBtn.setEnabled(false);
}
@Override //OnConnectionFailedListener
public void onConnectionFailed(ConnectionResult result) {
if (mResolvingError) {
// Already attempting to resolve an error.
return;
} else if (result.hasResolution()) {
try {
mResolvingError = true;
result.startResolutionForResult(this, REQUEST_RESOLVE_ERROR);
} catch (IntentSender.SendIntentException e) {
// There was an error with the resolution intent. Try again.
mGoogleApiClient.connect();
}
} else {
Log.e(TAG, "Connection to Google API client has failed");
mResolvingError = false;
mStartActivityBtn.setEnabled(false);
mSendPhotoBtn.setEnabled(false);
Wearable.DataApi.removeListener(mGoogleApiClient, this);
Wearable.MessageApi.removeListener(mGoogleApiClient, this);
Wearable.NodeApi.removeListener(mGoogleApiClient, this);
}
}
@Override //DataListener
public void onDataChanged(DataEventBuffer dataEvents) {
LOGD(TAG, "onDataChanged: " + dataEvents);
// Need to freeze the dataEvents so they will exist later on the UI thread
final List<DataEvent> events = FreezableUtils.freezeIterable(dataEvents);
runOnUiThread(new Runnable() {
@Override
public void run() {
for (DataEvent event : events) {
if (event.getType() == DataEvent.TYPE_CHANGED) {
mDataItemListAdapter.add(
new Event("DataItem Changed", event.getDataItem().toString()));
} else if (event.getType() == DataEvent.TYPE_DELETED) {
mDataItemListAdapter.add(
new Event("DataItem Deleted", event.getDataItem().toString()));
}
}
}
});
}
@Override //MessageListener
public void onMessageReceived(final MessageEvent messageEvent) {
LOGD(TAG, "onMessageReceived() A message from watch was received:" + messageEvent
.getRequestId() + " " + messageEvent.getPath());
mHandler.post(new Runnable() {
@Override
public void run() {
mDataItemListAdapter.add(new Event("Message from watch", messageEvent.toString()));
}
});
}
@Override //NodeListener
public void onPeerConnected(final Node peer) {
LOGD(TAG, "onPeerConnected: " + peer);
mHandler.post(new Runnable() {
@Override
public void run() {
mDataItemListAdapter.add(new Event("Connected", peer.toString()));
}
});
}
@Override //NodeListener
public void onPeerDisconnected(final Node peer) {
LOGD(TAG, "onPeerDisconnected: " + peer);
mHandler.post(new Runnable() {
@Override
public void run() {
mDataItemListAdapter.add(new Event("Disconnected", peer.toString()));
}
});
}
/**
* A View Adapter for presenting the Event objects in a list
*/
private static class DataItemAdapter extends ArrayAdapter<Event> {
private final Context mContext;
public DataItemAdapter(Context context, int unusedResource) {
super(context, unusedResource);
mContext = context;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(android.R.layout.two_line_list_item, null);
convertView.setTag(holder);
holder.text1 = (TextView) convertView.findViewById(android.R.id.text1);
holder.text2 = (TextView) convertView.findViewById(android.R.id.text2);
} else {
holder = (ViewHolder) convertView.getTag();
}
Event event = getItem(position);
holder.text1.setText(event.title);
holder.text2.setText(event.text);
return convertView;
}
private class ViewHolder {
TextView text1;
TextView text2;
}
}
private class Event {
String title;
String text;
public Event(String title, String text) {
this.title = title;
this.text = text;
}
}
private Collection<String> getNodes() {
HashSet<String> results = new HashSet<>();
NodeApi.GetConnectedNodesResult nodes =
Wearable.NodeApi.getConnectedNodes(mGoogleApiClient).await();
for (Node node : nodes.getNodes()) {
results.add(node.getId());
}
return results;
}
private void sendStartActivityMessage(String node) {
Wearable.MessageApi.sendMessage(
mGoogleApiClient, node, START_ACTIVITY_PATH, new byte[0]).setResultCallback(
new ResultCallback<SendMessageResult>() {
@Override
public void onResult(SendMessageResult sendMessageResult) {
if (!sendMessageResult.getStatus().isSuccess()) {
Log.e(TAG, "Failed to send message with status code: "
+ sendMessageResult.getStatus().getStatusCode());
}
}
}
);
}
private class StartWearableActivityTask extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... args) {
Collection<String> nodes = getNodes();
for (String node : nodes) {
sendStartActivityMessage(node);
}
return null;
}
}
/**
* Sends an RPC to start a fullscreen Activity on the wearable.
*/
public void onStartWearableActivityClick(View view) {
LOGD(TAG, "Generating RPC");
// Trigger an AsyncTask that will query for a list of connected nodes and send a
// "start-activity" message to each connected node.
new StartWearableActivityTask().execute();
}
/**
* Generates a DataItem based on an incrementing count.
*/
private class DataItemGenerator implements Runnable {
private int count = 0;
@Override
public void run() {
PutDataMapRequest putDataMapRequest = PutDataMapRequest.create(COUNT_PATH);
putDataMapRequest.getDataMap().putInt(COUNT_KEY, count++);
PutDataRequest request = putDataMapRequest.asPutDataRequest();
LOGD(TAG, "Generating DataItem: " + request);
if (!mGoogleApiClient.isConnected()) {
return;
}
Wearable.DataApi.putDataItem(mGoogleApiClient, request)
.setResultCallback(new ResultCallback<DataItemResult>() {
@Override
public void onResult(DataItemResult dataItemResult) {
if (!dataItemResult.getStatus().isSuccess()) {
Log.e(TAG, "ERROR: failed to putDataItem, status code: "
+ dataItemResult.getStatus().getStatusCode());
}
}
});
}
}
/**
* Dispatches an {@link android.content.Intent} to take a photo. Result will be returned back
* in onActivityResult().
*/
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
/**
* Builds an {@link com.google.android.gms.wearable.Asset} from a bitmap. The image that we get
* back from the camera in "data" is a thumbnail size. Typically, your image should not exceed
* 320x320 and if you want to have zoom and parallax effect in your app, limit the size of your
* image to 640x400. Resize your image before transferring to your wearable device.
*/
private static Asset toAsset(Bitmap bitmap) {
ByteArrayOutputStream byteStream = null;
try {
byteStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteStream);
return Asset.createFromBytes(byteStream.toByteArray());
} finally {
if (null != byteStream) {
try {
byteStream.close();
} catch (IOException e) {
// ignore
}
}
}
}
// Send data using DataMap interface
private void sendEnvironmentData()
{
PutDataMapRequest dataMapTemp = PutDataMapRequest.create(TEMPERATURE_PATH);
PutDataMapRequest dataMapHumid = PutDataMapRequest.create(HUMIDITY_PATH);
PutDataMapRequest dataMapFanstate = PutDataMapRequest.create(FANSTATE_PATH);
dataMapTemp.getDataMap().putString(TEMPERATURE_PATH, temperature);
dataMapHumid.getDataMap().putString(HUMIDITY_PATH, humidity);
dataMapFanstate.getDataMap().putString(FANSTATE_PATH, fanState);
dataMapTemp.getDataMap().putLong("time", new Date().getTime());
dataMapHumid.getDataMap().putLong("time", new Date().getTime());
dataMapFanstate.getDataMap().putLong("time", new Date().getTime());
PutDataRequest requestTemp = dataMapTemp.asPutDataRequest();
PutDataRequest requestHumid = dataMapHumid.asPutDataRequest();
PutDataRequest requestFanstate = dataMapFanstate.asPutDataRequest();
Wearable.DataApi.putDataItem(mGoogleApiClient,requestTemp)
.setResultCallback(new ResultCallback<DataItemResult>() {
@Override
public void onResult(DataItemResult dataItemResult) {
LOGD(TAG, "Sending data was successful: " + dataItemResult.getStatus()
.isSuccess());
}
});
Wearable.DataApi.putDataItem(mGoogleApiClient,requestHumid)
.setResultCallback(new ResultCallback<DataItemResult>() {
@Override
public void onResult(DataItemResult dataItemResult) {
LOGD(TAG, "Sending image was successful: " + dataItemResult.getStatus()
.isSuccess());
}
});
Wearable.DataApi.putDataItem(mGoogleApiClient,requestFanstate)
.setResultCallback(new ResultCallback<DataItemResult>() {
@Override
public void onResult(DataItemResult dataItemResult) {
LOGD(TAG, "Sending image was successful: " + dataItemResult.getStatus()
.isSuccess());
}
});
}
/**
* Sends the asset that was created form the photo we took by adding it to the Data Item store.
*/
private void sendPhoto(Asset asset) {
PutDataMapRequest dataMap = PutDataMapRequest.create(IMAGE_PATH);
dataMap.getDataMap().putAsset(IMAGE_KEY, asset);
dataMap.getDataMap().putLong("time", new Date().getTime());
PutDataRequest request = dataMap.asPutDataRequest();
Wearable.DataApi.putDataItem(mGoogleApiClient, request)
.setResultCallback(new ResultCallback<DataItemResult>() {
@Override
public void onResult(DataItemResult dataItemResult) {
LOGD(TAG, "Sending image was successful: " + dataItemResult.getStatus()
.isSuccess());
}
});
}
public void onTakePhotoClick(View view) {
dispatchTakePictureIntent();
}
public void onSendPhotoClick(View view) {
new getWebsiteDataTask().execute();
if (null != mImageBitmap && mGoogleApiClient.isConnected()) {
sendPhoto(toAsset(mImageBitmap));
}
}
/**
* Sets up UI components and their callback handlers.
*/
private void setupViews() {
mSendPhotoBtn = (Button) findViewById(R.id.sendPhoto);
mThumbView = (ImageView) findViewById(R.id.imageView);
mDataItemList = (ListView) findViewById(R.id.data_item_list);
mStartActivityBtn = findViewById(R.id.start_wearable_activity);
}
/**
* As simple wrapper around Log.d
*/
private static void LOGD(final String tag, String message) {
if (Log.isLoggable(tag, Log.DEBUG)) {
Log.d(tag, message);
}
}
}
| |
/*
* Copyright (C) 2007 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 android.opengl;
import javax.microedition.khronos.opengles.GL10;
/**
* A set of GL utilities inspired by the OpenGL Utility Toolkit.
*
*/
public class GLU {
/**
* Return an error string from a GL or GLU error code.
*
* @param error - a GL or GLU error code.
* @return the error string for the input error code, or NULL if the input
* was not a valid GL or GLU error code.
*/
public static String gluErrorString(int error) {
switch (error) {
case GL10.GL_NO_ERROR:
return "no error";
case GL10.GL_INVALID_ENUM:
return "invalid enum";
case GL10.GL_INVALID_VALUE:
return "invalid value";
case GL10.GL_INVALID_OPERATION:
return "invalid operation";
case GL10.GL_STACK_OVERFLOW:
return "stack overflow";
case GL10.GL_STACK_UNDERFLOW:
return "stack underflow";
case GL10.GL_OUT_OF_MEMORY:
return "out of memory";
default:
return null;
}
}
/**
* Define a viewing transformation in terms of an eye point, a center of
* view, and an up vector.
*
* @param gl a GL10 interface
* @param eyeX eye point X
* @param eyeY eye point Y
* @param eyeZ eye point Z
* @param centerX center of view X
* @param centerY center of view Y
* @param centerZ center of view Z
* @param upX up vector X
* @param upY up vector Y
* @param upZ up vector Z
*/
public static void gluLookAt(GL10 gl, float eyeX, float eyeY, float eyeZ,
float centerX, float centerY, float centerZ, float upX, float upY,
float upZ) {
float[] scratch = sScratch;
synchronized(scratch) {
Matrix.setLookAtM(scratch, 0, eyeX, eyeY, eyeZ, centerX, centerY, centerZ,
upX, upY, upZ);
gl.glMultMatrixf(scratch, 0);
}
}
/**
* Set up a 2D orthographic projection matrix
*
* @param gl
* @param left
* @param right
* @param bottom
* @param top
*/
public static void gluOrtho2D(GL10 gl, float left, float right,
float bottom, float top) {
gl.glOrthof(left, right, bottom, top, -1.0f, 1.0f);
}
/**
* Set up a perspective projection matrix
*
* @param gl a GL10 interface
* @param fovy specifies the field of view angle, in degrees, in the Y
* direction.
* @param aspect specifies the aspect ration that determins the field of
* view in the x direction. The aspect ratio is the ratio of x
* (width) to y (height).
* @param zNear specifies the distance from the viewer to the near clipping
* plane (always positive).
* @param zFar specifies the distance from the viewer to the far clipping
* plane (always positive).
*/
public static void gluPerspective(GL10 gl, float fovy, float aspect,
float zNear, float zFar) {
float top = zNear * (float) Math.tan(fovy * (Math.PI / 360.0));
float bottom = -top;
float left = bottom * aspect;
float right = top * aspect;
gl.glFrustumf(left, right, bottom, top, zNear, zFar);
}
/**
* Map object coordinates into window coordinates. gluProject transforms the
* specified object coordinates into window coordinates using model, proj,
* and view. The result is stored in win.
* <p>
* Note that you can use the OES_matrix_get extension, if present, to get
* the current modelView and projection matrices.
*
* @param objX object coordinates X
* @param objY object coordinates Y
* @param objZ object coordinates Z
* @param model the current modelview matrix
* @param modelOffset the offset into the model array where the modelview
* maxtrix data starts.
* @param project the current projection matrix
* @param projectOffset the offset into the project array where the project
* matrix data starts.
* @param view the current view, {x, y, width, height}
* @param viewOffset the offset into the view array where the view vector
* data starts.
* @param win the output vector {winX, winY, winZ}, that returns the
* computed window coordinates.
* @param winOffset the offset into the win array where the win vector data
* starts.
* @return A return value of GL_TRUE indicates success, a return value of
* GL_FALSE indicates failure.
*/
public static int gluProject(float objX, float objY, float objZ,
float[] model, int modelOffset, float[] project, int projectOffset,
int[] view, int viewOffset, float[] win, int winOffset) {
float[] scratch = sScratch;
synchronized(scratch) {
final int M_OFFSET = 0; // 0..15
final int V_OFFSET = 16; // 16..19
final int V2_OFFSET = 20; // 20..23
Matrix.multiplyMM(scratch, M_OFFSET, project, projectOffset,
model, modelOffset);
scratch[V_OFFSET + 0] = objX;
scratch[V_OFFSET + 1] = objY;
scratch[V_OFFSET + 2] = objZ;
scratch[V_OFFSET + 3] = 1.0f;
Matrix.multiplyMV(scratch, V2_OFFSET,
scratch, M_OFFSET, scratch, V_OFFSET);
float w = scratch[V2_OFFSET + 3];
if (w == 0.0f) {
return GL10.GL_FALSE;
}
float rw = 1.0f / w;
win[winOffset] =
view[viewOffset] + view[viewOffset + 2]
* (scratch[V2_OFFSET + 0] * rw + 1.0f)
* 0.5f;
win[winOffset + 1] =
view[viewOffset + 1] + view[viewOffset + 3]
* (scratch[V2_OFFSET + 1] * rw + 1.0f) * 0.5f;
win[winOffset + 2] = (scratch[V2_OFFSET + 2] * rw + 1.0f) * 0.5f;
}
return GL10.GL_TRUE;
}
/**
* Map window coordinates to object coordinates. gluUnProject maps the
* specified window coordinates into object coordinates using model, proj,
* and view. The result is stored in obj.
* <p>
* Note that you can use the OES_matrix_get extension, if present, to get
* the current modelView and projection matrices.
*
* @param winX window coordinates X
* @param winY window coordinates Y
* @param winZ window coordinates Z
* @param model the current modelview matrix
* @param modelOffset the offset into the model array where the modelview
* maxtrix data starts.
* @param project the current projection matrix
* @param projectOffset the offset into the project array where the project
* matrix data starts.
* @param view the current view, {x, y, width, height}
* @param viewOffset the offset into the view array where the view vector
* data starts.
* @param obj the output vector {objX, objY, objZ}, that returns the
* computed object coordinates.
* @param objOffset the offset into the obj array where the obj vector data
* starts.
* @return A return value of GL10.GL_TRUE indicates success, a return value
* of GL10.GL_FALSE indicates failure.
*/
public static int gluUnProject(float winX, float winY, float winZ,
float[] model, int modelOffset, float[] project, int projectOffset,
int[] view, int viewOffset, float[] obj, int objOffset) {
float[] scratch = sScratch;
synchronized(scratch) {
final int PM_OFFSET = 0; // 0..15
final int INVPM_OFFSET = 16; // 16..31
final int V_OFFSET = 0; // 0..3 Reuses PM_OFFSET space
Matrix.multiplyMM(scratch, PM_OFFSET, project, projectOffset,
model, modelOffset);
if (!Matrix.invertM(scratch, INVPM_OFFSET, scratch, PM_OFFSET)) {
return GL10.GL_FALSE;
}
scratch[V_OFFSET + 0] =
2.0f * (winX - view[viewOffset + 0]) / view[viewOffset + 2]
- 1.0f;
scratch[V_OFFSET + 1] =
2.0f * (winY - view[viewOffset + 1]) / view[viewOffset + 3]
- 1.0f;
scratch[V_OFFSET + 2] = 2.0f * winZ - 1.0f;
scratch[V_OFFSET + 3] = 1.0f;
Matrix.multiplyMV(obj, objOffset, scratch, INVPM_OFFSET,
scratch, V_OFFSET);
}
return GL10.GL_TRUE;
}
private static final float[] sScratch = new float[32];
}
| |
package org.ovirt.engine.api.restapi.types;
import org.ovirt.engine.api.common.util.StatusUtils;
import org.ovirt.engine.api.common.util.TimeZoneMapping;
import org.ovirt.engine.api.model.Boot;
import org.ovirt.engine.api.model.Cluster;
import org.ovirt.engine.api.model.CPU;
import org.ovirt.engine.api.model.CpuTopology;
import org.ovirt.engine.api.model.Display;
import org.ovirt.engine.api.model.DisplayType;
import org.ovirt.engine.api.model.Domain;
import org.ovirt.engine.api.model.HighAvailability;
import org.ovirt.engine.api.model.OperatingSystem;
import org.ovirt.engine.api.model.OsType;
import org.ovirt.engine.api.model.Template;
import org.ovirt.engine.api.model.TemplateStatus;
import org.ovirt.engine.api.model.Usb;
import org.ovirt.engine.api.model.UsbType;
import org.ovirt.engine.api.model.VmType;
import org.ovirt.engine.api.restapi.utils.UsbMapperUtils;
import org.ovirt.engine.core.common.businessentities.OriginType;
import org.ovirt.engine.core.common.businessentities.UsbPolicy;
import org.ovirt.engine.core.common.businessentities.VmTemplateStatus;
import org.ovirt.engine.core.common.businessentities.VmStatic;
import org.ovirt.engine.core.common.businessentities.VmTemplate;
import org.ovirt.engine.core.compat.Guid;
public class TemplateMapper {
private static final int BYTES_PER_MB = 1024 * 1024;
@Mapping(from = Template.class, to = VmTemplate.class)
public static VmTemplate map(Template model, VmTemplate incoming) {
VmTemplate entity = incoming != null ? incoming : new VmTemplate();
if (model.isSetName()) {
entity.setname(model.getName());
}
if (model.isSetId()) {
entity.setId(new Guid(model.getId()));
}
if (model.isSetDescription()) {
entity.setdescription(model.getDescription());
}
if (model.isSetCluster() && model.getCluster().getId() != null) {
entity.setvds_group_id(new Guid(model.getCluster().getId()));
}
if (model.isSetHighAvailability()) {
if (model.getHighAvailability().isSetEnabled()) {
entity.setauto_startup(model.getHighAvailability().isEnabled());
}
if (model.getHighAvailability().isSetPriority()) {
entity.setpriority(model.getHighAvailability().getPriority());
}
}
if (model.isSetStateless()) {
entity.setis_stateless(model.isStateless());
}
if (model.isSetType()) {
VmType vmType = VmType.fromValue(model.getType());
if (vmType != null) {
entity.setvm_type(VmMapper.map(vmType, null));
}
}
if (model.isSetOrigin()) {
entity.setorigin(VmMapper.map(model.getOrigin(), (OriginType)null));
}
if (model.isSetMemory()) {
entity.setmem_size_mb((int)(model.getMemory() / BYTES_PER_MB));
}
if (model.isSetCpu() && model.getCpu().isSetTopology()) {
if (model.getCpu().getTopology().getCores()!=null) {
entity.setcpu_per_socket(model.getCpu().getTopology().getCores());
}
if (model.getCpu().getTopology().getSockets()!=null) {
entity.setnum_of_sockets(model.getCpu().getTopology().getSockets());
}
}
if (model.isSetOs()) {
if (model.getOs().isSetType()) {
OsType osType = OsType.fromValue(model.getOs().getType());
if (osType != null) {
entity.setos(VmMapper.map(osType, null));
}
}
if (model.getOs().isSetBoot() && model.getOs().getBoot().size() > 0) {
entity.setdefault_boot_sequence(VmMapper.map(model.getOs().getBoot(), null));
}
if (model.getOs().isSetKernel()) {
entity.setkernel_url(model.getOs().getKernel());
}
if (model.getOs().isSetInitrd()) {
entity.setinitrd_url(model.getOs().getInitrd());
}
if (model.getOs().isSetCmdline()) {
entity.setkernel_params(model.getOs().getCmdline());
}
}
if (model.isSetDisplay()) {
if (model.getDisplay().isSetType()) {
DisplayType displayType = DisplayType.fromValue(model.getDisplay().getType());
if (displayType != null) {
entity.setdefault_display_type(VmMapper.map(displayType, null));
}
}
if (model.getDisplay().isSetMonitors()) {
entity.setnum_of_monitors(model.getDisplay().getMonitors());
}
if (model.getDisplay().isSetAllowOverride()) {
entity.setAllowConsoleReconnect(model.getDisplay().isAllowOverride());
}
}
if (model.isSetDomain() && model.getDomain().isSetName()) {
entity.setdomain(model.getDomain().getName());
}
if (model.isSetTimezone()) {
entity.settime_zone(TimeZoneMapping.getWindows(model.getTimezone()));
}
if (model.isSetUsb() && model.getUsb().isSetEnabled()) {
entity.setusb_policy(model.getUsb().isEnabled() ? UsbPolicy.ENABLED_LEGACY : UsbPolicy.DISABLED);
}
return entity;
}
@Mapping(from = Template.class, to = VmStatic.class)
public static VmStatic map(Template model, VmStatic incoming) {
VmStatic staticVm = incoming != null ? incoming : new VmStatic();
if (model.isSetName()) {
staticVm.setvm_name(model.getName());
}
if (model.isSetId()) {
staticVm.setId(new Guid(model.getId()));
}
if (model.isSetDescription()) {
staticVm.setdescription(model.getDescription());
}
if (model.isSetCluster() && model.getCluster().getId() != null) {
staticVm.setvds_group_id(new Guid(model.getCluster().getId()));
}
if (model.isSetHighAvailability()) {
if (model.getHighAvailability().isSetEnabled()) {
staticVm.setauto_startup(model.getHighAvailability().isEnabled());
}
if (model.getHighAvailability().isSetPriority()) {
staticVm.setpriority(model.getHighAvailability().getPriority());
}
}
if (model.isSetStateless()) {
staticVm.setis_stateless(model.isStateless());
}
if (model.isSetType()) {
VmType vmType = VmType.fromValue(model.getType());
if (vmType != null) {
staticVm.setvm_type(VmMapper.map(vmType, null));
}
}
if (model.isSetOrigin()) {
staticVm.setorigin(VmMapper.map(model.getOrigin(), (OriginType)null));
}
if (model.isSetMemory()) {
staticVm.setmem_size_mb((int)(model.getMemory() / BYTES_PER_MB));
}
if (model.isSetCpu() && model.getCpu().isSetTopology()) {
if (model.getCpu().getTopology().getCores()!=null) {
staticVm.setcpu_per_socket(model.getCpu().getTopology().getCores());
}
if (model.getCpu().getTopology().getSockets()!=null) {
staticVm.setnum_of_sockets(model.getCpu().getTopology().getSockets());
}
}
if (model.isSetOs()) {
if (model.getOs().isSetType()) {
OsType osType = OsType.fromValue(model.getOs().getType());
if (osType != null) {
staticVm.setos(VmMapper.map(osType, null));
}
}
if (model.getOs().isSetBoot() && model.getOs().getBoot().size() > 0) {
staticVm.setdefault_boot_sequence(VmMapper.map(model.getOs().getBoot(), null));
}
if (model.getOs().isSetKernel()) {
staticVm.setkernel_url(model.getOs().getKernel());
}
if (model.getOs().isSetInitrd()) {
staticVm.setinitrd_url(model.getOs().getInitrd());
}
if (model.getOs().isSetCmdline()) {
staticVm.setkernel_params(model.getOs().getCmdline());
}
}
if (model.isSetDisplay()) {
if (model.getDisplay().isSetType()) {
DisplayType displayType = DisplayType.fromValue(model.getDisplay().getType());
if (displayType != null) {
staticVm.setdefault_display_type(VmMapper.map(displayType, null));
}
}
if (model.getDisplay().isSetMonitors()) {
staticVm.setnum_of_monitors(model.getDisplay().getMonitors());
}
if (model.getDisplay().isSetAllowOverride()) {
staticVm.setAllowConsoleReconnect(model.getDisplay().isAllowOverride());
}
}
if (model.isSetDomain() && model.getDomain().isSetName()) {
staticVm.setdomain(model.getDomain().getName());
}
if (model.isSetTimezone()) {
staticVm.settime_zone(TimeZoneMapping.getWindows(model.getTimezone()));
}
return staticVm;
}
@Mapping(from = VmTemplate.class, to = Template.class)
public static Template map(VmTemplate entity, Template incoming) {
Template model = incoming != null ? incoming : new Template();
model.setId(entity.getId().toString());
model.setName(entity.getname());
model.setDescription(entity.getdescription());
model.setMemory((long)entity.getmem_size_mb() * BYTES_PER_MB);
model.setHighAvailability(new HighAvailability());
model.getHighAvailability().setEnabled(entity.getauto_startup());
model.getHighAvailability().setPriority(entity.getpriority());
model.setStateless(entity.getis_stateless());
if (entity.getvm_type() != null) {
model.setType(VmMapper.map(entity.getvm_type(), null));
}
if (entity.getorigin() != null) {
model.setOrigin(VmMapper.map(entity.getorigin(), null));
}
if (entity.getstatus() != null) {
model.setStatus(StatusUtils.create(map(entity.getstatus(), null)));
}
if (entity.getos() != null ||
entity.getdefault_boot_sequence() != null ||
entity.getkernel_url() != null ||
entity.getinitrd_url() != null ||
entity.getkernel_params() != null) {
OperatingSystem os = new OperatingSystem();
if (entity.getos() != null) {
OsType osType = VmMapper.map(entity.getos(), null);
if (osType != null) {
os.setType(osType.value());
}
}
if (entity.getdefault_boot_sequence() != null) {
for (Boot boot : VmMapper.map(entity.getdefault_boot_sequence(), null)) {
os.getBoot().add(boot);
}
}
os.setKernel(entity.getkernel_url());
os.setInitrd(entity.getinitrd_url());
os.setCmdline(entity.getkernel_params());
model.setOs(os);
}
if (entity.getvds_group_id() != null) {
Cluster cluster = new Cluster();
cluster.setId(entity.getvds_group_id().toString());
model.setCluster(cluster);
}
CpuTopology topology = new CpuTopology();
topology.setSockets(entity.getnum_of_sockets());
topology.setCores(entity.getnum_of_cpus() / entity.getnum_of_sockets());
model.setCpu(new CPU());
model.getCpu().setTopology(topology);
if (entity.getdefault_display_type() != null) {
model.setDisplay(new Display());
model.getDisplay().setType(VmMapper.map(entity.getdefault_display_type(), null));
model.getDisplay().setMonitors(entity.getnum_of_monitors());
model.getDisplay().setAllowOverride(entity.getAllowConsoleReconnect());
}
if (entity.getcreation_date() != null) {
model.setCreationTime(DateMapper.map(entity.getcreation_date(), null));
}
if (entity.getdomain()!=null && !entity.getdomain().isEmpty()) {
Domain domain = new Domain();
domain.setName(entity.getdomain());
model.setDomain(domain);
}
if (entity.getusb_policy()!=null) {
Usb usb = new Usb();
usb.setEnabled(UsbMapperUtils.getIsUsbEnabled(entity.getusb_policy()));
UsbType usbType = UsbMapperUtils.getUsbType(entity.getusb_policy());
if (usbType != null) {
usb.setType(usbType.value());
}
model.setUsb(usb);
}
model.setTimezone(TimeZoneMapping.getJava(entity.gettime_zone()));
return model;
}
@Mapping(from = VmTemplateStatus.class, to = TemplateStatus.class)
public static TemplateStatus map(VmTemplateStatus entityStatus, TemplateStatus incoming) {
switch (entityStatus) {
case OK:
return TemplateStatus.OK;
case Locked:
return TemplateStatus.LOCKED;
case Illegal:
return TemplateStatus.ILLEGAL;
default:
return null;
}
}
}
| |
/**
* 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.hadoop.yarn.server.nodemanager;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.hadoop.classification.InterfaceAudience.Private;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileContext;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.LocalDirAllocator;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.permission.FsPermission;
import org.apache.hadoop.service.AbstractService;
import org.apache.hadoop.util.StringUtils;
import org.apache.hadoop.yarn.conf.YarnConfiguration;
import org.apache.hadoop.yarn.exceptions.YarnRuntimeException;
import org.apache.hadoop.yarn.server.nodemanager.DirectoryCollection.DirsChangeListener;
import org.apache.hadoop.yarn.server.nodemanager.metrics.NodeManagerMetrics;
/**
* The class which provides functionality of checking the health of the local
* directories of a node. This specifically manages nodemanager-local-dirs and
* nodemanager-log-dirs by periodically checking their health.
*/
public class LocalDirsHandlerService extends AbstractService {
private static final Logger LOG =
LoggerFactory.getLogger(LocalDirsHandlerService.class);
private static final String diskCapacityExceededErrorMsg = "usable space is below configured utilization percentage/no more usable space";
/**
* Good local directories, use internally,
* initial value is the same as NM_LOCAL_DIRS.
*/
@Private
static final String NM_GOOD_LOCAL_DIRS =
YarnConfiguration.NM_PREFIX + "good-local-dirs";
/**
* Good log directories, use internally,
* initial value is the same as NM_LOG_DIRS.
*/
@Private
static final String NM_GOOD_LOG_DIRS =
YarnConfiguration.NM_PREFIX + "good-log-dirs";
/** Timer used to schedule disk health monitoring code execution */
private Timer dirsHandlerScheduler;
private long diskHealthCheckInterval;
private boolean isDiskHealthCheckerEnabled;
/**
* Minimum fraction of disks to be healthy for the node to be healthy in
* terms of disks. This applies to nm-local-dirs and nm-log-dirs.
*/
private float minNeededHealthyDisksFactor;
private MonitoringTimerTask monitoringTimerTask;
/** Local dirs to store localized files in */
private DirectoryCollection localDirs = null;
/** storage for container logs*/
private DirectoryCollection logDirs = null;
/**
* Everybody should go through this LocalDirAllocator object for read/write
* of any local path corresponding to {@link YarnConfiguration#NM_LOCAL_DIRS}
* instead of creating his/her own LocalDirAllocator objects
*/
private LocalDirAllocator localDirsAllocator;
/**
* Everybody should go through this LocalDirAllocator object for read/write
* of any local path corresponding to {@link YarnConfiguration#NM_LOG_DIRS}
* instead of creating his/her own LocalDirAllocator objects
*/
private LocalDirAllocator logDirsAllocator;
/** when disk health checking code was last run */
private long lastDisksCheckTime;
private static String FILE_SCHEME = "file";
private NodeManagerMetrics nodeManagerMetrics = null;
/**
* Class which is used by the {@link Timer} class to periodically execute the
* disks' health checker code.
*/
private final class MonitoringTimerTask extends TimerTask {
public MonitoringTimerTask(Configuration conf) throws YarnRuntimeException {
float highUsableSpacePercentagePerDisk =
conf.getFloat(
YarnConfiguration.NM_MAX_PER_DISK_UTILIZATION_PERCENTAGE,
YarnConfiguration.DEFAULT_NM_MAX_PER_DISK_UTILIZATION_PERCENTAGE);
float lowUsableSpacePercentagePerDisk =
conf.getFloat(
YarnConfiguration.NM_WM_LOW_PER_DISK_UTILIZATION_PERCENTAGE,
highUsableSpacePercentagePerDisk);
if (lowUsableSpacePercentagePerDisk > highUsableSpacePercentagePerDisk) {
LOG.warn("Using " + YarnConfiguration.
NM_MAX_PER_DISK_UTILIZATION_PERCENTAGE + " as " +
YarnConfiguration.NM_WM_LOW_PER_DISK_UTILIZATION_PERCENTAGE +
", because " + YarnConfiguration.
NM_WM_LOW_PER_DISK_UTILIZATION_PERCENTAGE +
" is not configured properly.");
lowUsableSpacePercentagePerDisk = highUsableSpacePercentagePerDisk;
}
long minFreeSpacePerDiskMB =
conf.getLong(YarnConfiguration.NM_MIN_PER_DISK_FREE_SPACE_MB,
YarnConfiguration.DEFAULT_NM_MIN_PER_DISK_FREE_SPACE_MB);
localDirs =
new DirectoryCollection(
validatePaths(conf
.getTrimmedStrings(YarnConfiguration.NM_LOCAL_DIRS)),
highUsableSpacePercentagePerDisk,
lowUsableSpacePercentagePerDisk,
minFreeSpacePerDiskMB);
logDirs =
new DirectoryCollection(
validatePaths(conf
.getTrimmedStrings(YarnConfiguration.NM_LOG_DIRS)),
highUsableSpacePercentagePerDisk,
lowUsableSpacePercentagePerDisk,
minFreeSpacePerDiskMB);
String local = conf.get(YarnConfiguration.NM_LOCAL_DIRS);
conf.set(NM_GOOD_LOCAL_DIRS,
(local != null) ? local : "");
localDirsAllocator = new LocalDirAllocator(
NM_GOOD_LOCAL_DIRS);
String log = conf.get(YarnConfiguration.NM_LOG_DIRS);
conf.set(NM_GOOD_LOG_DIRS,
(log != null) ? log : "");
logDirsAllocator = new LocalDirAllocator(
NM_GOOD_LOG_DIRS);
}
@Override
public void run() {
try {
checkDirs();
} catch (Throwable t) {
// Prevent uncaught exceptions from killing this thread
LOG.warn("Error while checking local directories: ", t);
}
}
}
public LocalDirsHandlerService() {
this(null);
}
public LocalDirsHandlerService(NodeManagerMetrics nodeManagerMetrics) {
super(LocalDirsHandlerService.class.getName());
this.nodeManagerMetrics = nodeManagerMetrics;
}
/**
* Method which initializes the timertask and its interval time.
*
*/
@Override
protected void serviceInit(Configuration config) throws Exception {
// Clone the configuration as we may do modifications to dirs-list
Configuration conf = new Configuration(config);
diskHealthCheckInterval = conf.getLong(
YarnConfiguration.NM_DISK_HEALTH_CHECK_INTERVAL_MS,
YarnConfiguration.DEFAULT_NM_DISK_HEALTH_CHECK_INTERVAL_MS);
monitoringTimerTask = new MonitoringTimerTask(conf);
isDiskHealthCheckerEnabled = conf.getBoolean(
YarnConfiguration.NM_DISK_HEALTH_CHECK_ENABLE, true);
minNeededHealthyDisksFactor = conf.getFloat(
YarnConfiguration.NM_MIN_HEALTHY_DISKS_FRACTION,
YarnConfiguration.DEFAULT_NM_MIN_HEALTHY_DISKS_FRACTION);
lastDisksCheckTime = System.currentTimeMillis();
super.serviceInit(conf);
FileContext localFs;
try {
localFs = FileContext.getLocalFSFileContext(config);
} catch (IOException e) {
throw new YarnRuntimeException("Unable to get the local filesystem", e);
}
FsPermission perm = new FsPermission((short)0755);
boolean createSucceeded = localDirs.createNonExistentDirs(localFs, perm);
createSucceeded &= logDirs.createNonExistentDirs(localFs, perm);
if (!createSucceeded) {
updateDirsAfterTest();
}
// Check the disk health immediately to weed out bad directories
// before other init code attempts to use them.
checkDirs();
}
/**
* Method used to start the disk health monitoring, if enabled.
*/
@Override
protected void serviceStart() throws Exception {
if (isDiskHealthCheckerEnabled) {
dirsHandlerScheduler = new Timer("DiskHealthMonitor-Timer", true);
dirsHandlerScheduler.scheduleAtFixedRate(monitoringTimerTask,
diskHealthCheckInterval, diskHealthCheckInterval);
}
super.serviceStart();
}
/**
* Method used to terminate the disk health monitoring service.
*/
@Override
protected void serviceStop() throws Exception {
if (dirsHandlerScheduler != null) {
dirsHandlerScheduler.cancel();
}
super.serviceStop();
}
public void registerLocalDirsChangeListener(DirsChangeListener listener) {
localDirs.registerDirsChangeListener(listener);
}
public void registerLogDirsChangeListener(DirsChangeListener listener) {
logDirs.registerDirsChangeListener(listener);
}
public void deregisterLocalDirsChangeListener(DirsChangeListener listener) {
localDirs.deregisterDirsChangeListener(listener);
}
public void deregisterLogDirsChangeListener(DirsChangeListener listener) {
logDirs.deregisterDirsChangeListener(listener);
}
/**
* @return the good/valid local directories based on disks' health
*/
public List<String> getLocalDirs() {
return localDirs.getGoodDirs();
}
/**
* @return the good/valid log directories based on disks' health
*/
public List<String> getLogDirs() {
return logDirs.getGoodDirs();
}
/**
* @return the local directories which have no disk space
*/
public List<String> getDiskFullLocalDirs() {
return localDirs.getFullDirs();
}
/**
* @return the log directories that have no disk space
*/
public List<String> getDiskFullLogDirs() {
return logDirs.getFullDirs();
}
/**
* Function to get the local dirs which should be considered for reading
* existing files on disk. Contains the good local dirs and the local dirs
* that have reached the disk space limit
*
* @return the local dirs which should be considered for reading
*/
public List<String> getLocalDirsForRead() {
return DirectoryCollection.concat(localDirs.getGoodDirs(),
localDirs.getFullDirs());
}
/**
* Function to get the local dirs which should be considered when cleaning up
* resources. Contains the good local dirs and the local dirs that have reached
* the disk space limit
*
* @return the local dirs which should be considered for cleaning up
*/
public List<String> getLocalDirsForCleanup() {
return DirectoryCollection.concat(localDirs.getGoodDirs(),
localDirs.getFullDirs());
}
/**
* Function to get the log dirs which should be considered for reading
* existing files on disk. Contains the good log dirs and the log dirs that
* have reached the disk space limit
*
* @return the log dirs which should be considered for reading
*/
public List<String> getLogDirsForRead() {
return DirectoryCollection.concat(logDirs.getGoodDirs(),
logDirs.getFullDirs());
}
/**
* Function to get the log dirs which should be considered when cleaning up
* resources. Contains the good log dirs and the log dirs that have reached
* the disk space limit
*
* @return the log dirs which should be considered for cleaning up
*/
public List<String> getLogDirsForCleanup() {
return DirectoryCollection.concat(logDirs.getGoodDirs(),
logDirs.getFullDirs());
}
/**
* Function to generate a report on the state of the disks.
*
* @param listGoodDirs
* flag to determine whether the report should report the state of
* good dirs or failed dirs
* @return the health report of nm-local-dirs and nm-log-dirs
*/
public String getDisksHealthReport(boolean listGoodDirs) {
if (!isDiskHealthCheckerEnabled) {
return "";
}
StringBuilder report = new StringBuilder();
List<String> erroredLocalDirsList = localDirs.getErroredDirs();
List<String> erroredLogDirsList = logDirs.getErroredDirs();
List<String> diskFullLocalDirsList = localDirs.getFullDirs();
List<String> diskFullLogDirsList = logDirs.getFullDirs();
List<String> goodLocalDirsList = localDirs.getGoodDirs();
List<String> goodLogDirsList = logDirs.getGoodDirs();
int numLocalDirs = goodLocalDirsList.size() + erroredLocalDirsList.size() + diskFullLocalDirsList.size();
int numLogDirs = goodLogDirsList.size() + erroredLogDirsList.size() + diskFullLogDirsList.size();
if (!listGoodDirs) {
if (!erroredLocalDirsList.isEmpty()) {
report.append(erroredLocalDirsList.size() + "/" + numLocalDirs
+ " local-dirs have errors: "
+ buildDiskErrorReport(erroredLocalDirsList, localDirs));
}
if (!diskFullLocalDirsList.isEmpty()) {
report.append(diskFullLocalDirsList.size() + "/" + numLocalDirs
+ " local-dirs " + diskCapacityExceededErrorMsg
+ buildDiskErrorReport(diskFullLocalDirsList, localDirs) + "; ");
}
if (!erroredLogDirsList.isEmpty()) {
report.append(erroredLogDirsList.size() + "/" + numLogDirs
+ " log-dirs have errors: "
+ buildDiskErrorReport(erroredLogDirsList, logDirs));
}
if (!diskFullLogDirsList.isEmpty()) {
report.append(diskFullLogDirsList.size() + "/" + numLogDirs
+ " log-dirs " + diskCapacityExceededErrorMsg
+ buildDiskErrorReport(diskFullLogDirsList, logDirs));
}
} else {
report.append(goodLocalDirsList.size() + "/" + numLocalDirs
+ " local-dirs are good: " + StringUtils.join(",", goodLocalDirsList)
+ "; ");
report.append(goodLogDirsList.size() + "/" + numLogDirs
+ " log-dirs are good: " + StringUtils.join(",", goodLogDirsList));
}
return report.toString();
}
/**
* The minimum fraction of number of disks needed to be healthy for a node to
* be considered healthy in terms of disks is configured using
* {@link YarnConfiguration#NM_MIN_HEALTHY_DISKS_FRACTION}, with a default
* value of {@link YarnConfiguration#DEFAULT_NM_MIN_HEALTHY_DISKS_FRACTION}.
* @return <em>false</em> if either (a) more than the allowed percentage of
* nm-local-dirs failed or (b) more than the allowed percentage of
* nm-log-dirs failed.
*/
public boolean areDisksHealthy() {
if (!isDiskHealthCheckerEnabled) {
return true;
}
int goodDirs = getLocalDirs().size();
int failedDirs = localDirs.getFailedDirs().size();
int totalConfiguredDirs = goodDirs + failedDirs;
if (goodDirs/(float)totalConfiguredDirs < minNeededHealthyDisksFactor) {
return false; // Not enough healthy local-dirs
}
goodDirs = getLogDirs().size();
failedDirs = logDirs.getFailedDirs().size();
totalConfiguredDirs = goodDirs + failedDirs;
if (goodDirs/(float)totalConfiguredDirs < minNeededHealthyDisksFactor) {
return false; // Not enough healthy log-dirs
}
return true;
}
public long getLastDisksCheckTime() {
return lastDisksCheckTime;
}
public boolean isGoodLocalDir(String path) {
return isInGoodDirs(getLocalDirs(), path);
}
public boolean isGoodLogDir(String path) {
return isInGoodDirs(getLogDirs(), path);
}
private boolean isInGoodDirs(List<String> goodDirs, String path) {
for (String goodDir : goodDirs) {
if (path.startsWith(goodDir)) {
return true;
}
}
return false;
}
/**
* Set good local dirs and good log dirs in the configuration so that the
* LocalDirAllocator objects will use this updated configuration only.
*/
private void updateDirsAfterTest() {
Configuration conf = getConfig();
List<String> localDirs = getLocalDirs();
conf.setStrings(NM_GOOD_LOCAL_DIRS,
localDirs.toArray(new String[localDirs.size()]));
List<String> logDirs = getLogDirs();
conf.setStrings(NM_GOOD_LOG_DIRS,
logDirs.toArray(new String[logDirs.size()]));
if (!areDisksHealthy()) {
// Just log.
LOG.error("Most of the disks failed. " + getDisksHealthReport(false));
}
}
private void logDiskStatus(boolean newDiskFailure, boolean diskTurnedGood) {
if (newDiskFailure) {
String report = getDisksHealthReport(false);
LOG.info("Disk(s) failed: " + report);
}
if (diskTurnedGood) {
String report = getDisksHealthReport(true);
LOG.info("Disk(s) turned good: " + report);
}
}
private void checkDirs() {
boolean disksStatusChange = false;
Set<String> failedLocalDirsPreCheck =
new HashSet<String>(localDirs.getFailedDirs());
Set<String> failedLogDirsPreCheck =
new HashSet<String>(logDirs.getFailedDirs());
if (localDirs.checkDirs()) {
disksStatusChange = true;
}
if (logDirs.checkDirs()) {
disksStatusChange = true;
}
Set<String> failedLocalDirsPostCheck =
new HashSet<String>(localDirs.getFailedDirs());
Set<String> failedLogDirsPostCheck =
new HashSet<String>(logDirs.getFailedDirs());
boolean disksFailed = false;
boolean disksTurnedGood = false;
disksFailed =
disksTurnedBad(failedLocalDirsPreCheck, failedLocalDirsPostCheck);
disksTurnedGood =
disksTurnedGood(failedLocalDirsPreCheck, failedLocalDirsPostCheck);
// skip check if we have new failed or good local dirs since we're going to
// log anyway
if (!disksFailed) {
disksFailed =
disksTurnedBad(failedLogDirsPreCheck, failedLogDirsPostCheck);
}
if (!disksTurnedGood) {
disksTurnedGood =
disksTurnedGood(failedLogDirsPreCheck, failedLogDirsPostCheck);
}
logDiskStatus(disksFailed, disksTurnedGood);
if (disksStatusChange) {
updateDirsAfterTest();
}
updateMetrics();
lastDisksCheckTime = System.currentTimeMillis();
}
private boolean disksTurnedBad(Set<String> preCheckFailedDirs,
Set<String> postCheckDirs) {
boolean disksFailed = false;
for (String dir : postCheckDirs) {
if (!preCheckFailedDirs.contains(dir)) {
disksFailed = true;
break;
}
}
return disksFailed;
}
private boolean disksTurnedGood(Set<String> preCheckDirs,
Set<String> postCheckDirs) {
boolean disksTurnedGood = false;
for (String dir : preCheckDirs) {
if (!postCheckDirs.contains(dir)) {
disksTurnedGood = true;
break;
}
}
return disksTurnedGood;
}
private Path getPathToRead(String pathStr, List<String> dirs)
throws IOException {
// remove the leading slash from the path (to make sure that the uri
// resolution results in a valid path on the dir being checked)
if (pathStr.startsWith("/")) {
pathStr = pathStr.substring(1);
}
FileSystem localFS = FileSystem.getLocal(getConfig());
for (String dir : dirs) {
try {
Path tmpDir = new Path(dir);
File tmpFile = tmpDir.isAbsolute()
? new File(localFS.makeQualified(tmpDir).toUri())
: new File(dir);
Path file = new Path(tmpFile.getPath(), pathStr);
if (localFS.exists(file)) {
return file;
}
} catch (IOException ie) {
// ignore
LOG.warn("Failed to find " + pathStr + " at " + dir, ie);
}
}
throw new IOException("Could not find " + pathStr + " in any of" +
" the directories");
}
public Path getLocalPathForWrite(String pathStr) throws IOException {
return localDirsAllocator.getLocalPathForWrite(pathStr, getConfig());
}
public Path getLocalPathForWrite(String pathStr, long size,
boolean checkWrite) throws IOException {
return localDirsAllocator.getLocalPathForWrite(pathStr, size, getConfig(),
checkWrite);
}
public Path getLocalPathForRead(String pathStr) throws IOException {
return getPathToRead(pathStr, getLocalDirsForRead());
}
public Path getLogPathForWrite(String pathStr, boolean checkWrite)
throws IOException {
return logDirsAllocator.getLocalPathForWrite(pathStr,
LocalDirAllocator.SIZE_UNKNOWN, getConfig(), checkWrite);
}
public Path getLogPathToRead(String pathStr) throws IOException {
return getPathToRead(pathStr, getLogDirsForRead());
}
public static String[] validatePaths(String[] paths) {
ArrayList<String> validPaths = new ArrayList<String>();
for (int i = 0; i < paths.length; ++i) {
try {
URI uriPath = (new Path(paths[i])).toUri();
if (uriPath.getScheme() == null
|| uriPath.getScheme().equals(FILE_SCHEME)) {
validPaths.add(new Path(uriPath.getPath()).toString());
} else {
LOG.warn(paths[i] + " is not a valid path. Path should be with "
+ FILE_SCHEME + " scheme or without scheme");
throw new YarnRuntimeException(paths[i]
+ " is not a valid path. Path should be with " + FILE_SCHEME
+ " scheme or without scheme");
}
} catch (IllegalArgumentException e) {
LOG.warn(e.getMessage());
throw new YarnRuntimeException(paths[i]
+ " is not a valid path. Path should be with " + FILE_SCHEME
+ " scheme or without scheme");
}
}
String[] arrValidPaths = new String[validPaths.size()];
validPaths.toArray(arrValidPaths);
return arrValidPaths;
}
protected void updateMetrics() {
if (nodeManagerMetrics != null) {
nodeManagerMetrics.setBadLocalDirs(localDirs.getFailedDirs().size());
nodeManagerMetrics.setBadLogDirs(logDirs.getFailedDirs().size());
nodeManagerMetrics.setGoodLocalDirsDiskUtilizationPerc(
localDirs.getGoodDirsDiskUtilizationPercentage());
nodeManagerMetrics.setGoodLogDirsDiskUtilizationPerc(
logDirs.getGoodDirsDiskUtilizationPercentage());
}
}
private String buildDiskErrorReport(List<String> dirs, DirectoryCollection directoryCollection) {
StringBuilder sb = new StringBuilder();
sb.append(" [ ");
for (int i = 0; i < dirs.size(); i++) {
final String dirName = dirs.get(i);
if ( directoryCollection.isDiskUnHealthy(dirName)) {
sb.append(dirName + " : " + directoryCollection.getDirectoryErrorInfo(dirName).message);
} else {
sb.append(dirName + " : " + "Unknown cause for disk error");
}
if ( i != (dirs.size() - 1)) {
sb.append(" , ");
}
}
sb.append(" ] ");
return sb.toString();
}
}
| |
/*
* Copyright 2010 JBoss 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.drools.impl;
import org.drools.RuleBase;
import org.drools.SessionConfiguration;
import org.drools.StatefulSession;
import org.drools.common.InternalRuleBase;
import org.drools.definitions.impl.KnowledgePackageImp;
import org.drools.definitions.rule.impl.RuleImpl;
import org.drools.event.AfterFunctionRemovedEvent;
import org.drools.event.AfterPackageAddedEvent;
import org.drools.event.AfterPackageRemovedEvent;
import org.drools.event.AfterProcessAddedEvent;
import org.drools.event.AfterProcessRemovedEvent;
import org.drools.event.AfterRuleAddedEvent;
import org.drools.event.AfterRuleBaseLockedEvent;
import org.drools.event.AfterRuleBaseUnlockedEvent;
import org.drools.event.AfterRuleRemovedEvent;
import org.drools.event.BeforeFunctionRemovedEvent;
import org.drools.event.BeforePackageAddedEvent;
import org.drools.event.BeforePackageRemovedEvent;
import org.drools.event.BeforeProcessAddedEvent;
import org.drools.event.BeforeProcessRemovedEvent;
import org.drools.event.BeforeRuleAddedEvent;
import org.drools.event.BeforeRuleBaseLockedEvent;
import org.drools.event.BeforeRuleBaseUnlockedEvent;
import org.drools.event.BeforeRuleRemovedEvent;
import org.drools.event.knowlegebase.impl.AfterFunctionRemovedEventImpl;
import org.drools.event.knowlegebase.impl.AfterKiePackageAddedEventImpl;
import org.drools.event.knowlegebase.impl.AfterKiePackageRemovedEventImpl;
import org.drools.event.knowlegebase.impl.AfterKnowledgeBaseLockedEventImpl;
import org.drools.event.knowlegebase.impl.AfterKnowledgeBaseUnlockedEventImpl;
import org.drools.event.knowlegebase.impl.AfterProcessAddedEventImpl;
import org.drools.event.knowlegebase.impl.AfterProcessRemovedEventImpl;
import org.drools.event.knowlegebase.impl.AfterRuleAddedEventImpl;
import org.drools.event.knowlegebase.impl.AfterRuleRemovedEventImpl;
import org.drools.event.knowlegebase.impl.BeforeFunctionRemovedEventImpl;
import org.drools.event.knowlegebase.impl.BeforeKiePackageAddedEventImpl;
import org.drools.event.knowlegebase.impl.BeforeKiePackageRemovedEventImpl;
import org.drools.event.knowlegebase.impl.BeforeKnowledgeBaseLockedEventImpl;
import org.drools.event.knowlegebase.impl.BeforeKnowledgeBaseUnlockedEventImpl;
import org.drools.event.knowlegebase.impl.BeforeProcessAddedEventImpl;
import org.drools.event.knowlegebase.impl.BeforeProcessRemovedEventImpl;
import org.drools.event.knowlegebase.impl.BeforeRuleAddedEventImpl;
import org.drools.event.knowlegebase.impl.BeforeRuleRemovedEventImpl;
import org.drools.reteoo.ReteooRuleBase;
import org.drools.reteoo.ReteooStatefulSession;
import org.drools.rule.Package;
import org.kie.KnowledgeBase;
import org.kie.definition.KiePackage;
import org.kie.definition.KnowledgePackage;
import org.kie.definition.process.Process;
import org.kie.definition.rule.Query;
import org.kie.definition.rule.Rule;
import org.kie.definition.type.FactType;
import org.kie.event.kiebase.KieBaseEventListener;
import org.kie.runtime.Environment;
import org.kie.runtime.KieSession;
import org.kie.runtime.KieSessionConfiguration;
import org.kie.runtime.StatefulKnowledgeSession;
import org.kie.runtime.StatelessKieSession;
import org.kie.runtime.StatelessKnowledgeSession;
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class KnowledgeBaseImpl
implements
InternalKnowledgeBase,
Externalizable {
public RuleBase ruleBase;
// This is just a hack, so spring can find the list of generated classes
public List<List<String>> jaxbClasses;
public Map<KieBaseEventListener, KnowledgeBaseEventListenerWrapper> mappedKnowledgeBaseListeners;
public KnowledgeBaseImpl() {
}
public KnowledgeBaseImpl(RuleBase ruleBase) {
this.ruleBase = ruleBase;
this.mappedKnowledgeBaseListeners = new HashMap<KieBaseEventListener, KnowledgeBaseEventListenerWrapper>();
}
public void writeExternal(ObjectOutput out) throws IOException {
this.ruleBase.writeExternal( out );
}
public void readExternal(ObjectInput in) throws IOException,
ClassNotFoundException {
ruleBase = new ReteooRuleBase();
ruleBase.readExternal( in );
}
public RuleBase getRuleBase() {
return ruleBase;
}
public void addEventListener(KieBaseEventListener listener) {
if (!mappedKnowledgeBaseListeners.containsKey(listener)) {
KnowledgeBaseEventListenerWrapper wrapper = new KnowledgeBaseEventListenerWrapper( this, listener );
mappedKnowledgeBaseListeners.put( listener, wrapper );
ruleBase.addEventListener( wrapper );
}
}
public void removeEventListener(KieBaseEventListener listener) {
KnowledgeBaseEventListenerWrapper wrapper = this.mappedKnowledgeBaseListeners.remove( listener );
this.ruleBase.removeEventListener( wrapper );
}
public Collection<KieBaseEventListener> getKieBaseEventListeners() {
return Collections.unmodifiableCollection( this.mappedKnowledgeBaseListeners.keySet() );
}
public void addKnowledgePackage(KnowledgePackage knowledgePackage) {
ruleBase.addPackage( ((KnowledgePackageImp) knowledgePackage).pkg );
}
public void addKnowledgePackages(Collection<KnowledgePackage> knowledgePackages) {
List<Package> list = new ArrayList<Package>();
for ( KnowledgePackage knowledgePackage : knowledgePackages ) {
list.add( ((KnowledgePackageImp) knowledgePackage).pkg );
}
((ReteooRuleBase)ruleBase).addPackages( list);
}
public Collection<KnowledgePackage> getKnowledgePackages() {
Package[] pkgs = ruleBase.getPackages();
List<KnowledgePackage> list = new ArrayList<KnowledgePackage>( pkgs.length );
for ( Package pkg : pkgs ) {
list.add( new KnowledgePackageImp( pkg ) );
}
return list;
}
public StatefulKnowledgeSession newStatefulKnowledgeSession() {
return newStatefulKnowledgeSession(null, EnvironmentFactory.newEnvironment() );
}
public StatefulKnowledgeSession newStatefulKnowledgeSession(KieSessionConfiguration conf, Environment environment) {
// NOTE if you update here, you'll also need to update the JPAService
if ( conf == null ) {
conf = SessionConfiguration.getDefaultInstance();
}
if ( environment == null ) {
environment = EnvironmentFactory.newEnvironment();
}
ReteooStatefulSession session = (ReteooStatefulSession) this.ruleBase.newStatefulSession( (SessionConfiguration) conf, environment );
return (StatefulKnowledgeSession) session.getKnowledgeRuntime();
}
public Collection<StatefulKnowledgeSession> getStatefulKnowledgeSessions()
{
Collection<StatefulKnowledgeSession> c = new ArrayList<StatefulKnowledgeSession>();
StatefulSession[] sss = this.ruleBase.getStatefulSessions();
if (sss != null) {
for (StatefulSession ss : sss) {
if (ss instanceof ReteooStatefulSession) {
c.add(new StatefulKnowledgeSessionImpl((ReteooStatefulSession)ss, this));
}
}
}
return c;
}
public StatelessKnowledgeSession newStatelessKnowledgeSession() {
return new StatelessKnowledgeSessionImpl( (InternalRuleBase) this.ruleBase, null, null );
}
public StatelessKnowledgeSession newStatelessKnowledgeSession(KieSessionConfiguration conf) {
return new StatelessKnowledgeSessionImpl( (InternalRuleBase) this.ruleBase, null, conf );
}
public void removeKnowledgePackage(String packageName) {
this.ruleBase.removePackage( packageName );
}
public void removeRule(String packageName,
String ruleName) {
this.ruleBase.removeRule( packageName,
ruleName );
}
public void removeQuery(String packageName,
String queryName) {
this.ruleBase.removeQuery( packageName,
queryName );
}
public void removeFunction(String packageName,
String ruleName) {
this.ruleBase.removeFunction( packageName,
ruleName );
}
public void removeProcess(String processId) {
this.ruleBase.removeProcess( processId );
}
public FactType getFactType(String packageName,
String typeName) {
return this.ruleBase.getFactType(packageName + "." + typeName);
}
public KnowledgePackage getKnowledgePackage(String packageName) {
Package pkg = this.ruleBase.getPackage( packageName );
if ( pkg != null ) {
return new KnowledgePackageImp( pkg );
} else {
return null;
}
}
public Process getProcess(String processId) {
return ((InternalRuleBase) this.ruleBase).getProcess(processId);
}
public Collection<Process> getProcesses() {
return Arrays.asList(((InternalRuleBase) this.ruleBase).getProcesses());
}
public Rule getRule(String packageName,
String ruleName) {
Package p = this.ruleBase.getPackage( packageName );
return p == null ? null : p.getRule( ruleName );
}
public Query getQuery(String packageName,
String queryName) {
return ( Query ) this.ruleBase.getPackage( packageName ).getRule( queryName );
}
public Set<String> getEntryPointIds() {
return this.ruleBase.getEntryPointIds();
}
public static class KnowledgeBaseEventListenerWrapper
implements
org.drools.event.RuleBaseEventListener {
private KieBaseEventListener listener;
private KnowledgeBase kbase;
public void readExternal(ObjectInput in) throws IOException,
ClassNotFoundException {
}
public void writeExternal(ObjectOutput out) throws IOException {
// TODO Auto-generated method stub
}
public KnowledgeBaseEventListenerWrapper(KnowledgeBase kbase,
KieBaseEventListener listener) {
this.listener = listener;
}
public void afterFunctionRemoved(AfterFunctionRemovedEvent event) {
this.listener.afterFunctionRemoved( new AfterFunctionRemovedEventImpl( this.kbase,
event.getFunction() ) );
}
public void afterPackageAdded(AfterPackageAddedEvent event) {
this.listener.afterKiePackageAdded(new AfterKiePackageAddedEventImpl(this.kbase,
new KnowledgePackageImp(event.getPackage())));
}
public void afterPackageRemoved(AfterPackageRemovedEvent event) {
this.listener.afterKiePackageRemoved(new AfterKiePackageRemovedEventImpl(this.kbase,
new KnowledgePackageImp(event.getPackage())));
}
public void afterRuleAdded(AfterRuleAddedEvent event) {
this.listener.afterRuleAdded( new AfterRuleAddedEventImpl( this.kbase,
new RuleImpl( event.getRule() ) ) );
}
public void afterRuleBaseLocked(AfterRuleBaseLockedEvent event) {
this.listener.afterKieBaseLocked(new AfterKnowledgeBaseLockedEventImpl(this.kbase));
}
public void afterRuleBaseUnlocked(AfterRuleBaseUnlockedEvent event) {
this.listener.afterKieBaseUnlocked(new AfterKnowledgeBaseUnlockedEventImpl(this.kbase));
}
public void afterRuleRemoved(AfterRuleRemovedEvent event) {
this.listener.afterRuleRemoved( new AfterRuleRemovedEventImpl( this.kbase,
new RuleImpl( event.getRule() ) ) );
}
public void beforeFunctionRemoved(BeforeFunctionRemovedEvent event) {
this.listener.beforeFunctionRemoved( new BeforeFunctionRemovedEventImpl( this.kbase,
event.getFunction() ) );
}
public void beforePackageAdded(BeforePackageAddedEvent event) {
this.listener.beforeKiePackageAdded(new BeforeKiePackageAddedEventImpl(this.kbase,
new KnowledgePackageImp(event.getPackage())));
}
public void beforePackageRemoved(BeforePackageRemovedEvent event) {
this.listener.beforeKiePackageRemoved(new BeforeKiePackageRemovedEventImpl(this.kbase,
new KnowledgePackageImp(event.getPackage())));
}
public void beforeRuleAdded(BeforeRuleAddedEvent event) {
this.listener.beforeRuleAdded( new BeforeRuleAddedEventImpl( this.kbase,
new RuleImpl( event.getRule() ) ) );
}
public void beforeRuleBaseLocked(BeforeRuleBaseLockedEvent event) {
this.listener.beforeKieBaseLocked(new BeforeKnowledgeBaseLockedEventImpl(this.kbase));
}
public void beforeRuleBaseUnlocked(BeforeRuleBaseUnlockedEvent event) {
this.listener.beforeKieBaseUnlocked(new BeforeKnowledgeBaseUnlockedEventImpl(this.kbase));
}
public void beforeRuleRemoved(BeforeRuleRemovedEvent event) {
this.listener.beforeRuleRemoved( new BeforeRuleRemovedEventImpl( this.kbase,
new RuleImpl( event.getRule() ) ) );
}
public void beforeProcessAdded(BeforeProcessAddedEvent event) {
this.listener.beforeProcessAdded(new BeforeProcessAddedEventImpl( this.kbase,
event.getProcess() ));
}
public void afterProcessAdded(AfterProcessAddedEvent event) {
this.listener.afterProcessAdded(new AfterProcessAddedEventImpl( this.kbase,
event.getProcess() ));
}
public void beforeProcessRemoved(BeforeProcessRemovedEvent event) {
this.listener.beforeProcessRemoved(new BeforeProcessRemovedEventImpl( this.kbase,
event.getProcess() ));
}
public void afterProcessRemoved(AfterProcessRemovedEvent event) {
this.listener.afterProcessRemoved(new AfterProcessRemovedEventImpl( this.kbase,
event.getProcess() ));
}
}
public KieSession newKieSession(KieSessionConfiguration conf,
Environment environment) {
return newStatefulKnowledgeSession( conf, environment );
}
public KieSession newKieSession() {
return newStatefulKnowledgeSession();
}
public Collection<? extends KieSession> getKieSessions() {
return getStatefulKnowledgeSessions();
}
public StatelessKieSession newStatelessKieSession(KieSessionConfiguration conf) {
return newStatelessKnowledgeSession( conf );
}
public StatelessKieSession newStatelessKieSession() {
return newStatelessKnowledgeSession();
}
public Collection<KiePackage> getKiePackages() {
Object o = getKnowledgePackages();
return (Collection<KiePackage>) o;
}
public KiePackage getKiePackage(String packageName) {
return getKnowledgePackage(packageName);
}
public void removeKiePackage(String packageName) {
removeKnowledgePackage(packageName);
}
}
| |
package aQute.bnd.build;
import static aQute.lib.exceptions.BiFunctionWithException.asBiFunction;
import static java.lang.invoke.MethodHandles.publicLookup;
import static java.lang.invoke.MethodType.methodType;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.invoke.MethodType;
import java.lang.ref.WeakReference;
import java.net.URI;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.FileTime;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Formatter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;
import java.util.SortedSet;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.jar.JarEntry;
import java.util.jar.JarInputStream;
import java.util.jar.Manifest;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.osgi.service.repository.Repository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import aQute.bnd.annotation.plugin.BndPlugin;
import aQute.bnd.exporter.executable.ExecutableJarExporter;
import aQute.bnd.exporter.runbundles.RunbundlesExporter;
import aQute.bnd.header.Attrs;
import aQute.bnd.header.OSGiHeader;
import aQute.bnd.header.Parameters;
import aQute.bnd.http.HttpClient;
import aQute.bnd.maven.support.Maven;
import aQute.bnd.osgi.About;
import aQute.bnd.osgi.BundleId;
import aQute.bnd.osgi.Constants;
import aQute.bnd.osgi.Macro;
import aQute.bnd.osgi.Processor;
import aQute.bnd.osgi.Resource;
import aQute.bnd.osgi.Verifier;
import aQute.bnd.osgi.repository.AggregateRepository;
import aQute.bnd.osgi.repository.AugmentRepository;
import aQute.bnd.remoteworkspace.server.RemoteWorkspaceServer;
import aQute.bnd.resource.repository.ResourceRepositoryImpl;
import aQute.bnd.service.BndListener;
import aQute.bnd.service.RepositoryListenerPlugin;
import aQute.bnd.service.RepositoryPlugin;
import aQute.bnd.service.action.Action;
import aQute.bnd.service.extension.ExtensionActivator;
import aQute.bnd.service.lifecycle.LifeCyclePlugin;
import aQute.bnd.service.repository.Prepare;
import aQute.bnd.service.repository.RepositoryDigest;
import aQute.bnd.service.repository.SearchableRepository.ResourceDescriptor;
import aQute.bnd.service.result.Result;
import aQute.bnd.stream.MapStream;
import aQute.bnd.url.MultiURLConnectionHandler;
import aQute.bnd.util.home.Home;
import aQute.bnd.version.Version;
import aQute.bnd.version.VersionRange;
import aQute.lib.collections.Iterables;
import aQute.lib.deployer.FileRepo;
import aQute.lib.hex.Hex;
import aQute.lib.io.IO;
import aQute.lib.io.IOConstants;
import aQute.lib.io.NonClosingInputStream;
import aQute.lib.lazy.Lazy;
import aQute.lib.settings.Settings;
import aQute.lib.strings.Strings;
import aQute.lib.utf8properties.UTF8Properties;
import aQute.lib.zip.ZipUtil;
import aQute.libg.glob.Glob;
import aQute.libg.uri.URIUtil;
import aQute.service.reporter.Reporter;
public class Workspace extends Processor {
private final static Logger logger = LoggerFactory.getLogger(Workspace.class);
public static final File BND_DEFAULT_WS = IO.getFile(Home.getUserHomeBnd() + "/default-ws");
public static final String BND_CACHE_REPONAME = "bnd-cache";
public static final String EXT = "ext";
public static final String BUILDFILE = "build.bnd";
public static final String CNFDIR = "cnf";
public static final String BNDDIR = "bnd";
public static final String CACHEDIR = "cache/" + About.CURRENT;
public static final String STANDALONE_REPO_CLASS = "aQute.bnd.repository.osgi.OSGiRepository";
static final int BUFFER_SIZE = IOConstants.PAGE_SIZE * 16;
private static final String PLUGIN_STANDALONE = Constants.PLUGIN + ".standalone_";
class WorkspaceData {
List<RepositoryPlugin> repositories;
RemoteWorkspaceServer remoteServer;
Lazy<ClassIndex> classIndex = new Lazy<ClassIndex>(() -> new ClassIndex(Workspace.this));
}
private final static Map<File, WeakReference<Workspace>> cache = newHashMap();
static Processor defaults = null;
final Map<String, Action> commands = newMap();
final Maven maven;
private final AtomicBoolean offline = new AtomicBoolean();
Settings settings = new Settings(
Home.getUserHomeBnd() + "/settings.json");
WorkspaceRepository workspaceRepo = new WorkspaceRepository(this);
static String overallDriver = "unset";
static Parameters overallGestalt = new Parameters();
/**
* Signal a BndListener plugin. We ran an infinite bug loop :-(
*/
final ThreadLocal<Reporter> signalBusy = new ThreadLocal<>();
ResourceRepositoryImpl resourceRepositoryImpl;
private Parameters gestalt;
private String driver;
private final WorkspaceLayout layout;
final Set<Project> trail = Collections
.newSetFromMap(new ConcurrentHashMap<Project, Boolean>());
private WorkspaceData data = new WorkspaceData();
private File buildDir;
private final ProjectTracker projects;
private final ReadWriteLock lock = new ReentrantReadWriteLock(true);
public static boolean remoteWorkspaces = false;
/**
* This static method finds the workspace and creates a project (or returns
* an existing project)
*
* @param projectDir
*/
public static Project getProject(File projectDir) throws Exception {
projectDir = projectDir.getAbsoluteFile();
assert projectDir.isDirectory();
Workspace ws = getWorkspace(projectDir.getParentFile());
return ws.getProject(projectDir.getName());
}
static synchronized public Processor getDefaults() {
if (defaults != null)
return defaults;
UTF8Properties props = new UTF8Properties();
try (InputStream propStream = Workspace.class.getResourceAsStream("defaults.bnd")) {
if (propStream != null) {
props.load(propStream);
} else {
System.err.println("Cannot load defaults");
}
} catch (IOException e) {
throw new IllegalArgumentException("Unable to load bnd defaults.", e);
}
defaults = new Processor(props, false);
return defaults;
}
public static Workspace createDefaultWorkspace() throws Exception {
File build = IO.getFile(BND_DEFAULT_WS, CNFDIR + "/" + BUILDFILE);
if (!build.exists()) {
build.getParentFile()
.mkdirs();
IO.store("", build);
}
Workspace ws = new Workspace(BND_DEFAULT_WS, CNFDIR);
return ws;
}
public static Workspace getWorkspace(File workspaceDir) throws Exception {
return getWorkspace(workspaceDir, CNFDIR);
}
public static Workspace getWorkspaceWithoutException(File workspaceDir) throws Exception {
try {
return getWorkspace(workspaceDir);
} catch (IllegalArgumentException e) {
return null;
}
}
/**
* /* Return the nearest workspace
*/
public static Workspace findWorkspace(File base) throws Exception {
File rover = base;
while (rover != null) {
File file = IO.getFile(rover, "cnf/build.bnd");
if (file.isFile())
return getWorkspace(rover);
rover = rover.getParentFile();
}
return null;
}
public static Workspace getWorkspace(File workspaceDir, String bndDir) throws Exception {
workspaceDir = workspaceDir.getAbsoluteFile();
// the cnf directory can actually be a
// file that redirects
while (workspaceDir.isDirectory()) {
File test = new File(workspaceDir, CNFDIR);
if (!test.exists())
test = new File(workspaceDir, bndDir);
if (test.isDirectory())
break;
if (test.isFile()) {
String redirect = IO.collect(test)
.trim();
test = getFile(test.getParentFile(), redirect).getAbsoluteFile();
workspaceDir = test;
}
if (!test.exists())
throw new IllegalArgumentException("No Workspace found from: " + workspaceDir);
}
synchronized (cache) {
WeakReference<Workspace> wsr = cache.get(workspaceDir);
Workspace ws;
if (wsr == null || (ws = wsr.get()) == null) {
ws = new Workspace(workspaceDir, bndDir);
cache.put(workspaceDir, new WeakReference<>(ws));
}
return ws;
}
}
public Workspace(File workspaceDir) throws Exception {
this(workspaceDir, CNFDIR);
}
public Workspace(File workspaceDir, String bndDir) throws Exception {
super(getDefaults());
this.maven = new Maven(Processor.getExecutor(), this);
this.layout = WorkspaceLayout.BND;
workspaceDir = workspaceDir.getAbsoluteFile();
setBase(workspaceDir); // setBase before call to setFileSystem
addBasicPlugin(new LoggingProgressPlugin());
setFileSystem(workspaceDir, bndDir);
projects = new ProjectTracker(this);
}
private Workspace(WorkspaceLayout layout) throws Exception {
super(getDefaults());
this.maven = new Maven(Processor.getExecutor(), this);
this.layout = layout;
setBuildDir(IO.getFile(BND_DEFAULT_WS, CNFDIR));
projects = new ProjectTracker(this);
}
public void setFileSystem(File workspaceDir, String bndDir) throws Exception {
workspaceDir = workspaceDir.getAbsoluteFile();
IO.mkdirs(workspaceDir);
assert workspaceDir.isDirectory();
synchronized (cache) {
WeakReference<Workspace> wsr = cache.get(getBase());
if ((wsr != null) && (wsr.get() == this)) {
cache.remove(getBase());
cache.put(workspaceDir, wsr);
}
}
File buildDir = new File(workspaceDir, bndDir).getAbsoluteFile();
if (!buildDir.isDirectory())
buildDir = new File(workspaceDir, CNFDIR).getAbsoluteFile();
setBuildDir(buildDir);
File buildFile = new File(buildDir, BUILDFILE).getAbsoluteFile();
if (!buildFile.isFile()) {
warning("No Build File in %s, creating it", workspaceDir);
IO.store("", buildFile);
}
setProperties(buildFile, workspaceDir);
propertiesChanged();
//
// There is a nasty bug/feature in Java that gives errors on our
// SSL use of github. The flag jsse.enableSNIExtension should be set
// to false. So here we provide a way to set system properties
// as early as possible
//
Attrs sysProps = OSGiHeader.parseProperties(mergeProperties(SYSTEMPROPERTIES));
sysProps.stream()
.forEachOrdered(System::setProperty);
}
public Project getProjectFromFile(File projectDir) {
projectDir = projectDir.getAbsoluteFile();
assert projectDir.isDirectory();
if (getBase().equals(projectDir.getParentFile())) {
return getProject(projectDir.getName());
}
return null;
}
public Project getProject(String bsn) {
return projects.getProject(bsn)
.orElse(null);
}
public boolean isPresent(String name) {
return projects.getProject(name)
.isPresent();
}
public Collection<Project> getCurrentProjects() {
return projects.getAllProjects();
}
@Override
public boolean refresh() {
data = new WorkspaceData();
gestalt = null;
if (super.refresh()) {
for (Project project : getCurrentProjects()) {
project.propertiesChanged();
}
return true;
}
return false;
}
/**
* Signal that the driver has detected a dynamic change in the workspace
* directory, for example a project was added or removed in the IDE. Since
* this does not affect the inherited properties we can only change the list
* of projects.
*/
public void refreshProjects() {
projects.refresh();
}
@Override
public void propertiesChanged() {
IO.close(data.remoteServer);
IO.close(data.classIndex);
data = new WorkspaceData();
File extDir = new File(getBuildDir(), EXT);
File[] extensions = extDir.listFiles();
if (extensions != null) {
for (File extension : extensions) {
String extensionName = extension.getName();
if (extensionName.endsWith(".bnd")) {
extensionName = extensionName.substring(0, extensionName.length() - ".bnd".length());
try {
doIncludeFile(extension, false, getProperties(), "ext." + extensionName);
} catch (Exception e) {
exception(e, "PropertiesChanged: %s", e);
}
}
}
}
if (remoteWorkspaces || Processor.isTrue(getProperty(Constants.REMOTEWORKSPACE))) {
try {
data.remoteServer = new RemoteWorkspaceServer(this);
} catch (IOException e) {
exception(e, "Could not create remote workspace %s", getBase());
}
}
super.propertiesChanged();
}
public String _workspace(@SuppressWarnings("unused") String args[]) {
return IO.absolutePath(getBase());
}
public void addCommand(String menu, Action action) {
commands.put(menu, action);
}
public void removeCommand(String menu) {
commands.remove(menu);
}
public void fillActions(Map<String, Action> all) {
all.putAll(commands);
}
public Collection<Project> getAllProjects() {
return projects.getAllProjects();
}
/**
* Inform any listeners that we changed a file (created/deleted/changed).
*
* @param f The changed file
*/
public void changedFile(File f) {
List<BndListener> listeners = getPlugins(BndListener.class);
for (BndListener l : listeners)
try {
l.changed(f);
} catch (Exception e) {
logger.debug("Exception in a BndListener changedFile method call", e);
}
}
public void bracket(boolean begin) {
List<BndListener> listeners = getPlugins(BndListener.class);
for (BndListener l : listeners)
try {
if (begin)
l.begin();
else
l.end();
} catch (Exception e) {
if (begin)
logger.debug("Exception in a BndListener begin method call", e);
else
logger.debug("Exception in a BndListener end method call", e);
}
}
public void signal(Reporter reporter) {
if (signalBusy.get() != null)
return;
signalBusy.set(reporter);
try {
List<BndListener> listeners = getPlugins(BndListener.class);
for (BndListener l : listeners)
try {
l.signal(this);
} catch (Exception e) {
logger.debug("Exception in a BndListener signal method call", e);
}
} catch (Exception e) {
// Ignore
} finally {
signalBusy.set(null);
}
}
@Override
public void signal() {
signal(this);
}
class CachedFileRepo extends FileRepo {
final Lock lock = new ReentrantLock();
boolean inited;
CachedFileRepo() {
super(BND_CACHE_REPONAME, getCache(BND_CACHE_REPONAME), false);
}
@Override
protected boolean init() throws Exception {
if (lock.tryLock(50, TimeUnit.SECONDS)) {
try {
if (super.init()) {
inited = true;
IO.mkdirs(root);
if (!root.isDirectory())
throw new IllegalArgumentException("Cache directory " + root + " not a directory");
URL url = getClass().getResource(EMBEDDED_REPO);
if (url != null) {
try (Resource resource = Resource.fromURL(url);
InputStream in = resource.openInputStream()) {
if (in != null) {
unzip(in, root.toPath());
return true;
}
}
}
error("Could not find " + EMBEDDED_REPO + " as a resource on the classpath");
}
return false;
} finally {
lock.unlock();
}
} else {
throw new TimeoutException("Cannot acquire Cached File Repo lock");
}
}
private void unzip(InputStream in, Path dir) throws Exception {
try (JarInputStream jin = new JarInputStream(in)) {
FileTime modifiedTime = FileTime.fromMillis(System.currentTimeMillis());
Manifest manifest = jin.getManifest();
if (manifest != null) {
String timestamp = manifest.getMainAttributes()
.getValue("Timestamp");
if (timestamp != null) {
// truncate to seconds since file system can discard
// milliseconds
long seconds = TimeUnit.MILLISECONDS.toSeconds(Long.parseLong(timestamp));
modifiedTime = FileTime.from(seconds, TimeUnit.SECONDS);
}
}
for (JarEntry jentry; (jentry = jin.getNextJarEntry()) != null;) {
if (jentry.isDirectory()) {
continue;
}
String jentryName = ZipUtil.cleanPath(jentry.getName());
if (jentryName.startsWith("META-INF/")) {
continue;
}
Path dest = IO.getBasedPath(dir, jentryName);
if (!Files.isRegularFile(dest) || Files.getLastModifiedTime(dest)
.compareTo(modifiedTime) < 0) {
IO.mkdirs(dest.getParent());
IO.copy(new NonClosingInputStream(jin), dest);
Files.setLastModifiedTime(dest, modifiedTime);
}
}
}
}
}
public void syncCache() throws Exception {
CachedFileRepo cf = new CachedFileRepo();
cf.init();
cf.close();
}
public List<RepositoryPlugin> getRepositories() throws Exception {
if (data.repositories == null) {
data.repositories = getPlugins(RepositoryPlugin.class);
for (RepositoryPlugin repo : data.repositories) {
if (repo instanceof Prepare) {
((Prepare) repo).prepare();
}
}
}
return data.repositories;
}
public Collection<Project> getBuildOrder() throws Exception {
Set<Project> result = new LinkedHashSet<>();
for (Project project : projects.getAllProjects()) {
Collection<Project> dependsOn = project.getDependson();
getBuildOrder(dependsOn, result);
result.add(project);
}
return result;
}
private void getBuildOrder(Collection<Project> dependsOn, Set<Project> result) throws Exception {
for (Project project : dependsOn) {
Collection<Project> subProjects = project.getDependson();
for (Project subProject : subProjects) {
result.add(subProject);
}
result.add(project);
}
}
public static Workspace getWorkspace(String path) throws Exception {
File file = IO.getFile(new File(""), path);
return getWorkspace(file);
}
public Maven getMaven() {
return maven;
}
@Override
protected void setTypeSpecificPlugins(Set<Object> list) {
try {
super.setTypeSpecificPlugins(list);
list.add(this);
list.add(maven);
list.add(settings);
if (!isTrue(getProperty(NOBUILDINCACHE))) {
CachedFileRepo repo = new CachedFileRepo();
list.add(repo);
}
resourceRepositoryImpl = new ResourceRepositoryImpl();
resourceRepositoryImpl.setCache(IO.getFile(getProperty(CACHEDIR, Home.getUserHomeBnd() + "/caches/shas")));
resourceRepositoryImpl.setExecutor(getExecutor());
resourceRepositoryImpl.setIndexFile(getFile(getBuildDir(), "repo.json"));
resourceRepositoryImpl.setURLConnector(new MultiURLConnectionHandler(this));
customize(resourceRepositoryImpl, null);
list.add(resourceRepositoryImpl);
//
// Exporters
//
list.add(new ExecutableJarExporter());
list.add(new RunbundlesExporter());
HttpClient client = new HttpClient();
try {
client.setOffline(getOffline());
client.setRegistry(this);
client.readSettings(this);
} catch (Exception e) {
exception(e, "Failed to load the communication settings");
}
list.add(client);
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* Add any extensions listed
*
* @param list
*/
@Override
protected void addExtensions(Set<Object> list) {
//
// <bsn>; version=<range>
//
Parameters extensions = getMergedParameters(EXTENSION);
Map<DownloadBlocker, Attrs> blockers = new HashMap<>();
for (Entry<String, Attrs> i : extensions.entrySet()) {
String bsn = removeDuplicateMarker(i.getKey());
String stringRange = i.getValue()
.get(VERSION_ATTRIBUTE);
logger.debug("Adding extension {}-{}", bsn, stringRange);
if (stringRange == null)
stringRange = Version.LOWEST.toString();
else if (!VersionRange.isVersionRange(stringRange)) {
error("Invalid version range %s on extension %s", stringRange, bsn);
continue;
}
try {
SortedSet<ResourceDescriptor> matches = resourceRepositoryImpl.find(null, bsn,
new VersionRange(stringRange));
if (matches.isEmpty()) {
error("Extension %s;version=%s not found in base repo", bsn, stringRange);
continue;
}
DownloadBlocker blocker = new DownloadBlocker(this);
blockers.put(blocker, i.getValue());
resourceRepositoryImpl.getResource(matches.last().id, blocker);
} catch (Exception e) {
error("Failed to load extension %s-%s, %s", bsn, stringRange, e);
}
}
logger.debug("Found extensions {}", blockers);
for (Entry<DownloadBlocker, Attrs> blocker : blockers.entrySet()) {
try {
String reason = blocker.getKey()
.getReason();
if (reason != null) {
error("Extension load failed: %s", reason);
continue;
}
@SuppressWarnings("resource")
URLClassLoader cl = new URLClassLoader(new URL[] {
blocker.getKey()
.getFile()
.toURI()
.toURL()
}, getClass().getClassLoader());
for (URL manifest : Iterables.iterable(cl.getResources("META-INF/MANIFEST.MF"))) {
try (InputStream is = manifest.openStream()) {
Manifest m = new Manifest(is);
Parameters activators = new Parameters(m.getMainAttributes()
.getValue("Extension-Activator"), this);
for (Entry<String, Attrs> e : activators.entrySet()) {
try {
Class<?> c = cl.loadClass(e.getKey());
ExtensionActivator extensionActivator = (ExtensionActivator) newInstance(c);
customize(extensionActivator, blocker.getValue());
List<?> plugins = extensionActivator.activate(this, blocker.getValue());
list.add(extensionActivator);
if (plugins != null)
for (Object plugin : plugins) {
list.add(plugin);
}
} catch (ClassNotFoundException cnfe) {
error("Loading extension %s, extension activator missing: %s (ignored)", blocker,
e.getKey());
}
}
}
}
} catch (Exception e) {
error("failed to install extension %s due to %s", blocker, e);
}
}
}
public boolean isOffline() {
return offline.get();
}
public AtomicBoolean getOffline() {
return offline;
}
public Workspace setOffline(boolean on) {
offline.set(on);
return this;
}
static final String _globalHelp = "${global;<name>[;<default>]}, get a global setting from ~/.bnd/settings.json";
/**
* Provide access to the global settings of this machine.
*
* @throws Exception
*/
public String _global(String[] args) throws Exception {
Macro.verifyCommand(args, _globalHelp, null, 2, 3);
String key = args[1];
if (key.equals("key.public"))
return Hex.toHexString(settings.getPublicKey());
if (key.equals("key.private"))
return Hex.toHexString(settings.getPrivateKey());
String s = settings.get(key);
if (s != null)
return s;
if (args.length == 3)
return args[2];
return null;
}
public String _user(String[] args) throws Exception {
return _global(args);
}
static final String _repodigestsHelp = "${repodigests;[;<repo names>]...}, get the repository digests";
/**
* Return the repository signature digests. These digests are a unique id
* for the contents of the repository
*/
public Object _repodigests(String[] args) throws Exception {
Macro.verifyCommand(args, _repodigestsHelp, null, 1, 10000);
List<RepositoryPlugin> repos = getRepositories();
if (args.length > 1) {
repos: for (Iterator<RepositoryPlugin> it = repos.iterator(); it.hasNext();) {
String name = it.next()
.getName();
for (int i = 1; i < args.length; i++) {
if (name.equals(args[i])) {
continue repos;
}
}
it.remove();
}
}
List<String> digests = new ArrayList<>();
for (RepositoryPlugin repo : repos) {
try {
if (repo instanceof RepositoryDigest) {
byte[] digest = ((RepositoryDigest) repo).getDigest();
digests.add(Hex.toHexString(digest));
} else {
if (args.length != 1)
error("Specified repo %s for ${repodigests} was named but it is not found", repo.getName());
}
} catch (Exception e) {
if (args.length != 1)
error("Specified repo %s for digests is not found", repo.getName());
// else Ignore
}
}
return join(digests, ",");
}
public static Run getRun(File file) throws Exception {
if (!file.isFile()) {
return null;
}
File projectDir = file.getParentFile();
File workspaceDir = projectDir.getParentFile();
if (!workspaceDir.isDirectory()) {
return null;
}
Workspace ws = getWorkspaceWithoutException(workspaceDir);
if (ws == null) {
return null;
}
return new Run(ws, projectDir, file);
}
/**
* Report details of this workspace
*/
@Override
public void report(Map<String, Object> table) throws Exception {
super.report(table);
table.put("Workspace", toString());
table.put("Plugins", getPlugins(Object.class));
table.put("Repos", getRepositories());
table.put("Projects in build order", getBuildOrder());
}
public File getCache(String name) {
return getFile(buildDir, CACHEDIR + "/" + name);
}
/**
* Return the workspace repo
*/
public WorkspaceRepository getWorkspaceRepository() {
return workspaceRepo;
}
public void checkStructure() {
if (!getBuildDir().isDirectory())
error("No directory for cnf %s", getBuildDir());
else {
File build = IO.getFile(getBuildDir(), BUILDFILE);
if (build.isFile()) {
error("No %s file in %s", BUILDFILE, getBuildDir());
}
}
}
public File getBuildDir() {
return buildDir;
}
public void setBuildDir(File buildDir) {
this.buildDir = buildDir;
}
public boolean isValid() {
return IO.getFile(getBuildDir(), BUILDFILE)
.isFile();
}
public RepositoryPlugin getRepository(String repo) throws Exception {
for (RepositoryPlugin r : getRepositories()) {
if (repo.equals(r.getName())) {
return r;
}
}
return null;
}
@Override
public void close() {
if (data.remoteServer != null) {
IO.close(data.remoteServer);
}
synchronized (cache) {
WeakReference<Workspace> wsr = cache.get(getBase());
if ((wsr != null) && (wsr.get() == this)) {
cache.remove(getBase());
}
}
projects.close();
try {
super.close();
} catch (IOException e) {
/* For backwards compatibility, we ignore the exception */
}
}
/**
* Get the bnddriver, can be null if not set. The overallDriver is the
* environment that runs this bnd.
*/
public String getDriver() {
if (driver == null) {
driver = getProperty(Constants.BNDDRIVER, null);
if (driver != null)
driver = driver.trim();
}
if (driver != null)
return driver;
return overallDriver;
}
/**
* Set the driver of this environment
*/
public static void setDriver(String driver) {
overallDriver = driver;
}
/**
* Macro to return the driver. Without any arguments, we return the name of
* the driver. If there are arguments, we check each of the arguments
* against the name of the driver. If it matches, we return the driver name.
* If none of the args match the driver name we return an empty string
* (which is false).
*/
public String _driver(String args[]) {
if (args.length == 1) {
return getDriver();
}
String driver = getDriver();
if (driver == null)
driver = getProperty(Constants.BNDDRIVER);
if (driver != null) {
for (int i = 1; i < args.length; i++) {
if (args[i].equalsIgnoreCase(driver))
return driver;
}
}
return "";
}
/**
* Add a gestalt to all workspaces. The gestalt is a set of parts describing
* the environment. Each part has a name and optionally attributes. This
* method adds a gestalt to the VM. Per workspace it is possible to augment
* this.
*/
public static void addGestalt(String part, Attrs attrs) {
Attrs already = overallGestalt.get(part);
if (attrs == null)
attrs = new Attrs();
if (already != null) {
already.putAll(attrs);
} else
already = attrs;
overallGestalt.put(part, already);
}
/**
* Get the attrs for a gestalt part
*/
public Attrs getGestalt(String part) {
return getGestalt().get(part);
}
/**
* Get the attrs for a gestalt part
*/
public Parameters getGestalt() {
if (gestalt == null) {
gestalt = getMergedParameters(Constants.GESTALT);
gestalt.mergeWith(overallGestalt, false);
}
return gestalt;
}
/**
* Get the layout style of the workspace.
*/
public WorkspaceLayout getLayout() {
return layout;
}
static final String _gestaltHelp = "${gestalt;<part>[;key[;<value>]]} has too many arguments";
/**
* The macro to access the gestalt
* <p>
* {@code $ gestalt;part[;key[;value]]}
*/
public String _gestalt(String args[]) {
if (args.length >= 2) {
Attrs attrs = getGestalt(args[1]);
if (attrs == null)
return "";
if (args.length == 2)
return args[1];
String s = attrs.get(args[2]);
if (args.length == 3) {
if (s == null)
s = "";
return s;
}
if (args.length == 4) {
if (args[3].equals(s))
return s;
else
return "";
}
}
throw new IllegalArgumentException(_gestaltHelp);
}
@Override
public String toString() {
return "Workspace [" + getBase().getName() + "]";
}
/**
* Add a plugin
*
* @param plugin
* @throws Exception
*/
public boolean addPlugin(Class<?> plugin, String alias, Map<String, String> parameters, boolean force)
throws Exception {
BndPlugin ann = plugin.getAnnotation(BndPlugin.class);
if (alias == null) {
if (ann != null)
alias = ann.name();
else {
alias = Strings.getLastSegment(plugin.getName())
.toLowerCase();
if (alias.endsWith("plugin")) {
alias = alias.substring(0, alias.length() - "plugin".length());
}
}
}
if (!Verifier.isBsn(alias)) {
error("Not a valid plugin name %s", alias);
}
File ext = getFile(Workspace.CNFDIR + "/" + Workspace.EXT);
IO.mkdirs(ext);
File f = new File(ext, alias + ".bnd");
if (!force) {
if (f.exists()) {
error("Plugin %s already exists", alias);
return false;
}
} else {
IO.delete(f);
}
Object l = newInstance(plugin);
try (Formatter setup = new Formatter()) {
setup.format("#\n" //
+ "# Plugin %s setup\n" //
+ "#\n", alias);
setup.format(Constants.PLUGIN + ".%s = %s", alias, plugin.getName());
MapStream.of(parameters)
.mapValue(this::escaped)
.forEachOrdered((k, v) -> setup.format("; \\\n \t%s = '%s'", k, v));
setup.format("\n\n");
String out = setup.toString();
if (l instanceof LifeCyclePlugin) {
out = ((LifeCyclePlugin) l).augmentSetup(out, alias, parameters);
((LifeCyclePlugin) l).init(this);
}
logger.debug("setup {}", out);
IO.store(out, f);
}
refresh();
for (LifeCyclePlugin lp : getPlugins(LifeCyclePlugin.class)) {
lp.addedPlugin(this, plugin.getName(), alias, parameters);
}
return true;
}
private static final MethodType defaultConstructor = methodType(void.class);
private static <T> T newInstance(Class<T> rawClass) throws Exception {
try {
return (T) publicLookup().findConstructor(rawClass, defaultConstructor)
.invoke();
} catch (Error | Exception e) {
throw e;
} catch (Throwable e) {
throw new RuntimeException(e);
}
}
private final static Pattern ESCAPE_P = Pattern.compile("([\"'])(.*)\\1");
private Object escaped(String value) {
Matcher matcher = ESCAPE_P.matcher(value);
if (matcher.matches())
value = matcher.group(2);
return value.replaceAll("'", "\\'");
}
public boolean removePlugin(String alias) {
File ext = getFile(Workspace.CNFDIR + "/" + Workspace.EXT);
File f = new File(ext, alias + ".bnd");
if (!f.exists()) {
error("No such plugin %s", alias);
return false;
}
IO.delete(f);
refresh();
return true;
}
/**
* Create a workspace that does not inherit from a cnf directory etc.
*
* @param run
*/
public static Workspace createStandaloneWorkspace(Processor run, URI base) throws Exception {
Workspace ws = new Workspace(WorkspaceLayout.STANDALONE);
AtomicBoolean copyAll = new AtomicBoolean(false);
AtomicInteger counter = new AtomicInteger();
Parameters standalone = new Parameters(run.getProperty(STANDALONE), ws);
standalone.stream()
.filterKey(locationStr -> {
if ("true".equalsIgnoreCase(locationStr)) {
copyAll.set(true);
return false;
}
return true;
})
.map(asBiFunction((locationStr, attrs) -> {
String index = String.format("%02d", counter.incrementAndGet());
String name = attrs.get("name");
if (name == null) {
name = "repo".concat(index);
}
URI resolvedLocation = URIUtil.resolve(base, locationStr);
try (Formatter f = new Formatter(Locale.US)) {
f.format(STANDALONE_REPO_CLASS + "; name='%s'; locations='%s'", name, resolvedLocation);
attrs.stream()
.filterKey(k -> !k.equals("name"))
.forEachOrdered((k, v) -> f.format("; %s='%s'", k, v));
return MapStream.entry(PLUGIN_STANDALONE.concat(index), f.toString());
}
}))
.forEachOrdered(ws::setProperty);
MapStream<String, Object> runProperties = MapStream.of(run.getProperties())
.mapKey(String.class::cast);
if (!copyAll.get()) {
runProperties = runProperties
.filterKey(k -> k.equals(Constants.PLUGIN) || k.startsWith(Constants.PLUGIN + "."));
}
Properties wsProperties = ws.getProperties();
runProperties.filterKey(k -> !k.startsWith(PLUGIN_STANDALONE))
.forEachOrdered(wsProperties::put);
return ws;
}
public boolean isDefaultWorkspace() {
return BND_DEFAULT_WS.equals(getBase());
}
@Override
public boolean isInteractive() {
return getGestalt(Constants.GESTALT_INTERACTIVE) != null;
}
public static void resetStatic() {
overallDriver = "unset";
overallGestalt = new Parameters();
}
/**
* Create a project in this workspace
*/
public Project createProject(String name) throws Exception {
if (!Verifier.SYMBOLICNAME.matcher(name)
.matches()) {
error(
"A project name is a Bundle Symbolic Name, this must therefore consist of only letters, digits and dots");
return null;
}
File pdir = getFile(name);
IO.mkdirs(pdir);
IO.store("#\n# " + name.toUpperCase()
.replace('.', ' ') + "\n#\n", getFile(pdir, Project.BNDFILE));
projects.refresh();
Project p = getProject(name);
IO.mkdirs(p.getTarget());
IO.mkdirs(p.getOutput());
IO.mkdirs(p.getTestOutput());
for (File dir : p.getSourcePath()) {
IO.mkdirs(dir);
}
IO.mkdirs(p.getTestSrc());
for (LifeCyclePlugin l : getPlugins(LifeCyclePlugin.class)) {
l.created(p);
}
if (!p.isValid()) {
error("project %s is not valid", p);
}
return p;
}
void removeProject(Project p) throws Exception {
if (p.isCnf())
return;
for (LifeCyclePlugin lp : getPlugins(LifeCyclePlugin.class)) {
lp.delete(p);
}
projects.refresh();
}
/**
* Create a new Workspace
*
* @param wsdir
* @throws Exception
*/
public static Workspace createWorkspace(File wsdir) throws Exception {
if (wsdir.exists())
return null;
IO.mkdirs(wsdir);
File cnf = IO.getFile(wsdir, CNFDIR);
IO.mkdirs(cnf);
IO.store("", new File(cnf, BUILDFILE));
IO.store("-nobundles: true\n", new File(cnf, Project.BNDFILE));
File ext = new File(cnf, EXT);
IO.mkdirs(ext);
Workspace ws = getWorkspace(wsdir);
return ws;
}
/**
* Lock the workspace and its corresponding projects for reading. The r
* parameter when called can freely use any read function in the workspace.
*
* @param r the lambda to run
* @param timeoutInMs the timeout in milliseconds
* @return the value of the lambda
*/
public <T> T readLocked(Callable<T> r, long timeoutInMs) throws Exception {
return locked(r, timeoutInMs, lock.readLock());
}
public <T> T readLocked(Callable<T> r) throws Exception {
return readLocked(r, 120000);
}
/**
* Lock the workspace and its corresponding projects for all functions. The
* r parameter when called can freely use any function in the workspace.
*
* @param r the lambda to run
* @param timeoutInMs the timeout in milliseconds
* @return the value of the lambda
*/
public <T> T writeLocked(Callable<T> r, long timeoutInMs) throws Exception {
return locked(r, timeoutInMs, lock.writeLock());
}
public <T> T writeLocked(Callable<T> r) throws Exception {
return writeLocked(r, 120000);
}
<T> T locked(Callable<T> r, long timeoutInMs, Lock readLock) throws Exception {
boolean locked = readLock.tryLock(timeoutInMs, TimeUnit.MILLISECONDS);
if (!locked)
throw new TimeoutException();
try {
return r.call();
} finally {
readLock.unlock();
}
}
/**
* Provide a macro that lists all currently loaded project names that match
* a macro. This macro checks for cycles since I am not sure if calling
* getAllProjects is safe for some macros in all cases. I.e. the primary use
* case wants to use it in -dependson
*
* <pre>
* ${projectswhere;key;glob}
* </pre>
*/
static final String _projectswhereHelp = "${projectswhere[;<key>;<glob>]} - Make sure this cannot be called recursively at startup";
private static final ThreadLocal<Boolean> projectswhereCycleCheck = new ThreadLocal<>();
public String _projectswhere(String args[]) {
if (projectswhereCycleCheck.get() != null) {
throw new IllegalStateException("The ${projectswhere} macro is called recursively");
}
projectswhereCycleCheck.set(Boolean.TRUE);
try {
Macro.verifyCommand(args, _projectswhereHelp, null, 1, 3);
Collection<Project> allProjects = getAllProjects();
if (args.length == 1) {
return Strings.join(allProjects);
}
String key = args[1];
boolean negate;
Glob g;
if (args.length > 2) {
if (args[2].startsWith("!")) {
g = new Glob(args[2].substring(1));
negate = true;
} else {
g = new Glob(args[2]);
negate = false;
}
} else {
g = null;
negate = false;
}
return allProjects.stream()
.filter(p -> {
String value = p.getProperty(key);
if (value == null)
return negate;
if (g == null)
return !negate;
return negate ^ g.matcher(value)
.matches();
})
.map(Project::getName)
.collect(Strings.joining());
} finally {
projectswhereCycleCheck.set(null);
}
}
public void refresh(RepositoryPlugin repo) {
for (RepositoryListenerPlugin listener : getPlugins(RepositoryListenerPlugin.class)) {
try {
listener.repositoryRefreshed(repo);
} catch (Exception e) {
exception(e, "Updating listener plugin %s", listener);
}
}
}
/**
* Search for a partial class name. The partialClass name may be a simple
* class name (Foo) or a fully qualified class name line (foo.bar.Foo),
* including nested classes, or only a package name prefix (foo.bar).
*
* @param partialFqn a packagename ( '.' classname )*
* @return a map with suggestion what to add to the -buildpath/-testpath
* @throws Exception
*/
public Result<Map<String, List<BundleId>>, String> search(String partialFqn) throws Exception {
return data.classIndex.get()
.search(partialFqn);
}
/**
* Return an aggregate repository of all the workspace's repository and the
* projects repository. This workspace must be gotten for each operation, it
* might become stale over time.
*
* @return an aggregate repository
* @throws Exception
*/
public Repository getResourceRepository() throws Exception {
List<Repository> plugins = getPlugins(Repository.class);
AggregateRepository repository = new AggregateRepository(plugins);
Parameters augments = getMergedParameters(Constants.AUGMENT);
if (augments.isEmpty())
return repository;
return new AugmentRepository(augments, repository);
}
}
| |
/*
* Copyright 2012 Google 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 com.google.android.apps.iosched.ui;
import com.google.analytics.tracking.android.EasyTracker;
import com.google.android.apps.iosched.Config;
import gdg.devfest.app.R;
import com.google.android.apps.iosched.util.ImageFetcher;
import com.google.android.apps.iosched.util.UIUtils;
import com.google.api.client.googleapis.services.GoogleKeyInitializer;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.http.json.JsonHttpRequestInitializer;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson.JacksonFactory;
import com.google.api.services.plus.Plus;
import com.google.api.services.plus.model.Activity;
import com.google.api.services.plus.model.ActivityFeed;
import com.actionbarsherlock.app.SherlockListFragment;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Color;
import android.net.ParseException;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.LoaderManager;
import android.support.v4.app.ShareCompat;
import android.support.v4.content.AsyncTaskLoader;
import android.support.v4.content.Loader;
import android.text.Html;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import static com.google.android.apps.iosched.util.LogUtils.LOGD;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
/**
* A {@link WebView}-based fragment that shows Google+ public search results for a given query,
* provided as the {@link SocialStreamFragment#EXTRA_QUERY} extra in the fragment arguments. If no
* search query is provided, the conference hashtag is used as the default query.
*
* <p>WARNING! This fragment uses the Google+ API, and is subject to quotas. If you expect to
* write a wildly popular app based on this code, please check the
* at <a href="https://developers.google.com/+/">Google+ Platform documentation</a> on latest
* best practices and quota details. You can check your current quota at the
* <a href="https://code.google.com/apis/console">APIs console</a>.
*/
public class SocialStreamFragment extends SherlockListFragment implements
AbsListView.OnScrollListener,
LoaderManager.LoaderCallbacks<List<Activity>> {
private static final String TAG = makeLogTag(SocialStreamFragment.class);
public static final String EXTRA_QUERY = "com.google.android.iosched.extra.QUERY";
private static final String STATE_POSITION = "position";
private static final String STATE_TOP = "top";
private static final long MAX_RESULTS_PER_REQUEST = 20;
private static final int STREAM_LOADER_ID = 0;
private String mSearchString;
private List<Activity> mStream = new ArrayList<Activity>();
private StreamAdapter mStreamAdapter = new StreamAdapter();
private int mListViewStatePosition;
private int mListViewStateTop;
private ImageFetcher mImageFetcher;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final Intent intent = BaseActivity.fragmentArgumentsToIntent(getArguments());
// mSearchString can be populated before onCreate() by called refresh(String)
if (TextUtils.isEmpty(mSearchString)) {
mSearchString = intent.getStringExtra(EXTRA_QUERY);
}
if (TextUtils.isEmpty(mSearchString)) {
mSearchString = UIUtils.CONFERENCE_HASHTAG;
}
if (!mSearchString.startsWith("#")) {
mSearchString = "#" + mSearchString;
}
mImageFetcher = UIUtils.getImageFetcher(getActivity());
setListAdapter(mStreamAdapter);
setHasOptionsMenu(true);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (savedInstanceState != null) {
mListViewStatePosition = savedInstanceState.getInt(STATE_POSITION, -1);
mListViewStateTop = savedInstanceState.getInt(STATE_TOP, 0);
} else {
mListViewStatePosition = -1;
mListViewStateTop = 0;
}
return super.onCreateView(inflater, container, savedInstanceState);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setEmptyText(getString(R.string.empty_social_stream));
// In support library r8, calling initLoader for a fragment in a FragmentPagerAdapter
// in the fragment's onCreate may cause the same LoaderManager to be dealt to multiple
// fragments because their mIndex is -1 (haven't been added to the activity yet). Thus,
// we do this in onActivityCreated.
getLoaderManager().initLoader(STREAM_LOADER_ID, null, this);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
view.setBackgroundColor(Color.WHITE);
final ListView listView = getListView();
listView.setCacheColorHint(Color.WHITE);
listView.setOnScrollListener(this);
listView.setDrawSelectorOnTop(true);
TypedValue v = new TypedValue();
getActivity().getTheme().resolveAttribute(R.attr.activatableItemBackground, v, true);
listView.setSelector(v.resourceId);
}
@Override
public void onStop() {
super.onStop();
if (mImageFetcher != null) {
mImageFetcher.closeCache();
}
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.social_stream, menu);
super.onCreateOptionsMenu(menu, inflater);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_compose:
Intent intent = ShareCompat.IntentBuilder.from(getActivity())
.setType("text/plain")
.setText(mSearchString + "\n\n")
.getIntent();
UIUtils.preferPackageForIntent(getActivity(), intent,
UIUtils.GOOGLE_PLUS_PACKAGE_NAME);
startActivity(intent);
EasyTracker.getTracker().trackEvent("Home Screen Dashboard", "Click",
"Post to Google+", 0L);
LOGD("Tracker", "Home Screen Dashboard: Click, post to Google+");
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onSaveInstanceState(Bundle outState) {
if (isAdded()) {
View v = getListView().getChildAt(0);
int top = (v == null) ? 0 : v.getTop();
outState.putInt(STATE_POSITION, getListView().getFirstVisiblePosition());
outState.putInt(STATE_TOP, top);
}
super.onSaveInstanceState(outState);
}
public void refresh(String newQuery) {
mSearchString = newQuery;
refresh(true);
}
public void refresh() {
refresh(false);
}
public void refresh(boolean forceRefresh) {
if (isStreamLoading() && !forceRefresh) {
return;
}
// clear current items
mStream.clear();
mStreamAdapter.notifyDataSetInvalidated();
if (isAdded()) {
Loader loader = getLoaderManager().getLoader(STREAM_LOADER_ID);
((StreamLoader) loader).init(mSearchString);
}
loadMoreResults();
}
public void loadMoreResults() {
if (isAdded()) {
Loader loader = getLoaderManager().getLoader(STREAM_LOADER_ID);
if (loader != null) {
loader.forceLoad();
}
}
}
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
Activity activity = mStream.get(position);
Intent postDetailIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(activity.getUrl()));
postDetailIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
UIUtils.preferPackageForIntent(getActivity(), postDetailIntent,
UIUtils.GOOGLE_PLUS_PACKAGE_NAME);
UIUtils.safeOpenLink(getActivity(), postDetailIntent);
}
@Override
public void onScrollStateChanged(AbsListView listView, int scrollState) {
// Pause disk cache access to ensure smoother scrolling
if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_FLING ||
scrollState == AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL) {
mImageFetcher.setPauseDiskCache(true);
} else {
mImageFetcher.setPauseDiskCache(false);
}
}
@Override
public void onScroll(AbsListView absListView, int firstVisibleItem, int visibleItemCount,
int totalItemCount) {
// Simple implementation of the infinite scrolling UI pattern; loads more Google+
// search results as the user scrolls to the end of the list.
if (!isStreamLoading()
&& streamHasMoreResults()
&& visibleItemCount != 0
&& firstVisibleItem + visibleItemCount >= totalItemCount - 1) {
loadMoreResults();
}
}
@Override
public Loader<List<Activity>> onCreateLoader(int id, Bundle args) {
return new StreamLoader(getActivity(), mSearchString);
}
@Override
public void onLoadFinished(Loader<List<Activity>> listLoader, List<Activity> activities) {
if (activities != null) {
mStream = activities;
}
mStreamAdapter.notifyDataSetChanged();
if (mListViewStatePosition != -1 && isAdded()) {
getListView().setSelectionFromTop(mListViewStatePosition, mListViewStateTop);
mListViewStatePosition = -1;
}
}
@Override
public void onLoaderReset(Loader<List<Activity>> listLoader) {
}
private boolean isStreamLoading() {
if (isAdded()) {
final Loader loader = getLoaderManager().getLoader(STREAM_LOADER_ID);
if (loader != null) {
return ((StreamLoader) loader).isLoading();
}
}
return true;
}
private boolean streamHasMoreResults() {
if (isAdded()) {
final Loader loader = getLoaderManager().getLoader(STREAM_LOADER_ID);
if (loader != null) {
return ((StreamLoader) loader).hasMoreResults();
}
}
return false;
}
private boolean streamHasError() {
if (isAdded()) {
final Loader loader = getLoaderManager().getLoader(STREAM_LOADER_ID);
if (loader != null) {
return ((StreamLoader) loader).hasError();
}
}
return false;
}
/**
* An {@link AsyncTaskLoader} that loads activities from the public Google+ stream for
* a given search query. The loader maintains a page state with the Google+ API and thus
* supports pagination.
*/
private static class StreamLoader extends AsyncTaskLoader<List<Activity>> {
List<Activity> mActivities;
private String mSearchString;
private String mNextPageToken;
private boolean mIsLoading;
private boolean mHasError;
public StreamLoader(Context context, String searchString) {
super(context);
init(searchString);
}
private void init(String searchString) {
mSearchString = searchString;
mHasError = false;
mNextPageToken = null;
mIsLoading = true;
mActivities = null;
}
@Override
public List<Activity> loadInBackground() {
mIsLoading = true;
// Set up the HTTP transport and JSON factory
HttpTransport httpTransport = new NetHttpTransport();
JsonFactory jsonFactory = new JacksonFactory();
JsonHttpRequestInitializer initializer = new GoogleKeyInitializer(
Config.API_KEY);
// Set up the main Google+ class
Plus plus = Plus.builder(httpTransport, jsonFactory)
.setApplicationName(Config.APP_NAME)
.setJsonHttpRequestInitializer(initializer)
.build();
ActivityFeed activities = null;
try {
activities = plus.activities().search(mSearchString)
.setPageToken(mNextPageToken)
.setMaxResults(MAX_RESULTS_PER_REQUEST)
.execute();
mHasError = false;
mNextPageToken = activities.getNextPageToken();
} catch (IOException e) {
e.printStackTrace();
mHasError = true;
mNextPageToken = null;
}
return (activities != null) ? activities.getItems() : null;
}
@Override
public void deliverResult(List<Activity> activities) {
mIsLoading = false;
if (activities != null) {
if (mActivities == null) {
mActivities = activities;
} else {
mActivities.addAll(activities);
}
}
if (isStarted()) {
// Need to return new ArrayList for some reason or onLoadFinished() is not called
super.deliverResult(mActivities == null ?
null : new ArrayList<Activity>(mActivities));
}
}
@Override
protected void onStartLoading() {
if (mActivities != null) {
// If we already have results and are starting up, deliver what we already have.
deliverResult(null);
} else {
forceLoad();
}
}
@Override
protected void onStopLoading() {
mIsLoading = false;
cancelLoad();
}
@Override
protected void onReset() {
super.onReset();
onStopLoading();
mActivities = null;
}
public boolean isLoading() {
return mIsLoading;
}
public boolean hasMoreResults() {
return mNextPageToken != null;
}
public boolean hasError() {
return mHasError;
}
public void setSearchString(String searchString) {
mSearchString = searchString;
}
public void refresh(String searchString) {
setSearchString(searchString);
refresh();
}
public void refresh() {
reset();
startLoading();
}
}
/**
* A list adapter that shows individual Google+ activities as list items.
* If another page is available, the last item is a "loading" view to support the
* infinite scrolling UI pattern.
*/
private class StreamAdapter extends BaseAdapter {
private static final int VIEW_TYPE_ACTIVITY = 0;
private static final int VIEW_TYPE_LOADING = 1;
@Override
public boolean areAllItemsEnabled() {
return false;
}
@Override
public boolean isEnabled(int position) {
return getItemViewType(position) == VIEW_TYPE_ACTIVITY;
}
@Override
public int getViewTypeCount() {
return 2;
}
@Override
public boolean hasStableIds() {
return true;
}
@Override
public int getCount() {
return mStream.size() + (
// show the status list row if...
((isStreamLoading() && mStream.size() == 0) // ...this is the first load
|| streamHasMoreResults() // ...or there's another page
|| streamHasError()) // ...or there's an error
? 1 : 0);
}
@Override
public int getItemViewType(int position) {
return (position >= mStream.size())
? VIEW_TYPE_LOADING
: VIEW_TYPE_ACTIVITY;
}
@Override
public Object getItem(int position) {
return (getItemViewType(position) == VIEW_TYPE_ACTIVITY)
? mStream.get(position)
: null;
}
@Override
public long getItemId(int position) {
// TODO: better unique ID heuristic
return (getItemViewType(position) == VIEW_TYPE_ACTIVITY)
? mStream.get(position).getId().hashCode()
: -1;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (getItemViewType(position) == VIEW_TYPE_LOADING) {
if (convertView == null) {
convertView = getLayoutInflater(null).inflate(
R.layout.list_item_stream_status, parent, false);
}
if (streamHasError()) {
convertView.findViewById(android.R.id.progress).setVisibility(View.GONE);
((TextView) convertView.findViewById(android.R.id.text1)).setText(
R.string.stream_error);
} else {
convertView.findViewById(android.R.id.progress).setVisibility(View.VISIBLE);
((TextView) convertView.findViewById(android.R.id.text1)).setText(
R.string.loading);
}
return convertView;
} else {
Activity activity = (Activity) getItem(position);
if (convertView == null) {
convertView = getLayoutInflater(null).inflate(
R.layout.list_item_stream_activity, parent, false);
}
StreamRowViewBinder.bindActivityView(convertView, activity, mImageFetcher);
return convertView;
}
}
}
/**
* A helper class to bind data from a Google+ {@link Activity} to the list item view.
*/
private static class StreamRowViewBinder {
private static class ViewHolder {
private TextView[] detail;
private ImageView[] detailIcon;
private ImageView[] media;
private ImageView[] mediaOverlay;
private TextView originalAuthor;
private View reshareLine;
private View reshareSpacer;
private ImageView userImage;
private TextView userName;
private TextView content;
private View plusOneIcon;
private TextView plusOneCount;
private View commentIcon;
private TextView commentCount;
}
private static void bindActivityView(
final View rootView, Activity activity, ImageFetcher imageFetcher) {
// Prepare view holder.
ViewHolder temp = (ViewHolder) rootView.getTag();
final ViewHolder views;
if (temp != null) {
views = temp;
} else {
views = new ViewHolder();
rootView.setTag(views);
views.detail = new TextView[] {
(TextView) rootView.findViewById(R.id.stream_detail_text)
};
views.detailIcon = new ImageView[] {
(ImageView) rootView.findViewById(R.id.stream_detail_media_small)
};
views.media = new ImageView[] {
(ImageView) rootView.findViewById(R.id.stream_media_1_1),
(ImageView) rootView.findViewById(R.id.stream_media_1_2),
};
views.mediaOverlay = new ImageView[] {
(ImageView) rootView.findViewById(R.id.stream_media_overlay_1_1),
(ImageView) rootView.findViewById(R.id.stream_media_overlay_1_2),
};
views.originalAuthor = (TextView) rootView.findViewById(R.id.stream_original_author);
views.reshareLine = rootView.findViewById(R.id.stream_reshare_line);
views.reshareSpacer = rootView.findViewById(R.id.stream_reshare_spacer);
views.userImage = (ImageView) rootView.findViewById(R.id.stream_user_image);
views.userName = (TextView) rootView.findViewById(R.id.stream_user_name);
views.content = (TextView) rootView.findViewById(R.id.stream_content);
views.plusOneIcon = rootView.findViewById(R.id.stream_plus_one_icon);
views.plusOneCount = (TextView) rootView.findViewById(R.id.stream_plus_one_count);
views.commentIcon = rootView.findViewById(R.id.stream_comment_icon);
views.commentCount = (TextView) rootView.findViewById(R.id.stream_comment_count);
}
final Resources res = rootView.getContext().getResources();
// Hide all the array items.
int detailIndex = 0;
int mediaIndex = 0;
for (View v : views.detail) {
v.setVisibility(View.GONE);
}
for (View v : views.detailIcon) {
v.setVisibility(View.GONE);
}
for (View v : views.media) {
v.setVisibility(View.GONE);
}
for (View v : views.mediaOverlay) {
v.setVisibility(View.GONE);
}
// Determine if this is a reshare (affects how activity fields are to be
// interpreted).
boolean isReshare = (activity.getObject().getActor() != null);
// Set user name.
views.userName.setText(activity.getActor().getDisplayName());
if (activity.getActor().getImage() != null) {
imageFetcher.loadThumbnailImage(activity.getActor().getImage().getUrl(), views.userImage,
R.drawable.person_image_empty);
} else {
views.userImage.setImageResource(R.drawable.person_image_empty);
}
// Set +1 and comment counts.
final int plusOneCount = (activity.getObject().getPlusoners() != null)
? activity.getObject().getPlusoners().getTotalItems().intValue() : 0;
if (plusOneCount == 0) {
views.plusOneIcon.setVisibility(View.GONE);
views.plusOneCount.setVisibility(View.GONE);
} else {
views.plusOneIcon.setVisibility(View.VISIBLE);
views.plusOneCount.setVisibility(View.VISIBLE);
views.plusOneCount.setText(Integer.toString(plusOneCount));
}
final int commentCount = (activity.getObject().getReplies() != null)
? activity.getObject().getReplies().getTotalItems().intValue() : 0;
if (commentCount == 0) {
views.commentIcon.setVisibility(View.GONE);
views.commentCount.setVisibility(View.GONE);
} else {
views.commentIcon.setVisibility(View.VISIBLE);
views.commentCount.setVisibility(View.VISIBLE);
views.commentCount.setText(Integer.toString(commentCount));
}
// Set content.
String selfContent = isReshare
? activity.getAnnotation()
: activity.getObject().getContent();
if (!TextUtils.isEmpty(selfContent)) {
views.content.setVisibility(View.VISIBLE);
views.content.setText(Html.fromHtml(selfContent));
} else {
views.content.setVisibility(View.GONE);
}
// Set original author.
if (activity.getObject().getActor() != null) {
views.originalAuthor.setVisibility(View.VISIBLE);
views.originalAuthor.setText(res.getString(R.string.stream_originally_shared,
activity.getObject().getActor().getDisplayName()));
views.reshareLine.setVisibility(View.VISIBLE);
views.reshareSpacer.setVisibility(View.INVISIBLE);
} else {
views.originalAuthor.setVisibility(View.GONE);
views.reshareLine.setVisibility(View.GONE);
views.reshareSpacer.setVisibility(View.GONE);
}
// Set document content.
if (isReshare && !TextUtils.isEmpty(activity.getObject().getContent())
&& detailIndex < views.detail.length) {
views.detail[detailIndex].setVisibility(View.VISIBLE);
views.detail[detailIndex].setTextColor(res.getColor(R.color.stream_content_color));
views.detail[detailIndex].setText(Html.fromHtml(activity.getObject().getContent()));
++detailIndex;
}
// Set location.
String location = activity.getPlaceName();
if (!TextUtils.isEmpty(location)) {
location = activity.getAddress();
}
if (!TextUtils.isEmpty(location)) {
location = activity.getGeocode();
}
if (!TextUtils.isEmpty(location) && detailIndex < views.detail.length) {
views.detail[detailIndex].setVisibility(View.VISIBLE);
views.detail[detailIndex].setTextColor(res.getColor(R.color.stream_link_color));
views.detailIcon[detailIndex].setVisibility(View.VISIBLE);
views.detail[detailIndex].setText(location);
if ("checkin".equals(activity.getVerb())) {
views.detailIcon[detailIndex].setImageResource(R.drawable.stream_ic_checkin);
} else {
views.detailIcon[detailIndex].setImageResource(R.drawable.stream_ic_location);
}
++detailIndex;
}
// Set media content.
if (activity.getObject().getAttachments() != null) {
for (Activity.PlusObject.Attachments attachment : activity.getObject().getAttachments()) {
String objectType = attachment.getObjectType();
if (("photo".equals(objectType) || "video".equals(objectType)) &&
mediaIndex < views.media.length) {
if (attachment.getImage() == null) {
continue;
}
final ImageView mediaView = views.media[mediaIndex];
mediaView.setVisibility(View.VISIBLE);
imageFetcher.loadThumbnailImage(attachment.getImage().getUrl(), mediaView);
if ("video".equals(objectType)) {
views.mediaOverlay[mediaIndex].setVisibility(View.VISIBLE);
}
++mediaIndex;
} else if (("article".equals(objectType)) &&
detailIndex < views.detail.length) {
try {
String faviconUrl = "http://www.google.com/s2/favicons?domain=" +
Uri.parse(attachment.getUrl()).getHost();
final ImageView iconView = views.detailIcon[detailIndex];
iconView.setVisibility(View.VISIBLE);
imageFetcher.loadThumbnailImage(faviconUrl, iconView);
} catch (ParseException ignored) {}
views.detail[detailIndex].setVisibility(View.VISIBLE);
views.detail[detailIndex].setTextColor(
res.getColor(R.color.stream_link_color));
views.detail[detailIndex].setText(attachment.getDisplayName());
++detailIndex;
}
}
}
}
}
}
| |
/*
* Copyright @ 2015 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.impl.neomedia.jmfext.media.renderer.audio;
import java.beans.*;
import java.nio.*;
import javax.media.*;
import javax.media.format.*;
import net.sf.fmj.media.util.*;
import org.jitsi.impl.neomedia.*;
import org.jitsi.impl.neomedia.device.*;
import org.jitsi.impl.neomedia.jmfext.media.renderer.*;
import org.jitsi.service.neomedia.*;
/**
* Provides an abstract base implementation of <tt>Renderer</tt> which processes
* media in <tt>AudioFormat</tt> in order to facilitate extenders.
*
* @param <T> the runtime type of the <tt>AudioSystem</tt> which provides the
* playback device used by the <tt>AbstractAudioRenderer</tt>
*
* @author Lyubomir Marinov
*/
public abstract class AbstractAudioRenderer<T extends AudioSystem>
extends AbstractRenderer<AudioFormat>
{
/**
* The byte order of the running Java virtual machine expressed in the
* <tt>endian</tt> term of {@link AudioFormat}.
*/
public static final int JAVA_AUDIO_FORMAT_ENDIAN = AudioFormat.BIG_ENDIAN;
/**
* The native byte order of the hardware upon which this Java virtual
* machine is running expressed in the <tt>endian</tt> term of
* {@link AudioFormat}.
*/
public static final int NATIVE_AUDIO_FORMAT_ENDIAN
= (ByteOrder.nativeOrder() == ByteOrder.BIG_ENDIAN)
? AudioFormat.BIG_ENDIAN
: AudioFormat.LITTLE_ENDIAN;
/**
* The <tt>AudioSystem</tt> which provides the playback device used by this
* <tt>Renderer</tt>.
*/
protected final T audioSystem;
/**
* The flow of the media data (to be) implemented by this instance which is
* either {@link AudioSystem.DataFlow#NOTIFY} or
* {@link AudioSystem.DataFlow#PLAYBACK}.
*/
protected final AudioSystem.DataFlow dataFlow;
/**
* The <tt>GainControl</tt> through which the volume/gain of the media
* rendered by this instance is (to be) controlled.
*/
private GainControl gainControl;
/**
* The <tt>MediaLocator</tt> which specifies the playback device to be used
* by this <tt>Renderer</tt>.
*/
private MediaLocator locator;
/**
* The <tt>PropertyChangeListener</tt> which listens to changes in the
* values of the properties of {@link #audioSystem}.
*/
private final PropertyChangeListener propertyChangeListener
= new PropertyChangeListener()
{
public void propertyChange(PropertyChangeEvent ev)
{
AbstractAudioRenderer.this.propertyChange(ev);
}
};
/**
* The <tt>VolumeControl</tt> through which the volume/gain of the media
* rendered by this instance is (to be) controlled. If non-<tt>null</tt>,
* overrides {@link #gainControl}.
*/
private VolumeControl volumeControl;
/**
* Initializes a new <tt>AbstractAudioRenderer</tt> instance which is to use
* playback devices provided by a specific <tt>AudioSystem</tt>.
*
* @param audioSystem the <tt>AudioSystem</tt> which is to provide the
* playback devices to be used by the new instance
*/
protected AbstractAudioRenderer(T audioSystem)
{
this(audioSystem, AudioSystem.DataFlow.PLAYBACK);
}
/**
* Initializes a new <tt>AbstractAudioRenderer</tt> instance which is to use
* notification or playback (as determined by <tt>dataFlow</tt>) devices
* provided by a specific <tt>AudioSystem</tt>.
*
* @param audioSystem the <tt>AudioSystem</tt> which is to provide the
* notification or playback devices to be used by the new instance
* @param dataFlow the flow of the media data to be implemented by the new
* instance i.e. whether notification or playback devices provided by the
* specified <tt>audioSystem</tt> are to be used by the new instance. Must
* be either {@link AudioSystem.DataFlow#NOTIFY} or
* {@link AudioSystem.DataFlow#PLAYBACK}.
* @throws IllegalArgumentException if the specified <tt>dataFlow</tt> is
* neither <tt>AudioSystem.DataFlow.NOTIFY</tt> nor
* <tt>AudioSystem.DataFlow.PLAYBACK</tt>
*/
protected AbstractAudioRenderer(
T audioSystem,
AudioSystem.DataFlow dataFlow)
{
if ((dataFlow != AudioSystem.DataFlow.NOTIFY)
&& (dataFlow != AudioSystem.DataFlow.PLAYBACK))
throw new IllegalArgumentException("dataFlow");
this.audioSystem = audioSystem;
this.dataFlow = dataFlow;
if (AudioSystem.DataFlow.PLAYBACK.equals(dataFlow))
{
/*
* XXX The Renderer implementations are probed for their
* supportedInputFormats during the initialization of
* MediaServiceImpl so the latter may not be available at this time.
* Which is not much of a problem given than the GainControl is of
* no interest during the probing of the supportedInputFormats.
*/
MediaServiceImpl mediaServiceImpl
= NeomediaServiceUtils.getMediaServiceImpl();
gainControl
= (mediaServiceImpl == null)
? null
: (GainControl) mediaServiceImpl.getOutputVolumeControl();
}
else
gainControl = null;
}
/**
* Initializes a new <tt>AbstractAudioRenderer</tt> instance which is to use
* playback devices provided by an <tt>AudioSystem</tt> specified by the
* protocol of the <tt>MediaLocator</tt>s of the <tt>CaptureDeviceInfo</tt>s
* registered by the <tt>AudioSystem</tt>.
*
* @param locatorProtocol the protocol of the <tt>MediaLocator</tt>s of the
* <tt>CaptureDeviceInfo</tt> registered by the <tt>AudioSystem</tt> which
* is to provide the playback devices to be used by the new instance
*/
protected AbstractAudioRenderer(String locatorProtocol)
{
this(locatorProtocol, AudioSystem.DataFlow.PLAYBACK);
}
/**
* Initializes a new <tt>AbstractAudioRenderer</tt> instance which is to use
* notification or playback devices provided by an <tt>AudioSystem</tt>
* specified by the protocol of the <tt>MediaLocator</tt>s of the
* <tt>CaptureDeviceInfo</tt>s registered by the <tt>AudioSystem</tt>.
*
* @param locatorProtocol the protocol of the <tt>MediaLocator</tt>s of the
* <tt>CaptureDeviceInfo</tt> registered by the <tt>AudioSystem</tt> which
* is to provide the notification or playback devices to be used by the new
* instance
* @param dataFlow the flow of the media data to be implemented by the new
* instance i.e. whether notification or playback devices provided by the
* specified <tt>audioSystem</tt> are to be used by the new instance. Must
* be either {@link AudioSystem.DataFlow#NOTIFY} or
* {@link AudioSystem.DataFlow#PLAYBACK}.
* @throws IllegalArgumentException if the specified <tt>dataFlow</tt> is
* neither <tt>AudioSystem.DataFlow.NOTIFY</tt> nor
* <tt>AudioSystem.DataFlow.PLAYBACK</tt>
*/
@SuppressWarnings("unchecked")
protected AbstractAudioRenderer(
String locatorProtocol,
AudioSystem.DataFlow dataFlow)
{
this((T) AudioSystem.getAudioSystem(locatorProtocol), dataFlow);
}
/**
* {@inheritDoc}
*/
public void close()
{
if (audioSystem != null)
audioSystem.removePropertyChangeListener(propertyChangeListener);
}
/**
* Implements {@link javax.media.Controls#getControls()}. Gets the available
* controls over this instance. <tt>AbstractAudioRenderer</tt> returns a
* {@link GainControl} if available.
*
* @return an array of <tt>Object</tt>s which represent the available
* controls over this instance
*/
@Override
public Object[] getControls()
{
GainControl gainControl = getGainControl();
return
(gainControl == null)
? super.getControls()
: new Object[] { gainControl };
}
/**
* Gets the <tt>GainControl</tt>, if any, which controls the volume level of
* the audio (to be) played back by this <tt>Renderer</tt>.
*
* @return the <tt>GainControl</tt>, if any, which controls the volume level
* of the audio (to be) played back by this <tt>Renderer</tt>
*/
protected GainControl getGainControl()
{
VolumeControl volumeControl = this.volumeControl;
GainControl gainControl = this.gainControl;
if (volumeControl instanceof GainControl)
gainControl = (GainControl) volumeControl;
return gainControl;
}
/**
* Gets the <tt>MediaLocator</tt> which specifies the playback device to be
* used by this <tt>Renderer</tt>.
*
* @return the <tt>MediaLocator</tt> which specifies the playback device to
* be used by this <tt>Renderer</tt>
*/
public MediaLocator getLocator()
{
MediaLocator locator = this.locator;
if ((locator == null) && (audioSystem != null))
{
CaptureDeviceInfo device = audioSystem.getSelectedDevice(dataFlow);
if (device != null)
locator = device.getLocator();
}
return locator;
}
/**
* {@inheritDoc}
*/
public Format[] getSupportedInputFormats()
{
/*
* XXX If the AudioSystem (class) associated with this Renderer (class
* and its instances) fails to initialize, the following may throw a
* NullPointerException. Such a throw should be considered appropriate.
*/
return audioSystem.getDevice(dataFlow, getLocator()).getFormats();
}
/**
* {@inheritDoc}
*/
public void open()
throws ResourceUnavailableException
{
/*
* If this Renderer has not been forced to use a playback device with a
* specific MediaLocator, it will use the default playback device (of
* its associated AudioSystem). In the case of using the default
* playback device, change the playback device used by this instance
* upon changes of the default playback device.
*/
if ((this.locator == null) && (audioSystem != null))
{
/*
* We actually want to allow the user to switch the playback and/or
* notify device to none mid-stream in order to disable the
* playback. If an extender does not want to support that behavior,
* they will throw an exception and/or not call this implementation
* anyway.
*/
audioSystem.addPropertyChangeListener(propertyChangeListener);
}
}
/**
* Notifies this instance that the value of the property of
* {@link #audioSystem} which identifies the default notification or
* playback (as determined by {@link #dataFlow}) device has changed. The
* default implementation does nothing so extenders may safely not call back
* to their <tt>AbstractAudioRenderer</tt> super.
*
* @param ev a <tt>PropertyChangeEvent</tt> which specifies details about
* the change such as the name of the property and its old and new values
*/
protected void playbackDevicePropertyChange(PropertyChangeEvent ev)
{
}
/**
* Notifies this instance about a specific <tt>PropertyChangeEvent</tt>.
* <tt>AbstractAudioRenderer</tt> listens to changes in the values of the
* properties of {@link #audioSystem}.
*
* @param ev the <tt>PropertyChangeEvent</tt> to notify this instance about
*/
private void propertyChange(PropertyChangeEvent ev)
{
String propertyName;
switch (dataFlow)
{
case NOTIFY:
propertyName = NotifyDevices.PROP_DEVICE;
break;
case PLAYBACK:
propertyName = PlaybackDevices.PROP_DEVICE;
break;
default:
// The value of the field dataFlow is either NOTIFY or PLAYBACK.
return;
}
if (propertyName.equals(ev.getPropertyName()))
playbackDevicePropertyChange(ev);
}
/**
* Sets the <tt>MediaLocator</tt> which specifies the playback device to be
* used by this <tt>Renderer</tt>.
*
* @param locator the <tt>MediaLocator</tt> which specifies the playback
* device to be used by this <tt>Renderer</tt>
*/
public void setLocator(MediaLocator locator)
{
if (this.locator == null)
{
if (locator == null)
return;
}
else if (this.locator.equals(locator))
return;
this.locator = locator;
}
/**
* Sets the <tt>VolumeControl</tt> which is to control the volume (level) of
* the audio (to be) played back by this <tt>Renderer</tt>.
*
* @param volumeControl the <tt>VolumeControl</tt> which is to control the
* volume (level) of the audio (to be) played back by this <tt>Renderer</tt>
*/
public void setVolumeControl(VolumeControl volumeControl)
{
this.volumeControl = volumeControl;
}
/**
* Changes the priority of the current thread to a value which is considered
* appropriate for the purposes of audio processing.
*/
public static void useAudioThreadPriority()
{
useThreadPriority(MediaThread.getAudioPriority());
}
}
| |
package org.dna.mqtt.moquette.messaging.spi.impl;
import org.dna.mqtt.moquette.MQTTException;
import org.dna.mqtt.moquette.messaging.spi.IMatchingCondition;
import org.dna.mqtt.moquette.messaging.spi.IStorageService;
import org.dna.mqtt.moquette.messaging.spi.impl.events.PublishEvent;
import org.dna.mqtt.moquette.messaging.spi.impl.storage.StoredPublishEvent;
import org.dna.mqtt.moquette.messaging.spi.impl.subscriptions.Subscription;
import org.dna.mqtt.moquette.proto.messages.AbstractMessage;
import org.dna.mqtt.moquette.server.Server;
import org.fusesource.hawtbuf.codec.StringCodec;
import org.fusesource.hawtdb.api.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.nio.ByteBuffer;
import java.util.*;
/**
* Implementation of IStorageService backed by HawtDB
*/
public class HawtDBStorageService implements IStorageService {
public static class StoredMessage implements Serializable {
AbstractMessage.QOSType m_qos;
byte[] m_payload;
String m_topic;
StoredMessage(byte[] message, AbstractMessage.QOSType qos, String topic) {
m_qos = qos;
m_payload = message;
m_topic = topic;
}
AbstractMessage.QOSType getQos() {
return m_qos;
}
ByteBuffer getPayload() {
return (ByteBuffer) ByteBuffer.allocate(m_payload.length).put(m_payload).flip();
}
String getTopic() {
return m_topic;
}
}
private static final Logger LOG = LoggerFactory.getLogger(HawtDBStorageService.class);
private MultiIndexFactory m_multiIndexFactory;
private PageFileFactory pageFactory;
//maps clientID to the list of pending messages stored
//TODO move in a multimap because only Qos1 and QoS2 are stored here and they have messageID(key of secondary map)
private SortedIndex<String, List<StoredPublishEvent>> m_persistentMessageStore;
private SortedIndex<String, StoredMessage> m_retainedStore;
//bind clientID+MsgID -> evt message published
private SortedIndex<String, StoredPublishEvent> m_inflightStore;
//bind clientID+MsgID -> evt message published
private SortedIndex<String, StoredPublishEvent> m_qos2Store;
//persistent Map of clientID, set of Subscriptions
private SortedIndex<String, Set<Subscription>> m_persistentSubscriptions;
public HawtDBStorageService() {
String storeFile = Server.STORAGE_FILE_PATH;
pageFactory = new PageFileFactory();
File tmpFile;
try {
tmpFile = new File(storeFile);
tmpFile.createNewFile();
} catch (IOException ex) {
LOG.error(null, ex);
throw new MQTTException("Can't create temp file for subscriptions storage [" + storeFile + "]", ex);
}
pageFactory.setFile(tmpFile);
pageFactory.open();
PageFile pageFile = pageFactory.getPageFile();
m_multiIndexFactory = new MultiIndexFactory(pageFile);
}
public void initStore() {
initRetainedStore();
//init the message store for QoS 1/2 messages in clean sessions
initPersistentMessageStore();
initInflightMessageStore();
initPersistentSubscriptions();
initPersistentQoS2MessageStore();
}
private void initRetainedStore() {
BTreeIndexFactory<String, StoredMessage> indexFactory = new BTreeIndexFactory<String, StoredMessage>();
indexFactory.setKeyCodec(StringCodec.INSTANCE);
m_retainedStore = (SortedIndex<String, StoredMessage>) m_multiIndexFactory.openOrCreate("retained", indexFactory);
}
private void initPersistentMessageStore() {
BTreeIndexFactory<String, List<StoredPublishEvent>> indexFactory = new BTreeIndexFactory<String, List<StoredPublishEvent>>();
indexFactory.setKeyCodec(StringCodec.INSTANCE);
m_persistentMessageStore = (SortedIndex<String, List<StoredPublishEvent>>) m_multiIndexFactory.openOrCreate("persistedMessages", indexFactory);
}
private void initPersistentSubscriptions() {
BTreeIndexFactory<String, Set<Subscription>> indexFactory = new BTreeIndexFactory<String, Set<Subscription>>();
indexFactory.setKeyCodec(StringCodec.INSTANCE);
m_persistentSubscriptions = (SortedIndex<String, Set<Subscription>>) m_multiIndexFactory.openOrCreate("subscriptions", indexFactory);
}
/**
* Initialize the message store used to handle the temporary storage of QoS 1,2
* messages in flight.
*/
private void initInflightMessageStore() {
BTreeIndexFactory<String, StoredPublishEvent> indexFactory = new BTreeIndexFactory<String, StoredPublishEvent>();
indexFactory.setKeyCodec(StringCodec.INSTANCE);
m_inflightStore = (SortedIndex<String, StoredPublishEvent>) m_multiIndexFactory.openOrCreate("inflight", indexFactory);
}
private void initPersistentQoS2MessageStore() {
BTreeIndexFactory<String, StoredPublishEvent> indexFactory = new BTreeIndexFactory<String, StoredPublishEvent>();
indexFactory.setKeyCodec(StringCodec.INSTANCE);
m_qos2Store = (SortedIndex<String, StoredPublishEvent>) m_multiIndexFactory.openOrCreate("qos2Store", indexFactory);
}
public void storeRetained(String topic, ByteBuffer message, AbstractMessage.QOSType qos) {
if (!message.hasRemaining()) {
//clean the message from topic
m_retainedStore.remove(topic);
} else {
//store the message to the topic
byte[] raw = new byte[message.remaining()];
message.get(raw);
m_retainedStore.put(topic, new StoredMessage(raw, qos, topic));
}
}
public Collection<StoredMessage> searchMatching(IMatchingCondition condition) {
LOG.debug("searchMatching scanning all retained messages, presents are {}", m_retainedStore.size());
List<StoredMessage> results = new ArrayList<StoredMessage>();
for (Map.Entry<String, StoredMessage> entry : m_retainedStore) {
StoredMessage storedMsg = entry.getValue();
if (condition.match(entry.getKey())) {
results.add(storedMsg);
}
}
return results;
}
public void storePublishForFuture(PublishEvent evt) {
List<StoredPublishEvent> storedEvents;
String clientID = evt.getClientID();
if (!m_persistentMessageStore.containsKey(clientID)) {
storedEvents = new ArrayList<StoredPublishEvent>();
} else {
storedEvents = m_persistentMessageStore.get(clientID);
}
storedEvents.add(convertToStored(evt));
m_persistentMessageStore.put(clientID, storedEvents);
//NB rewind the evt message content
LOG.debug("Stored published message for client <{}> on topic <{}>", clientID, evt.getTopic());
}
public List<PublishEvent> retrivePersistedPublishes(String clientID) {
List<StoredPublishEvent> storedEvts = m_persistentMessageStore.get(clientID);
if (storedEvts == null) {
return null;
}
List<PublishEvent> liveEvts = new ArrayList<PublishEvent>();
for (StoredPublishEvent storedEvt : storedEvts) {
liveEvts.add(convertFromStored(storedEvt));
}
return liveEvts;
}
public void cleanPersistedPublishMessage(String clientID, int messageID) {
List<StoredPublishEvent> events = m_persistentMessageStore.get(clientID);
if (events == null) {
return;
}
StoredPublishEvent toRemoveEvt = null;
for (StoredPublishEvent evt : events) {
if (evt.getMessageID() == messageID) {
toRemoveEvt = evt;
}
}
events.remove(toRemoveEvt);
m_persistentMessageStore.put(clientID, events);
}
public void cleanPersistedPublishes(String clientID) {
m_persistentMessageStore.remove(clientID);
}
public void cleanInFlight(String msgID) {
m_inflightStore.remove(msgID);
}
public void addInFlight(PublishEvent evt, String publishKey) {
StoredPublishEvent storedEvt = convertToStored(evt);
m_inflightStore.put(publishKey, storedEvt);
}
public void addNewSubscription(Subscription newSubscription, String clientID) {
LOG.debug("addNewSubscription invoked with subscription {} for client {}", newSubscription, clientID);
if (!m_persistentSubscriptions.containsKey(clientID)) {
LOG.debug("clientID {} is a newcome, creating it's subscriptions set", clientID);
m_persistentSubscriptions.put(clientID, new HashSet<Subscription>());
}
Set<Subscription> subs = m_persistentSubscriptions.get(clientID);
if (!subs.contains(newSubscription)) {
LOG.debug("updating clientID {} subscriptions set with new subscription", clientID);
//TODO check the subs doesn't contain another subscription to the same topic with different
Subscription existingSubscription = null;
for (Subscription scanSub : subs) {
if (newSubscription.getTopic().equals(scanSub.getTopic())) {
existingSubscription = scanSub;
break;
}
}
if (existingSubscription != null) {
subs.remove(existingSubscription);
}
subs.add(newSubscription);
m_persistentSubscriptions.put(clientID, subs);
LOG.debug("clientID {} subscriptions set now is {}", clientID, subs);
}
}
public void removeAllSubscriptions(String clientID) {
m_persistentSubscriptions.remove(clientID);
}
public List<Subscription> retrieveAllSubscriptions() {
List<Subscription> allSubscriptions = new ArrayList<Subscription>();
for (Map.Entry<String, Set<Subscription>> entry : m_persistentSubscriptions) {
allSubscriptions.addAll(entry.getValue());
}
LOG.debug("retrieveAllSubscriptions returning subs {}", allSubscriptions);
return allSubscriptions;
}
public void close() {
LOG.debug("closing disk storage");
try {
pageFactory.close();
} catch (IOException ex) {
LOG.error(null, ex);
}
}
/*-------- QoS 2 storage management --------------*/
public void persistQoS2Message(String publishKey, PublishEvent evt) {
LOG.debug("persistQoS2Message store pubKey {}, evt {}", publishKey, evt);
m_qos2Store.put(publishKey, convertToStored(evt));
}
public void removeQoS2Message(String publishKey) {
m_qos2Store.remove(publishKey);
}
public PublishEvent retrieveQoS2Message(String publishKey) {
StoredPublishEvent storedEvt = m_qos2Store.get(publishKey);
return convertFromStored(storedEvt);
}
private StoredPublishEvent convertToStored(PublishEvent evt) {
StoredPublishEvent storedEvt = new StoredPublishEvent(evt);
return storedEvt;
}
private PublishEvent convertFromStored(StoredPublishEvent evt) {
byte[] message = evt.getMessage();
ByteBuffer bbmessage = ByteBuffer.wrap(message);
//bbmessage.flip();
PublishEvent liveEvt = new PublishEvent(evt.getTopic(), evt.getQos(),
bbmessage, evt.isRetain(), evt.getClientID(), evt.getMessageID(), null);
return liveEvt;
}
}
| |
/*
* Copyright 2002-2013 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.http;
import java.io.Serializable;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.springframework.util.Assert;
import org.springframework.util.InvalidMimeTypeException;
import org.springframework.util.MimeType;
import org.springframework.util.MimeTypeUtils;
import org.springframework.util.StringUtils;
import org.springframework.util.comparator.CompoundComparator;
/**
* A sub-class of {@link MimeType} that adds support for quality parameters as defined
* in the HTTP specification.
*
* @author Arjen Poutsma
* @author Juergen Hoeller
* @author Rossen Stoyanchev
* @since 3.0
* @see <a href="http://tools.ietf.org/html/rfc2616#section-3.7">HTTP 1.1, section 3.7</a>
*/
public class MediaType extends MimeType implements Serializable {
private static final long serialVersionUID = 2069937152339670231L;
/**
* Public constant media type that includes all media ranges (i.e. "*/*").
*/
public static final MediaType ALL;
/**
* A String equivalent of {@link MediaType#ALL}.
*/
public static final String ALL_VALUE = "*/*";
/**
* Public constant media type for {@code application/atom+xml}.
*/
public final static MediaType APPLICATION_ATOM_XML;
/**
* A String equivalent of {@link MediaType#APPLICATION_ATOM_XML}.
*/
public final static String APPLICATION_ATOM_XML_VALUE = "application/atom+xml";
/**
* Public constant media type for {@code application/x-www-form-urlencoded}.
* */
public final static MediaType APPLICATION_FORM_URLENCODED;
/**
* A String equivalent of {@link MediaType#APPLICATION_FORM_URLENCODED}.
*/
public final static String APPLICATION_FORM_URLENCODED_VALUE = "application/x-www-form-urlencoded";
/**
* Public constant media type for {@code application/json}.
* */
public final static MediaType APPLICATION_JSON;
/**
* A String equivalent of {@link MediaType#APPLICATION_JSON}.
*/
public final static String APPLICATION_JSON_VALUE = "application/json";
/**
* Public constant media type for {@code application/octet-stream}.
* */
public final static MediaType APPLICATION_OCTET_STREAM;
/**
* A String equivalent of {@link MediaType#APPLICATION_OCTET_STREAM}.
*/
public final static String APPLICATION_OCTET_STREAM_VALUE = "application/octet-stream";
/**
* Public constant media type for {@code application/xhtml+xml}.
* */
public final static MediaType APPLICATION_XHTML_XML;
/**
* A String equivalent of {@link MediaType#APPLICATION_XHTML_XML}.
*/
public final static String APPLICATION_XHTML_XML_VALUE = "application/xhtml+xml";
/**
* Public constant media type for {@code application/xml}.
*/
public final static MediaType APPLICATION_XML;
/**
* A String equivalent of {@link MediaType#APPLICATION_XML}.
*/
public final static String APPLICATION_XML_VALUE = "application/xml";
/**
* Public constant media type for {@code image/gif}.
*/
public final static MediaType IMAGE_GIF;
/**
* A String equivalent of {@link MediaType#IMAGE_GIF}.
*/
public final static String IMAGE_GIF_VALUE = "image/gif";
/**
* Public constant media type for {@code image/jpeg}.
*/
public final static MediaType IMAGE_JPEG;
/**
* A String equivalent of {@link MediaType#IMAGE_JPEG}.
*/
public final static String IMAGE_JPEG_VALUE = "image/jpeg";
/**
* Public constant media type for {@code image/png}.
*/
public final static MediaType IMAGE_PNG;
/**
* A String equivalent of {@link MediaType#IMAGE_PNG}.
*/
public final static String IMAGE_PNG_VALUE = "image/png";
/**
* Public constant media type for {@code multipart/form-data}.
* */
public final static MediaType MULTIPART_FORM_DATA;
/**
* A String equivalent of {@link MediaType#MULTIPART_FORM_DATA}.
*/
public final static String MULTIPART_FORM_DATA_VALUE = "multipart/form-data";
/**
* Public constant media type for {@code text/html}.
* */
public final static MediaType TEXT_HTML;
/**
* A String equivalent of {@link MediaType#TEXT_HTML}.
*/
public final static String TEXT_HTML_VALUE = "text/html";
/**
* Public constant media type for {@code text/plain}.
* */
public final static MediaType TEXT_PLAIN;
/**
* A String equivalent of {@link MediaType#TEXT_PLAIN}.
*/
public final static String TEXT_PLAIN_VALUE = "text/plain";
/**
* Public constant media type for {@code text/xml}.
* */
public final static MediaType TEXT_XML;
/**
* A String equivalent of {@link MediaType#TEXT_XML}.
*/
public final static String TEXT_XML_VALUE = "text/xml";
private static final String PARAM_QUALITY_FACTOR = "q";
static {
ALL = valueOf(ALL_VALUE);
APPLICATION_ATOM_XML = valueOf(APPLICATION_ATOM_XML_VALUE);
APPLICATION_FORM_URLENCODED = valueOf(APPLICATION_FORM_URLENCODED_VALUE);
APPLICATION_JSON = valueOf(APPLICATION_JSON_VALUE);
APPLICATION_OCTET_STREAM = valueOf(APPLICATION_OCTET_STREAM_VALUE);
APPLICATION_XHTML_XML = valueOf(APPLICATION_XHTML_XML_VALUE);
APPLICATION_XML = valueOf(APPLICATION_XML_VALUE);
IMAGE_GIF = valueOf(IMAGE_GIF_VALUE);
IMAGE_JPEG = valueOf(IMAGE_JPEG_VALUE);
IMAGE_PNG = valueOf(IMAGE_PNG_VALUE);
MULTIPART_FORM_DATA = valueOf(MULTIPART_FORM_DATA_VALUE);
TEXT_HTML = valueOf(TEXT_HTML_VALUE);
TEXT_PLAIN = valueOf(TEXT_PLAIN_VALUE);
TEXT_XML = valueOf(TEXT_XML_VALUE);
}
/**
* Create a new {@code MediaType} for the given primary type.
* <p>The {@linkplain #getSubtype() subtype} is set to "*", parameters empty.
* @param type the primary type
* @throws IllegalArgumentException if any of the parameters contain illegal characters
*/
public MediaType(String type) {
super(type);
}
/**
* Create a new {@code MediaType} for the given primary type and subtype.
* <p>The parameters are empty.
* @param type the primary type
* @param subtype the subtype
* @throws IllegalArgumentException if any of the parameters contain illegal characters
*/
public MediaType(String type, String subtype) {
super(type, subtype, Collections.<String, String>emptyMap());
}
/**
* Create a new {@code MediaType} for the given type, subtype, and character set.
* @param type the primary type
* @param subtype the subtype
* @param charset the character set
* @throws IllegalArgumentException if any of the parameters contain illegal characters
*/
public MediaType(String type, String subtype, Charset charset) {
super(type, subtype, charset);
}
/**
* Create a new {@code MediaType} for the given type, subtype, and quality value.
* @param type the primary type
* @param subtype the subtype
* @param qualityValue the quality value
* @throws IllegalArgumentException if any of the parameters contain illegal characters
*/
public MediaType(String type, String subtype, double qualityValue) {
this(type, subtype, Collections.singletonMap(PARAM_QUALITY_FACTOR, Double.toString(qualityValue)));
}
/**
* Copy-constructor that copies the type and subtype of the given {@code MediaType},
* and allows for different parameter.
* @param other the other media type
* @param parameters the parameters, may be {@code null}
* @throws IllegalArgumentException if any of the parameters contain illegal characters
*/
public MediaType(MediaType other, Map<String, String> parameters) {
super(other.getType(), other.getSubtype(), parameters);
}
/**
* Create a new {@code MediaType} for the given type, subtype, and parameters.
* @param type the primary type
* @param subtype the subtype
* @param parameters the parameters, may be {@code null}
* @throws IllegalArgumentException if any of the parameters contain illegal characters
*/
public MediaType(String type, String subtype, Map<String, String> parameters) {
super(type, subtype, parameters);
}
protected void checkParameters(String attribute, String value) {
super.checkParameters(attribute, value);
if (PARAM_QUALITY_FACTOR.equals(attribute)) {
value = unquote(value);
double d = Double.parseDouble(value);
Assert.isTrue(d >= 0D && d <= 1D,
"Invalid quality value \"" + value + "\": should be between 0.0 and 1.0");
}
}
/**
* Return the quality value, as indicated by a {@code q} parameter, if any.
* Defaults to {@code 1.0}.
* @return the quality factory
*/
public double getQualityValue() {
String qualityFactory = getParameter(PARAM_QUALITY_FACTOR);
return (qualityFactory != null ? Double.parseDouble(unquote(qualityFactory)) : 1D);
}
/**
* Indicate whether this {@code MediaType} includes the given media type.
* <p>For instance, {@code text/*} includes {@code text/plain} and {@code text/html}, and {@code application/*+xml}
* includes {@code application/soap+xml}, etc. This method is <b>not</b> symmetric.
* @param other the reference media type with which to compare
* @return {@code true} if this media type includes the given media type; {@code false} otherwise
*/
public boolean includes(MediaType other) {
return super.includes(other);
}
/**
* Indicate whether this {@code MediaType} is compatible with the given media type.
* <p>For instance, {@code text/*} is compatible with {@code text/plain}, {@code text/html}, and vice versa.
* In effect, this method is similar to {@link #includes(MediaType)}, except that it <b>is</b> symmetric.
* @param other the reference media type with which to compare
* @return {@code true} if this media type is compatible with the given media type; {@code false} otherwise
*/
public boolean isCompatibleWith(MediaType other) {
return super.isCompatibleWith(other);
}
/**
* Return a replica of this instance with the quality value of the given MediaType.
* @return the same instance if the given MediaType doesn't have a quality value, or a new one otherwise
*/
public MediaType copyQualityValue(MediaType mediaType) {
if (!mediaType.getParameters().containsKey(PARAM_QUALITY_FACTOR)) {
return this;
}
Map<String, String> params = new LinkedHashMap<String, String>(getParameters());
params.put(PARAM_QUALITY_FACTOR, mediaType.getParameters().get(PARAM_QUALITY_FACTOR));
return new MediaType(this, params);
}
/**
* Return a replica of this instance with its quality value removed.
* @return the same instance if the media type doesn't contain a quality value, or a new one otherwise
*/
public MediaType removeQualityValue() {
if (!getParameters().containsKey(PARAM_QUALITY_FACTOR)) {
return this;
}
Map<String, String> params = new LinkedHashMap<String, String>(getParameters());
params.remove(PARAM_QUALITY_FACTOR);
return new MediaType(this, params);
}
/**
* Parse the given String value into a {@code MediaType} object,
* with this method name following the 'valueOf' naming convention
* (as supported by {@link org.springframework.core.convert.ConversionService}.
* @see #parseMediaType(String)
*/
public static MediaType valueOf(String value) {
return parseMediaType(value);
}
/**
* Parse the given String into a single {@code MediaType}.
* @param mediaType the string to parse
* @return the media type
* @throws InvalidMediaTypeException if the string cannot be parsed
*/
public static MediaType parseMediaType(String mediaType) {
MimeType type;
try {
type = MimeTypeUtils.parseMimeType(mediaType);
}
catch (InvalidMimeTypeException ex) {
throw new InvalidMediaTypeException(ex);
}
try {
return new MediaType(type.getType(), type.getSubtype(), type.getParameters());
}
catch (IllegalArgumentException ex) {
throw new InvalidMediaTypeException(mediaType, ex.getMessage());
}
}
/**
* Parse the given, comma-separated string into a list of {@code MediaType} objects.
* <p>This method can be used to parse an Accept or Content-Type header.
* @param mediaTypes the string to parse
* @return the list of media types
* @throws IllegalArgumentException if the string cannot be parsed
*/
public static List<MediaType> parseMediaTypes(String mediaTypes) {
if (!StringUtils.hasLength(mediaTypes)) {
return Collections.emptyList();
}
String[] tokens = mediaTypes.split(",\\s*");
List<MediaType> result = new ArrayList<MediaType>(tokens.length);
for (String token : tokens) {
result.add(parseMediaType(token));
}
return result;
}
/**
* Return a string representation of the given list of {@code MediaType} objects.
* <p>This method can be used to for an {@code Accept} or {@code Content-Type} header.
* @param mediaTypes the string to parse
* @return the list of media types
* @throws IllegalArgumentException if the String cannot be parsed
*/
public static String toString(Collection<MediaType> mediaTypes) {
return MimeTypeUtils.toString(mediaTypes);
}
/**
* Sorts the given list of {@code MediaType} objects by specificity.
* <p>Given two media types:
* <ol>
* <li>if either media type has a {@linkplain #isWildcardType() wildcard type}, then the media type without the
* wildcard is ordered before the other.</li>
* <li>if the two media types have different {@linkplain #getType() types}, then they are considered equal and
* remain their current order.</li>
* <li>if either media type has a {@linkplain #isWildcardSubtype() wildcard subtype}, then the media type without
* the wildcard is sorted before the other.</li>
* <li>if the two media types have different {@linkplain #getSubtype() subtypes}, then they are considered equal
* and remain their current order.</li>
* <li>if the two media types have different {@linkplain #getQualityValue() quality value}, then the media type
* with the highest quality value is ordered before the other.</li>
* <li>if the two media types have a different amount of {@linkplain #getParameter(String) parameters}, then the
* media type with the most parameters is ordered before the other.</li>
* </ol>
* <p>For example:
* <blockquote>audio/basic < audio/* < */*</blockquote>
* <blockquote>audio/* < audio/*;q=0.7; audio/*;q=0.3</blockquote>
* <blockquote>audio/basic;level=1 < audio/basic</blockquote>
* <blockquote>audio/basic == text/html</blockquote>
* <blockquote>audio/basic == audio/wave</blockquote>
* @param mediaTypes the list of media types to be sorted
* @see <a href="http://tools.ietf.org/html/rfc2616#section-14.1">HTTP 1.1, section 14.1</a>
*/
public static void sortBySpecificity(List<MediaType> mediaTypes) {
Assert.notNull(mediaTypes, "'mediaTypes' must not be null");
if (mediaTypes.size() > 1) {
Collections.sort(mediaTypes, SPECIFICITY_COMPARATOR);
}
}
/**
* Sorts the given list of {@code MediaType} objects by quality value.
* <p>Given two media types:
* <ol>
* <li>if the two media types have different {@linkplain #getQualityValue() quality value}, then the media type
* with the highest quality value is ordered before the other.</li>
* <li>if either media type has a {@linkplain #isWildcardType() wildcard type}, then the media type without the
* wildcard is ordered before the other.</li>
* <li>if the two media types have different {@linkplain #getType() types}, then they are considered equal and
* remain their current order.</li>
* <li>if either media type has a {@linkplain #isWildcardSubtype() wildcard subtype}, then the media type without
* the wildcard is sorted before the other.</li>
* <li>if the two media types have different {@linkplain #getSubtype() subtypes}, then they are considered equal
* and remain their current order.</li>
* <li>if the two media types have a different amount of {@linkplain #getParameter(String) parameters}, then the
* media type with the most parameters is ordered before the other.</li>
* </ol>
* @param mediaTypes the list of media types to be sorted
* @see #getQualityValue()
*/
public static void sortByQualityValue(List<MediaType> mediaTypes) {
Assert.notNull(mediaTypes, "'mediaTypes' must not be null");
if (mediaTypes.size() > 1) {
Collections.sort(mediaTypes, QUALITY_VALUE_COMPARATOR);
}
}
/**
* Sorts the given list of {@code MediaType} objects by specificity as the
* primary criteria and quality value the secondary.
* @see MediaType#sortBySpecificity(List)
* @see MediaType#sortByQualityValue(List)
*/
public static void sortBySpecificityAndQuality(List<MediaType> mediaTypes) {
Assert.notNull(mediaTypes, "'mediaTypes' must not be null");
if (mediaTypes.size() > 1) {
Collections.sort(mediaTypes, new CompoundComparator<MediaType>(
MediaType.SPECIFICITY_COMPARATOR, MediaType.QUALITY_VALUE_COMPARATOR));
}
}
/**
* Comparator used by {@link #sortByQualityValue(List)}.
*/
public static final Comparator<MediaType> QUALITY_VALUE_COMPARATOR = new Comparator<MediaType>() {
@Override
public int compare(MediaType mediaType1, MediaType mediaType2) {
double quality1 = mediaType1.getQualityValue();
double quality2 = mediaType2.getQualityValue();
int qualityComparison = Double.compare(quality2, quality1);
if (qualityComparison != 0) {
return qualityComparison; // audio/*;q=0.7 < audio/*;q=0.3
}
else if (mediaType1.isWildcardType() && !mediaType2.isWildcardType()) { // */* < audio/*
return 1;
}
else if (mediaType2.isWildcardType() && !mediaType1.isWildcardType()) { // audio/* > */*
return -1;
}
else if (!mediaType1.getType().equals(mediaType2.getType())) { // audio/basic == text/html
return 0;
}
else { // mediaType1.getType().equals(mediaType2.getType())
if (mediaType1.isWildcardSubtype() && !mediaType2.isWildcardSubtype()) { // audio/* < audio/basic
return 1;
}
else if (mediaType2.isWildcardSubtype() && !mediaType1.isWildcardSubtype()) { // audio/basic > audio/*
return -1;
}
else if (!mediaType1.getSubtype().equals(mediaType2.getSubtype())) { // audio/basic == audio/wave
return 0;
}
else {
int paramsSize1 = mediaType1.getParameters().size();
int paramsSize2 = mediaType2.getParameters().size();
return (paramsSize2 < paramsSize1 ? -1 : (paramsSize2 == paramsSize1 ? 0 : 1)); // audio/basic;level=1 < audio/basic
}
}
}
};
/**
* Comparator used by {@link #sortBySpecificity(List)}.
*/
public static final Comparator<MediaType> SPECIFICITY_COMPARATOR = new SpecificityComparator<MediaType>() {
@Override
protected int compareParameters(MediaType mediaType1, MediaType mediaType2) {
double quality1 = mediaType1.getQualityValue();
double quality2 = mediaType2.getQualityValue();
int qualityComparison = Double.compare(quality2, quality1);
if (qualityComparison != 0) {
return qualityComparison; // audio/*;q=0.7 < audio/*;q=0.3
}
return super.compareParameters(mediaType1, mediaType2);
}
};
}
| |
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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 General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This file is available under and governed by the GNU General Public
* License version 2 only, as published by the Free Software Foundation.
* However, the following notice accompanied the original version of this
* file:
*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/publicdomain/zero/1.0/
*/
package java.util.concurrent.atomic;
import sun.misc.Unsafe;
/**
* An {@code int} value that may be updated atomically. See the
* {@link java.util.concurrent.atomic} package specification for
* description of the properties of atomic variables. An
* {@code AtomicInteger} is used in applications such as atomically
* incremented counters, and cannot be used as a replacement for an
* {@link java.lang.Integer}. However, this class does extend
* {@code Number} to allow uniform access by tools and utilities that
* deal with numerically-based classes.
*
* @since 1.5
* @author Doug Lea
*/
public class AtomicInteger extends Number implements java.io.Serializable {
private static final long serialVersionUID = 6214790243416807050L;
// setup to use Unsafe.compareAndSwapInt for updates
private static final Unsafe unsafe = Unsafe.getUnsafe();
private static final long valueOffset;
static {
try {
valueOffset = unsafe.objectFieldOffset
(AtomicInteger.class.getDeclaredField("value"));
} catch (Exception ex) { throw new Error(ex); }
}
private volatile int value;
/**
* Creates a new AtomicInteger with the given initial value.
*
* @param initialValue the initial value
*/
public AtomicInteger(int initialValue) {
value = initialValue;
}
/**
* Creates a new AtomicInteger with initial value {@code 0}.
*/
public AtomicInteger() {
}
/**
* Gets the current value.
*
* @return the current value
*/
public final int get() {
return value;
}
/**
* Sets to the given value.
*
* @param newValue the new value
*/
public final void set(int newValue) {
value = newValue;
}
/**
* Eventually sets to the given value.
*
* @param newValue the new value
* @since 1.6
*/
public final void lazySet(int newValue) {
unsafe.putOrderedInt(this, valueOffset, newValue);
}
/**
* Atomically sets to the given value and returns the old value.
*
* @param newValue the new value
* @return the previous value
*/
public final int getAndSet(int newValue) {
for (;;) {
int current = get();
if (compareAndSet(current, newValue))
return current;
}
}
/**
* Atomically sets the value to the given updated value
* if the current value {@code ==} the expected value.
*
* @param expect the expected value
* @param update the new value
* @return true if successful. False return indicates that
* the actual value was not equal to the expected value.
*/
public final boolean compareAndSet(int expect, int update) {
return unsafe.compareAndSwapInt(this, valueOffset, expect, update);
}
/**
* Atomically sets the value to the given updated value
* if the current value {@code ==} the expected value.
*
* <p>May <a href="package-summary.html#Spurious">fail spuriously</a>
* and does not provide ordering guarantees, so is only rarely an
* appropriate alternative to {@code compareAndSet}.
*
* @param expect the expected value
* @param update the new value
* @return true if successful.
*/
public final boolean weakCompareAndSet(int expect, int update) {
return unsafe.compareAndSwapInt(this, valueOffset, expect, update);
}
/**
* Atomically increments by one the current value.
*
* @return the previous value
*/
public final int getAndIncrement() {
for (;;) {
int current = get();
int next = current + 1;
if (compareAndSet(current, next))
return current;
}
}
/**
* Atomically decrements by one the current value.
*
* @return the previous value
*/
public final int getAndDecrement() {
for (;;) {
int current = get();
int next = current - 1;
if (compareAndSet(current, next))
return current;
}
}
/**
* Atomically adds the given value to the current value.
*
* @param delta the value to add
* @return the previous value
*/
public final int getAndAdd(int delta) {
for (;;) {
int current = get();
int next = current + delta;
if (compareAndSet(current, next))
return current;
}
}
/**
* Atomically increments by one the current value.
*
* @return the updated value
*/
public final int incrementAndGet() {
for (;;) {
int current = get();
int next = current + 1;
if (compareAndSet(current, next))
return next;
}
}
/**
* Atomically decrements by one the current value.
*
* @return the updated value
*/
public final int decrementAndGet() {
for (;;) {
int current = get();
int next = current - 1;
if (compareAndSet(current, next))
return next;
}
}
/**
* Atomically adds the given value to the current value.
*
* @param delta the value to add
* @return the updated value
*/
public final int addAndGet(int delta) {
for (;;) {
int current = get();
int next = current + delta;
if (compareAndSet(current, next))
return next;
}
}
/**
* Returns the String representation of the current value.
* @return the String representation of the current value.
*/
public String toString() {
return Integer.toString(get());
}
public int intValue() {
return get();
}
public long longValue() {
return (long)get();
}
public float floatValue() {
return (float)get();
}
public double doubleValue() {
return (double)get();
}
}
| |
/* Generated by camel build tools - do NOT edit this file! */
package org.apache.camel.component.olingo2;
import java.util.Map;
import org.apache.camel.CamelContext;
import org.apache.camel.spi.ConfigurerStrategy;
import org.apache.camel.spi.GeneratedPropertyConfigurer;
import org.apache.camel.spi.PropertyConfigurerGetter;
import org.apache.camel.util.CaseInsensitiveMap;
import org.apache.camel.support.component.PropertyConfigurerSupport;
/**
* Generated by camel build tools - do NOT edit this file!
*/
@SuppressWarnings("unchecked")
public class Olingo2EndpointConfigurer extends PropertyConfigurerSupport implements GeneratedPropertyConfigurer, PropertyConfigurerGetter {
private static final Map<String, Object> ALL_OPTIONS;
static {
Map<String, Object> map = new CaseInsensitiveMap();
map.put("apiName", org.apache.camel.component.olingo2.internal.Olingo2ApiName.class);
map.put("methodName", java.lang.String.class);
map.put("connectTimeout", int.class);
map.put("contentType", java.lang.String.class);
map.put("entityProviderReadProperties", org.apache.olingo.odata2.api.ep.EntityProviderReadProperties.class);
map.put("entityProviderWriteProperties", org.apache.olingo.odata2.api.ep.EntityProviderWriteProperties.class);
map.put("filterAlreadySeen", boolean.class);
map.put("httpHeaders", java.util.Map.class);
map.put("inBody", java.lang.String.class);
map.put("proxy", org.apache.http.HttpHost.class);
map.put("serviceUri", java.lang.String.class);
map.put("socketTimeout", int.class);
map.put("bridgeErrorHandler", boolean.class);
map.put("sendEmptyMessageWhenIdle", boolean.class);
map.put("splitResult", boolean.class);
map.put("exceptionHandler", org.apache.camel.spi.ExceptionHandler.class);
map.put("exchangePattern", org.apache.camel.ExchangePattern.class);
map.put("pollStrategy", org.apache.camel.spi.PollingConsumerPollStrategy.class);
map.put("lazyStartProducer", boolean.class);
map.put("basicPropertyBinding", boolean.class);
map.put("httpAsyncClientBuilder", org.apache.http.impl.nio.client.HttpAsyncClientBuilder.class);
map.put("httpClientBuilder", org.apache.http.impl.client.HttpClientBuilder.class);
map.put("synchronous", boolean.class);
map.put("backoffErrorThreshold", int.class);
map.put("backoffIdleThreshold", int.class);
map.put("backoffMultiplier", int.class);
map.put("delay", long.class);
map.put("greedy", boolean.class);
map.put("initialDelay", long.class);
map.put("repeatCount", long.class);
map.put("runLoggingLevel", org.apache.camel.LoggingLevel.class);
map.put("scheduledExecutorService", java.util.concurrent.ScheduledExecutorService.class);
map.put("scheduler", java.lang.Object.class);
map.put("schedulerProperties", java.util.Map.class);
map.put("startScheduler", boolean.class);
map.put("timeUnit", java.util.concurrent.TimeUnit.class);
map.put("useFixedDelay", boolean.class);
map.put("sslContextParameters", org.apache.camel.support.jsse.SSLContextParameters.class);
ALL_OPTIONS = map;
ConfigurerStrategy.addConfigurerClearer(Olingo2EndpointConfigurer::clearConfigurers);
}
@Override
public boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) {
Olingo2Endpoint target = (Olingo2Endpoint) obj;
switch (ignoreCase ? name.toLowerCase() : name) {
case "backofferrorthreshold":
case "backoffErrorThreshold": target.setBackoffErrorThreshold(property(camelContext, int.class, value)); return true;
case "backoffidlethreshold":
case "backoffIdleThreshold": target.setBackoffIdleThreshold(property(camelContext, int.class, value)); return true;
case "backoffmultiplier":
case "backoffMultiplier": target.setBackoffMultiplier(property(camelContext, int.class, value)); return true;
case "basicpropertybinding":
case "basicPropertyBinding": target.setBasicPropertyBinding(property(camelContext, boolean.class, value)); return true;
case "bridgeerrorhandler":
case "bridgeErrorHandler": target.setBridgeErrorHandler(property(camelContext, boolean.class, value)); return true;
case "connecttimeout":
case "connectTimeout": target.getConfiguration().setConnectTimeout(property(camelContext, int.class, value)); return true;
case "contenttype":
case "contentType": target.getConfiguration().setContentType(property(camelContext, java.lang.String.class, value)); return true;
case "delay": target.setDelay(property(camelContext, long.class, value)); return true;
case "entityproviderreadproperties":
case "entityProviderReadProperties": target.getConfiguration().setEntityProviderReadProperties(property(camelContext, org.apache.olingo.odata2.api.ep.EntityProviderReadProperties.class, value)); return true;
case "entityproviderwriteproperties":
case "entityProviderWriteProperties": target.getConfiguration().setEntityProviderWriteProperties(property(camelContext, org.apache.olingo.odata2.api.ep.EntityProviderWriteProperties.class, value)); return true;
case "exceptionhandler":
case "exceptionHandler": target.setExceptionHandler(property(camelContext, org.apache.camel.spi.ExceptionHandler.class, value)); return true;
case "exchangepattern":
case "exchangePattern": target.setExchangePattern(property(camelContext, org.apache.camel.ExchangePattern.class, value)); return true;
case "filteralreadyseen":
case "filterAlreadySeen": target.getConfiguration().setFilterAlreadySeen(property(camelContext, boolean.class, value)); return true;
case "greedy": target.setGreedy(property(camelContext, boolean.class, value)); return true;
case "httpasyncclientbuilder":
case "httpAsyncClientBuilder": target.getConfiguration().setHttpAsyncClientBuilder(property(camelContext, org.apache.http.impl.nio.client.HttpAsyncClientBuilder.class, value)); return true;
case "httpclientbuilder":
case "httpClientBuilder": target.getConfiguration().setHttpClientBuilder(property(camelContext, org.apache.http.impl.client.HttpClientBuilder.class, value)); return true;
case "httpheaders":
case "httpHeaders": target.getConfiguration().setHttpHeaders(property(camelContext, java.util.Map.class, value)); return true;
case "inbody":
case "inBody": target.setInBody(property(camelContext, java.lang.String.class, value)); return true;
case "initialdelay":
case "initialDelay": target.setInitialDelay(property(camelContext, long.class, value)); return true;
case "lazystartproducer":
case "lazyStartProducer": target.setLazyStartProducer(property(camelContext, boolean.class, value)); return true;
case "pollstrategy":
case "pollStrategy": target.setPollStrategy(property(camelContext, org.apache.camel.spi.PollingConsumerPollStrategy.class, value)); return true;
case "proxy": target.getConfiguration().setProxy(property(camelContext, org.apache.http.HttpHost.class, value)); return true;
case "repeatcount":
case "repeatCount": target.setRepeatCount(property(camelContext, long.class, value)); return true;
case "runlogginglevel":
case "runLoggingLevel": target.setRunLoggingLevel(property(camelContext, org.apache.camel.LoggingLevel.class, value)); return true;
case "scheduledexecutorservice":
case "scheduledExecutorService": target.setScheduledExecutorService(property(camelContext, java.util.concurrent.ScheduledExecutorService.class, value)); return true;
case "scheduler": target.setScheduler(property(camelContext, java.lang.Object.class, value)); return true;
case "schedulerproperties":
case "schedulerProperties": target.setSchedulerProperties(property(camelContext, java.util.Map.class, value)); return true;
case "sendemptymessagewhenidle":
case "sendEmptyMessageWhenIdle": target.setSendEmptyMessageWhenIdle(property(camelContext, boolean.class, value)); return true;
case "serviceuri":
case "serviceUri": target.getConfiguration().setServiceUri(property(camelContext, java.lang.String.class, value)); return true;
case "sockettimeout":
case "socketTimeout": target.getConfiguration().setSocketTimeout(property(camelContext, int.class, value)); return true;
case "splitresult":
case "splitResult": target.getConfiguration().setSplitResult(property(camelContext, boolean.class, value)); return true;
case "sslcontextparameters":
case "sslContextParameters": target.getConfiguration().setSslContextParameters(property(camelContext, org.apache.camel.support.jsse.SSLContextParameters.class, value)); return true;
case "startscheduler":
case "startScheduler": target.setStartScheduler(property(camelContext, boolean.class, value)); return true;
case "synchronous": target.setSynchronous(property(camelContext, boolean.class, value)); return true;
case "timeunit":
case "timeUnit": target.setTimeUnit(property(camelContext, java.util.concurrent.TimeUnit.class, value)); return true;
case "usefixeddelay":
case "useFixedDelay": target.setUseFixedDelay(property(camelContext, boolean.class, value)); return true;
default: return false;
}
}
@Override
public Map<String, Object> getAllOptions(Object target) {
return ALL_OPTIONS;
}
public static void clearBootstrapConfigurers() {
}
public static void clearConfigurers() {
ALL_OPTIONS.clear();
}
@Override
public Object getOptionValue(Object obj, String name, boolean ignoreCase) {
Olingo2Endpoint target = (Olingo2Endpoint) obj;
switch (ignoreCase ? name.toLowerCase() : name) {
case "backofferrorthreshold":
case "backoffErrorThreshold": return target.getBackoffErrorThreshold();
case "backoffidlethreshold":
case "backoffIdleThreshold": return target.getBackoffIdleThreshold();
case "backoffmultiplier":
case "backoffMultiplier": return target.getBackoffMultiplier();
case "basicpropertybinding":
case "basicPropertyBinding": return target.isBasicPropertyBinding();
case "bridgeerrorhandler":
case "bridgeErrorHandler": return target.isBridgeErrorHandler();
case "connecttimeout":
case "connectTimeout": return target.getConfiguration().getConnectTimeout();
case "contenttype":
case "contentType": return target.getConfiguration().getContentType();
case "delay": return target.getDelay();
case "entityproviderreadproperties":
case "entityProviderReadProperties": return target.getConfiguration().getEntityProviderReadProperties();
case "entityproviderwriteproperties":
case "entityProviderWriteProperties": return target.getConfiguration().getEntityProviderWriteProperties();
case "exceptionhandler":
case "exceptionHandler": return target.getExceptionHandler();
case "exchangepattern":
case "exchangePattern": return target.getExchangePattern();
case "filteralreadyseen":
case "filterAlreadySeen": return target.getConfiguration().isFilterAlreadySeen();
case "greedy": return target.isGreedy();
case "httpasyncclientbuilder":
case "httpAsyncClientBuilder": return target.getConfiguration().getHttpAsyncClientBuilder();
case "httpclientbuilder":
case "httpClientBuilder": return target.getConfiguration().getHttpClientBuilder();
case "httpheaders":
case "httpHeaders": return target.getConfiguration().getHttpHeaders();
case "inbody":
case "inBody": return target.getInBody();
case "initialdelay":
case "initialDelay": return target.getInitialDelay();
case "lazystartproducer":
case "lazyStartProducer": return target.isLazyStartProducer();
case "pollstrategy":
case "pollStrategy": return target.getPollStrategy();
case "proxy": return target.getConfiguration().getProxy();
case "repeatcount":
case "repeatCount": return target.getRepeatCount();
case "runlogginglevel":
case "runLoggingLevel": return target.getRunLoggingLevel();
case "scheduledexecutorservice":
case "scheduledExecutorService": return target.getScheduledExecutorService();
case "scheduler": return target.getScheduler();
case "schedulerproperties":
case "schedulerProperties": return target.getSchedulerProperties();
case "sendemptymessagewhenidle":
case "sendEmptyMessageWhenIdle": return target.isSendEmptyMessageWhenIdle();
case "serviceuri":
case "serviceUri": return target.getConfiguration().getServiceUri();
case "sockettimeout":
case "socketTimeout": return target.getConfiguration().getSocketTimeout();
case "splitresult":
case "splitResult": return target.getConfiguration().isSplitResult();
case "sslcontextparameters":
case "sslContextParameters": return target.getConfiguration().getSslContextParameters();
case "startscheduler":
case "startScheduler": return target.isStartScheduler();
case "synchronous": return target.isSynchronous();
case "timeunit":
case "timeUnit": return target.getTimeUnit();
case "usefixeddelay":
case "useFixedDelay": return target.isUseFixedDelay();
default: return null;
}
}
}
| |
/*
*
* 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.airavata.registry.core.experiment.catalog.utils;
import org.apache.airavata.common.utils.AiravataUtils;
import org.apache.airavata.model.application.io.DataType;
import org.apache.airavata.model.application.io.InputDataObjectType;
import org.apache.airavata.model.application.io.OutputDataObjectType;
import org.apache.airavata.model.commons.ErrorModel;
import org.apache.airavata.model.experiment.ExperimentModel;
import org.apache.airavata.model.experiment.ExperimentSummaryModel;
import org.apache.airavata.model.experiment.UserConfigurationDataModel;
import org.apache.airavata.model.job.JobModel;
import org.apache.airavata.model.process.ProcessModel;
import org.apache.airavata.model.scheduling.ComputationalResourceSchedulingModel;
import org.apache.airavata.model.status.*;
import org.apache.airavata.model.task.TaskModel;
import org.apache.airavata.model.task.TaskTypes;
import org.apache.airavata.model.workspace.Gateway;
import org.apache.airavata.model.workspace.Project;
import org.apache.airavata.registry.core.experiment.catalog.ExperimentCatResource;
import org.apache.airavata.registry.core.experiment.catalog.resources.*;
import org.apache.airavata.registry.cpi.RegistryException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class ThriftDataModelConversion {
private final static Logger logger = LoggerFactory.getLogger(ThriftDataModelConversion.class);
public static Project getProject (ProjectResource pr) throws RegistryException {
if (pr != null) {
Project project = new Project();
project.setProjectID(pr.getId());
project.setName(pr.getName());
if (pr.getCreationTime()!=null) {
project.setCreationTime(pr.getCreationTime().getTime());
}
project.setDescription(pr.getDescription());
project.setOwner(pr.getWorker().getUser());
List<ProjectUserResource> projectUserList = pr.getProjectUserList();
List<String> sharedUsers = new ArrayList<String>();
if (projectUserList != null && !projectUserList.isEmpty()){
for (ProjectUserResource resource : projectUserList){
sharedUsers.add(resource.getUserName());
}
}
project.setSharedUsers(sharedUsers);
return project;
}
return null;
}
public static Gateway getGateway (GatewayResource resource){
Gateway gateway = new Gateway();
gateway.setGatewayId(resource.getGatewayId());
gateway.setGatewayName(resource.getGatewayName());
gateway.setDomain(resource.getDomain());
gateway.setEmailAddress(resource.getEmailAddress());
return gateway;
}
public static List<Gateway> getAllGateways (List<ExperimentCatResource> gatewayList){
List<Gateway> gateways = new ArrayList<Gateway>();
for (ExperimentCatResource resource : gatewayList){
gateways.add(getGateway((GatewayResource)resource));
}
return gateways;
}
public static ExperimentSummaryModel getExperimentSummary(ExperimentSummaryResource experimentSummaryResource) throws RegistryException {
if (experimentSummaryResource != null){
ExperimentSummaryModel experimentSummary = new ExperimentSummaryModel();
experimentSummary.setProjectId(experimentSummaryResource.getProjectId());
experimentSummary.setExperimentId(experimentSummaryResource.getExperimentId());
experimentSummary.setGatewayId(experimentSummaryResource.getGatewayId());
experimentSummary.setExecutionId(experimentSummaryResource.getExecutionId());
experimentSummary.setCreationTime(experimentSummaryResource.getCreationTime().getTime());
experimentSummary.setUserName(experimentSummaryResource.getUserName());
experimentSummary.setName(experimentSummaryResource.getExperimentName());
experimentSummary.setDescription(experimentSummaryResource.getDescription());
experimentSummary.setExperimentStatus(experimentSummaryResource.getState());
return experimentSummary;
}
return null;
}
public static ExperimentModel getExperiment(ExperimentResource experimentResource) throws RegistryException {
if (experimentResource != null){
ExperimentModel experiment = new ExperimentModel();
experiment.setProjectId(experimentResource.getProjectId());
experiment.setExperimentId(experimentResource.getExperimentId());
experiment.setGatewayId(experimentResource.getGatewayId());
experiment.setCreationTime(experimentResource.getCreationTime().getTime());
experiment.setUserName(experimentResource.getUserName());
experiment.setExperimentName(experimentResource.getExperimentName());
experiment.setExecutionId(experimentResource.getExecutionId());
experiment.setDescription(experimentResource.getDescription());
experiment.setEnableEmailNotification(experimentResource.getEnableEmailNotification());
experiment.setGatewayExecutionId(experimentResource.getGatewayExecutionId());
if (experiment.isEnableEmailNotification()){
String notificationEmails = experimentResource.getEmailAddresses();
experiment.setEmailAddresses(getEmailAddresses(notificationEmails.split(",")));
}
List<ExperimentInputResource> experimentInputs = experimentResource.getExperimentInputs();
experiment.setExperimentInputs(getExpInputs(experimentInputs));
List<ExperimentOutputResource> experimentOutputs = experimentResource.getExperimentOutputs();
experiment.setExperimentOutputs(getExpOutputs(experimentOutputs));
ExperimentStatusResource experimentStatus = experimentResource.getExperimentStatus();
if (experimentStatus != null){
experiment.setExperimentStatus(getExperimentStatus(experimentStatus));
}
List<ExperimentErrorResource> errorDetails = experimentResource.getExperimentErrors();
if (errorDetails!= null && !errorDetails.isEmpty()){
experiment.setErrors(getExperimentErrorList(errorDetails));
}
UserConfigurationDataResource userConfigurationDataResource
= experimentResource.getUserConfigurationDataResource();
if(userConfigurationDataResource != null){
experiment.setUserConfigurationData(getUserConfigData(userConfigurationDataResource));
}
return experiment;
}
return null;
}
public static InputDataObjectType getInput(Object object){
if (object != null){
InputDataObjectType dataObjectType = new InputDataObjectType();
if (object instanceof ExperimentInputResource){
ExperimentInputResource inputResource = (ExperimentInputResource) object;
dataObjectType.setName(inputResource.getInputName());
dataObjectType.setValue(inputResource.getInputValue());
dataObjectType.setType(DataType.valueOf(inputResource.getDataType()));
dataObjectType.setApplicationArgument(inputResource.getApplicationArgument());
dataObjectType.setStandardInput(inputResource.getStandardInput());
dataObjectType.setUserFriendlyDescription(inputResource.getUserFriendlyDescription());
dataObjectType.setMetaData(inputResource.getMetadata());
dataObjectType.setInputOrder(inputResource.getInputOrder());
dataObjectType.setIsRequired(inputResource.getIsRequired());
dataObjectType.setRequiredToAddedToCommandLine(inputResource.getRequiredToAddedToCmd());
dataObjectType.setDataStaged(inputResource.getDataStaged());
return dataObjectType;
}else if (object instanceof ProcessInputResource){
ProcessInputResource inputResource = (ProcessInputResource)object;
dataObjectType.setName(inputResource.getInputName());
dataObjectType.setValue(inputResource.getInputValue());
dataObjectType.setType(DataType.valueOf(inputResource.getDataType()));
dataObjectType.setApplicationArgument(inputResource.getApplicationArgument());
dataObjectType.setStandardInput(inputResource.getStandardInput());
dataObjectType.setUserFriendlyDescription(inputResource.getUserFriendlyDescription());
dataObjectType.setMetaData(inputResource.getMetadata());
dataObjectType.setInputOrder(inputResource.getInputOrder());
dataObjectType.setIsRequired(inputResource.getIsRequired());
dataObjectType.setRequiredToAddedToCommandLine(inputResource.getRequiredToAddedToCmd());
dataObjectType.setDataStaged(inputResource.getDataStaged());
return dataObjectType;
}else {
return null;
}
}
return null;
}
public static OutputDataObjectType getOutput(Object object){
if (object != null){
OutputDataObjectType dataObjectType = new OutputDataObjectType();
if (object instanceof ExperimentOutputResource){
ExperimentOutputResource outputResource = (ExperimentOutputResource)object;
dataObjectType.setName(outputResource.getOutputName());
dataObjectType.setValue(outputResource.getOutputValue());
dataObjectType.setType(DataType.valueOf(outputResource.getDataType()));
dataObjectType.setApplicationArgument(outputResource.getApplicationArgument());
dataObjectType.setIsRequired(outputResource.getIsRequired());
dataObjectType.setRequiredToAddedToCommandLine(outputResource.getRequiredToAddedToCmd());
dataObjectType.setDataMovement(outputResource.getDataMovement());
dataObjectType.setLocation(outputResource.getLocation());
dataObjectType.setSearchQuery(outputResource.getSearchQuery());
return dataObjectType;
}else if (object instanceof ProcessOutputResource) {
ProcessOutputResource outputResource = (ProcessOutputResource) object;
dataObjectType.setName(outputResource.getOutputName());
dataObjectType.setValue(outputResource.getOutputValue());
dataObjectType.setType(DataType.valueOf(outputResource.getDataType()));
dataObjectType.setApplicationArgument(outputResource.getApplicationArgument());
dataObjectType.setIsRequired(outputResource.getIsRequired());
dataObjectType.setRequiredToAddedToCommandLine(outputResource.getRequiredToAddedToCmd());
dataObjectType.setDataMovement(outputResource.getDataMovement());
dataObjectType.setLocation(outputResource.getLocation());
dataObjectType.setSearchQuery(outputResource.getSearchQuery());
return dataObjectType;
} else {
return null;
}
}
return null;
}
public static List<String> getEmailAddresses (String[] resourceList){
List<String> emailAddresses = new ArrayList<String>();
for (String email : resourceList){
emailAddresses.add(email);
}
return emailAddresses;
}
public static List<InputDataObjectType> getExpInputs (List<ExperimentInputResource> exInputList){
List<InputDataObjectType> expInputs = new ArrayList<InputDataObjectType>();
if (exInputList != null && !exInputList.isEmpty()){
for (ExperimentInputResource inputResource : exInputList){
InputDataObjectType exInput = getInput(inputResource);
expInputs.add(exInput);
}
}
return expInputs;
}
public static List<OutputDataObjectType> getExpOutputs (List<ExperimentOutputResource> experimentOutputResourceList){
List<OutputDataObjectType> exOutputs = new ArrayList<OutputDataObjectType>();
if (experimentOutputResourceList != null && !experimentOutputResourceList.isEmpty()){
for (ExperimentOutputResource outputResource : experimentOutputResourceList){
OutputDataObjectType output = getOutput(outputResource);
exOutputs.add(output);
}
}
return exOutputs;
}
public static List<InputDataObjectType> getProcessInputs (List<ProcessInputResource> processInputResources){
List<InputDataObjectType> nodeInputs = new ArrayList<InputDataObjectType>();
if (processInputResources != null && !processInputResources.isEmpty()){
for (ProcessInputResource inputResource : processInputResources){
InputDataObjectType nodeInput = getInput(inputResource);
nodeInputs.add(nodeInput);
}
}
return nodeInputs;
}
public static List<OutputDataObjectType> getProcessOutputs (List<ProcessOutputResource> processOutputResources){
List<OutputDataObjectType> processOutputs = new ArrayList<OutputDataObjectType>();
if (processOutputResources != null && !processOutputResources.isEmpty()){
for (ProcessOutputResource outputResource : processOutputResources){
OutputDataObjectType output = getOutput(outputResource);
processOutputs.add(output);
}
}
return processOutputs;
}
public static ExperimentStatus getExperimentStatus(ExperimentStatusResource status){
if (status != null){
ExperimentStatus experimentStatus = new ExperimentStatus();
experimentStatus.setState(ExperimentState.valueOf(status.getState()));
Timestamp timeOfStateChange = status.getTimeOfStateChange();
if (timeOfStateChange == null){
timeOfStateChange = AiravataUtils.getCurrentTimestamp();
}
experimentStatus.setTimeOfStateChange(timeOfStateChange.getTime());
experimentStatus.setReason(status.getReason());
return experimentStatus;
}
return null;
}
public static ProcessStatus getProcessStatus (ProcessStatusResource status){
if (status != null){
ProcessStatus processStatus = new ProcessStatus();
processStatus.setState(ProcessState.valueOf(status.getState()));
Timestamp timeOfStateChange = status.getTimeOfStateChange();
if (timeOfStateChange == null){
timeOfStateChange = AiravataUtils.getCurrentTimestamp();
}
processStatus.setTimeOfStateChange(timeOfStateChange.getTime());
processStatus.setReason(status.getReason());
return processStatus;
}
return null;
}
public static TaskStatus getTaskStatus (TaskStatusResource status){
if (status != null){
TaskStatus taskStatus = new TaskStatus();
taskStatus.setState(TaskState.valueOf(status.getState()));
Timestamp timeOfStateChange = status.getTimeOfStateChange();
if (timeOfStateChange == null){
timeOfStateChange = AiravataUtils.getCurrentTimestamp();
}
taskStatus.setTimeOfStateChange(timeOfStateChange.getTime());
taskStatus.setReason(status.getReason());
return taskStatus;
}
return null;
}
public static JobStatus getJobStatus (JobStatusResource status){
if (status != null){
JobStatus jobStatus = new JobStatus();
jobStatus.setJobState(JobState.valueOf(status.getState()));
Timestamp timeOfStateChange = status.getTimeOfStateChange();
if (timeOfStateChange == null){
timeOfStateChange = AiravataUtils.getCurrentTimestamp();
}
jobStatus.setTimeOfStateChange(timeOfStateChange.getTime());
jobStatus.setReason(status.getReason());
return jobStatus;
}
return null;
}
public static ProcessModel getProcesModel (ProcessResource processResource) throws RegistryException {
if (processResource != null){
ProcessModel processModel = new ProcessModel();
processModel.setProcessId(processResource.getProcessId());
processModel.setExperimentId(processResource.getExperimentId());
processModel.setCreationTime(processResource.getCreationTime().getTime());
processModel.setLastUpdateTime(processResource.getLastUpdateTime().getTime());
processModel.setProcessDetail(processResource.getProcessDetail());
processModel.setApplicationInterfaceId(processResource.getApplicationInterfaceId());
processModel.setTaskDag(processResource.getTaskDag());
processModel.setGatewayExecutionId(processResource.getGatewayExecutionId());
processModel.setApplicationDeploymentId(processResource.getApplicationDeploymentId());
processModel.setComputeResourceId(processResource.getComputeResourceId());
processModel.setEnableEmailNotification(processResource.getEnableEmailNotification());
if (processModel.isEnableEmailNotification()){
String notificationEmails = processResource.getEmailAddresses();
processModel.setEmailAddresses(getEmailAddresses(notificationEmails.split(",")));
}
processModel.setProcessInputs(getProcessInputs(processResource.getProcessInputs()));
processModel.setProcessOutputs(getProcessOutputs(processResource.getProcessOutputs()));
processModel.setProcessError(getErrorModel(processResource.getProcessError()));
processModel.setProcessStatus(getProcessStatus(processResource.getProcessStatus()));
processModel.setResourceSchedule(getProcessResourceSchedule(processResource.getProcessResourceSchedule()));
processModel.setTasks(getTaskModelList(processResource.getTaskList()));
return processModel;
}
return null;
}
public static List<TaskModel> getTaskModelList (List<TaskResource> resources) throws RegistryException {
List<TaskModel> taskDetailsList = new ArrayList<TaskModel>();
if (resources != null && !resources.isEmpty()){
for (TaskResource resource : resources){
taskDetailsList.add(getTaskModel(resource));
}
}
return taskDetailsList;
}
public static TaskModel getTaskModel (TaskResource taskResource) throws RegistryException {
TaskModel model = new TaskModel();
model.setTaskId(taskResource.getTaskId());
model.setTaskType(TaskTypes.valueOf(taskResource.getTaskType()));
model.setParentProcessId(taskResource.getParentProcessId());
model.setCreationTime(taskResource.getCreationTime().getTime());
model.setLastUpdateTime(taskResource.getLastUpdateTime().getTime());
model.setTaskDetail(taskResource.getTaskDetail());
model.setSubTaskModel(taskResource.getSubTaskModel());
model.setTaskStatus(getTaskStatus(taskResource.getTaskStatus()));
model.setTaskError(getErrorModel(taskResource.getTaskError()));
return model;
}
public static JobModel getJobModel (JobResource jobResource) throws RegistryException {
JobModel model = new JobModel();
model.setJobId(jobResource.getJobId());
model.setTaskId(jobResource.getTaskId());
model.setJobDescription(jobResource.getJobDescription());
model.setCreationTime(jobResource.getCreationTime().getTime());
model.setComputeResourceConsumed(jobResource.getComputeResourceConsumed());
model.setJobName(jobResource.getJobName());
model.setWorkingDir(jobResource.getWorkingDir());
model.setJobStatus(getJobStatus(jobResource.getJobStatus()));
return model;
}
public static ErrorModel getErrorModel (Object object){
if (object != null) {
ErrorModel errorModel = new ErrorModel();
if (object instanceof ExperimentErrorResource) {
ExperimentErrorResource errorResource = (ExperimentErrorResource) object;
errorModel.setErrorId(errorResource.getErrorId());
errorModel.setCreationTime(errorResource.getCreationTime().getTime());
errorModel.setActualErrorMessage(errorResource.getActualErrorMessage());
errorModel.setUserFriendlyMessage(errorResource.getUserFriendlyMessage());
errorModel.setTransientOrPersistent(errorResource.getTransientOrPersistent());
errorModel.setRootCauseErrorIdList(Arrays.asList(errorResource.getRootCauseErrorIdList().split(",")));
return errorModel;
} else if (object instanceof ProcessOutputResource) {
ProcessErrorResource errorResource = (ProcessErrorResource) object;
errorModel.setErrorId(errorResource.getErrorId());
errorModel.setCreationTime(errorResource.getCreationTime().getTime());
errorModel.setActualErrorMessage(errorResource.getActualErrorMessage());
errorModel.setUserFriendlyMessage(errorResource.getUserFriendlyMessage());
errorModel.setTransientOrPersistent(errorResource.getTransientOrPersistent());
errorModel.setRootCauseErrorIdList(Arrays.asList(errorResource.getRootCauseErrorIdList().split(",")));
return errorModel;
} else if (object instanceof TaskErrorResource) {
TaskErrorResource errorResource = (TaskErrorResource) object;
errorModel.setErrorId(errorResource.getErrorId());
errorModel.setCreationTime(errorResource.getCreationTime().getTime());
errorModel.setActualErrorMessage(errorResource.getActualErrorMessage());
errorModel.setUserFriendlyMessage(errorResource.getUserFriendlyMessage());
errorModel.setTransientOrPersistent(errorResource.getTransientOrPersistent());
errorModel.setRootCauseErrorIdList(Arrays.asList(errorResource.getRootCauseErrorIdList().split(",")));
return errorModel;
} else {
return null;
}
}
return null;
}
public static List<ErrorModel> getExperimentErrorList(List<ExperimentErrorResource> errorResources){
List<ErrorModel> errorList = new ArrayList<ErrorModel>();
if (errorResources != null && !errorResources.isEmpty()){
for (ExperimentErrorResource errorResource : errorResources){
errorList.add(getErrorModel(errorResource));
}
}
return errorList;
}
public static UserConfigurationDataModel getUserConfigData (UserConfigurationDataResource resource) throws RegistryException {
if (resource != null){
UserConfigurationDataModel data = new UserConfigurationDataModel();
data.setAiravataAutoSchedule(resource.getAiravataAutoSchedule());
data.setOverrideManualScheduledParams(resource.getOverrideManualScheduledParams());
data.setShareExperimentPublicly(resource.getShareExperimentPublically());
data.setUserDN(resource.getUserDn());
data.setGenerateCert(resource.getGenerateCert());
ComputationalResourceSchedulingModel resourceSchedulingModel = new ComputationalResourceSchedulingModel();
resourceSchedulingModel.setResourceHostId(resource.getResourceHostId());
resourceSchedulingModel.setTotalCPUCount(resource.getTotalCpuCount());
resourceSchedulingModel.setNodeCount(resource.getNodeCount());
resourceSchedulingModel.setNumberOfThreads(resource.getNumberOfThreads());
resourceSchedulingModel.setQueueName(resource.getQueueName());
resourceSchedulingModel.setWallTimeLimit(resource.getWallTimeLimit());
resourceSchedulingModel.setTotalPhysicalMemory(resource.getTotalPhysicalMemory());
data.setComputationalResourceScheduling(resourceSchedulingModel);
return data;
}
return null;
}
public static ComputationalResourceSchedulingModel getProcessResourceSchedule (ProcessResourceScheduleResource resource){
if (resource != null){
ComputationalResourceSchedulingModel resourceSchedulingModel = new ComputationalResourceSchedulingModel();
resourceSchedulingModel.setResourceHostId(resource.getResourceHostId());
resourceSchedulingModel.setTotalCPUCount(resource.getTotalCpuCount());
resourceSchedulingModel.setNodeCount(resource.getNodeCount());
resourceSchedulingModel.setNumberOfThreads(resource.getNumberOfThreads());
resourceSchedulingModel.setQueueName(resource.getQueueName());
resourceSchedulingModel.setWallTimeLimit(resource.getWallTimeLimit());
resourceSchedulingModel.setTotalPhysicalMemory(resource.getTotalPhysicalMemory());
return resourceSchedulingModel;
}
return null;
}
public static ComputationalResourceSchedulingModel getComputationalResourceScheduling(UserConfigurationDataResource resource) {
if (resource != null){
ComputationalResourceSchedulingModel resourceSchedulingModel = new ComputationalResourceSchedulingModel();
resourceSchedulingModel.setResourceHostId(resource.getResourceHostId());
resourceSchedulingModel.setTotalCPUCount(resource.getTotalCpuCount());
resourceSchedulingModel.setNodeCount(resource.getNodeCount());
resourceSchedulingModel.setNumberOfThreads(resource.getNumberOfThreads());
resourceSchedulingModel.setQueueName(resource.getQueueName());
resourceSchedulingModel.setWallTimeLimit(resource.getWallTimeLimit());
resourceSchedulingModel.setTotalPhysicalMemory(resource.getTotalPhysicalMemory());
return resourceSchedulingModel;
}
return null;
}
}
| |
/*
* Copyright 2012-2022 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
*
* https://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.image.paketo;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.jar.Attributes;
import java.util.jar.JarFile;
import com.github.dockerjava.api.model.ContainerConfig;
import org.assertj.core.api.Condition;
import org.gradle.testkit.runner.BuildResult;
import org.gradle.testkit.runner.TaskOutcome;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.testcontainers.containers.GenericContainer;
import org.testcontainers.containers.wait.strategy.Wait;
import org.springframework.boot.buildpack.platform.docker.DockerApi;
import org.springframework.boot.buildpack.platform.docker.type.ImageName;
import org.springframework.boot.buildpack.platform.docker.type.ImageReference;
import org.springframework.boot.image.assertions.ImageAssertions;
import org.springframework.boot.image.junit.GradleBuildInjectionExtension;
import org.springframework.boot.testsupport.gradle.testkit.GradleBuild;
import org.springframework.boot.testsupport.gradle.testkit.GradleBuildExtension;
import org.springframework.util.StringUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.entry;
/**
* Integration tests for the Paketo builder and buildpacks.
*
* See
* https://paketo.io/docs/buildpacks/language-family-buildpacks/java/#additional-metadata
*
* @author Scott Frederick
*/
@ExtendWith({ GradleBuildInjectionExtension.class, GradleBuildExtension.class })
class PaketoBuilderTests {
GradleBuild gradleBuild;
@BeforeEach
void configureGradleBuild() {
this.gradleBuild.scriptProperty("systemTestMavenRepository",
new File("build/system-test-maven-repository").getAbsoluteFile().toURI().toASCIIString());
}
@Test
void executableJarApp() throws Exception {
writeMainClass();
String imageName = "paketo-integration/" + this.gradleBuild.getProjectDir().getName();
ImageReference imageReference = ImageReference.of(ImageName.of(imageName));
BuildResult result = buildImage(imageName);
assertThat(result.task(":bootBuildImage").getOutcome()).isEqualTo(TaskOutcome.SUCCESS);
try (GenericContainer<?> container = new GenericContainer<>(imageName).withExposedPorts(8080)) {
container.waitingFor(Wait.forHttp("/test")).start();
ContainerConfig config = container.getContainerInfo().getConfig();
assertLabelsMatchManifestAttributes(config);
ImageAssertions.assertThat(config).buildMetadata((metadata) -> {
metadata.buildpacks().contains("paketo-buildpacks/ca-certificates",
"paketo-buildpacks/bellsoft-liberica", "paketo-buildpacks/executable-jar",
"paketo-buildpacks/dist-zip", "paketo-buildpacks/spring-boot");
metadata.processOfType("web").extracting("command", "args").containsExactly("java",
Collections.singletonList("org.springframework.boot.loader.JarLauncher"));
metadata.processOfType("executable-jar").extracting("command", "args").containsExactly("java",
Collections.singletonList("org.springframework.boot.loader.JarLauncher"));
});
assertImageHasSbomLayer(imageReference, config, "executable-jar");
assertImageLayersMatchLayersIndex(imageReference, config);
}
finally {
removeImage(imageReference);
}
}
@Test
void executableJarAppWithAdditionalArgs() throws Exception {
writeMainClass();
String imageName = "paketo-integration/" + this.gradleBuild.getProjectDir().getName();
ImageReference imageReference = ImageReference.of(ImageName.of(imageName));
BuildResult result = buildImage(imageName);
assertThat(result.task(":bootBuildImage").getOutcome()).isEqualTo(TaskOutcome.SUCCESS);
try (GenericContainer<?> container = new GenericContainer<>(imageName).withCommand("--server.port=9090")
.withExposedPorts(9090)) {
container.waitingFor(Wait.forHttp("/test")).start();
}
finally {
removeImage(imageReference);
}
}
@Test
void executableJarAppBuiltTwiceWithCaching() throws Exception {
writeMainClass();
String imageName = "paketo-integration/" + this.gradleBuild.getProjectDir().getName();
ImageReference imageReference = ImageReference.of(ImageName.of(imageName));
BuildResult result = buildImage(imageName);
assertThat(result.task(":bootBuildImage").getOutcome()).isEqualTo(TaskOutcome.SUCCESS);
try (GenericContainer<?> container = new GenericContainer<>(imageName).withExposedPorts(8080)) {
container.waitingFor(Wait.forHttp("/test")).start();
container.stop();
}
this.gradleBuild.expectDeprecationMessages("BOM table is deprecated in this buildpack api version");
result = buildImage(imageName);
assertThat(result.task(":bootBuildImage").getOutcome()).isEqualTo(TaskOutcome.SUCCESS);
try (GenericContainer<?> container = new GenericContainer<>(imageName).withExposedPorts(8080)) {
container.waitingFor(Wait.forHttp("/test")).start();
}
finally {
removeImage(imageReference);
}
}
@Test
void bootDistZipJarApp() throws Exception {
writeMainClass();
String projectName = this.gradleBuild.getProjectDir().getName();
String imageName = "paketo-integration/" + projectName;
ImageReference imageReference = ImageReference.of(ImageName.of(imageName));
BuildResult result = buildImage(imageName, "assemble", "bootDistZip");
assertThat(result.task(":bootBuildImage").getOutcome()).isEqualTo(TaskOutcome.SUCCESS);
try (GenericContainer<?> container = new GenericContainer<>(imageName).withExposedPorts(8080)) {
container.waitingFor(Wait.forHttp("/test")).start();
ContainerConfig config = container.getContainerInfo().getConfig();
ImageAssertions.assertThat(config).buildMetadata((metadata) -> {
metadata.buildpacks().contains("paketo-buildpacks/ca-certificates",
"paketo-buildpacks/bellsoft-liberica", "paketo-buildpacks/dist-zip",
"paketo-buildpacks/spring-boot");
metadata.processOfType("web").extracting("command", "args").containsExactly(
"/workspace/" + projectName + "-boot/bin/" + projectName, Collections.emptyList());
metadata.processOfType("dist-zip").extracting("command", "args").containsExactly(
"/workspace/" + projectName + "-boot/bin/" + projectName, Collections.emptyList());
});
assertImageHasSbomLayer(imageReference, config, "dist-zip");
DigestCapturingCondition digest = new DigestCapturingCondition();
ImageAssertions.assertThat(config)
.lifecycleMetadata((metadata) -> metadata.appLayerShas().haveExactly(1, digest));
ImageAssertions.assertThat(imageReference).layer(digest.getDigest(),
(layer) -> layer.entries().contains(projectName + "-boot/bin/" + projectName,
projectName + "-boot/lib/" + projectName + ".jar"));
}
finally {
removeImage(imageReference);
}
}
@Test
void plainDistZipJarApp() throws Exception {
writeMainClass();
String projectName = this.gradleBuild.getProjectDir().getName();
String imageName = "paketo-integration/" + projectName;
ImageReference imageReference = ImageReference.of(ImageName.of(imageName));
BuildResult result = buildImage(imageName, "assemble", "bootDistZip");
assertThat(result.task(":bootBuildImage").getOutcome()).isEqualTo(TaskOutcome.SUCCESS);
try (GenericContainer<?> container = new GenericContainer<>(imageName).withExposedPorts(8080)) {
container.waitingFor(Wait.forHttp("/test")).start();
ContainerConfig config = container.getContainerInfo().getConfig();
ImageAssertions.assertThat(config).buildMetadata((metadata) -> {
metadata.buildpacks().contains("paketo-buildpacks/ca-certificates",
"paketo-buildpacks/bellsoft-liberica", "paketo-buildpacks/dist-zip",
"paketo-buildpacks/spring-boot");
metadata.processOfType("web").extracting("command", "args")
.containsExactly("/workspace/" + projectName + "/bin/" + projectName, Collections.emptyList());
metadata.processOfType("dist-zip").extracting("command", "args")
.containsExactly("/workspace/" + projectName + "/bin/" + projectName, Collections.emptyList());
});
assertImageHasSbomLayer(imageReference, config, "dist-zip");
DigestCapturingCondition digest = new DigestCapturingCondition();
ImageAssertions.assertThat(config)
.lifecycleMetadata((metadata) -> metadata.appLayerShas().haveExactly(1, digest));
ImageAssertions.assertThat(imageReference).layer(digest.getDigest(), (layer) -> layer.entries()
.contains(projectName + "/bin/" + projectName, projectName + "/lib/" + projectName + "-plain.jar")
.anyMatch((s) -> s.startsWith(projectName + "/lib/spring-boot-"))
.anyMatch((s) -> s.startsWith(projectName + "/lib/spring-core-"))
.anyMatch((s) -> s.startsWith(projectName + "/lib/spring-web-")));
}
finally {
removeImage(imageReference);
}
}
@Test
void executableWarApp() throws Exception {
writeMainClass();
writeServletInitializerClass();
String imageName = "paketo-integration/" + this.gradleBuild.getProjectDir().getName();
ImageReference imageReference = ImageReference.of(ImageName.of(imageName));
BuildResult result = buildImage(imageName);
assertThat(result.task(":bootBuildImage").getOutcome()).isEqualTo(TaskOutcome.SUCCESS);
try (GenericContainer<?> container = new GenericContainer<>(imageName).withExposedPorts(8080)) {
container.waitingFor(Wait.forHttp("/test")).start();
ContainerConfig config = container.getContainerInfo().getConfig();
assertLabelsMatchManifestAttributes(config);
ImageAssertions.assertThat(config).buildMetadata((metadata) -> {
metadata.buildpacks().contains("paketo-buildpacks/ca-certificates",
"paketo-buildpacks/bellsoft-liberica", "paketo-buildpacks/executable-jar",
"paketo-buildpacks/dist-zip", "paketo-buildpacks/spring-boot");
metadata.processOfType("web").extracting("command", "args").containsExactly("java",
Collections.singletonList("org.springframework.boot.loader.WarLauncher"));
metadata.processOfType("executable-jar").extracting("command", "args").containsExactly("java",
Collections.singletonList("org.springframework.boot.loader.WarLauncher"));
});
assertImageHasSbomLayer(imageReference, config, "executable-jar");
assertImageLayersMatchLayersIndex(imageReference, config);
}
finally {
removeImage(imageReference);
}
}
@Test
void plainWarApp() throws Exception {
writeMainClass();
writeServletInitializerClass();
String imageName = "paketo-integration/" + this.gradleBuild.getProjectDir().getName();
ImageReference imageReference = ImageReference.of(ImageName.of(imageName));
BuildResult result = buildImage(imageName);
assertThat(result.task(":bootBuildImage").getOutcome()).isEqualTo(TaskOutcome.SUCCESS);
try (GenericContainer<?> container = new GenericContainer<>(imageName).withExposedPorts(8080)) {
container.waitingFor(Wait.forHttp("/test")).start();
ContainerConfig config = container.getContainerInfo().getConfig();
ImageAssertions.assertThat(config).buildMetadata((metadata) -> {
metadata.buildpacks().contains("paketo-buildpacks/ca-certificates",
"paketo-buildpacks/bellsoft-liberica", "paketo-buildpacks/apache-tomcat",
"paketo-buildpacks/dist-zip", "paketo-buildpacks/spring-boot");
metadata.processOfType("web").extracting("command", "args").containsExactly("bash",
Arrays.asList("catalina.sh", "run"));
metadata.processOfType("tomcat").extracting("command", "args").containsExactly("bash",
Arrays.asList("catalina.sh", "run"));
});
assertImageHasSbomLayer(imageReference, config, "apache-tomcat");
DigestCapturingCondition digest = new DigestCapturingCondition();
ImageAssertions.assertThat(config)
.lifecycleMetadata((metadata) -> metadata.appLayerShas().haveExactly(1, digest));
ImageAssertions.assertThat(imageReference).layer(digest.getDigest(),
(layer) -> layer.entries()
.contains("WEB-INF/classes/example/ExampleApplication.class",
"WEB-INF/classes/example/HelloController.class", "META-INF/MANIFEST.MF")
.anyMatch((s) -> s.startsWith("WEB-INF/lib/spring-boot-"))
.anyMatch((s) -> s.startsWith("WEB-INF/lib/spring-core-"))
.anyMatch((s) -> s.startsWith("WEB-INF/lib/spring-web-")));
}
finally {
removeImage(imageReference);
}
}
private BuildResult buildImage(String imageName, String... arguments) {
String[] buildImageArgs = { "bootBuildImage", "--imageName=" + imageName, "--pullPolicy=IF_NOT_PRESENT" };
String[] args = StringUtils.concatenateStringArrays(arguments, buildImageArgs);
return this.gradleBuild.build(args);
}
private void writeMainClass() throws IOException {
writeProjectFile("ExampleApplication.java", (writer) -> {
writer.println("package example;");
writer.println();
writer.println("import org.springframework.boot.SpringApplication;");
writer.println("import org.springframework.boot.autoconfigure.SpringBootApplication;");
writer.println("import org.springframework.stereotype.Controller;");
writer.println("import org.springframework.web.bind.annotation.RequestMapping;");
writer.println("import org.springframework.web.bind.annotation.ResponseBody;");
writer.println();
writer.println("@SpringBootApplication");
writer.println("public class ExampleApplication {");
writer.println();
writer.println(" public static void main(String[] args) {");
writer.println(" SpringApplication.run(ExampleApplication.class, args);");
writer.println(" }");
writer.println();
writer.println("}");
writer.println();
writer.println("@Controller");
writer.println("class HelloController {");
writer.println();
writer.println(" @RequestMapping(\"/test\")");
writer.println(" @ResponseBody");
writer.println(" String home() {");
writer.println(" return \"Hello, world!\";");
writer.println(" }");
writer.println();
writer.println("}");
});
}
private void writeServletInitializerClass() throws IOException {
writeProjectFile("ServletInitializer.java", (writer) -> {
writer.println("package example;");
writer.println();
writer.println("import org.springframework.boot.builder.SpringApplicationBuilder;");
writer.println("import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;");
writer.println();
writer.println("public class ServletInitializer extends SpringBootServletInitializer {");
writer.println();
writer.println(" @Override");
writer.println(" protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {");
writer.println(" return application.sources(ExampleApplication.class);");
writer.println(" }");
writer.println();
writer.println("}");
});
}
private void writeProjectFile(String fileName, Consumer<PrintWriter> consumer) throws IOException {
File examplePackage = new File(this.gradleBuild.getProjectDir(), "src/main/java/example");
examplePackage.mkdirs();
File main = new File(examplePackage, fileName);
try (PrintWriter writer = new PrintWriter(new FileWriter(main))) {
consumer.accept(writer);
}
}
private void assertLabelsMatchManifestAttributes(ContainerConfig config) throws IOException {
JarFile jarFile = new JarFile(projectArchiveFile());
Attributes attributes = jarFile.getManifest().getMainAttributes();
ImageAssertions.assertThat(config).labels((labels) -> {
labels.contains(entry("org.springframework.boot.version", attributes.getValue("Spring-Boot-Version")));
labels.contains(
entry("org.opencontainers.image.title", attributes.getValue(Attributes.Name.IMPLEMENTATION_TITLE)));
labels.contains(entry("org.opencontainers.image.version",
attributes.getValue(Attributes.Name.IMPLEMENTATION_VERSION)));
});
}
private void assertImageHasSbomLayer(ImageReference imageReference, ContainerConfig config, String buildpack)
throws IOException {
DigestCapturingCondition digest = new DigestCapturingCondition();
ImageAssertions.assertThat(config).lifecycleMetadata((metadata) -> metadata.sbomLayerSha().has(digest));
ImageAssertions.assertThat(imageReference).layer(digest.getDigest(), (layer) -> {
layer.entries().contains("/layers/sbom/launch/paketo-buildpacks_bellsoft-liberica/jre/sbom.syft.json",
"/layers/sbom/launch/paketo-buildpacks_" + buildpack + "/sbom.syft.json",
"/layers/sbom/launch/paketo-buildpacks_" + buildpack + "/sbom.cdx.json");
layer.jsonEntry("/layers/sbom/launch/paketo-buildpacks_bellsoft-liberica/jre/sbom.syft.json", (json) -> {
json.extractingJsonPathStringValue("$.Artifacts[0].Name").isEqualTo("BellSoft Liberica JRE");
json.extractingJsonPathStringValue("$.Artifacts[0].Version").startsWith(javaMajorVersion());
});
layer.jsonEntry("/layers/sbom/launch/paketo-buildpacks_" + buildpack + "/sbom.syft.json",
(json) -> json.extractingJsonPathArrayValue("$.artifacts.[*].name").contains("spring-beans",
"spring-boot", "spring-boot-autoconfigure", "spring-context", "spring-core",
"spring-expression", "spring-jcl", "spring-web", "spring-webmvc"));
layer.jsonEntry("/layers/sbom/launch/paketo-buildpacks_" + buildpack + "/sbom.cdx.json",
(json) -> json.extractingJsonPathArrayValue("$.components.[*].name").contains("spring-beans",
"spring-boot", "spring-boot-autoconfigure", "spring-context", "spring-core",
"spring-expression", "spring-jcl", "spring-web", "spring-webmvc"));
});
}
private void assertImageLayersMatchLayersIndex(ImageReference imageReference, ContainerConfig config)
throws IOException {
DigestsCapturingCondition digests = new DigestsCapturingCondition();
ImageAssertions.assertThat(config)
.lifecycleMetadata((metadata) -> metadata.appLayerShas().haveExactly(5, digests));
LayersIndex layersIndex = LayersIndex.fromArchiveFile(projectArchiveFile());
ImageAssertions.assertThat(imageReference).layer(digests.getDigest(0), (layer) -> layer.entries()
.allMatch((entry) -> startsWithOneOf(entry, layersIndex.getLayer("dependencies"))));
ImageAssertions.assertThat(imageReference).layer(digests.getDigest(1), (layer) -> layer.entries()
.allMatch((entry) -> startsWithOneOf(entry, layersIndex.getLayer("spring-boot-loader"))));
ImageAssertions.assertThat(imageReference).layer(digests.getDigest(2), (layer) -> layer.entries()
.allMatch((entry) -> startsWithOneOf(entry, layersIndex.getLayer("snapshot-dependencies"))));
ImageAssertions.assertThat(imageReference).layer(digests.getDigest(3), (layer) -> layer.entries()
.allMatch((entry) -> startsWithOneOf(entry, layersIndex.getLayer("application"))));
ImageAssertions.assertThat(imageReference).layer(digests.getDigest(4),
(layer) -> layer.entries().allMatch((entry) -> entry.contains("lib/spring-cloud-bindings-")));
}
private File projectArchiveFile() {
return new File(this.gradleBuild.getProjectDir(), "build/libs").listFiles()[0];
}
private String javaMajorVersion() {
String javaVersion = System.getProperty("java.version");
if (javaVersion.startsWith("1.")) {
return javaVersion.substring(2, 3);
}
else {
int firstDotIndex = javaVersion.indexOf(".");
if (firstDotIndex != -1) {
return javaVersion.substring(0, firstDotIndex);
}
}
return javaVersion;
}
private boolean startsWithOneOf(String actual, List<String> expectedPrefixes) {
for (String prefix : expectedPrefixes) {
if (actual.startsWith(prefix)) {
return true;
}
}
return false;
}
private void removeImage(ImageReference image) throws IOException {
new DockerApi().image().remove(image, false);
}
private static class DigestCapturingCondition extends Condition<Object> {
private static String digest = null;
DigestCapturingCondition() {
super(predicate(), "a value starting with 'sha256:'");
}
private static Predicate<Object> predicate() {
return (sha) -> {
digest = sha.toString();
return sha.toString().startsWith("sha256:");
};
}
String getDigest() {
return digest;
}
}
private static class DigestsCapturingCondition extends Condition<Object> {
private static List<String> digests;
DigestsCapturingCondition() {
super(predicate(), "a value starting with 'sha256:'");
}
private static Predicate<Object> predicate() {
digests = new ArrayList<>();
return (sha) -> {
digests.add(sha.toString());
return sha.toString().startsWith("sha256:");
};
}
String getDigest(int index) {
return digests.get(index);
}
}
}
| |
/*
* Copyright 2000-2016 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.debugger.settings;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import jakarta.inject.Singleton;
import org.jdom.Element;
import org.jetbrains.annotations.NonNls;
import com.intellij.debugger.DebuggerBundle;
import com.intellij.debugger.DebuggerContext;
import com.intellij.debugger.engine.DebugProcess;
import com.intellij.debugger.engine.evaluation.CodeFragmentKind;
import com.intellij.debugger.engine.evaluation.EvaluateException;
import com.intellij.debugger.engine.evaluation.EvaluateExceptionUtil;
import com.intellij.debugger.engine.evaluation.EvaluationContext;
import com.intellij.debugger.engine.evaluation.EvaluationContextImpl;
import com.intellij.debugger.engine.evaluation.TextWithImportsImpl;
import com.intellij.debugger.engine.evaluation.expression.ExpressionEvaluator;
import com.intellij.debugger.impl.DebuggerUtilsEx;
import com.intellij.debugger.ui.impl.watch.ArrayElementDescriptorImpl;
import com.intellij.debugger.ui.impl.watch.ValueDescriptorImpl;
import com.intellij.debugger.ui.impl.watch.WatchItemDescriptor;
import com.intellij.debugger.ui.tree.DebuggerTreeNode;
import com.intellij.debugger.ui.tree.ValueDescriptor;
import com.intellij.debugger.ui.tree.render.*;
import com.intellij.ide.highlighter.JavaFileType;
import consulo.disposer.Disposable;
import com.intellij.openapi.components.PersistentStateComponent;
import com.intellij.openapi.components.ServiceManager;
import com.intellij.openapi.components.State;
import com.intellij.openapi.components.Storage;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Computable;
import com.intellij.openapi.util.InvalidDataException;
import com.intellij.openapi.util.JDOMExternalizerUtil;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.WriteExternalException;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.PsiElement;
import com.intellij.util.EventDispatcher;
import com.intellij.util.IncorrectOperationException;
import consulo.internal.com.sun.jdi.Value;
import consulo.java.module.util.JavaClassNames;
import consulo.ui.image.Image;
@Singleton
@State(name = "NodeRendererSettings", storages = @Storage("debugger.renderers.xml"))
public class NodeRendererSettings implements PersistentStateComponent<Element>
{
@NonNls
private static final String REFERENCE_RENDERER = "Reference renderer";
@NonNls
public static final String RENDERER_TAG = "Renderer";
@NonNls
private static final String RENDERER_ID = "ID";
private final EventDispatcher<NodeRendererSettingsListener> myDispatcher = EventDispatcher.create(NodeRendererSettingsListener.class);
private RendererConfiguration myCustomRenderers = new RendererConfiguration(this);
// base renderers
private final PrimitiveRenderer myPrimitiveRenderer = new PrimitiveRenderer();
private final ArrayRenderer myArrayRenderer = new ArrayRenderer();
private final ClassRenderer myClassRenderer = new ClassRenderer();
private final HexRenderer myHexRenderer = new HexRenderer();
private final ToStringRenderer myToStringRenderer = new ToStringRenderer();
// alternate collections
private final NodeRenderer[] myAlternateCollectionRenderers = new NodeRenderer[]{
createCompoundReferenceRenderer("Map", JavaClassNames.JAVA_UTIL_MAP, createLabelRenderer(" size = ", "size()", null), createExpressionChildrenRenderer("entrySet().toArray()",
"!isEmpty" + "()")),
createCompoundReferenceRenderer("Map.Entry", "java.util.Map$Entry", new MapEntryLabelRenderer()/*createLabelRenderer(null, "\" \" + getKey() + \" -> \" + getValue()", null)*/,
createEnumerationChildrenRenderer(new String[][]{
{
"key",
"getKey()"
},
{
"value",
"getValue()"
}
})),
new ListObjectRenderer(this),
createCompoundReferenceRenderer("Collection", "java.util.Collection", createLabelRenderer(" size = ", "size()", null), createExpressionChildrenRenderer("toArray()", "!isEmpty()"))
};
@NonNls
private static final String HEX_VIEW_ENABLED = "HEX_VIEW_ENABLED";
@NonNls
private static final String ALTERNATIVE_COLLECTION_VIEW_ENABLED = "ALTERNATIVE_COLLECTION_VIEW_ENABLED";
@NonNls
private static final String CUSTOM_RENDERERS_TAG_NAME = "CustomRenderers";
public NodeRendererSettings()
{
// default configuration
myHexRenderer.setEnabled(false);
myToStringRenderer.setEnabled(true);
setAlternateCollectionViewsEnabled(true);
}
public static NodeRendererSettings getInstance()
{
return ServiceManager.getService(NodeRendererSettings.class);
}
public void setAlternateCollectionViewsEnabled(boolean enabled)
{
for(NodeRenderer myAlternateCollectionRenderer : myAlternateCollectionRenderers)
{
myAlternateCollectionRenderer.setEnabled(enabled);
}
}
public boolean areAlternateCollectionViewsEnabled()
{
return myAlternateCollectionRenderers[0].isEnabled();
}
public boolean equals(Object o)
{
if(!(o instanceof NodeRendererSettings))
{
return false;
}
return DebuggerUtilsEx.elementsEqual(getState(), ((NodeRendererSettings) o).getState());
}
public void addListener(NodeRendererSettingsListener listener, Disposable disposable)
{
myDispatcher.addListener(listener, disposable);
}
@Override
@SuppressWarnings({"HardCodedStringLiteral"})
public Element getState()
{
final Element element = new Element("NodeRendererSettings");
if(myHexRenderer.isEnabled())
{
JDOMExternalizerUtil.writeField(element, HEX_VIEW_ENABLED, "true");
}
if(!areAlternateCollectionViewsEnabled())
{
JDOMExternalizerUtil.writeField(element, ALTERNATIVE_COLLECTION_VIEW_ENABLED, "false");
}
try
{
element.addContent(writeRenderer(myArrayRenderer));
element.addContent(writeRenderer(myToStringRenderer));
element.addContent(writeRenderer(myClassRenderer));
element.addContent(writeRenderer(myPrimitiveRenderer));
if(myCustomRenderers.getRendererCount() > 0)
{
final Element custom = new Element(CUSTOM_RENDERERS_TAG_NAME);
element.addContent(custom);
myCustomRenderers.writeExternal(custom);
}
}
catch(WriteExternalException e)
{
// ignore
}
return element;
}
@Override
@SuppressWarnings({"HardCodedStringLiteral"})
public void loadState(final Element root)
{
final String hexEnabled = JDOMExternalizerUtil.readField(root, HEX_VIEW_ENABLED);
if(hexEnabled != null)
{
myHexRenderer.setEnabled("true".equalsIgnoreCase(hexEnabled));
}
final String alternativeEnabled = JDOMExternalizerUtil.readField(root, ALTERNATIVE_COLLECTION_VIEW_ENABLED);
if(alternativeEnabled != null)
{
setAlternateCollectionViewsEnabled("true".equalsIgnoreCase(alternativeEnabled));
}
for(final Element elem : root.getChildren(RENDERER_TAG))
{
final String id = elem.getAttributeValue(RENDERER_ID);
if(id == null)
{
continue;
}
try
{
if(ArrayRenderer.UNIQUE_ID.equals(id))
{
myArrayRenderer.readExternal(elem);
}
else if(ToStringRenderer.UNIQUE_ID.equals(id))
{
myToStringRenderer.readExternal(elem);
}
else if(ClassRenderer.UNIQUE_ID.equals(id))
{
myClassRenderer.readExternal(elem);
}
else if(PrimitiveRenderer.UNIQUE_ID.equals(id))
{
myPrimitiveRenderer.readExternal(elem);
}
}
catch(InvalidDataException e)
{
// ignore
}
}
final Element custom = root.getChild(CUSTOM_RENDERERS_TAG_NAME);
if(custom != null)
{
myCustomRenderers.readExternal(custom);
}
myDispatcher.getMulticaster().renderersChanged();
}
public RendererConfiguration getCustomRenderers()
{
return myCustomRenderers;
}
public void setCustomRenderers(@Nonnull final RendererConfiguration customRenderers)
{
RendererConfiguration oldConfig = myCustomRenderers;
myCustomRenderers = customRenderers;
if(oldConfig == null || !oldConfig.equals(customRenderers))
{
fireRenderersChanged();
}
}
public PrimitiveRenderer getPrimitiveRenderer()
{
return myPrimitiveRenderer;
}
public ArrayRenderer getArrayRenderer()
{
return myArrayRenderer;
}
public ClassRenderer getClassRenderer()
{
return myClassRenderer;
}
public HexRenderer getHexRenderer()
{
return myHexRenderer;
}
public ToStringRenderer getToStringRenderer()
{
return myToStringRenderer;
}
public NodeRenderer[] getAlternateCollectionRenderers()
{
return myAlternateCollectionRenderers;
}
public void fireRenderersChanged()
{
myDispatcher.getMulticaster().renderersChanged();
}
public List<NodeRenderer> getAllRenderers()
{
// the order is important as the renderers are applied according to it
final List<NodeRenderer> allRenderers = new ArrayList<>();
// user defined renderers must come first
myCustomRenderers.iterateRenderers(renderer ->
{
allRenderers.add(renderer);
return true;
});
// plugins registered renderers come after that
Collections.addAll(allRenderers, NodeRenderer.EP_NAME.getExtensions());
// now all predefined stuff
allRenderers.add(myHexRenderer);
allRenderers.add(myPrimitiveRenderer);
Collections.addAll(allRenderers, myAlternateCollectionRenderers);
allRenderers.add(myToStringRenderer);
allRenderers.add(myArrayRenderer);
allRenderers.add(myClassRenderer);
return allRenderers;
}
public Renderer readRenderer(Element root) throws InvalidDataException
{
if(root == null)
{
return null;
}
if(!RENDERER_TAG.equals(root.getName()))
{
throw new InvalidDataException("Cannot read renderer - tag name is not '" + RENDERER_TAG + "'");
}
final String rendererId = root.getAttributeValue(RENDERER_ID);
if(rendererId == null)
{
throw new InvalidDataException("unknown renderer ID: " + rendererId);
}
final Renderer renderer = createRenderer(rendererId);
if(renderer == null)
{
throw new InvalidDataException("unknown renderer ID: " + rendererId);
}
renderer.readExternal(root);
return renderer;
}
public Element writeRenderer(Renderer renderer) throws WriteExternalException
{
Element root = new Element(RENDERER_TAG);
if(renderer != null)
{
root.setAttribute(RENDERER_ID, renderer.getUniqueId());
renderer.writeExternal(root);
}
return root;
}
public Renderer createRenderer(final String rendererId)
{
if(ClassRenderer.UNIQUE_ID.equals(rendererId))
{
return myClassRenderer;
}
else if(ArrayRenderer.UNIQUE_ID.equals(rendererId))
{
return myArrayRenderer;
}
else if(PrimitiveRenderer.UNIQUE_ID.equals(rendererId))
{
return myPrimitiveRenderer;
}
else if(HexRenderer.UNIQUE_ID.equals(rendererId))
{
return myHexRenderer;
}
else if(rendererId.equals(ExpressionChildrenRenderer.UNIQUE_ID))
{
return new ExpressionChildrenRenderer();
}
else if(rendererId.equals(LabelRenderer.UNIQUE_ID))
{
return new LabelRenderer();
}
else if(rendererId.equals(EnumerationChildrenRenderer.UNIQUE_ID))
{
return new EnumerationChildrenRenderer();
}
else if(rendererId.equals(ToStringRenderer.UNIQUE_ID))
{
return myToStringRenderer;
}
else if(rendererId.equals(CompoundNodeRenderer.UNIQUE_ID) || rendererId.equals(REFERENCE_RENDERER))
{
return createCompoundReferenceRenderer("unnamed", JavaClassNames.JAVA_LANG_OBJECT, null, null);
}
else if(rendererId.equals(CompoundTypeRenderer.UNIQUE_ID))
{
return createCompoundTypeRenderer("unnamed", JavaClassNames.JAVA_LANG_OBJECT, null, null);
}
return null;
}
public CompoundTypeRenderer createCompoundTypeRenderer(@NonNls final String rendererName,
@NonNls final String className,
final ValueLabelRenderer labelRenderer,
final ChildrenRenderer childrenRenderer)
{
CompoundTypeRenderer renderer = new CompoundTypeRenderer(this, rendererName, labelRenderer, childrenRenderer);
renderer.setClassName(className);
return renderer;
}
public CompoundReferenceRenderer createCompoundReferenceRenderer(@NonNls final String rendererName,
@NonNls final String className,
final ValueLabelRenderer labelRenderer,
final ChildrenRenderer childrenRenderer)
{
CompoundReferenceRenderer renderer = new CompoundReferenceRenderer(this, rendererName, labelRenderer, childrenRenderer);
renderer.setClassName(className);
return renderer;
}
public static ExpressionChildrenRenderer createExpressionChildrenRenderer(@NonNls String expressionText, @NonNls String childrenExpandableText)
{
final ExpressionChildrenRenderer childrenRenderer = new ExpressionChildrenRenderer();
childrenRenderer.setChildrenExpression(new TextWithImportsImpl(CodeFragmentKind.EXPRESSION, expressionText, "", JavaFileType.INSTANCE));
if(childrenExpandableText != null)
{
childrenRenderer.setChildrenExpandable(new TextWithImportsImpl(CodeFragmentKind.EXPRESSION, childrenExpandableText, "", JavaFileType.INSTANCE));
}
return childrenRenderer;
}
public static EnumerationChildrenRenderer createEnumerationChildrenRenderer(@NonNls String[][] expressions)
{
EnumerationChildrenRenderer childrenRenderer = new EnumerationChildrenRenderer();
if(expressions != null && expressions.length > 0)
{
ArrayList<EnumerationChildrenRenderer.ChildInfo> childrenList = new ArrayList<>(expressions.length);
for(String[] expression : expressions)
{
childrenList.add(new EnumerationChildrenRenderer.ChildInfo(expression[0], new TextWithImportsImpl(CodeFragmentKind.EXPRESSION, expression[1], "", JavaFileType.INSTANCE), false));
}
childrenRenderer.setChildren(childrenList);
}
return childrenRenderer;
}
private static LabelRenderer createLabelRenderer(@NonNls final String prefix, @NonNls final String expressionText, @NonNls final String postfix)
{
final LabelRenderer labelRenderer = new LabelRenderer()
{
@Override
public String calcLabel(ValueDescriptor descriptor, EvaluationContext evaluationContext, DescriptorLabelListener labelListener) throws EvaluateException
{
final String evaluated = super.calcLabel(descriptor, evaluationContext, labelListener);
if(prefix == null && postfix == null)
{
return evaluated;
}
if(prefix != null && postfix != null)
{
return prefix + evaluated + postfix;
}
if(prefix != null)
{
return prefix + evaluated;
}
return evaluated + postfix;
}
};
labelRenderer.setLabelExpression(new TextWithImportsImpl(CodeFragmentKind.EXPRESSION, expressionText, "", JavaFileType.INSTANCE));
return labelRenderer;
}
private static class MapEntryLabelRenderer extends ReferenceRenderer implements ValueLabelRenderer
{
private static final Computable<String> NULL_LABEL_COMPUTABLE = () -> "null";
private final MyCachedEvaluator myKeyExpression = new MyCachedEvaluator();
private final MyCachedEvaluator myValueExpression = new MyCachedEvaluator();
private MapEntryLabelRenderer()
{
super("java.util.Map$Entry");
myKeyExpression.setReferenceExpression(new TextWithImportsImpl(CodeFragmentKind.EXPRESSION, "this.getKey()", "", JavaFileType.INSTANCE));
myValueExpression.setReferenceExpression(new TextWithImportsImpl(CodeFragmentKind.EXPRESSION, "this.getValue()", "", JavaFileType.INSTANCE));
}
@Override
public Image calcValueIcon(ValueDescriptor descriptor, EvaluationContext evaluationContext, DescriptorLabelListener listener) throws EvaluateException
{
return null;
}
@Override
public String calcLabel(ValueDescriptor descriptor, EvaluationContext evaluationContext, DescriptorLabelListener listener) throws EvaluateException
{
final DescriptorUpdater descriptorUpdater = new DescriptorUpdater(descriptor, listener);
final Value originalValue = descriptor.getValue();
final Pair<Computable<String>, ValueDescriptorImpl> keyPair = createValueComputable(evaluationContext, originalValue, myKeyExpression, descriptorUpdater);
final Pair<Computable<String>, ValueDescriptorImpl> valuePair = createValueComputable(evaluationContext, originalValue, myValueExpression, descriptorUpdater);
descriptorUpdater.setKeyDescriptor(keyPair.second);
descriptorUpdater.setValueDescriptor(valuePair.second);
return DescriptorUpdater.constructLabelText(keyPair.first.compute(), valuePair.first.compute());
}
private Pair<Computable<String>, ValueDescriptorImpl> createValueComputable(final EvaluationContext evaluationContext,
Value originalValue,
final MyCachedEvaluator evaluator,
final DescriptorLabelListener listener) throws EvaluateException
{
final Value eval = doEval(evaluationContext, originalValue, evaluator);
if(eval != null)
{
final WatchItemDescriptor evalDescriptor = new WatchItemDescriptor(evaluationContext.getProject(), evaluator.getReferenceExpression(), eval);
evalDescriptor.setShowIdLabel(false);
return new Pair<>(() ->
{
evalDescriptor.updateRepresentation((EvaluationContextImpl) evaluationContext, listener);
return evalDescriptor.getValueLabel();
}, evalDescriptor);
}
return new Pair<>(NULL_LABEL_COMPUTABLE, null);
}
@Override
public String getUniqueId()
{
return "MapEntry renderer";
}
private Value doEval(EvaluationContext evaluationContext, Value originalValue, MyCachedEvaluator cachedEvaluator) throws EvaluateException
{
final DebugProcess debugProcess = evaluationContext.getDebugProcess();
if(originalValue == null)
{
return null;
}
try
{
final ExpressionEvaluator evaluator = cachedEvaluator.getEvaluator(debugProcess.getProject());
if(!debugProcess.isAttached())
{
throw EvaluateExceptionUtil.PROCESS_EXITED;
}
final EvaluationContext thisEvaluationContext = evaluationContext.createEvaluationContext(originalValue);
return evaluator.evaluate(thisEvaluationContext);
}
catch(final EvaluateException ex)
{
throw new EvaluateException(DebuggerBundle.message("error.unable.to.evaluate.expression") + " " + ex.getMessage(), ex);
}
}
private class MyCachedEvaluator extends CachedEvaluator
{
@Override
protected String getClassName()
{
return MapEntryLabelRenderer.this.getClassName();
}
@Override
public ExpressionEvaluator getEvaluator(Project project) throws EvaluateException
{
return super.getEvaluator(project);
}
}
}
private static class ListObjectRenderer extends CompoundReferenceRenderer
{
public ListObjectRenderer(NodeRendererSettings rendererSettings)
{
super(rendererSettings, "List", createLabelRenderer(" size = ", "size()", null), createExpressionChildrenRenderer("toArray()", "!isEmpty()"));
setClassName(JavaClassNames.JAVA_UTIL_LIST);
}
@Override
public PsiElement getChildValueExpression(DebuggerTreeNode node, DebuggerContext context) throws EvaluateException
{
LOG.assertTrue(node.getDescriptor() instanceof ArrayElementDescriptorImpl);
try
{
return getChildValueExpression("this.get(" + ((ArrayElementDescriptorImpl) node.getDescriptor()).getIndex() + ")", node, context);
}
catch(IncorrectOperationException e)
{
// fallback to original
return super.getChildValueExpression(node, context);
}
}
}
private static class DescriptorUpdater implements DescriptorLabelListener
{
private final ValueDescriptor myTargetDescriptor;
@javax.annotation.Nullable
private ValueDescriptorImpl myKeyDescriptor;
@Nullable
private ValueDescriptorImpl myValueDescriptor;
private final DescriptorLabelListener myDelegate;
private DescriptorUpdater(ValueDescriptor descriptor, DescriptorLabelListener delegate)
{
myTargetDescriptor = descriptor;
myDelegate = delegate;
}
public void setKeyDescriptor(@Nullable ValueDescriptorImpl keyDescriptor)
{
myKeyDescriptor = keyDescriptor;
}
public void setValueDescriptor(@Nullable ValueDescriptorImpl valueDescriptor)
{
myValueDescriptor = valueDescriptor;
}
@Override
public void labelChanged()
{
myTargetDescriptor.setValueLabel(constructLabelText(getDescriptorLabel(myKeyDescriptor), getDescriptorLabel(myValueDescriptor)));
myDelegate.labelChanged();
}
static String constructLabelText(final String keylabel, final String valueLabel)
{
StringBuilder sb = new StringBuilder();
sb.append('\"').append(keylabel).append("\" -> ");
if(!StringUtil.isEmpty(valueLabel))
{
sb.append('\"').append(valueLabel).append('\"');
}
return sb.toString();
}
private static String getDescriptorLabel(final ValueDescriptorImpl keyDescriptor)
{
return keyDescriptor == null ? "null" : keyDescriptor.getValueLabel();
}
}
}
| |
/*
* Copyright 2017 Adaptris 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 com.adaptris.naming.adapter;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.Closeable;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
import javax.naming.CompositeName;
import javax.naming.Context;
import javax.naming.InvalidNameException;
import javax.naming.Name;
import javax.naming.NameAlreadyBoundException;
import javax.naming.NameNotFoundException;
import javax.naming.NameParser;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.NotContextException;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.adaptris.core.management.SystemPropertiesUtil;
public class NamingContextTest {
@Before
public void setUp() throws Exception {
}
@After
public void tearDown() throws Exception {
}
private CloseableNamingContext closeableContext() {
Hashtable<String, Object> env = new Hashtable();
env.put(Context.URL_PKG_PREFIXES, SystemPropertiesUtil.NAMING_PACKAGE);
Map<String, Object> bindings = new HashMap<>();
bindings.put(this.getClass().getSimpleName(), new Object());
return new CloseableNamingContext(env, bindings);
}
private Name createName(String s) throws InvalidNameException {
return new CompositeName(s);
}
@Test
public void testBind() throws Exception {
try (CloseableNamingContext context = closeableContext()) {
context.bind("hello", new Object());
assertNotNull(context.lookup("hello"));
context.bind("comp/env/hello", new Object());
context.bind("testBind", new Object());
context.createSubcontext("testBindContext");
assertNotNull(context.lookup("comp/env/hello"));
try {
context.bind(new CompositeName(), new Object());
fail();
}
catch (NamingException expected) {
}
try {
context.bind("comp/env/hello", new Object());
fail();
}
catch (NameAlreadyBoundException expected) {
}
try {
context.bind("testBind/object", new Object());
fail();
}
catch (NamingException expected) {
}
context.bind(createName("testBindContext/object"), new Object(), false);
context.unbind("testBindContext/object");
context.bind(createName("testBindContext/object"), new Object(), true);
}
}
@Test
public void testBindNameObjectBoolean() throws Exception {
try (CloseableNamingContext context = closeableContext()) {
Object bindObj = new Object();
context.bind(createName("hello"), bindObj, true);
assertNotNull(context.lookup("hello"));
assertEquals(bindObj, context.lookup("hello"));
context.bind(createName("hello"), new Object(), true);
assertNotNull(context.lookup("hello"));
assertNotSame(bindObj, context.lookup("hello"));
}
}
@Test
public void testComposeNameNameName() throws Exception {
try (CloseableNamingContext context = closeableContext()) {
Name c = context.composeName(createName("world"), createName("hello"));
assertEquals("hello/world", c.toString());
}
}
@Test
public void testComposeNameStringString() throws Exception {
try (CloseableNamingContext context = closeableContext()) {
assertEquals("hello/world", context.composeName("world", "hello"));
}
}
@Test
public void testCreateSubcontext() throws Exception {
try (CloseableNamingContext context = closeableContext()) {
Context sub = context.createSubcontext("hello");
assertNotNull(context.lookup("hello"));
}
}
@Test
public void testDestroySubcontext() throws Exception {
try (CloseableNamingContext context = closeableContext()) {
context.bind("goodbye", new Object());
context.bind("a/b/c", new Object());
context.createSubcontext(createName("hello"));
assertNotNull(context.lookup("hello"));
context.destroySubcontext(createName("hello"));
try {
context.destroySubcontext("hello");
fail();
}
catch (NameNotFoundException exoected) {
}
try {
context.destroySubcontext("a/b/c");
fail();
}
catch (NamingException exoected) {
}
context.destroySubcontext("a/b");
try {
context.destroySubcontext("goodbye");
fail();
}
catch (NotContextException expected) {
}
try {
context.destroySubcontext(new CompositeName());
fail();
}
catch (NamingException expected) {
}
}
}
@Test
public void testGetNameInNamespace() throws Exception {
try (CloseableNamingContext context = new CloseableNamingContext(null, "name")) {
assertEquals("name", context.getNameInNamespace());
}
}
@Test
public void testGetNameParserName() throws Exception {
try (CloseableNamingContext context = closeableContext()) {
NameParser p = context.getNameParser(createName("blah"));
assertEquals(createName("hello"), p.parse("hello"));
}
}
@Test
public void testGetNameParserString() throws Exception {
try (CloseableNamingContext context = closeableContext()) {
NameParser p = context.getNameParser("hello");
assertEquals(createName("hello"), p.parse("hello"));
}
}
@Test
public void testList() throws Exception {
try (CloseableNamingContext context = closeableContext()) {
context.bind(createName("hello"), context, true);
context.createSubcontext(createName("world"));
try (CloseableEnumeration e = new CloseableEnumeration(context.list("hello"))) {
while (e.hasMore()) {
e.next();
}
}
try (CloseableEnumeration e = new CloseableEnumeration(context.list("hello"))) {
while (e.hasMoreElements()) {
e.nextElement();
}
}
context.list("world");
context.bind(createName("NotContext"), new Object());
try {
context.list("NotContext");
fail();
}
catch (NotContextException exc) {
}
}
}
@Test
public void testListBindings() throws Exception {
try (CloseableNamingContext context = closeableContext()) {
context.bind(createName("hello"), context, true);
context.createSubcontext(createName("world"));
try (CloseableEnumeration e = new CloseableEnumeration(context.listBindings("hello"))) {
while (e.hasMore()) {
e.next();
}
}
try (CloseableEnumeration e = new CloseableEnumeration(context.listBindings("hello"))) {
while (e.hasMoreElements()) {
e.nextElement();
}
}
context.listBindings("world");
context.bind(createName("NotContext"), new Object());
try {
context.listBindings("NotContext");
fail();
}
catch (NotContextException exc) {
}
}
}
@Test
public void testLookup() throws Exception {
try (CloseableNamingContext context = closeableContext()) {
context.bind("hello", new Object());
assertNotNull(context.lookup(""));
assertNotNull(context.lookupLink("hello"));
try {
assertNotNull(context.lookup("adapter:/comp/env/object"));
}
catch (NameNotFoundException expected) {
}
try {
context.lookup("zzzz:/comp/env/object");
}
catch (NamingException expected) {
}
}
}
@Test
public void testUnbind() throws Exception {
try (CloseableNamingContext context = closeableContext()) {
context.bind("hello", new Object());
context.unbind("hello");
try {
context.lookup("hello");
fail();
}
catch (NamingException expected) {
}
try {
context.unbind("hello");
fail();
}
catch (NameNotFoundException expected) {
}
try {
context.unbind(new CompositeName());
fail();
}
catch (NamingException expected) {
}
}
}
@Test
public void testRebindStringObject() throws Exception {
try (CloseableNamingContext context = closeableContext()) {
context.rebind("hello", new Object());
assertNotNull(context.lookup("hello"));
}
}
@Test
public void testEnvironment() throws Exception {
try (CloseableNamingContext context = closeableContext()) {
context.addToEnvironment("hello", "world");
Hashtable env = context.getEnvironment();
assertTrue(env.containsKey("hello"));
context.removeFromEnvironment("hello");
assertFalse(context.getEnvironment().containsKey("hello"));
}
}
@Test
public void testRenameStringString() throws Exception {
try (CloseableNamingContext context = closeableContext()) {
context.bind("hello", new Object());
context.rename("hello", "world");
try {
context.lookup("hello");
fail();
}
catch (NamingException expected) {
}
context.lookup("world");
}
}
@SuppressWarnings("serial")
private class CloseableNamingContext extends NamingContext implements Closeable {
public CloseableNamingContext(Hashtable<String, Object> environment, Map<String, Object> objects) {
super(environment, objects);
}
public CloseableNamingContext(Hashtable<String, Object> environment, String nameInNamespace) {
super(environment, nameInNamespace);
}
@Override
public void close() {
try {
super.close();
}
catch (Exception e) {
}
}
}
private class CloseableEnumeration implements NamingEnumeration, Closeable {
private NamingEnumeration proxy;
private CloseableEnumeration(NamingEnumeration ne) {
proxy = ne;
}
@Override
public boolean hasMoreElements() {
return proxy.hasMoreElements();
}
@Override
public Object nextElement() {
return proxy.nextElement();
}
@Override
public Object next() throws NamingException {
return proxy.next();
}
@Override
public boolean hasMore() throws NamingException {
return proxy.hasMore();
}
@Override
public void close() {
try {
proxy.close();
}
catch (Exception e) {
}
}
}
}
| |
/**
* 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.hadoop.yarn.server.resourcemanager.webapp;
import static org.apache.hadoop.yarn.server.resourcemanager.MockNodes.newResource;
import static org.apache.hadoop.yarn.webapp.Params.TITLE;
import static org.junit.Assert.assertEquals;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentMap;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.yarn.api.protocolrecords.GetApplicationsRequest;
import org.apache.hadoop.yarn.api.protocolrecords.GetApplicationsResponse;
import org.apache.hadoop.yarn.api.records.ApplicationAttemptId;
import org.apache.hadoop.yarn.api.records.ApplicationId;
import org.apache.hadoop.yarn.api.records.ApplicationReport;
import org.apache.hadoop.yarn.api.records.ApplicationResourceUsageReport;
import org.apache.hadoop.yarn.api.records.NodeId;
import org.apache.hadoop.yarn.api.records.NodeState;
import org.apache.hadoop.yarn.api.records.Token;
import org.apache.hadoop.yarn.api.records.YarnApplicationState;
import org.apache.hadoop.yarn.conf.YarnConfiguration;
import org.apache.hadoop.yarn.exceptions.YarnException;
import org.apache.hadoop.yarn.server.resourcemanager.ClientRMService;
import org.apache.hadoop.yarn.server.resourcemanager.MockNodes;
import org.apache.hadoop.yarn.server.resourcemanager.RMContext;
import org.apache.hadoop.yarn.server.resourcemanager.RMContextImpl;
import org.apache.hadoop.yarn.server.resourcemanager.ResourceManager;
import org.apache.hadoop.yarn.server.resourcemanager.applicationsmanager.MockAsm;
import org.apache.hadoop.yarn.server.resourcemanager.nodelabels.NullRMNodeLabelsManager;
import org.apache.hadoop.yarn.server.resourcemanager.nodelabels.RMNodeLabelsManager;
import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMApp;
import org.apache.hadoop.yarn.server.resourcemanager.rmnode.RMNode;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.ResourceScheduler;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.capacity.CapacityScheduler;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.capacity.CapacitySchedulerConfiguration;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.fifo.FifoScheduler;
import org.apache.hadoop.yarn.server.resourcemanager.security.ClientToAMTokenSecretManagerInRM;
import org.apache.hadoop.yarn.server.resourcemanager.security.NMTokenSecretManagerInRM;
import org.apache.hadoop.yarn.server.resourcemanager.security.RMContainerTokenSecretManager;
import org.apache.hadoop.yarn.server.security.ApplicationACLsManager;
import org.apache.hadoop.yarn.util.StringHelper;
import org.apache.hadoop.yarn.webapp.WebApps;
import org.apache.hadoop.yarn.webapp.YarnWebParams;
import org.apache.hadoop.yarn.webapp.test.WebAppTests;
import org.junit.Assert;
import org.junit.Test;
import com.google.common.collect.Maps;
import com.google.inject.Binder;
import com.google.inject.Injector;
import com.google.inject.Module;
public class TestRMWebApp {
static final int GiB = 1024; // MiB
@Test
public void testControllerIndex() {
Injector injector = WebAppTests.createMockInjector(TestRMWebApp.class,
this, new Module() {
@Override
public void configure(Binder binder) {
binder.bind(ApplicationACLsManager.class).toInstance(
new ApplicationACLsManager(new Configuration()));
}
});
RmController c = injector.getInstance(RmController.class);
c.index();
assertEquals("Applications", c.get(TITLE, "unknown"));
}
@Test public void testView() {
Injector injector = WebAppTests.createMockInjector(RMContext.class,
mockRMContext(15, 1, 2, 8*GiB),
new Module() {
@Override
public void configure(Binder binder) {
try {
ResourceManager mockRm = mockRm(3, 1, 2, 8*GiB);
binder.bind(ResourceManager.class).toInstance(mockRm);
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
});
RmView rmViewInstance = injector.getInstance(RmView.class);
rmViewInstance.set(YarnWebParams.APP_STATE,
YarnApplicationState.RUNNING.toString());
rmViewInstance.render();
WebAppTests.flushOutput(injector);
rmViewInstance.set(YarnWebParams.APP_STATE, StringHelper.cjoin(
YarnApplicationState.ACCEPTED.toString(),
YarnApplicationState.RUNNING.toString()));
rmViewInstance.render();
WebAppTests.flushOutput(injector);
Map<String, String> moreParams =
rmViewInstance.context().requestContext().moreParams();
String appsTableColumnsMeta = moreParams.get("ui.dataTables.apps.init");
Assert.assertTrue(appsTableColumnsMeta.indexOf("natural") != -1);
}
@Test public void testNodesPage() {
// 10 nodes. Two of each type.
final RMContext rmContext = mockRMContext(3, 2, 12, 8*GiB);
Injector injector = WebAppTests.createMockInjector(RMContext.class,
rmContext,
new Module() {
@Override
public void configure(Binder binder) {
try {
binder.bind(ResourceManager.class).toInstance(mockRm(rmContext));
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
});
// All nodes
NodesPage instance = injector.getInstance(NodesPage.class);
instance.render();
WebAppTests.flushOutput(injector);
// Unhealthy nodes
instance.moreParams().put(YarnWebParams.NODE_STATE,
NodeState.UNHEALTHY.toString());
instance.render();
WebAppTests.flushOutput(injector);
// Lost nodes
instance.moreParams().put(YarnWebParams.NODE_STATE,
NodeState.LOST.toString());
instance.render();
WebAppTests.flushOutput(injector);
}
public static RMContext mockRMContext(int numApps, int racks, int numNodes,
int mbsPerNode) {
final List<RMApp> apps = MockAsm.newApplications(numApps);
final ConcurrentMap<ApplicationId, RMApp> applicationsMaps = Maps
.newConcurrentMap();
for (RMApp app : apps) {
applicationsMaps.put(app.getApplicationId(), app);
}
final List<RMNode> nodes = MockNodes.newNodes(racks, numNodes,
newResource(mbsPerNode));
final ConcurrentMap<NodeId, RMNode> nodesMap = Maps.newConcurrentMap();
for (RMNode node : nodes) {
nodesMap.put(node.getNodeID(), node);
}
final List<RMNode> deactivatedNodes =
MockNodes.deactivatedNodes(racks, numNodes, newResource(mbsPerNode));
final ConcurrentMap<NodeId, RMNode> deactivatedNodesMap =
Maps.newConcurrentMap();
for (RMNode node : deactivatedNodes) {
deactivatedNodesMap.put(node.getNodeID(), node);
}
RMContextImpl rmContext = new RMContextImpl(null, null, null, null,
null, null, null, null, null, null) {
@Override
public ConcurrentMap<ApplicationId, RMApp> getRMApps() {
return applicationsMaps;
}
@Override
public ConcurrentMap<NodeId, RMNode> getInactiveRMNodes() {
return deactivatedNodesMap;
}
@Override
public ConcurrentMap<NodeId, RMNode> getRMNodes() {
return nodesMap;
}
};
rmContext.setNodeLabelManager(new NullRMNodeLabelsManager());
rmContext.setYarnConfiguration(new YarnConfiguration());
return rmContext;
}
public static ResourceManager mockRm(int apps, int racks, int nodes,
int mbsPerNode) throws IOException {
RMContext rmContext = mockRMContext(apps, racks, nodes,
mbsPerNode);
return mockRm(rmContext);
}
public static ResourceManager mockRm(RMContext rmContext) throws IOException {
ResourceManager rm = mock(ResourceManager.class);
ResourceScheduler rs = mockCapacityScheduler();
ApplicationACLsManager aclMgr = mockAppACLsManager();
ClientRMService clientRMService = mockClientRMService(rmContext);
when(rm.getResourceScheduler()).thenReturn(rs);
when(rm.getRMContext()).thenReturn(rmContext);
when(rm.getApplicationACLsManager()).thenReturn(aclMgr);
when(rm.getClientRMService()).thenReturn(clientRMService);
return rm;
}
public static CapacityScheduler mockCapacityScheduler() throws IOException {
// stolen from TestCapacityScheduler
CapacitySchedulerConfiguration conf = new CapacitySchedulerConfiguration();
setupQueueConfiguration(conf);
CapacityScheduler cs = new CapacityScheduler();
YarnConfiguration yarnConf = new YarnConfiguration();
cs.setConf(yarnConf);
RMContext rmContext = new RMContextImpl(null, null, null, null, null,
null, new RMContainerTokenSecretManager(conf),
new NMTokenSecretManagerInRM(conf),
new ClientToAMTokenSecretManagerInRM(), null);
RMNodeLabelsManager labelManager = new NullRMNodeLabelsManager();
labelManager.init(yarnConf);
rmContext.setNodeLabelManager(labelManager);
cs.setRMContext(rmContext);
cs.init(conf);
return cs;
}
public static ApplicationACLsManager mockAppACLsManager() {
Configuration conf = new Configuration();
return new ApplicationACLsManager(conf);
}
public static ClientRMService mockClientRMService(RMContext rmContext) {
ClientRMService clientRMService = mock(ClientRMService.class);
List<ApplicationReport> appReports = new ArrayList<ApplicationReport>();
for (RMApp app : rmContext.getRMApps().values()) {
ApplicationReport appReport =
ApplicationReport.newInstance(
app.getApplicationId(), (ApplicationAttemptId) null,
app.getUser(), app.getQueue(),
app.getName(), (String) null, 0, (Token) null,
app.createApplicationState(),
app.getDiagnostics().toString(), (String) null,
app.getStartTime(), app.getFinishTime(),
app.getFinalApplicationStatus(),
(ApplicationResourceUsageReport) null, app.getTrackingUrl(),
app.getProgress(), app.getApplicationType(), (Token) null);
appReports.add(appReport);
}
GetApplicationsResponse response = mock(GetApplicationsResponse.class);
when(response.getApplicationList()).thenReturn(appReports);
try {
when(clientRMService.getApplications(any(GetApplicationsRequest.class)))
.thenReturn(response);
} catch (YarnException e) {
Assert.fail("Exception is not expected.");
}
return clientRMService;
}
static void setupQueueConfiguration(CapacitySchedulerConfiguration conf) {
// Define top-level queues
conf.setQueues(CapacitySchedulerConfiguration.ROOT, new String[] {"a", "b", "c"});
final String A = CapacitySchedulerConfiguration.ROOT + ".a";
conf.setCapacity(A, 10);
final String B = CapacitySchedulerConfiguration.ROOT + ".b";
conf.setCapacity(B, 20);
final String C = CapacitySchedulerConfiguration.ROOT + ".c";
conf.setCapacity(C, 70);
// Define 2nd-level queues
final String A1 = A + ".a1";
final String A2 = A + ".a2";
conf.setQueues(A, new String[] {"a1", "a2"});
conf.setCapacity(A1, 30);
conf.setCapacity(A2, 70);
final String B1 = B + ".b1";
final String B2 = B + ".b2";
final String B3 = B + ".b3";
conf.setQueues(B, new String[] {"b1", "b2", "b3"});
conf.setCapacity(B1, 50);
conf.setCapacity(B2, 30);
conf.setCapacity(B3, 20);
final String C1 = C + ".c1";
final String C2 = C + ".c2";
final String C3 = C + ".c3";
final String C4 = C + ".c4";
conf.setQueues(C, new String[] {"c1", "c2", "c3", "c4"});
conf.setCapacity(C1, 50);
conf.setCapacity(C2, 10);
conf.setCapacity(C3, 35);
conf.setCapacity(C4, 5);
// Define 3rd-level queues
final String C11 = C1 + ".c11";
final String C12 = C1 + ".c12";
final String C13 = C1 + ".c13";
conf.setQueues(C1, new String[] {"c11", "c12", "c13"});
conf.setCapacity(C11, 15);
conf.setCapacity(C12, 45);
conf.setCapacity(C13, 40);
}
public static ResourceManager mockFifoRm(int apps, int racks, int nodes,
int mbsPerNode)
throws Exception {
ResourceManager rm = mock(ResourceManager.class);
RMContext rmContext = mockRMContext(apps, racks, nodes,
mbsPerNode);
ResourceScheduler rs = mockFifoScheduler(rmContext);
when(rm.getResourceScheduler()).thenReturn(rs);
when(rm.getRMContext()).thenReturn(rmContext);
return rm;
}
public static FifoScheduler mockFifoScheduler(RMContext rmContext)
throws Exception {
CapacitySchedulerConfiguration conf = new CapacitySchedulerConfiguration();
setupFifoQueueConfiguration(conf);
FifoScheduler fs = new FifoScheduler();
fs.setConf(new YarnConfiguration());
fs.setRMContext(rmContext);
fs.init(conf);
return fs;
}
static void setupFifoQueueConfiguration(CapacitySchedulerConfiguration conf) {
// Define default queue
conf.setQueues("default", new String[] {"default"});
conf.setCapacity("default", 100);
}
public static void main(String[] args) throws Exception {
// For manual testing
WebApps.$for("yarn", new TestRMWebApp()).at(8888).inDevMode().
start(new RMWebApp(mockRm(2500, 8, 8, 8*GiB))).joinThread();
WebApps.$for("yarn", new TestRMWebApp()).at(8888).inDevMode().
start(new RMWebApp(mockFifoRm(10, 1, 4, 8*GiB))).joinThread();
}
}
| |
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch 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.elasticsearch.common.breaker;
import java.util.concurrent.atomic.AtomicLong;
import org.apache.logging.log4j.Logger;
import org.elasticsearch.common.unit.ByteSizeValue;
import org.elasticsearch.indices.breaker.BreakerSettings;
import org.elasticsearch.indices.breaker.CircuitBreakerService;
/**
* Breaker that will check a parent's when incrementing
*/
public class ChildMemoryCircuitBreaker implements CircuitBreaker {
private final long memoryBytesLimit;
private final BreakerSettings settings;
private final AtomicLong used;
private final AtomicLong trippedCount;
private final Logger logger;
private final CircuitBreakerService parent;
private final String name;
/**
* Create a circuit breaker that will break if the number of estimated
* bytes grows above the limit. All estimations will be multiplied by
* the given overheadConstant. This breaker starts with 0 bytes used.
* @param settings settings to configure this breaker
* @param parent parent circuit breaker service to delegate tripped breakers to
* @param name the name of the breaker
*/
public ChildMemoryCircuitBreaker(BreakerSettings settings, Logger logger, CircuitBreakerService parent) {
this(settings, null, logger, parent);
}
/**
* Create a circuit breaker that will break if the number of estimated
* bytes grows above the limit. All estimations will be multiplied by
* the given overheadConstant. Uses the given oldBreaker to initialize
* the starting offset.
* @param settings settings to configure this breaker
* @param parent parent circuit breaker service to delegate tripped breakers to
* @param name the name of the breaker
* @param oldBreaker the previous circuit breaker to inherit the used value from (starting offset)
*/
public ChildMemoryCircuitBreaker(BreakerSettings settings,
ChildMemoryCircuitBreaker oldBreaker,
Logger logger,
CircuitBreakerService parent) {
this.name = settings.getName();
this.settings = settings;
this.memoryBytesLimit = settings.getLimit();
if (oldBreaker == null) {
this.used = new AtomicLong(0);
this.trippedCount = new AtomicLong(0);
} else {
this.used = oldBreaker.used;
this.trippedCount = oldBreaker.trippedCount;
}
this.logger = logger;
if (logger.isTraceEnabled()) {
logger.trace("creating ChildCircuitBreaker with settings {}", this.settings);
}
this.parent = parent;
}
/**
* Method used to trip the breaker, delegates to the parent to determine
* whether to trip the breaker or not
*/
private void circuitBreak(String fieldName, long bytesNeeded) {
this.trippedCount.incrementAndGet();
final String message = "[" + this.name + "] Data too large, data for [" + fieldName + "]" +
" would be [" + bytesNeeded + "/" + new ByteSizeValue(bytesNeeded) + "]" +
", which is larger than the limit of [" +
memoryBytesLimit + "/" + new ByteSizeValue(memoryBytesLimit) + "]";
logger.debug("{}", message);
throw new CircuitBreakingException(message, bytesNeeded, memoryBytesLimit);
}
/**
* Add a number of bytes, tripping the circuit breaker if the aggregated
* estimates are above the limit. Automatically trips the breaker if the
* memory limit is set to 0. Will never trip the breaker if the limit is
* set < 0, but can still be used to aggregate estimations.
* @param bytes number of bytes to add to the breaker
* @return number of "used" bytes so far
*/
@Override
public double addEstimateBytesAndMaybeBreak(long bytes, String label) throws CircuitBreakingException {
// short-circuit on no data allowed, immediately throwing an exception
if (memoryBytesLimit == 0) {
circuitBreak(label, bytes);
}
long newUsed;
// If there is no limit (-1), we can optimize a bit by using
// .addAndGet() instead of looping (because we don't have to check a
// limit), which makes the RamAccountingTermsEnum case faster.
if (this.memoryBytesLimit == -1) {
newUsed = noLimit(bytes, label);
} else {
newUsed = limit(bytes, label);
}
// Additionally, we need to check that we haven't exceeded the parent's limit
try {
parent.checkParentLimit(bytes, label);
} catch (CircuitBreakingException e) {
// If the parent breaker is tripped, this breaker has to be
// adjusted back down because the allocation is "blocked" but the
// breaker has already been incremented
this.addWithoutBreaking(-bytes);
throw e;
}
return newUsed;
}
private long noLimit(long bytes, String label) {
long newUsed;
newUsed = this.used.addAndGet(bytes);
if (logger.isTraceEnabled()) {
logger.trace("[{}] Adding [{}][{}] to used bytes [new used: [{}], limit: [-1b]]",
this.name, new ByteSizeValue(bytes), label, new ByteSizeValue(newUsed));
}
return newUsed;
}
private long limit(long bytes, String label) {
long newUsed;// Otherwise, check the addition and commit the addition, looping if
// there are conflicts. May result in additional logging, but it's
// trace logging and shouldn't be counted on for additions.
long currentUsed;
do {
currentUsed = this.used.get();
newUsed = currentUsed + bytes;
if (logger.isTraceEnabled()) {
logger.trace(
"[{}] Adding [{}][{}] to used bytes [new used: [{}], limit: {} [{}]]",
this.name,
ByteSizeValue.humanReadableBytes(bytes),
label,
ByteSizeValue.humanReadableBytes(newUsed),
memoryBytesLimit,
ByteSizeValue.humanReadableBytes(memoryBytesLimit)
);
}
if (memoryBytesLimit > 0 && newUsed > memoryBytesLimit) {
logger.warn(
"[{}] New used memory {} [{}] for data of [{}] would be larger than configured breaker: {} [{}], breaking",
this.name,
newUsed,
ByteSizeValue.humanReadableBytes(newUsed),
label,
memoryBytesLimit,
ByteSizeValue.humanReadableBytes(memoryBytesLimit)
);
circuitBreak(label, newUsed);
}
// Attempt to set the new used value, but make sure it hasn't changed
// underneath us, if it has, keep trying until we are able to set it
} while (!this.used.compareAndSet(currentUsed, newUsed));
return newUsed;
}
/**
* Add an <b>exact</b> number of bytes, not checking for tripping the
* circuit breaker. This bypasses the overheadConstant multiplication.
*
* Also does not check with the parent breaker to see if the parent limit
* has been exceeded.
*
* @param bytes number of bytes to add to the breaker
* @return number of "used" bytes so far
*/
@Override
public long addWithoutBreaking(long bytes) {
long u = used.addAndGet(bytes);
if (logger.isTraceEnabled()) {
logger.trace("[{}] Adjusted breaker by [{}] bytes, now [{}]", this.name, bytes, u);
}
assert u >= 0 : "Used bytes: [" + u + "] must be >= 0";
return u;
}
/**
* @return the number of aggregated "used" bytes so far
*/
@Override
public long getUsed() {
return this.used.get();
}
/**
* @return the number of bytes that can be added before the breaker trips
*/
@Override
public long getLimit() {
return this.memoryBytesLimit;
}
/**
* @return the number of times the breaker has been tripped
*/
@Override
public long getTrippedCount() {
return this.trippedCount.get();
}
/**
* @return the name of the breaker
*/
@Override
public String getName() {
return this.name;
}
}
| |
/*
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
package com.facebook.drawee.backends.pipeline;
import android.content.res.Resources;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import com.facebook.cache.common.CacheKey;
import com.facebook.common.internal.ImmutableList;
import com.facebook.common.internal.Objects;
import com.facebook.common.internal.Preconditions;
import com.facebook.common.internal.Supplier;
import com.facebook.common.logging.FLog;
import com.facebook.common.references.CloseableReference;
import com.facebook.datasource.DataSource;
import com.facebook.drawable.base.DrawableWithCaches;
import com.facebook.drawee.components.DeferredReleaser;
import com.facebook.drawee.controller.AbstractDraweeController;
import com.facebook.drawee.debug.DebugControllerOverlayDrawable;
import com.facebook.drawee.drawable.OrientedDrawable;
import com.facebook.drawee.interfaces.SettableDraweeHierarchy;
import com.facebook.imagepipeline.animated.factory.AnimatedDrawableFactory;
import com.facebook.imagepipeline.cache.MemoryCache;
import com.facebook.imagepipeline.image.CloseableImage;
import com.facebook.imagepipeline.image.CloseableStaticBitmap;
import com.facebook.imagepipeline.image.EncodedImage;
import com.facebook.imagepipeline.image.ImageInfo;
import java.util.concurrent.Executor;
import javax.annotation.Nullable;
/**
* Drawee controller that bridges the image pipeline with {@link SettableDraweeHierarchy}. <p> The
* hierarchy's actual image is set to the image(s) obtained by the provided data source. The data
* source is automatically obtained and closed based on attach / detach calls.
*/
public class PipelineDraweeController
extends AbstractDraweeController<CloseableReference<CloseableImage>, ImageInfo> {
private static final Class<?> TAG = PipelineDraweeController.class;
// Components
private final Resources mResources;
private final AnimatedDrawableFactory mAnimatedDrawableFactory;
@Nullable
private final ImmutableList<DrawableFactory> mDrawableFactories;
private @Nullable MemoryCache<CacheKey, CloseableImage> mMemoryCache;
private CacheKey mCacheKey;
// Constant state (non-final because controllers can be reused)
private Supplier<DataSource<CloseableReference<CloseableImage>>> mDataSourceSupplier;
private boolean mDrawDebugOverlay;
private final DrawableFactory mDefaultDrawableFactory = new DrawableFactory() {
@Override
public boolean supportsImageType(CloseableImage image) {
return true;
}
@Override
public Drawable createDrawable(CloseableImage closeableImage) {
if (closeableImage instanceof CloseableStaticBitmap) {
CloseableStaticBitmap closeableStaticBitmap = (CloseableStaticBitmap) closeableImage;
Drawable bitmapDrawable = new BitmapDrawable(
mResources,
closeableStaticBitmap.getUnderlyingBitmap());
if (closeableStaticBitmap.getRotationAngle() == 0 ||
closeableStaticBitmap.getRotationAngle() == EncodedImage.UNKNOWN_ROTATION_ANGLE) {
return bitmapDrawable;
} else {
return new OrientedDrawable(bitmapDrawable, closeableStaticBitmap.getRotationAngle());
}
} else if (mAnimatedDrawableFactory != null) {
return mAnimatedDrawableFactory.create(closeableImage);
}
return null;
}
};
public PipelineDraweeController(
Resources resources,
DeferredReleaser deferredReleaser,
AnimatedDrawableFactory animatedDrawableFactory,
Executor uiThreadExecutor,
MemoryCache<CacheKey, CloseableImage> memoryCache,
Supplier<DataSource<CloseableReference<CloseableImage>>> dataSourceSupplier,
String id,
CacheKey cacheKey,
Object callerContext) {
this(
resources,
deferredReleaser,
animatedDrawableFactory,
uiThreadExecutor,
memoryCache,
dataSourceSupplier,
id,
cacheKey,
callerContext,
null);
}
public PipelineDraweeController(
Resources resources,
DeferredReleaser deferredReleaser,
AnimatedDrawableFactory animatedDrawableFactory,
Executor uiThreadExecutor,
MemoryCache<CacheKey, CloseableImage> memoryCache,
Supplier<DataSource<CloseableReference<CloseableImage>>> dataSourceSupplier,
String id,
CacheKey cacheKey,
Object callerContext,
@Nullable ImmutableList<DrawableFactory> drawableFactories) {
super(deferredReleaser, uiThreadExecutor, id, callerContext);
mResources = resources;
mAnimatedDrawableFactory = animatedDrawableFactory;
mMemoryCache = memoryCache;
mCacheKey = cacheKey;
mDrawableFactories = drawableFactories;
init(dataSourceSupplier);
}
/**
* Initializes this controller with the new data source supplier, id and caller context. This
* allows for reusing of the existing controller instead of instantiating a new one. This method
* should be called when the controller is in detached state.
*
* @param dataSourceSupplier data source supplier
* @param id unique id for this controller
* @param callerContext tag and context for this controller
*/
public void initialize(
Supplier<DataSource<CloseableReference<CloseableImage>>> dataSourceSupplier,
String id,
CacheKey cacheKey,
Object callerContext) {
super.initialize(id, callerContext);
init(dataSourceSupplier);
mCacheKey = cacheKey;
}
public void setDrawDebugOverlay(boolean drawDebugOverlay) {
mDrawDebugOverlay = drawDebugOverlay;
}
private void init(Supplier<DataSource<CloseableReference<CloseableImage>>> dataSourceSupplier) {
mDataSourceSupplier = dataSourceSupplier;
maybeUpdateDebugOverlay(null);
}
protected Resources getResources() {
return mResources;
}
@Override
protected DataSource<CloseableReference<CloseableImage>> getDataSource() {
if (FLog.isLoggable(FLog.VERBOSE)) {
FLog.v(TAG, "controller %x: getDataSource", System.identityHashCode(this));
}
return mDataSourceSupplier.get();
}
@Override
protected Drawable createDrawable(CloseableReference<CloseableImage> image) {
Preconditions.checkState(CloseableReference.isValid(image));
CloseableImage closeableImage = image.get();
maybeUpdateDebugOverlay(closeableImage);
if (mDrawableFactories != null) {
for (DrawableFactory factory : mDrawableFactories) {
if (factory.supportsImageType(closeableImage)) {
Drawable drawable = factory.createDrawable(closeableImage);
if (drawable != null) {
return drawable;
}
}
}
}
Drawable defaultDrawable = mDefaultDrawableFactory.createDrawable(closeableImage);
if (defaultDrawable != null) {
return defaultDrawable;
}
throw new UnsupportedOperationException("Unrecognized image class: " + closeableImage);
}
private void maybeUpdateDebugOverlay(@Nullable CloseableImage image) {
if (!mDrawDebugOverlay) {
return;
}
Drawable controllerOverlay = getControllerOverlay();
if (controllerOverlay == null) {
controllerOverlay = new DebugControllerOverlayDrawable();
setControllerOverlay(controllerOverlay);
}
if (controllerOverlay instanceof DebugControllerOverlayDrawable) {
DebugControllerOverlayDrawable debugOverlay =
(DebugControllerOverlayDrawable) controllerOverlay;
debugOverlay.setControllerId(getId());
if (image != null) {
debugOverlay.setDimensions(image.getWidth(), image.getHeight());
debugOverlay.setImageSize(image.getSizeInBytes());
} else {
debugOverlay.reset();
}
}
}
@Override
protected ImageInfo getImageInfo(CloseableReference<CloseableImage> image) {
Preconditions.checkState(CloseableReference.isValid(image));
return image.get();
}
@Override
protected int getImageHash(@Nullable CloseableReference<CloseableImage> image) {
return (image != null) ? image.getValueHash() : 0;
}
@Override
protected void releaseImage(@Nullable CloseableReference<CloseableImage> image) {
CloseableReference.closeSafely(image);
}
@Override
protected void releaseDrawable(@Nullable Drawable drawable) {
if (drawable instanceof DrawableWithCaches) {
((DrawableWithCaches) drawable).dropCaches();
}
}
@Override
protected CloseableReference<CloseableImage> getCachedImage() {
if (mMemoryCache == null || mCacheKey == null) {
return null;
}
// We get the CacheKey
CloseableReference<CloseableImage> closeableImage = mMemoryCache.get(mCacheKey);
if (closeableImage != null && !closeableImage.get().getQualityInfo().isOfFullQuality()) {
closeableImage.close();
return null;
}
return closeableImage;
}
@Override
public String toString() {
return Objects.toStringHelper(this)
.add("super", super.toString())
.add("dataSourceSupplier", mDataSourceSupplier)
.toString();
}
}
| |
/*
* Copyright 2017 Red Hat, Inc. and/or its affiliates.
*
* 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.kie.workbench.common.stunner.core.client.session.command.impl;
import java.util.Collection;
import java.util.Collections;
import java.util.DoubleSummaryStatistics;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Consumer;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
import javax.enterprise.context.Dependent;
import javax.enterprise.event.Event;
import javax.enterprise.event.Observes;
import javax.enterprise.inject.Default;
import javax.inject.Inject;
import org.kie.workbench.common.stunner.core.client.canvas.AbstractCanvas;
import org.kie.workbench.common.stunner.core.client.canvas.AbstractCanvasHandler;
import org.kie.workbench.common.stunner.core.client.canvas.controls.clipboard.ClipboardControl;
import org.kie.workbench.common.stunner.core.client.canvas.event.selection.CanvasSelectionEvent;
import org.kie.workbench.common.stunner.core.client.command.CanvasCommandFactory;
import org.kie.workbench.common.stunner.core.client.command.CanvasCommandResultBuilder;
import org.kie.workbench.common.stunner.core.client.command.CanvasViolation;
import org.kie.workbench.common.stunner.core.client.command.SessionCommandManager;
import org.kie.workbench.common.stunner.core.client.event.keyboard.KeyboardEvent.Key;
import org.kie.workbench.common.stunner.core.client.session.ClientSession;
import org.kie.workbench.common.stunner.core.client.session.Session;
import org.kie.workbench.common.stunner.core.client.session.command.AbstractClientSessionCommand;
import org.kie.workbench.common.stunner.core.client.session.impl.EditorSession;
import org.kie.workbench.common.stunner.core.command.Command;
import org.kie.workbench.common.stunner.core.command.CommandResult;
import org.kie.workbench.common.stunner.core.command.impl.CompositeCommand;
import org.kie.workbench.common.stunner.core.command.util.CommandUtils;
import org.kie.workbench.common.stunner.core.graph.Edge;
import org.kie.workbench.common.stunner.core.graph.Element;
import org.kie.workbench.common.stunner.core.graph.Node;
import org.kie.workbench.common.stunner.core.graph.content.view.Point2D;
import org.kie.workbench.common.stunner.core.graph.content.view.View;
import org.kie.workbench.common.stunner.core.graph.util.GraphUtils;
import org.kie.workbench.common.stunner.core.util.Counter;
import static org.kie.soup.commons.validation.PortablePreconditions.checkNotNull;
import static org.kie.workbench.common.stunner.core.client.canvas.controls.keyboard.KeysMatcher.doKeysMatch;
/**
* This session command obtains the selected elements on the clipboard and clone each one of them.
*/
@Dependent
@Default
public class PasteSelectionSessionCommand extends AbstractClientSessionCommand<EditorSession> {
public static final int DEFAULT_PADDING = 15;
private static Logger LOGGER = Logger.getLogger(PasteSelectionSessionCommand.class.getName());
private final SessionCommandManager<AbstractCanvasHandler> sessionCommandManager;
private final CanvasCommandFactory<AbstractCanvasHandler> canvasCommandFactory;
private final Event<CanvasSelectionEvent> selectionEvent;
private final Map<String, String> clonedElements;
private final CopySelectionSessionCommand copySelectionSessionCommand;
private ClipboardControl<Element, AbstractCanvas, ClientSession> clipboardControl;
private transient DoubleSummaryStatistics yPositionStatistics;
protected PasteSelectionSessionCommand() {
this(null, null, null, null);
}
@Inject
public PasteSelectionSessionCommand(final @Session SessionCommandManager<AbstractCanvasHandler> sessionCommandManager,
final CanvasCommandFactory<AbstractCanvasHandler> canvasCommandFactory,
final Event<CanvasSelectionEvent> selectionEvent,
final CopySelectionSessionCommand copySelectionSessionCommand) {
super(true);
this.sessionCommandManager = sessionCommandManager;
this.canvasCommandFactory = canvasCommandFactory;
this.selectionEvent = selectionEvent;
this.clonedElements = new HashMap<>();
this.copySelectionSessionCommand = copySelectionSessionCommand;
}
@Override
public void bind(final EditorSession session) {
super.bind(session);
session.getKeyboardControl().addKeyShortcutCallback(this::onKeyDownEvent);
this.clipboardControl = session.getClipboardControl();
this.copySelectionSessionCommand.bind(session);
}
@Override
public boolean accepts(final ClientSession session) {
return session instanceof EditorSession;
}
void onKeyDownEvent(final Key... keys) {
if (isEnabled()) {
handleCtrlV(keys);
}
}
private void handleCtrlV(final Key[] keys) {
if (doKeysMatch(keys,
Key.CONTROL,
Key.V)) {
this.execute();
}
}
@Override
public <V> void execute(final Callback<V> callback) {
checkNotNull("callback",
callback);
if (clipboardControl.hasElements()) {
final CompositeCommand.Builder<AbstractCanvasHandler, CanvasViolation> nodesCommandBuilder = createCommandBuilder();
Counter processedNodesCountdown = new Counter((int) clipboardControl.getElements().stream()
.filter(element -> element instanceof Node).count());
//first processing nodes
nodesCommandBuilder.addCommands(clipboardControl.getElements().stream()
.filter(element -> element instanceof Node)
.filter(Objects::nonNull)
.map(node -> (Node<View<?>, Edge>) node)
.map(node -> {
String newParentUUID = getNewParentUUID(node);
return canvasCommandFactory.cloneNode(node, newParentUUID, calculateNewLocation(node, newParentUUID), cloneNodeCallback(node, processedNodesCountdown));
})
.collect(Collectors.toList()));
if (Objects.equals(nodesCommandBuilder.size(), 0)) {
return;
}
// Execute the command for cloning nodes
CommandResult<CanvasViolation> finalResult;
if (wasNodesDeletedFromGraph()) {
//in case of a cut command the source elements were deleted from graph, so first undo the command to take node back into canvas
clipboardControl.getRollbackCommands().forEach(command -> command.undo(getCanvasHandler()));
finalResult = executeCommands(nodesCommandBuilder, processedNodesCountdown);
//after the clone execution than delete source elements again
clipboardControl.getRollbackCommands().forEach(command -> command.execute(getCanvasHandler()));
} else {
//if elements are still on the graph, in case copy command, just execute the clone commands
finalResult = executeCommands(nodesCommandBuilder, processedNodesCountdown);
}
if (CommandUtils.isError(finalResult)) {
LOGGER.severe("Error pasting selection." + getCanvasViolations(finalResult));
return;
}
fireSelectedElementEvent();
callback.onSuccess();
clear();
//copy the cloned node to the clipboard to allow pasting several times
copySelectionSessionCommand.execute();
}
}
private CommandResult<CanvasViolation> executeCommands(CompositeCommand.Builder<AbstractCanvasHandler, CanvasViolation> commandBuilder, Counter processedNodesCountdown) {
CommandResult<CanvasViolation> nodesResult = sessionCommandManager.execute(getCanvasHandler(), commandBuilder.build());
if (CommandUtils.isError(nodesResult)) {
return nodesResult;
}
// Processing connectors: after all nodes has been cloned (this is necessary because we need the cloned nodes UUIDs to than clone the Connectors
CommandResult<CanvasViolation> connectorsResult = processConnectors(processedNodesCountdown);
//After nodes and connectors command execution than it is necessary to update the command registry (to allow a single undo/redo)
if (!CommandUtils.isError(connectorsResult)) {
updateCommandsRegistry();
}
return new CanvasCommandResultBuilder()
.setType(nodesResult.getType())
.addViolations((Objects.nonNull(nodesResult.getViolations()) ?
StreamSupport.stream(nodesResult.getViolations().spliterator(), false).collect(Collectors.toList()) :
Collections.emptyList()))
.addViolations((Objects.nonNull(connectorsResult.getViolations()) ?
StreamSupport.stream(connectorsResult.getViolations().spliterator(), false).collect(Collectors.toList()) :
Collections.emptyList()))
.build();
}
private void updateCommandsRegistry() {
Command<AbstractCanvasHandler, CanvasViolation> connectorsExecutedCommand = sessionCommandManager.getRegistry().pop();
Command<AbstractCanvasHandler, CanvasViolation> nodesExecutedCommand = sessionCommandManager.getRegistry().pop();
sessionCommandManager.getRegistry().register(new CompositeCommand.Builder<AbstractCanvasHandler, CanvasViolation>()
.addCommand(nodesExecutedCommand)
.addCommand(connectorsExecutedCommand)
.reverse()
.build());
}
private CommandResult<CanvasViolation> processConnectors(Counter processedNodesCountdown) {
if (processedNodesCountdown.equalsToValue(0)) {
final CompositeCommand.Builder<AbstractCanvasHandler, CanvasViolation> commandBuilder = createCommandBuilder();
commandBuilder.addCommands(clipboardControl.getElements().stream()
.filter(element -> element instanceof Edge)
.filter(Objects::nonNull)
.map(edge -> (Edge) edge)
.filter(edge -> Objects.nonNull(edge.getSourceNode()) &&
Objects.nonNull(clonedElements.get(edge.getSourceNode().getUUID())) &&
Objects.nonNull(edge.getTargetNode()) &&
Objects.nonNull(clonedElements.get(edge.getTargetNode().getUUID())))
.map(edge -> canvasCommandFactory.cloneConnector(edge,
clonedElements.get(edge.getSourceNode().getUUID()),
clonedElements.get(edge.getTargetNode().getUUID()),
getCanvasHandler().getDiagram().getMetadata().getShapeSetId(),
cloneEdgeCallback(edge)))
.collect(Collectors.toList()));
return sessionCommandManager.execute(getCanvasHandler(), commandBuilder.build());
}
return new CanvasCommandResultBuilder().build();
}
private CompositeCommand.Builder<AbstractCanvasHandler, CanvasViolation> createCommandBuilder() {
return new CompositeCommand.Builder<>();
}
private Consumer<Edge> cloneEdgeCallback(Edge candidate) {
return clone -> clonedElements.put(candidate.getUUID(), clone.getUUID());
}
public boolean wasNodesDeletedFromGraph() {
return clipboardControl.getElements().stream().allMatch(element -> Objects.isNull(getElement(element.getUUID())));
}
@Override
protected void doDestroy() {
super.doDestroy();
clear();
clipboardControl = null;
}
public void clear() {
if (null != clipboardControl) {
clipboardControl.clear();
}
clonedElements.clear();
yPositionStatistics = null;
}
public String getCanvasViolations(CommandResult<CanvasViolation> result) {
if (Objects.nonNull(result) && Objects.nonNull(result.getViolations())) {
return CommandUtils.toList(result.getViolations()).stream().map(Objects::toString).collect(Collectors.joining());
}
return "";
}
protected void onCopySelectionCommandExecuted(@Observes CopySelectionSessionCommandExecutedEvent event) {
checkNotNull("event", event);
if (Objects.equals(getSession(), event.getClientSession())) {
setEnabled(true);
fire();
}
}
protected void onCutSelectionCommandExecuted(@Observes CutSelectionSessionCommandExecutedEvent event) {
checkNotNull("event", event);
if (Objects.equals(getSession(), event.getClientSession())) {
setEnabled(true);
fire();
}
}
private Consumer<Node> cloneNodeCallback(Node candidate, Counter processedNodesCountdown) {
return clone -> {
clonedElements.put(candidate.getUUID(), clone.getUUID());
processedNodesCountdown.decrement();
};
}
private void fireSelectedElementEvent() {
selectionEvent.fire(new CanvasSelectionEvent(getCanvasHandler(), clonedElements.values()));
}
private String getNewParentUUID(Node node) {
//getting parent if selected
Optional<Element> selectedParent = getSelectedParentElement(node.getUUID());
if (selectedParent.isPresent() && !Objects.equals(selectedParent.get().getUUID(), node.getUUID()) && checkIfExistsOnCanvas(selectedParent.get().getUUID())) {
return selectedParent.get().getUUID();
}
//getting node parent if no different parent is selected
String nodeParentUUID = clipboardControl.getParent(node.getUUID());
if (selectedParent.isPresent() &&
Objects.equals(selectedParent.get().getUUID(), node.getUUID()) &&
Objects.nonNull(nodeParentUUID) && checkIfExistsOnCanvas(nodeParentUUID)) {
return nodeParentUUID;
}
//return default parent that is the canvas in case no parent matches
return getCanvasRootUUID();
}
private boolean checkIfExistsOnCanvas(String nodeParentUUID) {
return Objects.nonNull(getElement(nodeParentUUID));
}
private String getCanvasRootUUID() {
return getCanvasHandler().getDiagram().getMetadata().getCanvasRootUUID();
}
private Optional<Element> getSelectedParentElement(String nodeUUID) {
if (null != getSession().getSelectionControl()) {
Collection<String> selectedItems = getSession().getSelectionControl().getSelectedItems();
if (Objects.nonNull(selectedItems) && !selectedItems.isEmpty()) {
Optional<String> selectedParent = selectedItems.stream()
.filter(Objects::nonNull)
.filter(item -> Objects.equals(item, nodeUUID))
.findFirst();
return (selectedParent.isPresent() ?
selectedParent : selectedItems.stream().filter(Objects::nonNull).findFirst())
.map(this::getElement);
}
}
return Optional.empty();
}
private Point2D calculateNewLocation(final Node<? extends View<?>, Edge> node, String newParentUUID) {
Point2D position = GraphUtils.getPosition(node.getContent());
//new parent different from the source node
if (hasParentChanged(node, newParentUUID)) {
return new Point2D(DEFAULT_PADDING, DEFAULT_PADDING);
}
//node is still on canvas (not deleted)
if (existsOnCanvas(node)) {
double x = position.getX();
double max = getYPositionStatistics().getMax();
double min = getYPositionStatistics().getMin();
double y = max + (position.getY() - min) + DEFAULT_PADDING;
return new Point2D(x, y);
}
//default or node was deleted
return position;
}
private DoubleSummaryStatistics getYPositionStatistics() {
if (Objects.isNull(yPositionStatistics)) {
yPositionStatistics = Stream.concat(clipboardControl.getElements().stream()
.filter(element -> element instanceof Node)
.map(element -> ((View) element.getContent()).getBounds().getLowerRight()),
clipboardControl.getElements().stream().filter(element -> element instanceof Node)
.map(element -> ((View) element.getContent()).getBounds().getUpperLeft())).mapToDouble(bound -> bound.getY()).summaryStatistics();
}
return yPositionStatistics;
}
private boolean hasParentChanged(Node<? extends View<?>, Edge> node, String newParentUUID) {
return !Objects.equals(clipboardControl.getParent(node.getUUID()), newParentUUID);
}
private boolean existsOnCanvas(Node<? extends View<?>, Edge> node) {
return Objects.nonNull(getCanvasHandler().getGraphIndex().getNode(node.getUUID()));
}
}
| |
/**
*/
package dk.dtu.se2.animation.presentation;
import java.util.ArrayList;
import java.util.Collection;
import org.eclipse.emf.common.ui.viewer.IViewerProvider;
import org.eclipse.emf.edit.domain.EditingDomain;
import org.eclipse.emf.edit.domain.IEditingDomainProvider;
import org.eclipse.emf.edit.ui.action.ControlAction;
import org.eclipse.emf.edit.ui.action.CreateChildAction;
import org.eclipse.emf.edit.ui.action.CreateSiblingAction;
import org.eclipse.emf.edit.ui.action.EditingDomainActionBarContributor;
import org.eclipse.emf.edit.ui.action.LoadResourceAction;
import org.eclipse.emf.edit.ui.action.ValidateAction;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.ActionContributionItem;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.action.IContributionItem;
import org.eclipse.jface.action.IContributionManager;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.action.SubContributionItem;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.PartInitException;
/**
* This is the action bar contributor for the Animation model editor.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public class AnimationActionBarContributor
extends EditingDomainActionBarContributor
implements ISelectionChangedListener {
/**
* This keeps track of the active editor.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected IEditorPart activeEditorPart;
/**
* This keeps track of the current selection provider.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected ISelectionProvider selectionProvider;
/**
* This action opens the Properties view.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected IAction showPropertiesViewAction =
new Action(AnimationEditorPlugin.INSTANCE.getString("_UI_ShowPropertiesView_menu_item")) {
@Override
public void run() {
try {
getPage().showView("org.eclipse.ui.views.PropertySheet");
}
catch (PartInitException exception) {
AnimationEditorPlugin.INSTANCE.log(exception);
}
}
};
/**
* This action refreshes the viewer of the current editor if the editor
* implements {@link org.eclipse.emf.common.ui.viewer.IViewerProvider}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected IAction refreshViewerAction =
new Action(AnimationEditorPlugin.INSTANCE.getString("_UI_RefreshViewer_menu_item")) {
@Override
public boolean isEnabled() {
return activeEditorPart instanceof IViewerProvider;
}
@Override
public void run() {
if (activeEditorPart instanceof IViewerProvider) {
Viewer viewer = ((IViewerProvider)activeEditorPart).getViewer();
if (viewer != null) {
viewer.refresh();
}
}
}
};
/**
* This will contain one {@link org.eclipse.emf.edit.ui.action.CreateChildAction} corresponding to each descriptor
* generated for the current selection by the item provider.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected Collection<IAction> createChildActions;
/**
* This is the menu manager into which menu contribution items should be added for CreateChild actions.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected IMenuManager createChildMenuManager;
/**
* This will contain one {@link org.eclipse.emf.edit.ui.action.CreateSiblingAction} corresponding to each descriptor
* generated for the current selection by the item provider.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected Collection<IAction> createSiblingActions;
/**
* This is the menu manager into which menu contribution items should be added for CreateSibling actions.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected IMenuManager createSiblingMenuManager;
/**
* This creates an instance of the contributor.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public AnimationActionBarContributor() {
super(ADDITIONS_LAST_STYLE);
loadResourceAction = new LoadResourceAction();
validateAction = new ValidateAction();
controlAction = new ControlAction();
}
/**
* This adds Separators for editor additions to the tool bar.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void contributeToToolBar(IToolBarManager toolBarManager) {
toolBarManager.add(new Separator("animation-settings"));
toolBarManager.add(new Separator("animation-additions"));
}
/**
* This adds to the menu bar a menu and some separators for editor additions,
* as well as the sub-menus for object creation items.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void contributeToMenu(IMenuManager menuManager) {
super.contributeToMenu(menuManager);
IMenuManager submenuManager = new MenuManager(AnimationEditorPlugin.INSTANCE.getString("_UI_AnimationEditor_menu"), "dk.dtu.se2.animationMenuID");
menuManager.insertAfter("additions", submenuManager);
submenuManager.add(new Separator("settings"));
submenuManager.add(new Separator("actions"));
submenuManager.add(new Separator("additions"));
submenuManager.add(new Separator("additions-end"));
// Prepare for CreateChild item addition or removal.
//
createChildMenuManager = new MenuManager(AnimationEditorPlugin.INSTANCE.getString("_UI_CreateChild_menu_item"));
submenuManager.insertBefore("additions", createChildMenuManager);
// Prepare for CreateSibling item addition or removal.
//
createSiblingMenuManager = new MenuManager(AnimationEditorPlugin.INSTANCE.getString("_UI_CreateSibling_menu_item"));
submenuManager.insertBefore("additions", createSiblingMenuManager);
// Force an update because Eclipse hides empty menus now.
//
submenuManager.addMenuListener
(new IMenuListener() {
public void menuAboutToShow(IMenuManager menuManager) {
menuManager.updateAll(true);
}
});
addGlobalActions(submenuManager);
}
/**
* When the active editor changes, this remembers the change and registers with it as a selection provider.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void setActiveEditor(IEditorPart part) {
super.setActiveEditor(part);
activeEditorPart = part;
// Switch to the new selection provider.
//
if (selectionProvider != null) {
selectionProvider.removeSelectionChangedListener(this);
}
if (part == null) {
selectionProvider = null;
}
else {
selectionProvider = part.getSite().getSelectionProvider();
selectionProvider.addSelectionChangedListener(this);
// Fake a selection changed event to update the menus.
//
if (selectionProvider.getSelection() != null) {
selectionChanged(new SelectionChangedEvent(selectionProvider, selectionProvider.getSelection()));
}
}
}
/**
* This implements {@link org.eclipse.jface.viewers.ISelectionChangedListener},
* handling {@link org.eclipse.jface.viewers.SelectionChangedEvent}s by querying for the children and siblings
* that can be added to the selected object and updating the menus accordingly.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void selectionChanged(SelectionChangedEvent event) {
// Remove any menu items for old selection.
//
if (createChildMenuManager != null) {
depopulateManager(createChildMenuManager, createChildActions);
}
if (createSiblingMenuManager != null) {
depopulateManager(createSiblingMenuManager, createSiblingActions);
}
// Query the new selection for appropriate new child/sibling descriptors
//
Collection<?> newChildDescriptors = null;
Collection<?> newSiblingDescriptors = null;
ISelection selection = event.getSelection();
if (selection instanceof IStructuredSelection && ((IStructuredSelection)selection).size() == 1) {
Object object = ((IStructuredSelection)selection).getFirstElement();
EditingDomain domain = ((IEditingDomainProvider)activeEditorPart).getEditingDomain();
newChildDescriptors = domain.getNewChildDescriptors(object, null);
newSiblingDescriptors = domain.getNewChildDescriptors(null, object);
}
// Generate actions for selection; populate and redraw the menus.
//
createChildActions = generateCreateChildActions(newChildDescriptors, selection);
createSiblingActions = generateCreateSiblingActions(newSiblingDescriptors, selection);
if (createChildMenuManager != null) {
populateManager(createChildMenuManager, createChildActions, null);
createChildMenuManager.update(true);
}
if (createSiblingMenuManager != null) {
populateManager(createSiblingMenuManager, createSiblingActions, null);
createSiblingMenuManager.update(true);
}
}
/**
* This generates a {@link org.eclipse.emf.edit.ui.action.CreateChildAction} for each object in <code>descriptors</code>,
* and returns the collection of these actions.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected Collection<IAction> generateCreateChildActions(Collection<?> descriptors, ISelection selection) {
Collection<IAction> actions = new ArrayList<IAction>();
if (descriptors != null) {
for (Object descriptor : descriptors) {
actions.add(new CreateChildAction(activeEditorPart, selection, descriptor));
}
}
return actions;
}
/**
* This generates a {@link org.eclipse.emf.edit.ui.action.CreateSiblingAction} for each object in <code>descriptors</code>,
* and returns the collection of these actions.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected Collection<IAction> generateCreateSiblingActions(Collection<?> descriptors, ISelection selection) {
Collection<IAction> actions = new ArrayList<IAction>();
if (descriptors != null) {
for (Object descriptor : descriptors) {
actions.add(new CreateSiblingAction(activeEditorPart, selection, descriptor));
}
}
return actions;
}
/**
* This populates the specified <code>manager</code> with {@link org.eclipse.jface.action.ActionContributionItem}s
* based on the {@link org.eclipse.jface.action.IAction}s contained in the <code>actions</code> collection,
* by inserting them before the specified contribution item <code>contributionID</code>.
* If <code>contributionID</code> is <code>null</code>, they are simply added.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void populateManager(IContributionManager manager, Collection<? extends IAction> actions, String contributionID) {
if (actions != null) {
for (IAction action : actions) {
if (contributionID != null) {
manager.insertBefore(contributionID, action);
}
else {
manager.add(action);
}
}
}
}
/**
* This removes from the specified <code>manager</code> all {@link org.eclipse.jface.action.ActionContributionItem}s
* based on the {@link org.eclipse.jface.action.IAction}s contained in the <code>actions</code> collection.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void depopulateManager(IContributionManager manager, Collection<? extends IAction> actions) {
if (actions != null) {
IContributionItem[] items = manager.getItems();
for (int i = 0; i < items.length; i++) {
// Look into SubContributionItems
//
IContributionItem contributionItem = items[i];
while (contributionItem instanceof SubContributionItem) {
contributionItem = ((SubContributionItem)contributionItem).getInnerItem();
}
// Delete the ActionContributionItems with matching action.
//
if (contributionItem instanceof ActionContributionItem) {
IAction action = ((ActionContributionItem)contributionItem).getAction();
if (actions.contains(action)) {
manager.remove(contributionItem);
}
}
}
}
}
/**
* This populates the pop-up menu before it appears.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void menuAboutToShow(IMenuManager menuManager) {
super.menuAboutToShow(menuManager);
MenuManager submenuManager = null;
submenuManager = new MenuManager(AnimationEditorPlugin.INSTANCE.getString("_UI_CreateChild_menu_item"));
populateManager(submenuManager, createChildActions, null);
menuManager.insertBefore("edit", submenuManager);
submenuManager = new MenuManager(AnimationEditorPlugin.INSTANCE.getString("_UI_CreateSibling_menu_item"));
populateManager(submenuManager, createSiblingActions, null);
menuManager.insertBefore("edit", submenuManager);
}
/**
* This inserts global actions before the "additions-end" separator.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected void addGlobalActions(IMenuManager menuManager) {
menuManager.insertAfter("additions-end", new Separator("ui-actions"));
menuManager.insertAfter("ui-actions", showPropertiesViewAction);
refreshViewerAction.setEnabled(refreshViewerAction.isEnabled());
menuManager.insertAfter("ui-actions", refreshViewerAction);
super.addGlobalActions(menuManager);
}
/**
* This ensures that a delete action will clean up all references to deleted objects.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected boolean removeAllReferencesOnDelete() {
return true;
}
}
| |
/*
* 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.logging.log4j;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.OutputStream;
import java.io.Writer;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import org.apache.logging.log4j.categories.PerformanceTests;
import org.apache.logging.log4j.core.config.ConfigurationFactory;
import org.apache.logging.log4j.core.util.Profiler;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.experimental.categories.Category;
/**
* Use this class to analyze performance between Log4j and other logging frameworks.
*/
@Category(PerformanceTests.class)
public class PerformanceComparison {
private final Logger logger = LogManager.getLogger(PerformanceComparison.class.getName());
private final org.slf4j.Logger logbacklogger = org.slf4j.LoggerFactory.getLogger(PerformanceComparison.class);
private final org.apache.log4j.Logger log4jlogger = org.apache.log4j.Logger.getLogger(PerformanceComparison.class);
// How many times should we try to log:
private static final int COUNT = 500000;
private static final int PROFILE_COUNT = 500000;
private static final int WARMUP = 50000;
private static final String CONFIG = "log4j2-perf.xml";
private static final String LOGBACK_CONFIG = "logback-perf.xml";
private static final String LOG4J_CONFIG = "log4j12-perf.xml";
private static final String LOGBACK_CONF = "logback.configurationFile";
private static final String LOG4J_CONF = "log4j.configuration";
@BeforeClass
public static void setupClass() {
System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY, CONFIG);
System.setProperty(LOGBACK_CONF, LOGBACK_CONFIG);
System.setProperty(LOG4J_CONF, LOG4J_CONFIG);
}
@AfterClass
public static void cleanupClass() {
System.clearProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY);
System.clearProperty(LOGBACK_CONF);
System.clearProperty(LOG4J_CONF);
new File("target/testlog4j.log").deleteOnExit();
new File("target/testlog4j2.log").deleteOnExit();
new File("target/testlogback.log").deleteOnExit();
}
@Test
public void testPerformance() throws Exception {
log4j(WARMUP);
logback(WARMUP);
log4j2(WARMUP);
if (Profiler.isActive()) {
System.out.println("Profiling Log4j 2.0");
Profiler.start();
final long result = log4j2(PROFILE_COUNT);
Profiler.stop();
System.out.println("###############################################");
System.out.println("Log4j 2.0: " + result);
System.out.println("###############################################");
} else {
doRun();
doRun();
doRun();
doRun();
}
}
private void doRun() {
System.out.print("Log4j : ");
System.out.println(log4j(COUNT));
System.out.print("Logback : ");
System.out.println(logback(COUNT));
System.out.print("Log4j 2.0: ");
System.out.println(log4j2(COUNT));
System.out.println("###############################################");
}
//@Test
public void testRawPerformance() throws Exception {
final OutputStream os = new FileOutputStream("target/testos.log", true);
final long result1 = writeToStream(COUNT, os);
os.close();
final OutputStream bos = new BufferedOutputStream(new FileOutputStream("target/testbuffer.log", true));
final long result2 = writeToStream(COUNT, bos);
bos.close();
final Writer w = new FileWriter("target/testwriter.log", true);
final long result3 = writeToWriter(COUNT, w);
w.close();
final FileOutputStream cos = new FileOutputStream("target/testchannel.log", true);
final FileChannel channel = cos.getChannel();
final long result4 = writeToChannel(COUNT, channel);
cos.close();
System.out.println("###############################################");
System.out.println("FileOutputStream: " + result1);
System.out.println("BufferedOutputStream: " + result2);
System.out.println("FileWriter: " + result3);
System.out.println("FileChannel: " + result4);
System.out.println("###############################################");
}
private long log4j(final int loop) {
final Integer j = Integer.valueOf(2);
final long start = System.nanoTime();
for (int i = 0; i < loop; i++) {
log4jlogger.debug("SEE IF THIS IS LOGGED " + j + '.');
}
return (System.nanoTime() - start) / loop;
}
private long logback(final int loop) {
final Integer j = Integer.valueOf(2);
final long start = System.nanoTime();
for (int i = 0; i < loop; i++) {
logbacklogger.debug("SEE IF THIS IS LOGGED " + j + '.');
}
return (System.nanoTime() - start) / loop;
}
private long log4j2(final int loop) {
final Integer j = Integer.valueOf(2);
final long start = System.nanoTime();
for (int i = 0; i < loop; i++) {
logger.debug("SEE IF THIS IS LOGGED " + j + '.');
}
return (System.nanoTime() - start) / loop;
}
private long writeToWriter(final int loop, final Writer w) throws Exception {
final Integer j = Integer.valueOf(2);
final long start = System.nanoTime();
for (int i = 0; i < loop; i++) {
w.write("SEE IF THIS IS LOGGED " + j + '.');
}
return (System.nanoTime() - start) / loop;
}
private long writeToStream(final int loop, final OutputStream os) throws Exception {
final Integer j = Integer.valueOf(2);
final long start = System.nanoTime();
for (int i = 0; i < loop; i++) {
os.write(getBytes("SEE IF THIS IS LOGGED " + j + '.'));
}
return (System.nanoTime() - start) / loop;
}
private long writeToChannel(final int loop, final FileChannel channel) throws Exception {
final Integer j = Integer.valueOf(2);
final ByteBuffer buf = ByteBuffer.allocateDirect(8*1024);
final long start = System.nanoTime();
for (int i = 0; i < loop; i++) {
channel.write(getByteBuffer(buf, "SEE IF THIS IS LOGGED " + j + '.'));
}
return (System.nanoTime() - start) / loop;
}
private ByteBuffer getByteBuffer(final ByteBuffer buf, final String s) {
buf.clear();
buf.put(s.getBytes());
buf.flip();
return buf;
}
private byte[] getBytes(final String s) {
return s.getBytes();
}
}
| |
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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 General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This file is available under and governed by the GNU General Public
* License version 2 only, as published by the Free Software Foundation.
* However, the following notice accompanied the original version of this
* file:
*
* Written by Josh Bloch of Google Inc. and released to the public domain,
* as explained at http://creativecommons.org/publicdomain/zero/1.0/.
*/
package benchmarks.instrumented.java17.util;
import java.io.*;
/**
* Resizable-array implementation of the {@link Deque} interface. Array
* deques have no capacity restrictions; they grow as necessary to support
* usage. They are not thread-safe; in the absence of external
* synchronization, they do not support concurrent access by multiple threads.
* Null elements are prohibited. This class is likely to be faster than
* {@link Stack} when used as a stack, and faster than {@link LinkedList}
* when used as a queue.
*
* <p>Most <tt>ArrayDeque</tt> operations run in amortized constant time.
* Exceptions include {@link #remove(Object) remove}, {@link
* #removeFirstOccurrence removeFirstOccurrence}, {@link #removeLastOccurrence
* removeLastOccurrence}, {@link #contains contains}, {@link #iterator
* iterator.remove()}, and the bulk operations, all of which run in linear
* time.
*
* <p>The iterators returned by this class's <tt>iterator</tt> method are
* <i>fail-fast</i>: If the deque is modified at any time after the iterator
* is created, in any way except through the iterator's own <tt>remove</tt>
* method, the iterator will generally throw a {@link
* ConcurrentModificationException}. Thus, in the face of concurrent
* modification, the iterator fails quickly and cleanly, rather than risking
* arbitrary, non-deterministic behavior at an undetermined time in the
* future.
*
* <p>Note that the fail-fast behavior of an iterator cannot be guaranteed
* as it is, generally speaking, impossible to make any hard guarantees in the
* presence of unsynchronized concurrent modification. Fail-fast iterators
* throw <tt>ConcurrentModificationException</tt> on a best-effort basis.
* Therefore, it would be wrong to write a program that depended on this
* exception for its correctness: <i>the fail-fast behavior of iterators
* should be used only to detect bugs.</i>
*
* <p>This class and its iterator implement all of the
* <em>optional</em> methods of the {@link Collection} and {@link
* Iterator} interfaces.
*
* <p>This class is a member of the
* <a href="{@docRoot}/../technotes/guides/collections/index.html">
* Java Collections Framework</a>.
*
* @author Josh Bloch and Doug Lea
* @since 1.6
* @param <E> the type of elements held in this collection
*/
public class ArrayDeque<E> extends AbstractCollection<E>
implements Deque<E>, Cloneable, Serializable
{
/**
* The array in which the elements of the deque are stored.
* The capacity of the deque is the length of this array, which is
* always a power of two. The array is never allowed to become
* full, except transiently within an addX method where it is
* resized (see doubleCapacity) immediately upon becoming full,
* thus avoiding head and tail wrapping around to equal each
* other. We also guarantee that all array cells not holding
* deque elements are always null.
*/
private transient E[] elements;
/**
* The index of the element at the head of the deque (which is the
* element that would be removed by remove() or pop()); or an
* arbitrary number equal to tail if the deque is empty.
*/
private transient int head;
/**
* The index at which the next element would be added to the tail
* of the deque (via addLast(E), add(E), or push(E)).
*/
private transient int tail;
/**
* The minimum capacity that we'll use for a newly created deque.
* Must be a power of 2.
*/
private static final int MIN_INITIAL_CAPACITY = 8;
// ****** Array allocation and resizing utilities ******
/**
* Allocate empty array to hold the given number of elements.
*
* @param numElements the number of elements to hold
*/
private void allocateElements(int numElements) {
int initialCapacity = MIN_INITIAL_CAPACITY;
// Find the best power of two to hold elements.
// Tests "<=" because arrays aren't kept full.
if (numElements >= initialCapacity) {
initialCapacity = numElements;
initialCapacity |= (initialCapacity >>> 1);
initialCapacity |= (initialCapacity >>> 2);
initialCapacity |= (initialCapacity >>> 4);
initialCapacity |= (initialCapacity >>> 8);
initialCapacity |= (initialCapacity >>> 16);
initialCapacity++;
if (initialCapacity < 0) // Too many elements, must back off
initialCapacity >>>= 1;// Good luck allocating 2 ^ 30 elements
}
elements = (E[]) new Object[initialCapacity];
}
/**
* Double the capacity of this deque. Call only when full, i.e.,
* when head and tail have wrapped around to become equal.
*/
private void doubleCapacity() {
assert head == tail;
int p = head;
int n = elements.length;
int r = n - p; // number of elements to the right of p
int newCapacity = n << 1;
if (newCapacity < 0)
throw new IllegalStateException("Sorry, deque too big");
Object[] a = new Object[newCapacity];
System.arraycopy(elements, p, a, 0, r);
System.arraycopy(elements, 0, a, r, p);
elements = (E[])a;
head = 0;
tail = n;
}
/**
* Copies the elements from our element array into the specified array,
* in order (from first to last element in the deque). It is assumed
* that the array is large enough to hold all elements in the deque.
*
* @return its argument
*/
private <T> T[] copyElements(T[] a) {
if (head < tail) {
System.arraycopy(elements, head, a, 0, size());
} else if (head > tail) {
int headPortionLen = elements.length - head;
System.arraycopy(elements, head, a, 0, headPortionLen);
System.arraycopy(elements, 0, a, headPortionLen, tail);
}
return a;
}
/**
* Constructs an empty array deque with an initial capacity
* sufficient to hold 16 elements.
*/
public ArrayDeque() {
elements = (E[]) new Object[16];
}
/**
* Constructs an empty array deque with an initial capacity
* sufficient to hold the specified number of elements.
*
* @param numElements lower bound on initial capacity of the deque
*/
public ArrayDeque(int numElements) {
allocateElements(numElements);
}
/**
* Constructs a deque containing the elements of the specified
* collection, in the order they are returned by the collection's
* iterator. (The first element returned by the collection's
* iterator becomes the first element, or <i>front</i> of the
* deque.)
*
* @param c the collection whose elements are to be placed into the deque
* @throws NullPointerException if the specified collection is null
*/
public ArrayDeque(Collection<? extends E> c) {
allocateElements(c.size());
addAll(c);
}
// The main insertion and extraction methods are addFirst,
// addLast, pollFirst, pollLast. The other methods are defined in
// terms of these.
/**
* Inserts the specified element at the front of this deque.
*
* @param e the element to add
* @throws NullPointerException if the specified element is null
*/
public void addFirst(E e) {
if (e == null)
throw new NullPointerException();
elements[head = (head - 1) & (elements.length - 1)] = e;
if (head == tail)
doubleCapacity();
}
/**
* Inserts the specified element at the end of this deque.
*
* <p>This method is equivalent to {@link #add}.
*
* @param e the element to add
* @throws NullPointerException if the specified element is null
*/
public void addLast(E e) {
if (e == null)
throw new NullPointerException();
elements[tail] = e;
if ( (tail = (tail + 1) & (elements.length - 1)) == head)
doubleCapacity();
}
/**
* Inserts the specified element at the front of this deque.
*
* @param e the element to add
* @return <tt>true</tt> (as specified by {@link Deque#offerFirst})
* @throws NullPointerException if the specified element is null
*/
public boolean offerFirst(E e) {
addFirst(e);
return true;
}
/**
* Inserts the specified element at the end of this deque.
*
* @param e the element to add
* @return <tt>true</tt> (as specified by {@link Deque#offerLast})
* @throws NullPointerException if the specified element is null
*/
public boolean offerLast(E e) {
addLast(e);
return true;
}
/**
* @throws NoSuchElementException {@inheritDoc}
*/
public E removeFirst() {
E x = pollFirst();
if (x == null)
throw new NoSuchElementException();
return x;
}
/**
* @throws NoSuchElementException {@inheritDoc}
*/
public E removeLast() {
E x = pollLast();
if (x == null)
throw new NoSuchElementException();
return x;
}
public E pollFirst() {
int h = head;
E result = elements[h]; // Element is null if deque empty
if (result == null)
return null;
elements[h] = null; // Must null out slot
head = (h + 1) & (elements.length - 1);
return result;
}
public E pollLast() {
int t = (tail - 1) & (elements.length - 1);
E result = elements[t];
if (result == null)
return null;
elements[t] = null;
tail = t;
return result;
}
/**
* @throws NoSuchElementException {@inheritDoc}
*/
public E getFirst() {
E x = elements[head];
if (x == null)
throw new NoSuchElementException();
return x;
}
/**
* @throws NoSuchElementException {@inheritDoc}
*/
public E getLast() {
E x = elements[(tail - 1) & (elements.length - 1)];
if (x == null)
throw new NoSuchElementException();
return x;
}
public E peekFirst() {
return elements[head]; // elements[head] is null if deque empty
}
public E peekLast() {
return elements[(tail - 1) & (elements.length - 1)];
}
/**
* Removes the first occurrence of the specified element in this
* deque (when traversing the deque from head to tail).
* If the deque does not contain the element, it is unchanged.
* More formally, removes the first element <tt>e</tt> such that
* <tt>o.equals(e)</tt> (if such an element exists).
* Returns <tt>true</tt> if this deque contained the specified element
* (or equivalently, if this deque changed as a result of the call).
*
* @param o element to be removed from this deque, if present
* @return <tt>true</tt> if the deque contained the specified element
*/
public boolean removeFirstOccurrence(Object o) {
if (o == null)
return false;
int mask = elements.length - 1;
int i = head;
E x;
while ( (x = elements[i]) != null) {
if (o.equals(x)) {
delete(i);
return true;
}
i = (i + 1) & mask;
}
return false;
}
/**
* Removes the last occurrence of the specified element in this
* deque (when traversing the deque from head to tail).
* If the deque does not contain the element, it is unchanged.
* More formally, removes the last element <tt>e</tt> such that
* <tt>o.equals(e)</tt> (if such an element exists).
* Returns <tt>true</tt> if this deque contained the specified element
* (or equivalently, if this deque changed as a result of the call).
*
* @param o element to be removed from this deque, if present
* @return <tt>true</tt> if the deque contained the specified element
*/
public boolean removeLastOccurrence(Object o) {
if (o == null)
return false;
int mask = elements.length - 1;
int i = (tail - 1) & mask;
E x;
while ( (x = elements[i]) != null) {
if (o.equals(x)) {
delete(i);
return true;
}
i = (i - 1) & mask;
}
return false;
}
// *** Queue methods ***
/**
* Inserts the specified element at the end of this deque.
*
* <p>This method is equivalent to {@link #addLast}.
*
* @param e the element to add
* @return <tt>true</tt> (as specified by {@link Collection#add})
* @throws NullPointerException if the specified element is null
*/
public boolean add(E e) {
addLast(e);
return true;
}
/**
* Inserts the specified element at the end of this deque.
*
* <p>This method is equivalent to {@link #offerLast}.
*
* @param e the element to add
* @return <tt>true</tt> (as specified by {@link Queue#offer})
* @throws NullPointerException if the specified element is null
*/
public boolean offer(E e) {
return offerLast(e);
}
/**
* Retrieves and removes the head of the queue represented by this deque.
*
* This method differs from {@link #poll poll} only in that it throws an
* exception if this deque is empty.
*
* <p>This method is equivalent to {@link #removeFirst}.
*
* @return the head of the queue represented by this deque
* @throws NoSuchElementException {@inheritDoc}
*/
public E remove() {
return removeFirst();
}
/**
* Retrieves and removes the head of the queue represented by this deque
* (in other words, the first element of this deque), or returns
* <tt>null</tt> if this deque is empty.
*
* <p>This method is equivalent to {@link #pollFirst}.
*
* @return the head of the queue represented by this deque, or
* <tt>null</tt> if this deque is empty
*/
public E poll() {
return pollFirst();
}
/**
* Retrieves, but does not remove, the head of the queue represented by
* this deque. This method differs from {@link #peek peek} only in
* that it throws an exception if this deque is empty.
*
* <p>This method is equivalent to {@link #getFirst}.
*
* @return the head of the queue represented by this deque
* @throws NoSuchElementException {@inheritDoc}
*/
public E element() {
return getFirst();
}
/**
* Retrieves, but does not remove, the head of the queue represented by
* this deque, or returns <tt>null</tt> if this deque is empty.
*
* <p>This method is equivalent to {@link #peekFirst}.
*
* @return the head of the queue represented by this deque, or
* <tt>null</tt> if this deque is empty
*/
public E peek() {
return peekFirst();
}
// *** Stack methods ***
/**
* Pushes an element onto the stack represented by this deque. In other
* words, inserts the element at the front of this deque.
*
* <p>This method is equivalent to {@link #addFirst}.
*
* @param e the element to push
* @throws NullPointerException if the specified element is null
*/
public void push(E e) {
addFirst(e);
}
/**
* Pops an element from the stack represented by this deque. In other
* words, removes and returns the first element of this deque.
*
* <p>This method is equivalent to {@link #removeFirst()}.
*
* @return the element at the front of this deque (which is the top
* of the stack represented by this deque)
* @throws NoSuchElementException {@inheritDoc}
*/
public E pop() {
return removeFirst();
}
private void checkInvariants() {
assert elements[tail] == null;
assert head == tail ? elements[head] == null :
(elements[head] != null &&
elements[(tail - 1) & (elements.length - 1)] != null);
assert elements[(head - 1) & (elements.length - 1)] == null;
}
/**
* Removes the element at the specified position in the elements array,
* adjusting head and tail as necessary. This can result in motion of
* elements backwards or forwards in the array.
*
* <p>This method is called delete rather than remove to emphasize
* that its semantics differ from those of {@link List#remove(int)}.
*
* @return true if elements moved backwards
*/
private boolean delete(int i) {
checkInvariants();
final E[] elements = this.elements;
final int mask = elements.length - 1;
final int h = head;
final int t = tail;
final int front = (i - h) & mask;
final int back = (t - i) & mask;
// Invariant: head <= i < tail mod circularity
if (front >= ((t - h) & mask))
throw new ConcurrentModificationException();
// Optimize for least element motion
if (front < back) {
if (h <= i) {
System.arraycopy(elements, h, elements, h + 1, front);
} else { // Wrap around
System.arraycopy(elements, 0, elements, 1, i);
elements[0] = elements[mask];
System.arraycopy(elements, h, elements, h + 1, mask - h);
}
elements[h] = null;
head = (h + 1) & mask;
return false;
} else {
if (i < t) { // Copy the null tail as well
System.arraycopy(elements, i + 1, elements, i, back);
tail = t - 1;
} else { // Wrap around
System.arraycopy(elements, i + 1, elements, i, mask - i);
elements[mask] = elements[0];
System.arraycopy(elements, 1, elements, 0, t);
tail = (t - 1) & mask;
}
return true;
}
}
// *** Collection Methods ***
/**
* Returns the number of elements in this deque.
*
* @return the number of elements in this deque
*/
public int size() {
return (tail - head) & (elements.length - 1);
}
/**
* Returns <tt>true</tt> if this deque contains no elements.
*
* @return <tt>true</tt> if this deque contains no elements
*/
public boolean isEmpty() {
return head == tail;
}
/**
* Returns an iterator over the elements in this deque. The elements
* will be ordered from first (head) to last (tail). This is the same
* order that elements would be dequeued (via successive calls to
* {@link #remove} or popped (via successive calls to {@link #pop}).
*
* @return an iterator over the elements in this deque
*/
public Iterator<E> iterator() {
return new DeqIterator();
}
public Iterator<E> descendingIterator() {
return new DescendingIterator();
}
private class DeqIterator implements Iterator<E> {
/**
* Index of element to be returned by subsequent call to next.
*/
private int cursor = head;
/**
* Tail recorded at construction (also in remove), to stop
* iterator and also to check for comodification.
*/
private int fence = tail;
/**
* Index of element returned by most recent call to next.
* Reset to -1 if element is deleted by a call to remove.
*/
private int lastRet = -1;
public boolean hasNext() {
return cursor != fence;
}
public E next() {
if (cursor == fence)
throw new NoSuchElementException();
E result = elements[cursor];
// This check doesn't catch all possible comodifications,
// but does catch the ones that corrupt traversal
if (tail != fence || result == null)
throw new ConcurrentModificationException();
lastRet = cursor;
cursor = (cursor + 1) & (elements.length - 1);
return result;
}
public void remove() {
if (lastRet < 0)
throw new IllegalStateException();
if (delete(lastRet)) { // if left-shifted, undo increment in next()
cursor = (cursor - 1) & (elements.length - 1);
fence = tail;
}
lastRet = -1;
}
}
private class DescendingIterator implements Iterator<E> {
/*
* This class is nearly a mirror-image of DeqIterator, using
* tail instead of head for initial cursor, and head instead of
* tail for fence.
*/
private int cursor = tail;
private int fence = head;
private int lastRet = -1;
public boolean hasNext() {
return cursor != fence;
}
public E next() {
if (cursor == fence)
throw new NoSuchElementException();
cursor = (cursor - 1) & (elements.length - 1);
E result = elements[cursor];
if (head != fence || result == null)
throw new ConcurrentModificationException();
lastRet = cursor;
return result;
}
public void remove() {
if (lastRet < 0)
throw new IllegalStateException();
if (!delete(lastRet)) {
cursor = (cursor + 1) & (elements.length - 1);
fence = head;
}
lastRet = -1;
}
}
/**
* Returns <tt>true</tt> if this deque contains the specified element.
* More formally, returns <tt>true</tt> if and only if this deque contains
* at least one element <tt>e</tt> such that <tt>o.equals(e)</tt>.
*
* @param o object to be checked for containment in this deque
* @return <tt>true</tt> if this deque contains the specified element
*/
public boolean contains(Object o) {
if (o == null)
return false;
int mask = elements.length - 1;
int i = head;
E x;
while ( (x = elements[i]) != null) {
if (o.equals(x))
return true;
i = (i + 1) & mask;
}
return false;
}
/**
* Removes a single instance of the specified element from this deque.
* If the deque does not contain the element, it is unchanged.
* More formally, removes the first element <tt>e</tt> such that
* <tt>o.equals(e)</tt> (if such an element exists).
* Returns <tt>true</tt> if this deque contained the specified element
* (or equivalently, if this deque changed as a result of the call).
*
* <p>This method is equivalent to {@link #removeFirstOccurrence}.
*
* @param o element to be removed from this deque, if present
* @return <tt>true</tt> if this deque contained the specified element
*/
public boolean remove(Object o) {
return removeFirstOccurrence(o);
}
/**
* Removes all of the elements from this deque.
* The deque will be empty after this call returns.
*/
public void clear() {
int h = head;
int t = tail;
if (h != t) { // clear all cells
head = tail = 0;
int i = h;
int mask = elements.length - 1;
do {
elements[i] = null;
i = (i + 1) & mask;
} while (i != t);
}
}
/**
* Returns an array containing all of the elements in this deque
* in proper sequence (from first to last element).
*
* <p>The returned array will be "safe" in that no references to it are
* maintained by this deque. (In other words, this method must allocate
* a new array). The caller is thus free to modify the returned array.
*
* <p>This method acts as bridge between array-based and collection-based
* APIs.
*
* @return an array containing all of the elements in this deque
*/
public Object[] toArray() {
return copyElements(new Object[size()]);
}
/**
* Returns an array containing all of the elements in this deque in
* proper sequence (from first to last element); the runtime type of the
* returned array is that of the specified array. If the deque fits in
* the specified array, it is returned therein. Otherwise, a new array
* is allocated with the runtime type of the specified array and the
* size of this deque.
*
* <p>If this deque fits in the specified array with room to spare
* (i.e., the array has more elements than this deque), the element in
* the array immediately following the end of the deque is set to
* <tt>null</tt>.
*
* <p>Like the {@link #toArray()} method, this method acts as bridge between
* array-based and collection-based APIs. Further, this method allows
* precise control over the runtime type of the output array, and may,
* under certain circumstances, be used to save allocation costs.
*
* <p>Suppose <tt>x</tt> is a deque known to contain only strings.
* The following code can be used to dump the deque into a newly
* allocated array of <tt>String</tt>:
*
* <pre>
* String[] y = x.toArray(new String[0]);</pre>
*
* Note that <tt>toArray(new Object[0])</tt> is identical in function to
* <tt>toArray()</tt>.
*
* @param a the array into which the elements of the deque are to
* be stored, if it is big enough; otherwise, a new array of the
* same runtime type is allocated for this purpose
* @return an array containing all of the elements in this deque
* @throws ArrayStoreException if the runtime type of the specified array
* is not a supertype of the runtime type of every element in
* this deque
* @throws NullPointerException if the specified array is null
*/
public <T> T[] toArray(T[] a) {
int size = size();
if (a.length < size)
a = (T[])java.lang.reflect.Array.newInstance(
a.getClass().getComponentType(), size);
copyElements(a);
if (a.length > size)
a[size] = null;
return a;
}
// *** Object methods ***
/**
* Returns a copy of this deque.
*
* @return a copy of this deque
*/
public ArrayDeque<E> clone() {
try {
ArrayDeque<E> result = (ArrayDeque<E>) super.clone();
result.elements = Arrays.copyOf(elements, elements.length);
return result;
} catch (CloneNotSupportedException e) {
throw new AssertionError();
}
}
/**
* Appease the serialization gods.
*/
private static final long serialVersionUID = 2340985798034038923L;
/**
* Serialize this deque.
*
* @serialData The current size (<tt>int</tt>) of the deque,
* followed by all of its elements (each an object reference) in
* first-to-last order.
*/
private void writeObject(ObjectOutputStream s) throws IOException {
s.defaultWriteObject();
// Write out size
s.writeInt(size());
// Write out elements in order.
int mask = elements.length - 1;
for (int i = head; i != tail; i = (i + 1) & mask)
s.writeObject(elements[i]);
}
/**
* Deserialize this deque.
*/
private void readObject(ObjectInputStream s)
throws IOException, ClassNotFoundException {
s.defaultReadObject();
// Read in size and allocate array
int size = s.readInt();
allocateElements(size);
head = 0;
tail = size;
// Read in all elements in the proper order.
for (int i = 0; i < size; i++)
elements[i] = (E)s.readObject();
}
}
| |
/*
* 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.jackrabbit.test.api.version;
import org.apache.jackrabbit.test.NotExecutableException;
import javax.jcr.nodetype.NodeDefinition;
import javax.jcr.version.Version;
import javax.jcr.version.VersionException;
import javax.jcr.version.OnParentVersionAction;
import javax.jcr.version.VersionManager;
import javax.jcr.Session;
import javax.jcr.Node;
import javax.jcr.RepositoryException;
import javax.jcr.ItemNotFoundException;
import javax.jcr.InvalidItemStateException;
import javax.jcr.ItemExistsException;
/**
* <code>WorkspaceRestoreTest</code> provides test methods for the {@link javax.jcr.Workspace#restore(javax.jcr.version.Version[], boolean)}
* method.
*
*/
public class WorkspaceRestoreTest extends AbstractVersionTest {
Session wSuperuser;
Version version;
Version version2;
Version rootVersion;
Node versionableNode2;
Node wTestRoot;
Node wVersionableNode;
Node wVersionableNode2;
Node wVersionableChildNode;
Version wChildVersion;
protected void setUp() throws Exception {
super.setUp();
VersionManager versionManager = versionableNode.getSession().getWorkspace().getVersionManager();
String path = versionableNode.getPath();
version = versionManager.checkin(path);
versionManager.checkout(path);
version2 = versionManager.checkin(path);
versionManager.checkout(path);
rootVersion = versionManager.getVersionHistory(path).getRootVersion();
// build a second versionable node below the testroot
try {
versionableNode2 = createVersionableNode(testRootNode, nodeName2, versionableNodeType);
} catch (RepositoryException e) {
fail("Failed to create a second versionable node: " + e.getMessage());
}
try {
wSuperuser = getHelper().getSuperuserSession(workspaceName);
} catch (RepositoryException e) {
fail("Failed to retrieve superuser session for second workspace '" + workspaceName + "': " + e.getMessage());
}
// test if the required nodes exist in the second workspace if not try to clone them
try {
testRootNode.getCorrespondingNodePath(workspaceName);
} catch (ItemNotFoundException e) {
// clone testRoot
wSuperuser.getWorkspace().clone(superuser.getWorkspace().getName(), testRoot, testRoot, true);
}
try {
versionableNode.getCorrespondingNodePath(workspaceName);
} catch (ItemNotFoundException e) {
// clone versionable node
wSuperuser.getWorkspace().clone(superuser.getWorkspace().getName(), versionableNode.getPath(), versionableNode.getPath(), true);
}
try {
versionableNode2.getCorrespondingNodePath(workspaceName);
} catch (ItemNotFoundException e) {
// clone second versionable node
wSuperuser.getWorkspace().clone(superuser.getWorkspace().getName(), versionableNode2.getPath(), versionableNode2.getPath(), true);
}
try {
// set node-fields (wTestRoot, wVersionableNode, wVersionableNode2)
// and check versionable nodes out.
wTestRoot = (Node) wSuperuser.getItem(testRootNode.getPath());
wVersionableNode = wSuperuser.getNodeByIdentifier(versionableNode.getIdentifier());
wVersionableNode.getSession().getWorkspace().getVersionManager().checkout(wVersionableNode.getPath());
wVersionableNode2 = wSuperuser.getNodeByIdentifier(versionableNode2.getIdentifier());
wVersionableNode2.getSession().getWorkspace().getVersionManager().checkout(wVersionableNode2.getPath());
} catch (RepositoryException e) {
fail("Failed to setup test environment in workspace: " + e.toString());
}
// create persistent versionable CHILD-node below wVersionableNode in workspace 2
// that is not present in the default workspace.
try {
wVersionableChildNode = createVersionableNode(wVersionableNode, nodeName4, versionableNodeType);
} catch (RepositoryException e) {
fail("Failed to create versionable child node in second workspace: " + e.getMessage());
}
// create a version of the versionable child node
VersionManager wVersionManager = wVersionableChildNode.getSession().getWorkspace().getVersionManager();
String wPath = wVersionableChildNode.getPath();
wVersionManager.checkout(wPath);
wChildVersion = wVersionManager.checkin(wPath);
wVersionManager.checkout(wPath);
}
protected void tearDown() throws Exception {
try {
// remove all versionable nodes below the test
versionableNode2.remove();
wVersionableNode.remove();
wVersionableNode2.remove();
wTestRoot.save();
} finally {
if (wSuperuser != null) {
wSuperuser.logout();
wSuperuser = null;
}
version = null;
version2 = null;
rootVersion = null;
versionableNode2 = null;
wTestRoot = null;
wVersionableNode = null;
wVersionableNode2 = null;
wVersionableChildNode = null;
wChildVersion = null;
super.tearDown();
}
}
/**
* Test if InvalidItemStateException is thrown if the session affected by
* Workspace.restore(Version[], boolean) has pending changes.
*/
@SuppressWarnings("deprecation")
public void testWorkspaceRestoreWithPendingChanges() throws RepositoryException {
versionableNode.checkout();
try {
// modify node without calling save()
versionableNode.setProperty(propertyName1, propertyValue);
// create version in second workspace
Version v = wVersionableNode.checkin();
// try to restore that version
superuser.getWorkspace().restore(new Version[]{v}, false);
fail("InvalidItemStateException must be thrown on attempt to call Workspace.restore(Version[], boolean) in a session having any unsaved changes pending.");
} catch (InvalidItemStateException e) {
// success
}
}
/**
* Test if InvalidItemStateException is thrown if the session affected by
* VersionManager.restore(Version[], boolean) has pending changes.
*/
public void testWorkspaceRestoreWithPendingChangesJcr2() throws RepositoryException {
versionableNode.getSession().getWorkspace().getVersionManager().checkout(versionableNode.getPath());
try {
// modify node without calling save()
versionableNode.setProperty(propertyName1, propertyValue);
// create version in second workspace
Version v = wVersionableNode.getSession().getWorkspace().getVersionManager().checkin(wVersionableNode.getPath());
// try to restore that version
superuser.getWorkspace().getVersionManager().restore(new Version[]{v}, false);
fail("InvalidItemStateException must be thrown on attempt to call Workspace.restore(Version[], boolean) in a session having any unsaved changes pending.");
} catch (InvalidItemStateException e) {
// success
}
}
/**
* Test if VersionException is thrown if the specified version array does
* not contain a version that has a corresponding node in this workspace.
*/
@SuppressWarnings("deprecation")
public void testWorkspaceRestoreHasCorrespondingNode() throws RepositoryException {
try {
superuser.getWorkspace().restore(new Version[]{wChildVersion}, false);
fail("Workspace.restore(Version[], boolean) must throw VersionException if non of the specified versions has a corresponding node in the workspace.");
} catch (VersionException e) {
// success
}
}
/**
* Test if VersionException is thrown if the specified version array does
* not contain a version that has a corresponding node in this workspace.
*/
public void testWorkspaceRestoreHasCorrespondingNodeJcr2() throws RepositoryException {
try {
superuser.getWorkspace().getVersionManager().restore(new Version[]{wChildVersion}, false);
fail("Workspace.restore(Version[], boolean) must throw VersionException if non of the specified versions has a corresponding node in the workspace.");
} catch (VersionException e) {
// success
}
}
/**
* Test if Workspace.restore(Version[], boolean) succeeds if the following two
* preconditions are fulfilled:<ul>
* <li>For every version V in S that corresponds to a missing node in the workspace,
* there must also be a parent of V in S.</li>
* <li>S must contain at least one version that corresponds to an existing
* node in the workspace.</li>
* </ul>
*/
@SuppressWarnings("deprecation")
public void testWorkspaceRestoreWithParent() throws RepositoryException {
try {
Version parentV = wVersionableNode.checkin();
superuser.getWorkspace().restore(new Version[]{parentV, wChildVersion}, false);
} catch (RepositoryException e) {
fail("Workspace.restore(Version[], boolean) with a version that has no corresponding node must succeed if a version of a parent with correspondance is present in the version array.");
}
}
/**
* Test if VersionManager.restore(Version[], boolean) succeeds if the following two
* preconditions are fulfilled:<ul>
* <li>For every version V in S that corresponds to a missing node in the workspace,
* there must also be a parent of V in S.</li>
* <li>S must contain at least one version that corresponds to an existing
* node in the workspace.</li>
* </ul>
*/
public void testWorkspaceRestoreWithParentJcr2() throws RepositoryException {
try {
Version parentV = wVersionableNode.getSession().getWorkspace().getVersionManager().checkin(wVersionableNode.getPath());
superuser.getWorkspace().getVersionManager().restore(new Version[]{parentV, wChildVersion}, false);
} catch (RepositoryException e) {
fail("Workspace.restore(Version[], boolean) with a version that has no corresponding node must succeed if a version of a parent with correspondance is present in the version array.");
}
}
/**
* Test if the removeExisting-flag removes an existing node in case of uuid conflict.
*/
@SuppressWarnings("deprecation")
public void testWorkspaceRestoreWithRemoveExisting() throws NotExecutableException, RepositoryException {
// create version for parentNode of childNode
superuser.getWorkspace().clone(workspaceName, wVersionableChildNode.getPath(), wVersionableChildNode.getPath(), false);
Version parentV = versionableNode.checkin();
// move child node in order to produce the uuid conflict
String newChildPath = wVersionableNode2.getPath() + "/" + wVersionableChildNode.getName();
wSuperuser.move(wVersionableChildNode.getPath(), newChildPath);
wSuperuser.save();
// restore the parent with removeExisting == true >> moved child node
// must be removed.
wSuperuser.getWorkspace().restore(new Version[]{parentV}, true);
if (wSuperuser.itemExists(newChildPath)) {
fail("Workspace.restore(Version[], boolean) with the boolean flag set to true, must remove the existing node in case of Uuid conflict.");
}
}
/**
* Test if the removeExisting-flag removes an existing node in case of uuid conflict.
*/
public void testWorkspaceRestoreWithRemoveExistingJcr2() throws NotExecutableException, RepositoryException {
// create version for parentNode of childNode
superuser.getWorkspace().clone(workspaceName, wVersionableChildNode.getPath(), wVersionableChildNode.getPath(), false);
Version parentV = versionableNode.getSession().getWorkspace().getVersionManager().checkin(versionableNode.getPath());
// move child node in order to produce the uuid conflict
String newChildPath = wVersionableNode2.getPath() + "/" + wVersionableChildNode.getName();
wSuperuser.move(wVersionableChildNode.getPath(), newChildPath);
wSuperuser.save();
// restore the parent with removeExisting == true >> moved child node
// must be removed.
wSuperuser.getWorkspace().getVersionManager().restore(new Version[]{parentV}, true);
if (wSuperuser.itemExists(newChildPath)) {
fail("Workspace.restore(Version[], boolean) with the boolean flag set to true, must remove the existing node in case of Uuid conflict.");
}
}
/**
* Tests if restoring the <code>Version</code> of an existing node throws an
* <code>ItemExistsException</code> if removeExisting is set to FALSE.
*/
@SuppressWarnings("deprecation")
public void testWorkspaceRestoreWithUUIDConflict() throws RepositoryException, NotExecutableException {
try {
// Verify that nodes used for the test are indeed versionable
NodeDefinition nd = wVersionableNode.getDefinition();
if (nd.getOnParentVersion() != OnParentVersionAction.COPY && nd.getOnParentVersion() != OnParentVersionAction.VERSION) {
throw new NotExecutableException("Nodes must be versionable in order to run this test.");
}
Version v = wVersionableNode.checkin();
wVersionableNode.checkout();
wSuperuser.move(wVersionableChildNode.getPath(), wVersionableNode2.getPath() + "/" + wVersionableChildNode.getName());
wSuperuser.save();
wSuperuser.getWorkspace().restore(new Version[]{v}, false);
fail("Node.restore( Version, boolean ): An ItemExistsException must be thrown if the node to be restored already exsits and removeExisting was set to false.");
} catch (ItemExistsException e) {
// success
}
}
/**
* Tests if restoring the <code>Version</code> of an existing node throws an
* <code>ItemExistsException</code> if removeExisting is set to FALSE.
*/
public void testWorkspaceRestoreWithUUIDConflictJcr2() throws RepositoryException, NotExecutableException {
try {
// Verify that nodes used for the test are indeed versionable
NodeDefinition nd = wVersionableNode.getDefinition();
if (nd.getOnParentVersion() != OnParentVersionAction.COPY && nd.getOnParentVersion() != OnParentVersionAction.VERSION) {
throw new NotExecutableException("Nodes must be versionable in order to run this test.");
}
VersionManager versionManager = wVersionableNode.getSession().getWorkspace().getVersionManager();
String path = wVersionableNode.getPath();
Version v = versionManager.checkin(path);
versionManager.checkout(path);
wSuperuser.move(wVersionableChildNode.getPath(), wVersionableNode2.getPath() + "/" + wVersionableChildNode.getName());
wSuperuser.save();
wSuperuser.getWorkspace().getVersionManager().restore(new Version[]{v}, false);
fail("Node.restore( Version, boolean ): An ItemExistsException must be thrown if the node to be restored already exsits and removeExisting was set to false.");
} catch (ItemExistsException e) {
// success
}
}
/**
* Test if workspace-restoring a node works on checked-in node.
*/
@SuppressWarnings("deprecation")
public void testWorkspaceRestoreOnCheckedInNode() throws RepositoryException {
if (versionableNode.isCheckedOut()) {
versionableNode.checkin();
}
superuser.getWorkspace().restore(new Version[]{version}, true);
}
/**
* Test if workspace-restoring a node works on checked-in node.
*/
public void testWorkspaceRestoreOnCheckedInNodeJcr2() throws RepositoryException {
VersionManager versionManager = versionableNode.getSession().getWorkspace().getVersionManager();
String path = versionableNode.getPath();
if (versionManager.isCheckedOut(path)) {
versionManager.checkin(path);
}
superuser.getWorkspace().getVersionManager().restore(new Version[]{version}, true);
}
/**
* Test if workspace-restoring a node works on checked-out node.
*/
@SuppressWarnings("deprecation")
public void testWorkspaceRestoreOnCheckedOutNode() throws RepositoryException {
if (!versionableNode.isCheckedOut()) {
versionableNode.checkout();
}
superuser.getWorkspace().restore(new Version[]{version}, true);
}
/**
* Test if workspace-restoring a node works on checked-out node.
*/
public void testWorkspaceRestoreOnCheckedOutNodeJcr2() throws RepositoryException {
VersionManager versionManager = versionableNode.getSession().getWorkspace().getVersionManager();
String path = versionableNode.getPath();
if (!versionManager.isCheckedOut(path)) {
versionManager.checkout(path);
}
superuser.getWorkspace().getVersionManager().restore(new Version[]{version}, true);
}
}
| |
package org.zstack.core.db;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowire;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.transaction.annotation.Transactional;
import org.zstack.core.db.DatabaseFacadeImpl.EntityInfo;
import org.zstack.core.db.SimpleQuery.Op;
import org.zstack.header.exception.CloudRuntimeException;
import org.zstack.utils.DebugUtils;
import org.zstack.utils.Utils;
import org.zstack.utils.logging.CLogger;
import javax.persistence.Query;
import javax.persistence.metamodel.SingularAttribute;
import java.util.*;
/**
* Created by xing5 on 2016/6/29.
*/
@Configurable(preConstruction=true,autowire= Autowire.BY_TYPE,dependencyCheck=true)
public class UpdateQueryImpl implements UpdateQuery {
private static CLogger logger = Utils.getLogger(UpdateQueryImpl.class);
@Autowired
private DatabaseFacadeImpl dbf;
private Class entityClass;
private Map<SingularAttribute, Object> setValues = new HashMap<>();
private Map<SingularAttribute, List<Cond>> andConditions = new HashMap<>();
private class Cond {
SingularAttribute attr;
Op op;
Object val;
}
UpdateQuery entity(Class clazz) {
entityClass = clazz;
return this;
}
@Override
public UpdateQuery set(SingularAttribute attr, Object val) {
if (setValues.containsKey(attr)) {
throw new CloudRuntimeException(String.format("unable to set a column[%s] twice", attr.getName()));
}
setValues.put(attr, val);
return this;
}
@Override
public UpdateQuery condAnd(SingularAttribute attr, Op op, Object val) {
if ((op == Op.IN || op == Op.NOT_IN) && !(val instanceof Collection)) {
throw new CloudRuntimeException(String.format("for operation IN or NOT IN, a Collection value is expected, but %s got", val.getClass()));
}
Cond cond = new Cond();
cond.attr = attr;
cond.op = op;
cond.val = val;
List<Cond> conds = andConditions.get(attr);
if (conds == null) {
conds = new ArrayList<>();
andConditions.put(attr, conds);
}
conds.add(cond);
return this;
}
@Override
public UpdateQuery eq(SingularAttribute attr, Object val) {
condAnd(attr, Op.EQ, val);
return this;
}
@Override
public UpdateQuery notEq(SingularAttribute attr, Object val) {
condAnd(attr, Op.NOT_EQ, val);
return this;
}
@Override
public UpdateQuery in(SingularAttribute attr, Collection val) {
condAnd(attr, Op.IN, val);
return this;
}
@Override
public UpdateQuery notIn(SingularAttribute attr, Collection val) {
condAnd(attr, Op.NOT_IN, val);
return this;
}
@Override
public UpdateQuery isNull(SingularAttribute attr) {
condAnd(attr, Op.NULL, null);
return this;
}
@Override
public UpdateQuery notNull(SingularAttribute attr) {
condAnd(attr, Op.NOT_NULL, null);
return this;
}
@Override
public UpdateQuery gt(SingularAttribute attr, Object val) {
condAnd(attr, Op.GT, val);
return this;
}
@Override
public UpdateQuery gte(SingularAttribute attr, Object val) {
condAnd(attr, Op.GTE, val);
return this;
}
@Override
public UpdateQuery lt(SingularAttribute attr, Object val) {
condAnd(attr, Op.LT, val);
return this;
}
@Override
public UpdateQuery lte(SingularAttribute attr, Object val) {
condAnd(attr, Op.LTE, val);
return this;
}
@Override
public UpdateQuery like(SingularAttribute attr, Object val) {
condAnd(attr, Op.LIKE, val);
return this;
}
@Override
public UpdateQuery notLike(SingularAttribute attr, Object val) {
condAnd(attr, Op.NOT_LIKE, val);
return this;
}
private String where() {
if (andConditions.isEmpty()) {
return null;
}
List<String> condstrs = new ArrayList<>();
for (List<Cond> conds : andConditions.values()) {
for (int i=0; i<conds.size(); i++) {
Cond cond = conds.get(i);
String condName = String.format("cond_%s_%s", cond.attr.getName(), i);
if (Op.IN == cond.op || Op.NOT_IN == cond.op) {
condstrs.add(String.format("vo.%s %s (:%s)", cond.attr.getName(), cond.op.toString(), condName));
} else if (Op.NULL == cond.op || Op.NOT_NULL == cond.op) {
condstrs.add(String.format("vo.%s %s", cond.attr.getName(), cond.op));
} else {
condstrs.add(String.format("vo.%s %s :%s", cond.attr.getName(), cond.op.toString(), condName));
}
}
}
return StringUtils.join(condstrs, " AND ");
}
private void fillConditions(Query q) {
for (List<Cond> conds : andConditions.values()) {
for (int i=0; i<conds.size(); i++) {
Cond cond = conds.get(i);
if (Op.NULL == cond.op || Op.NOT_NULL == cond.op) {
continue;
}
q.setParameter("cond_" + cond.attr.getName() + String.format("_%s", i), cond.val);
}
}
}
@Override
@Transactional
public int hardDelete() {
DebugUtils.Assert(entityClass!=null, "entity class cannot be null");
StringBuilder sb = new StringBuilder(String.format("DELETE FROM %s vo", entityClass.getSimpleName()));
String where = where();
if (where != null) {
sb.append(String.format(" WHERE %s", where));
}
String sql = sb.toString();
if (logger.isTraceEnabled()) {
logger.trace(sql);
}
Query q = dbf.getEntityManager().createQuery(sql);
if (where != null) {
fillConditions(q);
}
int ret = q.executeUpdate();
dbf.getEntityManager().flush();
return ret;
}
@Override
@Transactional
public void delete() {
DebugUtils.Assert(entityClass!=null, "entity class cannot be null");
EntityInfo info = dbf.getEntityInfo(entityClass);
DebugUtils.Assert(entityClass!=null, "entity class cannot be null");
StringBuilder sb = new StringBuilder(String.format("SELECT vo.%s FROM %s vo", info.voPrimaryKeyField.getName(),
entityClass.getSimpleName()));
String where = where();
if (where != null) {
sb.append(String.format(" WHERE %s", where));
}
String sql = sb.toString();
if (logger.isTraceEnabled()) {
logger.trace(sql);
}
Query q = dbf.getEntityManager().createQuery(sql);
if (where != null) {
fillConditions(q);
}
List ids = q.getResultList();
if (ids.isEmpty()) {
return;
}
info.removeByPrimaryKeys(ids);
}
@Override
@Transactional
public void update() {
DebugUtils.Assert(entityClass!=null, "entity class cannot be null");
StringBuilder sb = new StringBuilder(String.format("UPDATE %s vo", entityClass.getSimpleName()));
List<String> setters = new ArrayList<>();
for (Map.Entry<SingularAttribute, Object> e : setValues.entrySet()) {
setters.add(String.format("vo.%s=:%s", e.getKey().getName(), e.getKey().getName()));
}
sb.append(String.format(" SET %s ", StringUtils.join(setters, ",")));
String where = where();
if (where != null) {
sb.append(String.format(" WHERE %s", where));
}
String sql = sb.toString();
if (logger.isTraceEnabled()) {
logger.trace(sql);
}
Query q = dbf.getEntityManager().createQuery(sql);
for (Map.Entry<SingularAttribute, Object> e : setValues.entrySet()) {
q.setParameter(e.getKey().getName(), e.getValue());
}
if (where != null) {
fillConditions(q);
}
q.executeUpdate();
dbf.getEntityManager().flush();
}
}
| |
// -*- mode: java; c-basic-offset: 2; -*-
// Copyright 2009-2011 Google, All Rights reserved
// Copyright 2011-2012 MIT, All rights reserved
// Released under the MIT License https://raw.github.com/mit-cml/app-inventor/master/mitlicense.txt
package com.google.appinventor.components.runtime;
import com.google.appinventor.components.annotations.DesignerComponent;
import com.google.appinventor.components.annotations.DesignerProperty;
import com.google.appinventor.components.annotations.PropertyCategory;
import com.google.appinventor.components.annotations.SimpleEvent;
import com.google.appinventor.components.annotations.SimpleFunction;
import com.google.appinventor.components.annotations.SimpleObject;
import com.google.appinventor.components.annotations.SimpleProperty;
import com.google.appinventor.components.common.ComponentCategory;
import com.google.appinventor.components.common.PropertyTypeConstants;
import com.google.appinventor.components.common.YaVersion;
import android.os.Handler;
/**
* A component that provides a high-level interface to a sound sensor on a LEGO
* MINDSTORMS NXT robot.
*
*/
@DesignerComponent(version = YaVersion.NXT_SOUNDSENSOR_COMPONENT_VERSION,
description = "A component that provides a high-level interface to a sound sensor on a " +
"LEGO MINDSTORMS NXT robot.",
category = ComponentCategory.LEGOMINDSTORMS,
nonVisible = true,
iconName = "images/legoMindstormsNxt.png")
@SimpleObject
public class NxtSoundSensor extends LegoMindstormsNxtSensor implements Deleteable {
private enum State { UNKNOWN, BELOW_RANGE, WITHIN_RANGE, ABOVE_RANGE }
private static final String DEFAULT_SENSOR_PORT = "2";
private static final int DEFAULT_BOTTOM_OF_RANGE = 256;
private static final int DEFAULT_TOP_OF_RANGE = 767;
private Handler handler;
private final Runnable sensorReader;
private State previousState;
private int bottomOfRange;
private int topOfRange;
private boolean belowRangeEventEnabled;
private boolean withinRangeEventEnabled;
private boolean aboveRangeEventEnabled;
/**
* Creates a new NxtSoundSensor component.
*/
public NxtSoundSensor(ComponentContainer container) {
super(container, "NxtSoundSensor");
handler = new Handler();
previousState = State.UNKNOWN;
sensorReader = new Runnable() {
public void run() {
if (bluetooth != null && bluetooth.IsConnected()) {
SensorValue<Integer> sensorValue = getSoundValue("");
if (sensorValue.valid) {
State currentState;
if (sensorValue.value < bottomOfRange) {
currentState = State.BELOW_RANGE;
} else if (sensorValue.value > topOfRange) {
currentState = State.ABOVE_RANGE;
} else {
currentState = State.WITHIN_RANGE;
}
if (currentState != previousState) {
if (currentState == State.BELOW_RANGE && belowRangeEventEnabled) {
BelowRange();
}
if (currentState == State.WITHIN_RANGE && withinRangeEventEnabled) {
WithinRange();
}
if (currentState == State.ABOVE_RANGE && aboveRangeEventEnabled) {
AboveRange();
}
}
previousState = currentState;
}
}
if (isHandlerNeeded()) {
handler.post(sensorReader);
}
}
};
SensorPort(DEFAULT_SENSOR_PORT);
BottomOfRange(DEFAULT_BOTTOM_OF_RANGE);
TopOfRange(DEFAULT_TOP_OF_RANGE);
BelowRangeEventEnabled(false);
WithinRangeEventEnabled(false);
AboveRangeEventEnabled(false);
}
@Override
protected void initializeSensor(String functionName) {
// TODO(user) - support SENSOR_TYPE_SOUND_DBA by adding a DesignerProperty.
setInputMode(functionName, port, SENSOR_TYPE_SOUND_DB, SENSOR_MODE_RAWMODE);
}
/**
* Specifies the sensor port that the sensor is connected to.
*/
@DesignerProperty(editorType = PropertyTypeConstants.PROPERTY_TYPE_LEGO_NXT_SENSOR_PORT,
defaultValue = DEFAULT_SENSOR_PORT)
@SimpleProperty(userVisible = false)
public void SensorPort(String sensorPortLetter) {
setSensorPort(sensorPortLetter);
}
@SimpleFunction(description = "Returns the current sound level as a value between 0 and 1023, " +
"or -1 if the sound level can not be read.")
public int GetSoundLevel() {
String functionName = "GetSoundLevel";
if (!checkBluetooth(functionName)) {
return -1;
}
SensorValue<Integer> sensorValue = getSoundValue(functionName);
if (sensorValue.valid) {
return sensorValue.value;
}
// invalid response
return -1;
}
private SensorValue<Integer> getSoundValue(String functionName) {
byte[] returnPackage = getInputValues(functionName, port);
if (returnPackage != null) {
boolean valid = getBooleanValueFromBytes(returnPackage, 4);
if (valid) {
int normalizedValue = getUWORDValueFromBytes(returnPackage, 10);
return new SensorValue<Integer>(true, normalizedValue);
}
}
// invalid response
return new SensorValue<Integer>(false, null);
}
/**
* Returns the bottom of the range used for the BelowRange, WithinRange,
* and AboveRange events.
*/
@SimpleProperty(description = "The bottom of the range used for the BelowRange, WithinRange," +
" and AboveRange events.",
category = PropertyCategory.BEHAVIOR)
public int BottomOfRange() {
return bottomOfRange;
}
/**
* Specifies the bottom of the range used for the BelowRange, WithinRange,
* and AboveRange events.
*/
@DesignerProperty(editorType = PropertyTypeConstants.PROPERTY_TYPE_NON_NEGATIVE_INTEGER,
defaultValue = "" + DEFAULT_BOTTOM_OF_RANGE)
@SimpleProperty
public void BottomOfRange(int bottomOfRange) {
this.bottomOfRange = bottomOfRange;
previousState = State.UNKNOWN;
}
/**
* Returns the top of the range used for the BelowRange, WithinRange, and
* AboveRange events.
*/
@SimpleProperty(description = "The top of the range used for the BelowRange, WithinRange, and" +
" AboveRange events.",
category = PropertyCategory.BEHAVIOR)
public int TopOfRange() {
return topOfRange;
}
/**
* Specifies the top of the range used for the BelowRange, WithinRange, and
* AboveRange events.
*/
@DesignerProperty(editorType = PropertyTypeConstants.PROPERTY_TYPE_NON_NEGATIVE_INTEGER,
defaultValue = "" + DEFAULT_TOP_OF_RANGE)
@SimpleProperty
public void TopOfRange(int topOfRange) {
this.topOfRange = topOfRange;
previousState = State.UNKNOWN;
}
/**
* Returns whether the BelowRange event should fire when the sound level
* goes below the BottomOfRange.
*/
@SimpleProperty(description = "Whether the BelowRange event should fire when the sound level" +
" goes below the BottomOfRange.",
category = PropertyCategory.BEHAVIOR)
public boolean BelowRangeEventEnabled() {
return belowRangeEventEnabled;
}
/**
* Specifies whether the BelowRange event should fire when the sound level
* goes below the BottomOfRange.
*/
@DesignerProperty(editorType = PropertyTypeConstants.PROPERTY_TYPE_BOOLEAN, defaultValue = "False")
@SimpleProperty
public void BelowRangeEventEnabled(boolean enabled) {
boolean handlerWasNeeded = isHandlerNeeded();
belowRangeEventEnabled = enabled;
boolean handlerIsNeeded = isHandlerNeeded();
if (handlerWasNeeded && !handlerIsNeeded) {
handler.removeCallbacks(sensorReader);
}
if (!handlerWasNeeded && handlerIsNeeded) {
previousState = State.UNKNOWN;
handler.post(sensorReader);
}
}
@SimpleEvent(description = "Sound level has gone below the range.")
public void BelowRange() {
EventDispatcher.dispatchEvent(this, "BelowRange");
}
/**
* Returns whether the WithinRange event should fire when the sound level
* goes between the BottomOfRange and the TopOfRange.
*/
@SimpleProperty(description = "Whether the WithinRange event should fire when the sound level" +
" goes between the BottomOfRange and the TopOfRange.",
category = PropertyCategory.BEHAVIOR)
public boolean WithinRangeEventEnabled() {
return withinRangeEventEnabled;
}
/**
* Specifies whether the WithinRange event should fire when the sound level
* goes between the BottomOfRange and the TopOfRange.
*/
@DesignerProperty(editorType = PropertyTypeConstants.PROPERTY_TYPE_BOOLEAN, defaultValue = "False")
@SimpleProperty
public void WithinRangeEventEnabled(boolean enabled) {
boolean handlerWasNeeded = isHandlerNeeded();
withinRangeEventEnabled = enabled;
boolean handlerIsNeeded = isHandlerNeeded();
if (handlerWasNeeded && !handlerIsNeeded) {
handler.removeCallbacks(sensorReader);
}
if (!handlerWasNeeded && handlerIsNeeded) {
previousState = State.UNKNOWN;
handler.post(sensorReader);
}
}
@SimpleEvent(description = "Sound level has gone within the range.")
public void WithinRange() {
EventDispatcher.dispatchEvent(this, "WithinRange");
}
/**
* Returns whether the AboveRange event should fire when the sound level
* goes above the TopOfRange.
*/
@SimpleProperty(description = "Whether the AboveRange event should fire when the sound level" +
" goes above the TopOfRange.",
category = PropertyCategory.BEHAVIOR)
public boolean AboveRangeEventEnabled() {
return aboveRangeEventEnabled;
}
/**
* Specifies whether the AboveRange event should fire when the sound level
* goes above the TopOfRange.
*/
@DesignerProperty(editorType = PropertyTypeConstants.PROPERTY_TYPE_BOOLEAN, defaultValue = "False")
@SimpleProperty
public void AboveRangeEventEnabled(boolean enabled) {
boolean handlerWasNeeded = isHandlerNeeded();
aboveRangeEventEnabled = enabled;
boolean handlerIsNeeded = isHandlerNeeded();
if (handlerWasNeeded && !handlerIsNeeded) {
handler.removeCallbacks(sensorReader);
}
if (!handlerWasNeeded && handlerIsNeeded) {
previousState = State.UNKNOWN;
handler.post(sensorReader);
}
}
@SimpleEvent(description = "Sound level has gone above the range.")
public void AboveRange() {
EventDispatcher.dispatchEvent(this, "AboveRange");
}
private boolean isHandlerNeeded() {
return belowRangeEventEnabled || withinRangeEventEnabled || aboveRangeEventEnabled;
}
// Deleteable implementation
@Override
public void onDelete() {
handler.removeCallbacks(sensorReader);
super.onDelete();
}
}
| |
/*
* 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 com.alibaba.dubbo.remoting.transport;
import com.alibaba.dubbo.common.Constants;
import com.alibaba.dubbo.common.URL;
import com.alibaba.dubbo.common.Version;
import com.alibaba.dubbo.common.extension.ExtensionLoader;
import com.alibaba.dubbo.common.logger.Logger;
import com.alibaba.dubbo.common.logger.LoggerFactory;
import com.alibaba.dubbo.common.store.DataStore;
import com.alibaba.dubbo.common.utils.ExecutorUtil;
import com.alibaba.dubbo.common.utils.NamedThreadFactory;
import com.alibaba.dubbo.common.utils.NetUtils;
import com.alibaba.dubbo.remoting.Channel;
import com.alibaba.dubbo.remoting.ChannelHandler;
import com.alibaba.dubbo.remoting.Client;
import com.alibaba.dubbo.remoting.RemotingException;
import com.alibaba.dubbo.remoting.transport.dispatcher.ChannelHandlers;
import java.net.InetSocketAddress;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* AbstractClient
*/
public abstract class AbstractClient extends AbstractEndpoint implements Client {
protected static final String CLIENT_THREAD_POOL_NAME = "DubboClientHandler";
private static final Logger logger = LoggerFactory.getLogger(AbstractClient.class);
private static final AtomicInteger CLIENT_THREAD_POOL_ID = new AtomicInteger();
private static final ScheduledThreadPoolExecutor reconnectExecutorService = new ScheduledThreadPoolExecutor(2, new NamedThreadFactory("DubboClientReconnectTimer", true));
private final Lock connectLock = new ReentrantLock();
private final boolean send_reconnect;
private final AtomicInteger reconnect_count = new AtomicInteger(0);
// Reconnection error log has been called before?
private final AtomicBoolean reconnect_error_log_flag = new AtomicBoolean(false);
// reconnect warning period. Reconnect warning interval (log warning after how many times) //for test
private final int reconnect_warning_period;
private final long shutdown_timeout;
protected volatile ExecutorService executor;
private volatile ScheduledFuture<?> reconnectExecutorFuture = null;
// the last successed connected time
private long lastConnectedTime = System.currentTimeMillis();
public AbstractClient(URL url, ChannelHandler handler) throws RemotingException {
super(url, handler);
send_reconnect = url.getParameter(Constants.SEND_RECONNECT_KEY, false);
shutdown_timeout = url.getParameter(Constants.SHUTDOWN_TIMEOUT_KEY, Constants.DEFAULT_SHUTDOWN_TIMEOUT);
// The default reconnection interval is 2s, 1800 means warning interval is 1 hour.
reconnect_warning_period = url.getParameter("reconnect.waring.period", 1800);
try {
doOpen();
} catch (Throwable t) {
close();
throw new RemotingException(url.toInetSocketAddress(), null,
"Failed to start " + getClass().getSimpleName() + " " + NetUtils.getLocalAddress()
+ " connect to the server " + getRemoteAddress() + ", cause: " + t.getMessage(), t);
}
try {
// connect.
connect();
if (logger.isInfoEnabled()) {
logger.info("Start " + getClass().getSimpleName() + " " + NetUtils.getLocalAddress() + " connect to the server " + getRemoteAddress());
}
} catch (RemotingException t) {
if (url.getParameter(Constants.CHECK_KEY, true)) {
close();
throw t;
} else {
logger.warn("Failed to start " + getClass().getSimpleName() + " " + NetUtils.getLocalAddress()
+ " connect to the server " + getRemoteAddress() + " (check == false, ignore and retry later!), cause: " + t.getMessage(), t);
}
} catch (Throwable t) {
close();
throw new RemotingException(url.toInetSocketAddress(), null,
"Failed to start " + getClass().getSimpleName() + " " + NetUtils.getLocalAddress()
+ " connect to the server " + getRemoteAddress() + ", cause: " + t.getMessage(), t);
}
executor = (ExecutorService) ExtensionLoader.getExtensionLoader(DataStore.class)
.getDefaultExtension().get(Constants.CONSUMER_SIDE, Integer.toString(url.getPort()));
ExtensionLoader.getExtensionLoader(DataStore.class)
.getDefaultExtension().remove(Constants.CONSUMER_SIDE, Integer.toString(url.getPort()));
}
protected static ChannelHandler wrapChannelHandler(URL url, ChannelHandler handler) {
url = ExecutorUtil.setThreadName(url, CLIENT_THREAD_POOL_NAME);
url = url.addParameterIfAbsent(Constants.THREADPOOL_KEY, Constants.DEFAULT_CLIENT_THREADPOOL);
return ChannelHandlers.wrap(handler, url);
}
/**
* @param url
* @return 0-false
*/
private static int getReconnectParam(URL url) {
int reconnect;
String param = url.getParameter(Constants.RECONNECT_KEY);
if (param == null || param.length() == 0 || "true".equalsIgnoreCase(param)) {
reconnect = Constants.DEFAULT_RECONNECT_PERIOD;
} else if ("false".equalsIgnoreCase(param)) {
reconnect = 0;
} else {
try {
reconnect = Integer.parseInt(param);
} catch (Exception e) {
throw new IllegalArgumentException("reconnect param must be nonnegative integer or false/true. input is:" + param);
}
if (reconnect < 0) {
throw new IllegalArgumentException("reconnect param must be nonnegative integer or false/true. input is:" + param);
}
}
return reconnect;
}
/**
* init reconnect thread
*/
private synchronized void initConnectStatusCheckCommand() {
//reconnect=false to close reconnect
int reconnect = getReconnectParam(getUrl());
if (reconnect > 0 && (reconnectExecutorFuture == null || reconnectExecutorFuture.isCancelled())) {
Runnable connectStatusCheckCommand = new Runnable() {
public void run() {
try {
if (!isConnected()) {
connect();
} else {
lastConnectedTime = System.currentTimeMillis();
}
} catch (Throwable t) {
String errorMsg = "client reconnect to " + getUrl().getAddress() + " find error . url: " + getUrl();
// wait registry sync provider list
if (System.currentTimeMillis() - lastConnectedTime > shutdown_timeout) {
if (!reconnect_error_log_flag.get()) {
reconnect_error_log_flag.set(true);
logger.error(errorMsg, t);
return;
}
}
if (reconnect_count.getAndIncrement() % reconnect_warning_period == 0) {
logger.warn(errorMsg, t);
}
}
}
};
reconnectExecutorFuture = reconnectExecutorService.scheduleWithFixedDelay(connectStatusCheckCommand, reconnect, reconnect, TimeUnit.MILLISECONDS);
}
}
private synchronized void destroyConnectStatusCheckCommand() {
try {
if (reconnectExecutorFuture != null && !reconnectExecutorFuture.isDone()) {
reconnectExecutorFuture.cancel(true);
reconnectExecutorService.purge();
}
} catch (Throwable e) {
logger.warn(e.getMessage(), e);
}
}
protected ExecutorService createExecutor() {
return Executors.newCachedThreadPool(new NamedThreadFactory(CLIENT_THREAD_POOL_NAME + CLIENT_THREAD_POOL_ID.incrementAndGet() + "-" + getUrl().getAddress(), true));
}
public InetSocketAddress getConnectAddress() {
return new InetSocketAddress(NetUtils.filterLocalHost(getUrl().getHost()), getUrl().getPort());
}
public InetSocketAddress getRemoteAddress() {
Channel channel = getChannel();
if (channel == null)
return getUrl().toInetSocketAddress();
return channel.getRemoteAddress();
}
public InetSocketAddress getLocalAddress() {
Channel channel = getChannel();
if (channel == null)
return InetSocketAddress.createUnresolved(NetUtils.getLocalHost(), 0);
return channel.getLocalAddress();
}
public boolean isConnected() {
Channel channel = getChannel();
if (channel == null)
return false;
return channel.isConnected();
}
public Object getAttribute(String key) {
Channel channel = getChannel();
if (channel == null)
return null;
return channel.getAttribute(key);
}
public void setAttribute(String key, Object value) {
Channel channel = getChannel();
if (channel == null)
return;
channel.setAttribute(key, value);
}
public void removeAttribute(String key) {
Channel channel = getChannel();
if (channel == null)
return;
channel.removeAttribute(key);
}
public boolean hasAttribute(String key) {
Channel channel = getChannel();
if (channel == null)
return false;
return channel.hasAttribute(key);
}
public void send(Object message, boolean sent) throws RemotingException {
if (send_reconnect && !isConnected()) {
connect();
}
Channel channel = getChannel();
//TODO Can the value returned by getChannel() be null? need improvement.
if (channel == null || !channel.isConnected()) {
throw new RemotingException(this, "message can not send, because channel is closed . url:" + getUrl());
}
channel.send(message, sent);
}
protected void connect() throws RemotingException {
connectLock.lock();
try {
if (isConnected()) {
return;
}
initConnectStatusCheckCommand();
doConnect();
if (!isConnected()) {
throw new RemotingException(this, "Failed connect to server " + getRemoteAddress() + " from " + getClass().getSimpleName() + " "
+ NetUtils.getLocalHost() + " using dubbo version " + Version.getVersion()
+ ", cause: Connect wait timeout: " + getTimeout() + "ms.");
} else {
if (logger.isInfoEnabled()) {
logger.info("Successed connect to server " + getRemoteAddress() + " from " + getClass().getSimpleName() + " "
+ NetUtils.getLocalHost() + " using dubbo version " + Version.getVersion()
+ ", channel is " + this.getChannel());
}
}
reconnect_count.set(0);
reconnect_error_log_flag.set(false);
} catch (RemotingException e) {
throw e;
} catch (Throwable e) {
throw new RemotingException(this, "Failed connect to server " + getRemoteAddress() + " from " + getClass().getSimpleName() + " "
+ NetUtils.getLocalHost() + " using dubbo version " + Version.getVersion()
+ ", cause: " + e.getMessage(), e);
} finally {
connectLock.unlock();
}
}
public void disconnect() {
connectLock.lock();
try {
destroyConnectStatusCheckCommand();
try {
Channel channel = getChannel();
if (channel != null) {
channel.close();
}
} catch (Throwable e) {
logger.warn(e.getMessage(), e);
}
try {
doDisConnect();
} catch (Throwable e) {
logger.warn(e.getMessage(), e);
}
} finally {
connectLock.unlock();
}
}
public void reconnect() throws RemotingException {
disconnect();
connect();
}
public void close() {
try {
if (executor != null) {
ExecutorUtil.shutdownNow(executor, 100);
}
} catch (Throwable e) {
logger.warn(e.getMessage(), e);
}
try {
super.close();
} catch (Throwable e) {
logger.warn(e.getMessage(), e);
}
try {
disconnect();
} catch (Throwable e) {
logger.warn(e.getMessage(), e);
}
try {
doClose();
} catch (Throwable e) {
logger.warn(e.getMessage(), e);
}
}
public void close(int timeout) {
ExecutorUtil.gracefulShutdown(executor, timeout);
close();
}
@Override
public String toString() {
return getClass().getName() + " [" + getLocalAddress() + " -> " + getRemoteAddress() + "]";
}
/**
* Open client.
*
* @throws Throwable
*/
protected abstract void doOpen() throws Throwable;
/**
* Close client.
*
* @throws Throwable
*/
protected abstract void doClose() throws Throwable;
/**
* Connect to server.
*
* @throws Throwable
*/
protected abstract void doConnect() throws Throwable;
/**
* disConnect to server.
*
* @throws Throwable
*/
protected abstract void doDisConnect() throws Throwable;
/**
* Get the connected channel.
*
* @return channel
*/
protected abstract Channel getChannel();
}
| |
/*
* Copyright (c) 2008-2021, Hazelcast, 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.hazelcast.jet.impl.execution;
import com.hazelcast.internal.serialization.SerializationService;
import com.hazelcast.internal.serialization.impl.DefaultSerializationServiceBuilder;
import com.hazelcast.internal.util.UuidUtil;
import com.hazelcast.jet.config.ProcessingGuarantee;
import com.hazelcast.jet.core.Inbox;
import com.hazelcast.jet.core.Outbox;
import com.hazelcast.jet.core.Processor;
import com.hazelcast.jet.core.Watermark;
import com.hazelcast.jet.core.test.TestProcessorContext;
import com.hazelcast.jet.impl.operation.SnapshotPhase1Operation.SnapshotPhase1Result;
import com.hazelcast.jet.impl.util.ProgressState;
import com.hazelcast.logging.ILogger;
import com.hazelcast.test.HazelcastSerialClassRunner;
import com.hazelcast.test.annotation.ParallelJVMTest;
import com.hazelcast.test.annotation.QuickTest;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import javax.annotation.Nonnull;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Queue;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import static com.hazelcast.jet.Util.entry;
import static com.hazelcast.jet.config.ProcessingGuarantee.EXACTLY_ONCE;
import static com.hazelcast.jet.core.JetTestSupport.wm;
import static com.hazelcast.jet.core.TestUtil.DIRECT_EXECUTOR;
import static com.hazelcast.jet.impl.MasterJobContext.SNAPSHOT_RESTORE_EDGE_PRIORITY;
import static com.hazelcast.jet.impl.execution.DoneItem.DONE_ITEM;
import static com.hazelcast.jet.impl.util.ProgressState.DONE;
import static com.hazelcast.jet.impl.util.ProgressState.MADE_PROGRESS;
import static com.hazelcast.jet.impl.util.ProgressState.NO_PROGRESS;
import static java.util.Arrays.asList;
import static java.util.Collections.emptyList;
import static java.util.Collections.singletonList;
import static java.util.stream.Collectors.toList;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
@RunWith(HazelcastSerialClassRunner.class)
@Category({QuickTest.class, ParallelJVMTest.class})
public class ProcessorTaskletTest_Snapshots {
private static final int MOCK_INPUT_SIZE = 10;
private static final int CALL_COUNT_LIMIT = 10;
private List<Object> mockInput;
private List<MockInboundStream> instreams;
private List<OutboundEdgeStream> outstreams;
private SnapshottableProcessor processor;
private Processor.Context context;
private SerializationService serializationService;
private SnapshotContext snapshotContext;
private MockOutboundCollector snapshotCollector;
@Before
public void setUp() {
this.mockInput = IntStream.range(0, MOCK_INPUT_SIZE).boxed().collect(toList());
this.processor = new SnapshottableProcessor();
this.serializationService = new DefaultSerializationServiceBuilder().build();
this.context = new TestProcessorContext().setProcessingGuarantee(EXACTLY_ONCE);
this.instreams = new ArrayList<>();
this.outstreams = new ArrayList<>();
this.snapshotCollector = new MockOutboundCollector(1024);
}
@Test
public void when_isCooperative_then_true() {
assertTrue(createTasklet(ProcessingGuarantee.AT_LEAST_ONCE).isCooperative());
}
@Test
public void when_singleInbound_then_savesAllToSnapshotAndOutbound() {
// Given
List<Object> input = new ArrayList<>();
input.addAll(mockInput.subList(0, 4));
input.add(barrier0(false));
MockInboundStream instream1 = new MockInboundStream(0, input, input.size());
MockOutboundStream outstream1 = new MockOutboundStream(0);
instreams.add(instream1);
outstreams.add(outstream1);
ProcessorTasklet tasklet = createTasklet(ProcessingGuarantee.AT_LEAST_ONCE);
// When
callUntil(tasklet, NO_PROGRESS);
// Then
assertEquals(input, outstream1.getBuffer());
assertEquals(input, getSnapshotBufferValues());
}
@Test
public void when_multipleInbound_then_waitForBarrier() {
// Given
List<Object> input1 = new ArrayList<>();
input1.addAll(mockInput.subList(0, 4));
input1.add(barrier0(false));
input1.addAll(mockInput.subList(4, 8));
List<Object> input2 = new ArrayList<>();
MockInboundStream instream1 = new MockInboundStream(0, input1, 1024);
MockInboundStream instream2 = new MockInboundStream(0, input2, 1024);
MockOutboundStream outstream1 = new MockOutboundStream(0);
instreams.add(instream1);
instreams.add(instream2);
outstreams.add(outstream1);
ProcessorTasklet tasklet = createTasklet(EXACTLY_ONCE);
// When
callUntil(tasklet, NO_PROGRESS);
// Then
assertEquals(asList(0, 1, 2, 3), outstream1.getBuffer());
assertEquals(emptyList(), getSnapshotBufferValues());
// When
instream2.push(barrier0(false));
callUntil(tasklet, NO_PROGRESS);
assertEquals(asList(0, 1, 2, 3, barrier0(false), 4, 5, 6, 7), outstream1.getBuffer());
assertEquals(asList(0, 1, 2, 3, barrier0(false)), getSnapshotBufferValues());
}
@Test
public void when_snapshotTriggered_then_saveSnapshot_prepare_emitBarrier() {
// Given
MockOutboundStream outstream1 = new MockOutboundStream(0, 2);
outstreams.add(outstream1);
ProcessorTasklet tasklet = createTasklet(EXACTLY_ONCE);
processor.itemsToEmitInComplete = 4;
processor.itemsToEmitInSnapshotPrepareCommit = 1;
callUntil(tasklet, NO_PROGRESS);
assertEquals(asList(0, 1), outstream1.getBuffer());
assertEquals(emptyList(), getSnapshotBufferValues());
// When
snapshotContext.startNewSnapshotPhase1(0, "map", 0);
outstream1.flush();
callUntil(tasklet, NO_PROGRESS);
// Then
assertEquals(asList(2, "spc-0"), outstream1.getBuffer());
assertEquals(asList(0, 1, 2, barrier0(false)), getSnapshotBufferValues());
outstream1.flush();
callUntil(tasklet, NO_PROGRESS);
assertEquals(asList(barrier0(false), 3), outstream1.getBuffer());
}
@Test
public void when_exportOnly_then_commitMethodsNotCalled() {
// Given
MockOutboundStream outstream1 = new MockOutboundStream(0, 128);
outstreams.add(outstream1);
ProcessorTasklet tasklet = createTasklet(EXACTLY_ONCE);
processor.itemsToEmitInSnapshotPrepareCommit = 1;
processor.itemsToEmitInOnSnapshotComplete = 1;
processor.isStreaming = true;
// When
snapshotContext.startNewSnapshotPhase1(0, "map", SnapshotFlags.create(false, true));
callUntil(tasklet, NO_PROGRESS);
// Then
assertEquals(singletonList(barrier0(false)), outstream1.getBuffer());
snapshotContext.phase1DoneForTasklet(0, 0, 0);
outstream1.flush();
// When
snapshotContext.startNewSnapshotPhase2(0, true);
callUntil(tasklet, NO_PROGRESS);
assertEquals(emptyList(), outstream1.getBuffer());
}
@Test
public void when_snapshotRestoreInput_then_restoreMethodsCalled() {
Entry<String, String> ssEntry1 = entry("k1", "v1");
Entry<String, String> ssEntry2 = entry("k2", "v2");
List<Object> restoredSnapshot = asList(ssEntry1, ssEntry2, DONE_ITEM);
MockInboundStream instream1 = new MockInboundStream(SNAPSHOT_RESTORE_EDGE_PRIORITY, restoredSnapshot, 1024);
MockInboundStream instream2 = new MockInboundStream(0, singletonList(DONE_ITEM), 1024);
MockOutboundStream outstream1 = new MockOutboundStream(0);
instreams.add(instream1);
instreams.add(instream2);
outstreams.add(outstream1);
ProcessorTasklet tasklet = createTasklet(EXACTLY_ONCE);
processor.itemsToEmitInTryProcess = 1;
// When
callUntil(tasklet, DONE);
// Then
assertEquals(asList("finishRestore", DONE_ITEM), outstream1.getBuffer());
assertEquals(singletonList(DONE_ITEM), getSnapshotBufferValues());
assertEquals(0, processor.tryProcessCount);
}
@Test
public void test_phase2() {
MockInboundStream instream1 = new MockInboundStream(0, asList("item", barrier0(false)), 1024);
MockOutboundStream outstream1 = new MockOutboundStream(0);
instreams.add(instream1);
outstreams.add(outstream1);
ProcessorTasklet tasklet = createTasklet(EXACTLY_ONCE);
processor.itemsToEmitInOnSnapshotComplete = 1;
callUntil(tasklet, NO_PROGRESS);
assertEquals(asList("item", barrier0(false)), getSnapshotBufferValues());
assertEquals(asList("item", barrier0(false)), outstream1.getBuffer());
snapshotCollector.getBuffer().clear();
outstream1.flush();
// start phase 2
phase1StartAndDone(false);
CompletableFuture<Void> future = snapshotContext.startNewSnapshotPhase2(0, true);
callUntil(tasklet, NO_PROGRESS);
assertEquals(singletonList("osc-0"), outstream1.getBuffer());
assertEquals(emptyList(), getSnapshotBufferValues());
assertTrue("future not done", future.isDone());
}
@Test
public void when_processorCompletesAfterPhase1_then_doneAfterPhase2() {
MockInboundStream instream1 = new MockInboundStream(0, asList("item", barrier0(false), DONE_ITEM), 1024);
MockOutboundStream outstream1 = new MockOutboundStream(0);
instreams.add(instream1);
outstreams.add(outstream1);
ProcessorTasklet tasklet = createTasklet(EXACTLY_ONCE);
processor.itemsToEmitInOnSnapshotComplete = 1;
CompletableFuture<SnapshotPhase1Result> future1 = snapshotContext.startNewSnapshotPhase1(0, "map", 0);
callUntil(tasklet, NO_PROGRESS);
assertEquals(asList("item", barrier0(false)), getSnapshotBufferValues());
assertEquals(asList("item", barrier0(false)), outstream1.getBuffer());
snapshotContext.phase1DoneForTasklet(1, 1, 1);
assertTrue("future1 not done", future1.isDone());
snapshotCollector.getBuffer().clear();
outstream1.flush();
// we push an item after DONE_ITEM. This does not happen in reality, but we use it
// to test that the processor ignores it
instream1.push("item2");
callUntil(tasklet, NO_PROGRESS);
assertEquals(emptyList(), outstream1.getBuffer());
// start phase 2
CompletableFuture<Void> future2 = snapshotContext.startNewSnapshotPhase2(0, true);
callUntil(tasklet, DONE);
assertEquals(asList("osc-0", DONE_ITEM), outstream1.getBuffer());
assertEquals(singletonList(DONE_ITEM), getSnapshotBufferValues());
assertTrue("future2 not done", future2.isDone());
}
@Test
public void when_onSnapshotCompletedReturnsFalse_then_calledAgain() {
MockInboundStream instream1 = new MockInboundStream(0, singletonList(barrier0(false)), 1024);
MockOutboundStream outstream1 = new MockOutboundStream(0, 1);
instreams.add(instream1);
outstreams.add(outstream1);
ProcessorTasklet tasklet = createTasklet(EXACTLY_ONCE);
processor.itemsToEmitInOnSnapshotComplete = 2;
callUntil(tasklet, NO_PROGRESS);
assertEquals(singletonList(barrier0(false)), getSnapshotBufferValues());
assertEquals(singletonList(barrier0(false)), outstream1.getBuffer());
snapshotCollector.getBuffer().clear();
outstream1.flush();
// start phase 2
phase1StartAndDone(false);
snapshotContext.startNewSnapshotPhase2(0, true);
callUntil(tasklet, NO_PROGRESS);
assertEquals(singletonList("osc-0"), outstream1.getBuffer());
outstream1.flush();
callUntil(tasklet, NO_PROGRESS);
assertEquals(singletonList("osc-1"), outstream1.getBuffer());
}
@Test
public void test_tryProcessWatermark_notInterruptedByPhase2() {
MockInboundStream instream1 = new MockInboundStream(0, singletonList(wm(0)), 1024);
MockOutboundStream outstream1 = new MockOutboundStream(0, 1);
instreams.add(instream1);
outstreams.add(outstream1);
ProcessorTasklet tasklet = createTasklet(EXACTLY_ONCE);
processor.itemsToEmitInTryProcessWatermark = 1;
callUntil(tasklet, NO_PROGRESS);
phase1StartAndDone(false);
CompletableFuture<Void> future = snapshotContext.startNewSnapshotPhase2(0, true);
callUntil(tasklet, NO_PROGRESS);
assertFalse("future should not have been done", future.isDone());
outstream1.flush();
callUntil(tasklet, NO_PROGRESS);
assertTrue("future should have been done", future.isDone());
}
@Test
public void test_nullaryTryProcess_notInterruptedByPhase2() {
MockInboundStream instream1 = new MockInboundStream(0, emptyList(), 1024);
MockOutboundStream outstream1 = new MockOutboundStream(0, 1);
instreams.add(instream1);
outstreams.add(outstream1);
ProcessorTasklet tasklet = createTasklet(EXACTLY_ONCE);
processor.itemsToEmitInTryProcess = 2;
callUntil(tasklet, NO_PROGRESS);
phase1StartAndDone(false);
CompletableFuture<Void> future = snapshotContext.startNewSnapshotPhase2(0, true);
callUntil(tasklet, NO_PROGRESS);
assertFalse("future should not have been done", future.isDone());
outstream1.flush();
callUntil(tasklet, NO_PROGRESS);
assertTrue("future should have been done", future.isDone());
}
@Test
public void test_terminalSnapshot_receivedInBarrier() {
MockInboundStream instream1 = new MockInboundStream(0, singletonList(barrier0(true)), 1024);
MockOutboundStream outstream1 = new MockOutboundStream(0, 128);
instreams.add(instream1);
outstreams.add(outstream1);
ProcessorTasklet tasklet = createTasklet(EXACTLY_ONCE);
callUntil(tasklet, NO_PROGRESS);
phase1StartAndDone(false);
CompletableFuture<Void> future = snapshotContext.startNewSnapshotPhase2(0, true);
callUntil(tasklet, DONE);
assertTrue("future should have been done", future.isDone());
assertEquals(outstream1.getBuffer(), asList(barrier0(true), DONE_ITEM));
}
@Test
public void test_terminalSnapshot_source() {
MockOutboundStream outstream1 = new MockOutboundStream(0, 128);
outstreams.add(outstream1);
processor.isStreaming = true;
ProcessorTasklet tasklet = createTasklet(EXACTLY_ONCE);
phase1StartAndDone(true);
callUntil(tasklet, NO_PROGRESS);
CompletableFuture<Void> future = snapshotContext.startNewSnapshotPhase2(0, true);
callUntil(tasklet, DONE);
assertTrue("future should have been done", future.isDone());
assertEquals(outstream1.getBuffer(), asList(barrier0(true), DONE_ITEM));
}
private ProcessorTasklet createTasklet(ProcessingGuarantee guarantee) {
for (int i = 0; i < instreams.size(); i++) {
instreams.get(i).setOrdinal(i);
}
snapshotContext = new SnapshotContext(mock(ILogger.class), "test job", -1, guarantee);
snapshotContext.initTaskletCount(1, 1, 0);
final ProcessorTasklet t = new ProcessorTasklet(context, DIRECT_EXECUTOR, serializationService,
processor, instreams, outstreams, snapshotContext, snapshotCollector, false);
t.init();
return t;
}
private List<Object> getSnapshotBufferValues() {
return snapshotCollector.getBuffer().stream()
.map(e -> (e instanceof Map.Entry) ? deserializeEntryValue((Map.Entry) e) : e)
.collect(Collectors.toList());
}
private Object deserializeEntryValue(Entry e) {
return serializationService.toObject(e.getValue());
}
private static void callUntil(ProcessorTasklet tasklet, ProgressState expectedState) {
int iterCount = 0;
for (ProgressState r; (r = tasklet.call()) != expectedState; ) {
assertEquals("Failed to make progress after " + iterCount + " iterations", MADE_PROGRESS, r);
assertTrue(String.format(
"tasklet.call() invoked %d times without reaching %s. Last state was %s",
CALL_COUNT_LIMIT, expectedState, r),
++iterCount < CALL_COUNT_LIMIT);
}
}
private SnapshotBarrier barrier0(boolean isTerminal) {
return new SnapshotBarrier(0, isTerminal);
}
private void phase1StartAndDone(boolean isTerminal) {
snapshotContext.startNewSnapshotPhase1(0, "map", SnapshotFlags.create(isTerminal, false));
snapshotContext.phase1DoneForTasklet(0, 0, 0);
}
private static class SnapshottableProcessor implements Processor {
int itemsToEmitInTryProcess;
int itemsToEmitInTryProcessWatermark;
int itemsToEmitInComplete;
int itemsToEmitInCompleteEdge;
int itemsToEmitInSnapshotPrepareCommit;
int itemsToEmitInOnSnapshotComplete;
int tryProcessCount;
int tryProcessWatermarkCount;
int completedCount;
int completedEdgeCount;
int snapshotPrepareCommitCount;
int onSnapshotCompletedCount;
boolean isStreaming;
private Outbox outbox;
private final Queue<Map.Entry> snapshotQueue = new ArrayDeque<>();
@Override
public void init(@Nonnull Outbox outbox, @Nonnull Context context) {
this.outbox = outbox;
}
@Override
public void process(int ordinal, @Nonnull Inbox inbox) {
for (Object item; (item = inbox.peek()) != null; ) {
if (!outbox.offer(item)) {
return;
} else {
snapshotQueue.offer(entry(UuidUtil.newUnsecureUUID(), inbox.poll()));
}
}
}
@Override
public boolean tryProcessWatermark(@Nonnull Watermark watermark) {
if (tryProcessWatermarkCount < itemsToEmitInTryProcessWatermark
&& outbox.offer("tryProcessWatermark-" + tryProcessWatermarkCount)) {
tryProcessWatermarkCount++;
}
return tryProcessWatermarkCount == itemsToEmitInTryProcessWatermark && outbox.offer(watermark);
}
@Override
public boolean complete() {
if (completedCount < itemsToEmitInComplete && outbox.offer(completedCount)) {
snapshotQueue.add(entry(UuidUtil.newUnsecureUUID(), completedCount));
completedCount++;
}
return completedCount == itemsToEmitInComplete && !isStreaming;
}
@Override
public boolean completeEdge(int ordinal) {
if (completedEdgeCount < itemsToEmitInCompleteEdge && outbox.offer("completeEdge-" + completedEdgeCount)) {
completedEdgeCount++;
}
return completedEdgeCount == itemsToEmitInCompleteEdge;
}
@Override
public boolean tryProcess() {
if (tryProcessCount < itemsToEmitInTryProcess && outbox.offer("tryProcess-" + tryProcessCount)) {
tryProcessCount++;
}
return tryProcessCount == itemsToEmitInTryProcess;
}
@Override
public boolean saveToSnapshot() {
for (Map.Entry item; (item = snapshotQueue.peek()) != null; ) {
if (!outbox.offerToSnapshot(item.getKey(), item.getValue())) {
return false;
} else {
snapshotQueue.remove();
}
}
return true;
}
@Override
public boolean snapshotCommitPrepare() {
if (snapshotPrepareCommitCount < itemsToEmitInSnapshotPrepareCommit
&& outbox.offer("spc-" + snapshotPrepareCommitCount)) {
snapshotPrepareCommitCount++;
}
return snapshotPrepareCommitCount == itemsToEmitInSnapshotPrepareCommit;
}
@Override
public boolean snapshotCommitFinish(boolean success) {
if (onSnapshotCompletedCount < itemsToEmitInOnSnapshotComplete
&& outbox.offer("osc-" + onSnapshotCompletedCount)) {
onSnapshotCompletedCount++;
}
return onSnapshotCompletedCount == itemsToEmitInOnSnapshotComplete;
}
@Override
public void restoreFromSnapshot(@Nonnull Inbox inbox) {
for (Object o; (o = inbox.poll()) != null; ) {
snapshotQueue.add((Entry) o);
}
}
@Override
public boolean finishSnapshotRestore() {
return outbox.offer("finishRestore");
}
}
}
| |
package com.wesabe.api.accounts.analytics.tests;
import static com.wesabe.api.tests.util.InjectionHelper.*;
import static com.wesabe.api.tests.util.CurrencyHelper.*;
import static com.wesabe.api.tests.util.DateHelper.*;
import static com.wesabe.api.tests.util.NumberHelper.*;
import static org.junit.Assert.*;
import java.util.List;
import org.joda.time.DateTime;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.runners.Enclosed;
import org.junit.runner.RunWith;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.wesabe.api.accounts.analytics.TxactionListBuilder;
import com.wesabe.api.accounts.entities.Account;
import com.wesabe.api.accounts.entities.AccountBalance;
import com.wesabe.api.accounts.entities.AccountList;
import com.wesabe.api.accounts.entities.AccountType;
import com.wesabe.api.accounts.entities.Merchant;
import com.wesabe.api.accounts.entities.Tag;
import com.wesabe.api.accounts.entities.TaggedAmount;
import com.wesabe.api.accounts.entities.Txaction;
import com.wesabe.api.accounts.entities.TxactionList;
import com.wesabe.api.accounts.entities.TxactionStatus;
import com.wesabe.api.util.money.CurrencyExchangeRateMap;
@RunWith(Enclosed.class)
public class TxactionListBuilderTest {
public static class A_Builder_Without_Any_Explicit_Filters {
private List<Txaction> txactions;
private Account checking = Account.ofType(AccountType.CHECKING);
private Txaction wholeFoods = new Txaction(checking, decimal("-48.19"), apr1st);
private Txaction starbucks = new Txaction(checking, decimal("-3.00"), jun15th);
private Txaction deleted = new Txaction(checking, decimal("-20.00"), jun14th);
private Txaction disabled = new Txaction(checking, decimal("500.00"), jun16th);
private CurrencyExchangeRateMap exchangeRates = new CurrencyExchangeRateMap();
@Before
public void setup() throws Exception {
checking.setCurrency(USD);
inject(Account.class, checking, "accountBalances", Sets.newHashSet(new AccountBalance(checking, decimal("100.00"), new DateTime())));
starbucks.setStatus(TxactionStatus.ACTIVE);
wholeFoods.setStatus(TxactionStatus.ACTIVE);
deleted.setStatus(TxactionStatus.DELETED);
disabled.setStatus(TxactionStatus.DISABLED);
txactions = ImmutableList.of(starbucks, disabled, wholeFoods, deleted);
}
@Test
public void itFiltersDeletedAndDisabledTransactions() throws Exception {
assertEquals(Lists.newArrayList(starbucks, wholeFoods), new TxactionListBuilder()
.setCurrency(USD)
.setCurrencyExchangeRateMap(exchangeRates)
.setAccounts(new AccountList(checking))
.build(txactions)
.getTxactions());
}
@Test
public void itDoesNotIncludeTheDeletedOrDisabledTransactionsInTheTotalCount() throws Exception {
final TxactionList list = new TxactionListBuilder()
.setCurrency(USD)
.setCurrencyExchangeRateMap(exchangeRates)
.setAccounts(new AccountList(checking))
.build(txactions);
assertEquals(2, list.getTotalCount());
}
}
public static class A_Builder_With_Accounts {
private List<Txaction> txactions;
private List<Txaction> checkingTxactions;
private Account checking = Account.ofType(AccountType.CHECKING);
private Account savings = Account.ofType(AccountType.SAVINGS);
private Txaction wholeFoods = new Txaction(checking, decimal("-48.19"), jun14th);
private Txaction starbucks = new Txaction(checking, decimal("-3.00"), jun15th);
private Txaction interestEarned = new Txaction(savings, decimal("23.01"), new DateTime());
private CurrencyExchangeRateMap exchangeRates = new CurrencyExchangeRateMap();
@Before
public void setup() throws Exception {
checking.setCurrency(USD);
savings.setCurrency(USD);
inject(Account.class, checking, "accountBalances", Sets.newHashSet(new AccountBalance(checking, decimal("100.00"), new DateTime())));
inject(Account.class, savings, "accountBalances", Sets.newHashSet(new AccountBalance(savings, decimal("100.00"), new DateTime())));
starbucks.setStatus(TxactionStatus.ACTIVE);
wholeFoods.setStatus(TxactionStatus.ACTIVE);
interestEarned.setStatus(TxactionStatus.ACTIVE);
txactions = ImmutableList.of(starbucks, interestEarned, wholeFoods);
checkingTxactions = Lists.newArrayList(starbucks, wholeFoods);
}
@Test
public void itReturnsTxactionsContainedByTheGivenAccounts() {
assertEquals(checkingTxactions, new TxactionListBuilder()
.setAccounts(new AccountList(checking))
.setCurrency(USD)
.setCurrencyExchangeRateMap(exchangeRates)
.build(txactions)
.getTxactions());
}
@Test
public void itDoesNotIncludeOtherAccountsInTheTotalCount() throws Exception {
final TxactionList list = new TxactionListBuilder()
.setAccounts(new AccountList(checking))
.setCurrency(USD)
.setCurrencyExchangeRateMap(exchangeRates)
.build(txactions);
assertEquals(2, list.getTotalCount());
}
}
public static class A_Builder_With_Tags {
private List<Txaction> txactions;
private List<Txaction> foodTxactions;
private Account checking = Account.ofType(AccountType.CHECKING);
private Account savings = Account.ofType(AccountType.SAVINGS);
private Txaction wholeFoods = new Txaction(checking, decimal("-48.19"), jun14th);
private Txaction starbucks = new Txaction(checking, decimal("-3.00"), jun15th);
private Txaction interestEarned = new Txaction(savings, decimal("23.01"), new DateTime());
private Tag food = new Tag("food");
private CurrencyExchangeRateMap exchangeRates = new CurrencyExchangeRateMap();
@Before
public void setup() throws Exception {
checking.setCurrency(USD);
savings.setCurrency(USD);
inject(Account.class, checking, "accountBalances", Sets.newHashSet(new AccountBalance(checking, decimal("100.00"), new DateTime())));
inject(Account.class, savings, "accountBalances", Sets.newHashSet(new AccountBalance(savings, decimal("100.00"), new DateTime())));
starbucks.setStatus(TxactionStatus.ACTIVE);
wholeFoods.setStatus(TxactionStatus.ACTIVE);
interestEarned.setStatus(TxactionStatus.ACTIVE);
txactions = ImmutableList.of(starbucks, interestEarned, wholeFoods);
starbucks.addTag(new Tag("food"));
wholeFoods.addTag(new Tag("food"));
foodTxactions = Lists.newArrayList(starbucks, wholeFoods);
}
@Test
public void itReturnsTxactionsContainedByTheGivenAccounts() {
assertEquals(foodTxactions, new TxactionListBuilder()
.setTags(ImmutableSet.of(food))
.setAccounts(new AccountList(checking, savings))
.setCurrency(USD)
.setCurrencyExchangeRateMap(exchangeRates)
.build(txactions)
.getTxactions());
}
@Test
public void itDoesNotIncludeOtherTagsInTheTotalCount() throws Exception {
final TxactionList list = new TxactionListBuilder()
.setTags(ImmutableSet.of(food))
.setAccounts(new AccountList(checking, savings))
.setCurrency(USD)
.setCurrencyExchangeRateMap(exchangeRates)
.build(txactions);
assertEquals(2, list.getTotalCount());
}
@Test
public void itDoesNotCalculateARunningTotalBalance() throws Exception {
assertNull(new TxactionListBuilder()
.setTags(ImmutableSet.of(food))
.setAccounts(new AccountList(checking, savings))
.setCurrency(USD)
.setCurrencyExchangeRateMap(exchangeRates)
.build(txactions)
.get(0).getBalance());
}
}
public static class A_Builder_Without_Balances {
private List<Txaction> txactions;
private Account checking = Account.ofType(AccountType.CHECKING);
private Account savings = Account.ofType(AccountType.SAVINGS);
private Txaction wholeFoods = new Txaction(checking, decimal("-48.19"), jun14th);
private Txaction starbucks = new Txaction(checking, decimal("-3.00"), jun15th);
private Txaction interestEarned = new Txaction(savings, decimal("23.01"), new DateTime());
private CurrencyExchangeRateMap exchangeRates = new CurrencyExchangeRateMap();
@Before
public void setup() throws Exception {
checking.setCurrency(USD);
savings.setCurrency(USD);
inject(Account.class, checking, "accountBalances", Sets.newHashSet(new AccountBalance(checking, decimal("100.00"), new DateTime())));
inject(Account.class, savings, "accountBalances", Sets.newHashSet(new AccountBalance(savings, decimal("100.00"), new DateTime())));
starbucks.setStatus(TxactionStatus.ACTIVE);
wholeFoods.setStatus(TxactionStatus.ACTIVE);
interestEarned.setStatus(TxactionStatus.ACTIVE);
txactions = ImmutableList.of(starbucks, interestEarned, wholeFoods);
}
@Test
public void itDoesNotCalculateARunningTotalBalance() throws Exception {
assertNull(new TxactionListBuilder()
.setCalculateBalances(false)
.setAccounts(new AccountList(checking, savings))
.setCurrency(USD)
.setCurrencyExchangeRateMap(exchangeRates)
.build(txactions)
.get(0).getBalance());
}
}
public static class A_Builder_With_Merchant_Names {
private List<Txaction> txactions;
private List<Txaction> expectedTxactions;
private Account checking = Account.ofType(AccountType.CHECKING);
private Account savings = Account.ofType(AccountType.SAVINGS);
private Txaction wholeFoods = new Txaction(checking, decimal("-48.19"), jun14th);
private Txaction starbucks = new Txaction(checking, decimal("-3.00"), jun15th);
private Txaction interestEarned = new Txaction(savings, decimal("23.01"), new DateTime());
private Merchant wholeFoodsMerchant, starbucksMerchant;
private CurrencyExchangeRateMap exchangeRates = new CurrencyExchangeRateMap();
@Before
public void setup() throws Exception {
checking.setCurrency(USD);
savings.setCurrency(USD);
inject(Account.class, checking, "accountBalances", Sets.newHashSet(new AccountBalance(checking, decimal("100.00"), new DateTime())));
inject(Account.class, savings, "accountBalances", Sets.newHashSet(new AccountBalance(savings, decimal("100.00"), new DateTime())));
this.starbucksMerchant = new Merchant("Starbucks");
this.wholeFoodsMerchant = new Merchant("Whole Foods");
starbucks.setStatus(TxactionStatus.ACTIVE);
starbucks.setMerchant(starbucksMerchant);
wholeFoods.setStatus(TxactionStatus.ACTIVE);
wholeFoods.setMerchant(wholeFoodsMerchant);
interestEarned.setStatus(TxactionStatus.ACTIVE);
txactions = ImmutableList.of(starbucks, interestEarned, wholeFoods);
expectedTxactions = Lists.newArrayList(wholeFoods);
}
@Test
public void itReturnsTxactionsForTheGivenMerchants() {
assertEquals(expectedTxactions, new TxactionListBuilder()
.setAccounts(new AccountList(checking, savings))
.setMerchantNames(ImmutableSet.of("Whole Foods"))
.setCurrency(USD)
.setCurrencyExchangeRateMap(exchangeRates)
.build(txactions)
.getTxactions());
}
@Test
public void itDoesNotIncludeOtherMerchantsInTheTotalCount() throws Exception {
final TxactionList list = new TxactionListBuilder()
.setAccounts(new AccountList(checking, savings))
.setMerchantNames(ImmutableSet.of("Whole Foods"))
.setCurrency(USD)
.setCurrencyExchangeRateMap(exchangeRates)
.build(txactions);
assertEquals(1, list.getTotalCount());
}
@Test
public void itDoesNotCalculateARunningTotalBalance() throws Exception {
assertNull(new TxactionListBuilder()
.setMerchantNames(ImmutableSet.of("Whole Foods"))
.setAccounts(new AccountList(checking, savings))
.setCurrency(USD)
.setCurrencyExchangeRateMap(exchangeRates)
.build(txactions)
.get(0).getBalance());
}
}
public static class A_Builder_With_Unedited_Txactions {
private List<Txaction> txactions;
private List<Txaction> expectedTxactions;
private Account checking = Account.ofType(AccountType.CHECKING);
private Account savings = Account.ofType(AccountType.SAVINGS);
private Txaction taggedWholeFoods = new Txaction(checking, decimal("-48.19"), jun14th);
private Txaction untaggedStarbucks = new Txaction(checking, decimal("-3.00"), jun15th);
private Txaction interestEarned = new Txaction(savings, decimal("23.01"), new DateTime());
private Txaction transferToSavings = new Txaction(checking, decimal("1000"), new DateTime());
private Txaction transferFromChecking = new Txaction(savings, decimal("1000"), new DateTime());
private Merchant wholeFoodsMerchant, starbucksMerchant, transferMerchant;
private CurrencyExchangeRateMap exchangeRates = new CurrencyExchangeRateMap();
@Before
public void setup() throws Exception {
checking.setCurrency(USD);
savings.setCurrency(USD);
inject(Account.class, checking, "accountBalances", Sets.newHashSet(new AccountBalance(checking, decimal("100.00"), new DateTime())));
inject(Account.class, savings, "accountBalances", Sets.newHashSet(new AccountBalance(savings, decimal("100.00"), new DateTime())));
this.starbucksMerchant = new Merchant("Starbucks");
this.wholeFoodsMerchant = new Merchant("Whole Foods");
this.transferMerchant = new Merchant("Transfer");
untaggedStarbucks.setStatus(TxactionStatus.ACTIVE);
untaggedStarbucks.setTagged(false);
untaggedStarbucks.setMerchant(starbucksMerchant);
taggedWholeFoods.setStatus(TxactionStatus.ACTIVE);
taggedWholeFoods.setTagged(true);
taggedWholeFoods.setMerchant(wholeFoodsMerchant);
interestEarned.setStatus(TxactionStatus.ACTIVE);
interestEarned.setTagged(false);
transferToSavings.setMerchant(transferMerchant);
transferToSavings.setTransferTxaction(transferFromChecking);
transferFromChecking.setTransferTxaction(transferToSavings);
txactions = ImmutableList.of(untaggedStarbucks, interestEarned, taggedWholeFoods, transferToSavings, transferFromChecking);
}
@Test
public void itIncludesAllTxactionsIfUneditedIsFalse() {
final TxactionList list = new TxactionListBuilder()
.setAccounts(new AccountList(checking, savings))
.setUnedited(false)
.setCurrency(USD)
.setCurrencyExchangeRateMap(exchangeRates)
.build(txactions);
assertEquals(5, list.getTotalCount());
}
@Test
public void itIncludesNonTransferTxactionsWithNoMerchantOrNoTagsIfUneditedIsTrue() {
expectedTxactions = Lists.newArrayList(transferFromChecking, interestEarned, untaggedStarbucks);
final TxactionList list = new TxactionListBuilder()
.setAccounts(new AccountList(checking, savings))
.setUnedited(true)
.setCurrency(USD)
.setCurrencyExchangeRateMap(exchangeRates)
.build(txactions);
assertEquals(expectedTxactions, list.getTxactions());
}
}
public static class A_Builder_With_An_Offset {
private List<Txaction> txactions;
private Account checking = Account.ofType(AccountType.CHECKING);
private Account savings = Account.ofType(AccountType.SAVINGS);
private Txaction wholeFoods = new Txaction(checking, decimal("-48.19"), jun14th);
private Txaction starbucks = new Txaction(checking, decimal("-3.00"), jun15th);
private Txaction interestEarned = new Txaction(savings, decimal("23.01"), new DateTime());
private CurrencyExchangeRateMap exchangeRates = new CurrencyExchangeRateMap();
@Before
public void setup() throws Exception {
checking.setCurrency(USD);
savings.setCurrency(USD);
inject(Account.class, checking, "accountBalances", Sets.newHashSet(new AccountBalance(checking, decimal("100.00"), new DateTime())));
inject(Account.class, savings, "accountBalances", Sets.newHashSet(new AccountBalance(savings, decimal("100.00"), new DateTime())));
starbucks.setStatus(TxactionStatus.ACTIVE);
wholeFoods.setStatus(TxactionStatus.ACTIVE);
interestEarned.setStatus(TxactionStatus.ACTIVE);
txactions = ImmutableList.of(interestEarned, starbucks, wholeFoods);
}
@Test
public void itReturnsTxactionsExcludingTheOffsetOnes() {
assertEquals(Lists.newArrayList(starbucks, wholeFoods), new TxactionListBuilder()
.setOffset(1)
.setAccounts(new AccountList(checking, savings))
.setCurrency(USD)
.setCurrencyExchangeRateMap(exchangeRates)
.build(txactions)
.getTxactions());
}
@Test
public void itIncludesTheOffsetTransactionsInTheTotalCount() throws Exception {
final TxactionList list = new TxactionListBuilder()
.setOffset(1)
.setAccounts(new AccountList(checking, savings))
.setCurrency(USD)
.setCurrencyExchangeRateMap(exchangeRates)
.build(txactions);
assertEquals(3, list.getTotalCount());
}
}
public static class A_Builder_With_A_Limit {
private List<Txaction> txactions;
private Account checking = Account.ofType(AccountType.CHECKING);
private Account savings = Account.ofType(AccountType.SAVINGS);
private Txaction wholeFoods = new Txaction(checking, decimal("-48.19"), jun14th);
private Txaction starbucks = new Txaction(checking, decimal("-3.00"), jun15th);
private Txaction interestEarned = new Txaction(savings, decimal("23.01"), new DateTime());
private CurrencyExchangeRateMap exchangeRates = new CurrencyExchangeRateMap();
@Before
public void setup() throws Exception {
checking.setCurrency(USD);
savings.setCurrency(USD);
inject(Account.class, checking, "accountBalances", Sets.newHashSet(new AccountBalance(checking, decimal("100.00"), new DateTime())));
inject(Account.class, savings, "accountBalances", Sets.newHashSet(new AccountBalance(savings, decimal("100.00"), new DateTime())));
starbucks.setStatus(TxactionStatus.ACTIVE);
wholeFoods.setStatus(TxactionStatus.ACTIVE);
interestEarned.setStatus(TxactionStatus.ACTIVE);
txactions = ImmutableList.of(interestEarned, starbucks, wholeFoods);
}
@Test
public void itReturnsTxactionsExcludingTheOffsetOnes() {
assertEquals(Lists.newArrayList(interestEarned, starbucks), new TxactionListBuilder()
.setLimit(2)
.setAccounts(new AccountList(checking, savings))
.setCurrency(USD)
.setCurrencyExchangeRateMap(exchangeRates)
.build(txactions)
.getTxactions());
}
@Test
public void itIncludesTheLimitedTransactionsInTheTotalCount() throws Exception {
final TxactionList list = new TxactionListBuilder()
.setOffset(1)
.setAccounts(new AccountList(checking, savings))
.setCurrency(USD)
.setCurrencyExchangeRateMap(exchangeRates)
.build(txactions);
assertEquals(3, list.getTotalCount());
}
}
public static class A_Builder_With_An_Amount {
private List<Txaction> txactions;
private Account checking = Account.ofType(AccountType.CHECKING);
private Account savings = Account.ofType(AccountType.SAVINGS);
private Txaction wholeFoods = new Txaction(checking, decimal("-48.19"), jun14th);
private Txaction starbucks = new Txaction(checking, decimal("-3.00"), jun15th);
private Txaction interestEarned = new Txaction(savings, decimal("23.01"), new DateTime());
private CurrencyExchangeRateMap exchangeRates = new CurrencyExchangeRateMap();
@Before
public void setup() throws Exception {
checking.setCurrency(USD);
savings.setCurrency(USD);
inject(Account.class, checking, "accountBalances", Sets.newHashSet(new AccountBalance(checking, decimal("100.00"), new DateTime())));
inject(Account.class, savings, "accountBalances", Sets.newHashSet(new AccountBalance(savings, decimal("100.00"), new DateTime())));
starbucks.setStatus(TxactionStatus.ACTIVE);
wholeFoods.setStatus(TxactionStatus.ACTIVE);
interestEarned.setStatus(TxactionStatus.ACTIVE);
txactions = ImmutableList.of(interestEarned, starbucks, wholeFoods);
}
@Test
public void itReturnsTxactionsWithTheCorrectAmount() {
final TxactionList list = new TxactionListBuilder()
.setAmount(decimal("-3.00"))
.setCurrency(USD)
.setCurrencyExchangeRateMap(exchangeRates)
.build(txactions);
assertEquals(ImmutableList.of(starbucks), list.getTxactions());
}
}
public static class A_Builder_With_A_Query {
private List<Txaction> txactions;
private Account checking = Account.ofType(AccountType.CHECKING);
private Account savings = Account.ofType(AccountType.SAVINGS);
private Txaction wholeFoods = new Txaction(checking, decimal("-48.19"), jun14th);
private Txaction starbucks = new Txaction(checking, decimal("-3.00"), jun15th);
private Txaction interestEarned = new Txaction(savings, decimal("23.01"), new DateTime());
private CurrencyExchangeRateMap exchangeRates = new CurrencyExchangeRateMap();
@Before
public void setup() throws Exception {
checking.setCurrency(USD);
savings.setCurrency(USD);
inject(Account.class, checking, "accountBalances", Sets.newHashSet(new AccountBalance(checking, decimal("100.00"), new DateTime())));
inject(Account.class, savings, "accountBalances", Sets.newHashSet(new AccountBalance(savings, decimal("100.00"), new DateTime())));
starbucks.setStatus(TxactionStatus.ACTIVE);
wholeFoods.setStatus(TxactionStatus.ACTIVE);
interestEarned.setStatus(TxactionStatus.ACTIVE);
txactions = ImmutableList.of(interestEarned, starbucks, wholeFoods);
}
private TxactionList buildTxactionList(String query) {
final TxactionList list = new TxactionListBuilder()
.setQuery(query)
.setCurrency(USD)
.setCurrencyExchangeRateMap(exchangeRates)
.build(txactions);
return list;
}
@Test
public void itReturnsTxactionsWithFilteredNamesContainingTheQuery() throws Exception {
inject(Txaction.class, starbucks, "filteredName", "Starbucks San Francis");
final TxactionList list = buildTxactionList("Starbucks");
assertEquals(ImmutableList.of(starbucks), list.getTxactions());
}
@Test
public void itReturnsTxactionsWithMerchantNamesContainingTheQuery() throws Exception {
starbucks.setMerchant(new Merchant("Starbucks"));
final TxactionList list = buildTxactionList("Starbucks");
assertEquals(ImmutableList.of(starbucks), list.getTxactions());
}
@Test
public void itReturnsTxactionsWithTagNamesContainingTheQuery() throws Exception {
inject(Txaction.class, starbucks, "taggedAmounts", ImmutableList.of(new TaggedAmount(starbucks, new Tag("snack"), null)));
final TxactionList list = buildTxactionList("Snack");
assertEquals(ImmutableList.of(starbucks), list.getTxactions());
}
@Test
public void itReturnsTxactionsWithNotesContainingTheQuery() throws Exception {
inject(Txaction.class, starbucks, "note", "MUFFINS OH JOY");
final TxactionList list = buildTxactionList("muffins");
assertEquals(ImmutableList.of(starbucks), list.getTxactions());
}
}
}
| |
/* ====================================================================
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.poi.ss.extractor;
import static org.apache.poi.util.StringUtil.endsWithIgnoreCase;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import org.apache.poi.hpsf.ClassID;
import org.apache.poi.poifs.filesystem.DirectoryNode;
import org.apache.poi.poifs.filesystem.DocumentInputStream;
import org.apache.poi.poifs.filesystem.Entry;
import org.apache.poi.poifs.filesystem.Ole10Native;
import org.apache.poi.poifs.filesystem.Ole10NativeException;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Drawing;
import org.apache.poi.ss.usermodel.ObjectData;
import org.apache.poi.ss.usermodel.Picture;
import org.apache.poi.ss.usermodel.PictureData;
import org.apache.poi.ss.usermodel.Shape;
import org.apache.poi.ss.usermodel.ShapeContainer;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.util.Beta;
import org.apache.poi.util.IOUtils;
import org.apache.poi.util.LocaleUtil;
import org.apache.poi.util.POILogFactory;
import org.apache.poi.util.POILogger;
import org.apache.poi.xssf.usermodel.XSSFObjectData;
/**
* This extractor class tries to identify various embedded documents within Excel files
* and provide them via a common interface, i.e. the EmbeddedData instances
*/
@Beta
public class EmbeddedExtractor implements Iterable<EmbeddedExtractor> {
private static final POILogger LOG = POILogFactory.getLogger(EmbeddedExtractor.class);
// contentType
private static final String CONTENT_TYPE_BYTES = "binary/octet-stream";
private static final String CONTENT_TYPE_PDF = "application/pdf";
private static final String CONTENT_TYPE_DOC = "application/msword";
private static final String CONTENT_TYPE_XLS = "application/vnd.ms-excel";
/**
* @return the list of known extractors, if you provide custom extractors, override this method
*/
@Override
public Iterator<EmbeddedExtractor> iterator() {
EmbeddedExtractor[] ee = {
new Ole10Extractor(), new PdfExtractor(), new BiffExtractor(), new OOXMLExtractor(), new FsExtractor()
};
return Arrays.asList(ee).iterator();
}
public EmbeddedData extractOne(DirectoryNode src) throws IOException {
for (EmbeddedExtractor ee : this) {
if (ee.canExtract(src)) {
return ee.extract(src);
}
}
return null;
}
public EmbeddedData extractOne(Picture src) throws IOException {
for (EmbeddedExtractor ee : this) {
if (ee.canExtract(src)) {
return ee.extract(src);
}
}
return null;
}
public List<EmbeddedData> extractAll(Sheet sheet) throws IOException {
Drawing<?> patriarch = sheet.getDrawingPatriarch();
if (null == patriarch){
return Collections.emptyList();
}
List<EmbeddedData> embeddings = new ArrayList<EmbeddedData>();
extractAll(patriarch, embeddings);
return embeddings;
}
protected void extractAll(ShapeContainer<?> parent, List<EmbeddedData> embeddings) throws IOException {
for (Shape shape : parent) {
EmbeddedData data = null;
if (shape instanceof ObjectData) {
ObjectData od = (ObjectData)shape;
try {
if (od.hasDirectoryEntry()) {
data = extractOne((DirectoryNode)od.getDirectory());
} else {
String contentType = CONTENT_TYPE_BYTES;
if (od instanceof XSSFObjectData) {
contentType = ((XSSFObjectData)od).getObjectPart().getContentType();
}
data = new EmbeddedData(od.getFileName(), od.getObjectData(), contentType);
}
} catch (Exception e) {
LOG.log(POILogger.WARN, "Entry not found / readable - ignoring OLE embedding", e);
}
} else if (shape instanceof Picture) {
data = extractOne((Picture)shape);
} else if (shape instanceof ShapeContainer) {
extractAll((ShapeContainer<?>)shape, embeddings);
}
if (data == null) {
continue;
}
data.setShape(shape);
String filename = data.getFilename();
String extension = (filename == null || filename.lastIndexOf('.') == -1) ? ".bin" : filename.substring(filename.lastIndexOf('.'));
// try to find an alternative name
if (filename == null || "".equals(filename) || filename.startsWith("MBD") || filename.startsWith("Root Entry")) {
filename = shape.getShapeName();
if (filename != null) {
filename += extension;
}
}
// default to dummy name
if (filename == null || "".equals(filename)) {
filename = "picture_" + embeddings.size() + extension;
}
filename = filename.trim();
data.setFilename(filename);
embeddings.add(data);
}
}
public boolean canExtract(DirectoryNode source) {
return false;
}
public boolean canExtract(Picture source) {
return false;
}
protected EmbeddedData extract(DirectoryNode dn) throws IOException {
assert(canExtract(dn));
POIFSFileSystem dest = new POIFSFileSystem();
copyNodes(dn, dest.getRoot());
// start with a reasonable big size
ByteArrayOutputStream bos = new ByteArrayOutputStream(20000);
dest.writeFilesystem(bos);
dest.close();
return new EmbeddedData(dn.getName(), bos.toByteArray(), CONTENT_TYPE_BYTES);
}
protected EmbeddedData extract(Picture source) throws IOException {
return null;
}
public static class Ole10Extractor extends EmbeddedExtractor {
@Override
public boolean canExtract(DirectoryNode dn) {
ClassID clsId = dn.getStorageClsid();
return ClassID.OLE10_PACKAGE.equals(clsId);
}
@Override
public EmbeddedData extract(DirectoryNode dn) throws IOException {
try {
// TODO: inspect the CompObj record for more details, i.e. the content type
Ole10Native ole10 = Ole10Native.createFromEmbeddedOleObject(dn);
return new EmbeddedData(ole10.getFileName(), ole10.getDataBuffer(), CONTENT_TYPE_BYTES);
} catch (Ole10NativeException e) {
throw new IOException(e);
}
}
}
static class PdfExtractor extends EmbeddedExtractor {
static ClassID PdfClassID = new ClassID("{B801CA65-A1FC-11D0-85AD-444553540000}");
@Override
public boolean canExtract(DirectoryNode dn) {
ClassID clsId = dn.getStorageClsid();
return (PdfClassID.equals(clsId)
|| dn.hasEntry("CONTENTS"));
}
@Override
public EmbeddedData extract(DirectoryNode dn) throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
InputStream is = dn.createDocumentInputStream("CONTENTS");
IOUtils.copy(is, bos);
is.close();
return new EmbeddedData(dn.getName() + ".pdf", bos.toByteArray(), CONTENT_TYPE_PDF);
}
@Override
public boolean canExtract(Picture source) {
PictureData pd = source.getPictureData();
return (pd != null && pd.getPictureType() == Workbook.PICTURE_TYPE_EMF);
}
/**
* Mac Office encodes embedded objects inside the picture, e.g. PDF is part of an EMF.
* If an embedded stream is inside an EMF picture, this method extracts the payload.
*
* @return the embedded data in an EMF picture or null if none is found
*/
@Override
protected EmbeddedData extract(Picture source) throws IOException {
// check for emf+ embedded pdf (poor mans style :( )
// Mac Excel 2011 embeds pdf files with this method.
PictureData pd = source.getPictureData();
if (pd != null && pd.getPictureType() != Workbook.PICTURE_TYPE_EMF) {
return null;
}
// TODO: investigate if this is just an EMF-hack or if other formats are also embedded in EMF
byte pictureBytes[] = pd.getData();
int idxStart = indexOf(pictureBytes, 0, "%PDF-".getBytes(LocaleUtil.CHARSET_1252));
if (idxStart == -1) {
return null;
}
int idxEnd = indexOf(pictureBytes, idxStart, "%%EOF".getBytes(LocaleUtil.CHARSET_1252));
if (idxEnd == -1) {
return null;
}
int pictureBytesLen = idxEnd-idxStart+6;
byte[] pdfBytes = new byte[pictureBytesLen];
System.arraycopy(pictureBytes, idxStart, pdfBytes, 0, pictureBytesLen);
String filename = source.getShapeName().trim();
if (!endsWithIgnoreCase(filename, ".pdf")) {
filename += ".pdf";
}
return new EmbeddedData(filename, pdfBytes, CONTENT_TYPE_PDF);
}
}
static class OOXMLExtractor extends EmbeddedExtractor {
@Override
public boolean canExtract(DirectoryNode dn) {
return dn.hasEntry("package");
}
@Override
public EmbeddedData extract(DirectoryNode dn) throws IOException {
ClassID clsId = dn.getStorageClsid();
String contentType, ext;
if (ClassID.WORD2007.equals(clsId)) {
ext = ".docx";
contentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
} else if (ClassID.WORD2007_MACRO.equals(clsId)) {
ext = ".docm";
contentType = "application/vnd.ms-word.document.macroEnabled.12";
} else if (ClassID.EXCEL2007.equals(clsId) || ClassID.EXCEL2003.equals(clsId) || ClassID.EXCEL2010.equals(clsId)) {
ext = ".xlsx";
contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
} else if (ClassID.EXCEL2007_MACRO.equals(clsId)) {
ext = ".xlsm";
contentType = "application/vnd.ms-excel.sheet.macroEnabled.12";
} else if (ClassID.EXCEL2007_XLSB.equals(clsId)) {
ext = ".xlsb";
contentType = "application/vnd.ms-excel.sheet.binary.macroEnabled.12";
} else if (ClassID.POWERPOINT2007.equals(clsId)) {
ext = ".pptx";
contentType = "application/vnd.openxmlformats-officedocument.presentationml.presentation";
} else if (ClassID.POWERPOINT2007_MACRO.equals(clsId)) {
ext = ".ppsm";
contentType = "application/vnd.ms-powerpoint.slideshow.macroEnabled.12";
} else {
ext = ".zip";
contentType = "application/zip";
}
DocumentInputStream dis = dn.createDocumentInputStream("package");
byte data[] = IOUtils.toByteArray(dis);
dis.close();
return new EmbeddedData(dn.getName()+ext, data, contentType);
}
}
static class BiffExtractor extends EmbeddedExtractor {
@Override
public boolean canExtract(DirectoryNode dn) {
return canExtractExcel(dn) || canExtractWord(dn);
}
protected boolean canExtractExcel(DirectoryNode dn) {
ClassID clsId = dn.getStorageClsid();
return (ClassID.EXCEL95.equals(clsId)
|| ClassID.EXCEL97.equals(clsId)
|| dn.hasEntry("Workbook") /*...*/);
}
protected boolean canExtractWord(DirectoryNode dn) {
ClassID clsId = dn.getStorageClsid();
return (ClassID.WORD95.equals(clsId)
|| ClassID.WORD97.equals(clsId)
|| dn.hasEntry("WordDocument"));
}
@Override
public EmbeddedData extract(DirectoryNode dn) throws IOException {
EmbeddedData ed = super.extract(dn);
if (canExtractExcel(dn)) {
ed.setFilename(dn.getName() + ".xls");
ed.setContentType(CONTENT_TYPE_XLS);
} else if (canExtractWord(dn)) {
ed.setFilename(dn.getName() + ".doc");
ed.setContentType(CONTENT_TYPE_DOC);
}
return ed;
}
}
static class FsExtractor extends EmbeddedExtractor {
@Override
public boolean canExtract(DirectoryNode dn) {
return true;
}
@Override
public EmbeddedData extract(DirectoryNode dn) throws IOException {
EmbeddedData ed = super.extract(dn);
ed.setFilename(dn.getName() + ".ole");
// TODO: read the content type from CombObj stream
return ed;
}
}
protected static void copyNodes(DirectoryNode src, DirectoryNode dest) throws IOException {
for (Entry e : src) {
if (e instanceof DirectoryNode) {
DirectoryNode srcDir = (DirectoryNode)e;
DirectoryNode destDir = (DirectoryNode)dest.createDirectory(srcDir.getName());
destDir.setStorageClsid(srcDir.getStorageClsid());
copyNodes(srcDir, destDir);
} else {
InputStream is = src.createDocumentInputStream(e);
try {
dest.createDocument(e.getName(), is);
} finally {
is.close();
}
}
}
}
/**
* Knuth-Morris-Pratt Algorithm for Pattern Matching
* Finds the first occurrence of the pattern in the text.
*/
private static int indexOf(byte[] data, int offset, byte[] pattern) {
int[] failure = computeFailure(pattern);
int j = 0;
if (data.length == 0) {
return -1;
}
for (int i = offset; i < data.length; i++) {
while (j > 0 && pattern[j] != data[i]) {
j = failure[j - 1];
}
if (pattern[j] == data[i]) { j++; }
if (j == pattern.length) {
return i - pattern.length + 1;
}
}
return -1;
}
/**
* Computes the failure function using a boot-strapping process,
* where the pattern is matched against itself.
*/
private static int[] computeFailure(byte[] pattern) {
int[] failure = new int[pattern.length];
int j = 0;
for (int i = 1; i < pattern.length; i++) {
while (j > 0 && pattern[j] != pattern[i]) {
j = failure[j - 1];
}
if (pattern[j] == pattern[i]) {
j++;
}
failure[i] = j;
}
return failure;
}
}
| |
/*
* Copyright (C) 2011 University of Washington
*
* 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.odk.collect.android.views;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import org.javarosa.core.model.FormIndex;
import org.javarosa.core.model.data.IAnswerData;
import org.javarosa.form.api.FormEntryCaption;
import org.javarosa.form.api.FormEntryPrompt;
import org.odk.collect.android.application.Collect;
import org.odk.collect.android.widgets.IBinaryWidget;
import org.odk.collect.android.widgets.QuestionWidget;
import org.odk.collect.android.widgets.WidgetFactory;
import android.content.Context;
import android.os.Handler;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
/**
* This class is
*
* @author carlhartung
*/
public class ODKView extends ScrollView implements OnLongClickListener {
// starter random number for view IDs
private final static int VIEW_ID = 12345;
private final static String t = "ODKView";
private LinearLayout mView;
private LinearLayout.LayoutParams mLayout;
private ArrayList<QuestionWidget> widgets;
private Handler h = null;
public final static String FIELD_LIST = "field-list";
public ODKView(Context context, FormEntryPrompt[] questionPrompts,
FormEntryCaption[] groups, boolean advancingPage) {
super(context);
widgets = new ArrayList<QuestionWidget>();
mView = new LinearLayout(getContext());
mView.setOrientation(LinearLayout.VERTICAL);
mView.setGravity(Gravity.TOP);
mView.setPadding(0, 7, 0, 0);
mLayout =
new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
mLayout.setMargins(10, 0, 10, 0);
// display which group you are in as well as the question
addGroupText(groups);
boolean first = true;
int id = 0;
for (FormEntryPrompt p : questionPrompts) {
if (!first) {
View divider = new View(getContext());
divider.setBackgroundResource(android.R.drawable.divider_horizontal_bright);
divider.setMinimumHeight(3);
mView.addView(divider);
} else {
first = false;
}
// if question or answer type is not supported, use text widget
QuestionWidget qw =
WidgetFactory.createWidgetFromPrompt(p, getContext());
qw.setLongClickable(true);
qw.setOnLongClickListener(this);
qw.setId(VIEW_ID + id++);
widgets.add(qw);
mView.addView((View) qw, mLayout);
}
addView(mView);
// see if there is an autoplay option.
// Only execute it during forward swipes through the form
if ( advancingPage && questionPrompts.length == 1 ) {
final String playOption = widgets.get(0).getPrompt().getFormElement().getAdditionalAttribute(null, "autoplay");
if ( playOption != null ) {
h = new Handler();
h.postDelayed(new Runnable() {
@Override
public void run() {
if ( playOption.equalsIgnoreCase("audio") ) {
widgets.get(0).playAudio();
} else if ( playOption.equalsIgnoreCase("video") ) {
widgets.get(0).playVideo();
}
}
}, 150);
}
}
}
/**
* http://code.google.com/p/android/issues/detail?id=8488
*/
public void recycleDrawables() {
this.destroyDrawingCache();
mView.destroyDrawingCache();
for ( QuestionWidget q : widgets ) {
q.recycleDrawables();
}
}
protected void onScrollChanged(int l, int t, int oldl, int oldt) {
Collect.getInstance().getActivityLogger().logScrollAction(this, t - oldt);
}
/**
* @return a HashMap of answers entered by the user for this set of widgets
*/
public LinkedHashMap<FormIndex, IAnswerData> getAnswers() {
LinkedHashMap<FormIndex, IAnswerData> answers = new LinkedHashMap<FormIndex, IAnswerData>();
Iterator<QuestionWidget> i = widgets.iterator();
while (i.hasNext()) {
/*
* The FormEntryPrompt has the FormIndex, which is where the answer gets stored. The
* QuestionWidget has the answer the user has entered.
*/
QuestionWidget q = i.next();
FormEntryPrompt p = q.getPrompt();
answers.put(p.getIndex(), q.getAnswer());
}
return answers;
}
/**
* // * Add a TextView containing the hierarchy of groups to which the question belongs. //
*/
private void addGroupText(FormEntryCaption[] groups) {
StringBuffer s = new StringBuffer("");
String t = "";
int i;
// list all groups in one string
for (FormEntryCaption g : groups) {
i = g.getMultiplicity() + 1;
t = g.getLongText();
if (t != null) {
s.append(t);
if (g.repeats() && i > 0) {
s.append(" (" + i + ")");
}
s.append(" > ");
}
}
// build view
if (s.length() > 0) {
TextView tv = new TextView(getContext());
tv.setText(s.substring(0, s.length() - 3));
int questionFontsize = Collect.getQuestionFontsize();
tv.setTextSize(TypedValue.COMPLEX_UNIT_DIP, questionFontsize - 4);
tv.setPadding(0, 0, 0, 5);
mView.addView(tv, mLayout);
}
}
public void setFocus(Context context) {
if (widgets.size() > 0) {
widgets.get(0).setFocus(context);
}
}
/**
* Called when another activity returns information to answer this question.
*
* @param answer
*/
public void setBinaryData(Object answer) {
boolean set = false;
for (QuestionWidget q : widgets) {
if (q instanceof IBinaryWidget) {
if (((IBinaryWidget) q).isWaitingForBinaryData()) {
((IBinaryWidget) q).setBinaryData(answer);
set = true;
break;
}
}
}
if (!set) {
Log.w(t, "Attempting to return data to a widget or set of widgets not looking for data");
}
}
public void cancelWaitingForBinaryData() {
int count = 0;
for (QuestionWidget q : widgets) {
if (q instanceof IBinaryWidget) {
if (((IBinaryWidget) q).isWaitingForBinaryData()) {
((IBinaryWidget) q).cancelWaitingForBinaryData();
++count;
}
}
}
if (count != 1) {
Log.w(t, "Attempting to cancel waiting for binary data to a widget or set of widgets not looking for data");
}
}
public boolean suppressFlingGesture(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
for (QuestionWidget q : widgets) {
if ( q.suppressFlingGesture(e1, e2, velocityX, velocityY) ) {
return true;
}
}
return false;
}
/**
* @return true if the answer was cleared, false otherwise.
*/
public boolean clearAnswer() {
// If there's only one widget, clear the answer.
// If there are more, then force a long-press to clear the answer.
if (widgets.size() == 1 && !widgets.get(0).getPrompt().isReadOnly()) {
widgets.get(0).clearAnswer();
return true;
} else {
return false;
}
}
public ArrayList<QuestionWidget> getWidgets() {
return widgets;
}
@Override
public void setOnFocusChangeListener(OnFocusChangeListener l) {
for (int i = 0; i < widgets.size(); i++) {
QuestionWidget qw = widgets.get(i);
qw.setOnFocusChangeListener(l);
}
}
@Override
public boolean onLongClick(View v) {
return false;
}
@Override
public void cancelLongPress() {
super.cancelLongPress();
for (QuestionWidget qw : widgets) {
qw.cancelLongPress();
}
}
}
| |
/*
* $Header: /home/cvs/jakarta-tomcat-jasper/jasper2/src/share/org/apache/jasper/compiler/JspRuntimeContext.java,v 1.4.2.2 2002/09/20 23:04:12 glenn Exp $
* $Revision: 1.4.2.2 $
* $Date: 2002/09/20 23:04:12 $
*
* ====================================================================
*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. 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.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Tomcat", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.jasper.compiler;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FilePermission;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.security.CodeSource;
import java.security.Policy;
import java.security.PermissionCollection;
import java.util.Iterator;
import java.util.List;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.jsp.JspFactory;
import org.apache.jasper.JasperException;
import org.apache.jasper.Constants;
import org.apache.jasper.JspCompilationContext;
import org.apache.jasper.Options;
import org.apache.jasper.logging.Logger;
import org.apache.jasper.runtime.JspFactoryImpl;
import org.apache.jasper.servlet.JspServletWrapper;
/**
* Class for tracking JSP compile time file dependencies when the
* <%@include file="..."%> directive is used.
*
* A background thread periodically checks the files a JSP page
* is dependent upon. If a dpendent file changes the JSP page
* which included it is recompiled.
*
* Only used if a web application context is a directory.
*
* @author Glenn L. Nielsen
* @version $Revision: 1.4.2.2 $
*/
public final class JspRuntimeContext implements Runnable {
/**
* Preload classes required at runtime by a JSP servlet so that
* we don't get a defineClassInPackage security exception.
*/
static {
JspFactoryImpl factory = new JspFactoryImpl();
if( System.getSecurityManager() != null ) {
String basePackage = "org.apache.jasper.";
try {
factory.getClass().getClassLoader().loadClass( basePackage +
"runtime.JspFactoryImpl$PrivilegedGetPageContext");
factory.getClass().getClassLoader().loadClass( basePackage +
"runtime.JspFactoryImpl$PrivilegedReleasePageContext");
factory.getClass().getClassLoader().loadClass( basePackage +
"runtime.JspRuntimeLibrary");
factory.getClass().getClassLoader().loadClass( basePackage +
"runtime.JspRuntimeLibrary$PrivilegedIntrospectHelper");
factory.getClass().getClassLoader().loadClass( basePackage +
"runtime.ServletResponseWrapperInclude");
factory.getClass().getClassLoader().loadClass( basePackage +
"runtime.TagHandlerPool");
factory.getClass().getClassLoader().loadClass( basePackage +
"servlet.JspServletWrapper");
} catch (ClassNotFoundException ex) {
System.out.println(
"Jasper JspRuntimeContext preload of class failed: " +
ex.getMessage());
}
}
JspFactory.setDefaultFactory(factory);
}
// ----------------------------------------------------------- Constructors
/**
* Create a JspRuntimeContext for a web application context.
*
* Loads in any previously generated dependencies from file.
*
* @param ServletContext for web application
*/
public JspRuntimeContext(ServletContext context, Options options) {
this.context = context;
this.options = options;
// Get the parent class loader
parentClassLoader =
(URLClassLoader) Thread.currentThread().getContextClassLoader();
if (parentClassLoader == null) {
parentClassLoader =
(URLClassLoader)this.getClass().getClassLoader();
}
if (parentClassLoader != null) {
Constants.message("jsp.message.parent_class_loader_is",
new Object[] {
parentClassLoader.toString()
}, Logger.DEBUG);
} else {
Constants.message("jsp.message.parent_class_loader_is",
new Object[] {
"<none>"
}, Logger.DEBUG);
}
initSecurity();
initClassPath();
// If this web application context is running from a
// directory, start the background compilation thread
String appBase = context.getRealPath("/");
if (!options.getDevelopment()
&& appBase != null
&& options.getReloading() ) {
if (appBase.endsWith(File.separator) ) {
appBase = appBase.substring(0,appBase.length()-1);
}
String directory =
appBase.substring(appBase.lastIndexOf(File.separator));
threadName = threadName + "[" + directory + "]";
threadStart();
}
}
// ----------------------------------------------------- Instance Variables
/**
* This web applications ServletContext
*/
private ServletContext context;
private Options options;
private URLClassLoader parentClassLoader;
private PermissionCollection permissionCollection;
private CodeSource codeSource;
private String classpath;
/**
* Maps JSP pages to their JspServletWrapper's
*/
private Map jsps = Collections.synchronizedMap( new HashMap());
/**
* The background thread.
*/
private Thread thread = null;
/**
* The background thread completion semaphore.
*/
private boolean threadDone = false;
/**
* Name to register for the background thread.
*/
private String threadName = "JspRuntimeContext";
// ------------------------------------------------------ Protected Methods
/**
* Add a new JspServletWrapper.
*
* @param String uri of JSP
* @param JspServletWrapper for JSP
*/
public void addWrapper(String jspUri, JspServletWrapper jsw) {
jsps.remove(jspUri);
jsps.put(jspUri,jsw);
}
/**
* Get an already existing JspServletWrapper.
*
* @param String JSP URI
* @return JspServletWrapper for JSP
*/
public JspServletWrapper getWrapper(String jspUri) {
return (JspServletWrapper) jsps.get(jspUri);
}
/**
* Remove a JspServletWrapper.
*
* @param String JSP URI of JspServletWrapper to remove
*/
public void removeWrapper(String jspUri) {
jsps.remove(jspUri);
}
/**
* Get the SecurityManager Policy CodeSource for this web
* applicaiton context.
*
* @return CodeSource for JSP
*/
public CodeSource getCodeSource() {
return codeSource;
}
/**
* Get the parent URLClassLoader.
*
* @return URLClassLoader parent
*/
public URLClassLoader getParentClassLoader() {
return parentClassLoader;
}
/**
* Get the SecurityManager PermissionCollection for this
* web application context.
*
* @return PermissionCollection permissions
*/
public PermissionCollection getPermissionCollection() {
return permissionCollection;
}
/**
* Process a "destory" event for this web application context.
*/
public void destroy() {
threadStop();
Iterator servlets = jsps.values().iterator();
while (servlets.hasNext()) {
((JspServletWrapper) servlets.next()).destroy();
}
}
// -------------------------------------------------------- Private Methods
/**
* Method used by background thread to check the JSP dependencies
* registered with this class for JSP's.
*/
private void checkCompile() {
Iterator it = jsps.values().iterator();
while (it.hasNext()) {
JspServletWrapper jsw = (JspServletWrapper)it.next();
JspCompilationContext ctxt = jsw.getJspEngineContext();
// JspServletWrapper also synchronizes on this when
// it detects it has to do a reload
synchronized(jsw) {
try {
ctxt.compile();
} catch (FileNotFoundException ex) {
ctxt.incrementRemoved();
} catch (Throwable t) {
jsw.getServletContext().log("Background compile failed",t);
}
}
}
}
/**
* The classpath that is passed off to the Java compiler.
*/
public String getClassPath() {
return classpath;
}
/**
* Method used to initialize classpath for compiles.
*/
private void initClassPath() {
URL [] urls = parentClassLoader.getURLs();
StringBuffer cpath = new StringBuffer();
String sep = System.getProperty("path.separator");
for(int i = 0; i < urls.length; i++) {
// Tomcat 4 can use URL's other than file URL's,
// a protocol other than file: will generate a
// bad file system path, so only add file:
// protocol URL's to the classpath.
if( urls[i].getProtocol().equals("file") ) {
cpath.append((String)urls[i].getFile()+sep);
}
}
String cp = (String) context.getAttribute(Constants.SERVLET_CLASSPATH);
if (cp == null || cp.equals("")) {
cp = options.getClassPath();
}
classpath = cpath.toString() + cp;
}
/**
* Method used to initialize SecurityManager data.
*/
private void initSecurity() {
// Setup the PermissionCollection for this web app context
// based on the permissions configured for the root of the
// web app context directory, then add a file read permission
// for that directory.
Policy policy = Policy.getPolicy();
if( policy != null ) {
try {
// Get the permissions for the web app context
String contextDir = context.getRealPath("/");
if( contextDir == null ) {
contextDir = options.getScratchDir().toString();
}
URL url = new URL("file:" + contextDir);
codeSource = new CodeSource(url,null);
permissionCollection = policy.getPermissions(codeSource);
// Create a file read permission for web app context directory
if (contextDir.endsWith(File.separator)) {
contextDir = contextDir + "-";
} else {
contextDir = contextDir + File.separator + "-";
}
// Create a file read permission for web app tempdir (work) directory
String workDir = options.getScratchDir().toString();
if (workDir.endsWith(File.separator)) {
workDir = workDir + "-";
} else {
workDir = workDir + File.separator + "-";
}
permissionCollection.add(new FilePermission(workDir,"read"));
// Allow the JSP to access org.apache.jasper.runtime.HttpJspBase
permissionCollection.add( new RuntimePermission(
"accessClassInPackage.org.apache.jasper.runtime") );
if (parentClassLoader instanceof URLClassLoader) {
URL [] urls = parentClassLoader.getURLs();
String jarUrl = null;
String jndiUrl = null;
for (int i=0; i<urls.length; i++) {
if (jndiUrl == null
&& urls[i].toString().startsWith("jndi:") ) {
jndiUrl = urls[i].toString() + "-";
}
if (jarUrl == null
&& urls[i].toString().startsWith("jar:jndi:")
) {
jarUrl = urls[i].toString();
jarUrl = jarUrl.substring(0,jarUrl.length() - 2);
jarUrl = jarUrl.substring(0,
jarUrl.lastIndexOf('/')) + "/-";
}
}
if (jarUrl != null) {
permissionCollection.add(
new FilePermission(jarUrl,"read"));
permissionCollection.add(
new FilePermission(jarUrl.substring(4),"read"));
}
if (jndiUrl != null)
permissionCollection.add(
new FilePermission(jndiUrl,"read") );
}
} catch(MalformedURLException mfe) {
}
}
}
// -------------------------------------------------------- Thread Support
/**
* Start the background thread that will periodically check for
* changes to compile time included files in a JSP.
*
* @exception IllegalStateException if we should not be starting
* a background thread now
*/
protected void threadStart() {
// Has the background thread already been started?
if (thread != null) {
return;
}
// Start the background thread
threadDone = false;
thread = new Thread(this, threadName);
thread.setDaemon(true);
thread.start();
}
/**
* Stop the background thread that is periodically checking for
* changes to compile time included files in a JSP.
*/
protected void threadStop() {
if (thread == null) {
return;
}
threadDone = true;
thread.interrupt();
try {
thread.join();
} catch (InterruptedException e) {
;
}
thread = null;
}
/**
* Sleep for the duration specified by the <code>checkInterval</code>
* property.
*/
protected void threadSleep() {
try {
Thread.sleep(options.getCheckInterval() * 1000L);
} catch (InterruptedException e) {
;
}
}
// ------------------------------------------------------ Background Thread
/**
* The background thread that checks for changes to files
* included by a JSP and flags that a recompile is required.
*/
public void run() {
// Loop until the termination semaphore is set
while (!threadDone) {
// Wait for our check interval
threadSleep();
// Check for included files which are newer than the
// JSP which uses them.
checkCompile();
}
}
}
| |
/*
* The MIT License
*
* Copyright (c) 2004-2010, Sun Microsystems, Inc., Kohsuke Kawaguchi, Jene Jasper, Stephen Connolly, Tom Huybrechts, Yahoo! Inc.
*
* 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 hudson.tasks;
import hudson.Extension;
import hudson.Launcher;
import hudson.Functions;
import hudson.EnvVars;
import hudson.Util;
import hudson.CopyOnWrite;
import hudson.Launcher.LocalLauncher;
import hudson.FilePath.FileCallable;
import hudson.model.AbstractBuild;
import hudson.model.AbstractProject;
import hudson.model.BuildListener;
import hudson.model.Computer;
import hudson.model.EnvironmentSpecific;
import hudson.model.Node;
import hudson.model.Hudson;
import hudson.model.TaskListener;
import hudson.remoting.Callable;
import hudson.remoting.VirtualChannel;
import hudson.slaves.NodeSpecific;
import hudson.tasks._maven.MavenConsoleAnnotator;
import hudson.tools.ToolDescriptor;
import hudson.tools.ToolInstallation;
import hudson.tools.DownloadFromUrlInstaller;
import hudson.tools.ToolInstaller;
import hudson.tools.ToolProperty;
import hudson.util.ArgumentListBuilder;
import hudson.util.NullStream;
import hudson.util.StreamTaskListener;
import hudson.util.VariableResolver;
import hudson.util.FormValidation;
import hudson.util.XStream2;
import net.sf.json.JSONObject;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.QueryParameter;
import java.io.File;
import java.io.IOException;
import java.util.Properties;
import java.util.StringTokenizer;
import java.util.List;
import java.util.Collections;
import java.util.Set;
/**
* Build by using Maven.
*
* @author Kohsuke Kawaguchi
*/
public class Maven extends Builder {
/**
* The targets and other maven options.
* Can be separated by SP or NL.
*/
public final String targets;
/**
* Identifies {@link MavenInstallation} to be used.
*/
public final String mavenName;
/**
* MAVEN_OPTS if not null.
*/
public final String jvmOptions;
/**
* Optional POM file path relative to the workspace.
* Used for the Maven '-f' option.
*/
public final String pom;
/**
* Optional properties to be passed to Maven. Follows {@link Properties} syntax.
*/
public final String properties;
/**
* If true, the build will use its own local Maven repository
* via "-Dmaven.repo.local=...".
* <p>
* This would consume additional disk space, but provides isolation with other builds on the same machine,
* such as mixing SNAPSHOTS. Maven also doesn't try to coordinate the concurrent access to Maven repositories
* from multiple Maven process, so this helps there too.
*
* Identical to logic used in maven-plugin.
*
* @since 1.322
*/
public boolean usePrivateRepository = false;
private final static String MAVEN_1_INSTALLATION_COMMON_FILE = "bin/maven";
private final static String MAVEN_2_INSTALLATION_COMMON_FILE = "bin/mvn";
public Maven(String targets,String name) {
this(targets,name,null,null,null,false);
}
public Maven(String targets, String name, String pom, String properties, String jvmOptions) {
this(targets, name, pom, properties, jvmOptions, false);
}
@DataBoundConstructor
public Maven(String targets,String name, String pom, String properties, String jvmOptions, boolean usePrivateRepository) {
this.targets = targets;
this.mavenName = name;
this.pom = Util.fixEmptyAndTrim(pom);
this.properties = Util.fixEmptyAndTrim(properties);
this.jvmOptions = Util.fixEmptyAndTrim(jvmOptions);
this.usePrivateRepository = usePrivateRepository;
}
public String getTargets() {
return targets;
}
public void setUsePrivateRepository(boolean usePrivateRepository) {
this.usePrivateRepository = usePrivateRepository;
}
public boolean usesPrivateRepository() {
return usePrivateRepository;
}
/**
* Gets the Maven to invoke,
* or null to invoke the default one.
*/
public MavenInstallation getMaven() {
for( MavenInstallation i : getDescriptor().getInstallations() ) {
if(mavenName !=null && mavenName.equals(i.getName()))
return i;
}
return null;
}
/**
* Looks for <tt>pom.xlm</tt> or <tt>project.xml</tt> to determine the maven executable
* name.
*/
private static final class DecideDefaultMavenCommand implements FileCallable<String> {
// command line arguments.
private final String arguments;
public DecideDefaultMavenCommand(String arguments) {
this.arguments = arguments;
}
public String invoke(File ws, VirtualChannel channel) throws IOException {
String seed=null;
// check for the -f option
StringTokenizer tokens = new StringTokenizer(arguments);
while(tokens.hasMoreTokens()) {
String t = tokens.nextToken();
if(t.equals("-f") && tokens.hasMoreTokens()) {
File file = new File(ws,tokens.nextToken());
if(!file.exists())
continue; // looks like an error, but let the execution fail later
seed = file.isDirectory() ?
/* in M1, you specify a directory in -f */ "maven"
/* in M2, you specify a POM file name. */ : "mvn";
break;
}
}
if(seed==null) {
// as of 1.212 (2008 April), I think Maven2 mostly replaced Maven1, so
// switching to err on M2 side.
seed = new File(ws,"project.xml").exists() ? "maven" : "mvn";
}
if(Functions.isWindows())
seed += ".bat";
return seed;
}
}
@Override
public boolean perform(AbstractBuild<?,?> build, Launcher launcher, BuildListener listener) throws IOException, InterruptedException {
VariableResolver<String> vr = build.getBuildVariableResolver();
EnvVars env = build.getEnvironment(listener);
String targets = Util.replaceMacro(this.targets,vr);
targets = env.expand(targets);
String pom = env.expand(this.pom);
String properties = env.expand(this.properties);
int startIndex = 0;
int endIndex;
do {
// split targets into multiple invokations of maven separated by |
endIndex = targets.indexOf('|', startIndex);
if (-1 == endIndex) {
endIndex = targets.length();
}
String normalizedTarget = targets
.substring(startIndex, endIndex)
.replaceAll("[\t\r\n]+"," ");
ArgumentListBuilder args = new ArgumentListBuilder();
MavenInstallation mi = getMaven();
if(mi==null) {
String execName = build.getWorkspace().act(new DecideDefaultMavenCommand(normalizedTarget));
args.add(execName);
} else {
mi = mi.forNode(Computer.currentComputer().getNode(), listener);
mi = mi.forEnvironment(env);
String exec = mi.getExecutable(launcher);
if(exec==null) {
listener.fatalError(Messages.Maven_NoExecutable(mi.getHome()));
return false;
}
args.add(exec);
}
if(pom!=null)
args.add("-f",pom);
Set<String> sensitiveVars = build.getSensitiveBuildVariables();
args.addKeyValuePairs("-D",build.getBuildVariables(),sensitiveVars);
args.addKeyValuePairsFromPropertyString("-D",properties,vr,sensitiveVars);
if (usesPrivateRepository())
args.add("-Dmaven.repo.local=" + build.getWorkspace().child(".repository"));
args.addTokenized(normalizedTarget);
wrapUpArguments(args,normalizedTarget,build,launcher,listener);
buildEnvVars(env, mi);
try {
MavenConsoleAnnotator mca = new MavenConsoleAnnotator(listener.getLogger(),build.getCharset());
int r = launcher.launch().cmds(args).envs(env).stdout(mca).pwd(build.getModuleRoot()).join();
if (0 != r) {
return false;
}
} catch (IOException e) {
Util.displayIOException(e,listener);
e.printStackTrace( listener.fatalError(Messages.Maven_ExecFailed()) );
return false;
}
startIndex = endIndex + 1;
} while (startIndex < targets.length());
return true;
}
/**
* Allows the derived type to make additional modifications to the arguments list.
*
* @since 1.344
*/
protected void wrapUpArguments(ArgumentListBuilder args, String normalizedTarget, AbstractBuild<?,?> build, Launcher launcher, BuildListener listener) throws IOException, InterruptedException {
}
/**
* Build up the environment variables toward the Maven launch.
*/
protected void buildEnvVars(EnvVars env, MavenInstallation mi) throws IOException, InterruptedException {
if(mi!=null) {
// if somebody has use M2_HOME they will get a classloading error
// when M2_HOME points to a different version of Maven2 from
// MAVEN_HOME (as Maven 2 gives M2_HOME priority.)
//
// The other solution would be to set M2_HOME if we are calling Maven2
// and MAVEN_HOME for Maven1 (only of use for strange people that
// are calling Maven2 from Maven1)
env.put("M2_HOME",mi.getHome());
env.put("MAVEN_HOME",mi.getHome());
}
// just as a precaution
// see http://maven.apache.org/continuum/faqs.html#how-does-continuum-detect-a-successful-build
env.put("MAVEN_TERMINATE_CMD","on");
String jvmOptions = env.expand(this.jvmOptions);
if(jvmOptions!=null)
env.put("MAVEN_OPTS",jvmOptions.replaceAll("[\t\r\n]+"," "));
}
@Override
public DescriptorImpl getDescriptor() {
return (DescriptorImpl)super.getDescriptor();
}
/**
* @deprecated as of 1.286
* Use {@link Hudson#getDescriptorByType(Class)} to obtain the current instance.
* For compatibility, this field retains the last created {@link DescriptorImpl}.
* TODO: fix sonar plugin that depends on this. That's the only plugin that depends on this field.
*/
public static DescriptorImpl DESCRIPTOR;
@Extension
public static final class DescriptorImpl extends BuildStepDescriptor<Builder> {
@CopyOnWrite
private volatile MavenInstallation[] installations = new MavenInstallation[0];
public DescriptorImpl() {
DESCRIPTOR = this;
load();
}
public boolean isApplicable(Class<? extends AbstractProject> jobType) {
return true;
}
@Override
public String getHelpFile() {
return "/help/project-config/maven.html";
}
public String getDisplayName() {
return Messages.Maven_DisplayName();
}
public MavenInstallation[] getInstallations() {
return installations;
}
public void setInstallations(MavenInstallation... installations) {
this.installations = installations;
save();
}
@Override
public Builder newInstance(StaplerRequest req, JSONObject formData) throws FormException {
return req.bindJSON(Maven.class,formData);
}
}
/**
* Represents a Maven installation in a system.
*/
public static final class MavenInstallation extends ToolInstallation implements EnvironmentSpecific<MavenInstallation>, NodeSpecific<MavenInstallation> {
/**
* Constants for describing Maven versions for comparison.
*/
public static final int MAVEN_20 = 0;
public static final int MAVEN_21 = 1;
public static final int MAVEN_30 = 2;
/**
* @deprecated since 2009-02-25.
*/
@Deprecated // kept for backward compatiblity - use getHome()
private transient String mavenHome;
/**
* @deprecated as of 1.308.
* Use {@link #MavenInstallation(String, String, List)}
*/
public MavenInstallation(String name, String home) {
super(name, home);
}
@DataBoundConstructor
public MavenInstallation(String name, String home, List<? extends ToolProperty<?>> properties) {
super(name, home, properties);
}
/**
* install directory.
*
* @deprecated as of 1.308. Use {@link #getHome()}.
*/
public String getMavenHome() {
return getHome();
}
public File getHomeDir() {
return new File(getHome());
}
/**
* Compares the version of this Maven installation to the minimum required version specified.
*
* @param launcher
* Represents the node on which we evaluate the path.
* @param mavenReqVersion
* Represents the minimum required Maven version - constants defined above.
*/
public boolean meetsMavenReqVersion(Launcher launcher, int mavenReqVersion) throws IOException, InterruptedException {
// FIXME using similar stuff as in the maven plugin could be better
// olamy : but will add a dependency on maven in core -> so not so good
String mavenVersion = launcher.getChannel().call(new Callable<String,IOException>() {
public String call() throws IOException {
File[] jars = new File(getHomeDir(),"lib").listFiles();
if(jars!=null) { // be defensive
for (File jar : jars) {
if (jar.getName().endsWith("-uber.jar") && jar.getName().startsWith("maven-")) {
return jar.getName();
}
}
}
return "";
}
});
if (!mavenVersion.equals("")) {
if (mavenReqVersion == MAVEN_20) {
if(mavenVersion.startsWith("maven-2.") || mavenVersion.startsWith("maven-core-2"))
return true;
}
else if (mavenReqVersion == MAVEN_21) {
if(mavenVersion.startsWith("maven-2.") && !mavenVersion.startsWith("maven-2.0"))
return true;
}
else if (mavenReqVersion == MAVEN_30) {
if(mavenVersion.startsWith("maven-3.") && !mavenVersion.startsWith("maven-2.0"))
return true;
}
}
return false;
}
/**
* Is this Maven 2.1.x or later?
*
* @param launcher
* Represents the node on which we evaluate the path.
*/
public boolean isMaven2_1(Launcher launcher) throws IOException, InterruptedException {
return meetsMavenReqVersion(launcher, MAVEN_21);
}
/* return launcher.getChannel().call(new Callable<Boolean,IOException>() {
public Boolean call() throws IOException {
File[] jars = new File(getHomeDir(),"lib").listFiles();
if(jars!=null) // be defensive
for (File jar : jars)
if(jar.getName().startsWith("maven-2.") && !jar.getName().startsWith("maven-2.0") && jar.getName().endsWith("-uber.jar"))
return true;
return false;
}
});
} */
/**
* Gets the executable path of this maven on the given target system.
*/
public String getExecutable(Launcher launcher) throws IOException, InterruptedException {
return launcher.getChannel().call(new Callable<String,IOException>() {
public String call() throws IOException {
File exe = getExeFile("maven");
if(exe.exists())
return exe.getPath();
exe = getExeFile("mvn");
if(exe.exists())
return exe.getPath();
return null;
}
});
}
private File getExeFile(String execName) {
if(File.separatorChar=='\\')
execName += ".bat";
String m2Home = Util.replaceMacro(getHome(),EnvVars.masterEnvVars);
return new File(m2Home, "bin/" + execName);
}
/**
* Returns true if the executable exists.
*/
public boolean getExists() {
try {
return getExecutable(new LocalLauncher(new StreamTaskListener(new NullStream())))!=null;
} catch (IOException e) {
return false;
} catch (InterruptedException e) {
return false;
}
}
private static final long serialVersionUID = 1L;
public MavenInstallation forEnvironment(EnvVars environment) {
return new MavenInstallation(getName(), environment.expand(getHome()), getProperties().toList());
}
public MavenInstallation forNode(Node node, TaskListener log) throws IOException, InterruptedException {
return new MavenInstallation(getName(), translateFor(node, log), getProperties().toList());
}
@Extension
public static class DescriptorImpl extends ToolDescriptor<MavenInstallation> {
@Override
public String getDisplayName() {
return "Maven";
}
@Override
public List<? extends ToolInstaller> getDefaultInstallers() {
return Collections.singletonList(new MavenInstaller(null));
}
@Override
public MavenInstallation[] getInstallations() {
return Hudson.getInstance().getDescriptorByType(Maven.DescriptorImpl.class).getInstallations();
}
@Override
public void setInstallations(MavenInstallation... installations) {
Hudson.getInstance().getDescriptorByType(Maven.DescriptorImpl.class).setInstallations(installations);
}
/**
* Checks if the MAVEN_HOME is valid.
*/
public FormValidation doCheckMavenHome(@QueryParameter File value) {
// this can be used to check the existence of a file on the server, so needs to be protected
if(!Hudson.getInstance().hasPermission(Hudson.ADMINISTER))
return FormValidation.ok();
if(value.getPath().equals(""))
return FormValidation.ok();
if(!value.isDirectory())
return FormValidation.error(Messages.Maven_NotADirectory(value));
File maven1File = new File(value,MAVEN_1_INSTALLATION_COMMON_FILE);
File maven2File = new File(value,MAVEN_2_INSTALLATION_COMMON_FILE);
if(!maven1File.exists() && !maven2File.exists())
return FormValidation.error(Messages.Maven_NotMavenDirectory(value));
return FormValidation.ok();
}
public FormValidation doCheckName(@QueryParameter String value) {
return FormValidation.validateRequired(value);
}
}
public static class ConverterImpl extends ToolConverter {
public ConverterImpl(XStream2 xstream) { super(xstream); }
@Override protected String oldHomeField(ToolInstallation obj) {
return ((MavenInstallation)obj).mavenHome;
}
}
}
/**
* Automatic Maven installer from apache.org.
*/
public static class MavenInstaller extends DownloadFromUrlInstaller {
@DataBoundConstructor
public MavenInstaller(String id) {
super(id);
}
@Extension
public static final class DescriptorImpl extends DownloadFromUrlInstaller.DescriptorImpl<MavenInstaller> {
public String getDisplayName() {
return Messages.InstallFromApache();
}
@Override
public boolean isApplicable(Class<? extends ToolInstallation> toolType) {
return toolType==MavenInstallation.class;
}
}
}
/**
* Optional interface that can be implemented by {@link AbstractProject}
* that has "contextual" {@link MavenInstallation} associated with it.
*
* <p>
* Code like RedeployPublisher uses this interface in an attempt
* to use the consistent Maven installation attached to the project.
*
* @since 1.235
*/
public interface ProjectWithMaven {
/**
* Gets the {@link MavenInstallation} associated with the project.
* Can be null.
*
* <p>
* If the Maven installation can not be uniquely determined,
* it's often better to return just one of them, rather than returning
* null, since this method is currently ultimately only used to
* decide where to parse <tt>conf/settings.xml</tt> from.
*/
MavenInstallation inferMavenInstallation();
}
}
| |
// Copyright 2021 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.api.ads.admanager.jaxws.v202111;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlSeeAlso;
import javax.xml.bind.annotation.XmlType;
/**
*
* A {@code Creative} that is created by a Rich Media Studio.
*
*
* <p>Java class for BaseRichMediaStudioCreative complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="BaseRichMediaStudioCreative">
* <complexContent>
* <extension base="{https://www.google.com/apis/ads/publisher/v202111}Creative">
* <sequence>
* <element name="studioCreativeId" type="{http://www.w3.org/2001/XMLSchema}long" minOccurs="0"/>
* <element name="creativeFormat" type="{https://www.google.com/apis/ads/publisher/v202111}RichMediaStudioCreativeFormat" minOccurs="0"/>
* <element name="artworkType" type="{https://www.google.com/apis/ads/publisher/v202111}RichMediaStudioCreativeArtworkType" minOccurs="0"/>
* <element name="totalFileSize" type="{http://www.w3.org/2001/XMLSchema}long" minOccurs="0"/>
* <element name="adTagKeys" type="{http://www.w3.org/2001/XMLSchema}string" maxOccurs="unbounded" minOccurs="0"/>
* <element name="customKeyValues" type="{http://www.w3.org/2001/XMLSchema}string" maxOccurs="unbounded" minOccurs="0"/>
* <element name="surveyUrl" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="allImpressionsUrl" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="richMediaImpressionsUrl" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="backupImageImpressionsUrl" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="overrideCss" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="requiredFlashPluginVersion" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="duration" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/>
* <element name="billingAttribute" type="{https://www.google.com/apis/ads/publisher/v202111}RichMediaStudioCreativeBillingAttribute" minOccurs="0"/>
* <element name="richMediaStudioChildAssetProperties" type="{https://www.google.com/apis/ads/publisher/v202111}RichMediaStudioChildAssetProperty" maxOccurs="unbounded" minOccurs="0"/>
* <element name="sslScanResult" type="{https://www.google.com/apis/ads/publisher/v202111}SslScanResult" minOccurs="0"/>
* <element name="sslManualOverride" type="{https://www.google.com/apis/ads/publisher/v202111}SslManualOverride" minOccurs="0"/>
* </sequence>
* </extension>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "BaseRichMediaStudioCreative", propOrder = {
"studioCreativeId",
"creativeFormat",
"artworkType",
"totalFileSize",
"adTagKeys",
"customKeyValues",
"surveyUrl",
"allImpressionsUrl",
"richMediaImpressionsUrl",
"backupImageImpressionsUrl",
"overrideCss",
"requiredFlashPluginVersion",
"duration",
"billingAttribute",
"richMediaStudioChildAssetProperties",
"sslScanResult",
"sslManualOverride"
})
@XmlSeeAlso({
RichMediaStudioCreative.class
})
public abstract class BaseRichMediaStudioCreative
extends Creative
{
protected Long studioCreativeId;
@XmlSchemaType(name = "string")
protected RichMediaStudioCreativeFormat creativeFormat;
@XmlSchemaType(name = "string")
protected RichMediaStudioCreativeArtworkType artworkType;
protected Long totalFileSize;
protected List<String> adTagKeys;
protected List<String> customKeyValues;
protected String surveyUrl;
protected String allImpressionsUrl;
protected String richMediaImpressionsUrl;
protected String backupImageImpressionsUrl;
protected String overrideCss;
protected String requiredFlashPluginVersion;
protected Integer duration;
@XmlSchemaType(name = "string")
protected RichMediaStudioCreativeBillingAttribute billingAttribute;
protected List<RichMediaStudioChildAssetProperty> richMediaStudioChildAssetProperties;
@XmlSchemaType(name = "string")
protected SslScanResult sslScanResult;
@XmlSchemaType(name = "string")
protected SslManualOverride sslManualOverride;
/**
* Gets the value of the studioCreativeId property.
*
* @return
* possible object is
* {@link Long }
*
*/
public Long getStudioCreativeId() {
return studioCreativeId;
}
/**
* Sets the value of the studioCreativeId property.
*
* @param value
* allowed object is
* {@link Long }
*
*/
public void setStudioCreativeId(Long value) {
this.studioCreativeId = value;
}
/**
* Gets the value of the creativeFormat property.
*
* @return
* possible object is
* {@link RichMediaStudioCreativeFormat }
*
*/
public RichMediaStudioCreativeFormat getCreativeFormat() {
return creativeFormat;
}
/**
* Sets the value of the creativeFormat property.
*
* @param value
* allowed object is
* {@link RichMediaStudioCreativeFormat }
*
*/
public void setCreativeFormat(RichMediaStudioCreativeFormat value) {
this.creativeFormat = value;
}
/**
* Gets the value of the artworkType property.
*
* @return
* possible object is
* {@link RichMediaStudioCreativeArtworkType }
*
*/
public RichMediaStudioCreativeArtworkType getArtworkType() {
return artworkType;
}
/**
* Sets the value of the artworkType property.
*
* @param value
* allowed object is
* {@link RichMediaStudioCreativeArtworkType }
*
*/
public void setArtworkType(RichMediaStudioCreativeArtworkType value) {
this.artworkType = value;
}
/**
* Gets the value of the totalFileSize property.
*
* @return
* possible object is
* {@link Long }
*
*/
public Long getTotalFileSize() {
return totalFileSize;
}
/**
* Sets the value of the totalFileSize property.
*
* @param value
* allowed object is
* {@link Long }
*
*/
public void setTotalFileSize(Long value) {
this.totalFileSize = value;
}
/**
* Gets the value of the adTagKeys property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the adTagKeys property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getAdTagKeys().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link String }
*
*
*/
public List<String> getAdTagKeys() {
if (adTagKeys == null) {
adTagKeys = new ArrayList<String>();
}
return this.adTagKeys;
}
/**
* Gets the value of the customKeyValues property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the customKeyValues property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getCustomKeyValues().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link String }
*
*
*/
public List<String> getCustomKeyValues() {
if (customKeyValues == null) {
customKeyValues = new ArrayList<String>();
}
return this.customKeyValues;
}
/**
* Gets the value of the surveyUrl property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getSurveyUrl() {
return surveyUrl;
}
/**
* Sets the value of the surveyUrl property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setSurveyUrl(String value) {
this.surveyUrl = value;
}
/**
* Gets the value of the allImpressionsUrl property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getAllImpressionsUrl() {
return allImpressionsUrl;
}
/**
* Sets the value of the allImpressionsUrl property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setAllImpressionsUrl(String value) {
this.allImpressionsUrl = value;
}
/**
* Gets the value of the richMediaImpressionsUrl property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getRichMediaImpressionsUrl() {
return richMediaImpressionsUrl;
}
/**
* Sets the value of the richMediaImpressionsUrl property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setRichMediaImpressionsUrl(String value) {
this.richMediaImpressionsUrl = value;
}
/**
* Gets the value of the backupImageImpressionsUrl property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getBackupImageImpressionsUrl() {
return backupImageImpressionsUrl;
}
/**
* Sets the value of the backupImageImpressionsUrl property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setBackupImageImpressionsUrl(String value) {
this.backupImageImpressionsUrl = value;
}
/**
* Gets the value of the overrideCss property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getOverrideCss() {
return overrideCss;
}
/**
* Sets the value of the overrideCss property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setOverrideCss(String value) {
this.overrideCss = value;
}
/**
* Gets the value of the requiredFlashPluginVersion property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getRequiredFlashPluginVersion() {
return requiredFlashPluginVersion;
}
/**
* Sets the value of the requiredFlashPluginVersion property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setRequiredFlashPluginVersion(String value) {
this.requiredFlashPluginVersion = value;
}
/**
* Gets the value of the duration property.
*
* @return
* possible object is
* {@link Integer }
*
*/
public Integer getDuration() {
return duration;
}
/**
* Sets the value of the duration property.
*
* @param value
* allowed object is
* {@link Integer }
*
*/
public void setDuration(Integer value) {
this.duration = value;
}
/**
* Gets the value of the billingAttribute property.
*
* @return
* possible object is
* {@link RichMediaStudioCreativeBillingAttribute }
*
*/
public RichMediaStudioCreativeBillingAttribute getBillingAttribute() {
return billingAttribute;
}
/**
* Sets the value of the billingAttribute property.
*
* @param value
* allowed object is
* {@link RichMediaStudioCreativeBillingAttribute }
*
*/
public void setBillingAttribute(RichMediaStudioCreativeBillingAttribute value) {
this.billingAttribute = value;
}
/**
* Gets the value of the richMediaStudioChildAssetProperties property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the richMediaStudioChildAssetProperties property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getRichMediaStudioChildAssetProperties().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link RichMediaStudioChildAssetProperty }
*
*
*/
public List<RichMediaStudioChildAssetProperty> getRichMediaStudioChildAssetProperties() {
if (richMediaStudioChildAssetProperties == null) {
richMediaStudioChildAssetProperties = new ArrayList<RichMediaStudioChildAssetProperty>();
}
return this.richMediaStudioChildAssetProperties;
}
/**
* Gets the value of the sslScanResult property.
*
* @return
* possible object is
* {@link SslScanResult }
*
*/
public SslScanResult getSslScanResult() {
return sslScanResult;
}
/**
* Sets the value of the sslScanResult property.
*
* @param value
* allowed object is
* {@link SslScanResult }
*
*/
public void setSslScanResult(SslScanResult value) {
this.sslScanResult = value;
}
/**
* Gets the value of the sslManualOverride property.
*
* @return
* possible object is
* {@link SslManualOverride }
*
*/
public SslManualOverride getSslManualOverride() {
return sslManualOverride;
}
/**
* Sets the value of the sslManualOverride property.
*
* @param value
* allowed object is
* {@link SslManualOverride }
*
*/
public void setSslManualOverride(SslManualOverride value) {
this.sslManualOverride = value;
}
}
| |
package com.algocrafts.chapter3.interfaces;
import com.algocrafts.chapter2.factory.BetterWebDriverFactory;
import com.algocrafts.selectors.Id;
import com.algocrafts.selectors.LinkText;
import com.algocrafts.selectors.Xpath;
import com.algocrafts.selenium.Browser;
import com.algocrafts.selenium.Element;
import com.google.common.base.Function;
import org.apache.commons.lang.time.StopWatch;
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.FluentWait;
import org.openqa.selenium.support.ui.WebDriverWait;
import static com.algocrafts.browsers.Browsers.CHROME;
import static com.algocrafts.selectors.LinkText.CANADA;
import static com.algocrafts.selectors.LinkText.ONTARIO;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.openqa.selenium.By.*;
@Ignore
public class TicketflyTest {
StopWatch stopWatch = new StopWatch();
@Before
public void startStopWatch() {
stopWatch.start();
}
@After
public void print() {
System.out.println("Time taken " + stopWatch);
}
/**
* This test will fail.
*/
@Test
public void changeLocationUsingSelenium() {
WebDriver driver = BetterWebDriverFactory.CHROME.get();
driver.get("http://www.ticketfly.com");
driver.findElement(By.linkText("change location")).click();
WebElement location = driver.findElement(By.id("location"));
location.findElement(By.linkText("CANADA")).click();
WebElement element = location.findElement(By.linkText("Ontario"));
element.click();
assertEquals(0, location.findElements(By.linkText("Ontario")).size());
assertEquals("Ontario", driver
.findElement(By.xpath("div[@class='tools-location']/descendant::strong")).getText());
}
@Test
public void changeLocationWithImplicitWait() {
WebDriver driver = BetterWebDriverFactory.CHROME.get();
driver.manage().timeouts().implicitlyWait(30, SECONDS);
driver.get("http://www.ticketfly.com");
driver.findElement(By.linkText("change location")).click();
WebElement tabMenu = driver.findElement(By.id("location"));
tabMenu.findElement(By.linkText("CANADA")).click();
WebElement element = tabMenu.findElement(By.linkText("Ontario"));
element.click();
assertEquals(0, tabMenu.findElements(By.linkText("Ontario")).size());
assertEquals("Ontario", driver
.findElement(By.xpath("div[@class='tools-location']/descendant::strong")).getText());
}
//This is an ugly test not using page framework, it has the same function as the test below. :(
@Test
public void changeLocationUsingExplicitWait() {
WebDriver driver = BetterWebDriverFactory.CHROME.get();
driver.get("http://www.ticketfly.com");
driver.findElement(linkText("change location")).click();
WebDriverWait webDriverWait = new WebDriverWait(driver, 5);
WebElement location = webDriverWait.until(new Function<WebDriver, WebElement>() {
@Override
public WebElement apply(WebDriver driver) {
return driver.findElement(By.id("location"));
}
});
FluentWait<WebElement> webElementWait
= new FluentWait<WebElement>(location)
.withTimeout(30, SECONDS)
.ignoring(NoSuchElementException.class);
WebElement canada = webElementWait.until(new Function<WebElement, WebElement>() {
@Override
public WebElement apply(WebElement element) {
return location.findElement(linkText("CANADA"));
}
});
canada.click();
WebElement allCanada = webElementWait.until(new Function<WebElement, WebElement>() {
@Override
public WebElement apply(WebElement element) {
return location.findElement(linkText("Ontario"));
}
});
allCanada.click();
assertEquals(0, location.findElements(linkText("Ontario")).size());
assertEquals("Ontario", driver
.findElement(By.xpath("//div[@class='tools']/descendant::strong")).getText());
}
//This is an ugly test not using page framework, it has the same function as the test below. :(
@Test
public void changeLocationUsingExplicitWaitLambda() {
WebDriver driver = BetterWebDriverFactory.CHROME.get();
driver.get("http://www.ticketfly.com");
driver.findElement(linkText("change location")).click();
FluentWait<WebDriver> webDriverWait
= new FluentWait<>(driver)
.ignoring(NoSuchElementException.class);
WebElement location = webDriverWait.until(
(WebDriver d) ->
d.findElement(By.id("location"))
);
FluentWait<WebElement> webElementWait
= new FluentWait<>(location)
.withTimeout(30, SECONDS)
.ignoring(NoSuchElementException.class);
WebElement canada = webElementWait.until(
(WebElement element) ->
element.findElement(linkText("CANADA")));
canada.click();
WebElement ontario = webElementWait.until(
(WebElement element) ->
element.findElement(linkText("Ontario")));
ontario.click();
assertEquals("Ontario", driver
.findElement(className("tools-location"))
.findElement(tagName("a"))
.findElement(tagName("strong"))
.getText());
}
/**
* This is a clean test using page framework. It has the same function as the test above. :)
*/
@Test
public void changeLocationUsingBrowser() {
Browser browser = CHROME;
browser.get("http://www.ticketfly.com");
browser.untilFound(LinkText.CHANGE_LOCATION).click();
Element tabMenu = browser.untilFound(Id.LOCATION);
tabMenu.untilFound(LinkText.CANADA).click();
tabMenu.untilFound(LinkText.ONTARIO).click();
assertFalse(tabMenu.optionalElement(LinkText.ONTARIO).isPresent());
assertEquals("Ontario", browser.untilFound(Xpath.LOCATION).getText());
}
/**
* This is a cleaner test using page framework. It has the same function as the test above. :)
*/
@Test
public void changeLocation() {
TicketflyHomePage page = new TicketflyHomePage(CHROME);
page.open();
page.changeLocation(CANADA, ONTARIO);
assertEquals("Ontario", page.currentLocation());
}
/**
* This is a cleaner test using page framework. It has the same function as the test above. :)
*/
@Test
public void changeLocationAnonymous() {
new TicketflyEventPage(CHROME) {{
open();
changeLocation(CANADA, ONTARIO);
assertEquals("Canada", currentLocation());
}};
}
// /**
// * This method has compilation error
// */
// @Test
// public void changeLocationOnCareerPage() {
// TicketflyCareerPage page = new TicketflyCareerPage(CHROME);
// page.open();
// page.changeLocation(CANADA, ONTARIO);
// assertEquals("Ontario", page.currentLocation());
// }
}
| |
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch 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.elasticsearch.plugins;
import com.carrotsearch.randomizedtesting.annotations.ParametersFactory;
import com.google.common.jimfs.Configuration;
import com.google.common.jimfs.Jimfs;
import org.apache.lucene.util.LuceneTestCase;
import org.elasticsearch.Version;
import org.elasticsearch.cli.MockTerminal;
import org.elasticsearch.cli.Terminal;
import org.elasticsearch.cli.UserError;
import org.elasticsearch.common.SuppressForbidden;
import org.elasticsearch.common.collect.Tuple;
import org.elasticsearch.common.io.PathUtils;
import org.elasticsearch.common.io.PathUtilsForTesting;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.env.Environment;
import org.elasticsearch.test.ESTestCase;
import org.elasticsearch.test.PosixPermissionsResetter;
import org.junit.After;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.DirectoryStream;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.FileSystem;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.StandardCopyOption;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.PosixFileAttributeView;
import java.nio.file.attribute.PosixFileAttributes;
import java.nio.file.attribute.PosixFilePermission;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.not;
@LuceneTestCase.SuppressFileSystems("*")
public class InstallPluginCommandTests extends ESTestCase {
private final Function<String, Path> temp;
private final FileSystem fs;
private final boolean isPosix;
private final boolean isReal;
private final String javaIoTmpdir;
@SuppressForbidden(reason = "sets java.io.tmpdir")
public InstallPluginCommandTests(FileSystem fs, Function<String, Path> temp) {
this.fs = fs;
this.temp = temp;
this.isPosix = fs.supportedFileAttributeViews().contains("posix");
this.isReal = fs == PathUtils.getDefaultFileSystem();
PathUtilsForTesting.installMock(fs);
javaIoTmpdir = System.getProperty("java.io.tmpdir");
System.setProperty("java.io.tmpdir", temp.apply("tmpdir").toString());
}
@After
@SuppressForbidden(reason = "resets java.io.tmpdir")
public void tearDown() throws Exception {
System.setProperty("java.io.tmpdir", javaIoTmpdir);
PathUtilsForTesting.teardown();
super.tearDown();
}
@ParametersFactory
public static Iterable<Object[]> parameters() {
class Parameter {
private final FileSystem fileSystem;
private final Function<String, Path> temp;
public Parameter(FileSystem fileSystem, String root) {
this(fileSystem, s -> {
try {
return Files.createTempDirectory(fileSystem.getPath(root), s);
} catch (IOException e) {
throw new RuntimeException(e);
}
});
}
public Parameter(FileSystem fileSystem, Function<String, Path> temp) {
this.fileSystem = fileSystem;
this.temp = temp;
}
}
List<Parameter> parameters = new ArrayList<>();
parameters.add(new Parameter(Jimfs.newFileSystem(Configuration.windows()), "c:\\"));
parameters.add(new Parameter(Jimfs.newFileSystem(toPosix(Configuration.osX())), "/"));
parameters.add(new Parameter(Jimfs.newFileSystem(toPosix(Configuration.unix())), "/"));
parameters.add(new Parameter(PathUtils.getDefaultFileSystem(), LuceneTestCase::createTempDir ));
return parameters.stream().map(p -> new Object[] { p.fileSystem, p.temp }).collect(Collectors.toList());
}
private static Configuration toPosix(Configuration configuration) {
return configuration.toBuilder().setAttributeViews("basic", "owner", "posix", "unix").build();
}
/** Creates a test environment with bin, config and plugins directories. */
static Tuple<Path, Environment> createEnv(FileSystem fs, Function<String, Path> temp) throws IOException {
Path home = temp.apply("install-plugin-command-tests");
Files.createDirectories(home.resolve("bin"));
Files.createFile(home.resolve("bin").resolve("elasticsearch"));
Files.createDirectories(home.resolve("config"));
Files.createFile(home.resolve("config").resolve("elasticsearch.yml"));
Path plugins = Files.createDirectories(home.resolve("plugins"));
assertTrue(Files.exists(plugins));
Settings settings = Settings.builder()
.put("path.home", home)
.build();
return Tuple.tuple(home, new Environment(settings));
}
static Path createPluginDir(Function<String, Path> temp) throws IOException {
return temp.apply("pluginDir");
}
/** creates a fake jar file with empty class files */
static void writeJar(Path jar, String... classes) throws IOException {
try (ZipOutputStream stream = new ZipOutputStream(Files.newOutputStream(jar))) {
for (String clazz : classes) {
stream.putNextEntry(new ZipEntry(clazz + ".class")); // no package names, just support simple classes
}
}
}
static String writeZip(Path structure, String prefix) throws IOException {
Path zip = createTempDir().resolve(structure.getFileName() + ".zip");
try (ZipOutputStream stream = new ZipOutputStream(Files.newOutputStream(zip))) {
Files.walkFileTree(structure, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
String target = (prefix == null ? "" : prefix + "/") + structure.relativize(file).toString();
stream.putNextEntry(new ZipEntry(target));
Files.copy(file, stream);
return FileVisitResult.CONTINUE;
}
});
}
return zip.toUri().toURL().toString();
}
/** creates a plugin .zip and returns the url for testing */
static String createPlugin(String name, Path structure) throws IOException {
return createPlugin(name, structure, false);
}
static String createPlugin(String name, Path structure, boolean createSecurityPolicyFile) throws IOException {
PluginTestUtil.writeProperties(structure,
"description", "fake desc",
"name", name,
"version", "1.0",
"elasticsearch.version", Version.CURRENT.toString(),
"java.version", System.getProperty("java.specification.version"),
"classname", "FakePlugin");
if (createSecurityPolicyFile) {
String securityPolicyContent = "grant {\n permission java.lang.RuntimePermission \"setFactory\";\n};\n";
Files.write(structure.resolve("plugin-security.policy"), securityPolicyContent.getBytes(StandardCharsets.UTF_8));
}
writeJar(structure.resolve("plugin.jar"), "FakePlugin");
return writeZip(structure, "elasticsearch");
}
static MockTerminal installPlugin(String pluginUrl, Path home) throws Exception {
return installPlugin(pluginUrl, home, false);
}
static MockTerminal installPlugin(String pluginUrl, Path home, boolean jarHellCheck) throws Exception {
Map<String, String> settings = new HashMap<>();
settings.put("path.home", home.toString());
MockTerminal terminal = new MockTerminal();
new InstallPluginCommand() {
@Override
void jarHellCheck(Path candidate, Path pluginsDir) throws Exception {
if (jarHellCheck) {
super.jarHellCheck(candidate, pluginsDir);
}
}
}.execute(terminal, pluginUrl, true, settings);
return terminal;
}
void assertPlugin(String name, Path original, Environment env) throws IOException {
Path got = env.pluginsFile().resolve(name);
assertTrue("dir " + name + " exists", Files.exists(got));
if (isPosix) {
Set<PosixFilePermission> perms = Files.getPosixFilePermissions(got);
assertThat(
perms,
containsInAnyOrder(
PosixFilePermission.OWNER_READ,
PosixFilePermission.OWNER_WRITE,
PosixFilePermission.OWNER_EXECUTE,
PosixFilePermission.GROUP_READ,
PosixFilePermission.GROUP_EXECUTE,
PosixFilePermission.OTHERS_READ,
PosixFilePermission.OTHERS_EXECUTE));
}
assertTrue("jar was copied", Files.exists(got.resolve("plugin.jar")));
assertFalse("bin was not copied", Files.exists(got.resolve("bin")));
assertFalse("config was not copied", Files.exists(got.resolve("config")));
if (Files.exists(original.resolve("bin"))) {
Path binDir = env.binFile().resolve(name);
assertTrue("bin dir exists", Files.exists(binDir));
assertTrue("bin is a dir", Files.isDirectory(binDir));
PosixFileAttributes binAttributes = null;
if (isPosix) {
binAttributes = Files.readAttributes(env.binFile(), PosixFileAttributes.class);
}
try (DirectoryStream<Path> stream = Files.newDirectoryStream(binDir)) {
for (Path file : stream) {
assertFalse("not a dir", Files.isDirectory(file));
if (isPosix) {
PosixFileAttributes attributes = Files.readAttributes(file, PosixFileAttributes.class);
assertEquals(InstallPluginCommand.DIR_AND_EXECUTABLE_PERMS, attributes.permissions());
}
}
}
}
if (Files.exists(original.resolve("config"))) {
Path configDir = env.configFile().resolve(name);
assertTrue("config dir exists", Files.exists(configDir));
assertTrue("config is a dir", Files.isDirectory(configDir));
if (isPosix) {
Path configRoot = env.configFile();
PosixFileAttributes configAttributes =
Files.getFileAttributeView(configRoot, PosixFileAttributeView.class).readAttributes();
PosixFileAttributes attributes = Files.getFileAttributeView(configDir, PosixFileAttributeView.class).readAttributes();
assertThat(attributes.owner(), equalTo(configAttributes.owner()));
assertThat(attributes.group(), equalTo(configAttributes.group()));
}
try (DirectoryStream<Path> stream = Files.newDirectoryStream(configDir)) {
for (Path file : stream) {
assertFalse("not a dir", Files.isDirectory(file));
}
}
}
assertInstallCleaned(env);
}
void assertInstallCleaned(Environment env) throws IOException {
try (DirectoryStream<Path> stream = Files.newDirectoryStream(env.pluginsFile())) {
for (Path file : stream) {
if (file.getFileName().toString().startsWith(".installing")) {
fail("Installation dir still exists, " + file);
}
}
}
}
public void testSomethingWorks() throws Exception {
Tuple<Path, Environment> env = createEnv(fs, temp);
Path pluginDir = createPluginDir(temp);
String pluginZip = createPlugin("fake", pluginDir);
installPlugin(pluginZip, env.v1());
assertPlugin("fake", pluginDir, env.v2());
}
public void testSpaceInUrl() throws Exception {
Tuple<Path, Environment> env = createEnv(fs, temp);
Path pluginDir = createPluginDir(temp);
String pluginZip = createPlugin("fake", pluginDir);
Path pluginZipWithSpaces = createTempFile("foo bar", ".zip");
try (InputStream in = new URL(pluginZip).openStream()) {
Files.copy(in, pluginZipWithSpaces, StandardCopyOption.REPLACE_EXISTING);
}
installPlugin(pluginZipWithSpaces.toUri().toURL().toString(), env.v1());
assertPlugin("fake", pluginDir, env.v2());
}
public void testMalformedUrlNotMaven() throws Exception {
Tuple<Path, Environment> env = createEnv(fs, temp);
// has two colons, so it appears similar to maven coordinates
MalformedURLException e = expectThrows(MalformedURLException.class, () -> installPlugin("://host:1234", env.v1()));
assertTrue(e.getMessage(), e.getMessage().contains("no protocol"));
}
public void testUnknownPlugin() throws Exception {
Tuple<Path, Environment> env = createEnv(fs, temp);
UserError e = expectThrows(UserError.class, () -> installPlugin("foo", env.v1()));
assertTrue(e.getMessage(), e.getMessage().contains("Unknown plugin foo"));
}
public void testPluginsDirMissing() throws Exception {
Tuple<Path, Environment> env = createEnv(fs, temp);
Files.delete(env.v2().pluginsFile());
Path pluginDir = createPluginDir(temp);
String pluginZip = createPlugin("fake", pluginDir);
installPlugin(pluginZip, env.v1());
assertPlugin("fake", pluginDir, env.v2());
}
public void testPluginsDirReadOnly() throws Exception {
assumeTrue("posix and filesystem", isPosix && isReal);
Tuple<Path, Environment> env = createEnv(fs, temp);
Path pluginDir = createPluginDir(temp);
try (PosixPermissionsResetter pluginsAttrs = new PosixPermissionsResetter(env.v2().pluginsFile())) {
pluginsAttrs.setPermissions(new HashSet<>());
String pluginZip = createPlugin("fake", pluginDir);
IOException e = expectThrows(IOException.class, () -> installPlugin(pluginZip, env.v1()));
assertTrue(e.getMessage(), e.getMessage().contains(env.v2().pluginsFile().toString()));
}
assertInstallCleaned(env.v2());
}
public void testBuiltinModule() throws Exception {
Tuple<Path, Environment> env = createEnv(fs, temp);
Path pluginDir = createPluginDir(temp);
String pluginZip = createPlugin("lang-groovy", pluginDir);
UserError e = expectThrows(UserError.class, () -> installPlugin(pluginZip, env.v1()));
assertTrue(e.getMessage(), e.getMessage().contains("is a system module"));
assertInstallCleaned(env.v2());
}
public void testJarHell() throws Exception {
// jar hell test needs a real filesystem
assumeTrue("real filesystem", isReal);
Tuple<Path, Environment> environment = createEnv(fs, temp);
Path pluginDirectory = createPluginDir(temp);
writeJar(pluginDirectory.resolve("other.jar"), "FakePlugin");
String pluginZip = createPlugin("fake", pluginDirectory); // adds plugin.jar with FakePlugin
IllegalStateException e = expectThrows(IllegalStateException.class, () -> installPlugin(pluginZip, environment.v1(), true));
assertTrue(e.getMessage(), e.getMessage().contains("jar hell"));
assertInstallCleaned(environment.v2());
}
public void testIsolatedPlugins() throws Exception {
Tuple<Path, Environment> env = createEnv(fs, temp);
// these both share the same FakePlugin class
Path pluginDir1 = createPluginDir(temp);
String pluginZip1 = createPlugin("fake1", pluginDir1);
installPlugin(pluginZip1, env.v1());
Path pluginDir2 = createPluginDir(temp);
String pluginZip2 = createPlugin("fake2", pluginDir2);
installPlugin(pluginZip2, env.v1());
assertPlugin("fake1", pluginDir1, env.v2());
assertPlugin("fake2", pluginDir2, env.v2());
}
public void testExistingPlugin() throws Exception {
Tuple<Path, Environment> env = createEnv(fs, temp);
Path pluginDir = createPluginDir(temp);
String pluginZip = createPlugin("fake", pluginDir);
installPlugin(pluginZip, env.v1());
UserError e = expectThrows(UserError.class, () -> installPlugin(pluginZip, env.v1()));
assertTrue(e.getMessage(), e.getMessage().contains("already exists"));
assertInstallCleaned(env.v2());
}
public void testBin() throws Exception {
Tuple<Path, Environment> env = createEnv(fs, temp);
Path pluginDir = createPluginDir(temp);
Path binDir = pluginDir.resolve("bin");
Files.createDirectory(binDir);
Files.createFile(binDir.resolve("somescript"));
String pluginZip = createPlugin("fake", pluginDir);
installPlugin(pluginZip, env.v1());
assertPlugin("fake", pluginDir, env.v2());
}
public void testBinNotDir() throws Exception {
Tuple<Path, Environment> env = createEnv(fs, temp);
Path pluginDir = createPluginDir(temp);
Path binDir = pluginDir.resolve("bin");
Files.createFile(binDir);
String pluginZip = createPlugin("fake", pluginDir);
UserError e = expectThrows(UserError.class, () -> installPlugin(pluginZip, env.v1()));
assertTrue(e.getMessage(), e.getMessage().contains("not a directory"));
assertInstallCleaned(env.v2());
}
public void testBinContainsDir() throws Exception {
Tuple<Path, Environment> env = createEnv(fs, temp);
Path pluginDir = createPluginDir(temp);
Path dirInBinDir = pluginDir.resolve("bin").resolve("foo");
Files.createDirectories(dirInBinDir);
Files.createFile(dirInBinDir.resolve("somescript"));
String pluginZip = createPlugin("fake", pluginDir);
UserError e = expectThrows(UserError.class, () -> installPlugin(pluginZip, env.v1()));
assertTrue(e.getMessage(), e.getMessage().contains("Directories not allowed in bin dir for plugin"));
assertInstallCleaned(env.v2());
}
public void testBinConflict() throws Exception {
Tuple<Path, Environment> env = createEnv(fs, temp);
Path pluginDir = createPluginDir(temp);
Path binDir = pluginDir.resolve("bin");
Files.createDirectory(binDir);
Files.createFile(binDir.resolve("somescript"));
String pluginZip = createPlugin("elasticsearch", pluginDir);
FileAlreadyExistsException e = expectThrows(FileAlreadyExistsException.class, () -> installPlugin(pluginZip, env.v1()));
assertTrue(e.getMessage(), e.getMessage().contains(env.v2().binFile().resolve("elasticsearch").toString()));
assertInstallCleaned(env.v2());
}
public void testBinPermissions() throws Exception {
assumeTrue("posix filesystem", isPosix);
Tuple<Path, Environment> env = createEnv(fs, temp);
Path pluginDir = createPluginDir(temp);
Path binDir = pluginDir.resolve("bin");
Files.createDirectory(binDir);
Files.createFile(binDir.resolve("somescript"));
String pluginZip = createPlugin("fake", pluginDir);
try (PosixPermissionsResetter binAttrs = new PosixPermissionsResetter(env.v2().binFile())) {
Set<PosixFilePermission> perms = binAttrs.getCopyPermissions();
// make sure at least one execute perm is missing, so we know we forced it during installation
perms.remove(PosixFilePermission.GROUP_EXECUTE);
binAttrs.setPermissions(perms);
installPlugin(pluginZip, env.v1());
assertPlugin("fake", pluginDir, env.v2());
}
}
public void testConfig() throws Exception {
Tuple<Path, Environment> env = createEnv(fs, temp);
Path pluginDir = createPluginDir(temp);
Path configDir = pluginDir.resolve("config");
Files.createDirectory(configDir);
Files.createFile(configDir.resolve("custom.yaml"));
String pluginZip = createPlugin("fake", pluginDir);
installPlugin(pluginZip, env.v1());
assertPlugin("fake", pluginDir, env.v2());
}
public void testExistingConfig() throws Exception {
Tuple<Path, Environment> env = createEnv(fs, temp);
Path envConfigDir = env.v2().configFile().resolve("fake");
Files.createDirectories(envConfigDir);
Files.write(envConfigDir.resolve("custom.yaml"), "existing config".getBytes(StandardCharsets.UTF_8));
Path pluginDir = createPluginDir(temp);
Path configDir = pluginDir.resolve("config");
Files.createDirectory(configDir);
Files.write(configDir.resolve("custom.yaml"), "new config".getBytes(StandardCharsets.UTF_8));
Files.createFile(configDir.resolve("other.yaml"));
String pluginZip = createPlugin("fake", pluginDir);
installPlugin(pluginZip, env.v1());
assertPlugin("fake", pluginDir, env.v2());
List<String> configLines = Files.readAllLines(envConfigDir.resolve("custom.yaml"), StandardCharsets.UTF_8);
assertEquals(1, configLines.size());
assertEquals("existing config", configLines.get(0));
assertTrue(Files.exists(envConfigDir.resolve("other.yaml")));
}
public void testConfigNotDir() throws Exception {
Tuple<Path, Environment> env = createEnv(fs, temp);
Path pluginDir = createPluginDir(temp);
Path configDir = pluginDir.resolve("config");
Files.createFile(configDir);
String pluginZip = createPlugin("fake", pluginDir);
UserError e = expectThrows(UserError.class, () -> installPlugin(pluginZip, env.v1()));
assertTrue(e.getMessage(), e.getMessage().contains("not a directory"));
assertInstallCleaned(env.v2());
}
public void testConfigContainsDir() throws Exception {
Tuple<Path, Environment> env = createEnv(fs, temp);
Path pluginDir = createPluginDir(temp);
Path dirInConfigDir = pluginDir.resolve("config").resolve("foo");
Files.createDirectories(dirInConfigDir);
Files.createFile(dirInConfigDir.resolve("myconfig.yml"));
String pluginZip = createPlugin("fake", pluginDir);
UserError e = expectThrows(UserError.class, () -> installPlugin(pluginZip, env.v1()));
assertTrue(e.getMessage(), e.getMessage().contains("Directories not allowed in config dir for plugin"));
assertInstallCleaned(env.v2());
}
public void testConfigConflict() throws Exception {
Tuple<Path, Environment> env = createEnv(fs, temp);
Path pluginDir = createPluginDir(temp);
Path configDir = pluginDir.resolve("config");
Files.createDirectory(configDir);
Files.createFile(configDir.resolve("myconfig.yml"));
String pluginZip = createPlugin("elasticsearch.yml", pluginDir);
FileAlreadyExistsException e = expectThrows(FileAlreadyExistsException.class, () -> installPlugin(pluginZip, env.v1()));
assertTrue(e.getMessage(), e.getMessage().contains(env.v2().configFile().resolve("elasticsearch.yml").toString()));
assertInstallCleaned(env.v2());
}
public void testMissingDescriptor() throws Exception {
Tuple<Path, Environment> env = createEnv(fs, temp);
Path pluginDir = createPluginDir(temp);
Files.createFile(pluginDir.resolve("fake.yml"));
String pluginZip = writeZip(pluginDir, "elasticsearch");
NoSuchFileException e = expectThrows(NoSuchFileException.class, () -> installPlugin(pluginZip, env.v1()));
assertTrue(e.getMessage(), e.getMessage().contains("plugin-descriptor.properties"));
assertInstallCleaned(env.v2());
}
public void testMissingDirectory() throws Exception {
Tuple<Path, Environment> env = createEnv(fs, temp);
Path pluginDir = createPluginDir(temp);
Files.createFile(pluginDir.resolve(PluginInfo.ES_PLUGIN_PROPERTIES));
String pluginZip = writeZip(pluginDir, null);
UserError e = expectThrows(UserError.class, () -> installPlugin(pluginZip, env.v1()));
assertTrue(e.getMessage(), e.getMessage().contains("`elasticsearch` directory is missing in the plugin zip"));
assertInstallCleaned(env.v2());
}
public void testZipRelativeOutsideEntryName() throws Exception {
Tuple<Path, Environment> env = createEnv(fs, temp);
Path zip = createTempDir().resolve("broken.zip");
try (ZipOutputStream stream = new ZipOutputStream(Files.newOutputStream(zip))) {
stream.putNextEntry(new ZipEntry("elasticsearch/../blah"));
}
String pluginZip = zip.toUri().toURL().toString();
IOException e = expectThrows(IOException.class, () -> installPlugin(pluginZip, env.v1()));
assertTrue(e.getMessage(), e.getMessage().contains("resolving outside of plugin directory"));
}
public void testOfficialPluginsHelpSorted() throws Exception {
MockTerminal terminal = new MockTerminal();
new InstallPluginCommand().main(new String[] { "--help" }, terminal);
try (BufferedReader reader = new BufferedReader(new StringReader(terminal.getOutput()))) {
String line = reader.readLine();
// first find the beginning of our list of official plugins
while (line.endsWith("may be installed by name:") == false) {
line = reader.readLine();
}
// now check each line compares greater than the last, until we reach an empty line
String prev = reader.readLine();
line = reader.readLine();
while (line != null && line.trim().isEmpty() == false) {
assertTrue(prev + " < " + line, prev.compareTo(line) < 0);
prev = line;
line = reader.readLine();
}
}
}
public void testOfficialPluginsIncludesXpack() throws Exception {
MockTerminal terminal = new MockTerminal();
new InstallPluginCommand().main(new String[] { "--help" }, terminal);
assertTrue(terminal.getOutput(), terminal.getOutput().contains("x-pack"));
}
public void testInstallMisspelledOfficialPlugins() throws Exception {
Tuple<Path, Environment> env = createEnv(fs, temp);
UserError e = expectThrows(UserError.class, () -> installPlugin("xpack", env.v1()));
assertThat(e.getMessage(), containsString("Unknown plugin xpack, did you mean [x-pack]?"));
e = expectThrows(UserError.class, () -> installPlugin("analysis-smartnc", env.v1()));
assertThat(e.getMessage(), containsString("Unknown plugin analysis-smartnc, did you mean [analysis-smartcn]?"));
e = expectThrows(UserError.class, () -> installPlugin("repository", env.v1()));
assertThat(e.getMessage(), containsString("Unknown plugin repository, did you mean any of [repository-s3, repository-gcs]?"));
e = expectThrows(UserError.class, () -> installPlugin("unknown_plugin", env.v1()));
assertThat(e.getMessage(), containsString("Unknown plugin unknown_plugin"));
}
public void testBatchFlag() throws Exception {
MockTerminal terminal = new MockTerminal();
installPlugin(terminal, true);
assertThat(terminal.getOutput(), containsString("WARNING: plugin requires additional permissions"));
}
public void testQuietFlagDisabled() throws Exception {
MockTerminal terminal = new MockTerminal();
terminal.setVerbosity(randomFrom(Terminal.Verbosity.NORMAL, Terminal.Verbosity.VERBOSE));
installPlugin(terminal, false);
assertThat(terminal.getOutput(), containsString("100%"));
}
public void testQuietFlagEnabled() throws Exception {
MockTerminal terminal = new MockTerminal();
terminal.setVerbosity(Terminal.Verbosity.SILENT);
installPlugin(terminal, false);
assertThat(terminal.getOutput(), not(containsString("100%")));
}
private void installPlugin(MockTerminal terminal, boolean isBatch) throws Exception {
Tuple<Path, Environment> env = createEnv(fs, temp);
Path pluginDir = createPluginDir(temp);
// if batch is enabled, we also want to add a security policy
String pluginZip = createPlugin("fake", pluginDir, isBatch);
Map<String, String> settings = new HashMap<>();
settings.put("path.home", env.v1().toString());
new InstallPluginCommand() {
@Override
void jarHellCheck(Path candidate, Path pluginsDir) throws Exception {
}
}.execute(terminal, pluginZip, isBatch, settings);
}
// TODO: test checksum (need maven/official below)
// TODO: test maven, official, and staging install...need tests with fixtures...
}
| |
/**
* 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.nutch.crawl;
import java.io.*;
import java.util.*;
import java.util.Map.Entry;
import org.apache.hadoop.io.*;
import org.apache.nutch.util.*;
/* The crawl state of a url. */
public class CrawlDatum implements WritableComparable<CrawlDatum>, Cloneable {
public static final String GENERATE_DIR_NAME = "crawl_generate";
public static final String FETCH_DIR_NAME = "crawl_fetch";
public static final String PARSE_DIR_NAME = "crawl_parse";
private final static byte CUR_VERSION = 7;
/** Compatibility values for on-the-fly conversion from versions < 5. */
private static final byte OLD_STATUS_SIGNATURE = 0;
private static final byte OLD_STATUS_DB_UNFETCHED = 1;
private static final byte OLD_STATUS_DB_FETCHED = 2;
private static final byte OLD_STATUS_DB_GONE = 3;
private static final byte OLD_STATUS_LINKED = 4;
private static final byte OLD_STATUS_FETCH_SUCCESS = 5;
private static final byte OLD_STATUS_FETCH_RETRY = 6;
private static final byte OLD_STATUS_FETCH_GONE = 7;
private static HashMap<Byte, Byte> oldToNew = new HashMap<Byte, Byte>();
/** Page was not fetched yet. */
public static final byte STATUS_DB_UNFETCHED = 0x01;
/** Page was successfully fetched. */
public static final byte STATUS_DB_FETCHED = 0x02;
/** Page no longer exists. */
public static final byte STATUS_DB_GONE = 0x03;
/** Page temporarily redirects to other page. */
public static final byte STATUS_DB_REDIR_TEMP = 0x04;
/** Page permanently redirects to other page. */
public static final byte STATUS_DB_REDIR_PERM = 0x05;
/** Page was successfully fetched and found not modified. */
public static final byte STATUS_DB_NOTMODIFIED = 0x06;
/** Maximum value of DB-related status. */
public static final byte STATUS_DB_MAX = 0x1f;
/** Fetching was successful. */
public static final byte STATUS_FETCH_SUCCESS = 0x21;
/** Fetching unsuccessful, needs to be retried (transient errors). */
public static final byte STATUS_FETCH_RETRY = 0x22;
/** Fetching temporarily redirected to other page. */
public static final byte STATUS_FETCH_REDIR_TEMP = 0x23;
/** Fetching permanently redirected to other page. */
public static final byte STATUS_FETCH_REDIR_PERM = 0x24;
/** Fetching unsuccessful - page is gone. */
public static final byte STATUS_FETCH_GONE = 0x25;
/** Fetching successful - page is not modified. */
public static final byte STATUS_FETCH_NOTMODIFIED = 0x26;
/** Maximum value of fetch-related status. */
public static final byte STATUS_FETCH_MAX = 0x3f;
/** Page signature. */
public static final byte STATUS_SIGNATURE = 0x41;
/** Page was newly injected. */
public static final byte STATUS_INJECTED = 0x42;
/** Page discovered through a link. */
public static final byte STATUS_LINKED = 0x43;
/** Page got metadata from a parser */
public static final byte STATUS_PARSE_META = 0x44;
public static final HashMap<Byte, String> statNames = new HashMap<Byte, String>();
static {
statNames.put(STATUS_DB_UNFETCHED, "db_unfetched");
statNames.put(STATUS_DB_FETCHED, "db_fetched");
statNames.put(STATUS_DB_GONE, "db_gone");
statNames.put(STATUS_DB_REDIR_TEMP, "db_redir_temp");
statNames.put(STATUS_DB_REDIR_PERM, "db_redir_perm");
statNames.put(STATUS_DB_NOTMODIFIED, "db_notmodified");
statNames.put(STATUS_SIGNATURE, "signature");
statNames.put(STATUS_INJECTED, "injected");
statNames.put(STATUS_LINKED, "linked");
statNames.put(STATUS_FETCH_SUCCESS, "fetch_success");
statNames.put(STATUS_FETCH_RETRY, "fetch_retry");
statNames.put(STATUS_FETCH_REDIR_TEMP, "fetch_redir_temp");
statNames.put(STATUS_FETCH_REDIR_PERM, "fetch_redir_perm");
statNames.put(STATUS_FETCH_GONE, "fetch_gone");
statNames.put(STATUS_FETCH_NOTMODIFIED, "fetch_notmodified");
statNames.put(STATUS_PARSE_META, "parse_metadata");
oldToNew.put(OLD_STATUS_DB_UNFETCHED, STATUS_DB_UNFETCHED);
oldToNew.put(OLD_STATUS_DB_FETCHED, STATUS_DB_FETCHED);
oldToNew.put(OLD_STATUS_DB_GONE, STATUS_DB_GONE);
oldToNew.put(OLD_STATUS_FETCH_GONE, STATUS_FETCH_GONE);
oldToNew.put(OLD_STATUS_FETCH_SUCCESS, STATUS_FETCH_SUCCESS);
oldToNew.put(OLD_STATUS_FETCH_RETRY, STATUS_FETCH_RETRY);
oldToNew.put(OLD_STATUS_LINKED, STATUS_LINKED);
oldToNew.put(OLD_STATUS_SIGNATURE, STATUS_SIGNATURE);
}
private byte status;
private long fetchTime = System.currentTimeMillis();
private byte retries;
private int fetchInterval;
private float score = 0.0f;
private byte[] signature = null;
private long modifiedTime;
private org.apache.hadoop.io.MapWritable metaData;
public static boolean hasDbStatus(CrawlDatum datum) {
if (datum.status <= STATUS_DB_MAX) return true;
return false;
}
public static boolean hasFetchStatus(CrawlDatum datum) {
if (datum.status > STATUS_DB_MAX && datum.status <= STATUS_FETCH_MAX) return true;
return false;
}
public CrawlDatum() { }
public CrawlDatum(int status, int fetchInterval) {
this();
this.status = (byte)status;
this.fetchInterval = fetchInterval;
}
public CrawlDatum(int status, int fetchInterval, float score) {
this(status, fetchInterval);
this.score = score;
}
//
// accessor methods
//
public byte getStatus() { return status; }
public static String getStatusName(byte value) {
String res = statNames.get(value);
if (res == null) res = "unknown";
return res;
}
public void setStatus(int status) { this.status = (byte)status; }
/**
* Returns either the time of the last fetch, or the next fetch time,
* depending on whether Fetcher or CrawlDbReducer set the time.
*/
public long getFetchTime() { return fetchTime; }
/**
* Sets either the time of the last fetch or the next fetch time,
* depending on whether Fetcher or CrawlDbReducer set the time.
*/
public void setFetchTime(long fetchTime) { this.fetchTime = fetchTime; }
public long getModifiedTime() {
return modifiedTime;
}
public void setModifiedTime(long modifiedTime) {
this.modifiedTime = modifiedTime;
}
public byte getRetriesSinceFetch() { return retries; }
public void setRetriesSinceFetch(int retries) {this.retries = (byte)retries;}
public int getFetchInterval() { return fetchInterval; }
public void setFetchInterval(int fetchInterval) {
this.fetchInterval = fetchInterval;
}
public void setFetchInterval(float fetchInterval) {
this.fetchInterval = Math.round(fetchInterval);
}
public float getScore() { return score; }
public void setScore(float score) { this.score = score; }
public byte[] getSignature() {
return signature;
}
public void setSignature(byte[] signature) {
if (signature != null && signature.length > 256)
throw new RuntimeException("Max signature length (256) exceeded: " + signature.length);
this.signature = signature;
}
public void setMetaData(org.apache.hadoop.io.MapWritable mapWritable) {
this.metaData = new org.apache.hadoop.io.MapWritable(mapWritable);
}
/** Add all metadata from other CrawlDatum to this CrawlDatum.
*
* @param other CrawlDatum
*/
public void putAllMetaData(CrawlDatum other) {
for (Entry<Writable, Writable> e : other.getMetaData().entrySet()) {
getMetaData().put(e.getKey(), e.getValue());
}
}
/**
* returns a MapWritable if it was set or read in @see readFields(DataInput),
* returns empty map in case CrawlDatum was freshly created (lazily instantiated).
*/
public org.apache.hadoop.io.MapWritable getMetaData() {
if (this.metaData == null) this.metaData = new org.apache.hadoop.io.MapWritable();
return this.metaData;
}
//
// writable methods
//
public static CrawlDatum read(DataInput in) throws IOException {
CrawlDatum result = new CrawlDatum();
result.readFields(in);
return result;
}
public void readFields(DataInput in) throws IOException {
byte version = in.readByte(); // read version
if (version > CUR_VERSION) // check version
throw new VersionMismatchException(CUR_VERSION, version);
status = in.readByte();
fetchTime = in.readLong();
retries = in.readByte();
if (version > 5) {
fetchInterval = in.readInt();
} else fetchInterval = Math.round(in.readFloat());
score = in.readFloat();
if (version > 2) {
modifiedTime = in.readLong();
int cnt = in.readByte();
if (cnt > 0) {
signature = new byte[cnt];
in.readFully(signature);
} else signature = null;
}
if (version > 3) {
boolean hasMetadata = false;
if (version < 7) {
org.apache.hadoop.io.MapWritable oldMetaData = new org.apache.hadoop.io.MapWritable();
if (in.readBoolean()) {
hasMetadata = true;
metaData = new org.apache.hadoop.io.MapWritable();
oldMetaData.readFields(in);
}
for (Writable key : oldMetaData.keySet()) {
metaData.put(key, oldMetaData.get(key));
}
} else {
if (in.readBoolean()) {
hasMetadata = true;
metaData = new org.apache.hadoop.io.MapWritable();
metaData.readFields(in);
}
}
if (hasMetadata==false) metaData = null;
}
// translate status codes
if (version < 5) {
if (oldToNew.containsKey(status))
status = oldToNew.get(status);
else
status = STATUS_DB_UNFETCHED;
}
}
/** The number of bytes into a CrawlDatum that the score is stored. */
private static final int SCORE_OFFSET = 1 + 1 + 8 + 1 + 4;
private static final int SIG_OFFSET = SCORE_OFFSET + 4 + 8;
public void write(DataOutput out) throws IOException {
out.writeByte(CUR_VERSION); // store current version
out.writeByte(status);
out.writeLong(fetchTime);
out.writeByte(retries);
out.writeInt(fetchInterval);
out.writeFloat(score);
out.writeLong(modifiedTime);
if (signature == null) {
out.writeByte(0);
} else {
out.writeByte(signature.length);
out.write(signature);
}
if (metaData != null && metaData.size() > 0) {
out.writeBoolean(true);
metaData.write(out);
} else {
out.writeBoolean(false);
}
}
/** Copy the contents of another instance into this instance. */
public void set(CrawlDatum that) {
this.status = that.status;
this.fetchTime = that.fetchTime;
this.retries = that.retries;
this.fetchInterval = that.fetchInterval;
this.score = that.score;
this.modifiedTime = that.modifiedTime;
this.signature = that.signature;
if (that.metaData != null) {
this.metaData = new org.apache.hadoop.io.MapWritable(that.metaData); // make a deep copy
} else {
this.metaData = null;
}
}
//
// compare methods
//
/** Sort by decreasing score. */
public int compareTo(CrawlDatum that) {
if (that.score != this.score)
return (that.score - this.score) > 0 ? 1 : -1;
if (that.status != this.status)
return this.status - that.status;
if (that.fetchTime != this.fetchTime)
return (that.fetchTime - this.fetchTime) > 0 ? 1 : -1;
if (that.retries != this.retries)
return that.retries - this.retries;
if (that.fetchInterval != this.fetchInterval)
return (that.fetchInterval - this.fetchInterval) > 0 ? 1 : -1;
if (that.modifiedTime != this.modifiedTime)
return (that.modifiedTime - this.modifiedTime) > 0 ? 1 : -1;
return SignatureComparator._compare(this, that);
}
/** A Comparator optimized for CrawlDatum. */
public static class Comparator extends WritableComparator {
public Comparator() { super(CrawlDatum.class); }
public int compare(byte[] b1, int s1, int l1, byte[] b2, int s2, int l2) {
float score1 = readFloat(b1,s1+SCORE_OFFSET);
float score2 = readFloat(b2,s2+SCORE_OFFSET);
if (score2 != score1) {
return (score2 - score1) > 0 ? 1 : -1;
}
int status1 = b1[s1+1];
int status2 = b2[s2+1];
if (status2 != status1)
return status1 - status2;
long fetchTime1 = readLong(b1, s1+1+1);
long fetchTime2 = readLong(b2, s2+1+1);
if (fetchTime2 != fetchTime1)
return (fetchTime2 - fetchTime1) > 0 ? 1 : -1;
int retries1 = b1[s1+1+1+8];
int retries2 = b2[s2+1+1+8];
if (retries2 != retries1)
return retries2 - retries1;
int fetchInterval1 = readInt(b1, s1+1+1+8+1);
int fetchInterval2 = readInt(b2, s2+1+1+8+1);
if (fetchInterval2 != fetchInterval1)
return (fetchInterval2 - fetchInterval1) > 0 ? 1 : -1;
long modifiedTime1 = readLong(b1, s1 + SCORE_OFFSET + 4);
long modifiedTime2 = readLong(b2, s2 + SCORE_OFFSET + 4);
if (modifiedTime2 != modifiedTime1)
return (modifiedTime2 - modifiedTime1) > 0 ? 1 : -1;
int sigl1 = b1[s1+SIG_OFFSET];
int sigl2 = b2[s2+SIG_OFFSET];
return SignatureComparator._compare(b1, SIG_OFFSET, sigl1, b2, SIG_OFFSET, sigl2);
}
}
static { // register this comparator
WritableComparator.define(CrawlDatum.class, new Comparator());
}
//
// basic methods
//
public String toString() {
StringBuilder buf = new StringBuilder();
buf.append("Version: " + CUR_VERSION + "\n");
buf.append("Status: " + getStatus() + " (" + getStatusName(getStatus()) + ")\n");
buf.append("Fetch time: " + new Date(getFetchTime()) + "\n");
buf.append("Modified time: " + new Date(getModifiedTime()) + "\n");
buf.append("Retries since fetch: " + getRetriesSinceFetch() + "\n");
buf.append("Retry interval: " + getFetchInterval() + " seconds (" +
(getFetchInterval() / FetchSchedule.SECONDS_PER_DAY) + " days)\n");
buf.append("Score: " + getScore() + "\n");
buf.append("Signature: " + StringUtil.toHexString(getSignature()) + "\n");
buf.append("Metadata: ");
if (metaData != null) {
for (Entry<Writable, Writable> e : metaData.entrySet()) {
buf.append(e.getKey());
buf.append(": ");
buf.append(e.getValue());
}
}
buf.append('\n');
return buf.toString();
}
private boolean metadataEquals(org.apache.hadoop.io.MapWritable otherMetaData) {
if (metaData==null || metaData.size() ==0) {
return otherMetaData == null || otherMetaData.size() == 0;
}
if (otherMetaData == null) {
// we already know that the current object is not null or empty
return false;
}
HashSet<Entry<Writable, Writable>> set1 =
new HashSet<Entry<Writable,Writable>>(metaData.entrySet());
HashSet<Entry<Writable, Writable>> set2 =
new HashSet<Entry<Writable,Writable>>(otherMetaData.entrySet());
return set1.equals(set2);
}
public boolean equals(Object o) {
if (!(o instanceof CrawlDatum))
return false;
CrawlDatum other = (CrawlDatum)o;
boolean res =
(this.status == other.status) &&
(this.fetchTime == other.fetchTime) &&
(this.modifiedTime == other.modifiedTime) &&
(this.retries == other.retries) &&
(this.fetchInterval == other.fetchInterval) &&
(SignatureComparator._compare(this.signature, other.signature) == 0) &&
(this.score == other.score);
if (!res) return res;
return metadataEquals(other.metaData);
}
public int hashCode() {
int res = 0;
if (signature != null) {
for (int i = 0; i < signature.length / 4; i += 4) {
res ^= (int)(signature[i] << 24 + signature[i+1] << 16 +
signature[i+2] << 8 + signature[i+3]);
}
}
if (metaData != null) {
res ^= metaData.entrySet().hashCode();
}
return
res ^ status ^
((int)fetchTime) ^
((int)modifiedTime) ^
retries ^
fetchInterval ^
Float.floatToIntBits(score);
}
public Object clone() {
try {
return super.clone();
} catch (CloneNotSupportedException e) {
throw new RuntimeException(e);
}
}
}
| |
/**
* <copyright>
* </copyright>
*
* $Id$
*/
package org.wso2.developerstudio.eclipse.gmf.esb.impl;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.notify.NotificationChain;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.ecore.impl.ENotificationImpl;
import org.wso2.developerstudio.eclipse.gmf.esb.CallTemplateParameter;
import org.wso2.developerstudio.eclipse.gmf.esb.EsbPackage;
import org.wso2.developerstudio.eclipse.gmf.esb.NamespacedProperty;
import org.wso2.developerstudio.eclipse.gmf.esb.RuleOptionType;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Call Template Parameter</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* </p>
* <ul>
* <li>{@link org.wso2.developerstudio.eclipse.gmf.esb.impl.CallTemplateParameterImpl#getParameterName <em>Parameter Name</em>}</li>
* <li>{@link org.wso2.developerstudio.eclipse.gmf.esb.impl.CallTemplateParameterImpl#getTemplateParameterType <em>Template Parameter Type</em>}</li>
* <li>{@link org.wso2.developerstudio.eclipse.gmf.esb.impl.CallTemplateParameterImpl#getParameterValue <em>Parameter Value</em>}</li>
* <li>{@link org.wso2.developerstudio.eclipse.gmf.esb.impl.CallTemplateParameterImpl#getParameterExpression <em>Parameter Expression</em>}</li>
* </ul>
*
* @generated
*/
public class CallTemplateParameterImpl extends EsbNodeImpl implements CallTemplateParameter {
/**
* The default value of the '{@link #getParameterName() <em>Parameter Name</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getParameterName()
* @generated
* @ordered
*/
protected static final String PARAMETER_NAME_EDEFAULT = null;
/**
* The cached value of the '{@link #getParameterName() <em>Parameter Name</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getParameterName()
* @generated
* @ordered
*/
protected String parameterName = PARAMETER_NAME_EDEFAULT;
/**
* The default value of the '{@link #getTemplateParameterType() <em>Template Parameter Type</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getTemplateParameterType()
* @generated
* @ordered
*/
protected static final RuleOptionType TEMPLATE_PARAMETER_TYPE_EDEFAULT = RuleOptionType.VALUE;
/**
* The cached value of the '{@link #getTemplateParameterType() <em>Template Parameter Type</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getTemplateParameterType()
* @generated
* @ordered
*/
protected RuleOptionType templateParameterType = TEMPLATE_PARAMETER_TYPE_EDEFAULT;
/**
* The default value of the '{@link #getParameterValue() <em>Parameter Value</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getParameterValue()
* @generated
* @ordered
*/
protected static final String PARAMETER_VALUE_EDEFAULT = null;
/**
* The cached value of the '{@link #getParameterValue() <em>Parameter Value</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getParameterValue()
* @generated
* @ordered
*/
protected String parameterValue = PARAMETER_VALUE_EDEFAULT;
/**
* The cached value of the '{@link #getParameterExpression() <em>Parameter Expression</em>}' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getParameterExpression()
* @generated
* @ordered
*/
protected NamespacedProperty parameterExpression;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected CallTemplateParameterImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return EsbPackage.Literals.CALL_TEMPLATE_PARAMETER;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String getParameterName() {
return parameterName;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setParameterName(String newParameterName) {
String oldParameterName = parameterName;
parameterName = newParameterName;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, EsbPackage.CALL_TEMPLATE_PARAMETER__PARAMETER_NAME, oldParameterName, parameterName));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public RuleOptionType getTemplateParameterType() {
return templateParameterType;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setTemplateParameterType(RuleOptionType newTemplateParameterType) {
RuleOptionType oldTemplateParameterType = templateParameterType;
templateParameterType = newTemplateParameterType == null ? TEMPLATE_PARAMETER_TYPE_EDEFAULT : newTemplateParameterType;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, EsbPackage.CALL_TEMPLATE_PARAMETER__TEMPLATE_PARAMETER_TYPE, oldTemplateParameterType, templateParameterType));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String getParameterValue() {
return parameterValue;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setParameterValue(String newParameterValue) {
String oldParameterValue = parameterValue;
parameterValue = newParameterValue;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, EsbPackage.CALL_TEMPLATE_PARAMETER__PARAMETER_VALUE, oldParameterValue, parameterValue));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NamespacedProperty getParameterExpression() {
return parameterExpression;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NotificationChain basicSetParameterExpression(NamespacedProperty newParameterExpression, NotificationChain msgs) {
NamespacedProperty oldParameterExpression = parameterExpression;
parameterExpression = newParameterExpression;
if (eNotificationRequired()) {
ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, EsbPackage.CALL_TEMPLATE_PARAMETER__PARAMETER_EXPRESSION, oldParameterExpression, newParameterExpression);
if (msgs == null) msgs = notification; else msgs.add(notification);
}
return msgs;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setParameterExpression(NamespacedProperty newParameterExpression) {
if (newParameterExpression != parameterExpression) {
NotificationChain msgs = null;
if (parameterExpression != null)
msgs = ((InternalEObject)parameterExpression).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - EsbPackage.CALL_TEMPLATE_PARAMETER__PARAMETER_EXPRESSION, null, msgs);
if (newParameterExpression != null)
msgs = ((InternalEObject)newParameterExpression).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - EsbPackage.CALL_TEMPLATE_PARAMETER__PARAMETER_EXPRESSION, null, msgs);
msgs = basicSetParameterExpression(newParameterExpression, msgs);
if (msgs != null) msgs.dispatch();
}
else if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, EsbPackage.CALL_TEMPLATE_PARAMETER__PARAMETER_EXPRESSION, newParameterExpression, newParameterExpression));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) {
switch (featureID) {
case EsbPackage.CALL_TEMPLATE_PARAMETER__PARAMETER_EXPRESSION:
return basicSetParameterExpression(null, msgs);
}
return super.eInverseRemove(otherEnd, featureID, msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case EsbPackage.CALL_TEMPLATE_PARAMETER__PARAMETER_NAME:
return getParameterName();
case EsbPackage.CALL_TEMPLATE_PARAMETER__TEMPLATE_PARAMETER_TYPE:
return getTemplateParameterType();
case EsbPackage.CALL_TEMPLATE_PARAMETER__PARAMETER_VALUE:
return getParameterValue();
case EsbPackage.CALL_TEMPLATE_PARAMETER__PARAMETER_EXPRESSION:
return getParameterExpression();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case EsbPackage.CALL_TEMPLATE_PARAMETER__PARAMETER_NAME:
setParameterName((String)newValue);
return;
case EsbPackage.CALL_TEMPLATE_PARAMETER__TEMPLATE_PARAMETER_TYPE:
setTemplateParameterType((RuleOptionType)newValue);
return;
case EsbPackage.CALL_TEMPLATE_PARAMETER__PARAMETER_VALUE:
setParameterValue((String)newValue);
return;
case EsbPackage.CALL_TEMPLATE_PARAMETER__PARAMETER_EXPRESSION:
setParameterExpression((NamespacedProperty)newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID) {
switch (featureID) {
case EsbPackage.CALL_TEMPLATE_PARAMETER__PARAMETER_NAME:
setParameterName(PARAMETER_NAME_EDEFAULT);
return;
case EsbPackage.CALL_TEMPLATE_PARAMETER__TEMPLATE_PARAMETER_TYPE:
setTemplateParameterType(TEMPLATE_PARAMETER_TYPE_EDEFAULT);
return;
case EsbPackage.CALL_TEMPLATE_PARAMETER__PARAMETER_VALUE:
setParameterValue(PARAMETER_VALUE_EDEFAULT);
return;
case EsbPackage.CALL_TEMPLATE_PARAMETER__PARAMETER_EXPRESSION:
setParameterExpression((NamespacedProperty)null);
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case EsbPackage.CALL_TEMPLATE_PARAMETER__PARAMETER_NAME:
return PARAMETER_NAME_EDEFAULT == null ? parameterName != null : !PARAMETER_NAME_EDEFAULT.equals(parameterName);
case EsbPackage.CALL_TEMPLATE_PARAMETER__TEMPLATE_PARAMETER_TYPE:
return templateParameterType != TEMPLATE_PARAMETER_TYPE_EDEFAULT;
case EsbPackage.CALL_TEMPLATE_PARAMETER__PARAMETER_VALUE:
return PARAMETER_VALUE_EDEFAULT == null ? parameterValue != null : !PARAMETER_VALUE_EDEFAULT.equals(parameterValue);
case EsbPackage.CALL_TEMPLATE_PARAMETER__PARAMETER_EXPRESSION:
return parameterExpression != null;
}
return super.eIsSet(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String toString() {
if (eIsProxy()) return super.toString();
StringBuffer result = new StringBuffer(super.toString());
result.append(" (parameterName: ");
result.append(parameterName);
result.append(", templateParameterType: ");
result.append(templateParameterType);
result.append(", parameterValue: ");
result.append(parameterValue);
result.append(')');
return result.toString();
}
} //CallTemplateParameterImpl
| |
/*
* Copyright 2013 Google Inc.
* Copyright 2014 Andreas Schildbach
*
* 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.spreadcoinj.wallet;
import org.spreadcoinj.core.Coin;
import org.spreadcoinj.core.NetworkParameters;
import org.spreadcoinj.core.Transaction;
import org.spreadcoinj.core.TransactionConfidence;
import org.spreadcoinj.core.TransactionInput;
import org.spreadcoinj.core.TransactionOutput;
import org.spreadcoinj.core.Wallet;
import org.spreadcoinj.script.ScriptChunk;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nullable;
import java.util.List;
import static com.google.common.base.Preconditions.checkState;
/**
* <p>The default risk analysis. Currently, it only is concerned with whether a tx/dependency is non-final or not, and
* whether a tx/dependency violates the dust rules. Outside of specialised protocols you should not encounter non-final
* transactions.</p>
*/
public class DefaultRiskAnalysis implements RiskAnalysis {
private static final Logger log = LoggerFactory.getLogger(DefaultRiskAnalysis.class);
/**
* Any standard output smaller than this value (in satoshis) will be considered risky, as it's most likely be
* rejected by the network. Currently it's 546 satoshis. This is different from {@link Transaction#MIN_NONDUST_OUTPUT}
* because of an upcoming fee change in Bitcoin Core 0.9.
*/
public static final Coin MIN_ANALYSIS_NONDUST_OUTPUT = Coin.valueOf(546);
protected final Transaction tx;
protected final List<Transaction> dependencies;
protected final Wallet wallet;
private Transaction nonStandard;
protected Transaction nonFinal;
protected boolean analyzed;
private DefaultRiskAnalysis(Wallet wallet, Transaction tx, List<Transaction> dependencies) {
this.tx = tx;
this.dependencies = dependencies;
this.wallet = wallet;
}
@Override
public Result analyze() {
checkState(!analyzed);
analyzed = true;
Result result = analyzeIsFinal();
if (result != Result.OK)
return result;
return analyzeIsStandard();
}
private Result analyzeIsFinal() {
// Transactions we create ourselves are, by definition, not at risk of double spending against us.
if (tx.getConfidence().getSource() == TransactionConfidence.Source.SELF)
return Result.OK;
final int height = wallet.getLastBlockSeenHeight();
final long time = wallet.getLastBlockSeenTimeSecs();
// If the transaction has a lock time specified in blocks, we consider that if the tx would become final in the
// next block it is not risky (as it would confirm normally).
final int adjustedHeight = height + 1;
if (!tx.isFinal(adjustedHeight, time)) {
nonFinal = tx;
return Result.NON_FINAL;
}
for (Transaction dep : dependencies) {
if (!dep.isFinal(adjustedHeight, time)) {
nonFinal = dep;
return Result.NON_FINAL;
}
}
return Result.OK;
}
/**
* The reason a transaction is considered non-standard, returned by
* {@link #isStandard(org.spreadcoinj.core.Transaction)}.
*/
public enum RuleViolation {
NONE,
VERSION,
DUST,
SHORTEST_POSSIBLE_PUSHDATA,
NONEMPTY_STACK // Not yet implemented (for post 0.12)
}
/**
* <p>Checks if a transaction is considered "standard" by the reference client's IsStandardTx and AreInputsStandard
* functions.</p>
*
* <p>Note that this method currently only implements a minimum of checks. More to be added later.</p>
*/
public static RuleViolation isStandard(Transaction tx) {
// TODO: Finish this function off.
if (tx.getVersion() > 1 || tx.getVersion() < 1) {
log.warn("TX considered non-standard due to unknown version number {}", tx.getVersion());
return RuleViolation.VERSION;
}
final List<TransactionOutput> outputs = tx.getOutputs();
for (int i = 0; i < outputs.size(); i++) {
TransactionOutput output = outputs.get(i);
RuleViolation violation = isOutputStandard(output);
if (violation != RuleViolation.NONE) {
log.warn("TX considered non-standard due to output {} violating rule {}", i, violation);
return violation;
}
}
final List<TransactionInput> inputs = tx.getInputs();
for (int i = 0; i < inputs.size(); i++) {
TransactionInput input = inputs.get(i);
RuleViolation violation = isInputStandard(input);
if (violation != RuleViolation.NONE) {
log.warn("TX considered non-standard due to input {} violating rule {}", i, violation);
return violation;
}
}
return RuleViolation.NONE;
}
/**
* Checks the output to see if the script violates a standardness rule. Not complete.
*/
public static RuleViolation isOutputStandard(TransactionOutput output) {
if (output.getValue().compareTo(MIN_ANALYSIS_NONDUST_OUTPUT) < 0)
return RuleViolation.DUST;
for (ScriptChunk chunk : output.getScriptPubKey().getChunks()) {
if (chunk.isPushData() && !chunk.isShortestPossiblePushData())
return RuleViolation.SHORTEST_POSSIBLE_PUSHDATA;
}
return RuleViolation.NONE;
}
/** Checks if the given input passes some of the AreInputsStandard checks. Not complete. */
public static RuleViolation isInputStandard(TransactionInput input) {
for (ScriptChunk chunk : input.getScriptSig().getChunks()) {
if (chunk.data != null && !chunk.isShortestPossiblePushData())
return RuleViolation.SHORTEST_POSSIBLE_PUSHDATA;
}
return RuleViolation.NONE;
}
private Result analyzeIsStandard() {
// The IsStandard rules don't apply on testnet, because they're just a safety mechanism and we don't want to
// crush innovation with valueless test coins.
if (!wallet.getNetworkParameters().getId().equals(NetworkParameters.ID_MAINNET))
return Result.OK;
RuleViolation ruleViolation = isStandard(tx);
if (ruleViolation != RuleViolation.NONE) {
nonStandard = tx;
return Result.NON_STANDARD;
}
for (Transaction dep : dependencies) {
ruleViolation = isStandard(dep);
if (ruleViolation != RuleViolation.NONE) {
nonStandard = dep;
return Result.NON_STANDARD;
}
}
return Result.OK;
}
/** Returns the transaction that was found to be non-standard, or null. */
@Nullable
public Transaction getNonStandard() {
return nonStandard;
}
/** Returns the transaction that was found to be non-final, or null. */
@Nullable
public Transaction getNonFinal() {
return nonFinal;
}
@Override
public String toString() {
if (!analyzed)
return "Pending risk analysis for " + tx.getHashAsString();
else if (nonFinal != null)
return "Risky due to non-finality of " + nonFinal.getHashAsString();
else if (nonStandard != null)
return "Risky due to non-standard tx " + nonStandard.getHashAsString();
else
return "Non-risky";
}
public static class Analyzer implements RiskAnalysis.Analyzer {
@Override
public DefaultRiskAnalysis create(Wallet wallet, Transaction tx, List<Transaction> dependencies) {
return new DefaultRiskAnalysis(wallet, tx, dependencies);
}
}
public static Analyzer FACTORY = new Analyzer();
}
| |
/**
* 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.hadoop.hbase.regionserver;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HConstants;
import org.apache.hadoop.hbase.classification.InterfaceAudience;
import org.apache.hadoop.hbase.ipc.PriorityFunction;
import org.apache.hadoop.hbase.ipc.QosPriority;
import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.CloseRegionRequest;
import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.CompactRegionRequest;
import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.FlushRegionRequest;
import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.GetRegionInfoRequest;
import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.GetStoreFileRequest;
import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.SplitRegionRequest;
import org.apache.hadoop.hbase.shaded.protobuf.generated.ClientProtos.GetRequest;
import org.apache.hadoop.hbase.shaded.protobuf.generated.ClientProtos.MutateRequest;
import org.apache.hadoop.hbase.shaded.protobuf.generated.ClientProtos.ScanRequest;
import org.apache.hadoop.hbase.shaded.protobuf.generated.HBaseProtos.RegionSpecifier;
import org.apache.hadoop.hbase.shaded.protobuf.generated.RPCProtos.RequestHeader;
import org.apache.hadoop.hbase.shaded.com.google.common.annotations.VisibleForTesting;
import org.apache.hadoop.hbase.shaded.com.google.protobuf.Message;
import org.apache.hadoop.hbase.shaded.com.google.protobuf.TextFormat;
import org.apache.hadoop.hbase.security.User;
/**
* Reads special method annotations and table names to figure a priority for use by QoS facility in
* ipc; e.g: rpcs to hbase:meta get priority.
*/
// TODO: Remove. This is doing way too much work just to figure a priority. Do as Elliott
// suggests and just have the client specify a priority.
//The logic for figuring out high priority RPCs is as follows:
//1. if the method is annotated with a QosPriority of QOS_HIGH,
// that is honored
//2. parse out the protobuf message and see if the request is for meta
// region, and if so, treat it as a high priority RPC
//Some optimizations for (2) are done here -
//Clients send the argument classname as part of making the RPC. The server
//decides whether to deserialize the proto argument message based on the
//pre-established set of argument classes (knownArgumentClasses below).
//This prevents the server from having to deserialize all proto argument
//messages prematurely.
//All the argument classes declare a 'getRegion' method that returns a
//RegionSpecifier object. Methods can be invoked on the returned object
//to figure out whether it is a meta region or not.
@InterfaceAudience.Private
public class AnnotationReadingPriorityFunction implements PriorityFunction {
private static final Log LOG =
LogFactory.getLog(AnnotationReadingPriorityFunction.class.getName());
/** Used to control the scan delay, currently sqrt(numNextCall * weight) */
public static final String SCAN_VTIME_WEIGHT_CONF_KEY = "hbase.ipc.server.scan.vtime.weight";
protected final Map<String, Integer> annotatedQos;
//We need to mock the regionserver instance for some unit tests (set via
//setRegionServer method.
private RSRpcServices rpcServices;
@SuppressWarnings("unchecked")
private final Class<? extends Message>[] knownArgumentClasses = new Class[]{
GetRegionInfoRequest.class,
GetStoreFileRequest.class,
CloseRegionRequest.class,
FlushRegionRequest.class,
SplitRegionRequest.class,
CompactRegionRequest.class,
GetRequest.class,
MutateRequest.class,
ScanRequest.class
};
// Some caches for helping performance
private final Map<String, Class<? extends Message>> argumentToClassMap = new HashMap<>();
private final Map<String, Map<Class<? extends Message>, Method>> methodMap = new HashMap<>();
private final float scanVirtualTimeWeight;
/**
* Calls {@link #AnnotationReadingPriorityFunction(RSRpcServices, Class)} using the result of
* {@code rpcServices#getClass()}
*
* @param rpcServices
* The RPC server implementation
*/
public AnnotationReadingPriorityFunction(final RSRpcServices rpcServices) {
this(rpcServices, rpcServices.getClass());
}
/**
* Constructs the priority function given the RPC server implementation and the annotations on the
* methods in the provided {@code clz}.
*
* @param rpcServices
* The RPC server implementation
* @param clz
* The concrete RPC server implementation's class
*/
public AnnotationReadingPriorityFunction(final RSRpcServices rpcServices,
Class<? extends RSRpcServices> clz) {
Map<String,Integer> qosMap = new HashMap<>();
for (Method m : clz.getMethods()) {
QosPriority p = m.getAnnotation(QosPriority.class);
if (p != null) {
// Since we protobuf'd, and then subsequently, when we went with pb style, method names
// are capitalized. This meant that this brittle compare of method names gotten by
// reflection no longer matched the method names coming in over pb. TODO: Get rid of this
// check. For now, workaround is to capitalize the names we got from reflection so they
// have chance of matching the pb ones.
String capitalizedMethodName = capitalize(m.getName());
qosMap.put(capitalizedMethodName, p.priority());
}
}
this.rpcServices = rpcServices;
this.annotatedQos = qosMap;
if (methodMap.get("getRegion") == null) {
methodMap.put("hasRegion", new HashMap<>());
methodMap.put("getRegion", new HashMap<>());
}
for (Class<? extends Message> cls : knownArgumentClasses) {
argumentToClassMap.put(cls.getName(), cls);
try {
methodMap.get("hasRegion").put(cls, cls.getDeclaredMethod("hasRegion"));
methodMap.get("getRegion").put(cls, cls.getDeclaredMethod("getRegion"));
} catch (Exception e) {
throw new RuntimeException(e);
}
}
Configuration conf = rpcServices.getConfiguration();
scanVirtualTimeWeight = conf.getFloat(SCAN_VTIME_WEIGHT_CONF_KEY, 1.0f);
}
private String capitalize(final String s) {
StringBuilder strBuilder = new StringBuilder(s);
strBuilder.setCharAt(0, Character.toUpperCase(strBuilder.charAt(0)));
return strBuilder.toString();
}
/**
* Returns a 'priority' based on the request type.
*
* Currently the returned priority is used for queue selection.
* See the SimpleRpcScheduler as example. It maintains a queue per 'priory type'
* HIGH_QOS (meta requests), REPLICATION_QOS (replication requests),
* NORMAL_QOS (user requests).
*/
@Override
public int getPriority(RequestHeader header, Message param, User user) {
int priorityByAnnotation = getAnnotatedPriority(header);
if (priorityByAnnotation >= 0) {
return priorityByAnnotation;
}
return getBasePriority(header, param);
}
/**
* See if the method has an annotation.
* @param header
* @return Return the priority from the annotation. If there isn't
* an annotation, this returns something below zero.
*/
protected int getAnnotatedPriority(RequestHeader header) {
String methodName = header.getMethodName();
Integer priorityByAnnotation = annotatedQos.get(methodName);
if (priorityByAnnotation != null) {
return priorityByAnnotation;
}
return -1;
}
/**
* Get the priority for a given request from the header and the param
* This doesn't consider which user is sending the request at all.
* This doesn't consider annotations
*/
protected int getBasePriority(RequestHeader header, Message param) {
if (param == null) {
return HConstants.NORMAL_QOS;
}
// Trust the client-set priorities if set
if (header.hasPriority()) {
return header.getPriority();
}
String cls = param.getClass().getName();
Class<? extends Message> rpcArgClass = argumentToClassMap.get(cls);
RegionSpecifier regionSpecifier = null;
//check whether the request has reference to meta region or now.
try {
// Check if the param has a region specifier; the pb methods are hasRegion and getRegion if
// hasRegion returns true. Not all listed methods have region specifier each time. For
// example, the ScanRequest has it on setup but thereafter relies on the scannerid rather than
// send the region over every time.
Method hasRegion = methodMap.get("hasRegion").get(rpcArgClass);
if (hasRegion != null && (Boolean)hasRegion.invoke(param, (Object[])null)) {
Method getRegion = methodMap.get("getRegion").get(rpcArgClass);
regionSpecifier = (RegionSpecifier)getRegion.invoke(param, (Object[])null);
Region region = rpcServices.getRegion(regionSpecifier);
if (region.getRegionInfo().isSystemTable()) {
if (LOG.isTraceEnabled()) {
LOG.trace("High priority because region=" +
region.getRegionInfo().getRegionNameAsString());
}
return HConstants.SYSTEMTABLE_QOS;
}
}
} catch (Exception ex) {
// Not good throwing an exception out of here, a runtime anyways. Let the query go into the
// server and have it throw the exception if still an issue. Just mark it normal priority.
if (LOG.isTraceEnabled()) LOG.trace("Marking normal priority after getting exception=" + ex);
return HConstants.NORMAL_QOS;
}
if (param instanceof ScanRequest) { // scanner methods...
ScanRequest request = (ScanRequest)param;
if (!request.hasScannerId()) {
return HConstants.NORMAL_QOS;
}
RegionScanner scanner = rpcServices.getScanner(request.getScannerId());
if (scanner != null && scanner.getRegionInfo().isSystemTable()) {
if (LOG.isTraceEnabled()) {
// Scanner requests are small in size so TextFormat version should not overwhelm log.
LOG.trace("High priority scanner request " + TextFormat.shortDebugString(request));
}
return HConstants.SYSTEMTABLE_QOS;
}
}
return HConstants.NORMAL_QOS;
}
/**
* Based on the request content, returns the deadline of the request.
*
* @param header
* @param param
* @return Deadline of this request. 0 now, otherwise msec of 'delay'
*/
@Override
public long getDeadline(RequestHeader header, Message param) {
if (param instanceof ScanRequest) {
ScanRequest request = (ScanRequest)param;
if (!request.hasScannerId()) {
return 0;
}
// get the 'virtual time' of the scanner, and applies sqrt() to get a
// nice curve for the delay. More a scanner is used the less priority it gets.
// The weight is used to have more control on the delay.
long vtime = rpcServices.getScannerVirtualTime(request.getScannerId());
return Math.round(Math.sqrt(vtime * scanVirtualTimeWeight));
}
return 0;
}
@VisibleForTesting
void setRegionServer(final HRegionServer hrs) {
this.rpcServices = hrs.getRSRpcServices();
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/dialogflow/v2/context.proto
package com.google.cloud.dialogflow.v2;
/**
*
*
* <pre>
* The request message for
* [Contexts.GetContext][google.cloud.dialogflow.v2.Contexts.GetContext].
* </pre>
*
* Protobuf type {@code google.cloud.dialogflow.v2.GetContextRequest}
*/
public final class GetContextRequest extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.dialogflow.v2.GetContextRequest)
GetContextRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use GetContextRequest.newBuilder() to construct.
private GetContextRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private GetContextRequest() {
name_ = "";
}
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet getUnknownFields() {
return this.unknownFields;
}
private GetContextRequest(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
this();
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
int mutable_bitField0_ = 0;
com.google.protobuf.UnknownFieldSet.Builder unknownFields =
com.google.protobuf.UnknownFieldSet.newBuilder();
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
java.lang.String s = input.readStringRequireUtf8();
name_ = s;
break;
}
default:
{
if (!parseUnknownFieldProto3(input, unknownFields, extensionRegistry, tag)) {
done = true;
}
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this);
} finally {
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.dialogflow.v2.ContextProto
.internal_static_google_cloud_dialogflow_v2_GetContextRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.dialogflow.v2.ContextProto
.internal_static_google_cloud_dialogflow_v2_GetContextRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.dialogflow.v2.GetContextRequest.class,
com.google.cloud.dialogflow.v2.GetContextRequest.Builder.class);
}
public static final int NAME_FIELD_NUMBER = 1;
private volatile java.lang.Object name_;
/**
*
*
* <pre>
* Required. The name of the context. Format:
* `projects/<Project ID>/agent/sessions/<Session ID>/contexts/<Context ID>`.
* </pre>
*
* <code>string name = 1;</code>
*/
public java.lang.String getName() {
java.lang.Object ref = name_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
name_ = s;
return s;
}
}
/**
*
*
* <pre>
* Required. The name of the context. Format:
* `projects/<Project ID>/agent/sessions/<Session ID>/contexts/<Context ID>`.
* </pre>
*
* <code>string name = 1;</code>
*/
public com.google.protobuf.ByteString getNameBytes() {
java.lang.Object ref = name_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
name_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (!getNameBytes().isEmpty()) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, name_);
}
unknownFields.writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (!getNameBytes().isEmpty()) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, name_);
}
size += unknownFields.getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.dialogflow.v2.GetContextRequest)) {
return super.equals(obj);
}
com.google.cloud.dialogflow.v2.GetContextRequest other =
(com.google.cloud.dialogflow.v2.GetContextRequest) obj;
boolean result = true;
result = result && getName().equals(other.getName());
result = result && unknownFields.equals(other.unknownFields);
return result;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (37 * hash) + NAME_FIELD_NUMBER;
hash = (53 * hash) + getName().hashCode();
hash = (29 * hash) + unknownFields.hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.dialogflow.v2.GetContextRequest parseFrom(java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.dialogflow.v2.GetContextRequest parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.dialogflow.v2.GetContextRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.dialogflow.v2.GetContextRequest parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.dialogflow.v2.GetContextRequest parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.dialogflow.v2.GetContextRequest parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.dialogflow.v2.GetContextRequest parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.dialogflow.v2.GetContextRequest parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.dialogflow.v2.GetContextRequest parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.dialogflow.v2.GetContextRequest parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.dialogflow.v2.GetContextRequest parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.dialogflow.v2.GetContextRequest parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(com.google.cloud.dialogflow.v2.GetContextRequest prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* The request message for
* [Contexts.GetContext][google.cloud.dialogflow.v2.Contexts.GetContext].
* </pre>
*
* Protobuf type {@code google.cloud.dialogflow.v2.GetContextRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.dialogflow.v2.GetContextRequest)
com.google.cloud.dialogflow.v2.GetContextRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.dialogflow.v2.ContextProto
.internal_static_google_cloud_dialogflow_v2_GetContextRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.dialogflow.v2.ContextProto
.internal_static_google_cloud_dialogflow_v2_GetContextRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.dialogflow.v2.GetContextRequest.class,
com.google.cloud.dialogflow.v2.GetContextRequest.Builder.class);
}
// Construct using com.google.cloud.dialogflow.v2.GetContextRequest.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {}
}
@java.lang.Override
public Builder clear() {
super.clear();
name_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.dialogflow.v2.ContextProto
.internal_static_google_cloud_dialogflow_v2_GetContextRequest_descriptor;
}
@java.lang.Override
public com.google.cloud.dialogflow.v2.GetContextRequest getDefaultInstanceForType() {
return com.google.cloud.dialogflow.v2.GetContextRequest.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.dialogflow.v2.GetContextRequest build() {
com.google.cloud.dialogflow.v2.GetContextRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.dialogflow.v2.GetContextRequest buildPartial() {
com.google.cloud.dialogflow.v2.GetContextRequest result =
new com.google.cloud.dialogflow.v2.GetContextRequest(this);
result.name_ = name_;
onBuilt();
return result;
}
@java.lang.Override
public Builder clone() {
return (Builder) super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return (Builder) super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return (Builder) super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return (Builder) super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return (Builder) super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return (Builder) super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.dialogflow.v2.GetContextRequest) {
return mergeFrom((com.google.cloud.dialogflow.v2.GetContextRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.dialogflow.v2.GetContextRequest other) {
if (other == com.google.cloud.dialogflow.v2.GetContextRequest.getDefaultInstance())
return this;
if (!other.getName().isEmpty()) {
name_ = other.name_;
onChanged();
}
this.mergeUnknownFields(other.unknownFields);
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
com.google.cloud.dialogflow.v2.GetContextRequest parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (com.google.cloud.dialogflow.v2.GetContextRequest) e.getUnfinishedMessage();
throw e.unwrapIOException();
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private java.lang.Object name_ = "";
/**
*
*
* <pre>
* Required. The name of the context. Format:
* `projects/<Project ID>/agent/sessions/<Session ID>/contexts/<Context ID>`.
* </pre>
*
* <code>string name = 1;</code>
*/
public java.lang.String getName() {
java.lang.Object ref = name_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
name_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Required. The name of the context. Format:
* `projects/<Project ID>/agent/sessions/<Session ID>/contexts/<Context ID>`.
* </pre>
*
* <code>string name = 1;</code>
*/
public com.google.protobuf.ByteString getNameBytes() {
java.lang.Object ref = name_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
name_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Required. The name of the context. Format:
* `projects/<Project ID>/agent/sessions/<Session ID>/contexts/<Context ID>`.
* </pre>
*
* <code>string name = 1;</code>
*/
public Builder setName(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
name_ = value;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The name of the context. Format:
* `projects/<Project ID>/agent/sessions/<Session ID>/contexts/<Context ID>`.
* </pre>
*
* <code>string name = 1;</code>
*/
public Builder clearName() {
name_ = getDefaultInstance().getName();
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The name of the context. Format:
* `projects/<Project ID>/agent/sessions/<Session ID>/contexts/<Context ID>`.
* </pre>
*
* <code>string name = 1;</code>
*/
public Builder setNameBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
name_ = value;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFieldsProto3(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.dialogflow.v2.GetContextRequest)
}
// @@protoc_insertion_point(class_scope:google.cloud.dialogflow.v2.GetContextRequest)
private static final com.google.cloud.dialogflow.v2.GetContextRequest DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.dialogflow.v2.GetContextRequest();
}
public static com.google.cloud.dialogflow.v2.GetContextRequest getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<GetContextRequest> PARSER =
new com.google.protobuf.AbstractParser<GetContextRequest>() {
@java.lang.Override
public GetContextRequest parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new GetContextRequest(input, extensionRegistry);
}
};
public static com.google.protobuf.Parser<GetContextRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<GetContextRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.dialogflow.v2.GetContextRequest getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
| |
// =================================================================================================
// Copyright 2011 Twitter, Inc.
// -------------------------------------------------------------------------------------------------
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this work except in compliance with the License.
// You may obtain a copy of the License in the LICENSE file, or 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.twitter.common.application;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.google.common.base.Preconditions;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.common.base.Throwables;
import com.google.common.collect.ImmutableList;
import com.google.inject.Guice;
import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.Module;
import com.google.inject.Stage;
import com.google.inject.util.Modules;
import com.twitter.common.application.modules.AppLauncherModule;
import com.twitter.common.application.modules.LifecycleModule;
import com.twitter.common.args.Arg;
import com.twitter.common.args.ArgFilters;
import com.twitter.common.args.ArgScanner;
import com.twitter.common.args.ArgScanner.ArgScanException;
import com.twitter.common.args.CmdLine;
import com.twitter.common.args.constraints.NotNull;
import com.twitter.common.base.ExceptionalCommand;
/**
* An application launcher that sets up a framework for pluggable binding modules. This class
* should be called directly as the main class, with a command line argument {@code -app_class}
* which is the canonical class name of the application to execute.
*
* If your application uses command line arguments all {@link Arg} fields annotated with
* {@link CmdLine} will be discovered and command line arguments will be validated against this set,
* parsed and applied.
*
* A bootstrap module will be automatically applied ({@link AppLauncherModule}), which provides
* overridable default bindings for things like quit/abort hooks and a health check function.
* A {@link LifecycleModule} is also automatically applied to perform startup and shutdown
* actions.
*/
public final class AppLauncher {
private static final Logger LOG = Logger.getLogger(AppLauncher.class.getName());
private static final String APP_CLASS_NAME = "app_class";
@NotNull
@CmdLine(name = APP_CLASS_NAME,
help = "Fully-qualified name of the application class, which must implement Runnable.")
private static final Arg<Class<? extends Application>> APP_CLASS = Arg.create();
@CmdLine(name = "guice_stage",
help = "Guice development stage to create injector with.")
private static final Arg<Stage> GUICE_STAGE = Arg.create(Stage.DEVELOPMENT);
private static final Predicate<Field> SELECT_APP_CLASS =
ArgFilters.selectCmdLineArg(AppLauncher.class, APP_CLASS_NAME);
@Inject @StartupStage private ExceptionalCommand startupCommand;
@Inject private Lifecycle lifecycle;
private AppLauncher() {
// This should not be invoked directly.
}
private void run(Application application) {
try {
configureInjection(application);
LOG.info("Executing startup actions.");
// We're an app framework and this is the outer shell - it makes sense to handle all errors
// before exiting.
// SUPPRESS CHECKSTYLE:OFF IllegalCatch
try {
startupCommand.execute();
} catch (Exception e) {
LOG.log(Level.SEVERE, "Startup action failed, quitting.", e);
throw Throwables.propagate(e);
}
// SUPPRESS CHECKSTYLE:ON IllegalCatch
try {
application.run();
} finally {
LOG.info("Application run() exited.");
}
} finally {
if (lifecycle != null) {
lifecycle.shutdown();
}
}
}
private void configureInjection(Application application) {
Iterable<Module> modules = ImmutableList.<Module>builder()
.add(new LifecycleModule())
.add(new AppLauncherModule())
.addAll(application.getModules())
.build();
Injector injector = Guice.createInjector(GUICE_STAGE.get(), Modules.combine(modules));
injector.injectMembers(this);
injector.injectMembers(application);
}
public static void main(String... args) throws IllegalAccessException, InstantiationException {
// TODO(John Sirois): Support a META-INF/MANIFEST.MF App-Class attribute to allow java -jar
parseArgs(ArgFilters.SELECT_ALL, Arrays.asList(args));
new AppLauncher().run(APP_CLASS.get().newInstance());
}
/**
* A convenience for main wrappers. Equivalent to:
* <pre>
* AppLauncher.launch(appClass, ArgFilters.SELECT_ALL, Arrays.asList(args));
* </pre>
*
* @param appClass The application class to instantiate and launch.
* @param args The command line arguments to parse.
* @see ArgFilters
*/
public static void launch(Class<? extends Application> appClass, String... args) {
launch(appClass, ArgFilters.SELECT_ALL, Arrays.asList(args));
}
/**
* A convenience for main wrappers. Equivalent to:
* <pre>
* AppLauncher.launch(appClass, argFilter, Arrays.asList(args));
* </pre>
*
* @param appClass The application class to instantiate and launch.
* @param argFilter A filter that selects the {@literal @CmdLine} {@link Arg}s to enable for
* parsing.
* @param args The command line arguments to parse.
* @see ArgFilters
*/
public static void launch(Class<? extends Application> appClass, Predicate<Field> argFilter,
String... args) {
launch(appClass, argFilter, Arrays.asList(args));
}
/**
* Used to launch an application with a restricted set of {@literal @CmdLine} {@link Arg}s
* considered for parsing. This is useful if the classpath includes annotated fields you do not
* wish arguments to be parsed for.
*
* @param appClass The application class to instantiate and launch.
* @param argFilter A filter that selects the {@literal @CmdLine} {@link Arg}s to enable for
* parsing.
* @param args The command line arguments to parse.
* @see ArgFilters
*/
public static void launch(Class<? extends Application> appClass, Predicate<Field> argFilter,
List<String> args) {
Preconditions.checkNotNull(appClass);
Preconditions.checkNotNull(argFilter);
Preconditions.checkNotNull(args);
parseArgs(Predicates.<Field>and(Predicates.not(SELECT_APP_CLASS), argFilter), args);
try {
new AppLauncher().run(appClass.newInstance());
} catch (InstantiationException e) {
throw new IllegalStateException(e);
} catch (IllegalAccessException e) {
throw new IllegalStateException(e);
}
}
private static void parseArgs(Predicate<Field> filter, List<String> args) {
try {
if (!new ArgScanner().parse(filter, args)) {
System.exit(0);
}
} catch (ArgScanException e) {
exit("Failed to scan arguments", e);
} catch (IllegalArgumentException e) {
exit("Failed to apply arguments", e);
}
}
private static void exit(String message, Exception error) {
LOG.log(Level.SEVERE, message + "\n" + error, error);
System.exit(1);
}
}
| |
/*
* The aspiredb project
*
* Copyright (c) 2012 University of British Columbia
*
* 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 ubc.pavlab.aspiredb.server.model;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Transient;
import org.hibernate.annotations.BatchSize;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ubc.pavlab.aspiredb.shared.VariantValueObject;
/**
* This table is used to hold data about overlap between two variants. Originally this was only to be used for overlap
* with 'special' variants in DGV and DECIPHER, hence the 'special' in the name of the table new requirements were added
* to allow this functionality between two user projects so the 'special' is unnecessary in the name and should be
* removed/renamed
*
* @author cmcdonald
* @version $Id:$
*/
@Entity
@Table(name = "VARIANT2VARIANTOVERLAP")
@BatchSize(size = 50)
public class Variant2VariantOverlap implements Serializable {
/**
*
*/
private static final long serialVersionUID = 6734779432249098068L;
@Transient
private static Logger log = LoggerFactory.getLogger( Variant2VariantOverlap.class );
@Id
@Column(name = "ID")
@GeneratedValue
private Long id;
@Column(name = "VARIANTID")
private Long variantId;
@Column(name = "OVERLAPPED_VARIANTID")
private Long overlapSpecialVariantId;
@Column(name = "OVERLAP_LENGTH")
private Integer overlap;
// the percentage of the variantId-variant that is overlapped, storing for easier searching
// using integer as it is better for comparison, easy to change to float later if need be
@Column(name = "OVERLAP_PERCENTAGE")
private Integer overlapPercentage;
// the percentage of the overlapSpecialVariantId-variant that is overlapped
@Column(name = "OVERLAPPED_OVERLAP_PERCENTAGE")
private Integer overlappedOverlapPercentage;
@Column(name = "OVERLAP_PROJECTID")
private Long overlapProjectId;
@Column(name = "PROJECTID")
private Long projectId;
public Variant2VariantOverlap() {
}
public Variant2VariantOverlap( final VariantValueObject vvo, final VariantValueObject vvoOverlapped,
final Long projectId, final Long overlapProjectId ) {
this.projectId = projectId;
this.overlapProjectId = overlapProjectId;
if ( vvo == null || vvoOverlapped == null ) {
log.warn( "Both variants are required to compute overlap percentages" );
return;
}
computeOverlap( vvo, vvoOverlapped );
}
@Override
public boolean equals( Object obj ) {
if ( this == obj ) {
return true;
}
if ( obj == null ) {
return false;
}
if ( getClass() != obj.getClass() ) {
return false;
}
Variant2VariantOverlap other = ( Variant2VariantOverlap ) obj;
if ( overlapSpecialVariantId == null ) {
if ( other.overlapSpecialVariantId != null ) {
return false;
}
} else if ( !overlapSpecialVariantId.equals( other.overlapSpecialVariantId ) ) {
return false;
}
if ( variantId == null ) {
if ( other.variantId != null ) {
return false;
}
} else if ( !variantId.equals( other.variantId ) ) {
return false;
}
return true;
}
public Integer getOverlap() {
return overlap;
}
public Integer getOverlappedOverlapPercentage() {
return overlappedOverlapPercentage;
}
public Integer getOverlapPercentage() {
return overlapPercentage;
}
public Long getOverlapProjectId() {
return overlapProjectId;
}
public Long getOverlapSpecialVariantId() {
return overlapSpecialVariantId;
}
public Long getProjectId() {
return projectId;
}
public Long getVariantId() {
return variantId;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ( ( overlapSpecialVariantId == null ) ? 0 : overlapSpecialVariantId.hashCode() );
result = prime * result + ( ( variantId == null ) ? 0 : variantId.hashCode() );
return result;
}
public void setOverlap( Integer overlap ) {
this.overlap = overlap;
}
public void setOverlappedOverlapPercentage( Integer overlappedOverlapPercentage ) {
this.overlappedOverlapPercentage = overlappedOverlapPercentage;
}
public void setOverlapPercentage( Integer overlapPercentage ) {
this.overlapPercentage = overlapPercentage;
}
public void setOverlapProjectId( Long overlapProjectId ) {
this.overlapProjectId = overlapProjectId;
}
public void setOverlapSpecialVariantId( Long overlappedSpecialVariantId ) {
this.overlapSpecialVariantId = overlappedSpecialVariantId;
}
public void setProjectId( Long projectId ) {
this.projectId = projectId;
}
public void setVariantId( Long variantId ) {
this.variantId = variantId;
}
private void computeOverlap( final VariantValueObject vvo, final VariantValueObject vvoOverlapped ) {
if ( vvo == null || vvo.getId() == null ) {
throw new IllegalArgumentException( "VariantValueObject is null or has no ID!" );
}
if ( vvoOverlapped == null || vvoOverlapped.getId() == null ) {
throw new IllegalArgumentException( "Overlapped VariantValueObject is null or has no ID!" );
}
int start = Math.max( vvo.getGenomicRange().getBaseStart(), vvoOverlapped.getGenomicRange().getBaseStart() );
int end = Math.min( vvo.getGenomicRange().getBaseEnd(), vvoOverlapped.getGenomicRange().getBaseEnd() );
int overlap = end - start;
if ( overlap == 0 ) {
log.warn( "Overlap size is 0 between " + vvo.getId() + " and " + vvoOverlapped.getId() );
}
float vvoSize = vvo.getGenomicRange().getBaseEnd() - vvo.getGenomicRange().getBaseStart();
float vvoOverlappedSize = vvoOverlapped.getGenomicRange().getBaseEnd()
- vvoOverlapped.getGenomicRange().getBaseStart();
float vvoPercentageOverlap = overlap / vvoSize * 100;
float vvoOverlappedPercentageOverlap = overlap / vvoOverlappedSize * 100;
setOverlap( overlap );
setOverlapPercentage( Math.round( vvoPercentageOverlap ) );
// set the percentage overlap of the OverlapSpecialVariantId-variant, I realize that these method
// and variable names kind of suck
setOverlappedOverlapPercentage( Math.round( vvoOverlappedPercentageOverlap ) );
setVariantId( vvo.getId() );
setOverlapSpecialVariantId( vvoOverlapped.getId() );
}
}
| |
/**************************************************************************
* copyright file="SearchFilter.java" company="Microsoft"
* Copyright (c) Microsoft Corporation. All rights reserved.
*
* Defines the SearchFilter.java.
**************************************************************************/
package microsoft.exchange.webservices.data;
import java.util.ArrayList;
import java.util.Iterator;
import javax.xml.stream.XMLStreamException;
/**
* Represents the base search filter class. Use descendant search filter classes
* such as SearchFilter.IsEqualTo, SearchFilter.ContainsSubstring and
* SearchFilter.SearchFilterCollection to define search filters.
*
*/
public abstract class SearchFilter extends ComplexProperty {
/**
* Initializes a new instance of the SearchFilter class.
*/
protected SearchFilter() {
}
/**
* The search.
*
* @param reader the reader
* @return the search filter
* @throws Exception the exception
*/
//static SearchFilter search;
/**
* Loads from XML.
*
* @param reader
* the reader
* @return SearchFilter
* @throws Exception
* the exception
*/
protected static SearchFilter loadFromXml(EwsServiceXmlReader reader)
throws Exception {
reader.ensureCurrentNodeIsStartElement();
SearchFilter searchFilter = null;
if (reader.getLocalName().equalsIgnoreCase(XmlElementNames.Exists)) {
searchFilter = new Exists();
} else if (reader.getLocalName().equalsIgnoreCase(
XmlElementNames.Contains)) {
searchFilter = new ContainsSubstring();
} else if (reader.getLocalName().equalsIgnoreCase(
XmlElementNames.Excludes)) {
searchFilter = new ExcludesBitmask();
} else if (reader.getLocalName().equalsIgnoreCase(XmlElementNames.Not)) {
searchFilter = new Not();
} else if (reader.getLocalName().equalsIgnoreCase(XmlElementNames.And)) {
searchFilter = new SearchFilterCollection(
LogicalOperator.And);
} else if (reader.getLocalName().equalsIgnoreCase(XmlElementNames.Or)) {
searchFilter = new SearchFilterCollection(
LogicalOperator.Or);
} else if (reader.getLocalName().equalsIgnoreCase(
XmlElementNames.IsEqualTo)) {
searchFilter = new IsEqualTo();
} else if (reader.getLocalName().equalsIgnoreCase(
XmlElementNames.IsNotEqualTo)) {
searchFilter = new IsNotEqualTo();
} else if (reader.getLocalName().equalsIgnoreCase(
XmlElementNames.IsGreaterThan)) {
searchFilter = new IsGreaterThan();
} else if (reader.getLocalName().equalsIgnoreCase(
XmlElementNames.IsGreaterThanOrEqualTo)) {
searchFilter = new IsGreaterThanOrEqualTo();
} else if (reader.getLocalName().equalsIgnoreCase(
XmlElementNames.IsLessThan)) {
searchFilter = new IsLessThan();
} else if (reader.getLocalName().equalsIgnoreCase(
XmlElementNames.IsLessThanOrEqualTo)) {
searchFilter = new IsLessThanOrEqualTo();
} else {
searchFilter = null;
}
if (searchFilter != null) {
searchFilter.loadFromXml(reader, reader.getLocalName());
}
return searchFilter;
}
/**
* Gets the name of the XML element.
*
* @return the xml element name
*/
protected abstract String getXmlElementName();
/**
* Writes to XML.
*
* @param writer
* the writer
* @throws Exception
* the exception
*/
protected void writeToXml(EwsServiceXmlWriter writer) throws Exception {
super.writeToXml(writer, this.getXmlElementName());
}
/**
* Represents a search filter that checks for the presence of a substring
* inside a text property. Applications can use ContainsSubstring to define
* conditions such as "Field CONTAINS Value" or
* "Field IS PREFIXED WITH Value".
*
*/
public static final class ContainsSubstring extends PropertyBasedFilter {
/** The containment mode. */
private ContainmentMode containmentMode = ContainmentMode.Substring;
/** The comparison mode. */
private ComparisonMode comparisonMode = ComparisonMode.IgnoreCase;
/** The value. */
private String value;
/**
* Initializes a new instance of the class.
*/
public ContainsSubstring() {
super();
}
/**
* Initializes a new instance of the class.
*
* @param propertyDefinition
* The definition of the property that is being compared.
* @param value
* The value to compare with.
*/
public ContainsSubstring(PropertyDefinitionBase propertyDefinition,
String value) {
super(propertyDefinition);
this.value = value;
}
/**
* Initializes a new instance of the class.
*
* @param propertyDefinition
* The definition of the property that is being compared.
* @param value
* The value to compare with.
* @param containmentMode
* The containment mode.
* @param comparisonMode
* The comparison mode.
*/
public ContainsSubstring(PropertyDefinitionBase propertyDefinition,
String value, ContainmentMode containmentMode,
ComparisonMode comparisonMode) {
this(propertyDefinition, value);
this.containmentMode = containmentMode;
this.comparisonMode = comparisonMode;
}
/**
* validates instance.
*
* @throws ServiceValidationException
* the service validation exception
*/
@Override
protected void internalValidate() throws ServiceValidationException {
super.internalValidate();
if ((this.value == null) || this.value.isEmpty()) {
throw new ServiceValidationException(
Strings.ValuePropertyMustBeSet);
}
}
/**
* Gets the name of the XML element.
*
* @return the xml element name
*/
@Override
protected String getXmlElementName() {
return XmlElementNames.Contains;
}
/**
* Tries to read element from XML.
*
* @param reader
* the reader
* @return True if element was read.
* @throws Exception
* the exception
*/
@Override
protected boolean tryReadElementFromXml(EwsServiceXmlReader reader)
throws Exception {
boolean result = super.tryReadElementFromXml(reader);
if (!result) {
if (reader.getLocalName().equals(XmlElementNames.Constant)) {
this.value = reader
.readAttributeValue(XmlAttributeNames.Value);
result = true;
}
}
return result;
}
/**
* Reads the attribute of Xml.
*
* @param reader
* the reader
* @throws Exception
* the exception
*/
@Override
protected void readAttributesFromXml(EwsServiceXmlReader reader)
throws Exception {
super.readAttributesFromXml(reader);
this.containmentMode = reader.readAttributeValue(
ContainmentMode.class, XmlAttributeNames.ContainmentMode);
try {
this.comparisonMode = reader.readAttributeValue(
ComparisonMode.class,
XmlAttributeNames.ContainmentComparison);
} catch (IllegalArgumentException ile) {
// This will happen if we receive a value that is defined in the
// EWS
// schema but that is not defined
// in the API. We map that
// value to IgnoreCaseAndNonSpacingCharacters.
this.comparisonMode = ComparisonMode.
IgnoreCaseAndNonSpacingCharacters;
}
}
/**
* Writes the attributes to XML.
*
* @param writer
* the writer
* @throws ServiceXmlSerializationException
* the service xml serialization exception
*/
@Override
protected void writeAttributesToXml(EwsServiceXmlWriter writer)
throws ServiceXmlSerializationException {
super.writeAttributesToXml(writer);
writer.writeAttributeValue(XmlAttributeNames.ContainmentMode,
this.containmentMode);
writer.writeAttributeValue(XmlAttributeNames.ContainmentComparison,
this.comparisonMode);
}
/**
* Writes the elements to Xml.
*
* @param writer
* the writer
* @throws javax.xml.stream.XMLStreamException
* the xML stream exception
* @throws ServiceXmlSerializationException
* the service xml serialization exception
*/
@Override
protected void writeElementsToXml(EwsServiceXmlWriter writer)
throws XMLStreamException, ServiceXmlSerializationException {
super.writeElementsToXml(writer);
writer.writeStartElement(XmlNamespace.Types,
XmlElementNames.Constant);
writer.writeAttributeValue(XmlAttributeNames.Value, this.value);
writer.writeEndElement(); // Constant
}
/**
* Gets the containment mode.
*
* @return ContainmentMode
*/
public ContainmentMode getContainmentMode() {
return containmentMode;
}
/**
* sets the ContainmentMode.
*
* @param containmentMode
* the new containment mode
*/
public void setContainmentMode(ContainmentMode containmentMode) {
this.containmentMode = containmentMode;
}
/**
* Gets the comparison mode.
*
* @return ComparisonMode
*/
public ComparisonMode getComparisonMode() {
return comparisonMode;
}
/**
* sets the comparison mode.
*
* @param comparisonMode
* the new comparison mode
*/
public void setComparisonMode(ComparisonMode comparisonMode) {
this.comparisonMode = comparisonMode;
}
/**
* gets the value to compare the specified property with.
*
* @return String
*/
public String getValue() {
return value;
}
/**
* sets the value to compare the specified property with.
*
* @param value
* the new value
*/
public void setValue(String value) {
this.value = value;
}
}
/**
* Represents a bitmask exclusion search filter. Applications can use
* ExcludesBitExcludesBitmaskFilter to define conditions such as
* "(OrdinalField and 0x0010) != 0x0010"
*/
public static class ExcludesBitmask extends PropertyBasedFilter {
/** The bitmask. */
private int bitmask;
/**
* Initializes a new instance of the class.
*/
public ExcludesBitmask() {
super();
}
/**
* Initializes a new instance of the class.
*
* @param propertyDefinition
* the property definition
* @param bitmask
* the bitmask
*/
public ExcludesBitmask(PropertyDefinitionBase propertyDefinition,
int bitmask) {
super(propertyDefinition);
this.bitmask = bitmask;
}
/**
* Gets the name of the XML element.
*
* @return XML element name
*/
@Override
protected String getXmlElementName() {
return XmlElementNames.Excludes;
}
/**
* Tries to read element from XML.
*
* @param reader
* the reader
* @return true if element was read
* @throws Exception
* the exception
*/
@Override
protected boolean tryReadElementFromXml(EwsServiceXmlReader reader)
throws Exception {
boolean result = super.tryReadElementFromXml(reader);
if (!result) {
if (reader.getLocalName().equals(XmlElementNames.Bitmask)) {
// EWS always returns the Bitmask value in hexadecimal
this.bitmask = Integer.parseInt(reader
.readAttributeValue(XmlAttributeNames.Value));
}
}
return result;
}
/**
* Writes the elements to XML.
*
* @param writer
* the writer
* @throws javax.xml.stream.XMLStreamException
* , ServiceXmlSerializationException
* @throws ServiceXmlSerializationException
* the service xml serialization exception
*/
@Override
protected void writeElementsToXml(EwsServiceXmlWriter writer)
throws XMLStreamException, ServiceXmlSerializationException {
super.writeElementsToXml(writer);
writer.writeStartElement(XmlNamespace.Types,
XmlElementNames.Bitmask);
writer.writeAttributeValue(XmlAttributeNames.Value, this.bitmask);
writer.writeEndElement(); // Bitmask
}
/**
* Gets the bitmask to compare the property with.
*
* @return bitmask
*/
public int getBitmask() {
return bitmask;
}
/**
* Sets the bitmask to compare the property with.
*
* @param bitmask
* the new bitmask
*/
public void setBitmask(int bitmask) {
this.bitmask = bitmask;
}
}
/**
* Represents a search filter checking if a field is set. Applications can
* use ExistsFilter to define conditions such as "Field IS SET".
*
*/
public static final class Exists extends PropertyBasedFilter {
/**
* Initializes a new instance of the class.
*/
public Exists() {
super();
}
/**
* Initializes a new instance of the class.
*
* @param propertyDefinition
* the property definition
*/
public Exists(PropertyDefinitionBase propertyDefinition) {
super(propertyDefinition);
}
/**
* Gets the name of the XML element.
*
* @return the xml element name
*/
@Override
protected String getXmlElementName() {
return XmlElementNames.Exists;
}
}
/**
* Represents a search filter that checks if a property is equal to a given
* value or other property.
*
*
*/
public static class IsEqualTo extends RelationalFilter {
/**
* Initializes a new instance of the class.
*/
public IsEqualTo() {
super();
}
/**
* Initializes a new instance of the class.
*
* @param propertyDefinition
* The definition of the property that is being compared.
* @param otherPropertyDefinition
* The definition of the property to compare with.
*/
public IsEqualTo(PropertyDefinitionBase propertyDefinition,
PropertyDefinitionBase otherPropertyDefinition) {
super(propertyDefinition, otherPropertyDefinition);
}
/**
* Initializes a new instance of the class.
*
* @param propertyDefinition
* The definition of the property that is being compared.
* @param value
* The value of the property to compare with.
*/
public IsEqualTo(PropertyDefinitionBase propertyDefinition,
Object value) {
super(propertyDefinition, value);
}
/**
* Gets the name of the XML element.
*
* @return the xml element name
*/
@Override
protected String getXmlElementName() {
return XmlElementNames.IsEqualTo;
}
}
/**
* Represents a search filter that checks if a property is greater than a
* given value or other property.
*
*
*/
public static class IsGreaterThan extends RelationalFilter {
/**
* Initializes a new instance of the class.
*/
public IsGreaterThan() {
super();
}
/**
* Initializes a new instance of the class.
*
* @param propertyDefinition
* The definition of the property that is being compared.
* @param otherPropertyDefinition
* The definition of the property to compare with.
*/
public IsGreaterThan(PropertyDefinitionBase propertyDefinition,
PropertyDefinitionBase otherPropertyDefinition) {
super(propertyDefinition, otherPropertyDefinition);
}
/**
* Initializes a new instance of the class.
*
* @param propertyDefinition
* The definition of the property that is being compared.
* @param value
* The value of the property to compare with.
*/
public IsGreaterThan(PropertyDefinitionBase propertyDefinition,
Object value) {
super(propertyDefinition, value);
}
/**
* Gets the name of the XML element.
*
* @return XML element name.
*/
@Override
protected String getXmlElementName() {
return XmlElementNames.IsGreaterThan;
}
}
/**
* Represents a search filter that checks if a property is greater than or
* equal to a given value or other property.
*
*
*/
public static class IsGreaterThanOrEqualTo extends RelationalFilter {
/**
* Initializes a new instance of the class.
*/
public IsGreaterThanOrEqualTo() {
super();
}
/**
* Initializes a new instance of the class.
*
* @param propertyDefinition
* The definition of the property that is being compared.
* @param otherPropertyDefinition
* The definition of the property to compare with.
*/
public IsGreaterThanOrEqualTo(
PropertyDefinitionBase propertyDefinition,
PropertyDefinitionBase otherPropertyDefinition) {
super(propertyDefinition, otherPropertyDefinition);
}
/**
* Initializes a new instance of the class.
*
* @param propertyDefinition
* The definition of the property that is being compared.
* @param value
* The value of the property to compare with.
*/
public IsGreaterThanOrEqualTo(
PropertyDefinitionBase propertyDefinition, Object value) {
super(propertyDefinition, value);
}
/**
* Gets the name of the XML element. XML element name.
*
* @return the xml element name
*/
@Override
protected String getXmlElementName() {
return XmlElementNames.IsGreaterThanOrEqualTo;
}
}
/**
* Represents a search filter that checks if a property is less than a given
* value or other property.
*
*
*/
public static class IsLessThan extends RelationalFilter {
/**
* Initializes a new instance of the class.
*/
public IsLessThan() {
super();
}
/**
* Initializes a new instance of the class.
*
* @param propertyDefinition
* The definition of the property that is being compared.
* @param otherPropertyDefinition
* The definition of the property to compare with.
*/
public IsLessThan(PropertyDefinitionBase propertyDefinition,
PropertyDefinitionBase otherPropertyDefinition) {
super(propertyDefinition, otherPropertyDefinition);
}
/**
* Initializes a new instance of the class.
*
* @param propertyDefinition
* The definition of the property that is being compared.
* @param value
* The value of the property to compare with.
*/
public IsLessThan(PropertyDefinitionBase propertyDefinition,
Object value) {
super(propertyDefinition, value);
}
/**
* Gets the name of the XML element. XML element name.
*
* @return the xml element name
*/
@Override
protected String getXmlElementName() {
return XmlElementNames.IsLessThan;
}
}
/**
* Represents a search filter that checks if a property is less than or
* equal to a given value or other property.
*
*
*/
public static class IsLessThanOrEqualTo extends RelationalFilter {
/**
* Initializes a new instance of the class.
*/
public IsLessThanOrEqualTo() {
super();
}
/**
* Initializes a new instance of the class.
*
* @param propertyDefinition
* The definition of the property that is being compared.
* @param otherPropertyDefinition
* The definition of the property to compare with.
*/
public IsLessThanOrEqualTo(PropertyDefinitionBase propertyDefinition,
PropertyDefinitionBase otherPropertyDefinition) {
super(propertyDefinition, otherPropertyDefinition);
}
/**
* Initializes a new instance of the class.
*
* @param propertyDefinition
* The definition of the property that is being compared.
* @param value
* The value of the property to compare with.
*/
public IsLessThanOrEqualTo(PropertyDefinitionBase propertyDefinition,
Object value) {
super(propertyDefinition, value);
}
/**
* Gets the name of the XML element. XML element name.
*
* @return the xml element name
*/
@Override
protected String getXmlElementName() {
return XmlElementNames.IsLessThanOrEqualTo;
}
}
/**
* Represents a search filter that checks if a property is not equal to a
* given value or other property.
*
*
*/
public static class IsNotEqualTo extends RelationalFilter {
/**
* Initializes a new instance of the class.
*/
public IsNotEqualTo() {
super();
}
/**
* Initializes a new instance of the class.
*
* @param propertyDefinition
* The definition of the property that is being compared.
* @param otherPropertyDefinition
* The definition of the property to compare with.
*/
public IsNotEqualTo(PropertyDefinitionBase propertyDefinition,
PropertyDefinitionBase otherPropertyDefinition) {
super(propertyDefinition, otherPropertyDefinition);
}
/**
* Initializes a new instance of the class.
*
* @param propertyDefinition
* The definition of the property that is being compared.
* @param value
* The value of the property to compare with.
*/
public IsNotEqualTo(PropertyDefinitionBase propertyDefinition,
Object value) {
super(propertyDefinition, value);
}
/**
* Gets the name of the XML element.
*
* @return XML element name.
*/
@Override
protected String getXmlElementName() {
return XmlElementNames.IsNotEqualTo;
}
}
/**
* Represents a search filter that negates another. Applications can use
* NotFilter to define conditions such as "NOT(other filter)".
*
*
*/
public static class Not extends SearchFilter implements
IComplexPropertyChangedDelegate {
/** The search filter. */
private SearchFilter searchFilter;
/**
* Initializes a new instance of the class.
*/
public Not() {
super();
}
/**
* Initializes a new instance of the class.
*
* @param searchFilter
* the search filter
*/
public Not(SearchFilter searchFilter) {
super();
this.searchFilter = searchFilter;
}
/**
* Search filter changed.
*
* @param complexProperty
* the complex property
*/
private void searchFilterChanged(ComplexProperty complexProperty) {
this.changed();
}
/**
* validates the instance.
*
* @throws ServiceValidationException
* the service validation exception
*/
@Override
protected void internalValidate() throws ServiceValidationException {
if (this.searchFilter == null) {
throw new ServiceValidationException(
Strings.SearchFilterMustBeSet);
}
}
/**
* Gets the name of the XML element.
*
* @return the xml element name
*/
@Override
protected String getXmlElementName() {
return XmlElementNames.Not;
}
/**
* Tries to read element from XML.
*
* @param reader
* the reader
* @return true if the element was read
* @throws Exception
* the exception
*/
@Override
protected boolean tryReadElementFromXml(EwsServiceXmlReader reader)
throws Exception {
this.searchFilter = SearchFilter.loadFromXml(reader);
return true;
}
/**
* Writes the elements to XML.
*
* @param writer
* the writer
* @throws Exception
* the exception
*/
@Override
protected void writeElementsToXml(EwsServiceXmlWriter writer)
throws Exception {
this.searchFilter.writeToXml(writer);
}
/**
* Gets the search filter to negate. Available search filter
* classes include SearchFilter.IsEqualTo,
* SearchFilter.ContainsSubstring and
* SearchFilter.SearchFilterCollection.
*
* @return SearchFilter
*/
public SearchFilter getSearchFilter() {
return searchFilter;
}
/**
* Sets the search filter to negate. Available search filter classes
* include SearchFilter.IsEqualTo, SearchFilter.ContainsSubstring and
* SearchFilter.SearchFilterCollection.
*
* @param searchFilter
* the new search filter
*/
public void setSearchFilter(SearchFilter searchFilter) {
if (this.searchFilter != null) {
this.searchFilter.removeChangeEvent(this);
}
if (this.canSetFieldValue(this.searchFilter, searchFilter)) {
this.searchFilter = searchFilter;
this.changed();
}
if (this.searchFilter != null) {
this.searchFilter.addOnChangeEvent(this);
}
}
/*
* (non-Javadoc)
*
* @see
* microsoft.exchange.webservices.
* ComplexPropertyChangedDelegateInterface#
* complexPropertyChanged(microsoft.exchange.webservices.ComplexProperty
* )
*/
@Override
public void complexPropertyChanged(ComplexProperty complexProperty) {
searchFilterChanged(complexProperty);
}
}
/**
* Represents a search filter where an item or folder property is involved.
*/
@EditorBrowsable(state = EditorBrowsableState.Never)
public static abstract class PropertyBasedFilter extends SearchFilter {
/** The property definition. */
private PropertyDefinitionBase propertyDefinition;
/**
* Initializes a new instance of the class.
*/
PropertyBasedFilter() {
super();
}
/**
* Initializes a new instance of the class.
*
* @param propertyDefinition
* the property definition
*/
PropertyBasedFilter(PropertyDefinitionBase propertyDefinition) {
super();
this.propertyDefinition = propertyDefinition;
}
/**
* validate instance.
*
* @throws ServiceValidationException
* the service validation exception
*/
@Override
protected void internalValidate() throws ServiceValidationException {
if (this.propertyDefinition == null) {
throw new ServiceValidationException(
Strings.PropertyDefinitionPropertyMustBeSet);
}
}
/**
* Tries to read element from XML.
*
* @param reader
* the reader
* @return true if element was read
* @throws Exception
* the exception
*/
@Override
protected boolean tryReadElementFromXml(EwsServiceXmlReader reader)
throws Exception {
OutParam<PropertyDefinitionBase> outParam =
new OutParam<PropertyDefinitionBase>();
outParam.setParam(this.propertyDefinition);
return PropertyDefinitionBase.tryLoadFromXml(reader, outParam);
}
/**
* Writes the elements to XML.
*
* @param writer
* the writer
* @throws javax.xml.stream.XMLStreamException
* the xML stream exception
* @throws ServiceXmlSerializationException
* the service xml serialization exception
*/
@Override
protected void writeElementsToXml(EwsServiceXmlWriter writer)
throws XMLStreamException, ServiceXmlSerializationException {
this.propertyDefinition.writeToXml(writer);
}
/**
* Gets the definition of the property that is involved in the search
* filter.
*
* @return propertyDefinition
*/
public PropertyDefinitionBase getPropertyDefinition() {
return this.propertyDefinition;
}
/**
* Sets the definition of the property that is involved in the search
* filter.
*
* @param propertyDefinition
* the new property definition
*/
public void setPropertyDefinition(
PropertyDefinitionBase propertyDefinition) {
this.propertyDefinition = propertyDefinition;
}
}
/**
* Represents the base class for relational filters (for example, IsEqualTo,
* IsGreaterThan or IsLessThanOrEqualTo).
*
*
*/
@EditorBrowsable(state = EditorBrowsableState.Never)
public abstract static class RelationalFilter extends PropertyBasedFilter {
/** The other property definition. */
private PropertyDefinitionBase otherPropertyDefinition;
/** The value. */
private Object value;
/**
* Initializes a new instance of the class.
*/
RelationalFilter() {
super();
}
/**
* Initializes a new instance of the class.
*
* @param propertyDefinition
* The definition of the property that is being compared.
* @param otherPropertyDefinition
* The definition of the property to compare with
*/
RelationalFilter(PropertyDefinitionBase propertyDefinition,
PropertyDefinitionBase otherPropertyDefinition) {
super(propertyDefinition);
this.otherPropertyDefinition = otherPropertyDefinition;
}
/**
* Initializes a new instance of the class.
*
* @param propertyDefinition
* The definition of the property that is being compared.
* @param value
* The value to compare with.
*/
RelationalFilter(PropertyDefinitionBase propertyDefinition,
Object value) {
super(propertyDefinition);
this.value = value;
}
/**
* validates the instance.
*
* @throws ServiceValidationException
* the service validation exception
*/
@Override
protected void internalValidate() throws ServiceValidationException {
super.internalValidate();
if (this.otherPropertyDefinition == null && this.value == null) {
throw new ServiceValidationException(
Strings.EqualityComparisonFilterIsInvalid);
} else if (value != null) {
// All objects implement Object.
// Value types that don't implement Object must implement
// ISearchStringProvider
// in order to be used in a search filter.
if (!((value instanceof Object) || (value instanceof ISearchStringProvider))) {
throw new ServiceValidationException(
String
.format(
Strings.SearchFilterComparisonValueTypeIsNotSupported,
value.getClass().getName()));
}
}
}
/**
* Tries to read element from XML.
*
* @param reader
* the reader
* @return true if element was read
* @throws Exception
* the exception
*/
@Override
protected boolean tryReadElementFromXml(EwsServiceXmlReader reader)
throws Exception {
boolean result = super.tryReadElementFromXml(reader);
if (!result) {
if (reader.getLocalName().equals(
XmlElementNames.FieldURIOrConstant)) {
try {
reader.read();
reader.ensureCurrentNodeIsStartElement();
} catch (ServiceXmlDeserializationException e) {
e.printStackTrace();
} catch (XMLStreamException e) {
e.printStackTrace();
}
if (reader.isStartElement(XmlNamespace.Types,
XmlElementNames.Constant)) {
this.value = reader
.readAttributeValue(XmlAttributeNames.Value);
result = true;
} else {
OutParam<PropertyDefinitionBase> outParam =
new OutParam<PropertyDefinitionBase>();
outParam.setParam(this.otherPropertyDefinition);
result = PropertyDefinitionBase.tryLoadFromXml(reader,
outParam);
}
}
}
return result;
}
/**
* Writes the elements to XML.
*
* @param writer
* the writer
* @throws javax.xml.stream.XMLStreamException
* , ServiceXmlSerializationException
* @throws ServiceXmlSerializationException
* the service xml serialization exception
*/
@Override
protected void writeElementsToXml(EwsServiceXmlWriter writer)
throws XMLStreamException, ServiceXmlSerializationException {
super.writeElementsToXml(writer);
writer.writeStartElement(XmlNamespace.Types,
XmlElementNames.FieldURIOrConstant);
if (this.value != null) {
writer.writeStartElement(XmlNamespace.Types,
XmlElementNames.Constant);
writer.writeAttributeValue(XmlAttributeNames.Value,
true /* alwaysWriteEmptyString */,this.value);
writer.writeEndElement(); // Constant
} else {
this.otherPropertyDefinition.writeToXml(writer);
}
writer.writeEndElement(); // FieldURIOrConstant
}
/**
* Gets the definition of the property to compare with.
*
* @return otherPropertyDefinition
*/
public PropertyDefinitionBase getOtherPropertyDefinition() {
return this.otherPropertyDefinition;
}
/**
* Sets the definition of the property to compare with.
*
* @param OtherPropertyDefinition
* the new other property definition
*/
public void setOtherPropertyDefinition(
PropertyDefinitionBase OtherPropertyDefinition) {
this.otherPropertyDefinition = OtherPropertyDefinition;
this.value = null;
}
/**
* Gets the value of the property to compare with.
*
* @return the value
*/
public Object getValue() {
return value;
}
/**
* Sets the value of the property to compare with.
*
* @param value
* the new value
*/
public void setValue(Object value) {
this.value = value;
this.otherPropertyDefinition = null;
}
/**
* gets Xml Element name.
*
* @return the xml element name
*/
@Override
protected String getXmlElementName() {
return null;
}
}
/**
* Represents a collection of search filters linked by a logical operator.
* Applications can use SearchFilterCollection to define complex search
* filters such as "Condition1 AND Condition2".
*
*
*/
public static class SearchFilterCollection extends SearchFilter implements
Iterable<SearchFilter>, IComplexPropertyChangedDelegate {
/** The logical operator. */
private LogicalOperator logicalOperator = LogicalOperator.And;
/** The search filters. */
private ArrayList<SearchFilter> searchFilters =
new ArrayList<SearchFilter>();
/**
* Initializes a new instance of the class.
*/
public SearchFilterCollection() {
super();
}
/**
* Initializes a new instance of the class.
*
* @param logicalOperator
* The logical operator used to initialize the collection.
*/
public SearchFilterCollection(LogicalOperator logicalOperator) {
this.logicalOperator = logicalOperator;
}
/**
* Initializes a new instance of the class.
*
* @param logicalOperator
* The logical operator used to initialize the collection.
* @param searchFilters
* The search filters to add to the collection.
*/
public SearchFilterCollection(LogicalOperator logicalOperator,
SearchFilter... searchFilters) {
this(logicalOperator);
for (SearchFilter search : searchFilters) {
Iterable<SearchFilter> searchFil = java.util.Arrays
.asList(search);
this.addRange(searchFil);
}
}
/**
* Initializes a new instance of the class.
*
* @param logicalOperator
* The logical operator used to initialize the collection.
* @param searchFilters
* The search filters to add to the collection.
*/
public SearchFilterCollection(LogicalOperator logicalOperator,
Iterable<SearchFilter> searchFilters) {
this(logicalOperator);
this.addRange(searchFilters);
}
/**
* Validate instance.
* @throws Exception
*/
@Override
protected void internalValidate() throws Exception {
for (int i = 0; i < this.getCount(); i++) {
try {
this.searchFilters.get(i).internalValidate();
} catch (ServiceValidationException e) {
throw new ServiceValidationException(String.format(
Strings.SearchFilterAtIndexIsInvalid, i),
e);
}
}
}
/**
* A search filter has changed.
*
* @param complexProperty
* The complex property
*/
private void searchFilterChanged(ComplexProperty complexProperty) {
this.changed();
}
/**
* Gets the name of the XML element.
*
* @return xml element name
*/
@Override
protected String getXmlElementName() {
return this.logicalOperator.toString();
}
/**
* Tries to read element from XML.
*
* @param reader
* the reader
* @return true, if successful
* @throws Exception
* the exception
*/
@Override
protected boolean tryReadElementFromXml(EwsServiceXmlReader reader)
throws Exception {
this.add(SearchFilter.loadFromXml(reader));
return true;
}
/**
* Writes the elements to XML.
*
* @param writer
* the writer
* @throws Exception
* the exception
*/
@Override
protected void writeElementsToXml(EwsServiceXmlWriter writer)
throws Exception {
for (SearchFilter searchFilter : this.searchFilters) {
searchFilter.writeToXml(writer);
}
}
/**
* Writes to XML.
*
* @param writer
* the writer
* @throws Exception
* the exception
*/
@Override
protected void writeToXml(EwsServiceXmlWriter writer) throws Exception {
// If there is only one filter in the collection, which developers
// tend
// to do,
// we need to not emit the collection and instead only emit the one
// filter within
// the collection. This is to work around the fact that EWS does not
// allow filter
// collections that have less than two elements.
if (this.getCount() == 1) {
this.searchFilters.get(0).writeToXml(writer);
} else {
super.writeToXml(writer);
}
}
/**
* Adds a search filter of any type to the collection.
*
* @param searchFilter
* >The search filter to add. Available search filter classes
* include SearchFilter.IsEqualTo,
* SearchFilter.ContainsSubstring and
* SearchFilter.SearchFilterCollection.
*/
public void add(SearchFilter searchFilter) {
if (searchFilter == null) {
throw new IllegalArgumentException("searchFilter");
}
searchFilter.addOnChangeEvent(this);
this.searchFilters.add(searchFilter);
this.changed();
}
/**
* Adds multiple search filters to the collection.
*
* @param searchFilters
* The search filters to add. Available search filter classes
* include SearchFilter.IsEqualTo,
* SearchFilter.ContainsSubstring and
* SearchFilter.SearchFilterCollection
*/
public void addRange(Iterable<SearchFilter> searchFilters) {
if (searchFilters == null) {
throw new IllegalArgumentException("searchFilters");
}
for (SearchFilter searchFilter : searchFilters) {
searchFilter.addOnChangeEvent(this);
this.searchFilters.add(searchFilter);
}
this.changed();
}
/**
* Clears the collection.
*/
public void clear() {
if (this.getCount() > 0) {
for (SearchFilter searchFilter : this.searchFilters) {
searchFilter.removeChangeEvent(this);
}
this.searchFilters.clear();
this.changed();
}
}
/**
* Determines whether a specific search filter is in the collection.
*
* @param searchFilter
* The search filter to locate in the collection.
* @return True is the search filter was found in the collection, false
* otherwise.
*/
public boolean contains(SearchFilter searchFilter) {
return this.searchFilters.contains(searchFilter);
}
/**
* Removes a search filter from the collection.
*
* @param searchFilter
* The search filter to remove
*/
public void remove(SearchFilter searchFilter) {
if (searchFilter == null) {
throw new IllegalArgumentException("searchFilter");
}
if (this.contains(searchFilter)) {
searchFilter.removeChangeEvent(this);
this.searchFilters.remove(searchFilter);
this.changed();
}
}
/**
* Removes the search filter at the specified index from the collection.
*
* @param index
* The zero-based index of the search filter to remove.
*/
public void removeAt(int index) {
if (index < 0 || index >= this.getCount()) {
throw new IllegalArgumentException("index", new Throwable(
Strings.IndexIsOutOfRange));
}
this.searchFilters.get(index).removeChangeEvent(this);
this.searchFilters.remove(index);
this.changed();
}
/**
* Gets the total number of search filters in the collection.
*
* @return the count
*/
public int getCount() {
return this.searchFilters.size();
}
/**
* Gets the search filter at the specified index.
*
* @param index
* the index
* @return The search filter at the specified index.
*/
public SearchFilter getSearchFilter(int index) {
if (index < 0 || index >= this.getCount()) {
throw new IllegalArgumentException(Strings.IndexIsOutOfRange
+ ":" + index);
}
return this.searchFilters.get(index);
}
/**
* Sets the search filter at the specified index.
*
* @param index
* the index
* @param searchFilter
* the search filter
*/
public void setSearchFilter(int index, SearchFilter searchFilter) {
if (index < 0 || index >= this.getCount()) {
throw new IllegalArgumentException(Strings.IndexIsOutOfRange
+ ":" + index);
}
this.searchFilters.add(index, searchFilter);
}
/**
* Gets the logical operator that links the serach filters in this
* collection.
*
* @return LogicalOperator
*/
public LogicalOperator getLogicalOperator() {
return logicalOperator;
}
/**
* Sets the logical operator that links the serach filters in this
* collection.
*
* @param logicalOperator
* the new logical operator
*/
public void setLogicalOperator(LogicalOperator logicalOperator) {
this.logicalOperator = logicalOperator;
}
/*
* (non-Javadoc)
*
* @see
* microsoft.exchange.webservices.
* ComplexPropertyChangedDelegateInterface#
* complexPropertyChanged(microsoft.exchange.webservices.ComplexProperty
* )
*/
@Override
public void complexPropertyChanged(ComplexProperty complexProperty) {
searchFilterChanged(complexProperty);
}
/*
* (non-Javadoc)
*
* @see java.lang.Iterable#iterator()
*/
@Override
public Iterator<SearchFilter> iterator() {
return this.searchFilters.iterator();
}
}
}
| |
/*
* Copyright Terracotta, 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.terracotta.management.integration.tests;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import org.junit.Rule;
import org.junit.rules.Timeout;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.terracotta.connection.Connection;
import org.terracotta.connection.ConnectionFactory;
import org.terracotta.connection.ConnectionPropertyNames;
import org.terracotta.management.entity.nms.NmsConfig;
import org.terracotta.management.entity.nms.client.DefaultNmsService;
import org.terracotta.management.entity.nms.client.NmsEntity;
import org.terracotta.management.entity.nms.client.NmsEntityFactory;
import org.terracotta.management.entity.nms.client.NmsService;
import org.terracotta.management.entity.sample.Cache;
import org.terracotta.management.entity.sample.client.CacheFactory;
import org.terracotta.management.model.capabilities.context.CapabilityContext;
import org.terracotta.management.model.cluster.AbstractManageableNode;
import org.terracotta.management.model.cluster.ServerEntity;
import org.terracotta.management.model.notification.ContextualNotification;
import org.terracotta.management.model.stats.ContextualStatistics;
import org.terracotta.statistics.ConstantValueStatistic;
import org.terracotta.statistics.Sample;
import org.terracotta.statistics.StatisticType;
import org.terracotta.statistics.registry.Statistic;
import org.terracotta.testing.rules.Cluster;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.net.URI;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Properties;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.TimeUnit;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
/**
* @author Mathieu Carbou
*/
public abstract class AbstractTest {
protected Logger logger = LoggerFactory.getLogger(getClass());
private final ObjectMapper mapper = new ObjectMapper().configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY, true);
private Connection managementConnection;
protected Cluster cluster;
protected final List<CacheFactory> webappNodes = new ArrayList<>();
protected final Map<String, List<Cache>> caches = new HashMap<>();
protected NmsService nmsService;
@Rule
public Timeout timeout = Timeout.seconds(120);
protected final void commonSetUp(Cluster cluster) throws Exception {
this.cluster = cluster;
mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
mapper.addMixIn(CapabilityContext.class, CapabilityContextMixin.class);
mapper.addMixIn(Statistic.class, StatisticMixin.class);
mapper.addMixIn(ContextualStatistics.class, ContextualStatisticsMixin.class);
mapper.addMixIn(ConstantValueStatistic.class, ConstantValueStatisticMixin.class);
connectManagementClient(cluster.getConnectionURI());
addWebappNode(cluster.getConnectionURI(), "pet-clinic");
addWebappNode(cluster.getConnectionURI(), "pet-clinic");
getCaches("pets");
getCaches("clients");
}
protected final void commonTearDown() throws Exception {
closeNodes();
if (managementConnection != null) {
managementConnection.close();
}
if (cluster != null) {
cluster.getClusterControl().terminateAllServers();
}
}
protected JsonNode readJson(String file) {
try {
return mapper.readTree(new File(AbstractTest.class.getResource("/" + file).toURI()));
} catch (Exception e) {
throw new RuntimeException(e);
}
}
protected JsonNode readJsonStr(String json) {
try {
return mapper.readTree(json);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
protected JsonNode toJson(Object o) {
try {
return mapper.readTree(mapper.writeValueAsString(o));
} catch (Exception e) {
throw new RuntimeException(e);
}
}
protected int size(int nodeIdx, String cacheName) {
return caches.get(cacheName).get(nodeIdx).size();
}
protected String get(int nodeIdx, String cacheName, String key) {
return caches.get(cacheName).get(nodeIdx).get(key);
}
protected void put(int nodeIdx, String cacheName, String key, String value) {
caches.get(cacheName).get(nodeIdx).put(key, value);
}
protected void remove(int nodeIdx, String cacheName, String key) {
caches.get(cacheName).get(nodeIdx).remove(key);
}
protected void closeNodes() {
webappNodes.forEach(cacheFactory -> {
try {
cacheFactory.getConnection().close();
} catch (IOException ignored) {
}
});
}
protected void getCaches(String name) {
caches.put(name, webappNodes.stream().map(cacheFactory -> cacheFactory.getCache(name)).collect(Collectors.toList()));
}
protected void destroyCaches(String name) {
caches.remove(name);
webappNodes.forEach(cacheFactory -> cacheFactory.destroyCache(name));
}
protected void addWebappNode(URI uri, String path) throws Exception {
CacheFactory cacheFactory = new CacheFactory(nextInstanceId(), uri, path);
cacheFactory.init();
webappNodes.add(cacheFactory);
}
protected final String nextInstanceId() {
return "instance-" + webappNodes.size();
}
private void connectManagementClient(URI uri) throws Exception {
// connects to server
Properties properties = new Properties();
properties.setProperty(ConnectionPropertyNames.CONNECTION_NAME, getClass().getSimpleName());
properties.setProperty(ConnectionPropertyNames.CONNECTION_TIMEOUT, "20000");
this.managementConnection = ConnectionFactory.connect(uri, properties);
// create a NMS Entity
NmsEntityFactory nmsEntityFactory = new NmsEntityFactory(managementConnection, getClass().getSimpleName());
NmsEntity nmsEntity = nmsEntityFactory.retrieveOrCreate(new NmsConfig());
this.nmsService = new DefaultNmsService(nmsEntity);
this.nmsService.setOperationTimeout(60, TimeUnit.SECONDS);
}
protected void queryAllRemoteStatsUntil(Predicate<List<? extends ContextualStatistics>> test) throws InterruptedException {
List<? extends ContextualStatistics> statistics;
do {
statistics = nmsService.readMessages()
.stream()
.filter(message -> message.getType().equals("STATISTICS"))
.flatMap(message -> message.unwrap(ContextualStatistics.class).stream())
.collect(Collectors.toList());
// PLEASE KEEP THIS ! Really useful when troubleshooting stats!
/*if (!statistics.isEmpty()) {
System.out.println("received at " + System.currentTimeMillis() + ":");
statistics.stream()
.flatMap(o -> o.getStatistics().entrySet().stream())
.forEach(System.out::println);
}*/
Thread.sleep(500);
} while (!Thread.currentThread().isInterrupted() && (statistics.isEmpty() || !test.test(statistics)));
assertFalse(Thread.currentThread().isInterrupted());
assertTrue(test.test(statistics));
}
protected JsonNode removeRandomValues(JsonNode currentTopo) {
return readJsonStr(removeRandomValues(currentTopo.toString()));
}
protected String removeRandomValues(String currentTopo) {
// removes all random values
return currentTopo
.replaceAll("\"(hostName)\":\"[^\"]*\"", "\"$1\":\"<hostname>\"")
.replaceAll("\"hostAddress\":[^,]*", "\"hostAddress\":\"127\\.0\\.0\\.1\"")
.replaceAll("\"bindPort\":[0-9]+", "\"bindPort\":0")
.replaceAll("\"groupPort\":[0-9]+", "\"groupPort\":0")
.replaceAll("\"port\":[0-9]+", "\"port\":0")
.replaceAll("\"activateTime\":[0-9]+", "\"activateTime\":0")
.replaceAll("\"availableAtTime\":[0-9]+", "\"availableAtTime\":0")
.replaceAll("\"OffHeapResource:AllocatedMemory\":[0-9]+", "\"OffHeapResource:AllocatedMemory\":0")
.replaceAll("\"time\":[0-9]+", "\"time\":0")
.replaceAll("\"startTime\":[0-9]+", "\"startTime\":0")
.replaceAll("\"timestamp\":[0-9]+", "\"timestamp\":0")
.replaceAll("\"upTimeSec\":[0-9]+", "\"upTimeSec\":0")
.replaceAll("\"id\":\"[0-9]+@[^:]*:([^:]*):[^\"]*\",\"pid\":[0-9]+", "\"id\":\"0@127.0.0.1:$1:<uuid>\",\"pid\":0")
.replaceAll("\"alias\":\"[0-9]+@[^:]*:([^:]*):[^\"]*\",", "\"alias\":\"0@127.0.0.1:$1:<uuid>\",")
.replaceAll("\"buildId\":\"[^\"]*\"", "\"buildId\":\"Build ID\"")
.replaceAll("\"version\":\"[^\"]*\"", "\"version\":\"<version>\"")
.replaceAll("\"clientId\":\"[0-9]+@[^:]*:([^:]*):[^\"]*\"", "\"clientId\":\"0@127.0.0.1:$1:<uuid>\"")
.replaceAll("\"logicalConnectionUid\":\"[^\"]*\"", "\"logicalConnectionUid\":\"<uuid>\"")
.replaceAll("\"id\":\"[^\"]+:([\\w\\[\\]]+):[^\"]+:[^\"]+:[^\"]+\",\"logicalConnectionUid\":\"[^\"]*\"", "\"id\":\"<uuid>:$1:testServer0:127.0.0.1:0\",\"logicalConnectionUid\":\"<uuid>\"")
.replaceAll("\"vmId\":\"[^\"]*\"", "\"vmId\":\"0@127.0.0.1\"")
.replaceAll("-2", "")
.replaceAll("instance-0", "instance-?")
.replaceAll("instance-1", "instance-?")
.replaceAll("testServer1", "testServer0")
.replaceAll("\"(clientReportedAddress)\":\"[^\"]*\"", "\"$1\":\"<$1>\"")
.replaceAll("\"clientRevision\":\"[^\"]*\"", "\"clientRevision\":\"<uuid>\"");
}
protected void triggerServerStatComputation() throws Exception {
triggerServerStatComputation(1, TimeUnit.SECONDS);
}
protected void triggerServerStatComputation(long interval, TimeUnit unit) throws Exception {
triggerServerStatComputation(nmsService, getClass().getSimpleName(), interval, unit);
}
@SuppressWarnings("rawtypes")
protected void triggerServerStatComputation(NmsService nmsService, String entityName, long interval, TimeUnit unit) throws Exception {
logger.info("triggerServerStatComputation({}, {}, {})", entityName, interval, unit);
// trigger stats computation and wait for all stats to have been computed at least once
org.terracotta.management.model.cluster.Cluster topology = nmsService.readTopology();
logger.trace("topology:\n{}", toJson(topology.toMap()));
CompletableFuture.allOf(topology
.serverEntityStream()
.filter(e -> e.getType().equals(NmsConfig.ENTITY_TYPE) && e.getName().equals(entityName))
.filter(AbstractManageableNode::isManageable)
.map(ServerEntity::getContext)
.map(context -> {
try {
return nmsService.startStatisticCollector(context, interval, unit).asCompletionStage();
} catch (Exception e) {
throw new RuntimeException(e);
}
})
.map(CompletionStage::toCompletableFuture)
.toArray(CompletableFuture[]::new)).get();
}
protected void triggerClientStatComputation() throws Exception {
triggerClientStatComputation(1, TimeUnit.SECONDS);
}
@SuppressWarnings("rawtypes")
protected void triggerClientStatComputation(long interval, TimeUnit unit) throws Exception {
logger.info("triggerClientStatComputation({}, {})", interval, unit);
// trigger stats computation and wait for all stats to have been computed at least once
org.terracotta.management.model.cluster.Cluster topology = nmsService.readTopology();
logger.trace("topology:\n{}", toJson(topology.toMap()));
CompletableFuture.allOf(topology
.clientStream()
.filter(client -> client.getName().equals("pet-clinic"))
.filter(AbstractManageableNode::isManageable)
.map(AbstractManageableNode::getContext)
.map(context -> {
try {
return nmsService.startStatisticCollector(context, interval, unit).asCompletionStage();
} catch (Exception e) {
throw new RuntimeException(e);
}
})
.map(CompletionStage::toCompletableFuture)
.toArray(CompletableFuture[]::new)).get();
}
protected List<ContextualNotification> waitForAllNotifications(String... notificationTypes) throws InterruptedException {
List<String> waitingFor = new ArrayList<>(Arrays.asList(notificationTypes));
try {
return nmsService.waitForMessage(message -> {
if (message.getType().equals("NOTIFICATION")) {
for (ContextualNotification notification : message.unwrap(ContextualNotification.class)) {
waitingFor.remove(notification.getType());
}
}
return waitingFor.isEmpty();
}).stream()
.filter(message -> message.getType().equals("NOTIFICATION"))
.flatMap(message -> message.unwrap(ContextualNotification.class).stream())
.collect(Collectors.toList());
} catch (InterruptedException e) {
System.err.println("STILL WAITING FOR: " + waitingFor);
throw e;
}
}
public static abstract class CapabilityContextMixin {
@JsonIgnore
public abstract Collection<String> getRequiredAttributeNames();
@JsonIgnore
public abstract Collection<CapabilityContext.Attribute> getRequiredAttributes();
}
public static abstract class StatisticMixin<T extends Serializable> {
@JsonIgnore
public abstract boolean isEmpty();
@JsonIgnore
public abstract Optional<T> getLatestSampleValue();
@JsonIgnore
public abstract Optional<Sample<T>> getLatestSample();
}
public static abstract class ContextualStatisticsMixin {
@JsonIgnore
public abstract int size();
@JsonIgnore
public abstract boolean isEmpty();
@JsonIgnore
public abstract Map<String, ? extends Serializable> getLatestSampleValues();
@JsonIgnore
public abstract Map<String, Sample<? extends Serializable>> getLatestSamples();
}
public static abstract class ConstantValueStatisticMixin<T> {
@JsonProperty
public abstract T value();
@JsonProperty
public abstract StatisticType type();
}
}
| |
package quickfix.fix42;
import quickfix.FieldNotFound;
import quickfix.Group;
public class Logon extends Message
{
static final long serialVersionUID = 20050617;
public static final String MSGTYPE = "A";
public Logon()
{
super();
getHeader().setField(new quickfix.field.MsgType(MSGTYPE));
}
public Logon(quickfix.field.EncryptMethod encryptMethod, quickfix.field.HeartBtInt heartBtInt) {
this();
setField(encryptMethod);
setField(heartBtInt);
}
public void set(quickfix.field.EncryptMethod value)
{
setField(value);
}
public quickfix.field.EncryptMethod get(quickfix.field.EncryptMethod value) throws FieldNotFound
{
getField(value);
return value;
}
public quickfix.field.EncryptMethod getEncryptMethod() throws FieldNotFound
{
quickfix.field.EncryptMethod value = new quickfix.field.EncryptMethod();
getField(value);
return value;
}
public boolean isSet(quickfix.field.EncryptMethod field)
{
return isSetField(field);
}
public boolean isSetEncryptMethod()
{
return isSetField(98);
}
public void set(quickfix.field.HeartBtInt value)
{
setField(value);
}
public quickfix.field.HeartBtInt get(quickfix.field.HeartBtInt value) throws FieldNotFound
{
getField(value);
return value;
}
public quickfix.field.HeartBtInt getHeartBtInt() throws FieldNotFound
{
quickfix.field.HeartBtInt value = new quickfix.field.HeartBtInt();
getField(value);
return value;
}
public boolean isSet(quickfix.field.HeartBtInt field)
{
return isSetField(field);
}
public boolean isSetHeartBtInt()
{
return isSetField(108);
}
public void set(quickfix.field.RawDataLength value)
{
setField(value);
}
public quickfix.field.RawDataLength get(quickfix.field.RawDataLength value) throws FieldNotFound
{
getField(value);
return value;
}
public quickfix.field.RawDataLength getRawDataLength() throws FieldNotFound
{
quickfix.field.RawDataLength value = new quickfix.field.RawDataLength();
getField(value);
return value;
}
public boolean isSet(quickfix.field.RawDataLength field)
{
return isSetField(field);
}
public boolean isSetRawDataLength()
{
return isSetField(95);
}
public void set(quickfix.field.RawData value)
{
setField(value);
}
public quickfix.field.RawData get(quickfix.field.RawData value) throws FieldNotFound
{
getField(value);
return value;
}
public quickfix.field.RawData getRawData() throws FieldNotFound
{
quickfix.field.RawData value = new quickfix.field.RawData();
getField(value);
return value;
}
public boolean isSet(quickfix.field.RawData field)
{
return isSetField(field);
}
public boolean isSetRawData()
{
return isSetField(96);
}
public void set(quickfix.field.ResetSeqNumFlag value)
{
setField(value);
}
public quickfix.field.ResetSeqNumFlag get(quickfix.field.ResetSeqNumFlag value) throws FieldNotFound
{
getField(value);
return value;
}
public quickfix.field.ResetSeqNumFlag getResetSeqNumFlag() throws FieldNotFound
{
quickfix.field.ResetSeqNumFlag value = new quickfix.field.ResetSeqNumFlag();
getField(value);
return value;
}
public boolean isSet(quickfix.field.ResetSeqNumFlag field)
{
return isSetField(field);
}
public boolean isSetResetSeqNumFlag()
{
return isSetField(141);
}
public void set(quickfix.field.MaxMessageSize value)
{
setField(value);
}
public quickfix.field.MaxMessageSize get(quickfix.field.MaxMessageSize value) throws FieldNotFound
{
getField(value);
return value;
}
public quickfix.field.MaxMessageSize getMaxMessageSize() throws FieldNotFound
{
quickfix.field.MaxMessageSize value = new quickfix.field.MaxMessageSize();
getField(value);
return value;
}
public boolean isSet(quickfix.field.MaxMessageSize field)
{
return isSetField(field);
}
public boolean isSetMaxMessageSize()
{
return isSetField(383);
}
public void set(quickfix.field.NoMsgTypes value)
{
setField(value);
}
public quickfix.field.NoMsgTypes get(quickfix.field.NoMsgTypes value) throws FieldNotFound
{
getField(value);
return value;
}
public quickfix.field.NoMsgTypes getNoMsgTypes() throws FieldNotFound
{
quickfix.field.NoMsgTypes value = new quickfix.field.NoMsgTypes();
getField(value);
return value;
}
public boolean isSet(quickfix.field.NoMsgTypes field)
{
return isSetField(field);
}
public boolean isSetNoMsgTypes()
{
return isSetField(384);
}
public static class NoMsgTypes extends Group {
static final long serialVersionUID = 20050617;
public NoMsgTypes() {
super(384, 372,
new int[] {372, 385, 0 } );
}
public void set(quickfix.field.RefMsgType value)
{
setField(value);
}
public quickfix.field.RefMsgType get(quickfix.field.RefMsgType value) throws FieldNotFound
{
getField(value);
return value;
}
public quickfix.field.RefMsgType getRefMsgType() throws FieldNotFound
{
quickfix.field.RefMsgType value = new quickfix.field.RefMsgType();
getField(value);
return value;
}
public boolean isSet(quickfix.field.RefMsgType field)
{
return isSetField(field);
}
public boolean isSetRefMsgType()
{
return isSetField(372);
}
public void set(quickfix.field.MsgDirection value)
{
setField(value);
}
public quickfix.field.MsgDirection get(quickfix.field.MsgDirection value) throws FieldNotFound
{
getField(value);
return value;
}
public quickfix.field.MsgDirection getMsgDirection() throws FieldNotFound
{
quickfix.field.MsgDirection value = new quickfix.field.MsgDirection();
getField(value);
return value;
}
public boolean isSet(quickfix.field.MsgDirection field)
{
return isSetField(field);
}
public boolean isSetMsgDirection()
{
return isSetField(385);
}
}
}
| |
/*
* Copyright 2006-2021 Prowide
*
* 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.prowidesoftware.swift.model.field;
import com.prowidesoftware.swift.model.Tag;
import com.prowidesoftware.Generated;
import com.prowidesoftware.deprecation.ProwideDeprecated;
import com.prowidesoftware.deprecation.TargetYear;
import java.io.Serializable;
import java.util.Locale;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import java.util.Calendar;
import com.prowidesoftware.swift.model.field.GenericField;
import com.prowidesoftware.swift.model.field.DateContainer;
import com.prowidesoftware.swift.model.field.DateResolver;
import org.apache.commons.lang3.StringUtils;
import com.prowidesoftware.swift.model.field.SwiftParseUtils;
import com.prowidesoftware.swift.model.field.Field;
import com.prowidesoftware.swift.model.*;
import com.prowidesoftware.swift.utils.SwiftFormatUtils;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
/**
* SWIFT MT Field 69D.
* <p>
* Model and parser for field 69D of a SWIFT MT message.
*
* <p>Subfields (components) Data types
* <ol>
* <li><code>String</code></li>
* <li><code>Calendar</code></li>
* <li><code>Calendar</code></li>
* <li><code>String</code></li>
* </ol>
*
* <p>Structure definition
* <ul>
* <li>validation pattern: <code>:4!c//<DATE4><TIME2>/4!c</code></li>
* <li>parser pattern: <code>:S//<DATE4><TIME2>/S</code></li>
* <li>components pattern: <code>SDTS</code></li>
* </ul>
*
* <p>
* This class complies with standard release <strong>SRU2021</strong>
*/
@SuppressWarnings("unused")
@Generated
public class Field69D extends Field implements Serializable, DateContainer, GenericField {
/**
* Constant identifying the SRU to which this class belongs to.
*/
public static final int SRU = 2021;
private static final long serialVersionUID = 1L;
/**
* Constant with the field name 69D.
*/
public static final String NAME = "69D";
/**
* Same as NAME, intended to be clear when using static imports.
*/
public static final String F_69D = "69D";
/**
* @deprecated use {@link #parserPattern()} method instead.
*/
@Deprecated
@ProwideDeprecated(phase2 = TargetYear.SRU2022)
public static final String PARSER_PATTERN = ":S//<DATE4><TIME2>/S";
/**
* @deprecated use {@link #typesPattern()} method instead.
*/
@Deprecated
@ProwideDeprecated(phase2 = TargetYear.SRU2022)
public static final String COMPONENTS_PATTERN = "SDTS";
/**
* @deprecated use {@link #typesPattern()} method instead.
*/
@Deprecated
@ProwideDeprecated(phase2 = TargetYear.SRU2022)
public static final String TYPES_PATTERN = "SDTS";
/**
* Component number for the Qualifier subfield.
*/
public static final Integer QUALIFIER = 1;
/**
* Component number for the Date subfield.
*/
public static final Integer DATE = 2;
/**
* Component number for the Time subfield.
*/
public static final Integer TIME = 3;
/**
* Component number for the Date Code subfield.
*/
public static final Integer DATE_CODE = 4;
/**
* Default constructor. Creates a new field setting all components to null.
*/
public Field69D() {
super(4);
}
/**
* Creates a new field and initializes its components with content from the parameter value.
* @param value complete field value including separators and CRLF
*/
public Field69D(final String value) {
super(value);
}
/**
* Creates a new field and initializes its components with content from the parameter tag.
* The value is parsed with {@link #parse(String)}
* @throws IllegalArgumentException if the parameter tag is null or its tagname does not match the field name
* @since 7.8
*/
public Field69D(final Tag tag) {
this();
if (tag == null) {
throw new IllegalArgumentException("tag cannot be null.");
}
if (!StringUtils.equals(tag.getName(), "69D")) {
throw new IllegalArgumentException("cannot create field 69D from tag "+tag.getName()+", tagname must match the name of the field.");
}
parse(tag.getValue());
}
/**
* Copy constructor.
* Initializes the components list with a deep copy of the source components list.
* @param source a field instance to copy
* @since 7.7
*/
public static Field69D newInstance(Field69D source) {
Field69D cp = new Field69D();
cp.setComponents(new ArrayList<>(source.getComponents()));
return cp;
}
/**
* Create a Tag with this field name and the given value.
* Shorthand for <code>new Tag(NAME, value)</code>
* @see #NAME
* @since 7.5
*/
public static Tag tag(final String value) {
return new Tag(NAME, value);
}
/**
* Create a Tag with this field name and an empty string as value.
* Shorthand for <code>new Tag(NAME, "")</code>
* @see #NAME
* @since 7.5
*/
public static Tag emptyTag() {
return new Tag(NAME, "");
}
/**
* Parses the parameter value into the internal components structure.
*
* <p>Used to update all components from a full new value, as an alternative
* to setting individual components. Previous component values are overwritten.
*
* @param value complete field value including separators and CRLF
* @since 7.8
*/
@Override
public void parse(final String value) {
init(4);
setComponent1(SwiftParseUtils.getTokenFirst(value, ":", "//"));
String toparse = SwiftParseUtils.getTokenSecondLast(value, "//");
String toparse2 = SwiftParseUtils.getTokenFirst(toparse, "/");
setComponent4(SwiftParseUtils.getTokenSecondLast(toparse, "/"));
if (toparse2 != null) {
if (toparse2.length() >= 8) {
setComponent2(StringUtils.substring(toparse2, 0, 8));
}
if (toparse2.length() > 8) {
setComponent3(StringUtils.substring(toparse2, 8));
}
}
}
/**
* Serializes the fields' components into the single string value (SWIFT format)
*/
@Override
public String getValue() {
final StringBuilder result = new StringBuilder();
result.append(":");
append(result, 1);
result.append("//");
append(result, 2);
append(result, 3);
result.append("/");
append(result, 4);
return result.toString();
}
/**
* Returns a localized suitable for showing to humans string of a field component.<br>
*
* @param component number of the component to display
* @param locale optional locale to format date and amounts, if null, the default locale is used
* @return formatted component value or null if component number is invalid or not present
* @throws IllegalArgumentException if component number is invalid for the field
* @since 7.8
*/
@Override
public String getValueDisplay(int component, Locale locale) {
if (component < 1 || component > 4) {
throw new IllegalArgumentException("invalid component number " + component + " for field 69D");
}
if (component == 1) {
//default format (as is)
return getComponent(1);
}
if (component == 2) {
//date: [YY]YYMMDD
java.text.DateFormat f = java.text.DateFormat.getDateInstance(java.text.DateFormat.DEFAULT, notNull(locale));
java.util.Calendar cal = getComponent2AsCalendar();
if (cal != null) {
return f.format(cal.getTime());
}
}
if (component == 3) {
//time with seconds: HHmmss
java.text.DateFormat f = new java.text.SimpleDateFormat("HH:mm:ss", notNull(locale));
java.util.Calendar cal = getComponent3AsCalendar();
if (cal != null) {
return f.format(cal.getTime());
}
}
if (component == 4) {
//default format (as is)
return getComponent(4);
}
return null;
}
/**
* @deprecated use {@link #typesPattern()} instead.
*/
@Override
@Deprecated
@ProwideDeprecated(phase2 = TargetYear.SRU2022)
public String componentsPattern() {
return "SDTS";
}
/**
* Returns the field component types pattern.
*
* This method returns a letter representing the type for each component in the Field. It supersedes
* the Components Pattern because it distinguishes between N (Number) and I (BigDecimal).
* @since 9.2.7
*/
@Override
public String typesPattern() {
return "SDTS";
}
/**
* Returns the field parser pattern.
*/
@Override
public String parserPattern() {
return ":S//<DATE4><TIME2>/S";
}
/**
* Returns the field validator pattern
*/
@Override
public String validatorPattern() {
return ":4!c//<DATE4><TIME2>/4!c";
}
/**
* Given a component number it returns true if the component is optional,
* regardless of the field being mandatory in a particular message.<br>
* Being the field's value conformed by a composition of one or several
* internal component values, the field may be present in a message with
* a proper value but with some of its internal components not set.
*
* @param component component number, first component of a field is referenced as 1
* @return true if the component is optional for this field, false otherwise
*/
@Override
public boolean isOptional(int component) {
return false;
}
/**
* Returns true if the field is a GENERIC FIELD as specified by the standard.
* @return true if the field is generic, false otherwise
*/
@Override
public boolean isGeneric() {
return true;
}
/**
* Returns the defined amount of components.<br>
* This is not the amount of components present in the field instance, but the total amount of components
* that this field accepts as defined.
* @since 7.7
*/
@Override
public int componentsSize() {
return 4;
}
/**
* Returns english label for components.
* <br>
* The index in the list is in sync with specific field component structure.
* @see #getComponentLabel(int)
* @since 7.8.4
*/
@Override
public List<String> getComponentLabels() {
List<String> result = new ArrayList<>();
result.add("Qualifier");
result.add("Date");
result.add("Time");
result.add("Date Code");
return result;
}
/**
* Returns a mapping between component numbers and their label in camel case format.
* @since 7.10.3
*/
@Override
protected Map<Integer, String> getComponentMap() {
Map<Integer, String> result = new HashMap<>();
result.put(1, "qualifier");
result.put(2, "date");
result.put(3, "time");
result.put(4, "dateCode");
return result;
}
/**
* Gets the component 1 (Qualifier).
* @return the component 1
*/
public String getComponent1() {
return getComponent(1);
}
/**
* Gets the Qualifier (component 1).
* @return the Qualifier from component 1
*/
public String getQualifier() {
return getComponent1();
}
/**
* Gets the component 2 (Date).
* @return the component 2
*/
public String getComponent2() {
return getComponent(2);
}
/**
* Get the component 2 as Calendar
*
* @return the component 2 converted to Calendar or null if cannot be converted
*/
public java.util.Calendar getComponent2AsCalendar() {
return SwiftFormatUtils.getDate4(getComponent(2));
}
/**
* Gets the Date (component 2).
* @return the Date from component 2
*/
public String getDate() {
return getComponent2();
}
/**
* Get the Date (component 2) as Calendar
* @return the Date from component 2 converted to Calendar or null if cannot be converted
*/
public java.util.Calendar getDateAsCalendar() {
return getComponent2AsCalendar();
}
/**
* Gets the component 3 (Time).
* @return the component 3
*/
public String getComponent3() {
return getComponent(3);
}
/**
* Get the component 3 as Calendar
*
* @return the component 3 converted to Calendar or null if cannot be converted
*/
public java.util.Calendar getComponent3AsCalendar() {
return SwiftFormatUtils.getTime2(getComponent(3));
}
/**
* Gets the Time (component 3).
* @return the Time from component 3
*/
public String getTime() {
return getComponent3();
}
/**
* Get the Time (component 3) as Calendar
* @return the Time from component 3 converted to Calendar or null if cannot be converted
*/
public java.util.Calendar getTimeAsCalendar() {
return getComponent3AsCalendar();
}
/**
* Gets the component 4 (Date Code).
* @return the component 4
*/
public String getComponent4() {
return getComponent(4);
}
/**
* Gets the Date Code (component 4).
* @return the Date Code from component 4
*/
public String getDateCode() {
return getComponent4();
}
/**
* Set the component 1 (Qualifier).
*
* @param component1 the Qualifier to set
* @return the field object to enable build pattern
*/
public Field69D setComponent1(String component1) {
setComponent(1, component1);
return this;
}
/**
* Set the Qualifier (component 1).
*
* @param component1 the Qualifier to set
* @return the field object to enable build pattern
*/
public Field69D setQualifier(String component1) {
return setComponent1(component1);
}
/**
* Set the component 2 (Date).
*
* @param component2 the Date to set
* @return the field object to enable build pattern
*/
public Field69D setComponent2(String component2) {
setComponent(2, component2);
return this;
}
/**
* Set the component2 from a Calendar object.
*
* @param component2 the Calendar with the Date content to set
* @return the field object to enable build pattern
*/
public Field69D setComponent2(java.util.Calendar component2) {
setComponent(2, SwiftFormatUtils.getDate4(component2));
return this;
}
/**
* Set the Date (component 2).
*
* @param component2 the Date to set
* @return the field object to enable build pattern
*/
public Field69D setDate(String component2) {
return setComponent2(component2);
}
/**
* Set the Date (component 2) from a Calendar object.
*
* @see #setComponent2(java.util.Calendar)
*
* @param component2 Calendar with the Date content to set
* @return the field object to enable build pattern
*/
public Field69D setDate(java.util.Calendar component2) {
return setComponent2(component2);
}
/**
* Set the component 3 (Time).
*
* @param component3 the Time to set
* @return the field object to enable build pattern
*/
public Field69D setComponent3(String component3) {
setComponent(3, component3);
return this;
}
/**
* Set the component3 from a Calendar object.
*
* @param component3 the Calendar with the Time content to set
* @return the field object to enable build pattern
*/
public Field69D setComponent3(java.util.Calendar component3) {
setComponent(3, SwiftFormatUtils.getTime2(component3));
return this;
}
/**
* Set the Time (component 3).
*
* @param component3 the Time to set
* @return the field object to enable build pattern
*/
public Field69D setTime(String component3) {
return setComponent3(component3);
}
/**
* Set the Time (component 3) from a Calendar object.
*
* @see #setComponent3(java.util.Calendar)
*
* @param component3 Calendar with the Time content to set
* @return the field object to enable build pattern
*/
public Field69D setTime(java.util.Calendar component3) {
return setComponent3(component3);
}
/**
* Set the component 4 (Date Code).
*
* @param component4 the Date Code to set
* @return the field object to enable build pattern
*/
public Field69D setComponent4(String component4) {
setComponent(4, component4);
return this;
}
/**
* Set the Date Code (component 4).
*
* @param component4 the Date Code to set
* @return the field object to enable build pattern
*/
public Field69D setDateCode(String component4) {
return setComponent4(component4);
}
/**
* Returns all components that can be converted to a Calendar
*
* @return the list of converted components (a Calendar object or null)
*/
public List<Calendar> dates() {
return DateResolver.dates(this);
}
/**
* Returns the first component that can be converted to a Calendar
*
* @return the converted components (a Calendar object or null)
*/
public Calendar date() {
return DateResolver.date(this);
}
/**
* Returns the issuer code (or Data Source Scheme or DSS).
* The DSS is only present in some generic fields, when present, is equals to component two.
*
* @return DSS component value or null if the DSS is not set or not available for this field.
*/
public String getDSS() {
return null;
}
/**
* Checks if the issuer code (or Data Source Scheme or DSS) is present.
*
* @see #getDSS()
* @return true if DSS is present, false otherwise.
*/
public boolean isDSSPresent() {
return false;
}
/**
* Component number for the conditional qualifier subfield.
*/
public static final Integer CONDITIONAL_QUALIFIER = 4;
/**
* Gets the component with the conditional (secondary) qualifier.
*
* @return for generic fields returns the value of the conditional qualifier or null if not set or not applicable for this field.
*/
public String getConditionalQualifier() {
return getComponent(CONDITIONAL_QUALIFIER);
}
/**
* Returns the field's name composed by the field number and the letter option (if any).
* @return the static value of Field69D.NAME
*/
@Override
public String getName() {
return NAME;
}
/**
* Gets the first occurrence form the tag list or null if not found.
* @return null if not found o block is null or empty
* @param block may be null or empty
*/
public static Field69D get(final SwiftTagListBlock block) {
if (block == null || block.isEmpty()) {
return null;
}
final Tag t = block.getTagByName(NAME);
if (t == null) {
return null;
}
return new Field69D(t);
}
/**
* Gets the first instance of Field69D in the given message.
* @param msg may be empty or null
* @return null if not found or msg is empty or null
* @see #get(SwiftTagListBlock)
*/
public static Field69D get(final SwiftMessage msg) {
if (msg == null || msg.getBlock4() == null || msg.getBlock4().isEmpty()) {
return null;
}
return get(msg.getBlock4());
}
/**
* Gets a list of all occurrences of the field Field69D in the given message
* an empty list is returned if none found.
* @param msg may be empty or null in which case an empty list is returned
* @see #getAll(SwiftTagListBlock)
*/
public static List<Field69D> getAll(final SwiftMessage msg) {
if (msg == null || msg.getBlock4() == null || msg.getBlock4().isEmpty()) {
return java.util.Collections.emptyList();
}
return getAll(msg.getBlock4());
}
/**
* Gets a list of all occurrences of the field Field69D from the given block
* an empty list is returned if none found.
*
* @param block may be empty or null in which case an empty list is returned
*/
public static List<Field69D> getAll(final SwiftTagListBlock block) {
final List<Field69D> result = new ArrayList<>();
if (block == null || block.isEmpty()) {
return result;
}
final Tag[] arr = block.getTagsByName(NAME);
if (arr != null && arr.length > 0) {
for (final Tag f : arr) {
result.add(new Field69D(f));
}
}
return result;
}
/**
* This method deserializes the JSON data into a Field69D object.
* @param json JSON structure including tuples with label and value for all field components
* @return a new field instance with the JSON data parsed into field components or an empty field id the JSON is invalid
* @since 7.10.3
* @see Field#fromJson(String)
*/
public static Field69D fromJson(final String json) {
final Field69D field = new Field69D();
final JsonObject jsonObject = JsonParser.parseString(json).getAsJsonObject();
// **** COMPONENT 1 - Qualifier
if (jsonObject.get("qualifier") != null) {
field.setComponent1(jsonObject.get("qualifier").getAsString());
}
// **** COMPONENT 2 - Date
if (jsonObject.get("date") != null) {
field.setComponent2(jsonObject.get("date").getAsString());
}
// **** COMPONENT 3 - Time
if (jsonObject.get("time") != null) {
field.setComponent3(jsonObject.get("time").getAsString());
}
// **** COMPONENT 4 - Date Code
if (jsonObject.get("dateCode") != null) {
field.setComponent4(jsonObject.get("dateCode").getAsString());
}
return field;
}
}
| |
/*
* ModeShape (http://www.modeshape.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.
*/
package org.modeshape.jcr.cache.change;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import org.modeshape.jcr.ExecutionContext;
import org.modeshape.jcr.cache.CachedNode.Properties;
import org.modeshape.jcr.cache.NodeKey;
import org.modeshape.jcr.value.BinaryKey;
import org.modeshape.jcr.value.Name;
import org.modeshape.jcr.value.Path;
import org.modeshape.jcr.value.Path.Segment;
import org.modeshape.jcr.value.Property;
/**
* An adapter class that processes {@link ChangeSet} instances and for each {@link Change} calls the appropriate protected method
* that, by default, do nothing. Implementations simply override at least one of the relevant methods for the kind of changes they
* expect.
*
* @author Randall Hauch (rhauch@redhat.com)
*/
public abstract class ChangeSetAdapter implements ChangeSetListener {
protected final ExecutionContext context;
/**
* @param context the execution context in which this adapter is supposed to run; may not be null
*/
public ChangeSetAdapter( ExecutionContext context ) {
assert context != null;
this.context = context;
}
@Override
public void notify( ChangeSet changeSet ) {
final String workspaceName = changeSet.getWorkspaceName();
if (workspaceName != null) {
if (includesWorkspace(workspaceName)) {
try {
beginWorkspaceChanges();
final Map<Name, AbstractPropertyChange> propChanges = new HashMap<>();
NodeKey lastKey = null;
for (Change change : changeSet) {
if (change instanceof AbstractNodeChange) {
if (change instanceof NodeAdded) {
firePropertyChanges(lastKey, propChanges);
NodeAdded added = (NodeAdded)change;
addNode(workspaceName, added.getKey(), added.getPath(), added.getPrimaryType(),
added.getMixinTypes(), props(added.getProperties()), added.isQueryable());
} else if (change instanceof NodeRemoved) {
firePropertyChanges(lastKey, propChanges);
NodeRemoved removed = (NodeRemoved)change;
removeNode(workspaceName, removed.getKey(), removed.getParentKey(), removed.getPath(),
removed.getPrimaryType(), removed.getMixinTypes(), removed.isQueryable());
} else if (change instanceof AbstractPropertyChange) {
AbstractPropertyChange propChange = (AbstractPropertyChange)change;
if (propChange.getKey().equals(lastKey)) firePropertyChanges(lastKey, propChanges);
propChanges.put(propChange.getProperty().getName(), propChange);
} else if (change instanceof NodeChanged) {
firePropertyChanges(lastKey, propChanges);
NodeChanged nodeChanged = (NodeChanged)change;
changeNode(workspaceName, nodeChanged.getKey(), nodeChanged.getPath(),
nodeChanged.getPrimaryType(), nodeChanged.getMixinTypes(), nodeChanged.isQueryable());
} else if (change instanceof NodeMoved) {
firePropertyChanges(lastKey, propChanges);
NodeMoved moved = (NodeMoved)change;
moveNode(workspaceName, moved.getKey(), moved.getPrimaryType(), moved.getMixinTypes(),
moved.getNewParent(), moved.getOldParent(), moved.getNewPath(), moved.getOldPath(),
moved.isQueryable());
} else if (change instanceof NodeRenamed) {
firePropertyChanges(lastKey, propChanges);
NodeRenamed renamed = (NodeRenamed)change;
renameNode(workspaceName, renamed.getKey(), renamed.getPath(), renamed.getOldSegment(),
renamed.getPrimaryType(), renamed.getMixinTypes(), renamed.isQueryable());
} else if (change instanceof NodeReordered) {
firePropertyChanges(lastKey, propChanges);
NodeReordered reordered = (NodeReordered)change;
reorderNode(workspaceName, reordered.getKey(), reordered.getPrimaryType(),
reordered.getMixinTypes(), reordered.getParent(), reordered.getPath(),
reordered.getOldPath(), reordered.getReorderedBeforePath(), reordered.isQueryable());
} else if (change instanceof NodeSequenced) {
firePropertyChanges(lastKey, propChanges);
NodeSequenced s = (NodeSequenced)change;
sequenced(workspaceName, s.getKey(), s.getPath(), s.getPrimaryType(), s.getMixinTypes(),
s.getOutputNodeKey(), s.getOutputNodePath(), s.getOutputPath(), s.getUserId(),
s.getSelectedPath(), s.getSequencerName(), s.isQueryable());
} else if (change instanceof NodeSequencingFailure) {
firePropertyChanges(lastKey, propChanges);
NodeSequencingFailure f = (NodeSequencingFailure)change;
sequenceFailure(workspaceName, f.getKey(), f.getPath(), f.getPrimaryType(), f.getMixinTypes(),
f.getOutputPath(), f.getUserId(), f.getSelectedPath(), f.getSequencerName(),
f.isQueryable(), f.getCause());
}
lastKey = ((AbstractNodeChange)change).getKey();
}
}
} finally {
completeWorkspaceChanges();
}
}
} else {
for (Change change : changeSet) {
if (change instanceof WorkspaceAdded) {
WorkspaceAdded added = (WorkspaceAdded)change;
addWorkspace(added.getWorkspaceName());
} else if (change instanceof WorkspaceRemoved) {
WorkspaceRemoved removed = (WorkspaceRemoved)change;
removeWorkspace(removed.getWorkspaceName());
} else if (change instanceof RepositoryMetadataChanged) {
repositoryMetadataChanged();
} else if (change instanceof BinaryValueUnused) {
BinaryValueUnused bvu = (BinaryValueUnused)change;
binaryValueUnused(bvu.getKey());
}
}
}
}
/**
* Signals the beginning of processing for the changes in a transaction described by a single {@link ChangeSet}.
*
* @see #completeWorkspaceChanges()
*/
protected void beginWorkspaceChanges() {
}
/**
* Signals the end of processing for the changes in a transaction described by a single {@link ChangeSet}.
*
* @see #beginWorkspaceChanges()
*/
protected void completeWorkspaceChanges() {
}
private void firePropertyChanges( NodeKey key,
Map<Name, AbstractPropertyChange> propChanges ) {
if (propChanges.isEmpty()) {
modifyProperties(key, propChanges);
propChanges.clear();
}
}
/**
* Handle the addition, change, and removal of one or more properties of a single node. This method is called once for each
* existing node whose properties are modified.
*
* @param key the unique key for the node; may not be null
* @param propChanges the map of property modification events, keyed by the names of the properties; never null and never
* empty
*/
protected void modifyProperties( NodeKey key,
Map<Name, AbstractPropertyChange> propChanges ) {
}
private final Properties props( final Map<Name, Property> properties ) {
return new Properties() {
@Override
public org.modeshape.jcr.value.Property getProperty( Name name ) {
return properties.get(name);
}
@Override
public Iterator<Property> iterator() {
return properties.values().iterator();
}
};
}
/**
* Determine whether changes in the named workspace should be processed. By default this method returns {@code true}, which
* means changes to content in all workspaces are handled by this adapter.
*
* @param workspaceName the workspace that has changes in content
* @return true if the changes should be processed, or false otherwise
*/
protected boolean includesWorkspace( String workspaceName ) {
return true;
}
/**
* Handle the addition of a node.
*
* @param workspaceName the workspace in which the node information should be available; may not be null
* @param key the unique key for the node; may not be null
* @param path the path of the node; may not be null
* @param primaryType the primary type of the node; may not be null
* @param mixinTypes the mixin types for the node; may not be null but may be empty
* @param properties the properties of the node; may not be null but may be empty
* @param queryable true if the node is queryable, false otherwise
*/
protected void addNode( String workspaceName,
NodeKey key,
Path path,
Name primaryType,
Set<Name> mixinTypes,
Properties properties,
boolean queryable ) {
}
/**
* Handle the removal of a node.
*
* @param workspaceName the workspace in which the node information should be available; may not be null
* @param key the unique key for the node; may not be null
* @param parentKey the unique key for the parent of the node; may not be null
* @param path the path of the node; may not be null
* @param primaryType the primary type of the node; may not be null
* @param mixinTypes the mixin types for the node; may not be null but may be empty
* @param queryable true if the node is queryable, false otherwise
*/
protected void removeNode( String workspaceName,
NodeKey key,
NodeKey parentKey,
Path path,
Name primaryType,
Set<Name> mixinTypes,
boolean queryable ) {
}
/**
* Handle the change of a node.
*
* @param workspaceName the workspace in which the node information should be available; may not be null
* @param key the unique key for the node; may not be null
* @param path the path of the node; may not be null
* @param primaryType the primary type of the node; may not be null
* @param mixinTypes the mixin types for the node; may not be null but may be empty
* @param queryable true if the node is queryable, false otherwise
*/
protected void changeNode( String workspaceName,
NodeKey key,
Path path,
Name primaryType,
Set<Name> mixinTypes,
boolean queryable ) {
}
/**
* Handle the move of a node.
*
* @param workspaceName the workspace in which the node information should be available; may not be null
* @param key the unique key for the node; may not be null
* @param primaryType the primary type of the node; may not be null
* @param mixinTypes the mixin types for the node; may not be null but may be empty
* @param oldParent the key of the node's parent before it was moved; may not be null
* @param newParent the key of the node's parent after it was moved; may not be null
* @param newPath the new path of the node after it was moved; may not be null
* @param oldPath the old path of the node before it was moved; may not be null
* @param queryable true if the node is queryable, false otherwise
*/
protected void moveNode( String workspaceName,
NodeKey key,
Name primaryType,
Set<Name> mixinTypes,
NodeKey oldParent,
NodeKey newParent,
Path newPath,
Path oldPath,
boolean queryable ) {
}
/**
* Handle the renaming of a node.
*
* @param workspaceName the workspace in which the node information should be available; may not be null
* @param key the unique key for the node; may not be null
* @param newPath the new path of the node after it was moved; may not be null
* @param oldSegment the old segment of the node before it was moved; may not be null
* @param primaryType the primary type of the node; may not be null
* @param mixinTypes the mixin types for the node; may not be null but may be empty
* @param queryable true if the node is queryable, false otherwise
*/
protected void renameNode( String workspaceName,
NodeKey key,
Path newPath,
Segment oldSegment,
Name primaryType,
Set<Name> mixinTypes,
boolean queryable ) {
}
/**
* Handle the reordering of a node.
*
* @param workspaceName the workspace in which the node information should be available; may not be null
* @param key the unique key for the node; may not be null
* @param primaryType the primary type of the node; may not be null
* @param mixinTypes the mixin types for the node; may not be null but may be empty
* @param parent the key of the node's parent; may not be null
* @param newPath the new path of the node after it was moved; may not be null
* @param oldPath the old path of the node before it was moved; may not be null
* @param reorderedBeforePath the path of the node before which the node was placed; null if it was moved to the end
* @param queryable true if the node is queryable, false otherwise
*/
protected void reorderNode( String workspaceName,
NodeKey key,
Name primaryType,
Set<Name> mixinTypes,
NodeKey parent,
Path newPath,
Path oldPath,
Path reorderedBeforePath,
boolean queryable ) {
}
protected void sequenced( String workspaceName,
NodeKey sequencedNodeKey,
Path sequencedNodePath,
Name sequencedNodePrimaryType,
Set<Name> sequencedNodeMixinTypes,
NodeKey outputNodeKey,
Path outputNodePath,
String outputPath,
String userId,
String selectedPath,
String sequencerName,
boolean queryable ) {
}
protected void sequenceFailure( String workspaceName,
NodeKey sequencedNodeKey,
Path sequencedNodePath,
Name sequencedNodePrimaryType,
Set<Name> sequencedNodeMixinTypes,
String outputPath,
String userId,
String selectedPath,
String sequencerName,
boolean queryable,
Throwable cause ) {
}
/**
* Handle the changing of the repository metadata information.
*/
protected void repositoryMetadataChanged() {
}
/**
* Handle the marking of a binary value as being unused.
*
* @param key the binary key of the binary value that is no longer used; may not be null
*/
protected void binaryValueUnused( BinaryKey key ) {
}
/**
* Handle the addition of a new workspace in the repository.
*
* @param workspaceName the name of the workspace that was added; may not be null
*/
protected void addWorkspace( String workspaceName ) {
}
/**
* Handle the removal of a workspace in the repository.
*
* @param workspaceName the name of the workspace that was removed; may not be null
*/
protected void removeWorkspace( String workspaceName ) {
}
}
| |
/*=========================================================================
* Copyright (c) 2010-2014 Pivotal Software, Inc. All Rights Reserved.
* This product is protected by U.S. and international copyright
* and intellectual property laws. Pivotal products are covered by
* one or more patents listed at http://www.pivotal.io/patents.
*=========================================================================
*/
package com.gemstone.gemfire.internal.cache;
// DO NOT modify this class. It was generated from LeafRegionEntry.cpp
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
import java.util.concurrent.atomic.AtomicLongFieldUpdater;
import com.gemstone.gemfire.internal.cache.lru.EnableLRU;
import com.gemstone.gemfire.internal.cache.persistence.DiskRecoveryStore;
import com.gemstone.gemfire.internal.InternalStatisticsDisabledException;
import com.gemstone.gemfire.internal.cache.lru.LRUClockNode;
import com.gemstone.gemfire.internal.cache.lru.NewLRUClockHand;
import com.gemstone.gemfire.internal.util.concurrent.CustomEntryConcurrentHashMap.HashEntry;
// macros whose definition changes this class:
// disk: DISK
// lru: LRU
// stats: STATS
// versioned: VERSIONED
// offheap: OFFHEAP
// One of the following key macros must be defined:
// key object: KEY_OBJECT
// key int: KEY_INT
// key long: KEY_LONG
// key uuid: KEY_UUID
// key string1: KEY_STRING1
// key string2: KEY_STRING2
/**
* Do not modify this class. It was generated.
* Instead modify LeafRegionEntry.cpp and then run
* bin/generateRegionEntryClasses.sh from the directory
* that contains your build.xml.
*/
public class VMStatsDiskLRURegionEntryHeapLongKey extends VMStatsDiskLRURegionEntryHeap {
public VMStatsDiskLRURegionEntryHeapLongKey (RegionEntryContext context, long key,
Object value
) {
super(context,
(value instanceof RecoveredEntry ? null : value)
);
// DO NOT modify this class. It was generated from LeafRegionEntry.cpp
initialize(context, value);
this.key = key;
}
// DO NOT modify this class. It was generated from LeafRegionEntry.cpp
// common code
protected int hash;
private HashEntry<Object, Object> next;
@SuppressWarnings("unused")
private volatile long lastModified;
private static final AtomicLongFieldUpdater<VMStatsDiskLRURegionEntryHeapLongKey> lastModifiedUpdater
= AtomicLongFieldUpdater.newUpdater(VMStatsDiskLRURegionEntryHeapLongKey.class, "lastModified");
private volatile Object value;
@Override
protected final Object getValueField() {
return this.value;
}
@Override
protected void setValueField(Object v) {
this.value = v;
}
protected long getlastModifiedField() {
return lastModifiedUpdater.get(this);
}
protected boolean compareAndSetLastModifiedField(long expectedValue, long newValue) {
return lastModifiedUpdater.compareAndSet(this, expectedValue, newValue);
}
/**
* @see HashEntry#getEntryHash()
*/
public final int getEntryHash() {
return this.hash;
}
protected void setEntryHash(int v) {
this.hash = v;
}
/**
* @see HashEntry#getNextEntry()
*/
public final HashEntry<Object, Object> getNextEntry() {
return this.next;
}
/**
* @see HashEntry#setNextEntry
*/
public final void setNextEntry(final HashEntry<Object, Object> n) {
this.next = n;
}
// DO NOT modify this class. It was generated from LeafRegionEntry.cpp
// disk code
protected void initialize(RegionEntryContext drs, Object value) {
boolean isBackup;
if (drs instanceof LocalRegion) {
isBackup = ((LocalRegion)drs).getDiskRegion().isBackup();
} else if (drs instanceof PlaceHolderDiskRegion) {
isBackup = true;
} else {
throw new IllegalArgumentException("expected a LocalRegion or PlaceHolderDiskRegion");
}
// Delay the initialization of DiskID if overflow only
if (isBackup) {
diskInitialize(drs, value);
}
}
@Override
public final synchronized int updateAsyncEntrySize(EnableLRU capacityController) {
int oldSize = getEntrySize();
int newSize = capacityController.entrySize( getKeyForSizing(), null);
setEntrySize(newSize);
int delta = newSize - oldSize;
return delta;
}
// DO NOT modify this class. It was generated from LeafRegionEntry.cpp
private void diskInitialize(RegionEntryContext context, Object value) {
DiskRecoveryStore drs = (DiskRecoveryStore)context;
DiskStoreImpl ds = drs.getDiskStore();
long maxOplogSize = ds.getMaxOplogSize();
//get appropriate instance of DiskId implementation based on maxOplogSize
this.id = DiskId.createDiskId(maxOplogSize, true/* is persistence */, ds.needsLinkedList());
Helper.initialize(this, drs, value);
}
/**
* DiskId
*
* @since 5.1
*/
protected DiskId id;//= new DiskId();
public DiskId getDiskId() {
return this.id;
}
@Override
void setDiskId(RegionEntry old) {
this.id = ((AbstractDiskRegionEntry)old).getDiskId();
}
// // inlining DiskId
// // always have these fields
// /**
// * id consists of
// * most significant
// * 1 byte = users bits
// * 2-8 bytes = oplog id
// * least significant.
// *
// * The highest bit in the oplog id part is set to 1 if the oplog id
// * is negative.
// * @todo this field could be an int for an overflow only region
// */
// private long id;
// /**
// * Length of the bytes on disk.
// * This is always set. If the value is invalid then it will be set to 0.
// * The most significant bit is used by overflow to mark it as needing to be written.
// */
// protected int valueLength = 0;
// // have intOffset or longOffset
// // intOffset
// /**
// * The position in the oplog (the oplog offset) where this entry's value is
// * stored
// */
// private volatile int offsetInOplog;
// // longOffset
// /**
// * The position in the oplog (the oplog offset) where this entry's value is
// * stored
// */
// private volatile long offsetInOplog;
// // have overflowOnly or persistence
// // overflowOnly
// // no fields
// // persistent
// /** unique entry identifier * */
// private long keyId;
// DO NOT modify this class. It was generated from LeafRegionEntry.cpp
// lru code
@Override
public void setDelayedDiskId(LocalRegion r) {
DiskStoreImpl ds = r.getDiskStore();
long maxOplogSize = ds.getMaxOplogSize();
this.id = DiskId.createDiskId(maxOplogSize, false /* over flow only */, ds.needsLinkedList());
}
public final synchronized int updateEntrySize(EnableLRU capacityController) {
return updateEntrySize(capacityController, _getValue()); // OFHEAP: _getValue ok w/o incing refcount because we are synced and only getting the size
}
// DO NOT modify this class. It was generated from LeafRegionEntry.cpp
public final synchronized int updateEntrySize(EnableLRU capacityController,
Object value) {
int oldSize = getEntrySize();
int newSize = capacityController.entrySize( getKeyForSizing(), value);
setEntrySize(newSize);
int delta = newSize - oldSize;
// if ( debug ) log( "updateEntrySize key=" + getKey()
// + (_getValue() == Token.INVALID ? " invalid" :
// (_getValue() == Token.LOCAL_INVALID ? "local_invalid" :
// (_getValue()==null ? " evicted" : " valid")))
// + " oldSize=" + oldSize
// + " newSize=" + this.size );
return delta;
}
public final boolean testRecentlyUsed() {
return areAnyBitsSet(RECENTLY_USED);
}
@Override
public final void setRecentlyUsed() {
setBits(RECENTLY_USED);
}
public final void unsetRecentlyUsed() {
clearBits(~RECENTLY_USED);
}
public final boolean testEvicted() {
return areAnyBitsSet(EVICTED);
}
public final void setEvicted() {
setBits(EVICTED);
}
public final void unsetEvicted() {
clearBits(~EVICTED);
}
// DO NOT modify this class. It was generated from LeafRegionEntry.cpp
private LRUClockNode nextLRU;
private LRUClockNode prevLRU;
private int size;
public final void setNextLRUNode( LRUClockNode next ) {
this.nextLRU = next;
}
public final LRUClockNode nextLRUNode() {
return this.nextLRU;
}
public final void setPrevLRUNode( LRUClockNode prev ) {
this.prevLRU = prev;
}
public final LRUClockNode prevLRUNode() {
return this.prevLRU;
}
public final int getEntrySize() {
return this.size;
}
protected final void setEntrySize(int size) {
this.size = size;
}
// DO NOT modify this class. It was generated from LeafRegionEntry.cpp
//@Override
//public StringBuilder appendFieldsToString(final StringBuilder sb) {
// StringBuilder result = super.appendFieldsToString(sb);
// result.append("; prev=").append(this.prevLRU==null?"null":"not null");
// result.append("; next=").append(this.nextLRU==null?"null":"not null");
// return result;
//}
@Override
public Object getKeyForSizing() {
// inline keys always report null for sizing since the size comes from the entry size
return null;
}
// DO NOT modify this class. It was generated from LeafRegionEntry.cpp
// stats code
@Override
public final void updateStatsForGet(boolean hit, long time)
{
setLastAccessed(time);
if (hit) {
incrementHitCount();
} else {
incrementMissCount();
}
}
@Override
protected final void setLastModified(long lastModified) {
_setLastModified(lastModified);
if (!DISABLE_ACCESS_TIME_UPDATE_ON_PUT) {
setLastAccessed(lastModified);
}
}
private volatile long lastAccessed;
private volatile int hitCount;
private volatile int missCount;
private static final AtomicIntegerFieldUpdater<VMStatsDiskLRURegionEntryHeapLongKey> hitCountUpdater
= AtomicIntegerFieldUpdater.newUpdater(VMStatsDiskLRURegionEntryHeapLongKey.class, "hitCount");
private static final AtomicIntegerFieldUpdater<VMStatsDiskLRURegionEntryHeapLongKey> missCountUpdater
= AtomicIntegerFieldUpdater.newUpdater(VMStatsDiskLRURegionEntryHeapLongKey.class, "missCount");
@Override
public final long getLastAccessed() throws InternalStatisticsDisabledException {
return this.lastAccessed;
}
private void setLastAccessed(long lastAccessed) {
this.lastAccessed = lastAccessed;
}
@Override
public final long getHitCount() throws InternalStatisticsDisabledException {
return this.hitCount & 0xFFFFFFFFL;
}
@Override
public final long getMissCount() throws InternalStatisticsDisabledException {
return this.missCount & 0xFFFFFFFFL;
}
private void incrementHitCount() {
hitCountUpdater.incrementAndGet(this);
}
private void incrementMissCount() {
missCountUpdater.incrementAndGet(this);
}
@Override
public final void resetCounts() throws InternalStatisticsDisabledException {
hitCountUpdater.set(this,0);
missCountUpdater.set(this,0);
}
// DO NOT modify this class. It was generated from LeafRegionEntry.cpp
@Override
public final void txDidDestroy(long currTime) {
setLastModified(currTime);
setLastAccessed(currTime);
this.hitCount = 0;
this.missCount = 0;
}
@Override
public boolean hasStats() {
return true;
}
// DO NOT modify this class. It was generated from LeafRegionEntry.cpp
// key code
private final long key;
@Override
public final Object getKey() {
return this.key;
}
@Override
public boolean isKeyEqual(Object k) {
if (k instanceof Long) {
return ((Long) k).longValue() == this.key;
}
return false;
}
// DO NOT modify this class. It was generated from LeafRegionEntry.cpp
}
| |
/*
* NOTE: This copyright does *not* cover user programs that use HQ
* program services by normal system calls through the application
* program interfaces provided as part of the Hyperic Plug-in Development
* Kit or the Hyperic Client Development Kit - this is merely considered
* normal use of the program, and does *not* fall under the heading of
* "derived work".
*
* Copyright (C) [2004-2008], Hyperic, Inc.
* This file is part of HQ.
*
* HQ is free software; you can redistribute it and/or modify
* it under the terms version 2 of the GNU General Public License as
* published by the Free Software Foundation. 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 General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA.
*/
package org.hyperic.hq.common;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.LinkedBlockingQueue;
/**
* An object for maintaining a group of metrics derived from method invocation
* times on the instrumented method. This object maintains its own private
* internal queue such that the metric values in the group will be updated
* only after the internal queue is flushed. Flushing occurs automatically
* when the queue capacity is reached but it may be invoked explicitly by any
* client wishing to obtain the most recent snapshot of metrics. Clients may
* also choose to update the metric values in the group synchronously when a
* new method invocation time value is added. In this case, the internal queue
* and flush operations are not used.
*
* Each metric in the group (num invocations/max,min,avg invocation time) is
* guaranteed to be consistent with the current flushed state of the group.
* There is no guarantee that the metrics within the group will be consistent
* with respect to one another especially if there are concurrent threads
* flushing and querying the group.
*/
public class MethodInvocationMetricsGroup {
/**
* The system property key for the capacity of the internal metrics queue.
*/
public static final String QUEUE_CAPACITY =
"org.hq.diagnostic.method.invocation.metrics.queue.capacity";
/**
* The default queue capacity (1000).
*/
public static final int DEFAULT_QUEUE_CAPACITY = 1000;
private static int _queueSize =
Integer.getInteger(QUEUE_CAPACITY, DEFAULT_QUEUE_CAPACITY).intValue();
private final Object _lock = new Object();
private final LinkedBlockingQueue _queue;
private final String _metricGroupName;
private final int _queueCapacity;
private long _numInvocations;
private long _maxInvocationTime;
private long _minInvocationTime;
private long _totalInvocationTime;
/**
* Creates an instance using the invocation time queue capacity specified
* by the {@link #QUEUE_CAPACITY} system property value.
*
* @param metricGroupName The metric group name.
*/
public MethodInvocationMetricsGroup(String metricGroupName) {
this(metricGroupName, _queueSize);
}
/**
* Creates an instance.
*
* @param metricGroupName The metric group name. A <code>null</code> value
* will be converted to the empty string.
* @param queueCapacity The capacity of the invocation time queue.
* @throws IllegalArgumentException if the capacity is not greater than zero.
*/
public MethodInvocationMetricsGroup(String metricGroupName, int queueCapacity) {
if (metricGroupName == null) {
_metricGroupName = "";
} else {
_metricGroupName = metricGroupName;
}
_queueCapacity = queueCapacity;
_queue = new LinkedBlockingQueue(_queueCapacity);
}
/**
* @return The metric group name.
*/
public String getMetricGroupName() {
return _metricGroupName;
}
/**
* @return The capacity of the invocation time queue.
*/
public int getQueueCapacity() {
return _queueCapacity;
}
/**
* Add an invocation time to the internal queue, flushing the queue if the
* capacity is reached.
*
* @param invocationTime The invocation time.
*/
public void addInvocationTime(long invocationTime) {
Long latestInvocationTime = new Long(invocationTime);
if (!_queue.offer(latestInvocationTime)) {
flush(latestInvocationTime, true);
}
}
/**
* Add an invocation time and update the metrics in the group immediately.
*
* @param invocationTime The invocation time.
*/
public void addInvocationTimeSynch(long invocationTime) {
synchronized (_lock) {
updateMetrics(invocationTime);
}
}
/**
* Flush the metric group, updating the metrics in the group with the
* invocation times currently stored in the queue.
*/
public void flush() {
flush(null, false);
}
/**
* @return The total number of added invocation time metrics.
*/
public long getNumberInvocations() {
synchronized (_lock) {
return _numInvocations;
}
}
/**
* @return The maximum invocation time metric.
*/
public long getMaxInvocationTime() {
synchronized (_lock) {
return _maxInvocationTime;
}
}
/**
* @return The minimum invocation time metric.
*/
public long getMinInvocationTime() {
synchronized (_lock) {
return _minInvocationTime;
}
}
/**
* @return The average invocation time metric or {@link Double#NaN} if no
* invocation time metric has been added.
*/
public double getAverageInvocationTime() {
synchronized (_lock) {
if (_numInvocations==0) {
return Double.NaN;
}
return (double)_totalInvocationTime/(double)_numInvocations;
}
}
/**
* Reset all metrics in the group.
*/
public void reset() {
synchronized (_lock) {
_numInvocations = 0;
_maxInvocationTime = 0;
_minInvocationTime = 0;
_totalInvocationTime = 0;
}
}
private void flush(Long latestInvocationTime, boolean includeLatest) {
synchronized (_lock) {
List invocationTimes = new ArrayList();
_queue.drainTo(invocationTimes);
if (includeLatest) {
invocationTimes.add(latestInvocationTime);
}
for (Iterator it = invocationTimes.iterator(); it.hasNext();) {
Long invocationTime = (Long) it.next();
updateMetrics(invocationTime.longValue());
}
}
}
private void updateMetrics(long nextInvocationTime) {
_numInvocations++;
_totalInvocationTime+=nextInvocationTime;
// handle overflows
if (_numInvocations < 0 || _totalInvocationTime < 0) {
reset();
_numInvocations = 1;
_totalInvocationTime = nextInvocationTime;
}
if (nextInvocationTime > _maxInvocationTime) {
_maxInvocationTime = nextInvocationTime;
}
if (_numInvocations == 1) {
// we always prime min invocation time with the first value
_minInvocationTime = nextInvocationTime;
} else if (nextInvocationTime < _minInvocationTime) {
_minInvocationTime = nextInvocationTime;
}
}
}
| |
/*
* Autopsy Forensic Browser
*
* Copyright 2013-2018 Basis Technology Corp.
* Contact: carrier <at> sleuthkit <dot> 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.
*/
package org.sleuthkit.autopsy.modules.stix;
import org.sleuthkit.autopsy.casemodule.Case;
import org.sleuthkit.datamodel.TskCoreException;
import org.sleuthkit.datamodel.Content;
import org.sleuthkit.autopsy.datamodel.ContentUtils;
import org.sleuthkit.datamodel.AbstractFile;
import java.util.List;
import java.util.ArrayList;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.io.File;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
import org.mitre.cybox.objects.WindowsRegistryKey;
import org.mitre.cybox.common_2.ConditionTypeEnum;
import com.williballenthin.rejistry.*;
import org.sleuthkit.autopsy.casemodule.NoCurrentCaseException;
/**
*
*/
class EvalRegistryObj extends EvaluatableObject {
private final WindowsRegistryKey obj;
private final List<RegistryFileInfo> regFiles = new ArrayList<RegistryFileInfo>();
public EvalRegistryObj(WindowsRegistryKey a_obj, String a_id, String a_spacing, List<RegistryFileInfo> a_regFiles) {
obj = a_obj;
id = a_id;
spacing = a_spacing;
regFiles.addAll(a_regFiles);
}
private EvalRegistryObj() {
obj = null;
id = null;
spacing = "";
}
@Override
public synchronized ObservableResult evaluate() {
setWarnings("");
// Key name is required
if (obj.getKey() == null) {
return new ObservableResult(id, "RegistryObject: No key found", //NON-NLS
spacing, ObservableResult.ObservableState.INDETERMINATE, null);
}
// For now, only support a full string match
if (!((obj.getKey().getCondition() == null)
|| (obj.getKey().getCondition() == ConditionTypeEnum.EQUALS))) {
return new ObservableResult(id, "RegistryObject: Can not support condition " + obj.getKey().getCondition() //NON-NLS
+ " on Key field", //NON-NLS
spacing, ObservableResult.ObservableState.INDETERMINATE, null);
}
setUnsupportedFieldWarnings();
// Make a list of hives to test
List<RegistryFileInfo> hiveList = new ArrayList<RegistryFileInfo>();
if (obj.getHive() == null) {
// If the hive field is missing, add everything
hiveList.addAll(regFiles);
} else if (obj.getHive().getValue().toString().startsWith("HKEY")) { //NON-NLS
// If the hive name is HKEY_LOCAL_MACHINE, add the ones from the config directory.
// Otherwise, add the others
for (RegistryFileInfo regFile : regFiles) {
if (regFile.abstractFile.getParentPath() != null) {
Pattern pattern = Pattern.compile("system32", Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(regFile.abstractFile.getParentPath());
if (matcher.find()) {
// Looking for system files and found one, so add it to the list
if (obj.getHive().getValue().toString().equalsIgnoreCase("HKEY_LOCAL_MACHINE")) { //NON-NLS
hiveList.add(regFile);
}
} else {
// Looking for non-system files and found one, so add it to the list
if (!obj.getHive().getValue().toString().equalsIgnoreCase("HKEY_LOCAL_MACHINE")) { //NON-NLS
hiveList.add(regFile);
}
}
}
}
} else {
// Otherwise, try to match the name
String stixHiveName = obj.getHive().getValue().toString();
// The temp files will end \Temp\STIX\(hive)_(number)
Pattern pattern = Pattern.compile("Temp.STIX." + stixHiveName, Pattern.CASE_INSENSITIVE);
for (RegistryFileInfo hive : regFiles) {
Matcher matcher = pattern.matcher(hive.tempFileName);
if (matcher.find()) {
hiveList.add(hive);
}
}
// If nothing matched, add all the files
if (hiveList.isEmpty()) {
hiveList.addAll(regFiles);
}
}
// This is unlikely to happen unless we have no registry files to test against
if (hiveList.isEmpty()) {
return new ObservableResult(id, "RegistryObject: No matching registry hives found", //NON-NLS
spacing, ObservableResult.ObservableState.INDETERMINATE, null);
}
for (RegistryFileInfo hive : hiveList) {
try {
ObservableResult result = testRegistryFile(hive);
if (result.isTrue()) {
return result;
}
} catch (Exception ex) {
// The registry parser seems to throw lots of different types of exceptions,
// so make sure to catch them all by this point. Malformed registry files
// in particular cause problems.
addWarning("Error processing registry file " + hive); //NON-NLS
}
}
if (obj.getHive() == null) {
return new ObservableResult(id, "RegistryObject: Could not find key " + obj.getKey().getValue(), //NON-NLS
spacing, ObservableResult.ObservableState.FALSE, null);
}
return new ObservableResult(id, "RegistryObject: Could not find key " + obj.getKey().getValue() //NON-NLS
+ " in hive " + obj.getHive().getValue(), //NON-NLS
spacing, ObservableResult.ObservableState.FALSE, null);
}
/**
* Test the Registry object against one registry file.
*
* @param a_regInfo The registry file
*
* @return Result of the test
*/
private ObservableResult testRegistryFile(RegistryFileInfo a_regInfo) {
try {
RegistryKey root = openRegistry(a_regInfo.tempFileName);
RegistryKey result = findKey(root, obj.getKey().getValue().toString());
if (result == null) {
// Take another shot looking for the key minus the first part of the path (sometimes the
// hive file name is here). This should only happen if the hive name started
// with "HKEY"
if ((obj.getHive() != null)
&& obj.getHive().getValue().toString().startsWith("HKEY")) { //NON-NLS
String[] parts = obj.getKey().getValue().toString().split("\\\\");
String newKey = "";
for (int i = 1; i < parts.length; i++) {
if (newKey.length() > 0) {
newKey += "\\";
}
newKey += parts[i];
}
result = findKey(root, newKey);
}
if (result == null) {
return new ObservableResult(id, "RegistryObject: Could not find key " + obj.getKey().getValue(), //NON-NLS
spacing, ObservableResult.ObservableState.FALSE, null);
}
}
if ((obj.getValues() == null) || (obj.getValues().getValues().isEmpty())) {
// No values to test
List<StixArtifactData> artData = new ArrayList<StixArtifactData>();
artData.add(new StixArtifactData(a_regInfo.abstractFile.getId(), id, "Registry")); //NON-NLS
return new ObservableResult(id, "RegistryObject: Found key " + obj.getKey().getValue(), //NON-NLS
spacing, ObservableResult.ObservableState.TRUE, artData);
}
// Test all the values
for (org.mitre.cybox.objects.RegistryValueType stixRegValue : obj.getValues().getValues()) {
try {
for (RegistryValue valFromFile : result.getValueList()) {
// Test if the name field matches (if present)
boolean nameSuccess = true; // True if the name matches or isn't present
if (stixRegValue.getName() != null) {
try {
nameSuccess = compareStringObject(stixRegValue.getName(), valFromFile.getName());
} catch (UnsupportedEncodingException ex) {
nameSuccess = false;
}
}
boolean valueSuccess = true;
if (nameSuccess && (stixRegValue.getData() != null)) {
switch (valFromFile.getValueType()) {
case REG_SZ:
case REG_EXPAND_SZ:
try {
valueSuccess = compareStringObject(stixRegValue.getData(),
valFromFile.getValue().getAsString());
} catch (UnsupportedEncodingException ex) {
valueSuccess = false;
}
break;
case REG_DWORD:
case REG_BIG_ENDIAN:
case REG_QWORD:
// Only support "equals" for now.
if ((stixRegValue.getData().getCondition() == null)
|| (stixRegValue.getData().getCondition() == ConditionTypeEnum.EQUALS)) {
// Try to convert the STIX string to a long
try {
long stixValue = Long.decode(stixRegValue.getData().getValue().toString());
try {
valueSuccess = (stixValue == valFromFile.getValue().getAsNumber());
} catch (UnsupportedEncodingException ex) {
valueSuccess = false;
}
} catch (NumberFormatException ex) {
// We probably weren't looking at a numeric field to begin with,
// so getting this exception isn't really an error.
valueSuccess = false;
}
} else {
valueSuccess = false;
}
break;
default:
// Nothing to do here. These are the types we don't handle:
// REG_BIN, REG_FULL_RESOURCE_DESCRIPTOR, REG_LINK, REG_MULTI_SZ, REG_NONE,
// REG_RESOURCE_LIST, REG_RESOURCE_REQUIREMENTS_LIST
}
}
if (nameSuccess && valueSuccess) {
// Found a match for all values
List<StixArtifactData> artData = new ArrayList<StixArtifactData>();
artData.add(new StixArtifactData(a_regInfo.abstractFile.getId(), id, "Registry")); //NON-NLS
return new ObservableResult(id, "RegistryObject: Found key " + obj.getKey().getValue() //NON-NLS
+ " and value " + stixRegValue.getName().getValue().toString() //NON-NLS
+ " = " + stixRegValue.getData().getValue().toString(),
spacing, ObservableResult.ObservableState.TRUE, artData);
}
}
} catch (Exception ex) {
// Broad catch here becase the registry parser can create all kinds of exceptions beyond what it reports.
return new ObservableResult(id, "RegistryObject: Exception during evaluation: " + ex.getLocalizedMessage(), //NON-NLS
spacing, ObservableResult.ObservableState.INDETERMINATE, null);
}
}
} catch (TskCoreException ex) {
return new ObservableResult(id, "RegistryObject: Exception during evaluation: " + ex.getLocalizedMessage(), //NON-NLS
spacing, ObservableResult.ObservableState.INDETERMINATE, null);
}
return new ObservableResult(id, "RegistryObject: Not done", //NON-NLS
spacing, ObservableResult.ObservableState.INDETERMINATE, null);
}
public RegistryKey openRegistry(String hive) throws TskCoreException {
try {
RegistryHiveFile regFile = new RegistryHiveFile(new File(hive));
RegistryKey root = regFile.getRoot();
return root;
} catch (IOException ex) {
throw new TskCoreException("Error opening registry file - " + ex.getLocalizedMessage()); //NON-NLS
} catch (RegistryParseException ex) {
throw new TskCoreException("Error opening root node of registry - " + ex.getLocalizedMessage()); //NON-NLS
}
}
/**
* Go down the registry tree to find a key with the given name.
*
* @param root Root of the registry hive
* @param name Name of the subkey to seach for
*
* @return The matching subkey or null if not found
*/
public RegistryKey findKey(RegistryKey root, String name) {
RegistryKey currentKey = root;
// Split the key name into parts
String[] parts = name.split("\\\\");
for (String part : parts) {
if (part.length() > 0) {
try {
currentKey = currentKey.getSubkey(part);
} catch (Exception ex) {
// We get an exception if the value wasn't found (not a RegistryParseException).
// There doesn't seem to be a cleaner way to test for existance without cycling though
// everything ourselves. (Broad catch because things other than RegistryParseException
// can happen)
return null;
}
}
}
// If we make it this far, we've found it
return currentKey;
}
/**
* Copy all registry hives to the temp directory and return the list of
* created files.
*
* @return Paths to copied registry files.
*/
public static List<RegistryFileInfo> copyRegistryFiles() throws TskCoreException {
// First get all the abstract files
List<AbstractFile> regFilesAbstract = findRegistryFiles();
// List to hold all the extracted file names plus their abstract file
List<RegistryFileInfo> regFilesLocal = new ArrayList<RegistryFileInfo>();
// Make the temp directory
String tmpDir;
try {
tmpDir = Case.getCurrentCaseThrows().getTempDirectory() + File.separator + "STIX"; //NON-NLS
} catch (NoCurrentCaseException ex) {
throw new TskCoreException(ex.getLocalizedMessage());
}
File dir = new File(tmpDir);
if (dir.exists() == false) {
dir.mkdirs();
}
long index = 1;
for (AbstractFile regFile : regFilesAbstract) {
String regFileName = regFile.getName();
String regFileNameLocal = tmpDir + File.separator + regFileName + "_" + index;
File regFileNameLocalFile = new File(regFileNameLocal);
try {
// Don't save any unallocated versions
if (regFile.getMetaFlagsAsString().contains("Allocated")) { //NON-NLS
ContentUtils.writeToFile(regFile, regFileNameLocalFile);
regFilesLocal.add(new EvalRegistryObj().new RegistryFileInfo(regFile, regFileNameLocal));
}
} catch (IOException ex) {
throw new TskCoreException(ex.getLocalizedMessage());
}
index++;
}
return regFilesLocal;
}
/**
* Search for the registry hives on the system. Mostly copied from
* RecentActivity
*/
private static List<AbstractFile> findRegistryFiles() throws TskCoreException {
List<AbstractFile> registryFiles = new ArrayList<AbstractFile>();
Case openCase;
try {
openCase = Case.getCurrentCaseThrows();
} catch (NoCurrentCaseException ex) {
throw new TskCoreException(ex.getLocalizedMessage());
}
org.sleuthkit.autopsy.casemodule.services.FileManager fileManager = openCase.getServices().getFileManager();
for (Content ds : openCase.getDataSources()) {
// find the user-specific ntuser-dat files
registryFiles.addAll(fileManager.findFiles(ds, "ntuser.dat")); //NON-NLS
// find the system hives
String[] regFileNames = new String[]{"system", "software", "security", "sam"}; //NON-NLS
for (String regFileName : regFileNames) {
List<AbstractFile> allRegistryFiles = fileManager.findFiles(ds, regFileName, "/system32/config"); //NON-NLS
for (AbstractFile regFile : allRegistryFiles) {
// Don't want anything from regback
if (!regFile.getParentPath().contains("RegBack")) { //NON-NLS
registryFiles.add(regFile);
}
}
}
}
return registryFiles;
}
private void setUnsupportedFieldWarnings() {
List<String> fieldNames = new ArrayList<String>();
if (obj.getNumberValues() != null) {
fieldNames.add("Number_Values"); //NON-NLS
}
if (obj.getModifiedTime() != null) {
fieldNames.add("Modified_Time"); //NON-NLS
}
if (obj.getCreatorUsername() != null) {
fieldNames.add("Creator_Username"); //NON-NLS
}
if (obj.getHandleList() != null) {
fieldNames.add("Handle_List"); //NON-NLS
}
if (obj.getNumberSubkeys() != null) {
fieldNames.add("Number_Subkeys"); //NON-NLS
}
if (obj.getSubkeys() != null) {
fieldNames.add("Subkeys"); //NON-NLS
}
if (obj.getByteRuns() != null) {
fieldNames.add("Byte_Runs"); //NON-NLS
}
String warningStr = "";
for (String name : fieldNames) {
if (!warningStr.isEmpty()) {
warningStr += ", ";
}
warningStr += name;
}
addWarning("Unsupported field(s): " + warningStr); //NON-NLS
}
/**
* Class to keep track of the abstract file and temp file that goes with
* each registry hive.
*/
public class RegistryFileInfo {
private final AbstractFile abstractFile;
private final String tempFileName;
public RegistryFileInfo(AbstractFile a_abstractFile, String a_tempFileName) {
abstractFile = a_abstractFile;
tempFileName = a_tempFileName;
}
}
}
| |
package acceptance.td;
import com.google.common.collect.ImmutableMap;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpObject;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpResponse;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.littleshoot.proxy.HttpFilters;
import org.littleshoot.proxy.HttpFiltersAdapter;
import org.littleshoot.proxy.HttpFiltersSourceAdapter;
import org.littleshoot.proxy.HttpProxyServer;
import org.littleshoot.proxy.impl.DefaultHttpProxyServer;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import static acceptance.td.Secrets.TD_API_KEY;
import static io.netty.handler.codec.http.HttpHeaders.Names.AUTHORIZATION;
import static io.netty.handler.codec.http.HttpResponseStatus.OK;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.util.Arrays.asList;
import static java.util.Collections.emptyList;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.isEmptyOrNullString;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.MatcherAssert.assertThat;
import static utils.TestUtils.main;
public class TdConfIT
{
private static final String MOCK_TD_API_KEY = "4711/badf00d";
@Rule
public TemporaryFolder folder = new TemporaryFolder();
private Path tdConf;
private HttpProxyServer proxyServer;
private List<FullHttpRequest> requests = Collections.synchronizedList(new ArrayList<>());
private Path digdagConf;
@Before
public void setUp()
throws Exception
{
assertThat(TD_API_KEY, not(isEmptyOrNullString()));
tdConf = folder.newFolder().toPath().resolve("td.conf");
digdagConf = folder.newFolder().toPath().resolve("digdag");
Files.write(digdagConf, emptyList());
}
@Before
public void setupProxy()
{
proxyServer = DefaultHttpProxyServer
.bootstrap()
.withPort(0)
.withFiltersSource(new HttpFiltersSourceAdapter()
{
@Override
public int getMaximumRequestBufferSizeInBytes()
{
return 1024 * 1024;
}
@Override
public HttpFilters filterRequest(HttpRequest httpRequest, ChannelHandlerContext channelHandlerContext)
{
return new HttpFiltersAdapter(httpRequest)
{
@Override
public HttpResponse clientToProxyRequest(HttpObject httpObject)
{
assert httpObject instanceof FullHttpRequest;
FullHttpRequest req = ((FullHttpRequest) httpObject).copy();
requests.add(req);
if (req.getMethod() == HttpMethod.GET &&
req.getUri().equals("http://foo.baz.bar:80/api/projects")) {
return new DefaultFullHttpResponse(req.getProtocolVersion(), OK,
Unpooled.wrappedBuffer("[]".getBytes(UTF_8)));
}
return null;
}
};
}
}).start();
}
@After
public void stopProxy()
throws Exception
{
if (proxyServer != null) {
proxyServer.stop();
proxyServer = null;
}
}
@Before
public void enableClientConfiguration()
throws Exception
{
System.setProperty("io.digdag.standards.td.client-configurator.enabled", "true");
System.setProperty("io.digdag.standards.td.client-configurator.endpoint", "http://foo.baz.bar");
}
@After
public void disableClientConfiguration()
throws Exception
{
System.clearProperty("io.digdag.standards.td.client-configurator.enabled");
System.clearProperty("io.digdag.standards.td.client-configurator.endpoint");
}
@Test
public void verifyCliConfiguresDigdagClientUsingTdConf()
throws Exception
{
Files.write(tdConf, asList(
"[account]",
" user = foo@bar.com",
" apikey = " + MOCK_TD_API_KEY
));
String proxyUrl = "http://" + proxyServer.getListenAddress().getHostString() + ":" + proxyServer.getListenAddress().getPort();
Map<String, String> env = ImmutableMap.of(
"http_proxy", proxyUrl,
"TD_CONFIG_PATH", tdConf.toString()
);
main(env, "workflows",
"-c", digdagConf.toString(),
"--disable-version-check");
assertThat(requests.isEmpty(), is(false));
for (FullHttpRequest request : requests) {
assertThat(request.getUri(), is("http://foo.baz.bar:80/api/workflows?count=100"));
assertThat(request.headers().get(AUTHORIZATION), is("TD1 " + MOCK_TD_API_KEY));
}
}
@Test
public void verifyCliIgnoresMissingTdConf()
throws Exception
{
assertThat(Files.notExists(tdConf), is(true));
String proxyUrl = "http://" + proxyServer.getListenAddress().getHostString() + ":" + proxyServer.getListenAddress().getPort();
Map<String, String> env = ImmutableMap.of(
"http_proxy", proxyUrl,
"TD_CONFIG_PATH", tdConf.toString()
);
Files.write(digdagConf, asList(
"client.http.endpoint = http://baz.quux:80",
"client.http.headers.authorization = FOO " + MOCK_TD_API_KEY
));
main(env, "workflows",
"-c", digdagConf.toString(),
"--disable-version-check");
assertThat(requests.isEmpty(), is(false));
for (FullHttpRequest request : requests) {
assertThat(request.getUri(), is("http://baz.quux:80/api/workflows?count=100"));
assertThat(request.headers().get(AUTHORIZATION), is("FOO " + MOCK_TD_API_KEY));
}
}
@Test
public void verifyCliIgnoresBrokenTdConf()
throws Exception
{
Files.write(tdConf, asList("endpoint=foo:bar"));
String proxyUrl = "http://" + proxyServer.getListenAddress().getHostString() + ":" + proxyServer.getListenAddress().getPort();
Map<String, String> env = ImmutableMap.of(
"http_proxy", proxyUrl,
"TD_CONFIG_PATH", tdConf.toString()
);
Files.write(digdagConf, asList(
"client.http.endpoint = http://baz.quux:80",
"client.http.headers.authorization = FOO " + MOCK_TD_API_KEY
));
main(env, "workflows",
"-c", digdagConf.toString(),
"--disable-version-check");
assertThat(requests.isEmpty(), is(false));
for (FullHttpRequest request : requests) {
assertThat(request.getUri(), is("http://baz.quux:80/api/workflows?count=100"));
assertThat(request.headers().get(AUTHORIZATION), is("FOO " + MOCK_TD_API_KEY));
}
}
}
| |
/*
* 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 com.sun.jini.test.spec.security.security;
import java.util.logging.Level;
// jav
import java.util.ArrayList;
import java.io.File;
import java.net.URL;
import java.net.MalformedURLException;
// net.jini
import net.jini.security.Security;
// com.sun.jini
import com.sun.jini.qa.harness.TestException;
import com.sun.jini.qa.harness.QATest;
import com.sun.jini.test.spec.security.util.Util;
import com.sun.jini.test.spec.security.util.BaseIntegrityVerifier;
import com.sun.jini.test.spec.security.util.TrueIntegrityVerifier;
import com.sun.jini.test.spec.security.util.FalseIntegrityVerifier;
import com.sun.jini.test.spec.security.util.FakeClassLoader;
/**
* <pre>
* Purpose
* This test verifies the following:
* 'verifyCodebaseIntegrity' static method of Security class verifies that
* the URLs in the specified codebase all provide content integrity, using
* verifiers from the specified class loader. If a null class loader is
* specified, the context class loader of the current thread is used
* instead. An ordered list of integrity verifiers is obtained as specified
* below. For each URL (if any) in the specified codebase,
* IntegrityVerifier.providesIntegrity method of each verifier is called (in
* order) with the URL. If any verifier call returns true, the URL is
* verified (and no further verifiers are called with that URL). If all of
* the verifier calls return false for a URL, this method throws a
* SecurityException. If all of the URLs are verified, this method returns
* normally. The list of integrity verifiers is obtained as follows. For
* each resource named META-INF/services/net.jini.security.IntegrityVerifier
* that is visible to the specified class loader, the contents of the
* resource are parsed as UTF-8 text to produce a list of class names.
* The resource must contain a list of fully qualified class names, one per
* line. Space and tab characters surrounding each name, as well as blank
* lines, are ignored. The comment character is '#'; all characters on each
* line starting with the first comment character are ignored. Each class
* name (that is not a duplicate of any previous class name) is loaded
* through the specified class loader, and the resulting class must be
* assignable to IntegrityVerifier and have a public no-argument
* constructor. The constructor is invoked to create an integrity verifier
* instance. This method throws MalformedURLException if the specified
* codebase contains an invalid URL.
*
* Test Cases
* Case 1: actions described below
* Case 2: Set ClassLoader for current thread to FakeClassLoader1 with empty
* array of URLs. During the test construct each time
* FakeClassLoader2, do not set it as ClassLoader for current thread,
* and invoke 'verifyCodebaseIntegrity' with constructed
* FakeClassLoader2. In this case checks will be made that tested
* integrity verifiers where loaded through FakeClassLoader2 and not
* FakeClassLoader1.
* Case 3: Case1 for MultiURL
* Case 4: Case2 for MultiURL
*
* Infrastructure
* This test requires the following infrastructure:
* Resource1 - META-INF/services/net.jini.security.IntegrityVerifier
* resource containing TrueIntegrityVerifier and
* FalseIntegrityVerifier in this order
* Resource2 - META-INF/services/net.jini.security.IntegrityVerifier
* resource containing FalseIntegrityVerifier
* Resource3 - META-INF/services/net.jini.security.IntegrityVerifier
* resource containing FalseIntegrityVerifier and
* TrueIntegrityVerifier in this order
* TestURL - URL string for which 'providesIntegrity' method of any
* integrity verifier containing in jsk-resources.jar will return
* false
* MultiURL - String containing several URL strings
* WrongURL - wrong URL string
* TrueIntegrityVerifier - TrustVerifier whose 'providesIntegrity' method
* always returns true
* FalseIntegrityVerifier - TrustVerifier whose 'providesIntegrity' method
* always returns false
* FakeClassLoader - test class loader, which is actually a URLClassLoader
*
* Action
* For each test case the test performs the following steps:
* 1) invoke 'Security.verifyCodebaseIntegrity' method with WrongURL string
* 2) assert that MalformedURLException will be thrown
* 3) construct FakeClassLoader with Resource1 as a parameter and set it
* as ClassLoader for the current thread
* 4) invoke 'Security.verifyCodebaseIntegrity(TestURL, null)'
* 5) assert that TrueIntegrityVerifier will be loaded through
* FakeClassLoader
* 6) assert that FalseIntegrityVerifier will be loaded through
* FakeClassLoader
* 7) assert that 'providesIntegrity' method of TrueIntegrityVerifier will
* be invoked
* 8) assert that 'providesIntegrity' method of FalseIntegrityVerifier will
* not be invoked
* 9) assert that method will return normally
* 10) construct FakeClassLoader with Resource2 as a parameter and set it
* as ClassLoader for the current thread
* 11) invoke 'Security.verifyCodebaseIntegrity(TestURL, null)'
* 12) assert that FalseIntegrityVerifier will be loaded through
* FakeClassLoader
* 13) assert that 'providesIntegrity' method of FalseIntegrityVerifier will
* be invoked
* 14) assert that method will throw SecurityException
* 15) construct FakeClassLoader with Resource3 as a parameter and set it
* as ClassLoader for the current thread
* 16) invoke 'Security.verifyCodebaseIntegrity(TestURL, null)'
* 17) assert that FalseIntegrityVerifier will be loaded through
* FakeClassLoader
* 18) assert that TrueIntegrityVerifier will be loaded through
* FakeClassLoader
* 19) assert that 'providesIntegrity' method of FalseIntegrityVerifier
* will be invoked
* 20) assert that 'providesIntegrity' method of TrueIntegrityVerifier
* will be invoked
* 21) assert that method will return normally
* </pre>
*/
public class VerifyCodebaseIntegrityTest extends QATest {
/** Resource name method */
protected static String resName =
"META-INF/services/net.jini.security.IntegrityVerifier";
/**
* Array of classes whose 'providesIntegrity' methods are expected to be
* called.
*/
protected Class[] expCls = new Class[0];
/**
* Array of urls which are expected to be parameters for 'providesIntegrity'
* methods.
*/
protected URL[] expUrls = new URL[0];
/** Expected result of iteration. */
protected Class expRes;
/**
* This method performs all actions mentioned in class description.
*
*/
public void run() throws Exception {
File jarFile = null;
String[] wrongUrls = new String[] {
"?:", "file:/fake.jar ?: file:/fake1.java" };
String[] testUrls = new String[] {
"http://fakehost:8080/bla-bla.java",
"http://fh/bla1.java http://fh/bla2.java http://fh/bla3.java" };
boolean[] useNullLoader = new boolean[] { true, false };
Class[][] clNames = new Class[][] {
new Class[] {
TrueIntegrityVerifier.class,
FalseIntegrityVerifier.class },
new Class[] { FalseIntegrityVerifier.class },
new Class[] {
FalseIntegrityVerifier.class,
TrueIntegrityVerifier.class } };
ClassLoader testCl;
for (int i = 0; i < useNullLoader.length; ++i) {
logger.fine("=========== Check wrong URLs ===========");
for (int j = 0; j < wrongUrls.length; ++j) {
jarFile = Util.createResourceJar(resName,
new Class[] { Class.class });
if (useNullLoader[i]) {
testCl = null;
} else {
testCl = new FakeClassLoader(jarFile.toURI().toURL());
}
try {
callVerifyCodebaseIntegrity(wrongUrls[j], testCl);
// FAIL
throw new TestException(
"Method did not throw any exception while "
+ "MalformedURLException was expected.");
} catch (MalformedURLException mue) {
// PASS
logger.fine("MalformedURLException was thrown "
+ "as expected.");
} finally {
jarFile.delete();
}
}
logger.fine("=========== Check correct URLs ===========");
for (int j = 0; j < clNames.length; ++j) {
logger.fine("========== Iteration #" + (j + 1)
+ " ==========");
logger.fine("Test integrity verifiers are: "
+ Util.arrayToString(clNames[j]));
for (int k = 0; k < testUrls.length; ++k) {
BaseIntegrityVerifier.initLists();
jarFile = Util.createResourceJar(resName, clNames[j]);
expRes = getExpRes(clNames[j], testUrls[k]);
if (useNullLoader[i]) {
testCl = null;
} else {
testCl = new FakeClassLoader(jarFile.toURI().toURL());
}
Thread.currentThread().setContextClassLoader(
new FakeClassLoader(jarFile.toURI().toURL()));
try {
callVerifyCodebaseIntegrity(testUrls[k], testCl);
if (expRes != null) {
// FAIL
throw new TestException(
"Method returned normally while "
+ "SecurityException was expected "
+ "to be thrown.");
}
// PASS
logger.fine("Method returned normally "
+ "as expected.");
} catch (SecurityException se) {
if (expRes == null) {
// FAIL
throw new TestException(
"Method throws " + se
+ " exception while "
+ "normal return was expected.");
}
// PASS
logger.fine("Method threw " + se + " as expected.");
} finally {
jarFile.delete();
}
/*
* check that classes where loaded through the right
* classloader
*/
Class[] loadedCls = null;
if (testCl == null) {
loadedCls = ((FakeClassLoader)
Thread.currentThread()
.getContextClassLoader()).getClasses();
} else {
loadedCls = ((FakeClassLoader) testCl).getClasses();
}
Class[] notLoadedCls = Util.containsClasses(
loadedCls, clNames[j]);
if (notLoadedCls != null) {
// FAIL
throw new TestException(
"The following classes was not loaded "
+ " through expected class loader: "
+ Util.arrayToString(notLoadedCls));
}
// PASS
logger.fine("All requested classes were loaded through "
+ "expected class loader.");
// check that passed parameters where correct
Class[] classes = BaseIntegrityVerifier.getClasses();
URL[] actUrls = BaseIntegrityVerifier.getUrls();
String resStr = checkURLs(actUrls, classes);
if (resStr != null) {
// FAIL
throw new TestException(resStr);
}
// PASS
logger.fine("All classes got expected urls.");
}
}
}
}
/**
* Invokes 'Security.verifyCodebaseIntegrity' method with given argument.
* Rethrows any exception thrown by 'verifyCodebaseIntegrity' method.
*
* @param codebase space-separated list of URLs for
* 'verifyCodebaseIntegrity' method
* @param loader ClassLoader for 'verifyCodebaseIntegrity' method
*/
protected void callVerifyCodebaseIntegrity(String codebase,
ClassLoader loader) throws MalformedURLException {
logger.fine("Call 'Security.verifyCodebaseIntegrity([" + codebase
+ "], " + loader + ")'.");
Security.verifyCodebaseIntegrity(codebase, loader);
}
/**
* Return Class representing expected result - if non-null, that means
* that SecurityException must be thrown. Fills array of
* classes whose 'providesIntegrity' methods are expected to be called.
*
* @param clNames array of classes for which evaluate the result
* @param str URLs string for which get expected results
* @throws MalformedURLException if any of the URLs are invalid
*/
protected Class getExpRes(Class[] clNames, String str)
throws MalformedURLException {
ArrayList clList = new ArrayList();
expUrls = Util.strToUrls(str);
for (int i = 0; i < clNames.length; ++i) {
clList.add(clNames[i]);
if (clNames[i] == TrueIntegrityVerifier.class) {
expCls = (Class []) clList.toArray(new Class[clList.size()]);
return null;
}
}
expCls = (Class []) clList.toArray(new Class[clList.size()]);
return SecurityException.class;
}
/**
* Checks expected set of URLs with actual one.
* We need to check that all expected classes got all expected URLs.
*
* @param actUrls actual set of URLs
* @param actCls actual set of classes
* @return null if sets are equal or non-null string indicating error
*/
protected String checkURLs(URL[] actUrls, Class[] actCls) {
if ((actUrls.length == 0 && expUrls.length != 0)
&& (actUrls.length != 0 && expUrls.length == 0)) {
// FAIL
return "Actual set of URLs is: [" + Util.arrayToString(actUrls)
+ "] while [" + Util.arrayToString(expUrls)
+ "] was expected.";
}
if (expRes != null) {
/*
* We just need to check that at least one of expected urls was
* passed as a parameter.
*/
for (int i = 0; i < expUrls.length; ++i) {
if (expUrls[i].equals(actUrls[0])) {
Class[] cls = Util.containsClasses(actCls, expCls);
if (cls != null) {
// FAIL
return "'providesIntegrity' methods of the following "
+ "classes were not called with " + expUrls[i]
+ " as a parameter: " + Util.arrayToString(cls);
}
// PASS
return null;
}
}
// FAIL
return "No 'providesIntegrity' methods where called with one of "
+ Util.arrayToString(expUrls) + " URLs.";
}
for (int i = 0; i < expUrls.length; ++i) {
ArrayList clList = new ArrayList();
// get list of classes which got expUrls[i] as a parameter
for (int j = 0; j < actUrls.length; ++j) {
if (expUrls[i].equals(actUrls[j])) {
clList.add(actCls[j]);
}
}
// check what classes did not get expected url
Class[] cls = Util.containsClasses((Class []) clList.toArray(
new Class[clList.size()]), expCls);
if (cls != null) {
// FAIL
return "'providesIntegrity' methods of the following "
+ "classes were not called with " + expUrls[i]
+ " as a parameter: " + Util.arrayToString(cls);
}
}
// PASS
return null;
}
}
| |
/**
* Copyright 2000-2013 Geometria Contributors
* http://geocentral.net/geometria
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License
* http://www.gnu.org/licenses
*/
package net.geocentral.geometria.action;
import java.awt.Color;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.Set;
import javax.vecmath.Matrix3d;
import javax.vecmath.Vector3d;
import net.geocentral.geometria.model.GCamera;
import net.geocentral.geometria.model.GDocument;
import net.geocentral.geometria.model.GFace;
import net.geocentral.geometria.model.GFigure;
import net.geocentral.geometria.model.GPoint3d;
import net.geocentral.geometria.model.GSelectable;
import net.geocentral.geometria.model.GSolid;
import net.geocentral.geometria.model.GStick;
import net.geocentral.geometria.util.GDictionary;
import net.geocentral.geometria.util.GMath;
import net.geocentral.geometria.util.GStringUtils;
import net.geocentral.geometria.view.GCutDialog;
import org.apache.log4j.Logger;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
public class GCutAction implements GLoggable, GActionWithHelp {
private String figureName;
private String figure1Name;
private String figure2Name;
private String[] pLabels;
private GDocument document;
private GFigure figure;
private GSolid solid;
private String helpId;
private String comments;
private static Logger logger = Logger.getLogger("net.geocentral.geometria");
public boolean execute() {
return execute(false);
}
public boolean execute(boolean silent) {
logger.info(silent);
GDocumentHandler documentHandler = GDocumentHandler.getInstance();
document = documentHandler.getActiveDocument();
if (silent) {
try {
validateApply();
}
catch (Exception exception) {
return false;
}
}
else {
GFigure figure = document.getSelectedFigure();
figureName = figure.getName();
GSolid solid = figure.getSolid();
Set<GSelectable> selection = solid.getSelection();
prefill(selection);
try {
validateApply();
}
catch (Exception exception) {
GCutDialog dialog = new GCutDialog(documentHandler.getOwnerFrame(), this);
dialog.prefill(pLabels[0], pLabels[1], pLabels[2]);
dialog.setVisible(true);
if (!dialog.getResult()) {
return false;
}
}
solid.clearSelection();
}
document.setSelectedFigure(figure2Name);
if (!silent) {
documentHandler.setDocumentModified(true);
}
logger.info(figureName + ", " + Arrays.asList(pLabels) + ", " + figure1Name + ", " + figure2Name);
return true;
}
private void prefill(Set<GSelectable> selection) {
logger.info("");
GDocument document = GDocumentHandler.getInstance().getActiveDocument();
GFigure figure = document.getSelectedFigure();
GSolid solid = figure.getSolid();
pLabels = new String[3];
Iterator<GSelectable> it = selection.iterator();
if (selection.size() == 2) {
GSelectable element1 = it.next();
GSelectable element2 = it.next();
if (element1 instanceof GStick && element2 instanceof GStick) {
pLabels[0] = ((GStick)element1).label1;
pLabels[1] = ((GStick)element1).label2;
pLabels[2] = ((GStick)element2).label1;
Collection<GFace> faces = solid.facesThroughPoints(pLabels);
if (!faces.isEmpty()) {
pLabels[2] = ((GStick)element2).label2;
}
}
else if (element1 instanceof GPoint3d && element2 instanceof GStick
|| element2 instanceof GPoint3d && element1 instanceof GStick) {
GPoint3d p;
GStick s;
if (element1 instanceof GPoint3d && element2 instanceof GStick) {
p = (GPoint3d)element1;
s = (GStick)element2;
pLabels = new String[] { p.getLabel(), s.label1, s.label2 };
}
else {
p = (GPoint3d)element2;
s = (GStick)element1;
pLabels = new String[] { p.getLabel(), s.label1, s.label2 };
}
}
}
else if (selection.size() == 3) {
GSelectable element1 = it.next();
GSelectable element2 = it.next();
GSelectable element3 = it.next();
if (element1 instanceof GPoint3d && element2 instanceof GPoint3d && element3 instanceof GPoint3d)
pLabels = new String[] {
((GPoint3d)element1).getLabel(),
((GPoint3d)element2).getLabel(),
((GPoint3d)element3).getLabel() };
}
}
public void validateApply() throws Exception {
logger.info("");
figure = document.getFigure(figureName);
solid = figure.getSolid();
// Validate reference points
GPoint3d[] ps = new GPoint3d[3];
for (int i = 0; i < 3; i++) {
if (pLabels[i].length() == 0) {
logger.info("No end points: " + Arrays.asList(pLabels));
throw new Exception(GDictionary.get("EnterEndPoints"));
}
ps[i] = solid.getPoint(pLabels[i]);
if (ps[i] == null) {
logger.info("No point: " + pLabels[i]);
throw new Exception(GDictionary.get("FigureContainsNoPoint", figureName, pLabels[i]));
}
}
Collection<GFace> faces = solid.facesThroughPoints(pLabels);
if (!faces.isEmpty()) {
logger.info("No face: " + Arrays.asList(pLabels));
throw new Exception(GDictionary.get("PointsBelongToSameFace", pLabels[0], pLabels[1], pLabels[2]));
}
// Apply
GDocumentHandler documentHandler = GDocumentHandler.getInstance();
GFigure[] childFigures = new GFigure[2];
Vector3d v1 = new Vector3d(ps[1].coords);
v1.sub(ps[0].coords);
Vector3d v2 = new Vector3d(ps[2].coords);
v2.sub(ps[0].coords);
Vector3d n = new Vector3d();
n.cross(v1, v2);
n.normalize();
if (n.z < - GMath.EPSILON) {
n.scale(-1);
}
else if (n.z < GMath.EPSILON) {
if (n.y < - GMath.EPSILON) {
n.scale(-1);
}
else if (n.y < GMath.EPSILON) {
if (n.x < - GMath.EPSILON) {
n.scale(-1);
}
}
}
GSolid[] childSolids = new GSolid[2];
for (int i = 0; i < 2; i++) {
childSolids[i] = solid.clone();
childSolids[i].cutOff(pLabels[0], n);
n.scale(-1);
childSolids[i].makeConfig();
double zoomFactor = childSolids[i].getBoundingSphere().getRadius() / solid.getBoundingSphere().getRadius();
childFigures[i] = documentHandler.newFigure(childSolids[i], zoomFactor);
childFigures[i].setTransparent(figure.isTransparent());
childFigures[i].setLabelled(figure.isLabelled());
GCamera camera = figure.getCamera();
GCamera c = childFigures[i].getCamera();
c.setAttitude(new Matrix3d(camera.getAttitude()));
c.setInitialAttitude(new Matrix3d(camera.getInitialAttitude()));
Color baseColor = figure.getBaseColor();
childFigures[i].setBaseColor(new Color(baseColor.getRGB()));
}
figure1Name = childFigures[0].getName();
figure2Name = childFigures[1].getName();
}
public void undo(GDocumentHandler documentHandler) {
logger.info("");
solid.clearSelection();
documentHandler.removeFigure(figure1Name);
document.removeFigure(figure1Name);
documentHandler.removeFigure(figure2Name);
document.removeFigure(figure2Name);
document.setSelectedFigure(figureName);
logger.info("Cut figure " + figureName + " into figures " + figure1Name + ", " + figure2Name + " undone");
logger.info(figureName);
}
public GLoggable clone() {
GCutAction action = new GCutAction();
action.figureName = figureName;
action.pLabels = pLabels.clone();
action.figure1Name = figure1Name;
action.figure2Name = figure2Name;
return action;
}
public String toLogString() {
StringBuffer buf = new StringBuffer();
buf.append(GDictionary.get("CutFigureThroughPoints", figureName, pLabels[1], pLabels[0], pLabels[2]));
return String.valueOf(buf);
}
public String getComments() {
return comments;
}
public void setComments(String comments) {
this.comments = comments;
}
public void make(Element node) throws Exception {
logger.info("");
NodeList ns = node.getElementsByTagName("figureName");
if (ns.getLength() == 0) {
logger.error("No figure name");
throw new Exception();
}
figureName = ns.item(0).getTextContent();
pLabels = new String[3];
ns = node.getElementsByTagName("p0Label");
if (ns.getLength() == 0) {
logger.error("No p0Label");
throw new Exception();
}
pLabels[0] = ns.item(0).getTextContent();
ns = node.getElementsByTagName("p1Label");
if (ns.getLength() == 0) {
logger.error("No p1Label");
throw new Exception();
}
pLabels[1] = ns.item(0).getTextContent();
ns = node.getElementsByTagName("p2Label");
if (ns.getLength() == 0) {
logger.error("No p2Label");
throw new Exception();
}
pLabels[2] = ns.item(0).getTextContent();
ns = node.getElementsByTagName("figure1Name");
if (ns.getLength() == 0) {
logger.error("No figure1 name");
throw new Exception();
}
figure1Name = ns.item(0).getTextContent();
ns = node.getElementsByTagName("figure2Name");
if (ns.getLength() == 0) {
logger.error("No figure2 name");
throw new Exception();
}
figure2Name = ns.item(0).getTextContent();
ns = node.getElementsByTagName("comments");
if (ns.getLength() > 0) {
String s = ns.item(0).getTextContent();
comments = GStringUtils.fromXml(s);
}
}
public void serialize(StringBuffer buf) {
logger.info("");
buf.append("\n<action>")
.append("\n<className>")
.append(this.getClass().getSimpleName())
.append("</className>")
.append("\n<figureName>")
.append(figureName)
.append("</figureName>")
.append("\n<p0Label>")
.append(pLabels[0])
.append("</p0Label>")
.append("\n<p1Label>")
.append(pLabels[1])
.append("</p1Label>")
.append("\n<p2Label>")
.append(pLabels[2])
.append("</p2Label>")
.append("\n<figure1Name>")
.append(figure1Name)
.append("</figure1Name>")
.append("\n<figure2Name>")
.append(figure2Name)
.append("</figure2Name>");
if (comments != null) {
String s = GStringUtils.toXml(comments);
buf.append("\n<comments>")
.append(s)
.append("</comments>");
}
buf.append("\n</action>");
}
public void setInput(String p0String, String p1String, String p2String) {
logger.info(p0String + ", " + p1String + ", " + p2String);
this.pLabels[0] = p0String.toUpperCase();
this.pLabels[1] = p1String.toUpperCase();
this.pLabels[2] = p2String.toUpperCase();
}
public String getShortDescription() {
return GDictionary.get("cutFigure", figureName);
}
public String getHelpId() {
return helpId;
}
public void setHelpId(String helpId) {
this.helpId = helpId;
}
}
| |
/*
* Copyright 2001-2004 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 net.jforum.util.legacy.commons.fileupload;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import net.jforum.util.legacy.commons.fileupload.servlet.ServletRequestContext;
/**
* <p>High level API for processing file uploads.</p>
*
* <p>This class handles multiple files per single HTML widget, sent using
* <code>multipart/mixed</code> encoding type, as specified by
* <a href="http://www.ietf.org/rfc/rfc1867.txt">RFC 1867</a>. Use {@link
* #parseRequest(HttpServletRequest)} to acquire a list of {@link
* org.apache.commons.fileupload.FileItem}s associated with a given HTML
* widget.</p>
*
* <p>How the data for individual parts is stored is determined by the factory
* used to create them; a given part may be in memory, on disk, or somewhere
* else.</p>
*
* @author <a href="mailto:Rafal.Krzewski@e-point.pl">Rafal Krzewski</a>
* @author <a href="mailto:dlr@collab.net">Daniel Rall</a>
* @author <a href="mailto:jvanzyl@apache.org">Jason van Zyl</a>
* @author <a href="mailto:jmcnally@collab.net">John McNally</a>
* @author <a href="mailto:martinc@apache.org">Martin Cooper</a>
* @author Sean C. Sullivan
*
* @version $Id: FileUploadBase.java,v 1.3 2005/07/26 03:05:02 rafaelsteil Exp $
*/
public abstract class FileUploadBase {
// ---------------------------------------------------------- Class methods
/**
* <p>Utility method that determines whether the request contains multipart
* content.</p>
*
* <p><strong>NOTE:</strong>This method will be moved to the
* <code>ServletFileUpload</code> class after the FileUpload 1.1 release.
* Unfortunately, since this method is static, it is not possible to
* provide its replacement until this method is removed.</p>
*
* @param ctx The request context to be evaluated. Must be non-null.
*
* @return <code>true</code> if the request is multipart;
* <code>false</code> otherwise.
*/
public static final boolean isMultipartContent(RequestContext ctx) {
String contentType = ctx.getContentType();
if (contentType == null) {
return false;
}
if (contentType.toLowerCase().startsWith(MULTIPART)) {
return true;
}
return false;
}
/**
* Utility method that determines whether the request contains multipart
* content.
*
* @param req The servlet request to be evaluated. Must be non-null.
*
* @return <code>true</code> if the request is multipart;
* <code>false</code> otherwise.
*
* @deprecated Use the method on <code>ServletFileUpload</code> instead.
*/
public static final boolean isMultipartContent(HttpServletRequest req) {
if (!"post".equals(req.getMethod().toLowerCase())) {
return false;
}
String contentType = req.getContentType();
if (contentType == null) {
return false;
}
if (contentType.toLowerCase().startsWith(MULTIPART)) {
return true;
}
return false;
}
// ----------------------------------------------------- Manifest constants
/**
* HTTP content type header name.
*/
public static final String CONTENT_TYPE = "Content-type";
/**
* HTTP content disposition header name.
*/
public static final String CONTENT_DISPOSITION = "Content-disposition";
/**
* Content-disposition value for form data.
*/
public static final String FORM_DATA = "form-data";
/**
* Content-disposition value for file attachment.
*/
public static final String ATTACHMENT = "attachment";
/**
* Part of HTTP content type header.
*/
public static final String MULTIPART = "multipart/";
/**
* HTTP content type header for multipart forms.
*/
public static final String MULTIPART_FORM_DATA = "multipart/form-data";
/**
* HTTP content type header for multiple uploads.
*/
public static final String MULTIPART_MIXED = "multipart/mixed";
/**
* The maximum length of a single header line that will be parsed
* (1024 bytes).
*/
public static final int MAX_HEADER_SIZE = 1024;
// ----------------------------------------------------------- Data members
/**
* The maximum size permitted for an uploaded file. A value of -1 indicates
* no maximum.
*/
private long sizeMax = -1;
/**
* The content encoding to use when reading part headers.
*/
private String headerEncoding;
// ----------------------------------------------------- Property accessors
/**
* Returns the factory class used when creating file items.
*
* @return The factory class for new file items.
*/
public abstract FileItemFactory getFileItemFactory();
/**
* Sets the factory class to use when creating file items.
*
* @param factory The factory class for new file items.
*/
public abstract void setFileItemFactory(FileItemFactory factory);
/**
* Returns the maximum allowed upload size.
*
* @return The maximum allowed size, in bytes.
*
* @see #setSizeMax(long)
*
*/
public long getSizeMax() {
return sizeMax;
}
/**
* Sets the maximum allowed upload size. If negative, there is no maximum.
*
* @param sizeMax The maximum allowed size, in bytes, or -1 for no maximum.
*
* @see #getSizeMax()
*
*/
public void setSizeMax(long sizeMax) {
this.sizeMax = sizeMax;
}
/**
* Retrieves the character encoding used when reading the headers of an
* individual part. When not specified, or <code>null</code>, the platform
* default encoding is used.
*
* @return The encoding used to read part headers.
*/
public String getHeaderEncoding() {
return headerEncoding;
}
/**
* Specifies the character encoding to be used when reading the headers of
* individual parts. When not specified, or <code>null</code>, the platform
* default encoding is used.
*
* @param encoding The encoding used to read part headers.
*/
public void setHeaderEncoding(String encoding) {
headerEncoding = encoding;
}
// --------------------------------------------------------- Public methods
/**
* Processes an <a href="http://www.ietf.org/rfc/rfc1867.txt">RFC 1867</a>
* compliant <code>multipart/form-data</code> stream.
*
* @param req The servlet request to be parsed.
*
* @return A list of <code>FileItem</code> instances parsed from the
* request, in the order that they were transmitted.
*
* @exception FileUploadException if there are problems reading/parsing
* the request or storing files.
*
* @deprecated Use the method in <code>ServletFileUpload</code> instead.
*/
public List /* FileItem */ parseRequest(HttpServletRequest req)
throws FileUploadException {
return parseRequest(new ServletRequestContext(req));
}
/**
* Processes an <a href="http://www.ietf.org/rfc/rfc1867.txt">RFC 1867</a>
* compliant <code>multipart/form-data</code> stream.
*
* @param ctx The context for the request to be parsed.
*
* @return A list of <code>FileItem</code> instances parsed from the
* request, in the order that they were transmitted.
*
* @exception FileUploadException if there are problems reading/parsing
* the request or storing files.
*/
public List /* FileItem */ parseRequest(RequestContext ctx)
throws FileUploadException {
if (ctx == null) {
throw new NullPointerException("ctx parameter");
}
ArrayList items = new ArrayList();
String contentType = ctx.getContentType();
if ((null == contentType)
|| (!contentType.toLowerCase().startsWith(MULTIPART))) {
throw new InvalidContentTypeException(
"the request doesn't contain a "
+ MULTIPART_FORM_DATA
+ " or "
+ MULTIPART_MIXED
+ " stream, content type header is "
+ contentType);
}
int requestSize = ctx.getContentLength();
if (requestSize == -1) {
throw new UnknownSizeException(
"the request was rejected because its size is unknown");
}
if (sizeMax >= 0 && requestSize > sizeMax) {
throw new SizeLimitExceededException(
"the request was rejected because "
+ "its size exceeds allowed range");
}
try {
byte[] boundary = getBoundary(contentType);
if (boundary == null) {
throw new FileUploadException(
"the request was rejected because "
+ "no multipart boundary was found");
}
InputStream input = ctx.getInputStream();
MultipartStream multi = new MultipartStream(input, boundary);
multi.setHeaderEncoding(headerEncoding);
boolean nextPart = multi.skipPreamble();
while (nextPart) {
Map headers = parseHeaders(multi.readHeaders());
String fieldName = getFieldName(headers);
if (fieldName != null) {
String subContentType = getHeader(headers, CONTENT_TYPE);
if (subContentType != null && subContentType
.toLowerCase().startsWith(MULTIPART_MIXED)) {
// Multiple files.
byte[] subBoundary = getBoundary(subContentType);
multi.setBoundary(subBoundary);
boolean nextSubPart = multi.skipPreamble();
while (nextSubPart) {
headers = parseHeaders(multi.readHeaders());
if (getFileName(headers) != null) {
FileItem item =
createItem(headers, false);
OutputStream os = item.getOutputStream();
try {
multi.readBodyData(os);
} finally {
os.close();
}
items.add(item);
} else {
// Ignore anything but files inside
// multipart/mixed.
multi.discardBodyData();
}
nextSubPart = multi.readBoundary();
}
multi.setBoundary(boundary);
} else {
FileItem item = createItem(headers,
getFileName(headers) == null);
OutputStream os = item.getOutputStream();
try {
multi.readBodyData(os);
} finally {
os.close();
}
items.add(item);
}
} else {
// Skip this part.
multi.discardBodyData();
}
nextPart = multi.readBoundary();
}
} catch (IOException e) {
throw new FileUploadException(
"Processing of " + MULTIPART_FORM_DATA
+ " request failed. " + e.getMessage());
}
return items;
}
// ------------------------------------------------------ Protected methods
/**
* Retrieves the boundary from the <code>Content-type</code> header.
*
* @param contentType The value of the content type header from which to
* extract the boundary value.
*
* @return The boundary, as a byte array.
*/
protected byte[] getBoundary(String contentType) {
ParameterParser parser = new ParameterParser();
parser.setLowerCaseNames(true);
// Parameter parser can handle null input
Map params = parser.parse(contentType, ';');
String boundaryStr = (String) params.get("boundary");
if (boundaryStr == null) {
return null;
}
byte[] boundary;
try {
boundary = boundaryStr.getBytes("ISO-8859-1");
} catch (UnsupportedEncodingException e) {
boundary = boundaryStr.getBytes();
}
return boundary;
}
/**
* Retrieves the file name from the <code>Content-disposition</code>
* header.
*
* @param headers A <code>Map</code> containing the HTTP request headers.
*
* @return The file name for the current <code>encapsulation</code>.
*/
protected String getFileName(Map /* String, String */ headers) {
String fileName = null;
String cd = getHeader(headers, CONTENT_DISPOSITION);
if (cd.startsWith(FORM_DATA) || cd.startsWith(ATTACHMENT)) {
ParameterParser parser = new ParameterParser();
parser.setLowerCaseNames(true);
// Parameter parser can handle null input
Map params = parser.parse(cd, ';');
if (params.containsKey("filename")) {
fileName = (String) params.get("filename");
if (fileName != null) {
fileName = fileName.trim();
} else {
// Even if there is no value, the parameter is present, so
// we return an empty file name rather than no file name.
fileName = "";
}
}
}
return fileName;
}
/**
* Retrieves the field name from the <code>Content-disposition</code>
* header.
*
* @param headers A <code>Map</code> containing the HTTP request headers.
*
* @return The field name for the current <code>encapsulation</code>.
*/
protected String getFieldName(Map /* String, String */ headers) {
String fieldName = null;
String cd = getHeader(headers, CONTENT_DISPOSITION);
if (cd != null && cd.startsWith(FORM_DATA)) {
ParameterParser parser = new ParameterParser();
parser.setLowerCaseNames(true);
// Parameter parser can handle null input
Map params = parser.parse(cd, ';');
fieldName = (String) params.get("name");
if (fieldName != null) {
fieldName = fieldName.trim();
}
}
return fieldName;
}
/**
* Creates a new {@link FileItem} instance.
*
* @param headers A <code>Map</code> containing the HTTP request
* headers.
* @param isFormField Whether or not this item is a form field, as
* opposed to a file.
*
* @return A newly created <code>FileItem</code> instance.
*
* @exception FileUploadException if an error occurs.
*/
protected FileItem createItem(Map headers,
boolean isFormField) {
return getFileItemFactory().createItem(getFieldName(headers),
getHeader(headers, CONTENT_TYPE),
isFormField,
getFileName(headers));
}
/**
* <p> Parses the <code>header-part</code> and returns as key/value
* pairs.
*
* <p> If there are multiple headers of the same names, the name
* will map to a comma-separated list containing the values.
*
* @param headerPart The <code>header-part</code> of the current
* <code>encapsulation</code>.
*
* @return A <code>Map</code> containing the parsed HTTP request headers.
*/
protected Map /* String, String */ parseHeaders(String headerPart) {
Map headers = new HashMap();
char[] buffer = new char[MAX_HEADER_SIZE];
boolean done = false;
int j = 0;
int i;
String header, headerName, headerValue;
try {
while (!done) {
i = 0;
// Copy a single line of characters into the buffer,
// omitting trailing CRLF.
while (i < 2
|| buffer[i - 2] != '\r' || buffer[i - 1] != '\n') {
buffer[i++] = headerPart.charAt(j++);
}
header = new String(buffer, 0, i - 2);
if (header.equals("")) {
done = true;
} else {
if (header.indexOf(':') == -1) {
// This header line is malformed, skip it.
continue;
}
headerName = header.substring(0, header.indexOf(':'))
.trim().toLowerCase();
headerValue =
header.substring(header.indexOf(':') + 1).trim();
if (getHeader(headers, headerName) != null) {
// More that one heder of that name exists,
// append to the list.
headers.put(headerName,
getHeader(headers, headerName) + ','
+ headerValue);
} else {
headers.put(headerName, headerValue);
}
}
}
} catch (IndexOutOfBoundsException e) {
// Headers were malformed. continue with all that was
// parsed.
}
return headers;
}
/**
* Returns the header with the specified name from the supplied map. The
* header lookup is case-insensitive.
*
* @param headers A <code>Map</code> containing the HTTP request headers.
* @param name The name of the header to return.
*
* @return The value of specified header, or a comma-separated list if
* there were multiple headers of that name.
*/
protected final String getHeader(Map /* String, String */ headers,
String name) {
return (String) headers.get(name.toLowerCase());
}
/**
* Thrown to indicate that the request is not a multipart request.
*/
public static class InvalidContentTypeException
extends FileUploadException {
/**
* Constructs a <code>InvalidContentTypeException</code> with no
* detail message.
*/
public InvalidContentTypeException() {
super();
}
/**
* Constructs an <code>InvalidContentTypeException</code> with
* the specified detail message.
*
* @param message The detail message.
*/
public InvalidContentTypeException(String message) {
super(message);
}
}
/**
* Thrown to indicate that the request size is not specified.
*/
public static class UnknownSizeException
extends FileUploadException {
/**
* Constructs a <code>UnknownSizeException</code> with no
* detail message.
*/
public UnknownSizeException() {
super();
}
/**
* Constructs an <code>UnknownSizeException</code> with
* the specified detail message.
*
* @param message The detail message.
*/
public UnknownSizeException(String message) {
super(message);
}
}
/**
* Thrown to indicate that the request size exceeds the configured maximum.
*/
public static class SizeLimitExceededException
extends FileUploadException {
/**
* Constructs a <code>SizeExceededException</code> with no
* detail message.
*/
public SizeLimitExceededException() {
super();
}
/**
* Constructs an <code>SizeExceededException</code> with
* the specified detail message.
*
* @param message The detail message.
*/
public SizeLimitExceededException(String message) {
super(message);
}
}
}
| |
/*
* Copyright 2020 LINE Corporation
*
* LINE Corporation 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:
*
* https://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.linecorp.armeria.client.retry;
import static com.linecorp.armeria.client.retry.RetryRuleUtil.NEXT_DECISION;
import static java.util.Objects.requireNonNull;
import java.util.concurrent.CompletionStage;
import java.util.function.BiFunction;
import java.util.function.BiPredicate;
import com.linecorp.armeria.client.AbstractRuleWithContentBuilder;
import com.linecorp.armeria.client.ClientRequestContext;
import com.linecorp.armeria.client.UnprocessedRequestException;
import com.linecorp.armeria.common.HttpHeaders;
import com.linecorp.armeria.common.HttpStatus;
import com.linecorp.armeria.common.HttpStatusClass;
import com.linecorp.armeria.common.RequestHeaders;
import com.linecorp.armeria.common.Response;
import com.linecorp.armeria.common.ResponseHeaders;
import com.linecorp.armeria.internal.client.AbstractRuleBuilderUtil;
/**
* A builder for creating a new {@link RetryRuleWithContent}.
*/
public final class RetryRuleWithContentBuilder<T extends Response> extends AbstractRuleWithContentBuilder<T> {
RetryRuleWithContentBuilder(
BiPredicate<? super ClientRequestContext, ? super RequestHeaders> requestHeadersFilter) {
super(requestHeadersFilter);
}
/**
* Adds the specified {@code responseFilter} for a {@link RetryRuleWithContent} which will retry
* if the specified {@code responseFilter} completes with {@code true}.
*/
@Override
public RetryRuleWithContentBuilder<T> onResponse(
BiFunction<? super ClientRequestContext, ? super T,
? extends CompletionStage<Boolean>> responseFilter) {
return (RetryRuleWithContentBuilder<T>) super.onResponse(responseFilter);
}
/**
* Sets the {@linkplain Backoff#ofDefault() default backoff} and
* returns a newly created {@link RetryRuleWithContent}.
*/
public RetryRuleWithContent<T> thenBackoff() {
return thenBackoff(Backoff.ofDefault());
}
/**
* Sets the specified {@link Backoff} and returns a newly created {@link RetryRuleWithContent}.
*/
public RetryRuleWithContent<T> thenBackoff(Backoff backoff) {
requireNonNull(backoff, "backoff");
return build(RetryDecision.retry(backoff));
}
/**
* Returns a newly created {@link RetryRuleWithContent} that never retries.
*/
public RetryRuleWithContent<T> thenNoRetry() {
return build(RetryDecision.noRetry());
}
RetryRuleWithContent<T> build(RetryDecision decision) {
final BiFunction<? super ClientRequestContext, ? super T,
? extends CompletionStage<Boolean>> responseFilter = responseFilter();
final boolean hasResponseFilter = responseFilter != null;
if (decision != RetryDecision.noRetry() && exceptionFilter() == null &&
responseHeadersFilter() == null && !hasResponseFilter) {
throw new IllegalStateException("Should set at least one retry rule if a backoff was set.");
}
final BiFunction<? super ClientRequestContext, ? super Throwable, Boolean> ruleFilter =
AbstractRuleBuilderUtil.buildFilter(requestHeadersFilter(), responseHeadersFilter(),
responseTrailersFilter(), exceptionFilter(),
hasResponseFilter);
final RetryRule first = RetryRuleBuilder.build(ruleFilter, decision, responseTrailersFilter() != null);
if (!hasResponseFilter) {
return RetryRuleUtil.fromRetryRule(first);
}
final RetryRuleWithContent<T> second = (ctx, content, cause) -> {
if (content == null) {
return NEXT_DECISION;
}
return responseFilter.apply(ctx, content)
.handle((matched, cause0) -> {
if (cause0 != null) {
return RetryDecision.next();
}
return matched ? decision : RetryDecision.next();
});
};
return RetryRuleUtil.orElse(first, second);
}
// Override the return type of the chaining methods in the superclass.
/**
* Adds the specified {@code responseHeadersFilter} for a {@link RetryRuleWithContent} which will retry
* if the {@code responseHeadersFilter} returns {@code true}.
*/
@SuppressWarnings("unchecked")
@Override
public RetryRuleWithContentBuilder<T> onResponseHeaders(
BiPredicate<? super ClientRequestContext, ? super ResponseHeaders> responseHeadersFilter) {
return (RetryRuleWithContentBuilder<T>) super.onResponseHeaders(responseHeadersFilter);
}
/**
* Adds the specified {@code responseTrailersFilter} for a {@link RetryRuleWithContent} which will retry
* if the {@code responseTrailersFilter} returns {@code true}. Note that using this method makes the entire
* response buffered, which may lead to excessive memory usage.
*/
@SuppressWarnings("unchecked")
@Override
public RetryRuleWithContentBuilder<T> onResponseTrailers(
BiPredicate<? super ClientRequestContext, ? super HttpHeaders> responseTrailersFilter) {
return (RetryRuleWithContentBuilder<T>) super.onResponseTrailers(responseTrailersFilter);
}
/**
* Adds the specified {@link HttpStatusClass}es for a {@link RetryRuleWithContent} which will retry
* if a class of the response status is one of the specified {@link HttpStatusClass}es.
*/
@SuppressWarnings("unchecked")
@Override
public RetryRuleWithContentBuilder<T> onStatusClass(HttpStatusClass... statusClasses) {
return (RetryRuleWithContentBuilder<T>) super.onStatusClass(statusClasses);
}
/**
* Adds the specified {@link HttpStatusClass}es for a {@link RetryRuleWithContent} which will retry
* if a class of the response status is one of the specified {@link HttpStatusClass}es.
*/
@SuppressWarnings("unchecked")
@Override
public RetryRuleWithContentBuilder<T> onStatusClass(Iterable<HttpStatusClass> statusClasses) {
return (RetryRuleWithContentBuilder<T>) super.onStatusClass(statusClasses);
}
/**
* Adds the {@link HttpStatusClass#SERVER_ERROR} for a {@link RetryRuleWithContent} which will retry
* if a class of the response status is {@link HttpStatusClass#SERVER_ERROR}.
*/
@SuppressWarnings("unchecked")
@Override
public RetryRuleWithContentBuilder<T> onServerErrorStatus() {
return (RetryRuleWithContentBuilder<T>) super.onServerErrorStatus();
}
/**
* Adds the specified {@link HttpStatus}es for a {@link RetryRuleWithContent} which will retry
* if a response status is one of the specified {@link HttpStatus}es.
*/
@SuppressWarnings("unchecked")
@Override
public RetryRuleWithContentBuilder<T> onStatus(HttpStatus... statuses) {
return (RetryRuleWithContentBuilder<T>) super.onStatus(statuses);
}
/**
* Adds the specified {@link HttpStatus}es for a {@link RetryRuleWithContent} which will retry
* if a response status is one of the specified {@link HttpStatus}es.
*/
@SuppressWarnings("unchecked")
@Override
public RetryRuleWithContentBuilder<T> onStatus(Iterable<HttpStatus> statuses) {
return (RetryRuleWithContentBuilder<T>) super.onStatus(statuses);
}
/**
* Adds the specified {@code statusFilter} for a {@link RetryRuleWithContent} which will retry
* if a response status matches the specified {@code statusFilter}.
*/
@SuppressWarnings("unchecked")
@Override
public RetryRuleWithContentBuilder<T> onStatus(
BiPredicate<? super ClientRequestContext, ? super HttpStatus> statusFilter) {
return (RetryRuleWithContentBuilder<T>) super.onStatus(statusFilter);
}
/**
* Adds the specified exception type for a {@link RetryRuleWithContent} which will retry
* if an {@link Exception} is raised and it is an instance of the specified {@code exception}.
*/
@SuppressWarnings("unchecked")
@Override
public RetryRuleWithContentBuilder<T> onException(Class<? extends Throwable> exception) {
return (RetryRuleWithContentBuilder<T>) super.onException(exception);
}
/**
* Adds the specified {@code exceptionFilter} for a {@link RetryRuleWithContent} which will retry
* if an {@link Exception} is raised and the specified {@code exceptionFilter} returns {@code true}.
*/
@SuppressWarnings("unchecked")
@Override
public RetryRuleWithContentBuilder<T> onException(
BiPredicate<? super ClientRequestContext, ? super Throwable> exceptionFilter) {
return (RetryRuleWithContentBuilder<T>) super.onException(exceptionFilter);
}
/**
* Makes a {@link RetryRuleWithContent} retry on any {@link Exception}.
*/
@SuppressWarnings("unchecked")
@Override
public RetryRuleWithContentBuilder<T> onException() {
return (RetryRuleWithContentBuilder<T>) super.onException();
}
/**
* Makes a {@link RetryRuleWithContent} retry on an {@link UnprocessedRequestException} which means that
* the request has not been processed by the server.
* Therefore, you can safely retry the request without worrying about the idempotency of the request.
*/
@SuppressWarnings("unchecked")
@Override
public RetryRuleWithContentBuilder<T> onUnprocessed() {
return (RetryRuleWithContentBuilder<T>) super.onUnprocessed();
}
}
| |
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. 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.wso2.carbon.device.mgt.core.operation.mgt.dao.impl;
import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
import org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation;
import org.wso2.carbon.device.mgt.core.operation.mgt.OperationEnrolmentMapping;
import org.wso2.carbon.device.mgt.core.operation.mgt.OperationMapping;
import org.wso2.carbon.device.mgt.core.operation.mgt.dao.OperationManagementDAOException;
import org.wso2.carbon.device.mgt.core.operation.mgt.dao.OperationManagementDAOFactory;
import org.wso2.carbon.device.mgt.core.operation.mgt.dao.OperationManagementDAOUtil;
import org.wso2.carbon.device.mgt.core.operation.mgt.dao.OperationMappingDAO;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class OperationMappingDAOImpl implements OperationMappingDAO {
@Override
public void addOperationMapping(int operationId, Integer deviceId, boolean isScheduled) throws
OperationManagementDAOException {
PreparedStatement stmt = null;
try {
long time = System.currentTimeMillis() / 1000;
Connection conn = OperationManagementDAOFactory.getConnection();
String sql = "INSERT INTO DM_ENROLMENT_OP_MAPPING(ENROLMENT_ID, OPERATION_ID, STATUS, " +
"PUSH_NOTIFICATION_STATUS, CREATED_TIMESTAMP, UPDATED_TIMESTAMP) VALUES (?, ?, ?, ?, ?, ?)";
stmt = conn.prepareStatement(sql);
stmt.setInt(1, deviceId);
stmt.setInt(2, operationId);
stmt.setString(3, Operation.Status.PENDING.toString());
if (isScheduled) {
stmt.setString(4, Operation.PushNotificationStatus.SCHEDULED.toString());
} else {
stmt.setString(4, Operation.PushNotificationStatus.COMPLETED.toString());
}
stmt.setLong(5, time);
stmt.setLong(6, time);
stmt.executeUpdate();
} catch (SQLException e) {
throw new OperationManagementDAOException("Error occurred while persisting device operation mappings", e);
} finally {
OperationManagementDAOUtil.cleanupResources(stmt, null);
}
}
@Override
public void removeOperationMapping(int operationId,
Integer deviceId) throws OperationManagementDAOException {
PreparedStatement stmt = null;
try {
Connection conn = OperationManagementDAOFactory.getConnection();
String sql = "DELETE FROM DM_ENROLMENT_OP_MAPPING WHERE ENROLMENT_ID = ? AND OPERATION_ID = ?";
stmt = conn.prepareStatement(sql);
stmt.setInt(1, deviceId);
stmt.setInt(2, operationId);
stmt.executeUpdate();
} catch (SQLException e) {
throw new OperationManagementDAOException("Error occurred while persisting device operation mappings", e);
} finally {
OperationManagementDAOUtil.cleanupResources(stmt, null);
}
}
@Override
public void updateOperationMapping(int operationId, Integer deviceId, Operation.PushNotificationStatus pushNotificationStatus) throws OperationManagementDAOException {
PreparedStatement stmt = null;
try {
Connection conn = OperationManagementDAOFactory.getConnection();
String sql = "UPDATE DM_ENROLMENT_OP_MAPPING SET PUSH_NOTIFICATION_STATUS = ? WHERE ENROLMENT_ID = ? and " +
"OPERATION_ID = ?";
stmt = conn.prepareStatement(sql);
stmt.setString(1, pushNotificationStatus.toString());
stmt.setInt(2, deviceId);
stmt.setInt(3, operationId);
stmt.executeUpdate();
} catch (SQLException e) {
throw new OperationManagementDAOException("Error occurred while updating device operation mappings", e);
} finally {
OperationManagementDAOUtil.cleanupResources(stmt, null);
}
}
@Override
public void updateOperationMapping(List<OperationMapping> operationMappingList) throws
OperationManagementDAOException {
PreparedStatement stmt = null;
try {
Connection conn = OperationManagementDAOFactory.getConnection();
String sql = "UPDATE DM_ENROLMENT_OP_MAPPING SET PUSH_NOTIFICATION_STATUS = ? WHERE ENROLMENT_ID = ? and " +
"OPERATION_ID = ?";
stmt = conn.prepareStatement(sql);
if (conn.getMetaData().supportsBatchUpdates()) {
for (OperationMapping operationMapping : operationMappingList) {
stmt.setString(1, operationMapping.getPushNotificationStatus().toString());
stmt.setInt(2, operationMapping.getEnrollmentId());
stmt.setInt(3, operationMapping.getOperationId());
stmt.addBatch();
}
stmt.executeBatch();
} else {
for (OperationMapping operationMapping : operationMappingList) {
stmt.setString(1, operationMapping.getPushNotificationStatus().toString());
stmt.setInt(2, operationMapping.getEnrollmentId());
stmt.setInt(3, operationMapping.getOperationId());
stmt.executeUpdate();
}
}
} catch (SQLException e) {
throw new OperationManagementDAOException("Error occurred while updating device operation mappings as " +
"batch ", e);
} finally {
OperationManagementDAOUtil.cleanupResources(stmt, null);
}
}
@Override
public List<OperationEnrolmentMapping> getFirstPendingOperationMappingsForActiveEnrolments(long minDuration,
long maxDuration, int deviceTypeId) throws OperationManagementDAOException {
PreparedStatement stmt = null;
ResultSet rs = null;
List<OperationEnrolmentMapping> enrolmentOperationMappingList = null;
try {
Connection conn = OperationManagementDAOFactory.getConnection();
//We are specifically looking for operation mappings in 'Pending' & 'Repeated' states. Further we want
//devices to be active at that moment. Hence filtering by 'ACTIVE' & 'UNREACHABLE' device states.
String sql = "SELECT ENROLMENT_ID, D.DEVICE_IDENTIFICATION AS DEVICE_IDENTIFIER, MIN(CREATED_TIMESTAMP) " +
"AS CREATED_TIMESTAMP, E.STATUS AS ENROLMENT_STATUS, E.TENANT_ID FROM " +
"DM_ENROLMENT_OP_MAPPING AS OP INNER JOIN DM_ENROLMENT E ON OP.ENROLMENT_ID = E.ID INNER JOIN " +
"DM_DEVICE D ON E.DEVICE_ID = D.ID WHERE " +
"OP.STATUS IN ('"+ Operation.Status.PENDING.name() + "','" + Operation.Status.REPEATED.name() + "') " +
"AND OP.CREATED_TIMESTAMP BETWEEN ? AND ? AND E.STATUS IN ('" + EnrolmentInfo.Status.ACTIVE.name() +
"','" + EnrolmentInfo.Status.UNREACHABLE.name() + "') AND D.DEVICE_TYPE_ID = ? GROUP BY ENROLMENT_ID";
stmt = conn.prepareStatement(sql);
stmt.setLong(1, maxDuration);
stmt.setLong(2, minDuration);
stmt.setInt(3, deviceTypeId);
rs = stmt.executeQuery();
enrolmentOperationMappingList = new ArrayList<>();
while (rs.next()) {
OperationEnrolmentMapping enrolmentOperationMapping = this.getEnrolmentOpMapping(rs);
enrolmentOperationMappingList.add(enrolmentOperationMapping);
}
} catch (SQLException e) {
throw new OperationManagementDAOException("Error occurred while fetching pending operation mappings for " +
"active devices of type '" + deviceTypeId + "'", e);
} finally {
OperationManagementDAOUtil.cleanupResources(stmt, rs);
}
return enrolmentOperationMappingList;
}
@Override
public Map<Integer, Long> getLastConnectedTimeForActiveEnrolments(long timeStamp, int deviceTypeId) throws OperationManagementDAOException {
PreparedStatement stmt = null;
ResultSet rs = null;
Map<Integer, Long> lastConnectedTimeMap = null;
try {
Connection conn = OperationManagementDAOFactory.getConnection();
//We are specifically looking for operation mappings in 'Pending' & 'Repeated' states. Further we want
//devices to be active at that moment. Hence filtering by 'ACTIVE' & 'UNREACHABLE' device states.
String sql = "SELECT OP.ENROLMENT_ID AS EID, MAX(OP.UPDATED_TIMESTAMP) AS LAST_CONNECTED_TIME FROM " +
"DM_ENROLMENT_OP_MAPPING AS OP INNER JOIN DM_ENROLMENT E ON OP.ENROLMENT_ID = E.ID INNER JOIN " +
"DM_DEVICE D ON E.DEVICE_ID = D.ID WHERE " +
"OP.STATUS = '" + Operation.Status.COMPLETED.name() + "'" +
"AND OP.UPDATED_TIMESTAMP >= ? AND E.STATUS IN ('" + EnrolmentInfo.Status.ACTIVE.name() +
"','" + EnrolmentInfo.Status.UNREACHABLE.name() + "') AND D.DEVICE_TYPE_ID = ? GROUP BY ENROLMENT_ID";
stmt = conn.prepareStatement(sql);
stmt.setLong(1, timeStamp);
stmt.setInt(2, deviceTypeId);
rs = stmt.executeQuery();
lastConnectedTimeMap = new HashMap<>();
while (rs.next()) {
lastConnectedTimeMap.put(rs.getInt("EID"), rs.getLong("LAST_CONNECTED_TIME"));
}
} catch (SQLException e) {
throw new OperationManagementDAOException("Error occurred while fetching last connected time for " +
"active devices of type '" + deviceTypeId + "'", e);
} finally {
OperationManagementDAOUtil.cleanupResources(stmt, rs);
}
return lastConnectedTimeMap;
}
private OperationEnrolmentMapping getEnrolmentOpMapping(ResultSet rs) throws SQLException {
OperationEnrolmentMapping enrolmentOperationMapping = new OperationEnrolmentMapping();
enrolmentOperationMapping.setEnrolmentId(rs.getInt("ENROLMENT_ID"));
enrolmentOperationMapping.setDeviceId(rs.getString("DEVICE_IDENTIFIER"));
enrolmentOperationMapping.setTenantId(rs.getInt("TENANT_ID"));
enrolmentOperationMapping.setCreatedTime(rs.getLong("CREATED_TIMESTAMP"));
enrolmentOperationMapping.setDeviceStatus(rs.getString("ENROLMENT_STATUS"));
return enrolmentOperationMapping;
}
}
| |
/**
* 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.component.sparkrest;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.camel.CamelContext;
import org.apache.camel.Consumer;
import org.apache.camel.Endpoint;
import org.apache.camel.Processor;
import org.apache.camel.impl.UriEndpointComponent;
import org.apache.camel.spi.Metadata;
import org.apache.camel.spi.RestApiConsumerFactory;
import org.apache.camel.spi.RestConfiguration;
import org.apache.camel.spi.RestConsumerFactory;
import org.apache.camel.util.FileUtil;
import org.apache.camel.util.HostUtils;
import org.apache.camel.util.ObjectHelper;
import org.apache.camel.util.URISupport;
public class SparkComponent extends UriEndpointComponent implements RestConsumerFactory, RestApiConsumerFactory {
private static final Pattern PATTERN = Pattern.compile("\\{(.*?)\\}");
@Metadata(defaultValue = "4567")
private int port = 4567;
@Metadata(defaultValue = "0.0.0.0")
private String ipAddress;
@Metadata(label = "advanced")
private int minThreads;
@Metadata(label = "advanced")
private int maxThreads;
@Metadata(label = "advanced")
private int timeOutMillis;
@Metadata(label = "security")
private String keystoreFile;
@Metadata(label = "security", secret = true)
private String keystorePassword;
@Metadata(label = "security")
private String truststoreFile;
@Metadata(label = "security", secret = true)
private String truststorePassword;
@Metadata(label = "advanced")
private SparkConfiguration sparkConfiguration = new SparkConfiguration();
@Metadata(label = "advanced")
private SparkBinding sparkBinding = new DefaultSparkBinding();
public SparkComponent() {
super(SparkEndpoint.class);
}
public int getPort() {
return port;
}
/**
* Port number.
* <p/>
* Will by default use 4567
*/
public void setPort(int port) {
this.port = port;
}
public String getIpAddress() {
return ipAddress;
}
/**
* Set the IP address that Spark should listen on. If not called the default address is '0.0.0.0'.
*/
public void setIpAddress(String ipAddress) {
this.ipAddress = ipAddress;
}
public int getMinThreads() {
return minThreads;
}
/**
* Minimum number of threads in Spark thread-pool (shared globally)
*/
public void setMinThreads(int minThreads) {
this.minThreads = minThreads;
}
public int getMaxThreads() {
return maxThreads;
}
/**
* Maximum number of threads in Spark thread-pool (shared globally)
*/
public void setMaxThreads(int maxThreads) {
this.maxThreads = maxThreads;
}
public int getTimeOutMillis() {
return timeOutMillis;
}
/**
* Thread idle timeout in millis where threads that has been idle for a longer period will be terminated from the thread pool
*/
public void setTimeOutMillis(int timeOutMillis) {
this.timeOutMillis = timeOutMillis;
}
public String getKeystoreFile() {
return keystoreFile;
}
/**
* Configures connection to be secure to use the keystore file
*/
public void setKeystoreFile(String keystoreFile) {
this.keystoreFile = keystoreFile;
}
public String getKeystorePassword() {
return keystorePassword;
}
/**
* Configures connection to be secure to use the keystore password
*/
public void setKeystorePassword(String keystorePassword) {
this.keystorePassword = keystorePassword;
}
public String getTruststoreFile() {
return truststoreFile;
}
/**
* Configures connection to be secure to use the truststore file
*/
public void setTruststoreFile(String truststoreFile) {
this.truststoreFile = truststoreFile;
}
public String getTruststorePassword() {
return truststorePassword;
}
/**
* Configures connection to be secure to use the truststore password
*/
public void setTruststorePassword(String truststorePassword) {
this.truststorePassword = truststorePassword;
}
public SparkConfiguration getSparkConfiguration() {
return sparkConfiguration;
}
/**
* To use the shared SparkConfiguration
*/
public void setSparkConfiguration(SparkConfiguration sparkConfiguration) {
this.sparkConfiguration = sparkConfiguration;
}
public SparkBinding getSparkBinding() {
return sparkBinding;
}
/**
* To use a custom SparkBinding to map to/from Camel message.
*/
public void setSparkBinding(SparkBinding sparkBinding) {
this.sparkBinding = sparkBinding;
}
@Override
protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception {
SparkConfiguration config = getSparkConfiguration().copy();
setProperties(config, parameters);
SparkEndpoint answer = new SparkEndpoint(uri, this);
answer.setSparkConfiguration(config);
answer.setSparkBinding(getSparkBinding());
setProperties(answer, parameters);
if (!remaining.contains(":")) {
throw new IllegalArgumentException("Invalid syntax. Must be spark-rest:verb:path");
}
String verb = ObjectHelper.before(remaining, ":");
String path = ObjectHelper.after(remaining, ":");
answer.setVerb(verb);
answer.setPath(path);
return answer;
}
@Override
protected void doStart() throws Exception {
super.doStart();
if (getPort() != 4567) {
CamelSpark.port(getPort());
} else {
// if no explicit port configured, then use port from rest configuration
RestConfiguration config = getCamelContext().getRestConfiguration("spark-rest", true);
int port = config.getPort();
if (port > 0) {
CamelSpark.port(port);
}
}
String host = getIpAddress();
if (host != null) {
CamelSpark.ipAddress(host);
} else {
// if no explicit port configured, then use port from rest configuration
RestConfiguration config = getCamelContext().getRestConfiguration("spark-rest", true);
host = config.getHost();
if (ObjectHelper.isEmpty(host)) {
if (config.getRestHostNameResolver() == RestConfiguration.RestHostNameResolver.allLocalIp) {
host = "0.0.0.0";
} else if (config.getRestHostNameResolver() == RestConfiguration.RestHostNameResolver.localHostName) {
host = HostUtils.getLocalHostName();
} else if (config.getRestHostNameResolver() == RestConfiguration.RestHostNameResolver.localIp) {
host = HostUtils.getLocalIp();
}
}
CamelSpark.ipAddress(host);
}
if (keystoreFile != null || truststoreFile != null) {
CamelSpark.security(keystoreFile, keystorePassword, truststoreFile, truststorePassword);
}
// configure component options
RestConfiguration config = getCamelContext().getRestConfiguration("spark-rest", true);
// configure additional options on spark configuration
if (config.getComponentProperties() != null && !config.getComponentProperties().isEmpty()) {
setProperties(sparkConfiguration, config.getComponentProperties());
}
}
@Override
protected void doShutdown() throws Exception {
super.doShutdown();
CamelSpark.stop();
}
@Override
public Consumer createConsumer(CamelContext camelContext, Processor processor, String verb, String basePath, String uriTemplate,
String consumes, String produces, RestConfiguration configuration, Map<String, Object> parameters) throws Exception {
return doCreateConsumer(camelContext, processor, verb, basePath, uriTemplate, consumes, produces, configuration, parameters, false);
}
@Override
public Consumer createApiConsumer(CamelContext camelContext, Processor processor, String contextPath,
RestConfiguration configuration, Map<String, Object> parameters) throws Exception {
// reuse the createConsumer method we already have. The api need to use GET and match on uri prefix
return doCreateConsumer(camelContext, processor, "get", contextPath, null, null, null, configuration, parameters, true);
}
Consumer doCreateConsumer(CamelContext camelContext, Processor processor, String verb, String basePath, String uriTemplate,
String consumes, String produces, RestConfiguration configuration, Map<String, Object> parameters, boolean api) throws Exception {
String path = basePath;
if (uriTemplate != null) {
// make sure to avoid double slashes
if (uriTemplate.startsWith("/")) {
path = path + uriTemplate;
} else {
path = path + "/" + uriTemplate;
}
}
path = FileUtil.stripLeadingSeparator(path);
RestConfiguration config = configuration;
if (config == null) {
config = camelContext.getRestConfiguration("spark-rest", true);
}
Map<String, Object> map = new HashMap<String, Object>();
if (consumes != null) {
map.put("accept", consumes);
}
// setup endpoint options
if (config.getEndpointProperties() != null && !config.getEndpointProperties().isEmpty()) {
map.putAll(config.getEndpointProperties());
}
if (ObjectHelper.isNotEmpty(path)) {
// spark-rest uses :name syntax instead of {name} so we need to replace those
Matcher matcher = PATTERN.matcher(path);
path = matcher.replaceAll(":$1");
}
// prefix path with context-path if configured in rest-dsl configuration
String contextPath = config.getContextPath();
if (ObjectHelper.isNotEmpty(contextPath)) {
contextPath = FileUtil.stripTrailingSeparator(contextPath);
contextPath = FileUtil.stripLeadingSeparator(contextPath);
if (ObjectHelper.isNotEmpty(contextPath)) {
path = contextPath + "/" + path;
}
}
String url;
if (api) {
url = "spark-rest:%s:%s?matchOnUriPrefix=true";
} else {
url = "spark-rest:%s:%s";
}
url = String.format(url, verb, path);
String query = URISupport.createQueryString(map);
if (!query.isEmpty()) {
url = url + "?" + query;
}
// get the endpoint
SparkEndpoint endpoint = camelContext.getEndpoint(url, SparkEndpoint.class);
setProperties(camelContext, endpoint, parameters);
// configure consumer properties
Consumer consumer = endpoint.createConsumer(processor);
if (config.isEnableCORS()) {
// if CORS is enabled then configure that on the spark consumer
if (config.getConsumerProperties() == null) {
config.setConsumerProperties(new HashMap<String, Object>());
}
config.getConsumerProperties().put("enableCors", true);
}
if (config.getConsumerProperties() != null && !config.getConsumerProperties().isEmpty()) {
setProperties(camelContext, consumer, config.getConsumerProperties());
}
return consumer;
}
}
| |
// Copyright 2017 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.firebase.messaging.cpp;
import android.content.Context;
import android.net.Uri;
import com.google.firebase.messaging.RemoteMessage;
import com.google.firebase.messaging.RemoteMessage.Notification;
import com.google.flatbuffers.FlatBufferBuilder;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.channels.FileLock;
import java.util.Map;
/** */
public class MessageWriter {
// LINT.IfChange
static final String LOCK_FILE = "FIREBASE_CLOUD_MESSAGING_LOCKFILE";
// LINT.ThenChange(//depot_firebase_cpp/messaging/client/cpp/src/android/cpp/messaging_internal.h)
// LINT.IfChange
static final String STORAGE_FILE = "FIREBASE_CLOUD_MESSAGING_LOCAL_STORAGE";
// LINT.ThenChange(//depot_firebase_cpp/messaging/client/cpp/src/android/cpp/messaging_internal.h)
private static final String TAG = "FIREBASE_MESSAGE_WRITER";
private static final MessageWriter DEFAULT_INSTANCE = new MessageWriter();
public static MessageWriter defaultInstance() {
return DEFAULT_INSTANCE;
}
/** Send a message to the application. */
public void writeMessage(
Context context, RemoteMessage message, boolean notificationOpened, Uri linkUri) {
String from = message.getFrom();
String to = message.getTo();
String messageId = message.getMessageId();
String messageType = message.getMessageType();
Map<String, String> data = message.getData();
byte[] rawData = message.getRawData();
Notification notification = message.getNotification();
String collapseKey = message.getCollapseKey();
int priority = message.getPriority();
int originalPriority = message.getOriginalPriority();
long sentTime = message.getSentTime();
int timeToLive = message.getTtl();
// Links can either come from the intent or the notification.
if (linkUri == null && notification != null) {
linkUri = notification.getLink();
}
String link = (linkUri != null) ? linkUri.toString() : null;
DebugLogging.log(TAG,
String.format("onMessageReceived from=%s message_id=%s, data=%s, notification=%s", from,
messageId, (data == null ? "(null)" : data.toString()),
(notification == null ? "(null)" : notification.toString())));
writeMessageToInternalStorage(context, from, to, messageId, messageType, null, data, rawData,
notification, notificationOpened, link, collapseKey, priority, originalPriority, sentTime,
timeToLive);
}
/** Writes an event associated with a message to internal storage. */
void writeMessageEventToInternalStorage(
Context context, String messageId, String messageType, String error) {
writeMessageToInternalStorage(context, null, null, messageId, messageType, null, null, null,
null, false, null, null, 0, 0, 0, 0);
}
/**
* Writes a message to internal storage so that the app can respond to it.
*
* <p>Because the native code in the activity will not not always be running, we write out the
* messages recieved to internal storage for the activity to consume later. The current way we do
* this is just by writing flatbuffers out to a file which can then be consumed by the app
* whenever it gets around to it.
*/
@SuppressWarnings("CatchAndPrintStackTrace")
void writeMessageToInternalStorage(Context context, String from, String to, String messageId,
String messageType, String error, Map<String, String> data, byte[] rawData,
Notification notification, boolean notificationOpened, String link, String collapseKey,
int priority, int originalPriority, long sentTime, int timeToLive) {
byte[] buffer = generateMessageByteBuffer(from, to, messageId, messageType, error, data,
rawData, notification, notificationOpened, link, collapseKey, priority, originalPriority,
sentTime, timeToLive);
ByteBuffer sizeBuffer = ByteBuffer.allocate(4);
// Write out the buffer length into the first four bytes.
sizeBuffer.order(ByteOrder.LITTLE_ENDIAN);
sizeBuffer.putInt(buffer.length);
FileLock lock = null;
try {
// Acquire lock. This prevents the C++ code from consuming and clearing the file while we
// append to it.
FileOutputStream lockFileStream = context.openFileOutput(LOCK_FILE, 0);
lock = lockFileStream.getChannel().lock();
FileOutputStream outputStream = context.openFileOutput(STORAGE_FILE, Context.MODE_APPEND);
// We send both the buffer length and the buffer itself so that we can potentially process
// more than one message in the case where they get queued up.
outputStream.write(sizeBuffer.array());
outputStream.write(buffer);
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
// Release the lock.
try {
if (lock != null) {
lock.release();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
private static String emptyIfNull(String str) {
return str != null ? str : "";
}
private static String priorityToString(int priority) {
switch (priority) {
case RemoteMessage.PRIORITY_HIGH:
return "high";
case RemoteMessage.PRIORITY_NORMAL:
return "normal";
default:
return "";
}
}
private static byte[] generateMessageByteBuffer(String from, String to, String messageId,
String messageType, String error, Map<String, String> data, byte[] rawData,
Notification notification, boolean notificationOpened, String link, String collapseKey,
int priority, int originalPriority, long sentTime, int timeToLive) {
FlatBufferBuilder builder = new FlatBufferBuilder(0);
int fromOffset = builder.createString(emptyIfNull(from));
int toOffset = builder.createString(emptyIfNull(to));
int messageIdOffset = builder.createString(emptyIfNull(messageId));
int messageTypeOffset = builder.createString(emptyIfNull(messageType));
int errorOffset = builder.createString(emptyIfNull(error));
int linkOffset = builder.createString(emptyIfNull(link));
int collapseKeyOffset = builder.createString(emptyIfNull(collapseKey));
int priorityStringOffset = builder.createString(priorityToString(priority));
int originalPriorityStringOffset = builder.createString(priorityToString(originalPriority));
int dataOffset = 0;
if (data != null) {
int[] dataPairOffsets = new int[data.size()];
int index = 0;
for (Map.Entry<String, String> entry : data.entrySet()) {
int key = builder.createString(entry.getKey());
int value = builder.createString(entry.getValue());
dataPairOffsets[index++] = DataPair.createDataPair(builder, key, value);
}
dataOffset = SerializedMessage.createDataVector(builder, dataPairOffsets);
}
int rawDataOffset = 0;
if (rawData != null) {
rawDataOffset = builder.createByteVector(rawData);
}
int notificationOffset = 0;
if (notification != null) {
int titleOffset = builder.createString(emptyIfNull(notification.getTitle()));
int bodyOffset = builder.createString(emptyIfNull(notification.getBody()));
int iconOffset = builder.createString(emptyIfNull(notification.getIcon()));
int soundOffset = builder.createString(emptyIfNull(notification.getSound()));
int badgeOffset = builder.createString(""); // Badges are iOS only.
int tagOffset = builder.createString(emptyIfNull(notification.getTag()));
int colorOffset = builder.createString(emptyIfNull(notification.getColor()));
int clickActionOffset = builder.createString(emptyIfNull(notification.getClickAction()));
int androidChannelIdOffset = builder.createString(emptyIfNull(notification.getChannelId()));
int bodyLocalizationKeyOffset =
builder.createString(emptyIfNull(notification.getBodyLocalizationKey()));
int bodyLocalizationArgsOffset = 0;
String[] bodyLocalizationArgs = notification.getBodyLocalizationArgs();
if (bodyLocalizationArgs != null) {
int index = 0;
int[] bodyArgOffsets = new int[bodyLocalizationArgs.length];
for (String arg : bodyLocalizationArgs) {
bodyArgOffsets[index++] = builder.createString(arg);
}
bodyLocalizationArgsOffset =
SerializedNotification.createBodyLocArgsVector(builder, bodyArgOffsets);
}
int titleLocalizationKeyOffset =
builder.createString(emptyIfNull(notification.getTitleLocalizationKey()));
int titleLocalizationArgsOffset = 0;
String[] titleLocalizationArgs = notification.getTitleLocalizationArgs();
if (titleLocalizationArgs != null) {
int index = 0;
int[] titleArgOffsets = new int[titleLocalizationArgs.length];
for (String arg : titleLocalizationArgs) {
titleArgOffsets[index++] = builder.createString(arg);
}
titleLocalizationArgsOffset =
SerializedNotification.createTitleLocArgsVector(builder, titleArgOffsets);
}
SerializedNotification.startSerializedNotification(builder);
SerializedNotification.addTitle(builder, titleOffset);
SerializedNotification.addBody(builder, bodyOffset);
SerializedNotification.addIcon(builder, iconOffset);
SerializedNotification.addSound(builder, soundOffset);
SerializedNotification.addBadge(builder, badgeOffset);
SerializedNotification.addTag(builder, tagOffset);
SerializedNotification.addColor(builder, colorOffset);
SerializedNotification.addClickAction(builder, clickActionOffset);
SerializedNotification.addAndroidChannelId(builder, androidChannelIdOffset);
SerializedNotification.addBodyLocKey(builder, bodyLocalizationKeyOffset);
SerializedNotification.addBodyLocArgs(builder, bodyLocalizationArgsOffset);
SerializedNotification.addTitleLocKey(builder, titleLocalizationKeyOffset);
SerializedNotification.addTitleLocArgs(builder, titleLocalizationArgsOffset);
notificationOffset = SerializedNotification.endSerializedNotification(builder);
}
SerializedMessage.startSerializedMessage(builder);
SerializedMessage.addFrom(builder, fromOffset);
SerializedMessage.addTo(builder, toOffset);
SerializedMessage.addMessageId(builder, messageIdOffset);
SerializedMessage.addMessageType(builder, messageTypeOffset);
SerializedMessage.addPriority(builder, priorityStringOffset);
SerializedMessage.addOriginalPriority(builder, originalPriorityStringOffset);
SerializedMessage.addSentTime(builder, sentTime);
SerializedMessage.addTimeToLive(builder, timeToLive);
SerializedMessage.addError(builder, errorOffset);
SerializedMessage.addCollapseKey(builder, collapseKeyOffset);
if (data != null) {
SerializedMessage.addData(builder, dataOffset);
}
if (rawData != null) {
SerializedMessage.addRawData(builder, rawDataOffset);
}
if (notification != null) {
SerializedMessage.addNotification(builder, notificationOffset);
}
SerializedMessage.addNotificationOpened(builder, notificationOpened);
SerializedMessage.addLink(builder, linkOffset);
int messageOffset = SerializedMessage.endSerializedMessage(builder);
SerializedEvent.startSerializedEvent(builder);
SerializedEvent.addEventType(builder, SerializedEventUnion.SerializedMessage);
SerializedEvent.addEvent(builder, messageOffset);
builder.finish(SerializedEvent.endSerializedEvent(builder));
return builder.sizedByteArray();
}
}
| |
/*
* 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.calcite.rel.rules;
import org.apache.calcite.plan.RelOptCluster;
import org.apache.calcite.plan.RelOptRuleCall;
import org.apache.calcite.plan.RelOptUtil;
import org.apache.calcite.plan.RelRule;
import org.apache.calcite.rel.core.Aggregate;
import org.apache.calcite.rel.core.AggregateCall;
import org.apache.calcite.rel.core.Project;
import org.apache.calcite.rel.type.RelDataTypeFactory;
import org.apache.calcite.rex.RexCall;
import org.apache.calcite.rex.RexInputRef;
import org.apache.calcite.rex.RexLiteral;
import org.apache.calcite.rex.RexNode;
import org.apache.calcite.rex.RexPermuteInputsShuttle;
import org.apache.calcite.rex.RexShuttle;
import org.apache.calcite.rex.RexVisitorImpl;
import org.apache.calcite.sql.SqlKind;
import org.apache.calcite.sql.fun.SqlStdOperatorTable;
import org.apache.calcite.tools.RelBuilder;
import org.apache.calcite.util.ImmutableBitSet;
import org.apache.calcite.util.mapping.MappingType;
import org.apache.calcite.util.mapping.Mappings;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Planner rule that matches a {@link Project} on a {@link Aggregate}
* and projects away aggregate calls that are not used.
*
* <p>Also converts {@code COALESCE(SUM(x), 0)} to {@code SUM0(x)}.
* This transformation is useful because there are cases where
* {@link AggregateMergeRule} can merge {@code SUM0} but not {@code SUM}.
*
* @see CoreRules#PROJECT_AGGREGATE_MERGE
*/
public class ProjectAggregateMergeRule
extends RelRule<ProjectAggregateMergeRule.Config>
implements TransformationRule {
/** Creates a ProjectAggregateMergeRule. */
protected ProjectAggregateMergeRule(Config config) {
super(config);
}
@Override public void onMatch(RelOptRuleCall call) {
final Project project = call.rel(0);
final Aggregate aggregate = call.rel(1);
final RelOptCluster cluster = aggregate.getCluster();
// Do a quick check. If all aggregate calls are used, and there are no CASE
// expressions, there is nothing to do.
final ImmutableBitSet bits =
RelOptUtil.InputFinder.bits(project.getProjects(), null);
if (bits.contains(
ImmutableBitSet.range(aggregate.getGroupCount(),
aggregate.getRowType().getFieldCount()))
&& kindCount(project.getProjects(), SqlKind.CASE) == 0) {
return;
}
// Replace 'COALESCE(SUM(x), 0)' with 'SUM0(x)' wherever it occurs.
// Add 'SUM0(x)' to the aggregate call list, if necessary.
final List<AggregateCall> aggCallList =
new ArrayList<>(aggregate.getAggCallList());
final RexShuttle shuttle = new RexShuttle() {
@Override public RexNode visitCall(RexCall call) {
switch (call.getKind()) {
case CASE:
// Do we have "CASE(IS NOT NULL($0), CAST($0):INTEGER NOT NULL, 0)"?
final List<RexNode> operands = call.operands;
if (operands.size() == 3
&& operands.get(0).getKind() == SqlKind.IS_NOT_NULL
&& ((RexCall) operands.get(0)).operands.get(0).getKind()
== SqlKind.INPUT_REF
&& operands.get(1).getKind() == SqlKind.CAST
&& ((RexCall) operands.get(1)).operands.get(0).getKind()
== SqlKind.INPUT_REF
&& operands.get(2).getKind() == SqlKind.LITERAL) {
final RexCall isNotNull = (RexCall) operands.get(0);
final RexInputRef ref0 = (RexInputRef) isNotNull.operands.get(0);
final RexCall cast = (RexCall) operands.get(1);
final RexInputRef ref1 = (RexInputRef) cast.operands.get(0);
final RexLiteral literal = (RexLiteral) operands.get(2);
if (ref0.getIndex() == ref1.getIndex()
&& literal.getValueAs(BigDecimal.class).equals(BigDecimal.ZERO)) {
final int aggCallIndex =
ref1.getIndex() - aggregate.getGroupCount();
if (aggCallIndex >= 0) {
final AggregateCall aggCall =
aggregate.getAggCallList().get(aggCallIndex);
if (aggCall.getAggregation().getKind() == SqlKind.SUM) {
int j =
findSum0(cluster.getTypeFactory(), aggCall, aggCallList);
return cluster.getRexBuilder().makeInputRef(call.type, j);
}
}
}
}
break;
default:
break;
}
return super.visitCall(call);
}
};
final List<RexNode> projects2 = shuttle.visitList(project.getProjects());
final ImmutableBitSet bits2 =
RelOptUtil.InputFinder.bits(projects2, null);
// Build the mapping that we will apply to the project expressions.
final Mappings.TargetMapping mapping =
Mappings.create(MappingType.FUNCTION,
aggregate.getGroupCount() + aggCallList.size(), -1);
int j = 0;
for (int i = 0; i < mapping.getSourceCount(); i++) {
if (i < aggregate.getGroupCount()) {
// Field is a group key. All group keys are retained.
mapping.set(i, j++);
} else if (bits2.get(i)) {
// Field is an aggregate call. It is used.
mapping.set(i, j++);
} else {
// Field is an aggregate call. It is not used. Remove it.
aggCallList.remove(j - aggregate.getGroupCount());
}
}
final RelBuilder builder = call.builder();
builder.push(aggregate.getInput());
builder.aggregate(
builder.groupKey(aggregate.getGroupSet(),
(Iterable<ImmutableBitSet>) aggregate.groupSets), aggCallList);
builder.project(
RexPermuteInputsShuttle.of(mapping).visitList(projects2));
call.transformTo(builder.build());
}
/** Given a call to SUM, finds a call to SUM0 with identical arguments,
* or creates one and adds it to the list. Returns the index. */
private static int findSum0(RelDataTypeFactory typeFactory, AggregateCall sum,
List<AggregateCall> aggCallList) {
final AggregateCall sum0 =
AggregateCall.create(SqlStdOperatorTable.SUM0, sum.isDistinct(),
sum.isApproximate(), sum.ignoreNulls(), sum.getArgList(),
sum.filterArg, sum.collation,
typeFactory.createTypeWithNullability(sum.type, false), null);
final int i = aggCallList.indexOf(sum0);
if (i >= 0) {
return i;
}
aggCallList.add(sum0);
return aggCallList.size() - 1;
}
/** Returns the number of calls of a given kind in a list of expressions. */
private static int kindCount(Iterable<? extends RexNode> nodes,
final SqlKind kind) {
final AtomicInteger kindCount = new AtomicInteger(0);
new RexVisitorImpl<Void>(true) {
@Override public Void visitCall(RexCall call) {
if (call.getKind() == kind) {
kindCount.incrementAndGet();
}
return super.visitCall(call);
}
}.visitEach(nodes);
return kindCount.get();
}
/** Rule configuration. */
public interface Config extends RelRule.Config {
Config DEFAULT = EMPTY
.withOperandSupplier(b0 ->
b0.operand(Project.class)
.oneInput(b1 ->
b1.operand(Aggregate.class).anyInputs()))
.as(Config.class);
@Override default ProjectAggregateMergeRule toRule() {
return new ProjectAggregateMergeRule(this);
}
}
}
| |
/*
* 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.hyracks.dataflow.std.join;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.nio.ByteBuffer;
import org.apache.hyracks.api.context.IHyracksTaskContext;
import org.apache.hyracks.api.dataflow.ActivityId;
import org.apache.hyracks.api.dataflow.IActivityGraphBuilder;
import org.apache.hyracks.api.dataflow.IOperatorNodePushable;
import org.apache.hyracks.api.dataflow.TaskId;
import org.apache.hyracks.api.dataflow.value.INullWriter;
import org.apache.hyracks.api.dataflow.value.INullWriterFactory;
import org.apache.hyracks.api.dataflow.value.IPredicateEvaluator;
import org.apache.hyracks.api.dataflow.value.IPredicateEvaluatorFactory;
import org.apache.hyracks.api.dataflow.value.IRecordDescriptorProvider;
import org.apache.hyracks.api.dataflow.value.ITuplePairComparator;
import org.apache.hyracks.api.dataflow.value.ITuplePairComparatorFactory;
import org.apache.hyracks.api.dataflow.value.RecordDescriptor;
import org.apache.hyracks.api.exceptions.HyracksDataException;
import org.apache.hyracks.api.job.IOperatorDescriptorRegistry;
import org.apache.hyracks.api.job.JobId;
import org.apache.hyracks.dataflow.common.comm.io.FrameTupleAccessor;
import org.apache.hyracks.dataflow.common.comm.util.FrameUtils;
import org.apache.hyracks.dataflow.std.base.AbstractActivityNode;
import org.apache.hyracks.dataflow.std.base.AbstractOperatorDescriptor;
import org.apache.hyracks.dataflow.std.base.AbstractStateObject;
import org.apache.hyracks.dataflow.std.base.AbstractUnaryInputSinkOperatorNodePushable;
import org.apache.hyracks.dataflow.std.base.AbstractUnaryInputUnaryOutputOperatorNodePushable;
public class NestedLoopJoinOperatorDescriptor extends AbstractOperatorDescriptor {
private static final int JOIN_CACHE_ACTIVITY_ID = 0;
private static final int NL_JOIN_ACTIVITY_ID = 1;
private static final long serialVersionUID = 1L;
private final ITuplePairComparatorFactory comparatorFactory;
private final int memSize;
private final IPredicateEvaluatorFactory predEvaluatorFactory;
private final boolean isLeftOuter;
private final INullWriterFactory[] nullWriterFactories1;
public NestedLoopJoinOperatorDescriptor(IOperatorDescriptorRegistry spec,
ITuplePairComparatorFactory comparatorFactory, RecordDescriptor recordDescriptor, int memSize,
boolean isLeftOuter, INullWriterFactory[] nullWriterFactories1) {
this(spec, comparatorFactory, recordDescriptor, memSize, null, isLeftOuter, nullWriterFactories1);
}
public NestedLoopJoinOperatorDescriptor(IOperatorDescriptorRegistry spec,
ITuplePairComparatorFactory comparatorFactory, RecordDescriptor recordDescriptor, int memSize,
IPredicateEvaluatorFactory predEvalFactory, boolean isLeftOuter,
INullWriterFactory[] nullWriterFactories1) {
super(spec, 2, 1);
this.comparatorFactory = comparatorFactory;
this.recordDescriptors[0] = recordDescriptor;
this.memSize = memSize;
this.predEvaluatorFactory = predEvalFactory;
this.isLeftOuter = isLeftOuter;
this.nullWriterFactories1 = nullWriterFactories1;
}
@Override
public void contributeActivities(IActivityGraphBuilder builder) {
ActivityId jcaId = new ActivityId(getOperatorId(), JOIN_CACHE_ACTIVITY_ID);
ActivityId nljAid = new ActivityId(getOperatorId(), NL_JOIN_ACTIVITY_ID);
JoinCacheActivityNode jc = new JoinCacheActivityNode(jcaId, nljAid);
NestedLoopJoinActivityNode nlj = new NestedLoopJoinActivityNode(nljAid);
builder.addActivity(this, jc);
builder.addSourceEdge(1, jc, 0);
builder.addActivity(this, nlj);
builder.addSourceEdge(0, nlj, 0);
builder.addTargetEdge(0, nlj, 0);
builder.addBlockingEdge(jc, nlj);
}
public static class JoinCacheTaskState extends AbstractStateObject {
private NestedLoopJoin joiner;
public JoinCacheTaskState() {
}
private JoinCacheTaskState(JobId jobId, TaskId taskId) {
super(jobId, taskId);
}
@Override
public void toBytes(DataOutput out) throws IOException {
}
@Override
public void fromBytes(DataInput in) throws IOException {
}
}
private class JoinCacheActivityNode extends AbstractActivityNode {
private static final long serialVersionUID = 1L;
private final ActivityId nljAid;
public JoinCacheActivityNode(ActivityId id, ActivityId nljAid) {
super(id);
this.nljAid = nljAid;
}
@Override
public IOperatorNodePushable createPushRuntime(final IHyracksTaskContext ctx,
IRecordDescriptorProvider recordDescProvider, final int partition, int nPartitions) {
final RecordDescriptor rd0 = recordDescProvider.getInputRecordDescriptor(nljAid, 0);
final RecordDescriptor rd1 = recordDescProvider.getInputRecordDescriptor(getActivityId(), 0);
final ITuplePairComparator comparator = comparatorFactory.createTuplePairComparator(ctx);
final IPredicateEvaluator predEvaluator = ((predEvaluatorFactory != null)
? predEvaluatorFactory.createPredicateEvaluator() : null);
final INullWriter[] nullWriters1 = isLeftOuter ? new INullWriter[nullWriterFactories1.length] : null;
if (isLeftOuter) {
for (int i = 0; i < nullWriterFactories1.length; i++) {
nullWriters1[i] = nullWriterFactories1[i].createNullWriter();
}
}
IOperatorNodePushable op = new AbstractUnaryInputSinkOperatorNodePushable() {
private JoinCacheTaskState state;
@Override
public void open() throws HyracksDataException {
state = new JoinCacheTaskState(ctx.getJobletContext().getJobId(),
new TaskId(getActivityId(), partition));
state.joiner = new NestedLoopJoin(ctx, new FrameTupleAccessor(rd0), new FrameTupleAccessor(rd1),
comparator, memSize, predEvaluator, isLeftOuter, nullWriters1);
}
@Override
public void nextFrame(ByteBuffer buffer) throws HyracksDataException {
ByteBuffer copyBuffer = ctx.allocateFrame(buffer.capacity());
FrameUtils.copyAndFlip(buffer, copyBuffer);
state.joiner.cache(copyBuffer);
}
@Override
public void close() throws HyracksDataException {
state.joiner.closeCache();
ctx.setStateObject(state);
}
@Override
public void fail() throws HyracksDataException {
}
};
return op;
}
}
private class NestedLoopJoinActivityNode extends AbstractActivityNode {
private static final long serialVersionUID = 1L;
public NestedLoopJoinActivityNode(ActivityId id) {
super(id);
}
@Override
public IOperatorNodePushable createPushRuntime(final IHyracksTaskContext ctx,
IRecordDescriptorProvider recordDescProvider, final int partition, int nPartitions) {
IOperatorNodePushable op = new AbstractUnaryInputUnaryOutputOperatorNodePushable() {
private JoinCacheTaskState state;
@Override
public void open() throws HyracksDataException {
writer.open();
state = (JoinCacheTaskState) ctx.getStateObject(
new TaskId(new ActivityId(getOperatorId(), JOIN_CACHE_ACTIVITY_ID), partition));
}
@Override
public void nextFrame(ByteBuffer buffer) throws HyracksDataException {
state.joiner.join(buffer, writer);
}
@Override
public void close() throws HyracksDataException {
try {
state.joiner.closeJoin(writer);
} finally {
writer.close();
}
}
@Override
public void fail() throws HyracksDataException {
writer.fail();
}
};
return op;
}
}
}
| |
package edu.tamu.tcat.account.apacheds.internal;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
import org.apache.directory.api.ldap.codec.api.LdapApiServiceFactory;
import org.apache.directory.api.ldap.codec.protocol.mina.LdapProtocolCodecFactory;
import org.apache.directory.api.ldap.model.cursor.EntryCursor;
import org.apache.directory.api.ldap.model.entry.DefaultEntry;
import org.apache.directory.api.ldap.model.entry.Entry;
import org.apache.directory.api.ldap.model.entry.Value;
import org.apache.directory.api.ldap.model.message.AddRequest;
import org.apache.directory.api.ldap.model.message.AddRequestImpl;
import org.apache.directory.api.ldap.model.message.AddResponse;
import org.apache.directory.api.ldap.model.message.ModifyRequest;
import org.apache.directory.api.ldap.model.message.ModifyRequestImpl;
import org.apache.directory.api.ldap.model.message.ModifyResponse;
import org.apache.directory.api.ldap.model.message.ResultCodeEnum;
import org.apache.directory.api.ldap.model.message.SearchScope;
import org.apache.directory.api.ldap.model.name.Dn;
import org.apache.directory.ldap.client.api.LdapConnection;
import org.apache.directory.ldap.client.api.LdapConnectionConfig;
import org.apache.directory.ldap.client.api.LdapNetworkConnection;
import edu.tamu.tcat.account.apacheds.LdapAuthException;
import edu.tamu.tcat.account.apacheds.LdapException;
import edu.tamu.tcat.account.apacheds.LdapHelperMutator;
import edu.tamu.tcat.account.apacheds.LdapHelperReader;
/** Turn this into a declarative service that binds to configuration */
public class LdapHelperAdImpl implements LdapHelperReader, LdapHelperMutator
{
private static final Logger logger = Logger.getLogger(LdapHelperAdImpl.class.getName());
private LdapConnectionConfig config = null;
private String defaultSearchOu;
/**
* must be called after configure and before any queries
*/
public void init()
{
if(config == null)
throw new IllegalStateException("Configure must be called before init");
// as of 1.0.0.RC2 default factory does not properly instantiate due to dependency issues
if (!LdapApiServiceFactory.isInitialized())
try
{
StandaloneLdapApiService svc = new StandaloneLdapApiService();
if (svc.getProtocolCodecFactory() == null)
svc.registerProtocolCodecFactory(new LdapProtocolCodecFactory());
LdapApiServiceFactory.initialize(svc);
LdapApiServiceFactory.getSingleton();
}
catch (Exception e)
{
throw new IllegalStateException("Unable to instantiate Ldap API Service.", e);
}
}
/** must be called before init */
public void configure(String ip, int port, String userDn, String userPassword, boolean useSsl, boolean useTls, String defaultSearchOu)
{
config = new LdapConnectionConfig();
config.setLdapHost(ip);
config.setLdapPort(port);
config.setName(userDn);
config.setCredentials(userPassword);
config.setUseSsl(useSsl);
config.setUseTls(useTls);
this.defaultSearchOu = defaultSearchOu;
}
// this may be replaced with getMatches
protected String findDistinguishingName(String ouSearchPrefix, String otherName) throws LdapException
{
try (LdapConnection connection = new LdapNetworkConnection(config))
{
connection.bind();
try(ClosableCursor c = new ClosableCursor(connection.search(ouSearchPrefix, "(objectclass=*)", SearchScope.SUBTREE, "*")))
{
EntryCursor cursor = c.cursor;
String found = StreamSupport.stream(cursor.spliterator(), false)
.filter(entry -> entry.contains("sAMAccountName", otherName) || entry.contains("userPrincipleName", otherName))
.map(entry -> String.valueOf(entry.get("distinguishedName").get()))
.findAny()
.orElseThrow(() -> new LdapAuthException("No such user " + otherName + " in " + ouSearchPrefix));
return found;
}
finally
{
connection.unBind();
}
}
catch (LdapException e)
{
throw e;
}
catch (Exception e)
{
throw new LdapException("Failed finding distinguished name " + otherName + " in " + ouSearchPrefix, e);
}
}
@Override
public void checkValidUser(String user) throws LdapException
{
checkValidUser(computeDefaultOu(user), user);
}
String computeDefaultOu(String user)
{
if(user == null || user.isEmpty())
return defaultSearchOu;
// , is valid char in dn if preceeded by slash
// TODO clean up with fancy regex
int cnIndx = user.lastIndexOf("CN");
if(cnIndx <0)
return defaultSearchOu;
int commaIndx = user.indexOf(',', user.lastIndexOf("CN"));
while (commaIndx > -1)
{
if(user.charAt(commaIndx -1) == '\\')
commaIndx = commaIndx + 1;
else
{
logger.fine("Searching OU for [" + user + "] is [" + user.substring(commaIndx + 1) + "]");
return user.substring(commaIndx + 1);
}
commaIndx = user.indexOf(',', commaIndx);
}
return defaultSearchOu;
}
@Override
public void checkValidUser(String ouSearchPrefix, String userDistinguishedName) throws LdapException
{
try (LdapConnection connection = new LdapNetworkConnection(config))
{
connection.bind();
try
{
checkValidUser(ouSearchPrefix, userDistinguishedName, connection);
}
finally
{
connection.unBind();
}
}
catch (IOException | org.apache.directory.api.ldap.model.exception.LdapException e)
{
throw new LdapException("Failed validating distinguished name " + userDistinguishedName + " in " + ouSearchPrefix, e);
}
}
void checkValidUser(String ouSearchPrefix, String userDistinguishedName, LdapConnection boundConnection) throws LdapException
{
try//(ClosableCursor c = new ClosableCursor(boundConnection.search(ouSearchPrefix, "(objectclass=*)", SearchScope.SUBTREE, "*")))
{
Entry e = boundConnection.lookup(userDistinguishedName);
if (e == null)
throw new LdapAuthException("No such user [" + userDistinguishedName + "]");
}
catch (LdapException e)
{
throw e;
}
catch (Exception e)
{
throw new LdapException("Failed validating distinguished name " + userDistinguishedName + " in " + ouSearchPrefix, e);
}
}
@Override
public void checkValidPassword(String userDistinguishedName, String password) throws LdapException
{
if(password == null || password.isEmpty())
throw new LdapException("Failed validating password for distinguished name " + userDistinguishedName + ". Password required.");
try (LdapConnection connection = new LdapNetworkConnection(config))
{
checkValidPassword(userDistinguishedName, password, connection);
}
catch (IOException e)
{
throw new LdapException("Failed validating password for distinguished name " + userDistinguishedName, e);
}
}
void checkValidPassword(String userDistinguishedName, String password, LdapConnection unboundConnection) throws LdapException
{
synchronized (unboundConnection)
{
try
{
//bind will fail if the user pwd is not valid OR account is disabled
unboundConnection.bind(userDistinguishedName, password);
unboundConnection.unBind();
}
catch (org.apache.directory.api.ldap.model.exception.LdapException e)
{
throw new LdapAuthException("Failed validating password for distinguished name [" + userDistinguishedName + "] " + e.getMessage());
}
}
}
// other LDAP systems (possible to modify MS to take this attribute
void changePasswordUserPassword(String userDistinguishedName, String password, LdapConnection boundConnection) throws LdapException
{
try
{
modifyAttribute(userDistinguishedName, "userpassword", password, boundConnection);
}
catch (Exception e)
{
throw new LdapAuthException("Failed changing password for distinguished name [" + userDistinguishedName + "] " + e.getMessage(), e);
}
}
@Override
public void changePasswordUserPassword(String userDistinguishedName, String password) throws LdapException
{
try (LdapConnection connection = new LdapNetworkConnection(config))
{
connection.bind();
try
{
changePasswordUserPassword(userDistinguishedName, password, connection);
}
finally
{
connection.unBind();
}
}
catch (IOException | org.apache.directory.api.ldap.model.exception.LdapException e)
{
throw new LdapException("Failed distinguished name " + userDistinguishedName + " change password.", e);
}
}
@Override
public void changePasswordUnicodePassword(String userDistinguishedName, String password) throws LdapException
{
try (LdapConnection connection = new LdapNetworkConnection(config))
{
connection.bind();
try
{
changePasswordUincodePassword(userDistinguishedName, password, connection);
}
finally
{
connection.unBind();
}
}
catch (IOException | org.apache.directory.api.ldap.model.exception.LdapException e)
{
throw new LdapException("Failed distinguished name " + userDistinguishedName + " change password.", e);
}
}
// AD direct
void changePasswordUincodePassword(String userDistinguishedName, String password, LdapConnection boundConnection) throws LdapException
{
try
{
byte[] pwdArray = encodeUnicodePassword(password);
modifyAttribute(userDistinguishedName, "UnicodePwd", pwdArray, boundConnection);
}
catch (Exception e)
{
throw new LdapAuthException("Failed changing password for distinguished name [" + userDistinguishedName + "] " + e.getMessage());
}
}
@Override
public List<String> getMemberNamesOfGroup(String userDistinguishedName) throws LdapException
{
return getMemberNamesOfGroup(computeDefaultOu(userDistinguishedName), userDistinguishedName);
}
@Override
public List<String> getMemberNamesOfGroup(String ouSearchPrefix, String groupDn) throws LdapException
{
List<String> members = new CopyOnWriteArrayList<>();
try (LdapConnection connection = new LdapNetworkConnection(config))
{
connection.bind();
try
{
getMemberNamesOfGroupInternal(members, groupDn, connection);
return new ArrayList<>(members);
}
finally
{
connection.unBind();
}
}
catch (IOException | org.apache.directory.api.ldap.model.exception.LdapException e)
{
throw new LdapException("Failed member list lookup for user " + groupDn + " in " + ouSearchPrefix, e);
}
}
void getMemberNamesOfGroupInternal(List<String> members, String groupDn, LdapConnection boundConnection) throws LdapException
{
// in ou search prefix, list all distinguished names that have the memberof attribute = to the parameter
getAttributes(computeDefaultOu(groupDn), groupDn, Collections.singleton("member"), boundConnection).get("member").forEach(member -> {
if (members.contains(member))
return;
members.add(member.toString());
getMemberNamesOfGroupInternal(members, member.toString(), boundConnection);
});
}
@Override
public List<String> getGroupNames(String userDistinguishedName) throws LdapException
{
return getGroupNames(computeDefaultOu(userDistinguishedName), userDistinguishedName);
}
void getGroupsInternal(String userDistinguishedName, Set<String> groups, LdapConnection boundConnection) throws LdapException
{
List<String> newGroups = new ArrayList<>();
// remove CN from string to get top level OU
String ouSearchPrefix = computeDefaultOu(userDistinguishedName);
// LdapConnection connection = boundConnection;
try//(ClosableCursor c = new ClosableCursor(connection.search(ouSearchPrefix, "(objectclass=*)", SearchScope.SUBTREE, "*")))
{
boundConnection.lookup(userDistinguishedName).forEach(attribute -> {
//extract all the groups the user is a memberof
if (attribute.getId().equalsIgnoreCase("memberof"))
newGroups.add(String.valueOf(attribute.get()));
// System.out.println('['+attribute.getId() +']'+ attribute.get());
});
}
catch(NullPointerException npe)
{
throw new LdapAuthException("No such user [" + userDistinguishedName + "]");
}
catch (LdapAuthException e)
{
throw new LdapAuthException("Failed group list lookup for user " + userDistinguishedName + " in " + ouSearchPrefix, e);
}
catch (LdapException e)
{
throw e;
}
catch (Exception e)
{
throw new LdapException("Failed group list lookup for user " + userDistinguishedName + " in " + ouSearchPrefix, e);
}
newGroups.removeAll(groups);
groups.addAll(newGroups);
for (String g : newGroups)
{
getGroupsInternal(g, groups, boundConnection);
}
}
@Override
public List<String> getGroupNames(String ouSearchPrefix, String userDistinguishedName) throws LdapException
{
try (LdapConnection connection = new LdapNetworkConnection(config))
{
connection.bind();
List<String> groups = getAttributes(computeDefaultOu(userDistinguishedName), userDistinguishedName, Collections.singleton("memberof"), connection).get("memberof").stream()
.map(String::valueOf)
.collect(Collectors.toList());
Set<String> recursiveGroups = new HashSet<>(groups);
try
{
groups.forEach(g -> getGroupsInternal(g, recursiveGroups, connection));
return new ArrayList<>(recursiveGroups);
}
finally
{
connection.unBind();
}
}
catch (IOException | org.apache.directory.api.ldap.model.exception.LdapException e)
{
throw new LdapException("Failed group list lookup for user " + userDistinguishedName + " in " + ouSearchPrefix, e);
}
}
@Override
public List<String> getGroupNamesAndValidate(String userDistinguishedName, String password) throws LdapException
{
return getGroupNamesAndValidate(computeDefaultOu(userDistinguishedName), userDistinguishedName, password);
}
@Override
public List<String> getGroupNamesAndValidate(String ouSearchPrefix, String userDistinguishedName, String password) throws LdapException
{
try (LdapConnection connection = new LdapNetworkConnection(config))
{
List<String> groups = new ArrayList<>();
try
{
//bind will fail if the user pwd is not valid
connection.bind(userDistinguishedName, password);
try//(ClosableCursor c = new ClosableCursor(connection.search(ouSearchPrefix, "(objectclass=*)", SearchScope.SUBTREE, "*")))
{
connection.lookup(userDistinguishedName).forEach(attribute -> {
//extract all the groups the user is a memberof
if (attribute.getId().equalsIgnoreCase("memberof"))
groups.add(String.valueOf(attribute.get()));
// System.out.println('['+attribute.getId() +']'+ attribute.get());
});
}
catch (org.apache.directory.api.ldap.model.exception.LdapException e)
{
throw new LdapException("Failed group list lookup for user " + userDistinguishedName + " in " + ouSearchPrefix, e);
}
catch(NullPointerException npe)
{
throw new LdapAuthException("No such user [" + userDistinguishedName + "]");
}
finally
{
connection.unBind();
}
return groups;
}
catch (org.apache.directory.api.ldap.model.exception.LdapException e)
{
throw new LdapAuthException("Failed validating password for distinguished name " + userDistinguishedName);
}
}
catch (LdapException e)
{
throw e;
}
catch (Exception e)
{
throw new LdapException("Failed group list lookup for user " + userDistinguishedName + " in " + ouSearchPrefix, e);
}
}
@Override
public Map<String, Collection<Object>> getAttributes(String userDistinguishedName, Collection<String> attributeId) throws LdapException
{
return getAttributes(computeDefaultOu(userDistinguishedName), userDistinguishedName, attributeId);
}
@Override
public Map<String, Collection<Object>> getAttributes(String ouSearchPrefix, String userDistinguishedName, Collection<String> attributeId) throws LdapException
{
try (LdapConnection connection = new LdapNetworkConnection(config))
{
try
{
connection.bind();
return getAttributes(ouSearchPrefix, userDistinguishedName, attributeId, connection);
}
finally
{
connection.unBind();
}
}
catch (IOException | org.apache.directory.api.ldap.model.exception.LdapException e)
{
throw new LdapException("Failed " + attributeId + " lookup for user " + userDistinguishedName + " in " + ouSearchPrefix, e);
}
}
Map<String, Collection<Object>> getAttributes(String ouSearchPrefix, String userDistinguishedName, Collection<String> attributeIds, LdapConnection boundConnection) throws LdapException
{
Map<String, Collection<Object>> values = new HashMap<>();
// LdapConnection connection = boundConnection;
try//(ClosableCursor c = new ClosableCursor(connection.search(ouSearchPrefix, "(objectclass=*)", SearchScope.SUBTREE, "*")))
{
boundConnection.lookup(userDistinguishedName).getAttributes().forEach(attribute -> {
//extract all the groups the user is a memberof
attributeIds.stream().forEach(attributeId -> {
values.putIfAbsent(attributeId, new ArrayList<>());
if (attribute.getId().equalsIgnoreCase(attributeId))
{
Collection<Object> valueList = values.get(attributeId);
attribute.forEach(v -> {
if (v instanceof Value)
valueList.add(((Value)v).getValue());
else
valueList.add(v);
});
}
}
);
});
}
catch(NullPointerException npe)
{
throw new LdapAuthException("No such user [" + userDistinguishedName + "]");
}
catch (LdapAuthException e)
{
throw new LdapAuthException("Failed attribute lookup for user " + userDistinguishedName + " in " + ouSearchPrefix, e);
}
catch (LdapException e)
{
throw e;
}
catch (Exception e)
{
throw new LdapException("Failed attribute lookup for user " + userDistinguishedName + " in " + ouSearchPrefix, e);
}
return values;
}
@Override
public void addAttribute(String userDistinguishedName, String attributeId, Object value) throws LdapException
{
try (LdapConnection connection = new LdapNetworkConnection(config))
{
connection.bind();
try
{
addAttribute(userDistinguishedName, attributeId, value, connection);
}
finally
{
connection.unBind();
}
}
catch (LdapException e)
{
throw e;
}
catch (Exception e)
{
throw new LdapException("Failed " + attributeId + " add for user " + userDistinguishedName, e);
}
}
void addAttribute(String userDistinguishedName, String attributeId, Object value, LdapConnection connection) throws LdapException
{
try
{
Entry entry = connection.lookup(userDistinguishedName);
if (entry == null)
throw new LdapAuthException("No such user [" + userDistinguishedName + "]");
ModifyRequest req = new ModifyRequestImpl();
if (value == null)
throw new IllegalArgumentException("Value cannot be null.");
else if (value.getClass().equals(byte[].class))
req = req.add(attributeId, (byte[])value);
else if (value instanceof Collection)
{
value =((Collection<?>)value).stream().map(v-> String.valueOf(v)).collect(Collectors.toList()).toArray(new String[0]);
req = req.add(attributeId, (String[])value);
}
else if (value instanceof String[])
{
req = req.add(attributeId, (String[])value);
}
else
req = req.add(attributeId, String.valueOf(value));
Dn dn = entry.getDn();
req = req.setName(dn);
ModifyResponse resp = connection.modify(req);
if (Objects.equals(ResultCodeEnum.SUCCESS, resp.getLdapResult().getResultCode()))
return;
throw new LdapException("Failed to add attribute ["+attributeId+"] to user ["+userDistinguishedName+"] " + resp.getLdapResult().getResultCode() + " " + resp.getLdapResult().getDiagnosticMessage());
}
catch (LdapException | org.apache.directory.api.ldap.model.exception.LdapException e)
{
throw new LdapException("Failed " + attributeId + " add for user " + userDistinguishedName, e);
}
}
public void modifyAttribute(String userDistinguishedName, String attributeId, Object value) throws LdapException
{
try (LdapConnection connection = new LdapNetworkConnection(config))
{
connection.bind();
try
{
modifyAttribute(userDistinguishedName, attributeId, value, connection);
}
finally
{
connection.unBind();
}
}
catch (LdapException e)
{
throw e;
}
catch (Exception e)
{
throw new LdapException("Failed " + attributeId + " add for user " + userDistinguishedName, e);
}
}
void modifyAttribute(String userDistinguishedName, String attributeId, Object value, LdapConnection connection) throws LdapException
{
if (value == null)
throw new IllegalArgumentException("Value cannot be null. Use removeAttribute instead");
try
{
Entry entry = connection.lookup(userDistinguishedName);
if (entry == null)
throw new LdapAuthException("No such user [" + userDistinguishedName + "]");
ModifyRequest req = new ModifyRequestImpl();
if (value.getClass().equals(byte[].class))
req = req.replace(attributeId, (byte[])value);
else if (value instanceof Collection)
{
value =((Collection<?>)value).stream().map(v-> String.valueOf(v)).collect(Collectors.toList()).toArray(new String[0]);
req = req.replace(attributeId, (String[])value);
}
else if (value instanceof String[])
{
req = req.replace(attributeId, (String[])value);
}
else
req = req.replace(attributeId, String.valueOf(value));
Dn dn = entry.getDn();
req = req.setName(dn);
ModifyResponse resp = connection.modify(req);
if (Objects.equals(ResultCodeEnum.SUCCESS, resp.getLdapResult().getResultCode()))
return;
throw new LdapException("Failed to modify attribute ["+attributeId+"] to user ["+userDistinguishedName+"] " + resp.getLdapResult().getResultCode() + " " + resp.getLdapResult().getDiagnosticMessage());
}
catch (LdapException | org.apache.directory.api.ldap.model.exception.LdapException e)
{
throw new LdapException("Failed " + attributeId + " modify for user " + userDistinguishedName, e);
}
}
@Override
public void removeAttribute(String userDistinguishedName, String attributeId, Object value) throws LdapException
{
try (LdapConnection connection = new LdapNetworkConnection(config))
{
connection.bind();
try
{
removeAttribute(userDistinguishedName, attributeId, value, connection);
}
finally
{
connection.unBind();
}
}
catch (LdapException e)
{
throw e;
}
catch (Exception e)
{
throw new LdapException("Failed " + attributeId + " remove for user " + userDistinguishedName, e);
}
}
void removeAttribute(String userDistinguishedName, String attributeId, Object value, LdapConnection connection) throws LdapException
{
try
{
Entry entry = connection.lookup(userDistinguishedName);
if (entry == null)
throw new LdapAuthException("No such user [" + userDistinguishedName + "]");
ModifyRequest req = new ModifyRequestImpl();
if (value.getClass().equals(byte[].class))
req = req.remove(attributeId, (byte[])value);
else
req = req.remove(attributeId, String.valueOf(value));
Dn dn = entry.getDn();
req.setName(dn);
ModifyResponse resp = connection.modify(req);
if (Objects.equals(ResultCodeEnum.SUCCESS, resp.getLdapResult().getResultCode()))
return;
throw new LdapException("Failed to remove attribute ["+attributeId+"] from user ["+userDistinguishedName+"] " + resp.getLdapResult().getResultCode() + " " + resp.getLdapResult().getDiagnosticMessage());
}
catch (LdapException | org.apache.directory.api.ldap.model.exception.LdapException e)
{
throw new LdapException("Failed " + attributeId + " remove for user " + userDistinguishedName, e);
}
}
@Override
public void removeAttribute(String userDistinguishedName, String attributeId) throws LdapException
{
try (LdapConnection connection = new LdapNetworkConnection(config))
{
connection.bind();
try
{
removeAttribute(userDistinguishedName, attributeId, connection);
}
finally
{
connection.unBind();
}
}
catch (LdapException e)
{
throw e;
}
catch (Exception e)
{
throw new LdapException("Failed " + attributeId + " remove for user " + userDistinguishedName, e);
}
}
void removeAttribute(String userDistinguishedName, String attributeId, LdapConnection connection) throws LdapException
{
try
{
Entry entry = connection.lookup(userDistinguishedName);
if (entry == null)
throw new LdapAuthException("No such user [" + userDistinguishedName + "]");
ModifyRequest req = new ModifyRequestImpl();
req = req.remove(attributeId);
Dn dn = entry.getDn();
req.setName(dn);
ModifyResponse resp = connection.modify(req);
if (Objects.equals(ResultCodeEnum.SUCCESS, resp.getLdapResult().getResultCode()))
return;
throw new LdapException("Failed to remove attribute ["+attributeId+"] from user ["+userDistinguishedName+"] " + resp.getLdapResult().getResultCode() + " " + resp.getLdapResult().getDiagnosticMessage());
}
catch (LdapException | org.apache.directory.api.ldap.model.exception.LdapException e)
{
throw new LdapException("Failed " + attributeId + " remove for user " + userDistinguishedName, e);
}
}
@Override
public List<String> getMatches(String ouSearchPrefix, String attributeId, String value, boolean caseSensitive) throws LdapException
{
try (LdapConnection connection = new LdapNetworkConnection(config))
{
connection.bind();
try
{
return getMatchesInternal(ouSearchPrefix, attributeId, value, caseSensitive, connection);
}
finally
{
connection.unBind();
}
}
catch (IOException | org.apache.directory.api.ldap.model.exception.LdapException e)
{
throw new LdapException("Failed " + attributeId + " lookup for user " + value + " in " + ouSearchPrefix, e);
}
}
List<String> getMatchesInternal(String ouSearchPrefix, String attributeId, String value, boolean caseSensitive, LdapConnection connection) throws LdapException
{
if(ouSearchPrefix ==null || ouSearchPrefix.isEmpty())
ouSearchPrefix = defaultSearchOu;
try(ClosableCursor c = new ClosableCursor(connection.search(ouSearchPrefix, "(objectclass=*)", SearchScope.SUBTREE, "*")))
{
EntryCursor cursor = c.cursor;
List<String> matches = new ArrayList<>();
cursor.forEach(entry -> {
entry.getAttributes().forEach(attribute -> {
//extract all the groups the user is a memberof
if (attribute.getId().equalsIgnoreCase(attributeId))
attribute.forEach(v -> {
Object val;
if (v instanceof Value)
val = (((Value)v).getValue());
else
val = v;
if(!caseSensitive && val instanceof String)
{
if(((String)val).equalsIgnoreCase(value))
matches .add(String.valueOf(entry.get("distinguishedName").get()));
}else
{
if(Objects.equals(value, val))
matches .add(String.valueOf(entry.get("distinguishedName").get()));
}
});
});
});
return matches;
}
catch (LdapException e)
{
throw e;
}
catch (Exception e)
{
throw new LdapException("Failed " + attributeId + " lookup for value " + value + " in " + ouSearchPrefix, e);
}
}
@Override
public List<String> getMatches(String ouSearchPrefix, String attributeId, byte[] value) throws LdapException
{
try (LdapNetworkConnection connection = new LdapNetworkConnection(config))
{
connection.bind();
try
{
return getMatchesInternal(ouSearchPrefix, attributeId, value, connection);
}
finally
{
connection.unBind();
}
}
catch (IOException | org.apache.directory.api.ldap.model.exception.LdapException e)
{
throw new LdapException("Failed " + attributeId + " lookup for user " + value + " in " + ouSearchPrefix, e);
}
}
List<String> getMatchesInternal (String ouSearchPrefix, String attributeId, byte[] value, LdapConnection boundConnection) throws LdapException
{
if(ouSearchPrefix ==null || ouSearchPrefix.isEmpty())
ouSearchPrefix = defaultSearchOu;
try(ClosableCursor c = new ClosableCursor(boundConnection.search(ouSearchPrefix, "(objectclass=*)", SearchScope.SUBTREE, "*")))
{
EntryCursor cursor = c.cursor;
List<String> matches = new ArrayList<>();
cursor.forEach(entry -> {
if (entry.contains(attributeId, value))
{
matches.add(String.valueOf(entry.get("distinguishedName").get()));
}
});
return matches;
}catch(LdapException e)
{
throw e;
}
catch (Exception e)
{
throw new LdapException("Failed " + attributeId + " lookup for value " + value + " in " + ouSearchPrefix, e);
}
}
//
// private Entry getEntryFor(String distinguishedName, EntryCursor cursor) throws LdapException
// {
// return StreamSupport.stream(cursor.spliterator(), false)
// .filter(entry -> entry.contains("distinguishedName", distinguishedName))
// .findAny()
// .orElseThrow(() -> new LdapAuthException(distinguishedName + "not found."));
// }
@Override
public boolean isMemberOf(String groupDn, String userDn) throws LdapException
{
try (LdapConnection connection = new LdapNetworkConnection(config))
{
try
{
connection.bind();
return isMemberOf(groupDn, userDn, connection);
}
finally
{
connection.unBind();
}
}
catch (IOException | org.apache.directory.api.ldap.model.exception.LdapException e)
{
throw new LdapException("Failed isMemberOf [" + userDn + "] of group [" + groupDn + "]", e);
}
}
boolean isMemberOf(String groupDn, String userDn, LdapConnection boundConnection) throws LdapException
{
try
{
boolean found = getAttributes(computeDefaultOu(groupDn), groupDn, Collections.singleton("member"), boundConnection).get("member").stream()
.anyMatch(member -> member.toString().equals(userDn) || isMemberOf(member.toString(), userDn));
return found;
}
catch (LdapAuthException ae)
{
return false;
}
}
public void createUser(String cn, String ou, String unicodePassword, String userPassword, List<String> objectClasses,
String instanceType, String objectCategory, Map<String, String> attributes, LdapConnection boundConnection) throws LdapException
{
String dn = "CN=" + cn + ",OU=" + ou;
try {
Entry entry = new DefaultEntry();
entry.add("cn", cn);
for (String c: objectClasses)
entry.add("objectClass", c);
// entry.add("objectClass", "organizationalPerson");
// entry.add("objectClass", "person");
// entry.add("objectClass", "top");
// entry.add("objectClass", "user");
entry.add("instanceType", instanceType);
// entry.add("instanceType", "4");
entry.add("objectCategory",objectCategory);
// entry.add("objectCategory",
// "CN=Person,CN=Schema,CN=Configuration,CN={DC42C6A0-6A5A-4683-9B9C-E7B7C93E30E9}");
for(java.util.Map.Entry<String,String> e : attributes.entrySet())
entry.add(e.getKey(), e.getValue());
// entry.add("distinguishedName", dn);
// entry.add("msDS-UserAccountDisabled", "FALSE");
// entry.add("msDS-UserDontExpirePassword", "TRUE");
// entry.add("name", displayName);
// entry.add("sAMAccountName", userName);
entry.setDn(new Dn(dn));
// entry.setDn(dn);
if(unicodePassword != null && !unicodePassword.isEmpty())
{
byte[] pwdArray = encodeUnicodePassword(unicodePassword);
entry.add("UnicodePwd", pwdArray);
}
if(userPassword != null && !userPassword.isEmpty())
{
entry.add("userpassword", userPassword);
}
AddRequest addRequest = new AddRequestImpl();
addRequest.setEntry(entry);
AddResponse response = boundConnection.add(addRequest);
if (null == response)
throw new LdapException("Null response for ldap entry add of [" + dn + "]");
if (!ResultCodeEnum.SUCCESS.equals(response.getLdapResult().getResultCode()))
throw new LdapException(
"Response " + response.getLdapResult().getResultCode() + " for ldap entry add of [" + dn + "]\n"+response.getLdapResult().getDiagnosticMessage());
} catch (org.apache.directory.api.ldap.model.exception.LdapException e) {
throw new LdapException("Failed add entry [" + dn + "]", e);
}
}
private byte[] encodeUnicodePassword(String password) {
String quotedPassword = "\"" + password + "\"";
char unicodePwd[] = quotedPassword.toCharArray();
byte pwdArray[] = new byte[unicodePwd.length * 2];
for (int i = 0; i < unicodePwd.length; i++)
{
pwdArray[i * 2 + 1] = (byte)(unicodePwd[i] >>> 8);
pwdArray[i * 2 + 0] = (byte)(unicodePwd[i] & 0xff);
}
return pwdArray;
}
public void createUser(String cn, String ou, String unicodePassword, String userPassword, List<String> objectClasses,
String instanceType, String objectCategory, Map<String, String> attributes) throws LdapException
{
try (LdapConnection connection = new LdapNetworkConnection(config))
{
try
{
connection.bind();
createUser(cn, ou, unicodePassword, userPassword, objectClasses, instanceType, objectCategory, attributes, connection);
}
finally
{
connection.unBind();
}
}
catch (IOException | org.apache.directory.api.ldap.model.exception.LdapException e)
{
throw new LdapException("Failed add entry [CN=" + cn + ",OU=" + ou + "]", e);
}
}
public void addUserToGroup(String userDn, String groupDn, LdapConnection boundConnection) throws LdapException {
try {
addAttribute(groupDn, "member", userDn, boundConnection);
//addAttribute(userDn, "memberOf", groupDn, boundConnection);
} catch (LdapException e) {
throw new LdapException("Failed add user [" + userDn + "] to group [" + groupDn + "]", e);
}
}
public void removeUserFromGroup(String userDn, String groupDn, LdapConnection boundConnection)
throws LdapException {
try {
removeAttribute(groupDn, "member", userDn, boundConnection);
//removeAttribute(userDn, "memberOf", groupDn, boundConnection);
} catch (LdapException e) {
throw new LdapException("Failed remove user [" + userDn + "] from group [" + groupDn + "]", e);
}
}
@Override
public void addUserToGroup(String userDn, String groupDn) throws LdapException {
try (LdapConnection connection = new LdapNetworkConnection(config)) {
try {
connection.bind();
addUserToGroup(userDn, groupDn, connection);
} finally {
connection.unBind();
}
} catch (IOException | org.apache.directory.api.ldap.model.exception.LdapException e) {
throw new LdapException("Failed add user [" + userDn + "] to group [" + groupDn + "]", e);
}
}
@Override
public void removeUserFromGroup(String userDn, String groupDn) throws LdapException {
try (LdapConnection connection = new LdapNetworkConnection(config)) {
try {
connection.bind();
removeUserFromGroup(userDn, groupDn, connection);
} finally {
connection.unBind();
}
} catch (IOException | org.apache.directory.api.ldap.model.exception.LdapException e) {
throw new LdapException("Failed remove user [" + userDn + "] from group [" + groupDn + "]", e);
}
}
static class ClosableCursor implements AutoCloseable
{
final EntryCursor cursor;
public ClosableCursor(EntryCursor cursor)
{
this.cursor = cursor;
}
@Override
public void close() throws Exception
{
cursor.close();
}
}
}
| |
/*
* Copyright (C) 2015 Google 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 com.google.cloud.dataflow.examples.complete;
import com.google.api.services.bigquery.model.TableFieldSchema;
import com.google.api.services.bigquery.model.TableReference;
import com.google.api.services.bigquery.model.TableRow;
import com.google.api.services.bigquery.model.TableSchema;
import com.google.cloud.dataflow.examples.common.DataflowExampleOptions;
import com.google.cloud.dataflow.examples.common.DataflowExampleUtils;
import com.google.cloud.dataflow.examples.common.ExampleBigQueryTableOptions;
import com.google.cloud.dataflow.examples.common.ExamplePubsubTopicOptions;
import com.google.cloud.dataflow.sdk.Pipeline;
import com.google.cloud.dataflow.sdk.PipelineResult;
import com.google.cloud.dataflow.sdk.coders.AvroCoder;
import com.google.cloud.dataflow.sdk.coders.DefaultCoder;
import com.google.cloud.dataflow.sdk.io.BigQueryIO;
import com.google.cloud.dataflow.sdk.io.PubsubIO;
import com.google.cloud.dataflow.sdk.io.TextIO;
import com.google.cloud.dataflow.sdk.options.Default;
import com.google.cloud.dataflow.sdk.options.Description;
import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory;
import com.google.cloud.dataflow.sdk.runners.DataflowPipelineRunner;
import com.google.cloud.dataflow.sdk.transforms.DoFn;
import com.google.cloud.dataflow.sdk.transforms.GroupByKey;
import com.google.cloud.dataflow.sdk.transforms.PTransform;
import com.google.cloud.dataflow.sdk.transforms.ParDo;
import com.google.cloud.dataflow.sdk.transforms.windowing.SlidingWindows;
import com.google.cloud.dataflow.sdk.transforms.windowing.Window;
import com.google.cloud.dataflow.sdk.values.KV;
import com.google.cloud.dataflow.sdk.values.PCollection;
import com.google.common.collect.Lists;
import org.apache.avro.reflect.Nullable;
import org.joda.time.Duration;
import org.joda.time.Instant;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
/**
* A Dataflow Example that runs in both batch and streaming modes with traffic sensor data.
* You can configure the running mode by setting {@literal --streaming} to true or false.
*
* <p>Concepts: The batch and streaming runners, GroupByKey, sliding windows, and
* Google Cloud Pub/Sub topic injection.
*
* <p>This example analyzes traffic sensor data using SlidingWindows. For each window,
* it calculates the average speed over the window for some small set of predefined 'routes',
* and looks for 'slowdowns' in those routes. It writes its results to a BigQuery table.
*
* <p>In batch mode, the pipeline reads traffic sensor data from {@literal --inputFile}.
*
* <p>In streaming mode, the pipeline reads the data from a Pub/Sub topic.
* By default, the example will run a separate pipeline to inject the data from the default
* {@literal --inputFile} to the Pub/Sub {@literal --pubsubTopic}. It will make it available for
* the streaming pipeline to process. You may override the default {@literal --inputFile} with the
* file of your choosing. You may also set {@literal --inputFile} to an empty string, which will
* disable the automatic Pub/Sub injection, and allow you to use separate tool to control the input
* to this example. An example code, which publishes traffic sensor data to a Pub/Sub topic,
* is provided in
* <a href="https://github.com/GoogleCloudPlatform/cloud-pubsub-samples-python/tree/master/gce-cmdline-publisher"></a>.
*
* <p>The example is configured to use the default Pub/Sub topic and the default BigQuery table
* from the example common package (there are no defaults for a general Dataflow pipeline).
* You can override them by using the {@literal --pubsubTopic}, {@literal --bigQueryDataset}, and
* {@literal --bigQueryTable} options. If the Pub/Sub topic or the BigQuery table do not exist,
* the example will try to create them.
*
* <p>The example will try to cancel the pipelines on the signal to terminate the process (CTRL-C)
* and then exits.
*/
public class TrafficRoutes {
// Instantiate some small predefined San Diego routes to analyze
static Map<String, String> sdStations = buildStationInfo();
static final int WINDOW_DURATION = 3; // Default sliding window duration in minutes
static final int WINDOW_SLIDE_EVERY = 1; // Default window 'slide every' setting in minutes
/**
* This class holds information about a station reading's average speed.
*/
@DefaultCoder(AvroCoder.class)
static class StationSpeed implements Comparable<StationSpeed> {
@Nullable String stationId;
@Nullable Double avgSpeed;
@Nullable Long timestamp;
public StationSpeed() {}
public StationSpeed(String stationId, Double avgSpeed, Long timestamp) {
this.stationId = stationId;
this.avgSpeed = avgSpeed;
this.timestamp = timestamp;
}
public String getStationId() {
return this.stationId;
}
public Double getAvgSpeed() {
return this.avgSpeed;
}
@Override
public int compareTo(StationSpeed other) {
return Long.compare(this.timestamp, other.timestamp);
}
}
/**
* This class holds information about a route's speed/slowdown.
*/
@DefaultCoder(AvroCoder.class)
static class RouteInfo {
@Nullable String route;
@Nullable Double avgSpeed;
@Nullable Boolean slowdownEvent;
public RouteInfo() {}
public RouteInfo(String route, Double avgSpeed, Boolean slowdownEvent) {
this.route = route;
this.avgSpeed = avgSpeed;
this.slowdownEvent = slowdownEvent;
}
public String getRoute() {
return this.route;
}
public Double getAvgSpeed() {
return this.avgSpeed;
}
public Boolean getSlowdownEvent() {
return this.slowdownEvent;
}
}
/**
* Filter out readings for the stations along predefined 'routes', and output
* (station, speed info) keyed on route.
*/
static class ExtractStationSpeedFn extends DoFn<String, KV<String, StationSpeed>> {
private static final DateTimeFormatter dateTimeFormat =
DateTimeFormat.forPattern("MM/dd/yyyy HH:mm:ss");
private final boolean outputTimestamp;
public ExtractStationSpeedFn(boolean outputTimestamp) {
this.outputTimestamp = outputTimestamp;
}
@Override
public void processElement(ProcessContext c) {
String[] items = c.element().split(",");
String stationType = tryParseStationType(items);
// For this analysis, use only 'main line' station types
if (stationType != null && stationType.equals("ML")) {
Double avgSpeed = tryParseAvgSpeed(items);
String stationId = tryParseStationId(items);
// For this simple example, filter out everything but some hardwired routes.
if (avgSpeed != null && stationId != null && sdStations.containsKey(stationId)) {
Instant timestamp;
if (outputTimestamp) {
timestamp = new Instant(dateTimeFormat.parseMillis(tryParseTimestamp(items)));
} else {
timestamp = c.timestamp();
}
StationSpeed stationSpeed = new StationSpeed(stationId, avgSpeed, timestamp.getMillis());
// The tuple key is the 'route' name stored in the 'sdStations' hash.
KV<String, StationSpeed> outputValue = KV.of(sdStations.get(stationId), stationSpeed);
if (outputTimestamp) {
c.outputWithTimestamp(outputValue, timestamp);
} else {
c.output(outputValue);
}
}
}
}
}
/**
* For a given route, track average speed for the window. Calculate whether
* traffic is currently slowing down, via a predefined threshold. If a supermajority of
* speeds in this sliding window are less than the previous reading we call this a 'slowdown'.
* Note: these calculations are for example purposes only, and are unrealistic and oversimplified.
*/
static class GatherStats
extends DoFn<KV<String, Iterable<StationSpeed>>, KV<String, RouteInfo>> {
@Override
public void processElement(ProcessContext c) throws IOException {
String route = c.element().getKey();
double speedSum = 0.0;
int speedCount = 0;
int speedups = 0;
int slowdowns = 0;
List<StationSpeed> infoList = Lists.newArrayList(c.element().getValue());
// StationSpeeds sort by embedded timestamp.
Collections.sort(infoList);
Map<String, Double> prevSpeeds = new HashMap<>();
// For all stations in the route, sum (non-null) speeds. Keep a count of the non-null speeds.
for (StationSpeed item : infoList) {
Double speed = item.getAvgSpeed();
if (speed != null) {
speedSum += speed;
speedCount++;
Double lastSpeed = prevSpeeds.get(item.getStationId());
if (lastSpeed != null) {
if (lastSpeed < speed) {
speedups += 1;
} else {
slowdowns += 1;
}
}
prevSpeeds.put(item.getStationId(), speed);
}
}
if (speedCount == 0) {
// No average to compute.
return;
}
double speedAvg = speedSum / speedCount;
boolean slowdownEvent = slowdowns >= 2 * speedups;
RouteInfo routeInfo = new RouteInfo(route, speedAvg, slowdownEvent);
c.output(KV.of(route, routeInfo));
}
}
/**
* Format the results of the slowdown calculations to a TableRow, to save to BigQuery.
*/
static class FormatStatsFn extends DoFn<KV<String, RouteInfo>, TableRow> {
@Override
public void processElement(ProcessContext c) {
RouteInfo routeInfo = c.element().getValue();
TableRow row = new TableRow()
.set("avg_speed", routeInfo.getAvgSpeed())
.set("slowdown_event", routeInfo.getSlowdownEvent())
.set("route", c.element().getKey())
.set("window_timestamp", c.timestamp().toString());
c.output(row);
}
/**
* Defines the BigQuery schema used for the output.
*/
static TableSchema getSchema() {
List<TableFieldSchema> fields = new ArrayList<>();
fields.add(new TableFieldSchema().setName("route").setType("STRING"));
fields.add(new TableFieldSchema().setName("avg_speed").setType("FLOAT"));
fields.add(new TableFieldSchema().setName("slowdown_event").setType("BOOLEAN"));
fields.add(new TableFieldSchema().setName("window_timestamp").setType("TIMESTAMP"));
TableSchema schema = new TableSchema().setFields(fields);
return schema;
}
}
/**
* This PTransform extracts speed info from traffic station readings.
* It groups the readings by 'route' and analyzes traffic slowdown for that route.
* Lastly, it formats the results for BigQuery.
*/
static class TrackSpeed extends
PTransform<PCollection<KV<String, StationSpeed>>, PCollection<TableRow>> {
@Override
public PCollection<TableRow> apply(PCollection<KV<String, StationSpeed>> stationSpeed) {
// Apply a GroupByKey transform to collect a list of all station
// readings for a given route.
PCollection<KV<String, Iterable<StationSpeed>>> timeGroup = stationSpeed.apply(
GroupByKey.<String, StationSpeed>create());
// Analyze 'slowdown' over the route readings.
PCollection<KV<String, RouteInfo>> stats = timeGroup.apply(ParDo.of(new GatherStats()));
// Format the results for writing to BigQuery
PCollection<TableRow> results = stats.apply(
ParDo.of(new FormatStatsFn()));
return results;
}
}
/**
* Options supported by {@link TrafficRoutes}.
*
* <p>Inherits standard configuration options.
*/
private interface TrafficRoutesOptions
extends DataflowExampleOptions, ExamplePubsubTopicOptions, ExampleBigQueryTableOptions {
@Description("Input file to inject to Pub/Sub topic")
@Default.String("gs://dataflow-samples/traffic_sensor/"
+ "Freeways-5Minaa2010-01-01_to_2010-02-15_test2.csv")
String getInputFile();
void setInputFile(String value);
@Description("Numeric value of sliding window duration, in minutes")
@Default.Integer(WINDOW_DURATION)
Integer getWindowDuration();
void setWindowDuration(Integer value);
@Description("Numeric value of window 'slide every' setting, in minutes")
@Default.Integer(WINDOW_SLIDE_EVERY)
Integer getWindowSlideEvery();
void setWindowSlideEvery(Integer value);
}
/**
* Sets up and starts streaming pipeline.
*
* @throws IOException if there is a problem setting up resources
*/
public static void main(String[] args) throws IOException {
TrafficRoutesOptions options = PipelineOptionsFactory.fromArgs(args)
.withValidation()
.as(TrafficRoutesOptions.class);
if (options.isStreaming()) {
// In order to cancel the pipelines automatically,
// {@literal DataflowPipelineRunner} is forced to be used.
options.setRunner(DataflowPipelineRunner.class);
}
options.setBigQuerySchema(FormatStatsFn.getSchema());
// Using DataflowExampleUtils to set up required resources.
DataflowExampleUtils dataflowUtils = new DataflowExampleUtils(options);
dataflowUtils.setup();
Pipeline pipeline = Pipeline.create(options);
TableReference tableRef = new TableReference();
tableRef.setProjectId(options.getProject());
tableRef.setDatasetId(options.getBigQueryDataset());
tableRef.setTableId(options.getBigQueryTable());
PCollection<KV<String, StationSpeed>> input;
if (options.isStreaming()) {
input = pipeline
.apply(PubsubIO.Read.topic(options.getPubsubTopic()))
// row... => <station route, station speed> ...
.apply(ParDo.of(new ExtractStationSpeedFn(false /* outputTimestamp */)));
} else {
input = pipeline
.apply(TextIO.Read.from(options.getInputFile()))
.apply(ParDo.of(new ExtractStationSpeedFn(true /* outputTimestamp */)));
}
// map the incoming data stream into sliding windows.
// The default window duration values work well if you're running the accompanying Pub/Sub
// generator script without the --replay flag, so that there are no simulated pauses in
// the sensor data publication. You may want to adjust the values otherwise.
input.apply(Window.<KV<String, StationSpeed>>into(SlidingWindows.of(
Duration.standardMinutes(options.getWindowDuration())).
every(Duration.standardMinutes(options.getWindowSlideEvery()))))
.apply(new TrackSpeed())
.apply(BigQueryIO.Write.to(tableRef)
.withSchema(FormatStatsFn.getSchema()));
PipelineResult result = pipeline.run();
if (options.isStreaming() && !options.getInputFile().isEmpty()) {
// Inject the data into the Pub/Sub topic with a Dataflow batch pipeline.
dataflowUtils.runInjectorPipeline(options.getInputFile(), options.getPubsubTopic());
}
// dataflowUtils will try to cancel the pipeline and the injector before the program exists.
dataflowUtils.waitToFinish(result);
}
private static Double tryParseAvgSpeed(String[] inputItems) {
try {
return Double.parseDouble(tryParseString(inputItems, 9));
} catch (NumberFormatException e) {
return null;
} catch (NullPointerException e) {
return null;
}
}
private static String tryParseStationType(String[] inputItems) {
return tryParseString(inputItems, 4);
}
private static String tryParseStationId(String[] inputItems) {
return tryParseString(inputItems, 1);
}
private static String tryParseTimestamp(String[] inputItems) {
return tryParseString(inputItems, 0);
}
private static String tryParseString(String[] inputItems, int index) {
return inputItems.length >= index ? inputItems[index] : null;
}
/**
* Define some small hard-wired San Diego 'routes' to track based on sensor station ID.
*/
private static Map<String, String> buildStationInfo() {
Map<String, String> stations = new Hashtable<String, String>();
stations.put("1108413", "SDRoute1"); // from freeway 805 S
stations.put("1108699", "SDRoute2"); // from freeway 78 E
stations.put("1108702", "SDRoute2");
return stations;
}
}
| |
package org.hisp.dhis.period;
/*
* Copyright (c) 2004-2016, University of Oslo
* 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 the HISP project 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.
*/
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;
import org.hisp.dhis.common.BaseDimensionalItemObject;
import org.hisp.dhis.common.DimensionItemType;
import org.hisp.dhis.common.DxfNamespaces;
import org.hisp.dhis.common.adapter.JacksonPeriodTypeDeserializer;
import org.hisp.dhis.common.adapter.JacksonPeriodTypeSerializer;
import org.hisp.dhis.schema.PropertyType;
import org.hisp.dhis.schema.annotation.Property;
import org.joda.time.DateTime;
import org.joda.time.Days;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* @author Kristian Nordal
*/
@JacksonXmlRootElement( localName = "period", namespace = DxfNamespaces.DXF_2_0 )
public class Period
extends BaseDimensionalItemObject
{
public static final String DEFAULT_DATE_FORMAT = "yyyy-MM-dd";
/**
* Required.
*/
private PeriodType periodType;
/**
* Required. Must be unique together with endDate.
*/
private Date startDate;
/**
* Required. Must be unique together with startDate.
*/
private Date endDate;
/**
* Transient string holding the ISO representation of the period.
*/
private transient String isoPeriod;
// -------------------------------------------------------------------------
// Constructors
// -------------------------------------------------------------------------
public Period()
{
}
public Period( Period period )
{
this.id = period.getId();
this.periodType = period.getPeriodType();
this.startDate = period.getStartDate();
this.endDate = period.getEndDate();
this.name = period.getName();
this.isoPeriod = period.getIsoDate();
}
protected Period( PeriodType periodType, Date startDate, Date endDate )
{
this.periodType = periodType;
this.startDate = startDate;
this.endDate = endDate;
}
protected Period( PeriodType periodType, Date startDate, Date endDate, String isoPeriod )
{
this.periodType = periodType;
this.startDate = startDate;
this.endDate = endDate;
this.isoPeriod = isoPeriod;
}
// -------------------------------------------------------------------------
// Logic
// -------------------------------------------------------------------------
@Override
public void setAutoFields()
{
}
@Override
public String getDimensionItem()
{
return getIsoDate();
}
@Override
public String getUid()
{
return uid != null ? uid : getIsoDate();
}
public String getRealUid()
{
return uid;
}
@Override
public String getCode()
{
return getIsoDate();
}
@Override
public String getName()
{
return name != null ? name : getIsoDate();
}
@Override
public String getShortName()
{
return shortName != null ? shortName : getIsoDate();
}
/**
* Returns an ISO8601 formatted string version of the period.
*
* @return the period string
*/
public String getIsoDate()
{
return isoPeriod != null ? isoPeriod : periodType.getIsoDate( this );
}
/**
* Copies the transient properties (name) from the argument Period
* to this Period.
*
* @param other Period to copy from.
* @return this Period.
*/
public Period copyTransientProperties( Period other )
{
this.name = other.getName();
this.shortName = other.getShortName();
this.code = other.getCode();
return this;
}
/**
* Returns the frequency order of the period type of the period.
*
* @return the frequency order.
*/
public int frequencyOrder()
{
return periodType != null ? periodType.getFrequencyOrder() : YearlyPeriodType.FREQUENCY_ORDER;
}
/**
* Returns start date formatted as string.
*
* @return start date formatted as string.
*/
public String getStartDateString()
{
return getMediumDateString( startDate );
}
/**
* Returns end date formatted as string.
*
* @return end date formatted as string.
*/
public String getEndDateString()
{
return getMediumDateString( endDate );
}
/**
* Formats a Date to the format YYYY-MM-DD.
*
* @param date the Date to parse.
* @return A formatted date string. Null if argument is null.
*/
private String getMediumDateString( Date date )
{
final SimpleDateFormat format = new SimpleDateFormat();
format.applyPattern( DEFAULT_DATE_FORMAT );
return date != null ? format.format( date ) : null;
}
/**
* Returns the potential number of periods of the given period type which is
* spanned by this period.
*
* @param type the period type.
* @return the potential number of periods of the given period type spanned
* by this period.
*/
public int getPeriodSpan( PeriodType type )
{
double no = (double) this.periodType.getFrequencyOrder() / type.getFrequencyOrder();
return (int) Math.floor( no );
}
/**
* Returns the number of days in the period, i.e. the days between the start
* and end date.
*
* @return number of days in period.
*/
public int getDaysInPeriod()
{
Days days = Days.daysBetween( new DateTime( startDate ), new DateTime( endDate ) );
return days.getDays() + 1;
}
/**
* Validates this period. TODO Make more comprehensive.
*/
public boolean isValid()
{
if ( startDate == null || endDate == null || periodType == null )
{
return false;
}
if ( !DailyPeriodType.NAME.equals( periodType.getName() ) && getDaysInPeriod() < 2 )
{
return false;
}
return true;
}
/**
* Determines whether this is a future period relative to the current time.
*
* @return true if this period ends in the future, false otherwise.
*/
public boolean isFuture()
{
return getEndDate().after( new Date() );
}
/**
* Indicates whether this period is after the given period. Bases the
* comparison on the end dates of the periods. If the given period is null,
* false is returned.
*
* @param period the period to compare.
* @return true if this period is after the given period.
*/
public boolean isAfter( Period period )
{
if ( period == null || period.getEndDate() == null )
{
return false;
}
return getEndDate().after( period.getEndDate() );
}
// -------------------------------------------------------------------------
// DimensionalItemObject
// -------------------------------------------------------------------------
@Override
public DimensionItemType getDimensionItemType()
{
return DimensionItemType.PERIOD;
}
// -------------------------------------------------------------------------
// hashCode, equals and toString
// -------------------------------------------------------------------------
@Override
public int hashCode()
{
int prime = 31;
int result = 1;
result = result * prime + (startDate != null ? startDate.hashCode() : 0);
result = result * prime + (endDate != null ? endDate.hashCode() : 0);
result = result * prime + (periodType != null ? periodType.hashCode() : 0);
return result;
}
@Override
public boolean equals( Object o )
{
if ( this == o )
{
return true;
}
if ( o == null )
{
return false;
}
if ( !(o instanceof Period) )
{
return false;
}
final Period other = (Period) o;
return startDate.equals( other.getStartDate() ) &&
endDate.equals( other.getEndDate() ) &&
periodType.equals( other.getPeriodType() );
}
@Override
public String toString()
{
return "[" + (periodType == null ? "" : periodType.getName() + ": ") + startDate + " - " + endDate + "]";
}
// -------------------------------------------------------------------------
// Getters and setters
// -------------------------------------------------------------------------
@JsonProperty
@JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
public Date getStartDate()
{
return startDate;
}
public void setStartDate( Date startDate )
{
this.startDate = startDate;
}
@JsonProperty
@JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
public Date getEndDate()
{
return endDate;
}
public void setEndDate( Date endDate )
{
this.endDate = endDate;
}
@JsonProperty
@JsonSerialize( using = JacksonPeriodTypeSerializer.class )
@JsonDeserialize( using = JacksonPeriodTypeDeserializer.class )
@JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
@Property( PropertyType.TEXT )
public PeriodType getPeriodType()
{
return periodType;
}
public void setPeriodType( PeriodType periodType )
{
this.periodType = periodType;
}
}
| |
/*
* @(#)DefaultKeyboardFocusManager.java 1.41 07/03/15
*
* Copyright 2006 Sun Microsystems, Inc. All rights reserved.
* SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
package java.awt;
import java.awt.event.FocusEvent;
import java.awt.event.KeyEvent;
import java.awt.event.WindowEvent;
import java.awt.peer.ComponentPeer;
import java.awt.peer.LightweightPeer;
import java.beans.PropertyChangeListener;
import java.util.LinkedList;
import java.util.Iterator;
import java.util.ListIterator;
import java.util.Set;
import java.util.logging.*;
import sun.awt.AppContext;
import sun.awt.SunToolkit;
import sun.awt.CausedFocusEvent;
/**
* The default KeyboardFocusManager for AWT applications. Focus traversal is
* done in response to a Component's focus traversal keys, and using a
* Container's FocusTraversalPolicy.
* <p>
* Please see
* <a href="http://java.sun.com/docs/books/tutorial/uiswing/misc/focus.html">
* How to Use the Focus Subsystem</a>,
* a section in <em>The Java Tutorial</em>, and the
* <a href="../../java/awt/doc-files/FocusSpec.html">Focus Specification</a>
* for more information.
*
* @author David Mendenhall
* @version 1.41, 03/15/07
*
* @see FocusTraversalPolicy
* @see Component#setFocusTraversalKeys
* @see Component#getFocusTraversalKeys
* @since 1.4
*/
public class DefaultKeyboardFocusManager extends KeyboardFocusManager {
private static final Logger focusLog = Logger.getLogger("java.awt.focus.DefaultKeyboardFocusManager");
private Window realOppositeWindow;
private Component realOppositeComponent;
private int inSendMessage;
private LinkedList enqueuedKeyEvents = new LinkedList(),
typeAheadMarkers = new LinkedList();
private boolean consumeNextKeyTyped;
private static class TypeAheadMarker {
long after;
Component untilFocused;
TypeAheadMarker(long after, Component untilFocused) {
this.after = after;
this.untilFocused = untilFocused;
}
/**
* Returns string representation of the marker
*/
public String toString() {
return ">>> Marker after " + after + " on " + untilFocused;
}
}
private Window getOwningFrameDialog(Window window) {
while (window != null && !(window instanceof Frame ||
window instanceof Dialog)) {
window = (Window)window.getParent();
}
return window;
}
/*
* This series of restoreFocus methods is used for recovering from a
* rejected focus or activation change. Rejections typically occur when
* the user attempts to focus a non-focusable Component or Window.
*/
private void restoreFocus(FocusEvent fe, Window newFocusedWindow) {
Component realOppositeComponent = this.realOppositeComponent;
Component vetoedComponent = fe.getComponent();
if (newFocusedWindow != null && restoreFocus(newFocusedWindow,
vetoedComponent, false))
{
} else if (realOppositeComponent != null &&
doRestoreFocus(realOppositeComponent, vetoedComponent, false)) {
} else if (fe.getOppositeComponent() != null &&
doRestoreFocus(fe.getOppositeComponent(), vetoedComponent, false)) {
} else {
clearGlobalFocusOwner();
}
}
private void restoreFocus(WindowEvent we) {
Window realOppositeWindow = this.realOppositeWindow;
if (realOppositeWindow != null && restoreFocus(realOppositeWindow,
null, false)) {
} else if (we.getOppositeWindow() != null &&
restoreFocus(we.getOppositeWindow(), null, false)) {
} else {
clearGlobalFocusOwner();
}
}
private boolean restoreFocus(Window aWindow, Component vetoedComponent,
boolean clearOnFailure) {
Component toFocus =
KeyboardFocusManager.getMostRecentFocusOwner(aWindow);
if (toFocus != null && toFocus != vetoedComponent && doRestoreFocus(toFocus, vetoedComponent, false)) {
return true;
} else if (clearOnFailure) {
clearGlobalFocusOwner();
return true;
} else {
return false;
}
}
private boolean restoreFocus(Component toFocus, boolean clearOnFailure) {
return doRestoreFocus(toFocus, null, clearOnFailure);
}
private boolean doRestoreFocus(Component toFocus, Component vetoedComponent,
boolean clearOnFailure)
{
if (toFocus.isShowing() && toFocus.isFocusable() &&
toFocus.requestFocus(false, CausedFocusEvent.Cause.ROLLBACK)) {
return true;
} else {
Component nextFocus = toFocus.preNextFocusHelper();
if (nextFocus != vetoedComponent && Component.postNextFocusHelper(nextFocus)) {
return true;
} else if (clearOnFailure) {
clearGlobalFocusOwner();
return true;
} else {
return false;
}
}
}
/**
* A special type of SentEvent which updates a counter in the target
* KeyboardFocusManager if it is an instance of
* DefaultKeyboardFocusManager.
*/
private static class DefaultKeyboardFocusManagerSentEvent
extends SentEvent
{
/*
* serialVersionUID
*/
private static final long serialVersionUID = -2924743257508701758L;
public DefaultKeyboardFocusManagerSentEvent(AWTEvent nested,
AppContext toNotify) {
super(nested, toNotify);
}
public final void dispatch() {
KeyboardFocusManager manager =
KeyboardFocusManager.getCurrentKeyboardFocusManager();
DefaultKeyboardFocusManager defaultManager =
(manager instanceof DefaultKeyboardFocusManager)
? (DefaultKeyboardFocusManager)manager
: null;
if (defaultManager != null) {
synchronized (defaultManager) {
defaultManager.inSendMessage++;
}
}
super.dispatch();
if (defaultManager != null) {
synchronized (defaultManager) {
defaultManager.inSendMessage--;
}
}
}
}
/**
* Sends a synthetic AWTEvent to a Component. If the Component is in
* the current AppContext, then the event is immediately dispatched.
* If the Component is in a different AppContext, then the event is
* posted to the other AppContext's EventQueue, and this method blocks
* until the event is handled or target AppContext is disposed.
* Returns true if successfuly dispatched event, false if failed
* to dispatch.
*/
static boolean sendMessage(Component target, AWTEvent e) {
e.isPosted = true;
AppContext myAppContext = AppContext.getAppContext();
final AppContext targetAppContext = target.appContext;
final SentEvent se =
new DefaultKeyboardFocusManagerSentEvent(e, myAppContext);
if (myAppContext == targetAppContext) {
se.dispatch();
} else {
if (targetAppContext.isDisposed()) {
return false;
}
SunToolkit.postEvent(targetAppContext, se);
if (EventQueue.isDispatchThread()) {
EventDispatchThread edt = (EventDispatchThread)
Thread.currentThread();
edt.pumpEvents(SentEvent.ID, new Conditional() {
public boolean evaluate() {
return !se.dispatched && !targetAppContext.isDisposed();
}
});
} else {
synchronized (se) {
while (!se.dispatched && !targetAppContext.isDisposed()) {
try {
se.wait(1000);
} catch (InterruptedException ie) {
break;
}
}
}
}
}
return se.dispatched;
}
/**
* This method is called by the AWT event dispatcher requesting that the
* current KeyboardFocusManager dispatch the specified event on its behalf.
* DefaultKeyboardFocusManagers dispatch all FocusEvents, all WindowEvents
* related to focus, and all KeyEvents. These events are dispatched based
* on the KeyboardFocusManager's notion of the focus owner and the focused
* and active Windows, sometimes overriding the source of the specified
* AWTEvent. If this method returns <code>false</code>, then the AWT event
* dispatcher will attempt to dispatch the event itself.
*
* @param e the AWTEvent to be dispatched
* @return <code>true</code> if this method dispatched the event;
* <code>false</code> otherwise
*/
public boolean dispatchEvent(AWTEvent e) {
if (focusLog.isLoggable(Level.FINE) && (e instanceof WindowEvent || e instanceof FocusEvent)) focusLog.fine("" + e);
switch (e.getID()) {
case WindowEvent.WINDOW_GAINED_FOCUS: {
WindowEvent we = (WindowEvent)e;
Window oldFocusedWindow = getGlobalFocusedWindow();
Window newFocusedWindow = we.getWindow();
if (newFocusedWindow == oldFocusedWindow) {
break;
}
// If there exists a current focused window, then notify it
// that it has lost focus.
if (oldFocusedWindow != null) {
boolean isEventDispatched =
sendMessage(oldFocusedWindow,
new WindowEvent(oldFocusedWindow,
WindowEvent.WINDOW_LOST_FOCUS,
newFocusedWindow));
// Failed to dispatch, clear by ourselfves
if (!isEventDispatched) {
setGlobalFocusOwner(null);
setGlobalFocusedWindow(null);
}
}
// Because the native libraries do not post WINDOW_ACTIVATED
// events, we need to synthesize one if the active Window
// changed.
Window newActiveWindow =
getOwningFrameDialog(newFocusedWindow);
Window currentActiveWindow = getGlobalActiveWindow();
if (newActiveWindow != currentActiveWindow) {
sendMessage(newActiveWindow,
new WindowEvent(newActiveWindow,
WindowEvent.WINDOW_ACTIVATED,
currentActiveWindow));
if (newActiveWindow != getGlobalActiveWindow()) {
// Activation change was rejected. Unlikely, but
// possible.
restoreFocus(we);
break;
}
}
setGlobalFocusedWindow(newFocusedWindow);
if (newFocusedWindow != getGlobalFocusedWindow()) {
// Focus change was rejected. Will happen if
// newFocusedWindow is not a focusable Window.
restoreFocus(we);
break;
}
setNativeFocusedWindow(newFocusedWindow);
// Restore focus to the Component which last held it. We do
// this here so that client code can override our choice in
// a WINDOW_GAINED_FOCUS handler.
//
// Make sure that the focus change request doesn't change the
// focused Window in case we are no longer the focused Window
// when the request is handled.
if (inSendMessage == 0) {
// Identify which Component should initially gain focus
// in the Window.
//
// * If we're in SendMessage, then this is a synthetic
// WINDOW_GAINED_FOCUS message which was generated by a
// the FOCUS_GAINED handler. Allow the Component to
// which the FOCUS_GAINED message was targeted to
// receive the focus.
// * Otherwise, look up the correct Component here.
// We don't use Window.getMostRecentFocusOwner because
// window is focused now and 'null' will be returned
// Calculating of most recent focus owner and focus
// request should be synchronized on KeyboardFocusManager.class
// to prevent from thread race when user will request
// focus between calculation and our request.
// But if focus transfer is synchronous, this synchronization
// may cause deadlock, thus we don't synchronize this block.
Component toFocus = KeyboardFocusManager.
getMostRecentFocusOwner(newFocusedWindow);
if ((toFocus == null) &&
newFocusedWindow.isFocusableWindow())
{
toFocus = newFocusedWindow.getFocusTraversalPolicy().
getInitialComponent(newFocusedWindow);
}
Component tempLost = null;
synchronized(KeyboardFocusManager.class) {
tempLost = newFocusedWindow.setTemporaryLostComponent(null);
}
// The component which last has the focus when this window was focused
// should receive focus first
if (focusLog.isLoggable(Level.FINER)) {
focusLog.log(Level.FINER, "tempLost {0}, toFocus {1}",
new Object[]{tempLost, toFocus});
}
if (tempLost != null) {
tempLost.requestFocusInWindow(CausedFocusEvent.Cause.ACTIVATION);
}
if (toFocus != null && toFocus != tempLost) {
// If there is a component which requested focus when this window
// was inactive it expects to receive focus after activation.
toFocus.requestFocusInWindow(CausedFocusEvent.Cause.ACTIVATION);
}
}
Window realOppositeWindow = this.realOppositeWindow;
if (realOppositeWindow != we.getOppositeWindow()) {
we = new WindowEvent(newFocusedWindow,
WindowEvent.WINDOW_GAINED_FOCUS,
realOppositeWindow);
}
return typeAheadAssertions(newFocusedWindow, we);
}
case WindowEvent.WINDOW_ACTIVATED: {
WindowEvent we = (WindowEvent)e;
Window oldActiveWindow = getGlobalActiveWindow();
Window newActiveWindow = we.getWindow();
if (oldActiveWindow == newActiveWindow) {
break;
}
// If there exists a current active window, then notify it that
// it has lost activation.
if (oldActiveWindow != null) {
boolean isEventDispatched =
sendMessage(oldActiveWindow,
new WindowEvent(oldActiveWindow,
WindowEvent.WINDOW_DEACTIVATED,
newActiveWindow));
// Failed to dispatch, clear by ourselfves
if (!isEventDispatched) {
setGlobalActiveWindow(null);
}
if (getGlobalActiveWindow() != null) {
// Activation change was rejected. Unlikely, but
// possible.
break;
}
}
setGlobalActiveWindow(newActiveWindow);
if (newActiveWindow != getGlobalActiveWindow()) {
// Activation change was rejected. Unlikely, but
// possible.
break;
}
return typeAheadAssertions(newActiveWindow, we);
}
case FocusEvent.FOCUS_GAINED: {
FocusEvent fe = (FocusEvent)e;
CausedFocusEvent.Cause cause = (fe instanceof CausedFocusEvent) ?
((CausedFocusEvent)fe).getCause() : CausedFocusEvent.Cause.UNKNOWN;
Component oldFocusOwner = getGlobalFocusOwner();
Component newFocusOwner = fe.getComponent();
if (oldFocusOwner == newFocusOwner) {
if (focusLog.isLoggable(Level.FINE)) focusLog.log(Level.FINE, "Skipping {0} because focus owner is the same",
new Object[] {e});
// We can't just drop the event - there could be
// type-ahead markers associated with it.
dequeueKeyEvents(-1, newFocusOwner);
break;
}
// If there exists a current focus owner, then notify it that
// it has lost focus.
if (oldFocusOwner != null) {
boolean isEventDispatched =
sendMessage(oldFocusOwner,
new CausedFocusEvent(oldFocusOwner,
FocusEvent.FOCUS_LOST,
fe.isTemporary(),
newFocusOwner, cause));
// Failed to dispatch, clear by ourselfves
if (!isEventDispatched) {
setGlobalFocusOwner(null);
if (!fe.isTemporary()) {
setGlobalPermanentFocusOwner(null);
}
}
}
// Because the native windowing system has a different notion
// of the current focus and activation states, it is possible
// that a Component outside of the focused Window receives a
// FOCUS_GAINED event. We synthesize a WINDOW_GAINED_FOCUS
// event in that case.
Component newFocusedWindow = newFocusOwner;
while (newFocusedWindow != null &&
!(newFocusedWindow instanceof Window)) {
newFocusedWindow = newFocusedWindow.parent;
}
Window currentFocusedWindow = getGlobalFocusedWindow();
if (newFocusedWindow != null &&
newFocusedWindow != currentFocusedWindow)
{
sendMessage(newFocusedWindow,
new WindowEvent((Window)newFocusedWindow,
WindowEvent.WINDOW_GAINED_FOCUS,
currentFocusedWindow));
if (newFocusedWindow != getGlobalFocusedWindow()) {
// Focus change was rejected. Will happen if
// newFocusedWindow is not a focusable Window.
// Need to recover type-ahead, but don't bother
// restoring focus. That was done by the
// WINDOW_GAINED_FOCUS handler
dequeueKeyEvents(-1, newFocusOwner);
break;
}
}
setGlobalFocusOwner(newFocusOwner);
if (newFocusOwner != getGlobalFocusOwner()) {
// Focus change was rejected. Will happen if
// newFocusOwner is not focus traversable.
dequeueKeyEvents(-1, newFocusOwner);
if (! disableRestoreFocus ){
restoreFocus(fe, (Window)newFocusedWindow);
}
break;
}
if (!fe.isTemporary()) {
setGlobalPermanentFocusOwner(newFocusOwner);
if (newFocusOwner != getGlobalPermanentFocusOwner()) {
// Focus change was rejected. Unlikely, but possible.
dequeueKeyEvents(-1, newFocusOwner);
if (! disableRestoreFocus ){
restoreFocus(fe, (Window)newFocusedWindow);
}
break;
}
}
setNativeFocusOwner(getHeavyweight(newFocusOwner));
Component realOppositeComponent = this.realOppositeComponent;
if (realOppositeComponent != null &&
realOppositeComponent != fe.getOppositeComponent()) {
fe = new CausedFocusEvent(newFocusOwner,
FocusEvent.FOCUS_GAINED,
fe.isTemporary(),
realOppositeComponent, cause);
((AWTEvent) fe).isPosted = true;
}
return typeAheadAssertions(newFocusOwner, fe);
}
case FocusEvent.FOCUS_LOST: {
FocusEvent fe = (FocusEvent)e;
Component currentFocusOwner = getGlobalFocusOwner();
if (currentFocusOwner == null) {
if (focusLog.isLoggable(Level.FINE)) focusLog.log(Level.FINE, "Skipping {0} because focus owner is null",
new Object[] {e});
break;
}
// Ignore cases where a Component loses focus to itself.
// If we make a mistake because of retargeting, then the
// FOCUS_GAINED handler will correct it.
if (currentFocusOwner == fe.getOppositeComponent()) {
if (focusLog.isLoggable(Level.FINE)) focusLog.log(Level.FINE, "Skipping {0} because current focus owner is equal to opposite",
new Object[] {e});
break;
}
setGlobalFocusOwner(null);
if (getGlobalFocusOwner() != null) {
// Focus change was rejected. Unlikely, but possible.
restoreFocus(currentFocusOwner, true);
break;
}
if (!fe.isTemporary()) {
setGlobalPermanentFocusOwner(null);
if (getGlobalPermanentFocusOwner() != null) {
// Focus change was rejected. Unlikely, but possible.
restoreFocus(currentFocusOwner, true);
break;
}
} else {
Window owningWindow = currentFocusOwner.getContainingWindow();
if (owningWindow != null) {
owningWindow.setTemporaryLostComponent(currentFocusOwner);
}
}
setNativeFocusOwner(null);
fe.setSource(currentFocusOwner);
realOppositeComponent = (fe.getOppositeComponent() != null)
? currentFocusOwner : null;
return typeAheadAssertions(currentFocusOwner, fe);
}
case WindowEvent.WINDOW_DEACTIVATED: {
WindowEvent we = (WindowEvent)e;
Window currentActiveWindow = getGlobalActiveWindow();
if (currentActiveWindow == null) {
break;
}
if (currentActiveWindow != e.getSource()) {
// The event is lost in time.
// Allow listeners to precess the event but do not
// change any global states
break;
}
setGlobalActiveWindow(null);
if (getGlobalActiveWindow() != null) {
// Activation change was rejected. Unlikely, but possible.
break;
}
we.setSource(currentActiveWindow);
return typeAheadAssertions(currentActiveWindow, we);
}
case WindowEvent.WINDOW_LOST_FOCUS: {
WindowEvent we = (WindowEvent)e;
Window currentFocusedWindow = getGlobalFocusedWindow();
Window losingFocusWindow = we.getWindow();
Window activeWindow = getGlobalActiveWindow();
Window oppositeWindow = we.getOppositeWindow();
if (focusLog.isLoggable(Level.FINE)) focusLog.log(Level.FINE, "Active {0}, Current focused {1}, losing focus {2} opposite {3}",
new Object[] {activeWindow, currentFocusedWindow,
losingFocusWindow, oppositeWindow});
if (currentFocusedWindow == null) {
break;
}
// Special case -- if the native windowing system posts an
// event claiming that the active Window has lost focus to the
// focused Window, then discard the event. This is an artifact
// of the native windowing system not knowing which Window is
// really focused.
if (inSendMessage == 0 && losingFocusWindow == activeWindow &&
oppositeWindow == currentFocusedWindow)
{
break;
}
Component currentFocusOwner = getGlobalFocusOwner();
if (currentFocusOwner != null) {
// The focus owner should always receive a FOCUS_LOST event
// before the Window is defocused.
Component oppositeComp = null;
if (oppositeWindow != null) {
oppositeComp = oppositeWindow.getTemporaryLostComponent();
if (oppositeComp == null) {
oppositeComp = oppositeWindow.getMostRecentFocusOwner();
}
}
if (oppositeComp == null) {
oppositeComp = oppositeWindow;
}
sendMessage(currentFocusOwner,
new CausedFocusEvent(currentFocusOwner,
FocusEvent.FOCUS_LOST,
true,
oppositeComp, CausedFocusEvent.Cause.ACTIVATION));
}
setGlobalFocusedWindow(null);
if (getGlobalFocusedWindow() != null) {
// Focus change was rejected. Unlikely, but possible.
restoreFocus(currentFocusedWindow, null, true);
break;
}
setNativeFocusedWindow(null);
we.setSource(currentFocusedWindow);
realOppositeWindow = (oppositeWindow != null)
? currentFocusedWindow
: null;
typeAheadAssertions(currentFocusedWindow, we);
if (oppositeWindow == null) {
// Then we need to deactive the active Window as well.
// No need to synthesize in other cases, because
// WINDOW_ACTIVATED will handle it if necessary.
sendMessage(activeWindow,
new WindowEvent(activeWindow,
WindowEvent.WINDOW_DEACTIVATED,
null));
if (getGlobalActiveWindow() != null) {
// Activation change was rejected. Unlikely,
// but possible.
restoreFocus(currentFocusedWindow, null, true);
}
}
break;
}
case KeyEvent.KEY_TYPED:
case KeyEvent.KEY_PRESSED:
case KeyEvent.KEY_RELEASED:
return typeAheadAssertions(null, e);
default:
return false;
}
return true;
}
/**
* Called by <code>dispatchEvent</code> if no other
* KeyEventDispatcher in the dispatcher chain dispatched the KeyEvent, or
* if no other KeyEventDispatchers are registered. If the event has not
* been consumed, its target is enabled, and the focus owner is not null,
* this method dispatches the event to its target. This method will also
* subsequently dispatch the event to all registered
* KeyEventPostProcessors. After all this operations are finished,
* the event is passed to peers for processing.
* <p>
* In all cases, this method returns <code>true</code>, since
* DefaultKeyboardFocusManager is designed so that neither
* <code>dispatchEvent</code>, nor the AWT event dispatcher, should take
* further action on the event in any situation.
*
* @param e the KeyEvent to be dispatched
* @return <code>true</code>
* @see Component#dispatchEvent
*/
public boolean dispatchKeyEvent(KeyEvent e) {
Component focusOwner = (((AWTEvent)e).isPosted) ? getFocusOwner() : e.getComponent();
if (focusOwner != null && focusOwner.isShowing() &&
focusOwner.isFocusable() && focusOwner.isEnabled()) {
if (!e.isConsumed()) {
Component comp = e.getComponent();
if (comp != null && comp.isEnabled()) {
redispatchEvent(comp, e);
}
}
}
boolean stopPostProcessing = false;
java.util.List processors = getKeyEventPostProcessors();
if (processors != null) {
for (java.util.Iterator iter = processors.iterator();
!stopPostProcessing && iter.hasNext(); )
{
stopPostProcessing = (((KeyEventPostProcessor)(iter.next())).
postProcessKeyEvent(e));
}
}
if (!stopPostProcessing) {
postProcessKeyEvent(e);
}
// Allow the peer to process KeyEvent
Component source = e.getComponent();
ComponentPeer peer = source.getPeer();
if (peer == null || peer instanceof LightweightPeer) {
// if focus owner is lightweight then its native container
// processes event
Container target = source.getNativeContainer();
if (target != null) {
peer = target.getPeer();
}
}
if (peer != null) {
peer.handleEvent(e);
}
return true;
}
/**
* This method will be called by <code>dispatchKeyEvent</code>. It will
* handle any unconsumed KeyEvents that map to an AWT
* <code>MenuShortcut</code> by consuming the event and activating the
* shortcut.
*
* @param e the KeyEvent to post-process
* @return <code>true</code>
* @see #dispatchKeyEvent
* @see MenuShortcut
*/
public boolean postProcessKeyEvent(KeyEvent e) {
if (!e.isConsumed()) {
Component target = e.getComponent();
Container p = (Container)
(target instanceof Container ? target : target.getParent());
if (p != null) {
p.postProcessKeyEvent(e);
}
}
return true;
}
private void pumpApprovedKeyEvents() {
KeyEvent ke;
do {
ke = null;
synchronized (this) {
if (enqueuedKeyEvents.size() != 0) {
ke = (KeyEvent)enqueuedKeyEvents.getFirst();
if (typeAheadMarkers.size() != 0) {
TypeAheadMarker marker = (TypeAheadMarker)
typeAheadMarkers.getFirst();
// Fixed 5064013: may appears that the events have the same time
// if (ke.getWhen() >= marker.after) {
// The fix is rolled out.
if (ke.getWhen() > marker.after) {
ke = null;
}
}
if (ke != null) {
focusLog.log(Level.FINER, "Pumping approved event {0}", new Object[] {ke});
enqueuedKeyEvents.removeFirst();
}
}
}
if (ke != null) {
preDispatchKeyEvent(ke);
}
} while (ke != null);
}
/**
* Dumps the list of type-ahead queue markers to stderr
*/
void dumpMarkers() {
if (focusLog.isLoggable(Level.FINEST)) {
focusLog.log(Level.FINEST, ">>> Markers dump, time: {0}", System.currentTimeMillis());
synchronized (this) {
if (typeAheadMarkers.size() != 0) {
Iterator iter = typeAheadMarkers.iterator();
while (iter.hasNext()) {
TypeAheadMarker marker = (TypeAheadMarker)iter.next();
focusLog.log(Level.FINEST, " {0}", marker);
}
}
}
}
}
private boolean typeAheadAssertions(Component target, AWTEvent e) {
// Clear any pending events here as well as in the FOCUS_GAINED
// handler. We need this call here in case a marker was removed in
// response to a call to dequeueKeyEvents.
pumpApprovedKeyEvents();
switch (e.getID()) {
case KeyEvent.KEY_TYPED:
case KeyEvent.KEY_PRESSED:
case KeyEvent.KEY_RELEASED: {
KeyEvent ke = (KeyEvent)e;
synchronized (this) {
if (e.isPosted && typeAheadMarkers.size() != 0) {
TypeAheadMarker marker = (TypeAheadMarker)
typeAheadMarkers.getFirst();
// Fixed 5064013: may appears that the events have the same time
// if (ke.getWhen() >= marker.after) {
// The fix is rolled out.
if (ke.getWhen() > marker.after) {
focusLog.log(Level.FINER, "Storing event {0} because of marker {1}", new Object[] {ke, marker});
enqueuedKeyEvents.addLast(ke);
return true;
}
}
}
// KeyEvent was posted before focus change request
return preDispatchKeyEvent(ke);
}
case FocusEvent.FOCUS_GAINED:
focusLog.log(Level.FINEST, "Markers before FOCUS_GAINED on {0}", new Object[] {target});
dumpMarkers();
// Search the marker list for the first marker tied to
// the Component which just gained focus. Then remove
// that marker, any markers which immediately follow
// and are tied to the same component, and all markers
// that preceed it. This handles the case where
// multiple focus requests were made for the same
// Component in a row and when we lost some of the
// earlier requests. Since FOCUS_GAINED events will
// not be generated for these additional requests, we
// need to clear those markers too.
synchronized (this) {
boolean found = false;
if (hasMarker(target)) {
for (Iterator iter = typeAheadMarkers.iterator();
iter.hasNext(); )
{
if (((TypeAheadMarker)iter.next()).untilFocused ==
target)
{
found = true;
} else if (found) {
break;
}
iter.remove();
}
} else {
// Exception condition - event without marker
focusLog.log(Level.FINER, "Event without marker {0}", e);
}
}
focusLog.log(Level.FINEST, "Markers after FOCUS_GAINED");
dumpMarkers();
redispatchEvent(target, e);
// Now, dispatch any pending KeyEvents which have been
// released because of the FOCUS_GAINED event so that we don't
// have to wait for another event to be posted to the queue.
pumpApprovedKeyEvents();
return true;
default:
redispatchEvent(target, e);
return true;
}
}
/**
* Returns true if there are some marker associated with component <code>comp</code>
* in a markers' queue
* @since 1.5
*/
private boolean hasMarker(Component comp) {
for (Iterator iter = typeAheadMarkers.iterator(); iter.hasNext(); ) {
if (((TypeAheadMarker)iter.next()).untilFocused == comp) {
return true;
}
}
return false;
}
/**
* Clears markers queue
* @since 1.5
*/
void clearMarkers() {
synchronized(this) {
typeAheadMarkers.clear();
}
}
private boolean preDispatchKeyEvent(KeyEvent ke) {
if (((AWTEvent) ke).isPosted) {
Component focusOwner = getFocusOwner();
ke.setSource(((focusOwner != null) ? focusOwner : getFocusedWindow()));
}
if (ke.getSource() == null) {
return true;
}
// Explicitly set the current event and most recent timestamp here in
// addition to the call in Component.dispatchEventImpl. Because
// KeyEvents can be delivered in response to a FOCUS_GAINED event, the
// current timestamp may be incorrect. We need to set it here so that
// KeyEventDispatchers will use the correct time.
EventQueue.setCurrentEventAndMostRecentTime(ke);
/**
* Fix for 4495473.
* This fix allows to correctly dispatch events when native
* event proxying mechanism is active.
* If it is active we should redispatch key events after
* we detected its correct target.
*/
if (KeyboardFocusManager.isProxyActive(ke)) {
Component source = (Component)ke.getSource();
Container target = source.getNativeContainer();
if (target != null) {
ComponentPeer peer = target.getPeer();
if (peer != null) {
peer.handleEvent(ke);
/**
* Fix for 4478780 - consume event after it was dispatched by peer.
*/
ke.consume();
}
}
return true;
}
java.util.List dispatchers = getKeyEventDispatchers();
if (dispatchers != null) {
for (java.util.Iterator iter = dispatchers.iterator();
iter.hasNext(); )
{
if (((KeyEventDispatcher)(iter.next())).
dispatchKeyEvent(ke))
{
return true;
}
}
}
return dispatchKeyEvent(ke);
}
/*
* @param e is a KEY_PRESSED event that can be used
* to track the next KEY_TYPED related.
*/
private void consumeNextKeyTyped(KeyEvent e) {
consumeNextKeyTyped = true;
}
private void consumeTraversalKey(KeyEvent e) {
e.consume();
consumeNextKeyTyped = (e.getID() == KeyEvent.KEY_PRESSED) &&
!e.isActionKey();
}
/*
* return true if event was consumed
*/
private boolean consumeProcessedKeyEvent(KeyEvent e) {
if ((e.getID() == KeyEvent.KEY_TYPED) && consumeNextKeyTyped) {
e.consume();
consumeNextKeyTyped = false;
return true;
}
return false;
}
/**
* This method initiates a focus traversal operation if and only if the
* KeyEvent represents a focus traversal key for the specified
* focusedComponent. It is expected that focusedComponent is the current
* focus owner, although this need not be the case. If it is not,
* focus traversal will nevertheless proceed as if focusedComponent
* were the focus owner.
*
* @param focusedComponent the Component that is the basis for a focus
* traversal operation if the specified event represents a focus
* traversal key for the Component
* @param e the event that may represent a focus traversal key
*/
public void processKeyEvent(Component focusedComponent, KeyEvent e) {
// consume processed event if needed
if (consumeProcessedKeyEvent(e)) {
return;
}
// KEY_TYPED events cannot be focus traversal keys
if (e.getID() == KeyEvent.KEY_TYPED) {
return;
}
if (focusedComponent.getFocusTraversalKeysEnabled() &&
!e.isConsumed())
{
AWTKeyStroke stroke = AWTKeyStroke.getAWTKeyStrokeForEvent(e),
oppStroke = AWTKeyStroke.getAWTKeyStroke(stroke.getKeyCode(),
stroke.getModifiers(),
!stroke.isOnKeyRelease());
Set toTest;
boolean contains, containsOpp;
toTest = focusedComponent.getFocusTraversalKeys(
KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS);
contains = toTest.contains(stroke);
containsOpp = toTest.contains(oppStroke);
if (contains || containsOpp) {
consumeTraversalKey(e);
if (contains) {
focusNextComponent(focusedComponent);
}
return;
}
toTest = focusedComponent.getFocusTraversalKeys(
KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS);
contains = toTest.contains(stroke);
containsOpp = toTest.contains(oppStroke);
if (contains || containsOpp) {
consumeTraversalKey(e);
if (contains) {
focusPreviousComponent(focusedComponent);
}
return;
}
toTest = focusedComponent.getFocusTraversalKeys(
KeyboardFocusManager.UP_CYCLE_TRAVERSAL_KEYS);
contains = toTest.contains(stroke);
containsOpp = toTest.contains(oppStroke);
if (contains || containsOpp) {
consumeTraversalKey(e);
if (contains) {
upFocusCycle(focusedComponent);
}
return;
}
if (!((focusedComponent instanceof Container) &&
((Container)focusedComponent).isFocusCycleRoot())) {
return;
}
toTest = focusedComponent.getFocusTraversalKeys(
KeyboardFocusManager.DOWN_CYCLE_TRAVERSAL_KEYS);
contains = toTest.contains(stroke);
containsOpp = toTest.contains(oppStroke);
if (contains || containsOpp) {
consumeTraversalKey(e);
if (contains) {
downFocusCycle((Container)focusedComponent);
}
}
}
}
/**
* Delays dispatching of KeyEvents until the specified Component becomes
* the focus owner. KeyEvents with timestamps later than the specified
* timestamp will be enqueued until the specified Component receives a
* FOCUS_GAINED event, or the AWT cancels the delay request by invoking
* <code>dequeueKeyEvents</code> or <code>discardKeyEvents</code>.
*
* @param after timestamp of current event, or the current, system time if
* the current event has no timestamp, or the AWT cannot determine
* which event is currently being handled
* @param untilFocused Component which will receive a FOCUS_GAINED event
* before any pending KeyEvents
* @see #dequeueKeyEvents
* @see #discardKeyEvents
*/
protected synchronized void enqueueKeyEvents(long after,
Component untilFocused) {
if (untilFocused == null) {
return;
}
focusLog.log(Level.FINER, "Enqueue at {0} for {1}",
new Object[] {after, untilFocused});
int insertionIndex = 0,
i = typeAheadMarkers.size();
ListIterator iter = typeAheadMarkers.listIterator(i);
for (; i > 0; i--) {
TypeAheadMarker marker = (TypeAheadMarker)iter.previous();
if (marker.after <= after) {
insertionIndex = i;
break;
}
}
typeAheadMarkers.add(insertionIndex,
new TypeAheadMarker(after, untilFocused));
}
/**
* Releases for normal dispatching to the current focus owner all
* KeyEvents which were enqueued because of a call to
* <code>enqueueKeyEvents</code> with the same timestamp and Component.
* If the given timestamp is less than zero, the outstanding enqueue
* request for the given Component with the <b>oldest</b> timestamp (if
* any) should be cancelled.
*
* @param after the timestamp specified in the call to
* <code>enqueueKeyEvents</code>, or any value < 0
* @param untilFocused the Component specified in the call to
* <code>enqueueKeyEvents</code>
* @see #enqueueKeyEvents
* @see #discardKeyEvents
*/
protected synchronized void dequeueKeyEvents(long after,
Component untilFocused) {
if (untilFocused == null) {
return;
}
focusLog.log(Level.FINER, "Dequeue at {0} for {1}",
new Object[] {after, untilFocused});
TypeAheadMarker marker;
ListIterator iter = typeAheadMarkers.listIterator
((after >= 0) ? typeAheadMarkers.size() : 0);
if (after < 0) {
while (iter.hasNext()) {
marker = (TypeAheadMarker)iter.next();
if (marker.untilFocused == untilFocused)
{
iter.remove();
return;
}
}
} else {
while (iter.hasPrevious()) {
marker = (TypeAheadMarker)iter.previous();
if (marker.untilFocused == untilFocused &&
marker.after == after)
{
iter.remove();
return;
}
}
}
}
/**
* Discards all KeyEvents which were enqueued because of one or more calls
* to <code>enqueueKeyEvents</code> with the specified Component, or one of
* its descendants.
*
* @param comp the Component specified in one or more calls to
* <code>enqueueKeyEvents</code>, or a parent of such a Component
* @see #enqueueKeyEvents
* @see #dequeueKeyEvents
*/
protected synchronized void discardKeyEvents(Component comp) {
if (comp == null) {
return;
}
long start = -1;
for (Iterator iter = typeAheadMarkers.iterator(); iter.hasNext(); ) {
TypeAheadMarker marker = (TypeAheadMarker)iter.next();
Component toTest = marker.untilFocused;
boolean match = (toTest == comp);
while (!match && toTest != null && !(toTest instanceof Window)) {
toTest = toTest.getParent();
match = (toTest == comp);
}
if (match) {
if (start < 0) {
start = marker.after;
}
iter.remove();
} else if (start >= 0) {
purgeStampedEvents(start, marker.after);
start = -1;
}
}
purgeStampedEvents(start, -1);
}
// Notes:
// * must be called inside a synchronized block
// * if 'start' is < 0, then this function does nothing
// * if 'end' is < 0, then all KeyEvents from 'start' to the end of the
// queue will be removed
private void purgeStampedEvents(long start, long end) {
if (start < 0) {
return;
}
for (Iterator iter = enqueuedKeyEvents.iterator(); iter.hasNext(); ) {
KeyEvent ke = (KeyEvent)iter.next();
long time = ke.getWhen();
if (start < time && (end < 0 || time <= end)) {
iter.remove();
}
if (end >= 0 && time > end) {
break;
}
}
}
/**
* Focuses the Component before aComponent, typically based on a
* FocusTraversalPolicy.
*
* @param aComponent the Component that is the basis for the focus
* traversal operation
* @see FocusTraversalPolicy
* @see Component#transferFocusBackward
*/
public void focusPreviousComponent(Component aComponent) {
if (aComponent != null) {
aComponent.transferFocusBackward();
}
}
/**
* Focuses the Component after aComponent, typically based on a
* FocusTraversalPolicy.
*
* @param aComponent the Component that is the basis for the focus
* traversal operation
* @see FocusTraversalPolicy
* @see Component#transferFocus
*/
public void focusNextComponent(Component aComponent) {
if (aComponent != null) {
aComponent.transferFocus();
}
}
/**
* Moves the focus up one focus traversal cycle. Typically, the focus owner
* is set to aComponent's focus cycle root, and the current focus cycle
* root is set to the new focus owner's focus cycle root. If, however,
* aComponent's focus cycle root is a Window, then the focus owner is set
* to the focus cycle root's default Component to focus, and the current
* focus cycle root is unchanged.
*
* @param aComponent the Component that is the basis for the focus
* traversal operation
* @see Component#transferFocusUpCycle
*/
public void upFocusCycle(Component aComponent) {
if (aComponent != null) {
aComponent.transferFocusUpCycle();
}
}
/**
* Moves the focus down one focus traversal cycle. If aContainer is a focus
* cycle root, then the focus owner is set to aContainer's default
* Component to focus, and the current focus cycle root is set to
* aContainer. If aContainer is not a focus cycle root, then no focus
* traversal operation occurs.
*
* @param aContainer the Container that is the basis for the focus
* traversal operation
* @see Container#transferFocusDownCycle
*/
public void downFocusCycle(Container aContainer) {
if (aContainer != null && aContainer.isFocusCycleRoot()) {
aContainer.transferFocusDownCycle();
}
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: BcePRCOpen.proto
package com.xinqihd.sns.gameserver.proto;
public final class XinqiBcePRCOpen {
private XinqiBcePRCOpen() {}
public static void registerAllExtensions(
com.google.protobuf.ExtensionRegistry registry) {
}
public interface BcePRCOpenOrBuilder
extends com.google.protobuf.MessageOrBuilder {
}
public static final class BcePRCOpen extends
com.google.protobuf.GeneratedMessage
implements BcePRCOpenOrBuilder {
// Use BcePRCOpen.newBuilder() to construct.
private BcePRCOpen(Builder builder) {
super(builder);
}
private BcePRCOpen(boolean noInit) {}
private static final BcePRCOpen defaultInstance;
public static BcePRCOpen getDefaultInstance() {
return defaultInstance;
}
public BcePRCOpen getDefaultInstanceForType() {
return defaultInstance;
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.xinqihd.sns.gameserver.proto.XinqiBcePRCOpen.internal_static_com_xinqihd_sns_gameserver_proto_BcePRCOpen_descriptor;
}
protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.xinqihd.sns.gameserver.proto.XinqiBcePRCOpen.internal_static_com_xinqihd_sns_gameserver_proto_BcePRCOpen_fieldAccessorTable;
}
private void initFields() {
}
private byte memoizedIsInitialized = -1;
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized != -1) return isInitialized == 1;
memoizedIsInitialized = 1;
return true;
}
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
getSerializedSize();
getUnknownFields().writeTo(output);
}
private int memoizedSerializedSize = -1;
public int getSerializedSize() {
int size = memoizedSerializedSize;
if (size != -1) return size;
size = 0;
size += getUnknownFields().getSerializedSize();
memoizedSerializedSize = size;
return size;
}
private static final long serialVersionUID = 0L;
@java.lang.Override
protected java.lang.Object writeReplace()
throws java.io.ObjectStreamException {
return super.writeReplace();
}
public static com.xinqihd.sns.gameserver.proto.XinqiBcePRCOpen.BcePRCOpen parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return newBuilder().mergeFrom(data).buildParsed();
}
public static com.xinqihd.sns.gameserver.proto.XinqiBcePRCOpen.BcePRCOpen parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return newBuilder().mergeFrom(data, extensionRegistry)
.buildParsed();
}
public static com.xinqihd.sns.gameserver.proto.XinqiBcePRCOpen.BcePRCOpen parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return newBuilder().mergeFrom(data).buildParsed();
}
public static com.xinqihd.sns.gameserver.proto.XinqiBcePRCOpen.BcePRCOpen parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return newBuilder().mergeFrom(data, extensionRegistry)
.buildParsed();
}
public static com.xinqihd.sns.gameserver.proto.XinqiBcePRCOpen.BcePRCOpen parseFrom(java.io.InputStream input)
throws java.io.IOException {
return newBuilder().mergeFrom(input).buildParsed();
}
public static com.xinqihd.sns.gameserver.proto.XinqiBcePRCOpen.BcePRCOpen parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return newBuilder().mergeFrom(input, extensionRegistry)
.buildParsed();
}
public static com.xinqihd.sns.gameserver.proto.XinqiBcePRCOpen.BcePRCOpen parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
Builder builder = newBuilder();
if (builder.mergeDelimitedFrom(input)) {
return builder.buildParsed();
} else {
return null;
}
}
public static com.xinqihd.sns.gameserver.proto.XinqiBcePRCOpen.BcePRCOpen parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
Builder builder = newBuilder();
if (builder.mergeDelimitedFrom(input, extensionRegistry)) {
return builder.buildParsed();
} else {
return null;
}
}
public static com.xinqihd.sns.gameserver.proto.XinqiBcePRCOpen.BcePRCOpen parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return newBuilder().mergeFrom(input).buildParsed();
}
public static com.xinqihd.sns.gameserver.proto.XinqiBcePRCOpen.BcePRCOpen parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return newBuilder().mergeFrom(input, extensionRegistry)
.buildParsed();
}
public static Builder newBuilder() { return Builder.create(); }
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder(com.xinqihd.sns.gameserver.proto.XinqiBcePRCOpen.BcePRCOpen prototype) {
return newBuilder().mergeFrom(prototype);
}
public Builder toBuilder() { return newBuilder(this); }
@java.lang.Override
protected Builder newBuilderForType(
com.google.protobuf.GeneratedMessage.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
public static final class Builder extends
com.google.protobuf.GeneratedMessage.Builder<Builder>
implements com.xinqihd.sns.gameserver.proto.XinqiBcePRCOpen.BcePRCOpenOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.xinqihd.sns.gameserver.proto.XinqiBcePRCOpen.internal_static_com_xinqihd_sns_gameserver_proto_BcePRCOpen_descriptor;
}
protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.xinqihd.sns.gameserver.proto.XinqiBcePRCOpen.internal_static_com_xinqihd_sns_gameserver_proto_BcePRCOpen_fieldAccessorTable;
}
// Construct using com.xinqihd.sns.gameserver.proto.XinqiBcePRCOpen.BcePRCOpen.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) {
}
}
private static Builder create() {
return new Builder();
}
public Builder clear() {
super.clear();
return this;
}
public Builder clone() {
return create().mergeFrom(buildPartial());
}
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return com.xinqihd.sns.gameserver.proto.XinqiBcePRCOpen.BcePRCOpen.getDescriptor();
}
public com.xinqihd.sns.gameserver.proto.XinqiBcePRCOpen.BcePRCOpen getDefaultInstanceForType() {
return com.xinqihd.sns.gameserver.proto.XinqiBcePRCOpen.BcePRCOpen.getDefaultInstance();
}
public com.xinqihd.sns.gameserver.proto.XinqiBcePRCOpen.BcePRCOpen build() {
com.xinqihd.sns.gameserver.proto.XinqiBcePRCOpen.BcePRCOpen result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
private com.xinqihd.sns.gameserver.proto.XinqiBcePRCOpen.BcePRCOpen buildParsed()
throws com.google.protobuf.InvalidProtocolBufferException {
com.xinqihd.sns.gameserver.proto.XinqiBcePRCOpen.BcePRCOpen result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(
result).asInvalidProtocolBufferException();
}
return result;
}
public com.xinqihd.sns.gameserver.proto.XinqiBcePRCOpen.BcePRCOpen buildPartial() {
com.xinqihd.sns.gameserver.proto.XinqiBcePRCOpen.BcePRCOpen result = new com.xinqihd.sns.gameserver.proto.XinqiBcePRCOpen.BcePRCOpen(this);
onBuilt();
return result;
}
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.xinqihd.sns.gameserver.proto.XinqiBcePRCOpen.BcePRCOpen) {
return mergeFrom((com.xinqihd.sns.gameserver.proto.XinqiBcePRCOpen.BcePRCOpen)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.xinqihd.sns.gameserver.proto.XinqiBcePRCOpen.BcePRCOpen other) {
if (other == com.xinqihd.sns.gameserver.proto.XinqiBcePRCOpen.BcePRCOpen.getDefaultInstance()) return this;
this.mergeUnknownFields(other.getUnknownFields());
return this;
}
public final boolean isInitialized() {
return true;
}
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
com.google.protobuf.UnknownFieldSet.Builder unknownFields =
com.google.protobuf.UnknownFieldSet.newBuilder(
this.getUnknownFields());
while (true) {
int tag = input.readTag();
switch (tag) {
case 0:
this.setUnknownFields(unknownFields.build());
onChanged();
return this;
default: {
if (!parseUnknownField(input, unknownFields,
extensionRegistry, tag)) {
this.setUnknownFields(unknownFields.build());
onChanged();
return this;
}
break;
}
}
}
}
// @@protoc_insertion_point(builder_scope:com.xinqihd.sns.gameserver.proto.BcePRCOpen)
}
static {
defaultInstance = new BcePRCOpen(true);
defaultInstance.initFields();
}
// @@protoc_insertion_point(class_scope:com.xinqihd.sns.gameserver.proto.BcePRCOpen)
}
private static com.google.protobuf.Descriptors.Descriptor
internal_static_com_xinqihd_sns_gameserver_proto_BcePRCOpen_descriptor;
private static
com.google.protobuf.GeneratedMessage.FieldAccessorTable
internal_static_com_xinqihd_sns_gameserver_proto_BcePRCOpen_fieldAccessorTable;
public static com.google.protobuf.Descriptors.FileDescriptor
getDescriptor() {
return descriptor;
}
private static com.google.protobuf.Descriptors.FileDescriptor
descriptor;
static {
java.lang.String[] descriptorData = {
"\n\020BcePRCOpen.proto\022 com.xinqihd.sns.game" +
"server.proto\"\014\n\nBcePRCOpenB\021B\017XinqiBcePR" +
"COpen"
};
com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner =
new com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner() {
public com.google.protobuf.ExtensionRegistry assignDescriptors(
com.google.protobuf.Descriptors.FileDescriptor root) {
descriptor = root;
internal_static_com_xinqihd_sns_gameserver_proto_BcePRCOpen_descriptor =
getDescriptor().getMessageTypes().get(0);
internal_static_com_xinqihd_sns_gameserver_proto_BcePRCOpen_fieldAccessorTable = new
com.google.protobuf.GeneratedMessage.FieldAccessorTable(
internal_static_com_xinqihd_sns_gameserver_proto_BcePRCOpen_descriptor,
new java.lang.String[] { },
com.xinqihd.sns.gameserver.proto.XinqiBcePRCOpen.BcePRCOpen.class,
com.xinqihd.sns.gameserver.proto.XinqiBcePRCOpen.BcePRCOpen.Builder.class);
return null;
}
};
com.google.protobuf.Descriptors.FileDescriptor
.internalBuildGeneratedFileFrom(descriptorData,
new com.google.protobuf.Descriptors.FileDescriptor[] {
}, assigner);
}
// @@protoc_insertion_point(outer_class_scope)
}
| |
/**
* CommonFramework 7.x Connector
*
* Copyright (C) 2017 Black Duck Software, Inc.
* http://www.blackducksoftware.com/
*
* 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 com.blackducksoftware.tools.connector.protex;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.blackducksoftware.sdk.fault.SdkFault;
import com.blackducksoftware.sdk.protex.license.LicenseCategory;
import com.blackducksoftware.sdk.protex.project.ProjectApi;
import com.blackducksoftware.sdk.protex.project.ProjectInfo;
import com.blackducksoftware.sdk.protex.project.ProjectRequest;
import com.blackducksoftware.tools.commonframework.core.config.ConfigConstants.APPLICATION;
import com.blackducksoftware.tools.commonframework.core.config.ConfigurationManager;
import com.blackducksoftware.tools.commonframework.core.config.server.ServerBean;
import com.blackducksoftware.tools.commonframework.core.exception.CommonFrameworkException;
import com.blackducksoftware.tools.commonframework.standard.common.ProjectPojo;
import com.blackducksoftware.tools.commonframework.standard.protex.ProtexProjectPojo;
import com.blackducksoftware.tools.connector.common.ILicenseManager;
import com.blackducksoftware.tools.connector.protex.component.IProtexComponentManager;
import com.blackducksoftware.tools.connector.protex.component.ProtexComponentManager;
import com.blackducksoftware.tools.connector.protex.license.LicenseManager;
import com.blackducksoftware.tools.connector.protex.license.ProtexLicensePojo;
import com.blackducksoftware.tools.connector.protex.obligation.IObligationManager;
import com.blackducksoftware.tools.connector.protex.obligation.ObligationManager;
import com.blackducksoftware.tools.connector.protex.project.IProjectManager;
import com.blackducksoftware.tools.connector.protex.project.ProjectManager;
import com.blackducksoftware.tools.connector.protex.report.IReportManager;
import com.blackducksoftware.tools.connector.protex.report.ReportManager;
/**
* Wrapper class around the Protex Server that provides common methods. This is
* the primary class for SDK access.
*
* @author akamen
*
*/
public class ProtexServerWrapper<T extends ProtexProjectPojo> implements
IProtexServerWrapper<T> {
/** The log. */
private final Logger log = LoggerFactory.getLogger(this.getClass()
.getName());
private ILicenseManager<ProtexLicensePojo> licenseManager;
private IReportManager reportManager;
private IProjectManager projectManager;
private IProtexComponentManager componentManager;
private IObligationManager obligationManager;
/** The api wrapper. */
private ProtexAPIWrapper apiWrapper;
/** The config manager. */
private ConfigurationManager configManager;
private ServerBean serverBean;
/**
* Assistors These are the static helpers that contain code that pertain to
* a specific type of operation.
*/
private CodeTreeHelper codeTreeHelper;
public ProtexServerWrapper() {
}
/**
* Deprecated as of 1.6.5, use the simpler constructor.
*
* @param bean
* @param manager
* @param validate
* @throws Exception
*/
@Deprecated
public ProtexServerWrapper(ServerBean bean, ConfigurationManager manager,
boolean validate) throws Exception
{
initialize(bean, manager, validate);
}
public ProtexServerWrapper(ConfigurationManager manager,
boolean validate) throws Exception
{
ServerBean bean = manager.getServerBean(APPLICATION.PROTEX);
initialize(bean, manager, validate);
}
private void initialize(ServerBean bean, ConfigurationManager manager, boolean validate) throws Exception {
ServerBean protexBean = manager.getServerBean(APPLICATION.PROTEX);
if (protexBean == null) {
throw new Exception("No connection available for Protex");
}
serverBean = protexBean;
configManager = manager;
apiWrapper = new ProtexAPIWrapper(manager, validate);
// Sets all the APIs
codeTreeHelper = new CodeTreeHelper(apiWrapper);
licenseManager = new LicenseManager(apiWrapper);
obligationManager = new ObligationManager(apiWrapper);
reportManager = new ReportManager(apiWrapper);
componentManager = new ProtexComponentManager(apiWrapper,
licenseManager);
projectManager = new ProjectManager(apiWrapper, componentManager);
}
@Override
public CodeTreeHelper getCodeTreeHelper() {
return codeTreeHelper;
}
@Override
public ProjectPojo getProjectByName(String projectName)
throws CommonFrameworkException {
return projectManager.getProjectByName(projectName);
}
@Override
public ProjectPojo getProjectByID(String projectID)
throws CommonFrameworkException {
return projectManager.getProjectById(projectID);
}
// TODO: Get rid of this!
@Override
public String getProjectURL(ProjectPojo pojo) {
String bomUrl = serverBean.getServerName()
+ "/protex/ProtexIPIdentifyFolderBillOfMaterialsContainer?isAtTop=true&ProtexIPProjectId="
+ pojo.getProjectKey()
+ "&ProtexIPIdentifyFileViewLevel=folder&ProtexIPIdentifyFileId=-1";
log.debug("Built URL for project: " + bomUrl);
return bomUrl;
}
@Override
public <T> List<T> getProjects(Class<T> theProjectClass) throws Exception {
ArrayList<T> projectList = new ArrayList<T>();
try {
ProjectApi projectAPI = apiWrapper.getProjectApi();
String userName = configManager.getServerBean(APPLICATION.PROTEX).getUserName();
if (userName == null || userName.length() == 0) {
userName = serverBean.getUserName();
}
List<ProjectInfo> project_list_info = projectAPI
.getProjectsByUser(userName);
for (ProjectInfo project : project_list_info) {
if (project != null) {
String projName = project.getName();
String projID = project.getProjectId();
T projPojo = (T) generateNewInstance(theProjectClass);
// Set the basic
((ProtexProjectPojo) projPojo).setProjectKey(projID);
((ProtexProjectPojo) projPojo).setProjectName(projName);
projectList.add(projPojo);
}
}
} catch (SdkFault sf) {
// Try to explain why this has failed...messy, but could save time
// and aggravation
String message = sf.getMessage();
if (message != null) {
if (message.contains("role")) {
throw new Exception(
"You do not have enough permission to list projects, you must be at least a 'Manager' to perform this task");
}
} else {
throw new Exception("Error getting project list", sf);
}
} catch (Throwable t) {
if (t instanceof javax.xml.ws.soap.SOAPFaultException) {
throw new Exception("There *may* be problem with SDK", t);
} else if (t instanceof javax.xml.ws.WebServiceException) {
throw new Exception(
"There *may* be problem with the connection. The URL specified cannot be reached!",
t);
} else {
throw new Exception("General error, cannot continue! Error: ",
t);
}
}
return projectList;
}
@Override
public String createProject(String projectName, String description)
throws Exception {
String projectID = "";
ProjectRequest projectRequest = new ProjectRequest();
projectRequest.setName(projectName);
if (description != null) {
projectRequest.setDescription(description);
}
try {
ProjectApi projectAPI = apiWrapper.getProjectApi();
projectID = projectAPI.createProject(projectRequest,
LicenseCategory.PROPRIETARY);
} catch (SdkFault e) {
throw new Exception(e.getMessage());
}
return projectID;
}
@Override
public ProtexAPIWrapper getInternalApiWrapper() {
return apiWrapper;
}
@Override
public ConfigurationManager getConfigManager() {
return this.configManager;
}
private T generateNewInstance(Class<?> theProjectClass) throws Exception {
T pojo = null;
Constructor<?> constructor = null;
;
try {
constructor = theProjectClass.getConstructor();
} catch (SecurityException e) {
throw new Exception(e.getMessage());
} catch (NoSuchMethodException e) {
throw new Exception(e.getMessage());
}
try {
pojo = (T) constructor.newInstance();
} catch (IllegalArgumentException e) {
throw new Exception(e.getMessage());
} catch (InstantiationException e) {
throw new Exception(e.getMessage());
} catch (IllegalAccessException e) {
throw new Exception(e.getMessage());
} catch (InvocationTargetException e) {
throw new Exception(e.getMessage());
}
return pojo;
}
@Override
public ILicenseManager<ProtexLicensePojo> getLicenseManager() {
return licenseManager;
}
@Override
public IReportManager getReportManager() {
return reportManager;
}
@Override
public IProjectManager getProjectManager() {
return projectManager;
}
@Override
public IProtexComponentManager getComponentManager() {
return componentManager;
}
@Override
public IObligationManager getObligationManager() {
return obligationManager;
}
}
| |
/*
* Copyright (C) 2009 IT Wizard.
* http://www.itwizard.ro
*
* 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.itwizard.mezzofanti;
import pfg.uem.biocon.R;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.CheckBoxPreference;
import android.preference.EditTextPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.Preference.OnPreferenceClickListener;
import android.preference.PreferenceScreen;
import android.util.Log;
import android.view.KeyEvent;
import android.view.WindowManager;
import com.itwizard.mezzofanti.LanguageDialog.LDActivity;
import com.itwizard.mezzofanti.Languages.Language;
/**
* This activity implements the Settings/Menu button.
*
*/
public final class PreferenciasActivity extends android.preference.PreferenceActivity
implements OnSharedPreferenceChangeListener, LDActivity
{
private static final String TAG = "MLOG: PreferencesActivity.java: ";
private ProgressDialog m_ProgressDialog = null; // local progress dialog for language download
private DownloadManager m_DownloadManager = null; // the download manager (for the langs)
private SharedPreferences m_AppSharedPrefs = null; // the application shared preferences,
// used to save/load the settings that are not visible in the menu
public static final String KEY_SKIP_INTRO_AT_STARTUP = "preferences_skip_intro_at_startup";
public static final String KEY_USE_IMAGE_LIGHT_FILTER = "preferences_use_image_ligth_filter";
public static final String KEY_SPEED_QUALITY = "preferences_speed_quality";
public static final String KEY_SET_OCR_LANGUAGE = "preferences_set_OCR_language";
public static final String KEY_DOWNLOAD_LANGUAGE = "preferences_download_language";
public static final String KEY_MIN_OVERALL_CONFIDENCE = "preferences_min_overall_confidence";
public static final String KEY_MIN_WORD_CONFIDENCE = "preferences_min_word_confidence";
public static final String KEY_RESTORE_FACTORY_SETTINGS = "preferences_restore_factory_settings";
public static final String KEY_TRANSLATE_FROM_SETTINGS = "preferences_translate_from";
public static final String KEY_TRANSLATE_TO_SETTINGS = "preferences_translate_to";
// the options in the menu
private CheckBoxPreference m_cbpSkipIntroAtStartup;
private CheckBoxPreference m_cbpUseImageLightFilter;
private ListPreference m_lpSpeedQuality;
private ListPreference m_lpSetOcrLanguage;
private ListPreference m_lpDownloadLanguage;
private EditTextPreference m_etpMinOverallConfidence;
private EditTextPreference m_etpMinWordConfidence;
private Preference m_pfRestoreFactorySettings;
private Preference m_pfTranslateFromLang;
private Preference m_pfTranslateToLang;
@Override
protected void onCreate(Bundle icicle)
{
try
{
super.onCreate(icicle);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
addPreferencesFromResource(R.layout.preferencias);
PreferenceScreen preferences = getPreferenceScreen();
m_AppSharedPrefs = preferences.getSharedPreferences();
preferences.getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
m_cbpSkipIntroAtStartup = (CheckBoxPreference) preferences.findPreference(KEY_SKIP_INTRO_AT_STARTUP);
m_cbpUseImageLightFilter = (CheckBoxPreference) preferences.findPreference(KEY_USE_IMAGE_LIGHT_FILTER);
m_lpSpeedQuality = (ListPreference) preferences.findPreference(KEY_SPEED_QUALITY);
m_lpSetOcrLanguage = (ListPreference) preferences.findPreference(KEY_SET_OCR_LANGUAGE);
m_lpDownloadLanguage = (ListPreference) preferences.findPreference(KEY_DOWNLOAD_LANGUAGE);
m_etpMinOverallConfidence = (EditTextPreference) preferences.findPreference(KEY_MIN_OVERALL_CONFIDENCE);
m_etpMinWordConfidence = (EditTextPreference) preferences.findPreference(KEY_MIN_WORD_CONFIDENCE);
m_pfRestoreFactorySettings = (Preference) preferences.findPreference(KEY_RESTORE_FACTORY_SETTINGS);
m_pfTranslateFromLang = (Preference) preferences.findPreference(KEY_TRANSLATE_FROM_SETTINGS);
m_pfTranslateToLang = (Preference) preferences.findPreference(KEY_TRANSLATE_TO_SETTINGS);
m_etpMinOverallConfidence.setOnPreferenceChangeListener(new OnPreferenceChangeListener(){
public boolean onPreferenceChange(Preference preference,
Object newValue)
{
Log.v(TAG, "onPreferenceChange m_etpMinOverallConfidence --------------------------");
Message message = m_LocalMessageHandler.obtainMessage(R.id.preferences_MinOverallConfidence, null);
message.sendToTarget();
return true;
}
});
m_etpMinWordConfidence.setOnPreferenceChangeListener(new OnPreferenceChangeListener()
{
public boolean onPreferenceChange(Preference preference,
Object newValue)
{
Log.v(TAG, "onPreferenceChange m_etpMinWordConfidence--------------------------");
Message message = m_LocalMessageHandler.obtainMessage(R.id.preferences_MinWordConfidence, null);
message.sendToTarget();
return true;
}
});
m_pfRestoreFactorySettings.setOnPreferenceClickListener(new OnPreferenceClickListener()
{
public boolean onPreferenceClick(Preference preference) {
Log.v(TAG, "setOnPreferenceClickListener CLICK");
ShowRestoreFactorySettingsDialog();
return false;
}
});
String langfrom = m_AppSharedPrefs.getString(KEY_TRANSLATE_FROM_SETTINGS, Languages.Language.ENGLISH.getLongName());
m_pfTranslateFromLang.setTitle(this.getString(R.string.preferences_translate_from_settings) + ": " + langfrom);
m_pfTranslateFromLang.setOnPreferenceClickListener(new OnPreferenceClickListener()
{
public boolean onPreferenceClick(Preference preference) {
Log.v(TAG, "setOnPreferenceClickListener CLICK");
ShowLanaguageDialog(true);
return false;
}
});
String langto = m_AppSharedPrefs.getString(KEY_TRANSLATE_TO_SETTINGS, Languages.Language.SPANISH.getLongName());
m_pfTranslateToLang.setTitle(this.getString(R.string.preferences_translate_to_settings) + ": " + langto);
m_pfTranslateToLang.setOnPreferenceClickListener(new OnPreferenceClickListener()
{
public boolean onPreferenceClick(Preference preference) {
Log.v(TAG, "setOnPreferenceClickListener CLICK");
ShowLanaguageDialog(false);
return false;
}
});
m_DownloadManager = new DownloadManager();
m_DownloadManager.SetMessageHandler(m_LocalMessageHandler);
CreateDownloadableLangsSubMenu();
CreateSettingsMenu();
}
catch (Exception ex)
{
Log.v(TAG, "exception: " + ex.toString());
}
}
/**
* Show the language dialog for selecting the language by flag.
* @param from true=language_from false=language_to
*/
private void ShowLanaguageDialog(boolean from)
{
LanguageDialog ld = new LanguageDialog(this);
ld.SetFrom(from);
ld.show();
}
/**
* Show an alert on the screen.
* @param title the alert title
* @param message the alert body
*/
private void ShowAlert(String title, String message)
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(title);
builder.setMessage(message);
builder.setPositiveButton(R.string.preferences_restore_factory_settings_button_ok, null);
builder.show();
}
/**
* display a dialog to ask for the "Restore-factory-settings" approval
*/
private void ShowRestoreFactorySettingsDialog()
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setIcon(R.drawable.alert32);
builder.setTitle(R.string.preferencesactivity_rfs_title);
builder.setMessage(R.string.preferencesactivity_rfs_body);
builder.setPositiveButton(R.string.preferences_restore_factory_settings_button_ok, m_pfRestoreFactorySettingsListener);
builder.setNegativeButton(R.string.preferences_restore_factory_settings_button_cancel, null);
builder.show();
}
/**
* if the restore-factory-settings button is pressed
*/
private final DialogInterface.OnClickListener m_pfRestoreFactorySettingsListener = new DialogInterface.OnClickListener()
{
public void onClick(android.content.DialogInterface dialogInterface, int i)
{
Log.v(TAG, "do restore factory settings");
OCR.mConfig.LoadFabricDefaults();
Log.v(TAG, "m_pfRestoreFactorySettingsListener: " + OCR.mConfig.GetLanguage());
CreateSettingsMenu();
}
};
/**
* create the settings menu
*/
private void CreateSettingsMenu()
{
try
{
// get settings from file and set it
m_cbpSkipIntroAtStartup.setChecked(Mezzofanti.m_bSkipIntroAtStartup);
m_cbpUseImageLightFilter.setChecked(OCR.mConfig.m_bUseBWFilter);
CharSequence entries[] = new CharSequence[2];
CharSequence entriesLarge[] = new CharSequence[2];
entriesLarge[0] = getString(R.string.preferencesactivity_imgsz_optimal);
entriesLarge[1] = getString(R.string.preferencesactivity_imgsz_medium);
entries[0] = "2";
entries[1] = "4";
m_lpSpeedQuality.setEntries(entriesLarge);
m_lpSpeedQuality.setEntryValues(entries);
m_lpSpeedQuality.setValue("" + OCR.mConfig.GetImgDivisor());
CreateValidLangsSubMenu();
m_etpMinOverallConfidence.setText("" + OCR.mConfig.m_iMinOveralConfidence);
m_etpMinWordConfidence.setText("" + OCR.mConfig.m_iMinWordConfidence);
}
catch (Exception ex)
{
Log.v(TAG, "Exception: " + ex.toString());
}
}
/**
* Create the downloadable-languages submenu.
*/
private void CreateDownloadableLangsSubMenu()
{
if (m_DownloadManager.DownloadLanguageBrief(Mezzofanti.DOWNLOAD_URL, "languages.txt"))
{
// downloaded file correctly
OCR.ReadAvailableLanguages();
int len = m_DownloadManager.m_ServerLanguages.length;
CharSequence entriesLarge[] = new CharSequence[len];
CharSequence entries[] = new CharSequence[len];
for (int i=0; i<len; i++)
{
if (OCR.mConfig.IsLanguageInstalled(m_DownloadManager.m_ServerLanguages[i].sExtName))
entriesLarge[i] = m_DownloadManager.m_ServerLanguages[i].sFullName + " - " + (m_DownloadManager.m_ServerLanguages[i].lDownloadSz/1024) + "KB" + getString(R.string.preferencesactivity_reinstall);
else
entriesLarge[i] = m_DownloadManager.m_ServerLanguages[i].sFullName + " - " + (m_DownloadManager.m_ServerLanguages[i].lDownloadSz/1024) + "KB";
entries[i] = "" + i;
}
m_lpDownloadLanguage.setEntries(entriesLarge);
m_lpDownloadLanguage.setEntryValues(entries);
m_lpDownloadLanguage.setOnPreferenceChangeListener(
new OnPreferenceChangeListener()
{
//@Override
public boolean onPreferenceChange(Preference preference, Object newValue)
{
m_LocalMessageHandler.sendEmptyMessage(R.id.preferences_selectedLang2Download);
return true;
}
}
);
}
else
{
CharSequence entriesLarge[] = new CharSequence[1];
entriesLarge[0] = getString(R.string.preferencesactivity_cannotaccessinternet);
m_lpDownloadLanguage.setEntries(entriesLarge);
m_lpDownloadLanguage.setEntryValues(entriesLarge);
ShowAlert(getString(R.string.preferencesactivity_warning), getString(R.string.preferencesactivity_problems));
}
}
/**
* Create the available-languages submenu.
*/
private void CreateValidLangsSubMenu()
{
OCR.ReadAvailableLanguages();
String[] svLangs = OCR.mConfig.GetvLanguages();
m_lpSetOcrLanguage.setEntries(svLangs);
m_lpSetOcrLanguage.setEntryValues(OCR.mConfig.m_asLanguages);
m_lpSetOcrLanguage.setValue(OCR.mConfig.GetLanguage());
}
/**
* show the range dialog for the "confidence" selectors
*/
private void ShowRangeDialog()
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setIcon(R.drawable.alert32);
builder.setTitle(R.string.preferencesactivity_rangedialog_title);
builder.setMessage(R.string.preferencesactivity_rangedialog_body);
builder.setPositiveButton(R.string.preferences_button_cancel, null);
builder.show();
}
/**
* the local message handler
*/
private Handler m_LocalMessageHandler = new Handler()
{
@Override
public void handleMessage(Message msg)
{
switch(msg.what)
{
// download manager started unziping
case R.id.downloadmanager_unziping:
m_ProgressDialog.setMessage(getString(R.string.preferencesactivity_pd_body2));
break;
// download manager finished with an error
case R.id.downloadmanager_downloadFinishedError:
m_ProgressDialog.dismiss();
ShowAlert(getString(R.string.preferencesactivity_download_title), getString(R.string.preferencesactivity_downloaderr_body));
break;
// download manager finished with an error
case R.id.downloadmanager_downloadFinishedErrorSdcard:
m_ProgressDialog.dismiss();
ShowAlert(getString(R.string.preferencesactivity_download_title), getString(R.string.preferencesactivity_downloaderrsdcard_body));
break;
// download manager finished ok
case R.id.downloadmanager_downloadFinishedOK:
m_ProgressDialog.dismiss();
CreateValidLangsSubMenu();
CreateDownloadableLangsSubMenu();
ShowAlert(getString(R.string.preferencesactivity_download_title), getString(R.string.preferencesactivity_downloadok_body));
int index = Integer.parseInt(m_lpDownloadLanguage.getValue());
String lang = m_DownloadManager.m_ServerLanguages[index].sExtName;
Log.v(TAG, "Installed " + lang);
OCR.get().SetLanguage(lang);
// save lang in file
SharedPreferences.Editor spe = m_AppSharedPrefs.edit();
spe.putString(KEY_SET_OCR_LANGUAGE, lang);
spe.commit();
Log.v(TAG, "mconfig lang=" + OCR.mConfig.GetLanguageMore());
break;
// user selected a language to download
case R.id.preferences_selectedLang2Download:
m_DownloadManager.DownloadLanguageJob(Integer.parseInt(m_lpDownloadLanguage.getValue()));
CreateProgressDialog(m_lpDownloadLanguage.getEntry());
m_DownloadManager.SetProgressDialog(m_ProgressDialog);
break;
// user wants to set the confidence
case R.id.preferences_MinOverallConfidence:
try
{
if ( Integer.parseInt(m_etpMinOverallConfidence.getText()) >=0 && Integer.parseInt(m_etpMinOverallConfidence.getText()) <=100)
{
Log.v("TEST",">" + Integer.parseInt(m_etpMinOverallConfidence.getText()));
}
else
{
Log.v("TEST",">" + Integer.parseInt(m_etpMinOverallConfidence.getText()));
ShowRangeDialog();
// set default value
m_etpMinOverallConfidence.setText("60");
}
}
catch(Exception e)
{
Log.v("TEST",">" + Integer.parseInt(m_etpMinOverallConfidence.getText()));
ShowRangeDialog();
// set default value
m_etpMinOverallConfidence.setText("60");
}
break;
// user wants to set the confidence
case R.id.preferences_MinWordConfidence:
try
{
if ( Integer.parseInt(m_etpMinWordConfidence.getText()) >=0 && Integer.parseInt(m_etpMinWordConfidence.getText()) <=100)
{
Log.v("TEST",">" + Integer.parseInt(m_etpMinWordConfidence.getText()));
}
else
{
Log.v("TEST",">" + Integer.parseInt(m_etpMinWordConfidence.getText()));
ShowRangeDialog();
// set default value
m_etpMinWordConfidence.setText("50");
}
}
catch(Exception e)
{
Log.v("TEST",">" + Integer.parseInt(m_etpMinWordConfidence.getText()));
ShowRangeDialog();
// set default value
m_etpMinWordConfidence.setText("50");
}
break;
}
}
};
/**
* create a progress dialog for the download menu
* @param lang the language that is downloaded
*/
private void CreateProgressDialog(CharSequence lang)
{
m_ProgressDialog = new ProgressDialog(this);
m_ProgressDialog.setTitle(R.string.preferencesactivity_pd_title);
m_ProgressDialog.setMessage(getString(R.string.preferencesactivity_pd_body1) + " " + lang);
m_ProgressDialog.setCancelable(true);
m_ProgressDialog.setMax(100);
m_ProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
m_ProgressDialog.show();
m_ProgressDialog.setOnCancelListener(new OnCancelListener() {
public void onCancel(DialogInterface dialog)
{
m_DownloadManager.CancelDownload();
}
});
}
//@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
// TODO Auto-generated method stub
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
if ( keyCode == KeyEvent.KEYCODE_BACK )
{ // if "BACK-KEY" pressed
if (event.getRepeatCount() == 0)
{
finish();
}
}
return super.onKeyDown(keyCode, event);
}
/**
* user selected a translate-language from settings
*/
public void SetNewLanguage(Language language, boolean from)
{
SharedPreferences.Editor spe = m_AppSharedPrefs.edit();
if (from)
{
String fromName = language.getLongName();
Log.v(TAG, "Set lang-from: " + fromName);
spe.putString(KEY_TRANSLATE_FROM_SETTINGS, fromName);
m_pfTranslateFromLang.setTitle(this.getString(R.string.preferences_translate_from_settings) + ": " + fromName);
}
else
{
String toName = language.getLongName();
Log.v(TAG, "Set lang-in: " + toName);
spe.putString(KEY_TRANSLATE_TO_SETTINGS, toName);
m_pfTranslateToLang.setTitle(this.getString(R.string.preferences_translate_to_settings) + ": " + toName);
}
spe.commit();
}
}
| |
package cz.metacentrum.perun.core.blImpl;
import cz.metacentrum.perun.core.api.PerunClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import cz.metacentrum.perun.core.api.AttributesManager;
import cz.metacentrum.perun.core.api.AuditMessagesManager;
import cz.metacentrum.perun.core.api.BeansUtils;
import cz.metacentrum.perun.core.api.DatabaseManager;
import cz.metacentrum.perun.core.api.ExtSource;
import cz.metacentrum.perun.core.api.ExtSourcesManager;
import cz.metacentrum.perun.core.api.FacilitiesManager;
import cz.metacentrum.perun.core.api.GroupsManager;
import cz.metacentrum.perun.core.api.MembersManager;
import cz.metacentrum.perun.core.api.OwnersManager;
import cz.metacentrum.perun.core.api.Perun;
import cz.metacentrum.perun.core.api.PerunPrincipal;
import cz.metacentrum.perun.core.api.PerunSession;
import cz.metacentrum.perun.core.api.RTMessagesManager;
import cz.metacentrum.perun.core.api.ResourcesManager;
import cz.metacentrum.perun.core.api.Searcher;
import cz.metacentrum.perun.core.api.SecurityTeamsManager;
import cz.metacentrum.perun.core.api.ServicesManager;
import cz.metacentrum.perun.core.api.UserExtSource;
import cz.metacentrum.perun.core.api.UsersManager;
import cz.metacentrum.perun.core.api.VosManager;
import cz.metacentrum.perun.core.api.exceptions.ExtSourceNotExistsException;
import cz.metacentrum.perun.core.api.exceptions.InternalErrorException;
import cz.metacentrum.perun.core.api.exceptions.UserExtSourceNotExistsException;
import cz.metacentrum.perun.core.api.exceptions.UserNotExistsException;
import cz.metacentrum.perun.core.bl.AttributesManagerBl;
import cz.metacentrum.perun.core.bl.AuditMessagesManagerBl;
import cz.metacentrum.perun.core.bl.AuthzResolverBl;
import cz.metacentrum.perun.core.bl.DatabaseManagerBl;
import cz.metacentrum.perun.core.bl.ExtSourcesManagerBl;
import cz.metacentrum.perun.core.bl.FacilitiesManagerBl;
import cz.metacentrum.perun.core.bl.GroupsManagerBl;
import cz.metacentrum.perun.core.bl.MembersManagerBl;
import cz.metacentrum.perun.core.bl.ModulesUtilsBl;
import cz.metacentrum.perun.core.bl.OwnersManagerBl;
import cz.metacentrum.perun.core.bl.PerunBl;
import cz.metacentrum.perun.core.bl.RTMessagesManagerBl;
import cz.metacentrum.perun.core.bl.ResourcesManagerBl;
import cz.metacentrum.perun.core.bl.SearcherBl;
import cz.metacentrum.perun.core.bl.SecurityTeamsManagerBl;
import cz.metacentrum.perun.core.bl.ServicesManagerBl;
import cz.metacentrum.perun.core.bl.UsersManagerBl;
import cz.metacentrum.perun.core.bl.VosManagerBl;
import cz.metacentrum.perun.core.impl.Auditer;
import cz.metacentrum.perun.core.impl.PerunSessionImpl;
import java.util.HashSet;
import java.util.Set;
/**
* Implementation of Perun.
*
* @author Martin Kuba makub@ics.muni.cz
*/
public class PerunBlImpl implements PerunBl {
private VosManager vosManager = null;
private UsersManager usersManager = null;
private MembersManager membersManager = null;
private GroupsManager groupsManager = null;
private FacilitiesManager facilitiesManager = null;
private DatabaseManager databaseManager = null;
private ResourcesManager resourcesManager = null;
private ExtSourcesManager extSourcesManager = null;
private AttributesManager attributesManager = null;
private ServicesManager servicesManager = null;
private OwnersManager ownersManager = null;
private AuditMessagesManager auditMessagesManager = null;
private RTMessagesManager rtMessagesManager = null;
private SecurityTeamsManager securityTeamsManager = null;
private Searcher searcher = null;
private ModulesUtilsBl modulesUtilsBl = null;
private VosManagerBl vosManagerBl = null;
private UsersManagerBl usersManagerBl = null;
private MembersManagerBl membersManagerBl = null;
private GroupsManagerBl groupsManagerBl = null;
private FacilitiesManagerBl facilitiesManagerBl = null;
private DatabaseManagerBl databaseManagerBl = null;
private ResourcesManagerBl resourcesManagerBl = null;
private ExtSourcesManagerBl extSourcesManagerBl = null;
private AttributesManagerBl attributesManagerBl = null;
private ServicesManagerBl servicesManagerBl = null;
private OwnersManagerBl ownersManagerBl = null;
private AuditMessagesManagerBl auditMessagesManagerBl = null;
private RTMessagesManagerBl rtMessagesManagerBl = null;
private SecurityTeamsManagerBl securityTeamsManagerBl = null;
private AuthzResolverBl authzResolverBl = null;
private SearcherBl searcherBl = null;
private Auditer auditer = null;
final static Logger log = LoggerFactory.getLogger(PerunBlImpl.class);
final static Set<String> dontLookupUsersForLogins = new HashSet<>();
// fill list of logins we don't want to lookup users for
static {
String propValue = null;
try {
propValue = BeansUtils.getPropertyFromConfiguration("perun.dont.lookup.users");
} catch (InternalErrorException e) {
log.error("Unable to load logins for which we don't lookup users");
}
if (propValue != null) {
String[] dontLogins = propValue.split(",");
for (String str : dontLogins) {
dontLookupUsersForLogins.add(str.trim());
}
}
}
public PerunBlImpl() {
}
public PerunSession getPerunSession(PerunPrincipal principal, PerunClient client) throws InternalErrorException {
if (principal.getUser() == null &&
this.getUsersManagerBl() != null &&
!dontLookupUsersForLogins.contains(principal.getActor())) {
// Get the user if we are completely initialized
try {
principal.setUser(this.getUsersManagerBl().getUserByExtSourceNameAndExtLogin(getPerunSession(), principal.getExtSourceName(), principal.getActor()));
// Try to update LoA for userExtSource
ExtSource es = this.getExtSourcesManagerBl().getExtSourceByName(getPerunSession(), principal.getExtSourceName());
UserExtSource ues = this.getUsersManagerBl().getUserExtSourceByExtLogin(getPerunSession(), es, principal.getActor());
if (ues.getLoa() != principal.getExtSourceLoa()) {
ues.setLoa(principal.getExtSourceLoa());
this.getUsersManagerBl().updateUserExtSource(getPerunSession(), ues);
}
// Update last access for userExtSource
this.getUsersManagerBl().updateUserExtSourceLastAccess(getPerunSession(), ues);
} catch (ExtSourceNotExistsException e) {
// OK - We don't know user yet
} catch (UserExtSourceNotExistsException e) {
// OK - We don't know user yet
} catch (UserNotExistsException e) {
// OK - We don't know user yet
}
}
return new PerunSessionImpl(this, principal, client);
}
/**
* This method is used only internally.
*
* @return
* @throws InternalErrorException
*/
public PerunSession getPerunSession() throws InternalErrorException {
PerunPrincipal principal = new PerunPrincipal(INTERNALPRINCIPAL, ExtSourcesManager.EXTSOURCE_NAME_INTERNAL, ExtSourcesManager.EXTSOURCE_INTERNAL);
PerunClient client = new PerunClient();
return new PerunSessionImpl(this, principal, client);
}
public GroupsManager getGroupsManager() {
return groupsManager;
}
public FacilitiesManager getFacilitiesManager() {
return facilitiesManager;
}
public DatabaseManager getDatabaseManager() {
return databaseManager;
}
public UsersManager getUsersManager() {
return usersManager;
}
public MembersManager getMembersManager() {
return membersManager;
}
public VosManager getVosManager() {
return vosManager;
}
public ResourcesManager getResourcesManager() {
return resourcesManager;
}
public RTMessagesManager getRTMessagesManager() {
return rtMessagesManager;
}
public void setRTMessagesManager(RTMessagesManager rtMessagesManager) {
this.rtMessagesManager = rtMessagesManager;
}
public SecurityTeamsManager getSecurityTeamsManager() {
return securityTeamsManager;
}
public void setSecurityTeamsManager(SecurityTeamsManager securityTeamsManager) {
this.securityTeamsManager = securityTeamsManager;
}
public void setVosManager(VosManager vosManager) {
this.vosManager = vosManager;
}
public void setUsersManager(UsersManager usersManager) {
this.usersManager = usersManager;
}
public void setAuditMessagesManager(AuditMessagesManager auditMessagesManager) {
this.auditMessagesManager = auditMessagesManager;
}
public void setAuditMessagesManagerBl(AuditMessagesManagerBl auditMessagesManagerBl) {
this.auditMessagesManagerBl = auditMessagesManagerBl;
}
public void setGroupsManager(GroupsManager groupsManager) {
this.groupsManager = groupsManager;
}
public void setFacilitiesManager(FacilitiesManager facilitiesManager) {
this.facilitiesManager = facilitiesManager;
}
public void setDatabaseManager(DatabaseManager databaseManager) {
this.databaseManager = databaseManager;
}
public void setMembersManager(MembersManager membersManager) {
this.membersManager = membersManager;
}
public void setResourcesManager(ResourcesManager resourcesManager) {
this.resourcesManager = resourcesManager;
}
public ExtSourcesManager getExtSourcesManager() {
return extSourcesManager;
}
public void setExtSourcesManager(ExtSourcesManager extSourcesManager) {
this.extSourcesManager = extSourcesManager;
}
public void setAttributesManager(AttributesManager attributesManager) {
this.attributesManager = attributesManager;
}
public void setSearcher(Searcher searcher) {
this.searcher = searcher;
}
public AttributesManager getAttributesManager() {
return attributesManager;
}
public void setServicesManager(ServicesManager servicesManager) {
this.servicesManager = servicesManager;
}
public ServicesManager getServicesManager() {
return servicesManager;
}
public void setOwnersManager(OwnersManager ownersManager) {
this.ownersManager = ownersManager;
}
public OwnersManager getOwnersManager() {
return ownersManager;
}
public Searcher getSearcher() {
return searcher;
}
public ModulesUtilsBl getModulesUtilsBl() {
return modulesUtilsBl;
}
public void setModulesUtilsBl(ModulesUtilsBl modulesUtilsBl) {
this.modulesUtilsBl = modulesUtilsBl;
}
public RTMessagesManagerBl getRTMessagesManagerBl() {
return rtMessagesManagerBl;
}
public void setRTMessagesManagerBl(RTMessagesManagerBl rtMessagesManagerBl) {
this.rtMessagesManagerBl = rtMessagesManagerBl;
}
public AuditMessagesManager getAuditMessagesManager() {
return auditMessagesManager;
}
public VosManagerBl getVosManagerBl() {
return vosManagerBl;
}
public void setVosManagerBl(VosManagerBl vosManagerBl) {
this.vosManagerBl = vosManagerBl;
}
public UsersManagerBl getUsersManagerBl() {
return usersManagerBl;
}
public AuditMessagesManagerBl getAuditMessagesManagerBl() {
return auditMessagesManagerBl;
}
public void setUsersManagerBl(UsersManagerBl usersManagerBl) {
this.usersManagerBl = usersManagerBl;
}
public MembersManagerBl getMembersManagerBl() {
return membersManagerBl;
}
public void setMembersManagerBl(MembersManagerBl membersManagerBl) {
this.membersManagerBl = membersManagerBl;
}
public GroupsManagerBl getGroupsManagerBl() {
return groupsManagerBl;
}
public void setGroupsManagerBl(GroupsManagerBl groupsManagerBl) {
this.groupsManagerBl = groupsManagerBl;
}
public FacilitiesManagerBl getFacilitiesManagerBl() {
return facilitiesManagerBl;
}
public void setFacilitiesManagerBl(FacilitiesManagerBl facilitiesManagerBl) {
this.facilitiesManagerBl = facilitiesManagerBl;
}
public DatabaseManagerBl getDatabaseManagerBl() {
return databaseManagerBl;
}
public void setDatabaseManagerBl(DatabaseManagerBl databaseManagerBl) {
this.databaseManagerBl = databaseManagerBl;
}
public ResourcesManagerBl getResourcesManagerBl() {
return resourcesManagerBl;
}
public void setResourcesManagerBl(ResourcesManagerBl resourcesManagerBl) {
this.resourcesManagerBl = resourcesManagerBl;
}
public ExtSourcesManagerBl getExtSourcesManagerBl() {
return extSourcesManagerBl;
}
public void setExtSourcesManagerBl(ExtSourcesManagerBl extSourcesManagerBl) {
this.extSourcesManagerBl = extSourcesManagerBl;
}
public AttributesManagerBl getAttributesManagerBl() {
return attributesManagerBl;
}
public void setAttributesManagerBl(AttributesManagerBl attributesManagerBl) {
this.attributesManagerBl = attributesManagerBl;
}
public ServicesManagerBl getServicesManagerBl() {
return servicesManagerBl;
}
public void setServicesManagerBl(ServicesManagerBl servicesManagerBl) {
this.servicesManagerBl = servicesManagerBl;
}
public OwnersManagerBl getOwnersManagerBl() {
return ownersManagerBl;
}
public void setOwnersManagerBl(OwnersManagerBl ownersManagerBl) {
this.ownersManagerBl = ownersManagerBl;
}
public SecurityTeamsManagerBl getSecurityTeamsManagerBl() {
return securityTeamsManagerBl;
}
public void setSecurityTeamsManagerBl(SecurityTeamsManagerBl securityTeamsManagerBl) {
this.securityTeamsManagerBl = securityTeamsManagerBl;
}
public Auditer getAuditer() {
return this.auditer;
}
public void setAuditer(Auditer auditer) {
this.auditer = auditer;
}
public AuthzResolverBl getAuthzResolverBl() {
return authzResolverBl;
}
public void setAuthzResolverBl(AuthzResolverBl authzResolverBl) {
this.authzResolverBl = authzResolverBl;
}
public SearcherBl getSearcherBl() {
return searcherBl;
}
public void setSearcherBl(SearcherBl searcherBl) {
this.searcherBl = searcherBl;
}
@Override
public boolean isPerunReadOnly() {
return BeansUtils.isPerunReadOnly();
}
/**
* Call managers' initialization methods
*/
public void initialize() throws InternalErrorException {
this.extSourcesManagerBl.initialize(this.getPerunSession());
this.auditer.initialize();
}
/**
* Creates a Perun instance.
* <p/>
* Uses {@link org.springframework.context.support.ClassPathXmlApplicationContext#ClassPathXmlApplicationContext(String...)}
* to load files perun-core.xml and perun-core-jdbc.xml from CLASSPATH.
* <p/>
* <h3>Web applications</h3>
* <p>In web applications, use {@link org.springframework.web.context.WebApplicationContext} to either load
* the same files, or load just perun-core.xml and provide your own definition of {@link javax.sql.DataSource}
* with id dataSource.</p>
* <p>The use {link org.springframework.web.context.support.WebApplicationContextUtils#getRequiredWebApplicationContext}
* to retrieve the context, i.e. add to web.xml the following:</p>
* <pre>
* <listener>
* <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
* </listener>
* <context-param>
* <param-name>contextConfigLocation</param-name>
* <param-value>classpath:perun-core.xml,classpath:perun-core-jdbc.xml</param-value>
* </context-param>
* </pre>
* and in servlets use this code:
* <pre>
* Perun perun = WebApplicationContextUtils.getWebApplicationContext(getServletContext()).getBean("perun",Perun.class);
* </pre>
* <p>The code gets always the same instance of Perun, as the getWebApplicationContext() only gets application context
* from ServletContext attribute, and getBean() then gets the same singleton.</p>
*
* @deprecated It is discouraged to use the Perun bootstrap in order
* to obtain a new Perun instance. Use Spring dependency injection please (both in the application code and in tests).
* Perun bootstrap is going to be removed in one of the future versions.
*
* E.g:
*
* Put following code in your Spring Application Context xml file:
*
* <import resource="classpath:perun-core.xml"/>
*
*
* @return Perun instance
*/
@Deprecated
public static Perun bootstrap() {
ApplicationContext springCtx = new ClassPathXmlApplicationContext("perun-beans.xml", "perun-datasources.xml");
return springCtx.getBean("perun",Perun.class);
}
public String toString() {
return getClass().getSimpleName() + ":[" +
"vosManager='" + vosManager + "', " +
"usersManager='" + usersManager + "', " +
"membersManager='" + membersManager + "', " +
"groupsManager='" + groupsManager + "', " +
"facilitiesManager='" + facilitiesManager + "', " +
"databaseManager='" + databaseManager + "', " +
"auditMessagesManager=" + auditMessagesManager + ", " +
"resourcesManager='" + resourcesManager + "', " +
"extSourcesManager='" + extSourcesManager + "', " +
"attributesManager='" + attributesManager + "', " +
"rtMessagesManager='" + rtMessagesManager + "', " +
"securityTeamsManager='" + securityTeamsManager + "', " +
"searcher='" + searcher + "', " +
"servicesManager='" + servicesManager + "']";
}
}
| |
package org.ebookdroid.core.models;
import org.ebookdroid.R;
import org.ebookdroid.core.DecodeService;
import org.ebookdroid.core.IDocumentView;
import org.ebookdroid.core.IViewerActivity;
import org.ebookdroid.core.Page;
import org.ebookdroid.core.PageIndex;
import org.ebookdroid.core.PageType;
import org.ebookdroid.core.bitmaps.BitmapManager;
import org.ebookdroid.core.bitmaps.Bitmaps;
import org.ebookdroid.core.cache.CacheManager;
import org.ebookdroid.core.codec.CodecPageInfo;
import org.ebookdroid.core.settings.SettingsManager;
import org.ebookdroid.core.settings.books.BookSettings;
import org.ebookdroid.utils.LengthUtils;
import android.graphics.RectF;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class DocumentModel extends CurrentPageModel {
private static final boolean CACHE_ENABLED = true;
private static final Page[] EMPTY_PAGES = {};
private DecodeService decodeService;
private Page[] pages = EMPTY_PAGES;
public DocumentModel(final DecodeService decodeService) {
this.decodeService = decodeService;
}
public Page[] getPages() {
return pages;
}
public Iterable<Page> getPages(final int start) {
return new PageIterator(start, pages.length);
}
public Iterable<Page> getPages(final int start, final int end) {
return new PageIterator(start, Math.min(end, pages.length));
}
public int getPageCount() {
return LengthUtils.length(pages);
}
public DecodeService getDecodeService() {
return decodeService;
}
public void recycle() {
decodeService.recycle();
decodeService = null;
recyclePages();
}
private void recyclePages() {
if (LengthUtils.isNotEmpty(pages)) {
final List<Bitmaps> bitmapsToRecycle = new ArrayList<Bitmaps>();
for (final Page page : pages) {
page.recycle(bitmapsToRecycle);
}
BitmapManager.release(bitmapsToRecycle);
BitmapManager.release();
}
pages = EMPTY_PAGES;
}
public Page getPageObject(final int viewIndex) {
return pages != null && 0 <= viewIndex && viewIndex < pages.length ? pages[viewIndex] : null;
}
/**
* Gets the current page object.
*
* @return the current page object
*/
public Page getCurrentPageObject() {
return getPageObject(this.currentIndex.viewIndex);
}
/**
* Gets the next page object.
*
* @return the next page object
*/
public Page getNextPageObject() {
return getPageObject(this.currentIndex.viewIndex + 1);
}
/**
* Gets the prev page object.
*
* @return the prev page object
*/
public Page getPrevPageObject() {
return getPageObject(this.currentIndex.viewIndex - 1);
}
/**
* Gets the last page object.
*
* @return the last page object
*/
public Page getLastPageObject() {
return getPageObject(pages.length - 1);
}
public void setCurrentPageByFirstVisible(final int firstVisiblePage) {
final Page page = getPageObject(firstVisiblePage);
if (page != null) {
setCurrentPageIndex(page.index);
}
}
public void initPages(final IViewerActivity base, final IViewerActivity.IBookLoadTask task) {
recyclePages();
final BookSettings bs = SettingsManager.getBookSettings();
if (base == null || bs == null) {
return;
}
final IDocumentView view = base.getView();
final CodecPageInfo defCpi = new CodecPageInfo();
defCpi.width = (view.getWidth());
defCpi.height = (view.getHeight());
int viewIndex = 0;
final long start = System.currentTimeMillis();
try {
final ArrayList<Page> list = new ArrayList<Page>();
final CodecPageInfo[] infos = retrievePagesInfo(base, bs, task);
for (int docIndex = 0; docIndex < infos.length; docIndex++) {
if (!bs.splitPages || infos[docIndex] == null || (infos[docIndex].width < infos[docIndex].height)) {
final Page page = new Page(base, new PageIndex(docIndex, viewIndex++), PageType.FULL_PAGE,
infos[docIndex] != null ? infos[docIndex] : defCpi);
list.add(page);
} else {
final Page page1 = new Page(base, new PageIndex(docIndex, viewIndex++), PageType.LEFT_PAGE,
infos[docIndex]);
list.add(page1);
final Page page2 = new Page(base, new PageIndex(docIndex, viewIndex++), PageType.RIGHT_PAGE,
infos[docIndex]);
list.add(page2);
}
}
pages = list.toArray(new Page[list.size()]);
if (pages.length > 0) {
createBookThumbnail(bs, pages[0], false);
}
} finally {
LCTX.d("Loading page info: " + (System.currentTimeMillis() - start) + " ms");
}
}
public void createBookThumbnail(final BookSettings bs, Page page, boolean override) {
final File thumbnailFile = CacheManager.getThumbnailFile(bs.fileName);
if (!override && thumbnailFile.exists()) {
return;
}
int width = 200, height = 200;
RectF bounds = page.getBounds(1.0f);
float pageWidth = bounds.width();
float pageHeight = bounds.height();
if (pageHeight > pageWidth) {
width = (int) (200 * pageWidth / pageHeight);
} else {
height = (int) (200 * pageHeight / pageWidth);
}
decodeService.createThumbnail(thumbnailFile, width, height, page.index.docIndex, page.type.getInitialRect());
}
private CodecPageInfo[] retrievePagesInfo(final IViewerActivity base, final BookSettings bs,
IViewerActivity.IBookLoadTask task) {
final File pagesFile = CacheManager.getPageFile(bs.fileName);
if (CACHE_ENABLED) {
if (pagesFile.exists()) {
final CodecPageInfo[] infos = loadPagesInfo(pagesFile);
if (infos != null) {
boolean nullInfoFound = false;
for (CodecPageInfo info : infos) {
if (info == null) {
nullInfoFound = true;
break;
}
}
if (!nullInfoFound) {
return infos;
}
}
}
}
final CodecPageInfo[] infos = new CodecPageInfo[getDecodeService().getPageCount()];
for (int i = 0; i < infos.length; i++) {
if (task != null) {
task.setProgressDialogMessage(R.string.msg_getting_page_size, (i + 1), infos.length);
}
infos[i] = getDecodeService().getPageInfo(i);
}
if (CACHE_ENABLED) {
storePagesInfo(pagesFile, infos);
}
return infos;
}
private CodecPageInfo[] loadPagesInfo(final File pagesFile) {
try {
final DataInputStream in = new DataInputStream(new FileInputStream(pagesFile));
try {
final int pages = in.readInt();
final CodecPageInfo[] infos = new CodecPageInfo[pages];
for (int i = 0; i < infos.length; i++) {
final CodecPageInfo cpi = new CodecPageInfo();
cpi.width = (in.readInt());
cpi.height = (in.readInt());
if (cpi.width != -1 && cpi.height != -1) {
infos[i] = cpi;
}
}
return infos;
} catch (final EOFException ex) {
LCTX.e("Loading pages cache failed: " + ex.getMessage());
} catch (final IOException ex) {
LCTX.e("Loading pages cache failed: " + ex.getMessage());
} finally {
try {
in.close();
} catch (final IOException ex) {
}
}
} catch (final FileNotFoundException ex) {
LCTX.e("Loading pages cache failed: " + ex.getMessage());
}
return null;
}
private void storePagesInfo(final File pagesFile, final CodecPageInfo[] infos) {
if (!decodeService.isPageSizeCacheable()) {
return;
}
try {
final DataOutputStream out = new DataOutputStream(new FileOutputStream(pagesFile));
try {
out.writeInt(infos.length);
for (int i = 0; i < infos.length; i++) {
if (infos[i] != null) {
out.writeInt(infos[i].width);
out.writeInt(infos[i].height);
} else {
out.writeInt(-1);
out.writeInt(-1);
}
}
} catch (final IOException ex) {
LCTX.e("Saving pages cache failed: " + ex.getMessage());
} finally {
try {
out.close();
} catch (final IOException ex) {
}
}
} catch (final IOException ex) {
LCTX.e("Saving pages cache failed: " + ex.getMessage());
}
}
private final class PageIterator implements Iterable<Page>, Iterator<Page> {
private final int end;
private int index;
private PageIterator(final int start, final int end) {
this.index = start;
this.end = end;
}
@Override
public boolean hasNext() {
return 0 <= index && index < end;
}
@Override
public Page next() {
return hasNext() ? pages[index++] : null;
}
@Override
public void remove() {
}
@Override
public Iterator<Page> iterator() {
return this;
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.