diff
stringlengths 262
553k
| is_single_chunk
bool 2
classes | is_single_function
bool 1
class | buggy_function
stringlengths 20
391k
| fixed_function
stringlengths 0
392k
|
---|---|---|---|---|
diff --git a/src/petrglad/javarpc/util/Sockets.java b/src/petrglad/javarpc/util/Sockets.java
index 626e7a7..61d8932 100644
--- a/src/petrglad/javarpc/util/Sockets.java
+++ b/src/petrglad/javarpc/util/Sockets.java
@@ -1,53 +1,53 @@
package petrglad.javarpc.util;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import org.apache.log4j.Logger;
public final class Sockets {
static final Logger LOG = Logger.getLogger(Sockets.class);
private Sockets() {
}
public static Socket openClientSocket(final String host, final int port) {
try {
return new Socket(host, port);
} catch (UnknownHostException e) {
- throw new RuntimeException("Host is not found " + host + ":" + port);
+ throw new RuntimeException("Host is not found " + host + ":" + port, e);
} catch (IOException e) {
- throw new RuntimeException("Could not open connection to " + host);
+ throw new RuntimeException("Could not open connection to " + host, e);
}
}
/**
* @return Stop condition for spoolers.
*/
public static Flag getIsSocketOpen(final Socket socket) {
return new Flag() {
@Override
public Boolean get() {
return !socket.isClosed();
}
};
}
public static void closeSocket(final ServerSocket socket) {
try {
socket.close();
} catch (IOException e) {
LOG.error("Error closing server socket " + socket, e);
}
}
public static void closeSocket(final Socket socket) {
try {
socket.close();
} catch (IOException e) {
LOG.error("Error closing socket " + socket, e);
}
}
}
| false | true | public static Socket openClientSocket(final String host, final int port) {
try {
return new Socket(host, port);
} catch (UnknownHostException e) {
throw new RuntimeException("Host is not found " + host + ":" + port);
} catch (IOException e) {
throw new RuntimeException("Could not open connection to " + host);
}
}
| public static Socket openClientSocket(final String host, final int port) {
try {
return new Socket(host, port);
} catch (UnknownHostException e) {
throw new RuntimeException("Host is not found " + host + ":" + port, e);
} catch (IOException e) {
throw new RuntimeException("Could not open connection to " + host, e);
}
}
|
diff --git a/HSRBuddy/src/ch/hsr/hsrbuddy/activity/map/MapActivity.java b/HSRBuddy/src/ch/hsr/hsrbuddy/activity/map/MapActivity.java
index a70d51a..90917b3 100644
--- a/HSRBuddy/src/ch/hsr/hsrbuddy/activity/map/MapActivity.java
+++ b/HSRBuddy/src/ch/hsr/hsrbuddy/activity/map/MapActivity.java
@@ -1,72 +1,69 @@
package ch.hsr.hsrbuddy.activity.map;
import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import ch.hsr.hsrbuddy.R;
import ch.hsr.hsrbuddy.activity.SettingsActivity;
import ch.hsr.hsrbuddy.view.ImageMap;
import ch.hsr.hsrbuddy.view.ImageMap.OnImageMapClickedHandler;
public class MapActivity extends Activity {
ImageMap mImageMap;
Drawable hsrmap;
OnImageMapClickedHandler handler = new ImageMap.OnImageMapClickedHandler() {
public void onImageMapClicked(int id) { changeMap(id); }
public void onBubbleClicked(int id) { }
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
mImageMap = (ImageMap) findViewById(R.id.map);
mImageMap.addOnImageMapClickedHandler(handler);
}
private void changeMap(int id){
Intent intent = new Intent(this, MapActivityDetail.class);
Integer buildingId = 0;
switch (id)
{
case R.id.building1:
- buildingId = R.drawable.schulgebaeude_og;
- break;
- case R.id.building2:
- buildingId = R.drawable.laborgebaeude_eg;
+ buildingId = R.drawable.geb1;
break;
case R.id.building3:
- buildingId = R.drawable.hoersaalgebaeude_eg;
- break;
- case R.id.building4:
- buildingId = R.drawable.verwaltungsgebaeude_og;
+ buildingId = R.drawable.geb3;
break;
case R.id.building5:
- buildingId = R.drawable.foyergebaeude_eg;
+ buildingId = R.drawable.geb5;
break;
+ case R.id.building6:
+ buildingId = R.drawable.geb6;
+ break;
}
intent.putExtra("imageId", buildingId);
startActivity(intent);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_map, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_settings:
startActivity(new Intent(this, SettingsActivity.class));
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
| false | true | private void changeMap(int id){
Intent intent = new Intent(this, MapActivityDetail.class);
Integer buildingId = 0;
switch (id)
{
case R.id.building1:
buildingId = R.drawable.schulgebaeude_og;
break;
case R.id.building2:
buildingId = R.drawable.laborgebaeude_eg;
break;
case R.id.building3:
buildingId = R.drawable.hoersaalgebaeude_eg;
break;
case R.id.building4:
buildingId = R.drawable.verwaltungsgebaeude_og;
break;
case R.id.building5:
buildingId = R.drawable.foyergebaeude_eg;
break;
}
intent.putExtra("imageId", buildingId);
startActivity(intent);
}
| private void changeMap(int id){
Intent intent = new Intent(this, MapActivityDetail.class);
Integer buildingId = 0;
switch (id)
{
case R.id.building1:
buildingId = R.drawable.geb1;
break;
case R.id.building3:
buildingId = R.drawable.geb3;
break;
case R.id.building5:
buildingId = R.drawable.geb5;
break;
case R.id.building6:
buildingId = R.drawable.geb6;
break;
}
intent.putExtra("imageId", buildingId);
startActivity(intent);
}
|
diff --git a/bundles/org.eclipse.test.performance.ui/src/org/eclipse/test/performance/ui/ScenarioStatusTable.java b/bundles/org.eclipse.test.performance.ui/src/org/eclipse/test/performance/ui/ScenarioStatusTable.java
index 327c93c..76ab08f 100644
--- a/bundles/org.eclipse.test.performance.ui/src/org/eclipse/test/performance/ui/ScenarioStatusTable.java
+++ b/bundles/org.eclipse.test.performance.ui/src/org/eclipse/test/performance/ui/ScenarioStatusTable.java
@@ -1,302 +1,302 @@
/*******************************************************************************
* Copyright (c) 2005, 2007 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.test.performance.ui;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.StringTokenizer;
import org.eclipse.test.internal.performance.PerformanceTestPlugin;
import org.eclipse.test.internal.performance.data.Dim;
import org.eclipse.test.internal.performance.db.DB;
import org.eclipse.test.internal.performance.db.Scenario;
import org.eclipse.test.internal.performance.db.SummaryEntry;
import org.eclipse.test.internal.performance.db.TimeSeries;
import org.eclipse.test.internal.performance.db.Variations;
import org.eclipse.test.performance.Dimension;
public class ScenarioStatusTable {
private Hashtable configMaps=null;
private Variations variations;
private String scenarioPattern;
private ArrayList configNames=new ArrayList();
private Hashtable scenarioComments;
private SummaryEntry[] fingerprintEntries;
private final String baseline;
private class ScenarioStatus{
Hashtable statusMap;
String name, shortName;
Hashtable configStatus;
Hashtable resultsMap;
boolean hasSlowDownExplanation=false;
boolean fingerprint = false;
boolean hasBaseline = true;
public ScenarioStatus(String scenarioName){
name = scenarioName;
statusMap = new Hashtable();
configStatus = new Hashtable();
resultsMap = new Hashtable();
}
}
/**
* Creates an HTML table of red x/green check for a scenario for each
* configuration.
*
* @param variations
* @param scenarioPattern
* @param configDescriptors
*/
public ScenarioStatusTable(Variations variations,String scenarioPattern,Hashtable configDescriptors,Hashtable scenarioComments, SummaryEntry[] fpSummaries, String baseline){
configMaps=configDescriptors;
this.variations=variations;
this.scenarioPattern=scenarioPattern;
this.scenarioComments=scenarioComments;
this.baseline= baseline;
this.fingerprintEntries = fpSummaries;
}
/**
* Prints the HTML representation of scenario status table into the given stream.
*/
public void print(PrintStream stream, boolean filter) {
String OS="config";
Scenario[] scenarios= DB.queryScenarios(variations, scenarioPattern, OS, null);
if (scenarios != null && scenarios.length > 0) {
ArrayList scenarioStatusList=new ArrayList();
for (int i= 0; i < scenarios.length; i++) {
Scenario scenario= scenarios[i];
String scenarioName=scenario.getScenarioName();
if (filter && !Utils.matchPattern(scenarioName, scenarioPattern)) continue;
// returns the config names. Making assumption that indices in
// the configs array map to the indices of the failure messages.
String[] configs=scenario.getTimeSeriesLabels();
String[] failureMessages= scenario.getFailureMessages();
ScenarioStatus scenarioStatus=new ScenarioStatus(scenarioName);
scenarioStatus.fingerprint = Utils.hasSummary(this.fingerprintEntries, scenarioName);
String scenarioComment= (String)scenarioComments.get(scenarioName);
if (scenarioComment != null)
scenarioStatus.hasSlowDownExplanation= true;
int confsLength = configs.length;
for (int j=0; j<confsLength; j++){
if (!configNames.contains(configs[j]))
configNames.add(configs[j]);
// Compute confidence level and store it in scenario status
Variations v = (Variations) variations.clone();
v.put(PerformanceTestPlugin.CONFIG, configs[j]);
// double[] resultStats = Utils.resultStats(v, scenarioName, baseline, configs[j]);
String current = (String) v.get(PerformanceTestPlugin.BUILD);
Dim significanceDimension = (Dim) Dimension.ELAPSED_PROCESS;
Scenario newScenario= DB.getScenarioSeries(scenarioName, v, PerformanceTestPlugin.BUILD, baseline, current, new Dim[] { significanceDimension });
String[] timeSeriesLabels= newScenario.getTimeSeriesLabels();
TimeSeries timeSeries = newScenario.getTimeSeries(significanceDimension);
boolean hasBaseline = timeSeriesLabels.length == 2 && timeSeriesLabels[0].equals(baseline);
double[] resultStats = Utils.resultsStatistics(timeSeries);
if (resultStats == null) continue;
if (resultStats != null && resultStats[1] < 0 && scenarioStatus.hasBaseline) scenarioStatus.hasBaseline = false;
- int confidenceLevel = Utils.confidenceLevel(resultStats);
- scenarioStatus.configStatus.put(configs[j], new Integer(confidenceLevel));
// Store failure message in scenario status
+ int confidenceLevel = Utils.confidenceLevel(resultStats);
boolean hasScenarioFailure = failureMessages[j] != null && failureMessages[j].indexOf(configs[j]) != -1; // ensure correct failure message relates to config
StringBuffer buffer = new StringBuffer();
if (hasScenarioFailure) {
buffer.append(failureMessages[j]);
if (scenarioStatus.hasSlowDownExplanation) {
buffer.append(" - Explanation comment: ");
buffer.append(scenarioComment);
}
confidenceLevel |= Utils.DEV;
}
+ scenarioStatus.configStatus.put(configs[j], new Integer(confidenceLevel));
scenarioStatus.statusMap.put(configs[j], buffer.toString());
// Store text for numbers in scenario status
String text = Utils.failureMessage(resultStats, false);
scenarioStatus.resultsMap.put(configs[j], text);
// Store scenario short name in scenario status (for table column)
if (scenarioStatus.shortName == null) {
if (hasBaseline) { // baseline is OK
scenarioStatus.shortName = Utils.getScenarioShortName(scenarioName, -1);
} else {
StringBuffer shortName = new StringBuffer("*");
shortName.append(Utils.getScenarioShortName(scenarioName, -1));
shortName.append(" <small>(vs. ");
shortName.append(timeSeriesLabels[0]);
shortName.append(")</small>");
scenarioStatus.shortName = shortName.toString();
}
}
// Store scenario status
if (!scenarioStatusList.contains(scenarioStatus)) {
scenarioStatusList.add(scenarioStatus);
}
}
}
String label=null;
stream.println("<br><h4>Scenario Status</h4>");
stream.println("The following table gives a complete but compact view of performance results for the component.<br>");
stream.println("Each line of the table shows the results for one scenario on all machines.<br><br>");
stream.println("The name of the scenario is in <b>bold</b> when its results are also displayed in the fingerprints<br>");
stream.println("and starts with an '*' when the scenario has no results in the last baseline run.<br><br>");
stream.println("Here are information displayed for each test (ie. in each cell):");
stream.println("<ul>");
stream.println("<li>an icon showing whether the test fails or passes and whether it's reliable or not.<br>");
stream.println("The legend for this icon is:");
stream.println("<ul>");
stream.print("<li>Green (<img src=\"");
stream.print(Utils.OK_IMAGE);
stream.print("\">): mark a <b>successful result</b>, which means this test has neither significant performance regression nor significant standard error</li>");
stream.print("<li>Red (<img src=\"");
stream.print(Utils.FAIL_IMAGE);
stream.println("\">): mark a <b>failing result</b>, which means this test shows a significant performance regression (more than 10%)</li>");
stream.print("<li>Gray (<img src=\"");
stream.print(Utils.FAIL_IMAGE_EXPLAINED);
stream.println("\">): mark a <b>failing result</b> (see above) with a comment explaining this degradation.</li>");
stream.print("<li>Yellow (<img src=\"");
stream.print(Utils.FAIL_IMAGE_WARN);
stream.print("\"> or <img src=\"");
stream.print(Utils.OK_IMAGE_WARN);
stream.print("\">): mark a <b>failing or successful result</b> with a significant standard error (more than ");
stream.print(Utils.STANDARD_ERROR_THRESHOLD_STRING);
stream.println(")</li>");
stream.print("<li>Black (<img src=\"");
stream.print(Utils.UNKNOWN_IMAGE);
stream.print("\">): mark an <b>undefined result</b>, which means that deviation on this test is not a number (<code>NaN</code>) or is infinite (happens when the reference value is equals to 0!)</li>");
stream.println("<li>\"n/a\": mark a test for with <b>no</b> performance results</li>");
stream.println("</ul></li>");
stream.println("<li>the value of the deviation from the baseline as a percentage (ie. formula is: <code>(build_test_time - baseline_test_time) / baseline_test_time</code>)</li>");
stream.println("<li>the value of the standard error of this deviation as a percentage (ie. formula is: <code>sqrt(build_test_stddev^2 / N + baseline_test_stddev^2 / N) / baseline_test_time</code>)<br>");
stream.println("When test only has one measure, the standard error cannot be computed and is replaced with a '<font color=\"#CCCC00\">[n/a]</font>'.</li>");
stream.println("</ul>");
stream.println("<u>Hints</u>:<ul>");
stream.println("<li>fly over image of failing tests to see the complete error message</li>");
stream.println("<li>to look at the complete and detailed test results, click on its image</li>");
stream.println("</ul>");
stream.println();
stream.println("<table border=\"1\">");
stream.println("<tr>");
stream.print("<td><h4>All ");
stream.print(scenarios.length);
stream.println(" scenarios</h4></td>");
for (int i= 0; i < configNames.size(); i++){
label = configNames.get(i).toString();
String columnTitle = label;
if (configMaps!=null) {
Utils.ConfigDescriptor configDescriptor= (Utils.ConfigDescriptor)configMaps.get(label);
if (configDescriptor != null) {
int idx = configDescriptor.description.indexOf('(');
if (idx < 0) {
columnTitle = configDescriptor.description;
} else {
// first line
StringTokenizer tokenizer = new StringTokenizer(configDescriptor.description.substring(0, idx).trim(), " ");
StringBuffer buffer = new StringBuffer(tokenizer.nextToken());
while (tokenizer.hasMoreTokens()) {
buffer.append(" ");
buffer.append(tokenizer.nextToken());
}
buffer.append(' ');
// second line
tokenizer = new StringTokenizer(configDescriptor.description.substring(idx).trim(), " ");
buffer.append(tokenizer.nextToken());
while (tokenizer.hasMoreTokens()) {
buffer.append(" ");
buffer.append(tokenizer.nextToken());
}
columnTitle = buffer.toString();
}
}
}
stream.print("<td><h5>");
stream.print(columnTitle);
stream.println("</h5>");
}
// counter for js class Id's
int jsIdCount=0;
for (int j= 0; j < scenarioStatusList.size(); j++) {
ScenarioStatus status=(ScenarioStatus)scenarioStatusList.get(j);
stream.println("<tr>");
stream.print("<td>");
if (status.fingerprint) stream.print("<b>");
if (!status.hasBaseline) stream.print("*");
// stream.print(status.name.substring(status.name.indexOf(".",status.name.indexOf(".test")+1)+1));
stream.print(status.shortName);
if (!status.hasBaseline) stream.print("</i>");
if (status.fingerprint) stream.print("</b>");
stream.println();
for (int i=0;i<configNames.size();i++){
String configName=configNames.get(i).toString();
String aUrl=configName;
if (status.statusMap.containsKey(configName)){
String message = (String) status.statusMap.get(configName);
int confidence = ((Integer) status.configStatus.get(configName)).intValue();
String image = Utils.getImage(confidence, status.hasSlowDownExplanation);
stream.print("<td><a ");
if ((confidence & Utils.DEV) == 0 || (confidence & Utils.NAN) != 0 || message.length() == 0){
// write deviation with error in table when test pass
stream.print("href=\"");
stream.print(aUrl);
stream.print('/');
stream.print(status.name.replace('#', '.').replace(':', '_').replace('\\', '_'));
stream.println(".html\">");
stream.print("<img hspace=\"10\" border=\"0\" src=\"");
stream.print(image);
stream.println("\"/></a>");
} else {
// create message with tooltip text including deviation with error plus failure message
jsIdCount+=1;
stream.print("class=\"tooltipSource\" onMouseover=\"show_element('toolTip");
stream.print(jsIdCount);
stream.print("')\" onMouseout=\"hide_element('toolTip");
stream.print(jsIdCount);
stream.print("')\" \nhref=\"");
stream.print(aUrl);
stream.print('/');
stream.print(status.name.replace('#', '.').replace(':', '_').replace('\\', '_'));
stream.println(".html\">");
stream.print("<img hspace=\"10\" border=\"0\" src=\"");
stream.print(image);
stream.println("\"/>");
stream.print("<span class=\"hidden_tooltip\" id=\"toolTip");
stream.print(jsIdCount);
stream.print("\">");
stream.print(message);
stream.println("</span></a>");
}
String result = (String) status.resultsMap.get(configName);
stream.println(result);
}else{
stream.println("<td> n/a");
}
}
stream.flush();
}
stream.println("</table>");
}
}
}
| false | true | public void print(PrintStream stream, boolean filter) {
String OS="config";
Scenario[] scenarios= DB.queryScenarios(variations, scenarioPattern, OS, null);
if (scenarios != null && scenarios.length > 0) {
ArrayList scenarioStatusList=new ArrayList();
for (int i= 0; i < scenarios.length; i++) {
Scenario scenario= scenarios[i];
String scenarioName=scenario.getScenarioName();
if (filter && !Utils.matchPattern(scenarioName, scenarioPattern)) continue;
// returns the config names. Making assumption that indices in
// the configs array map to the indices of the failure messages.
String[] configs=scenario.getTimeSeriesLabels();
String[] failureMessages= scenario.getFailureMessages();
ScenarioStatus scenarioStatus=new ScenarioStatus(scenarioName);
scenarioStatus.fingerprint = Utils.hasSummary(this.fingerprintEntries, scenarioName);
String scenarioComment= (String)scenarioComments.get(scenarioName);
if (scenarioComment != null)
scenarioStatus.hasSlowDownExplanation= true;
int confsLength = configs.length;
for (int j=0; j<confsLength; j++){
if (!configNames.contains(configs[j]))
configNames.add(configs[j]);
// Compute confidence level and store it in scenario status
Variations v = (Variations) variations.clone();
v.put(PerformanceTestPlugin.CONFIG, configs[j]);
// double[] resultStats = Utils.resultStats(v, scenarioName, baseline, configs[j]);
String current = (String) v.get(PerformanceTestPlugin.BUILD);
Dim significanceDimension = (Dim) Dimension.ELAPSED_PROCESS;
Scenario newScenario= DB.getScenarioSeries(scenarioName, v, PerformanceTestPlugin.BUILD, baseline, current, new Dim[] { significanceDimension });
String[] timeSeriesLabels= newScenario.getTimeSeriesLabels();
TimeSeries timeSeries = newScenario.getTimeSeries(significanceDimension);
boolean hasBaseline = timeSeriesLabels.length == 2 && timeSeriesLabels[0].equals(baseline);
double[] resultStats = Utils.resultsStatistics(timeSeries);
if (resultStats == null) continue;
if (resultStats != null && resultStats[1] < 0 && scenarioStatus.hasBaseline) scenarioStatus.hasBaseline = false;
int confidenceLevel = Utils.confidenceLevel(resultStats);
scenarioStatus.configStatus.put(configs[j], new Integer(confidenceLevel));
// Store failure message in scenario status
boolean hasScenarioFailure = failureMessages[j] != null && failureMessages[j].indexOf(configs[j]) != -1; // ensure correct failure message relates to config
StringBuffer buffer = new StringBuffer();
if (hasScenarioFailure) {
buffer.append(failureMessages[j]);
if (scenarioStatus.hasSlowDownExplanation) {
buffer.append(" - Explanation comment: ");
buffer.append(scenarioComment);
}
confidenceLevel |= Utils.DEV;
}
scenarioStatus.statusMap.put(configs[j], buffer.toString());
// Store text for numbers in scenario status
String text = Utils.failureMessage(resultStats, false);
scenarioStatus.resultsMap.put(configs[j], text);
// Store scenario short name in scenario status (for table column)
if (scenarioStatus.shortName == null) {
if (hasBaseline) { // baseline is OK
scenarioStatus.shortName = Utils.getScenarioShortName(scenarioName, -1);
} else {
StringBuffer shortName = new StringBuffer("*");
shortName.append(Utils.getScenarioShortName(scenarioName, -1));
shortName.append(" <small>(vs. ");
shortName.append(timeSeriesLabels[0]);
shortName.append(")</small>");
scenarioStatus.shortName = shortName.toString();
}
}
// Store scenario status
if (!scenarioStatusList.contains(scenarioStatus)) {
scenarioStatusList.add(scenarioStatus);
}
}
}
String label=null;
stream.println("<br><h4>Scenario Status</h4>");
stream.println("The following table gives a complete but compact view of performance results for the component.<br>");
stream.println("Each line of the table shows the results for one scenario on all machines.<br><br>");
stream.println("The name of the scenario is in <b>bold</b> when its results are also displayed in the fingerprints<br>");
stream.println("and starts with an '*' when the scenario has no results in the last baseline run.<br><br>");
stream.println("Here are information displayed for each test (ie. in each cell):");
stream.println("<ul>");
stream.println("<li>an icon showing whether the test fails or passes and whether it's reliable or not.<br>");
stream.println("The legend for this icon is:");
stream.println("<ul>");
stream.print("<li>Green (<img src=\"");
stream.print(Utils.OK_IMAGE);
stream.print("\">): mark a <b>successful result</b>, which means this test has neither significant performance regression nor significant standard error</li>");
stream.print("<li>Red (<img src=\"");
stream.print(Utils.FAIL_IMAGE);
stream.println("\">): mark a <b>failing result</b>, which means this test shows a significant performance regression (more than 10%)</li>");
stream.print("<li>Gray (<img src=\"");
stream.print(Utils.FAIL_IMAGE_EXPLAINED);
stream.println("\">): mark a <b>failing result</b> (see above) with a comment explaining this degradation.</li>");
stream.print("<li>Yellow (<img src=\"");
stream.print(Utils.FAIL_IMAGE_WARN);
stream.print("\"> or <img src=\"");
stream.print(Utils.OK_IMAGE_WARN);
stream.print("\">): mark a <b>failing or successful result</b> with a significant standard error (more than ");
stream.print(Utils.STANDARD_ERROR_THRESHOLD_STRING);
stream.println(")</li>");
stream.print("<li>Black (<img src=\"");
stream.print(Utils.UNKNOWN_IMAGE);
stream.print("\">): mark an <b>undefined result</b>, which means that deviation on this test is not a number (<code>NaN</code>) or is infinite (happens when the reference value is equals to 0!)</li>");
stream.println("<li>\"n/a\": mark a test for with <b>no</b> performance results</li>");
stream.println("</ul></li>");
stream.println("<li>the value of the deviation from the baseline as a percentage (ie. formula is: <code>(build_test_time - baseline_test_time) / baseline_test_time</code>)</li>");
stream.println("<li>the value of the standard error of this deviation as a percentage (ie. formula is: <code>sqrt(build_test_stddev^2 / N + baseline_test_stddev^2 / N) / baseline_test_time</code>)<br>");
stream.println("When test only has one measure, the standard error cannot be computed and is replaced with a '<font color=\"#CCCC00\">[n/a]</font>'.</li>");
stream.println("</ul>");
stream.println("<u>Hints</u>:<ul>");
stream.println("<li>fly over image of failing tests to see the complete error message</li>");
stream.println("<li>to look at the complete and detailed test results, click on its image</li>");
stream.println("</ul>");
stream.println();
stream.println("<table border=\"1\">");
stream.println("<tr>");
stream.print("<td><h4>All ");
stream.print(scenarios.length);
stream.println(" scenarios</h4></td>");
for (int i= 0; i < configNames.size(); i++){
label = configNames.get(i).toString();
String columnTitle = label;
if (configMaps!=null) {
Utils.ConfigDescriptor configDescriptor= (Utils.ConfigDescriptor)configMaps.get(label);
if (configDescriptor != null) {
int idx = configDescriptor.description.indexOf('(');
if (idx < 0) {
columnTitle = configDescriptor.description;
} else {
// first line
StringTokenizer tokenizer = new StringTokenizer(configDescriptor.description.substring(0, idx).trim(), " ");
StringBuffer buffer = new StringBuffer(tokenizer.nextToken());
while (tokenizer.hasMoreTokens()) {
buffer.append(" ");
buffer.append(tokenizer.nextToken());
}
buffer.append(' ');
// second line
tokenizer = new StringTokenizer(configDescriptor.description.substring(idx).trim(), " ");
buffer.append(tokenizer.nextToken());
while (tokenizer.hasMoreTokens()) {
buffer.append(" ");
buffer.append(tokenizer.nextToken());
}
columnTitle = buffer.toString();
}
}
}
stream.print("<td><h5>");
stream.print(columnTitle);
stream.println("</h5>");
}
// counter for js class Id's
int jsIdCount=0;
for (int j= 0; j < scenarioStatusList.size(); j++) {
ScenarioStatus status=(ScenarioStatus)scenarioStatusList.get(j);
stream.println("<tr>");
stream.print("<td>");
if (status.fingerprint) stream.print("<b>");
if (!status.hasBaseline) stream.print("*");
// stream.print(status.name.substring(status.name.indexOf(".",status.name.indexOf(".test")+1)+1));
stream.print(status.shortName);
if (!status.hasBaseline) stream.print("</i>");
if (status.fingerprint) stream.print("</b>");
stream.println();
for (int i=0;i<configNames.size();i++){
String configName=configNames.get(i).toString();
String aUrl=configName;
if (status.statusMap.containsKey(configName)){
String message = (String) status.statusMap.get(configName);
int confidence = ((Integer) status.configStatus.get(configName)).intValue();
String image = Utils.getImage(confidence, status.hasSlowDownExplanation);
stream.print("<td><a ");
if ((confidence & Utils.DEV) == 0 || (confidence & Utils.NAN) != 0 || message.length() == 0){
// write deviation with error in table when test pass
stream.print("href=\"");
stream.print(aUrl);
stream.print('/');
stream.print(status.name.replace('#', '.').replace(':', '_').replace('\\', '_'));
stream.println(".html\">");
stream.print("<img hspace=\"10\" border=\"0\" src=\"");
stream.print(image);
stream.println("\"/></a>");
} else {
// create message with tooltip text including deviation with error plus failure message
jsIdCount+=1;
stream.print("class=\"tooltipSource\" onMouseover=\"show_element('toolTip");
stream.print(jsIdCount);
stream.print("')\" onMouseout=\"hide_element('toolTip");
stream.print(jsIdCount);
stream.print("')\" \nhref=\"");
stream.print(aUrl);
stream.print('/');
stream.print(status.name.replace('#', '.').replace(':', '_').replace('\\', '_'));
stream.println(".html\">");
stream.print("<img hspace=\"10\" border=\"0\" src=\"");
stream.print(image);
stream.println("\"/>");
stream.print("<span class=\"hidden_tooltip\" id=\"toolTip");
stream.print(jsIdCount);
stream.print("\">");
stream.print(message);
stream.println("</span></a>");
}
String result = (String) status.resultsMap.get(configName);
stream.println(result);
}else{
stream.println("<td> n/a");
}
}
stream.flush();
}
stream.println("</table>");
}
}
| public void print(PrintStream stream, boolean filter) {
String OS="config";
Scenario[] scenarios= DB.queryScenarios(variations, scenarioPattern, OS, null);
if (scenarios != null && scenarios.length > 0) {
ArrayList scenarioStatusList=new ArrayList();
for (int i= 0; i < scenarios.length; i++) {
Scenario scenario= scenarios[i];
String scenarioName=scenario.getScenarioName();
if (filter && !Utils.matchPattern(scenarioName, scenarioPattern)) continue;
// returns the config names. Making assumption that indices in
// the configs array map to the indices of the failure messages.
String[] configs=scenario.getTimeSeriesLabels();
String[] failureMessages= scenario.getFailureMessages();
ScenarioStatus scenarioStatus=new ScenarioStatus(scenarioName);
scenarioStatus.fingerprint = Utils.hasSummary(this.fingerprintEntries, scenarioName);
String scenarioComment= (String)scenarioComments.get(scenarioName);
if (scenarioComment != null)
scenarioStatus.hasSlowDownExplanation= true;
int confsLength = configs.length;
for (int j=0; j<confsLength; j++){
if (!configNames.contains(configs[j]))
configNames.add(configs[j]);
// Compute confidence level and store it in scenario status
Variations v = (Variations) variations.clone();
v.put(PerformanceTestPlugin.CONFIG, configs[j]);
// double[] resultStats = Utils.resultStats(v, scenarioName, baseline, configs[j]);
String current = (String) v.get(PerformanceTestPlugin.BUILD);
Dim significanceDimension = (Dim) Dimension.ELAPSED_PROCESS;
Scenario newScenario= DB.getScenarioSeries(scenarioName, v, PerformanceTestPlugin.BUILD, baseline, current, new Dim[] { significanceDimension });
String[] timeSeriesLabels= newScenario.getTimeSeriesLabels();
TimeSeries timeSeries = newScenario.getTimeSeries(significanceDimension);
boolean hasBaseline = timeSeriesLabels.length == 2 && timeSeriesLabels[0].equals(baseline);
double[] resultStats = Utils.resultsStatistics(timeSeries);
if (resultStats == null) continue;
if (resultStats != null && resultStats[1] < 0 && scenarioStatus.hasBaseline) scenarioStatus.hasBaseline = false;
// Store failure message in scenario status
int confidenceLevel = Utils.confidenceLevel(resultStats);
boolean hasScenarioFailure = failureMessages[j] != null && failureMessages[j].indexOf(configs[j]) != -1; // ensure correct failure message relates to config
StringBuffer buffer = new StringBuffer();
if (hasScenarioFailure) {
buffer.append(failureMessages[j]);
if (scenarioStatus.hasSlowDownExplanation) {
buffer.append(" - Explanation comment: ");
buffer.append(scenarioComment);
}
confidenceLevel |= Utils.DEV;
}
scenarioStatus.configStatus.put(configs[j], new Integer(confidenceLevel));
scenarioStatus.statusMap.put(configs[j], buffer.toString());
// Store text for numbers in scenario status
String text = Utils.failureMessage(resultStats, false);
scenarioStatus.resultsMap.put(configs[j], text);
// Store scenario short name in scenario status (for table column)
if (scenarioStatus.shortName == null) {
if (hasBaseline) { // baseline is OK
scenarioStatus.shortName = Utils.getScenarioShortName(scenarioName, -1);
} else {
StringBuffer shortName = new StringBuffer("*");
shortName.append(Utils.getScenarioShortName(scenarioName, -1));
shortName.append(" <small>(vs. ");
shortName.append(timeSeriesLabels[0]);
shortName.append(")</small>");
scenarioStatus.shortName = shortName.toString();
}
}
// Store scenario status
if (!scenarioStatusList.contains(scenarioStatus)) {
scenarioStatusList.add(scenarioStatus);
}
}
}
String label=null;
stream.println("<br><h4>Scenario Status</h4>");
stream.println("The following table gives a complete but compact view of performance results for the component.<br>");
stream.println("Each line of the table shows the results for one scenario on all machines.<br><br>");
stream.println("The name of the scenario is in <b>bold</b> when its results are also displayed in the fingerprints<br>");
stream.println("and starts with an '*' when the scenario has no results in the last baseline run.<br><br>");
stream.println("Here are information displayed for each test (ie. in each cell):");
stream.println("<ul>");
stream.println("<li>an icon showing whether the test fails or passes and whether it's reliable or not.<br>");
stream.println("The legend for this icon is:");
stream.println("<ul>");
stream.print("<li>Green (<img src=\"");
stream.print(Utils.OK_IMAGE);
stream.print("\">): mark a <b>successful result</b>, which means this test has neither significant performance regression nor significant standard error</li>");
stream.print("<li>Red (<img src=\"");
stream.print(Utils.FAIL_IMAGE);
stream.println("\">): mark a <b>failing result</b>, which means this test shows a significant performance regression (more than 10%)</li>");
stream.print("<li>Gray (<img src=\"");
stream.print(Utils.FAIL_IMAGE_EXPLAINED);
stream.println("\">): mark a <b>failing result</b> (see above) with a comment explaining this degradation.</li>");
stream.print("<li>Yellow (<img src=\"");
stream.print(Utils.FAIL_IMAGE_WARN);
stream.print("\"> or <img src=\"");
stream.print(Utils.OK_IMAGE_WARN);
stream.print("\">): mark a <b>failing or successful result</b> with a significant standard error (more than ");
stream.print(Utils.STANDARD_ERROR_THRESHOLD_STRING);
stream.println(")</li>");
stream.print("<li>Black (<img src=\"");
stream.print(Utils.UNKNOWN_IMAGE);
stream.print("\">): mark an <b>undefined result</b>, which means that deviation on this test is not a number (<code>NaN</code>) or is infinite (happens when the reference value is equals to 0!)</li>");
stream.println("<li>\"n/a\": mark a test for with <b>no</b> performance results</li>");
stream.println("</ul></li>");
stream.println("<li>the value of the deviation from the baseline as a percentage (ie. formula is: <code>(build_test_time - baseline_test_time) / baseline_test_time</code>)</li>");
stream.println("<li>the value of the standard error of this deviation as a percentage (ie. formula is: <code>sqrt(build_test_stddev^2 / N + baseline_test_stddev^2 / N) / baseline_test_time</code>)<br>");
stream.println("When test only has one measure, the standard error cannot be computed and is replaced with a '<font color=\"#CCCC00\">[n/a]</font>'.</li>");
stream.println("</ul>");
stream.println("<u>Hints</u>:<ul>");
stream.println("<li>fly over image of failing tests to see the complete error message</li>");
stream.println("<li>to look at the complete and detailed test results, click on its image</li>");
stream.println("</ul>");
stream.println();
stream.println("<table border=\"1\">");
stream.println("<tr>");
stream.print("<td><h4>All ");
stream.print(scenarios.length);
stream.println(" scenarios</h4></td>");
for (int i= 0; i < configNames.size(); i++){
label = configNames.get(i).toString();
String columnTitle = label;
if (configMaps!=null) {
Utils.ConfigDescriptor configDescriptor= (Utils.ConfigDescriptor)configMaps.get(label);
if (configDescriptor != null) {
int idx = configDescriptor.description.indexOf('(');
if (idx < 0) {
columnTitle = configDescriptor.description;
} else {
// first line
StringTokenizer tokenizer = new StringTokenizer(configDescriptor.description.substring(0, idx).trim(), " ");
StringBuffer buffer = new StringBuffer(tokenizer.nextToken());
while (tokenizer.hasMoreTokens()) {
buffer.append(" ");
buffer.append(tokenizer.nextToken());
}
buffer.append(' ');
// second line
tokenizer = new StringTokenizer(configDescriptor.description.substring(idx).trim(), " ");
buffer.append(tokenizer.nextToken());
while (tokenizer.hasMoreTokens()) {
buffer.append(" ");
buffer.append(tokenizer.nextToken());
}
columnTitle = buffer.toString();
}
}
}
stream.print("<td><h5>");
stream.print(columnTitle);
stream.println("</h5>");
}
// counter for js class Id's
int jsIdCount=0;
for (int j= 0; j < scenarioStatusList.size(); j++) {
ScenarioStatus status=(ScenarioStatus)scenarioStatusList.get(j);
stream.println("<tr>");
stream.print("<td>");
if (status.fingerprint) stream.print("<b>");
if (!status.hasBaseline) stream.print("*");
// stream.print(status.name.substring(status.name.indexOf(".",status.name.indexOf(".test")+1)+1));
stream.print(status.shortName);
if (!status.hasBaseline) stream.print("</i>");
if (status.fingerprint) stream.print("</b>");
stream.println();
for (int i=0;i<configNames.size();i++){
String configName=configNames.get(i).toString();
String aUrl=configName;
if (status.statusMap.containsKey(configName)){
String message = (String) status.statusMap.get(configName);
int confidence = ((Integer) status.configStatus.get(configName)).intValue();
String image = Utils.getImage(confidence, status.hasSlowDownExplanation);
stream.print("<td><a ");
if ((confidence & Utils.DEV) == 0 || (confidence & Utils.NAN) != 0 || message.length() == 0){
// write deviation with error in table when test pass
stream.print("href=\"");
stream.print(aUrl);
stream.print('/');
stream.print(status.name.replace('#', '.').replace(':', '_').replace('\\', '_'));
stream.println(".html\">");
stream.print("<img hspace=\"10\" border=\"0\" src=\"");
stream.print(image);
stream.println("\"/></a>");
} else {
// create message with tooltip text including deviation with error plus failure message
jsIdCount+=1;
stream.print("class=\"tooltipSource\" onMouseover=\"show_element('toolTip");
stream.print(jsIdCount);
stream.print("')\" onMouseout=\"hide_element('toolTip");
stream.print(jsIdCount);
stream.print("')\" \nhref=\"");
stream.print(aUrl);
stream.print('/');
stream.print(status.name.replace('#', '.').replace(':', '_').replace('\\', '_'));
stream.println(".html\">");
stream.print("<img hspace=\"10\" border=\"0\" src=\"");
stream.print(image);
stream.println("\"/>");
stream.print("<span class=\"hidden_tooltip\" id=\"toolTip");
stream.print(jsIdCount);
stream.print("\">");
stream.print(message);
stream.println("</span></a>");
}
String result = (String) status.resultsMap.get(configName);
stream.println(result);
}else{
stream.println("<td> n/a");
}
}
stream.flush();
}
stream.println("</table>");
}
}
|
diff --git a/IGVC2013_Component_1/src/ClientSocket.java b/IGVC2013_Component_1/src/ClientSocket.java
index f9353e1..a5aaf6f 100644
--- a/IGVC2013_Component_1/src/ClientSocket.java
+++ b/IGVC2013_Component_1/src/ClientSocket.java
@@ -1,232 +1,232 @@
package src;
import java.net.*;
import java.util.LinkedList;
import java.io.*;
import src.urn_jaus_jss_mobility_LocalWaypointListDriver_1_0.Messages.ReportLocalWaypoint;
import src.urn_jaus_jss_mobility_LocalWaypointListDriver_1_0.Messages.SetElement.Body.SetElementSeq.ElementList.ElementRec;
public class ClientSocket {//SocketClient
//http://edn.embarcadero.com/article/31995
//Sockets allow you the programmer to treat the network connection as you would any other I/O.
//(see your JBuilder help files or http://java.sun.com/j2se/1.5.0/docs/api/java/net/package-summary.html for more information).
private ObjectOutputStream oos;
private ObjectInputStream ois;
private Socket connection;
private LinkedList<Object> setLocalPoseList = new LinkedList<Object>();
private LinkedList<Object> setExecuteList = new LinkedList<Object>();
private LinkedList<Object> setExecuteSpeed = new LinkedList<Object>();
private Object[] RobData;
private Object o;;
ClientSocket(){}
public void connect()
//String host,int port
{
/**Define a host **/
- String host = "192.168.32.64";
+ String host = "192.168.33.73";
/**Define a port**/
int port = 19998;
StringBuffer instr = new StringBuffer();
System.out.println("SocketClient initialized");
try{//how to request a socket and establishing a connection
/**obtain an address object of the server*/
InetAddress address = InetAddress.getByName(host);
/**Establish a socket connection*/
connection = new Socket(address, port);
this.oos = new ObjectOutputStream(connection.getOutputStream());
this.ois =new ObjectInputStream(connection.getInputStream());
System.out.println(instr);
}
catch (IOException f) {
System.out.println("IOException: " + f);
}
catch (Exception g) {
System.out.println("Exception: " + g);
}
}
public void JausDataRequest()
{
System.out.println("Sending JausDataRequest...");
try {
Object[] messageID = new Object[] {4};
oos.writeObject(messageID);
oos.flush();
o = ois.readObject();
updateVariablesAndGUI(o);
} catch (ClassNotFoundException e) {
System.out.println(e);
e.printStackTrace();
} catch (IOException e) {
System.out.println(e);
e.printStackTrace();
}
System.out.println("Recieved JausData");
}
public void SetLocalPoseRequest(Double x, Double y, Double yaw)
{
System.out.println("Sending SetLocalPose...");
try {
Integer messageID = 0;
setLocalPoseList.clear();
setLocalPoseList.add(messageID);
setLocalPoseList.add(x);
setLocalPoseList.add(y);
setLocalPoseList.add(yaw);
oos.writeObject(setLocalPoseList.toArray());
oos.flush();
o = ois.readObject();
} catch (ClassNotFoundException e) {
System.out.println(e);
e.printStackTrace();
} catch (IOException e) {
System.out.println(e);
e.printStackTrace();
}
System.out.println("Sent SetLocalPose");
}
public void ExecuteListRequest(LinkedList<ElementRec> waypointList, Double executeSpeed, Integer startElementPos)
{
System.out.println("Sending ExecuteListRequest...");
ReportLocalWaypoint decodedWaypoint = new ReportLocalWaypoint();
Integer messageID = 1;
try {
setExecuteList.clear();
setExecuteList.add(messageID);
for(int j=startElementPos; j<waypointList.size(); j++){
decodedWaypoint.decode(waypointList.get(j).getElementData().getData(), 0);
setExecuteList.add(new Object[] {waypointList.get(j).getElementUID(), decodedWaypoint.getBody().getLocalWaypointRec().getX(), decodedWaypoint.getBody().getLocalWaypointRec().getY()});
}
oos.writeObject(setExecuteList.toArray());
oos.flush();
o = ois.readObject();
} catch (ClassNotFoundException e) {
System.out.println(e);
e.printStackTrace();
} catch (IOException e) {
System.out.println(e);
e.printStackTrace();
}
System.out.println("Sent ExecuteListRequest");
}
public void SetSpeedRequest(Double executeSpeed)
{
System.out.println("Sending SetSpeedRequest...");
Integer messageID = 2;
try {
setExecuteSpeed.clear();
setExecuteSpeed.add(messageID);
setExecuteSpeed.add(executeSpeed);
oos.writeObject(setExecuteSpeed.toArray());
oos.flush();
o = ois.readObject();
} catch (ClassNotFoundException e) {
System.out.println(e);
e.printStackTrace();
} catch (IOException e) {
System.out.println(e);
e.printStackTrace();
}
System.out.println("Sent SetSpeedRequest");
}
public void Shutdown()
{
Object[] messageID = new Object[] {3};
try {
oos.writeObject(messageID);
oos.flush();
o = ois.readObject();
} catch (ClassNotFoundException e) {
System.out.println(e);
e.printStackTrace();
} catch (IOException e) {
System.out.println(e);
e.printStackTrace();
}
}
public void close()
{
try {
connection.close();
} catch (IOException e) {
System.out.println(e);
e.printStackTrace();
}
}
private void updateVariablesAndGUI(Object o){
RobData = (Object[]) o;
JausGUI.robot_x_position = (Double) RobData[0];
JausGUI.robot_y_position = (Double) RobData[1];
JausGUI.robot_yaw_position = (Double) RobData[2];
JausGUI.robot_x_velocity = (Double) RobData[3];
JausGUI.robot_omega = (Double) RobData[4];
JausGUI.robot_desired_speed = (Double) RobData[5];
JausGUI.robot_Active_Element_UID = (Integer) RobData[6];
JausGUI.robot_LocalWaypoint_X = (Double) RobData[7];
JausGUI.robot_LocalWaypoint_Y = (Double) RobData[8];
JausGUI.updateRobotValues();
System.out.println("-------------------------------------------");
System.out.println("X Position: " + RobData[0]);
System.out.println("Y Position: " + RobData[1]);
System.out.println("YAW Position: " + RobData[2]);
System.out.println("X Velocity: " + RobData[3]);
System.out.println("Omega: " + RobData[4]);
System.out.println("Desired Speed: " + RobData[5]);
System.out.println("Active Element UID: " + RobData[6]);
System.out.println("Local Waypoint X: " + RobData[7]);
System.out.println("Local Waypoint Y: " + RobData[8]);
}
}
//servers
//client
//have it send to itself
| true | true | public void connect()
//String host,int port
{
/**Define a host **/
String host = "192.168.32.64";
/**Define a port**/
int port = 19998;
StringBuffer instr = new StringBuffer();
System.out.println("SocketClient initialized");
try{//how to request a socket and establishing a connection
/**obtain an address object of the server*/
InetAddress address = InetAddress.getByName(host);
/**Establish a socket connection*/
connection = new Socket(address, port);
this.oos = new ObjectOutputStream(connection.getOutputStream());
this.ois =new ObjectInputStream(connection.getInputStream());
System.out.println(instr);
}
catch (IOException f) {
System.out.println("IOException: " + f);
}
catch (Exception g) {
System.out.println("Exception: " + g);
}
}
| public void connect()
//String host,int port
{
/**Define a host **/
String host = "192.168.33.73";
/**Define a port**/
int port = 19998;
StringBuffer instr = new StringBuffer();
System.out.println("SocketClient initialized");
try{//how to request a socket and establishing a connection
/**obtain an address object of the server*/
InetAddress address = InetAddress.getByName(host);
/**Establish a socket connection*/
connection = new Socket(address, port);
this.oos = new ObjectOutputStream(connection.getOutputStream());
this.ois =new ObjectInputStream(connection.getInputStream());
System.out.println(instr);
}
catch (IOException f) {
System.out.println("IOException: " + f);
}
catch (Exception g) {
System.out.println("Exception: " + g);
}
}
|
diff --git a/src/com/menny/android/anysoftkeyboard/keyboards/LatinKeyboard.java b/src/com/menny/android/anysoftkeyboard/keyboards/LatinKeyboard.java
index 010e38d1..c63d0f9d 100644
--- a/src/com/menny/android/anysoftkeyboard/keyboards/LatinKeyboard.java
+++ b/src/com/menny/android/anysoftkeyboard/keyboards/LatinKeyboard.java
@@ -1,83 +1,83 @@
package com.menny.android.anysoftkeyboard.keyboards;
import com.menny.android.anysoftkeyboard.AnyKeyboardContextProvider;
public class LatinKeyboard extends AnyKeyboard
{
protected LatinKeyboard(AnyKeyboardContextProvider context, int keyboardLayoutId)
{
super(context, keyboardLayoutId);
}
protected void setPopupKeyChars(Key aKey)
{
if ((aKey.codes != null) && (aKey.codes.length > 0))
{
switch((char)aKey.codes[0])
{
case 'a':
- aKey.popupCharacters = "\u00e0\u00e2\u00e1\u00e4\u00e3\u00e6\u00e5\u0105";
+ aKey.popupCharacters = "\u00e0\u00e1\u00e2\u00e3\u00e4\u00e5\u00e6\u0105";
aKey.popupResId = com.menny.android.anysoftkeyboard.R.xml.popup;
break;
case 'c':
- aKey.popupCharacters = "\u00e7\u010d\u0107\u0109";
+ aKey.popupCharacters = "\u00e7\u0107\u0109\u010d";
aKey.popupResId = com.menny.android.anysoftkeyboard.R.xml.popup;
break;
case 'd':
aKey.popupCharacters = "\u0111";
aKey.popupResId = com.menny.android.anysoftkeyboard.R.xml.popup;
break;
case 'e':
- aKey.popupCharacters = "\u00e9\u00e8\u00ea\u00eb\u0119\u20ac";
+ aKey.popupCharacters = "\u00e8\u00e9\u00ea\u00eb\u0119\u20ac";
aKey.popupResId = com.menny.android.anysoftkeyboard.R.xml.popup;
break;
case 'g':
aKey.popupCharacters = "\u011d";
aKey.popupResId = com.menny.android.anysoftkeyboard.R.xml.popup;
break;
case 'h':
aKey.popupCharacters = "\u0125";
aKey.popupResId = com.menny.android.anysoftkeyboard.R.xml.popup;
break;
case 'i':
- aKey.popupCharacters = "\u00ee\u00ef\u00ed\u00ec\u0142";
+ aKey.popupCharacters = "\u00ec\u00ed\u00ee\u00ef\u0142";
aKey.popupResId = com.menny.android.anysoftkeyboard.R.xml.popup;
break;
case 'j':
aKey.popupCharacters = "\u0135";
aKey.popupResId = com.menny.android.anysoftkeyboard.R.xml.popup;
break;
case 'l':
aKey.popupCharacters = "\u0142";
aKey.popupResId = com.menny.android.anysoftkeyboard.R.xml.popup;
break;
case 'o':
- aKey.popupCharacters = "\u00f4\u00f6\u00f2\u00f3\u00f5\u0153\u00f8\u0151";
+ aKey.popupCharacters = "\u00f2\u00f3\u00f4\u00f5\u00f6\u00f8\u0151\u0153";
aKey.popupResId = com.menny.android.anysoftkeyboard.R.xml.popup;
break;
case 's':
- aKey.popupCharacters = "\u00a7\u0161\u015b\u00df\u015d";
+ aKey.popupCharacters = "\u00a7\u00df\u015b\u015d\u0161";
aKey.popupResId = com.menny.android.anysoftkeyboard.R.xml.popup;
break;
case 'u':
- aKey.popupCharacters = "\u00f9\u00fb\u00fc\u00fa\u0171\u016d";
+ aKey.popupCharacters = "\u00f9\u00fa\u00fb\u00fc\u016d\u0171";
aKey.popupResId = com.menny.android.anysoftkeyboard.R.xml.popup;
break;
case 'n':
aKey.popupCharacters = "\u00f1";
aKey.popupResId = com.menny.android.anysoftkeyboard.R.xml.popup;
break;
case 'y':
- aKey.popupCharacters = "\u00ff\u00fd";
+ aKey.popupCharacters = "\u00fd\u00ff";
aKey.popupResId = com.menny.android.anysoftkeyboard.R.xml.popup;
break;
case 'z':
- aKey.popupCharacters = "\u017e\u017c";
+ aKey.popupCharacters = "\u017c\u017e";
aKey.popupResId = com.menny.android.anysoftkeyboard.R.xml.popup;
break;
default:
super.setPopupKeyChars(aKey);
}
}
}
}
| false | true | protected void setPopupKeyChars(Key aKey)
{
if ((aKey.codes != null) && (aKey.codes.length > 0))
{
switch((char)aKey.codes[0])
{
case 'a':
aKey.popupCharacters = "\u00e0\u00e2\u00e1\u00e4\u00e3\u00e6\u00e5\u0105";
aKey.popupResId = com.menny.android.anysoftkeyboard.R.xml.popup;
break;
case 'c':
aKey.popupCharacters = "\u00e7\u010d\u0107\u0109";
aKey.popupResId = com.menny.android.anysoftkeyboard.R.xml.popup;
break;
case 'd':
aKey.popupCharacters = "\u0111";
aKey.popupResId = com.menny.android.anysoftkeyboard.R.xml.popup;
break;
case 'e':
aKey.popupCharacters = "\u00e9\u00e8\u00ea\u00eb\u0119\u20ac";
aKey.popupResId = com.menny.android.anysoftkeyboard.R.xml.popup;
break;
case 'g':
aKey.popupCharacters = "\u011d";
aKey.popupResId = com.menny.android.anysoftkeyboard.R.xml.popup;
break;
case 'h':
aKey.popupCharacters = "\u0125";
aKey.popupResId = com.menny.android.anysoftkeyboard.R.xml.popup;
break;
case 'i':
aKey.popupCharacters = "\u00ee\u00ef\u00ed\u00ec\u0142";
aKey.popupResId = com.menny.android.anysoftkeyboard.R.xml.popup;
break;
case 'j':
aKey.popupCharacters = "\u0135";
aKey.popupResId = com.menny.android.anysoftkeyboard.R.xml.popup;
break;
case 'l':
aKey.popupCharacters = "\u0142";
aKey.popupResId = com.menny.android.anysoftkeyboard.R.xml.popup;
break;
case 'o':
aKey.popupCharacters = "\u00f4\u00f6\u00f2\u00f3\u00f5\u0153\u00f8\u0151";
aKey.popupResId = com.menny.android.anysoftkeyboard.R.xml.popup;
break;
case 's':
aKey.popupCharacters = "\u00a7\u0161\u015b\u00df\u015d";
aKey.popupResId = com.menny.android.anysoftkeyboard.R.xml.popup;
break;
case 'u':
aKey.popupCharacters = "\u00f9\u00fb\u00fc\u00fa\u0171\u016d";
aKey.popupResId = com.menny.android.anysoftkeyboard.R.xml.popup;
break;
case 'n':
aKey.popupCharacters = "\u00f1";
aKey.popupResId = com.menny.android.anysoftkeyboard.R.xml.popup;
break;
case 'y':
aKey.popupCharacters = "\u00ff\u00fd";
aKey.popupResId = com.menny.android.anysoftkeyboard.R.xml.popup;
break;
case 'z':
aKey.popupCharacters = "\u017e\u017c";
aKey.popupResId = com.menny.android.anysoftkeyboard.R.xml.popup;
break;
default:
super.setPopupKeyChars(aKey);
}
}
}
| protected void setPopupKeyChars(Key aKey)
{
if ((aKey.codes != null) && (aKey.codes.length > 0))
{
switch((char)aKey.codes[0])
{
case 'a':
aKey.popupCharacters = "\u00e0\u00e1\u00e2\u00e3\u00e4\u00e5\u00e6\u0105";
aKey.popupResId = com.menny.android.anysoftkeyboard.R.xml.popup;
break;
case 'c':
aKey.popupCharacters = "\u00e7\u0107\u0109\u010d";
aKey.popupResId = com.menny.android.anysoftkeyboard.R.xml.popup;
break;
case 'd':
aKey.popupCharacters = "\u0111";
aKey.popupResId = com.menny.android.anysoftkeyboard.R.xml.popup;
break;
case 'e':
aKey.popupCharacters = "\u00e8\u00e9\u00ea\u00eb\u0119\u20ac";
aKey.popupResId = com.menny.android.anysoftkeyboard.R.xml.popup;
break;
case 'g':
aKey.popupCharacters = "\u011d";
aKey.popupResId = com.menny.android.anysoftkeyboard.R.xml.popup;
break;
case 'h':
aKey.popupCharacters = "\u0125";
aKey.popupResId = com.menny.android.anysoftkeyboard.R.xml.popup;
break;
case 'i':
aKey.popupCharacters = "\u00ec\u00ed\u00ee\u00ef\u0142";
aKey.popupResId = com.menny.android.anysoftkeyboard.R.xml.popup;
break;
case 'j':
aKey.popupCharacters = "\u0135";
aKey.popupResId = com.menny.android.anysoftkeyboard.R.xml.popup;
break;
case 'l':
aKey.popupCharacters = "\u0142";
aKey.popupResId = com.menny.android.anysoftkeyboard.R.xml.popup;
break;
case 'o':
aKey.popupCharacters = "\u00f2\u00f3\u00f4\u00f5\u00f6\u00f8\u0151\u0153";
aKey.popupResId = com.menny.android.anysoftkeyboard.R.xml.popup;
break;
case 's':
aKey.popupCharacters = "\u00a7\u00df\u015b\u015d\u0161";
aKey.popupResId = com.menny.android.anysoftkeyboard.R.xml.popup;
break;
case 'u':
aKey.popupCharacters = "\u00f9\u00fa\u00fb\u00fc\u016d\u0171";
aKey.popupResId = com.menny.android.anysoftkeyboard.R.xml.popup;
break;
case 'n':
aKey.popupCharacters = "\u00f1";
aKey.popupResId = com.menny.android.anysoftkeyboard.R.xml.popup;
break;
case 'y':
aKey.popupCharacters = "\u00fd\u00ff";
aKey.popupResId = com.menny.android.anysoftkeyboard.R.xml.popup;
break;
case 'z':
aKey.popupCharacters = "\u017c\u017e";
aKey.popupResId = com.menny.android.anysoftkeyboard.R.xml.popup;
break;
default:
super.setPopupKeyChars(aKey);
}
}
}
|
diff --git a/rest/src/main/java/org/mayocat/shop/rest/resources/LoginResource.java b/rest/src/main/java/org/mayocat/shop/rest/resources/LoginResource.java
index 5f833d3b..414cc670 100644
--- a/rest/src/main/java/org/mayocat/shop/rest/resources/LoginResource.java
+++ b/rest/src/main/java/org/mayocat/shop/rest/resources/LoginResource.java
@@ -1,80 +1,80 @@
package org.mayocat.shop.rest.resources;
import javax.inject.Inject;
import javax.ws.rs.Consumes;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.FormParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.NewCookie;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.core.UriInfo;
import org.mayocat.shop.authorization.PasswordManager;
import org.mayocat.shop.authorization.cookies.CookieCrypter;
import org.mayocat.shop.authorization.cookies.EncryptionException;
import org.mayocat.shop.model.User;
import org.mayocat.shop.service.UserService;
import org.mayocat.shop.store.StoreException;
import org.xwiki.component.annotation.Component;
@Component("LoginResource")
@Path("/login/")
public class LoginResource implements Resource
{
@Inject
private UserService userService;
@Inject
private PasswordManager passwordManager;
@Inject
private CookieCrypter crypter;
@POST
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response login(@FormParam("username") String username, @FormParam("password") String password,
@FormParam("remember") @DefaultValue("false") Boolean remember, @Context UriInfo uri)
{
try {
User user = userService.findByEmailOrUserName(username);
if (user == null) {
// Don't give more information than this
- return Response.status(Status.UNAUTHORIZED).build();
+ return Response.noContent().status(Status.UNAUTHORIZED).build();
}
if (!passwordManager.verifyPassword(password, user.getPassword())) {
// Don't give more information than this
- return Response.status(Status.UNAUTHORIZED).build();
+ return Response.noContent().status(Status.UNAUTHORIZED).build();
}
// Find out some cookie parameters we will need
int ageWhenRemember = 60 * 60 * 24 * 15; // TODO make configurable
// String domain = uri.geBaseUri().getHost();
// TODO set domain when at least two dots ? Or config ?
// See http://curl.haxx.se/rfc/cookie_spec.html
// Create the new cookies to be sent with the response
NewCookie newUserCookie =
new NewCookie("username", crypter.encrypt(username), "/", null, null, remember ? ageWhenRemember : -1,
false);
NewCookie newPassCookie =
new NewCookie("password", crypter.encrypt(password), "/", null, null, remember ? ageWhenRemember : -1,
false);
return Response.ok().cookie(newUserCookie, newPassCookie).build();
} catch (StoreException e) {
throw new WebApplicationException(e);
} catch (EncryptionException e) {
// Don't give more information than this
throw new WebApplicationException();
}
}
}
| false | true | public Response login(@FormParam("username") String username, @FormParam("password") String password,
@FormParam("remember") @DefaultValue("false") Boolean remember, @Context UriInfo uri)
{
try {
User user = userService.findByEmailOrUserName(username);
if (user == null) {
// Don't give more information than this
return Response.status(Status.UNAUTHORIZED).build();
}
if (!passwordManager.verifyPassword(password, user.getPassword())) {
// Don't give more information than this
return Response.status(Status.UNAUTHORIZED).build();
}
// Find out some cookie parameters we will need
int ageWhenRemember = 60 * 60 * 24 * 15; // TODO make configurable
// String domain = uri.geBaseUri().getHost();
// TODO set domain when at least two dots ? Or config ?
// See http://curl.haxx.se/rfc/cookie_spec.html
// Create the new cookies to be sent with the response
NewCookie newUserCookie =
new NewCookie("username", crypter.encrypt(username), "/", null, null, remember ? ageWhenRemember : -1,
false);
NewCookie newPassCookie =
new NewCookie("password", crypter.encrypt(password), "/", null, null, remember ? ageWhenRemember : -1,
false);
return Response.ok().cookie(newUserCookie, newPassCookie).build();
} catch (StoreException e) {
throw new WebApplicationException(e);
} catch (EncryptionException e) {
// Don't give more information than this
throw new WebApplicationException();
}
}
| public Response login(@FormParam("username") String username, @FormParam("password") String password,
@FormParam("remember") @DefaultValue("false") Boolean remember, @Context UriInfo uri)
{
try {
User user = userService.findByEmailOrUserName(username);
if (user == null) {
// Don't give more information than this
return Response.noContent().status(Status.UNAUTHORIZED).build();
}
if (!passwordManager.verifyPassword(password, user.getPassword())) {
// Don't give more information than this
return Response.noContent().status(Status.UNAUTHORIZED).build();
}
// Find out some cookie parameters we will need
int ageWhenRemember = 60 * 60 * 24 * 15; // TODO make configurable
// String domain = uri.geBaseUri().getHost();
// TODO set domain when at least two dots ? Or config ?
// See http://curl.haxx.se/rfc/cookie_spec.html
// Create the new cookies to be sent with the response
NewCookie newUserCookie =
new NewCookie("username", crypter.encrypt(username), "/", null, null, remember ? ageWhenRemember : -1,
false);
NewCookie newPassCookie =
new NewCookie("password", crypter.encrypt(password), "/", null, null, remember ? ageWhenRemember : -1,
false);
return Response.ok().cookie(newUserCookie, newPassCookie).build();
} catch (StoreException e) {
throw new WebApplicationException(e);
} catch (EncryptionException e) {
// Don't give more information than this
throw new WebApplicationException();
}
}
|
diff --git a/src/uk/me/parabola/mkgmap/combiners/TdbBuilder.java b/src/uk/me/parabola/mkgmap/combiners/TdbBuilder.java
index 161c00ba..2965d6c5 100644
--- a/src/uk/me/parabola/mkgmap/combiners/TdbBuilder.java
+++ b/src/uk/me/parabola/mkgmap/combiners/TdbBuilder.java
@@ -1,265 +1,265 @@
/*
* Copyright (C) 2007 Steve Ratcliffe
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 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.
*
*
* Author: Steve Ratcliffe
* Create date: Dec 9, 2007
*/
package uk.me.parabola.mkgmap.combiners;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import uk.me.parabola.imgfmt.ExitException;
import uk.me.parabola.imgfmt.FileExistsException;
import uk.me.parabola.imgfmt.FileNotWritableException;
import uk.me.parabola.imgfmt.FileSystemParam;
import uk.me.parabola.imgfmt.app.Area;
import uk.me.parabola.imgfmt.app.Coord;
import uk.me.parabola.imgfmt.app.map.Map;
import uk.me.parabola.log.Logger;
import uk.me.parabola.mkgmap.CommandArgs;
import uk.me.parabola.mkgmap.build.MapBuilder;
import uk.me.parabola.mkgmap.general.MapShape;
import uk.me.parabola.tdbfmt.DetailMapBlock;
import uk.me.parabola.tdbfmt.TdbFile;
/**
* Build the TDB file and the overview map.
*
* @author Steve Ratcliffe
*/
public class TdbBuilder implements Combiner {
private static final Logger log = Logger.getLogger(TdbBuilder.class);
private OverviewMap overviewSource;
private TdbFile tdb;
private int parent = 63240000;
private String overviewMapname;
private String overviewMapnumber;
private String areaName;
private int tdbVersion;
/**
* Initialise by saving all the information we require from the command line
* args.
*
* @param args The command line arguments as they are at the end of the list.
* In otherwords if the same argument appears more than once, then it will
*/
public void init(CommandArgs args) {
overviewMapname = args.get("overview-mapname", "osmmap");
overviewMapnumber = args.get("overview-mapnumber", "63240000");
try {
parent = Integer.parseInt(overviewMapnumber);
} catch (NumberFormatException e) {
log.debug("overview map number not an integer", overviewMapnumber);
}
areaName = args.get("area-name", "Overview Map");
int familyId = args.get("family-id", 0);
int productId = args.get("product-id", 1);
short productVersion = (short)args.get("product-version", 100);
String seriesName = args.get("series-name", "OSM map");
String familyName = args.get("family-name", "OSM map");
// Versin 4 is the default. If you really want v3 then the tdb-v3
// option can be used.
if (args.exists("tdb-v3")) {
tdbVersion = TdbFile.TDB_V3;
} else {
tdbVersion = TdbFile.TDB_V407;
}
tdb = new TdbFile(tdbVersion);
tdb.setProductInfo(familyId, productId, productVersion, seriesName,
familyName, areaName);
}
/**
* Called at the end of every map that is to be combined. We only deal
* with IMG files and ignore everything else.
*
* @param finfo Information on the file.
*/
public void onMapEnd(FileInfo finfo) {
if (!finfo.isImg())
return;
addToTdb(finfo);
addToOverviewMap(finfo);
}
/**
* Add the information about the current map to the tdb file.
*
* @param finfo Information about the current .img file.
*/
private void addToTdb(FileInfo finfo) {
DetailMapBlock detail = new DetailMapBlock(tdbVersion);
detail.setArea(finfo.getBounds());
String mapname = finfo.getMapname();
String mapdesc = finfo.getDescription();
detail.setMapName(mapname, mapname);
String desc = mapdesc + " (" + mapname + ')';
detail.setDescription(desc);
detail.setLblDataSize(finfo.getLblsize());
detail.setTreDataSize(finfo.getTresize());
detail.setRgnDataSize(finfo.getRgnsize());
detail.setNetDataSize(finfo.getNetsize());
detail.setNodDataSize(finfo.getNodsize());
log.info("overview-mapname", overviewMapname);
log.info("overview-mapnumber", parent);
detail.setParentMapNumber(parent);
tdb.addDetail(detail);
String[] msgs = finfo.getCopyrights();
for (String m : msgs)
tdb.addCopyright(m);
}
/**
* Add an individual .img file to the overview map.
*
* @param finfo Information about an individual map.
*/
private void addToOverviewMap(FileInfo finfo) {
Area bounds = finfo.getBounds();
//System.out.printf("overview shift %d\n", overviewSource.getShift());
int overviewMask = ((1 << overviewSource.getShift()) - 1);
//System.out.printf("mask %x\n", overviewMask);
//System.out.println("overviewSource.getShift() = " + overviewSource.getShift());
- int maxLon = roundUp(bounds.getMaxLong(), overviewMask);
+ int maxLon = roundDown(bounds.getMaxLong(), overviewMask);
int maxLat = roundUp(bounds.getMaxLat(), overviewMask);
- int minLat = roundDown(bounds.getMinLat(), overviewMask);
+ int minLat = roundUp(bounds.getMinLat(), overviewMask);
int minLon = roundDown(bounds.getMinLong(), overviewMask);
//System.out.printf("maxLat 0x%x, modified=0x%x\n", bounds.getMaxLat(), maxLat);
//System.out.printf("maxLat %f, modified=%f\n", Utils.toDegrees(bounds.getMaxLat()), Utils.toDegrees(maxLat));
//System.out.printf("minLat 0x%x, modified=0x%x\n", bounds.getMinLat(), minLat);
//System.out.printf("minLat %f, modified=%f\n", Utils.toDegrees(bounds.getMinLat()), Utils.toDegrees(minLat));
//System.out.printf("maxLon 0x%x, modified=0x%x\n", bounds.getMaxLong(), maxLon);
//System.out.printf("maxLon %f, modified=%f\n", Utils.toDegrees(bounds.getMaxLong()), Utils.toDegrees(maxLon));
//System.out.printf("minLon 0x%x, modified=0x%x\n", bounds.getMinLong(), minLon);
//System.out.printf("minLon %f, modified=%f\n", Utils.toDegrees(bounds.getMinLong()), Utils.toDegrees(minLon));
// Add a background polygon for this map.
List<Coord> points = new ArrayList<Coord>();
Coord start = new Coord(minLat, minLon);
points.add(start);
overviewSource.addToBounds(start);
Coord co = new Coord(maxLat, minLon);
points.add(co);
overviewSource.addToBounds(co);
co = new Coord(maxLat, maxLon);
points.add(co);
overviewSource.addToBounds(co);
co = new Coord(minLat, maxLon);
points.add(co);
overviewSource.addToBounds(co);
points.add(start);
// Create the background rectangle
MapShape bg = new MapShape();
bg.setType(0x4a);
bg.setPoints(points);
bg.setMinResolution(10);
bg.setName(finfo.getDescription() + '\u001d' + finfo.getMapname());
overviewSource.addShape(bg);
}
private int roundUp(int len, int overviewMask) {
//System.out.printf("before up 0x%x\n", len);
if (len > 0)
return (len + overviewMask) & ~overviewMask;
else
return len & ~overviewMask;
}
private int roundDown(int len, int overviewMask) {
//System.out.printf("before down 0x%x\n", len);
if (len > 0)
return len & ~overviewMask;
else
return -(-len +overviewMask & ~overviewMask);
}
/**
* Called when all the .img files have been processed. We finish up and
* create the TDB file and the overview map.
*/
public void onFinish() {
log.debug("finishing overview");
// We can set the overall bounds easily as it was calcualted as part of
// the overview map.
tdb.setOverview(overviewMapname, overviewSource.getBounds(), overviewMapnumber);
writeTdbFile();
writeOverviewMap();
}
/**
* Write out the overview map.
*/
private void writeOverviewMap() {
MapBuilder mb = new MapBuilder();
mb.setEnableLineCleanFilters(false);
FileSystemParam params = new FileSystemParam();
params.setBlockSize(512);
params.setMapDescription(areaName);
try {
Map map = Map.createMap(overviewMapname, params, overviewMapnumber);
mb.makeMap(map, overviewSource);
map.close();
} catch (FileExistsException e) {
throw new ExitException("Could not create overview map", e);
} catch (FileNotWritableException e) {
throw new ExitException("Could not write to overview map", e);
}
}
/**
* Write out the TDB file at the end of processing.
*/
private void writeTdbFile() {
try {
tdb.write(overviewMapname + ".tdb");
} catch (IOException e) {
log.error("tdb write", e);
throw new ExitException("Could not write the TDB file", e);
}
}
public void setOverviewSource(OverviewMap overviewSource) {
this.overviewSource = overviewSource;
}
}
| false | true | private void addToOverviewMap(FileInfo finfo) {
Area bounds = finfo.getBounds();
//System.out.printf("overview shift %d\n", overviewSource.getShift());
int overviewMask = ((1 << overviewSource.getShift()) - 1);
//System.out.printf("mask %x\n", overviewMask);
//System.out.println("overviewSource.getShift() = " + overviewSource.getShift());
int maxLon = roundUp(bounds.getMaxLong(), overviewMask);
int maxLat = roundUp(bounds.getMaxLat(), overviewMask);
int minLat = roundDown(bounds.getMinLat(), overviewMask);
int minLon = roundDown(bounds.getMinLong(), overviewMask);
//System.out.printf("maxLat 0x%x, modified=0x%x\n", bounds.getMaxLat(), maxLat);
//System.out.printf("maxLat %f, modified=%f\n", Utils.toDegrees(bounds.getMaxLat()), Utils.toDegrees(maxLat));
//System.out.printf("minLat 0x%x, modified=0x%x\n", bounds.getMinLat(), minLat);
//System.out.printf("minLat %f, modified=%f\n", Utils.toDegrees(bounds.getMinLat()), Utils.toDegrees(minLat));
//System.out.printf("maxLon 0x%x, modified=0x%x\n", bounds.getMaxLong(), maxLon);
//System.out.printf("maxLon %f, modified=%f\n", Utils.toDegrees(bounds.getMaxLong()), Utils.toDegrees(maxLon));
//System.out.printf("minLon 0x%x, modified=0x%x\n", bounds.getMinLong(), minLon);
//System.out.printf("minLon %f, modified=%f\n", Utils.toDegrees(bounds.getMinLong()), Utils.toDegrees(minLon));
// Add a background polygon for this map.
List<Coord> points = new ArrayList<Coord>();
Coord start = new Coord(minLat, minLon);
points.add(start);
overviewSource.addToBounds(start);
Coord co = new Coord(maxLat, minLon);
points.add(co);
overviewSource.addToBounds(co);
co = new Coord(maxLat, maxLon);
points.add(co);
overviewSource.addToBounds(co);
co = new Coord(minLat, maxLon);
points.add(co);
overviewSource.addToBounds(co);
points.add(start);
// Create the background rectangle
MapShape bg = new MapShape();
bg.setType(0x4a);
bg.setPoints(points);
bg.setMinResolution(10);
bg.setName(finfo.getDescription() + '\u001d' + finfo.getMapname());
overviewSource.addShape(bg);
}
| private void addToOverviewMap(FileInfo finfo) {
Area bounds = finfo.getBounds();
//System.out.printf("overview shift %d\n", overviewSource.getShift());
int overviewMask = ((1 << overviewSource.getShift()) - 1);
//System.out.printf("mask %x\n", overviewMask);
//System.out.println("overviewSource.getShift() = " + overviewSource.getShift());
int maxLon = roundDown(bounds.getMaxLong(), overviewMask);
int maxLat = roundUp(bounds.getMaxLat(), overviewMask);
int minLat = roundUp(bounds.getMinLat(), overviewMask);
int minLon = roundDown(bounds.getMinLong(), overviewMask);
//System.out.printf("maxLat 0x%x, modified=0x%x\n", bounds.getMaxLat(), maxLat);
//System.out.printf("maxLat %f, modified=%f\n", Utils.toDegrees(bounds.getMaxLat()), Utils.toDegrees(maxLat));
//System.out.printf("minLat 0x%x, modified=0x%x\n", bounds.getMinLat(), minLat);
//System.out.printf("minLat %f, modified=%f\n", Utils.toDegrees(bounds.getMinLat()), Utils.toDegrees(minLat));
//System.out.printf("maxLon 0x%x, modified=0x%x\n", bounds.getMaxLong(), maxLon);
//System.out.printf("maxLon %f, modified=%f\n", Utils.toDegrees(bounds.getMaxLong()), Utils.toDegrees(maxLon));
//System.out.printf("minLon 0x%x, modified=0x%x\n", bounds.getMinLong(), minLon);
//System.out.printf("minLon %f, modified=%f\n", Utils.toDegrees(bounds.getMinLong()), Utils.toDegrees(minLon));
// Add a background polygon for this map.
List<Coord> points = new ArrayList<Coord>();
Coord start = new Coord(minLat, minLon);
points.add(start);
overviewSource.addToBounds(start);
Coord co = new Coord(maxLat, minLon);
points.add(co);
overviewSource.addToBounds(co);
co = new Coord(maxLat, maxLon);
points.add(co);
overviewSource.addToBounds(co);
co = new Coord(minLat, maxLon);
points.add(co);
overviewSource.addToBounds(co);
points.add(start);
// Create the background rectangle
MapShape bg = new MapShape();
bg.setType(0x4a);
bg.setPoints(points);
bg.setMinResolution(10);
bg.setName(finfo.getDescription() + '\u001d' + finfo.getMapname());
overviewSource.addShape(bg);
}
|
diff --git a/orcid-persistence/src/main/java/org/orcid/persistence/jpa/entities/OrcidOauth2TokenDetail.java b/orcid-persistence/src/main/java/org/orcid/persistence/jpa/entities/OrcidOauth2TokenDetail.java
index 7d187579a5..5c74b7eb9c 100644
--- a/orcid-persistence/src/main/java/org/orcid/persistence/jpa/entities/OrcidOauth2TokenDetail.java
+++ b/orcid-persistence/src/main/java/org/orcid/persistence/jpa/entities/OrcidOauth2TokenDetail.java
@@ -1,238 +1,239 @@
/**
* =============================================================================
*
* ORCID (R) Open Source
* http://orcid.org
*
* Copyright (c) 2012-2013 ORCID, Inc.
* Licensed under an MIT-Style License (MIT)
* http://orcid.org/open-source-license
*
* This copyright and license information (including a link to the full license)
* shall be included in its entirety in all copies or substantial portion of
* the software.
*
* =============================================================================
*/
package org.orcid.persistence.jpa.entities;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import java.util.Date;
/**
* 2011-2012 ORCID
*
* @author Declan Newman (declan) Date: 16/04/2012
*/
@Entity
@Table(name = "oauth2_token_detail")
public class OrcidOauth2TokenDetail extends BaseEntity<Long> implements ProfileAware, Comparable<OrcidOauth2TokenDetail> {
/**
*
*/
private static final long serialVersionUID = 1L;
private Long id;
private String tokenValue;
private ProfileEntity profile;
private ClientDetailsEntity clientDetailsEntity;
private boolean approved = false;
private String resourceId;
private String redirectUri;
private String responseType;
private String state;
private String scope;
private String tokenType;
private Date tokenExpiration;
private String refreshTokenValue;
private Date refreshTokenExpiration;
private String authenticationKey;
private Boolean tokenDisabled;
/**
* This should be implemented by all entity classes to return the id of the
* entity represented by the <T> generic argument
*
* @return the id of the entity
*/
@Id
@GeneratedValue(strategy = GenerationType.AUTO, generator = "access_token_seq")
@SequenceGenerator(name = "access_token_seq", sequenceName = "access_token_seq")
@Column(name = "id")
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@Column(name = "token_value", length = 150, unique = true, nullable = true)
public String getTokenValue() {
return tokenValue;
}
public void setTokenValue(String tokenValue) {
this.tokenValue = tokenValue;
}
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "user_orcid")
public ProfileEntity getProfile() {
return profile;
}
public void setProfile(ProfileEntity profile) {
this.profile = profile;
}
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "client_details_id")
public ClientDetailsEntity getClientDetailsEntity() {
return clientDetailsEntity;
}
public void setClientDetailsEntity(ClientDetailsEntity clientDetailsEntity) {
this.clientDetailsEntity = clientDetailsEntity;
}
@Column(name = "refresh_token_expiration")
public Date getRefreshTokenExpiration() {
return refreshTokenExpiration;
}
public void setRefreshTokenExpiration(Date refreshTokenExpiration) {
this.refreshTokenExpiration = refreshTokenExpiration;
}
@Column(name = "refresh_token_value", length = 150, unique = true, nullable = true)
public String getRefreshTokenValue() {
return refreshTokenValue;
}
public void setRefreshTokenValue(String refreshTokenValue) {
this.refreshTokenValue = refreshTokenValue;
}
@Column(name = "is_approved")
public boolean isApproved() {
return approved;
}
public void setApproved(boolean approved) {
this.approved = approved;
}
@Column(name = "redirect_uri", length = 350)
public String getRedirectUri() {
return redirectUri;
}
public void setRedirectUri(String redirectUri) {
this.redirectUri = redirectUri;
}
@Column(name = "response_type", length = 100)
public String getResponseType() {
return responseType;
}
public void setResponseType(String responseType) {
this.responseType = responseType;
}
@Column(name = "state", length = 40)
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
@Column(name = "scope_type", length = 50)
public String getScope() {
return scope;
}
public void setScope(String scope) {
this.scope = scope;
}
@Column(name = "resource_id", length = 50)
public String getResourceId() {
return resourceId;
}
public void setResourceId(String resourceId) {
this.resourceId = resourceId;
}
@Column(name = "token_type", length = 50)
public String getTokenType() {
return tokenType;
}
public void setTokenType(String tokenType) {
this.tokenType = tokenType;
}
@Column(name = "token_expiration")
public Date getTokenExpiration() {
return tokenExpiration;
}
public void setTokenExpiration(Date tokenExpiration) {
this.tokenExpiration = tokenExpiration;
}
@Column(name = "authentication_key", length = 150, unique = true)
public String getAuthenticationKey() {
return authenticationKey;
}
public void setAuthenticationKey(String authenticationKey) {
this.authenticationKey = authenticationKey;
}
@Column(name = "token_disabled")
public Boolean getTokenDisabled() {
return tokenDisabled;
}
public void setTokenDisabled(Boolean tokenDisabled) {
this.tokenDisabled = tokenDisabled;
}
@Override
public int compareTo(OrcidOauth2TokenDetail other) {
- ProfileEntity otherProfileEntity = other.getProfile();
- int compareName = profile.getCreditName().compareTo(otherProfileEntity.getCreditName());
+ ProfileEntity clientProfileEntity = clientDetailsEntity.getProfile();
+ ProfileEntity otherClientProfileEntity = other.getClientDetailsEntity().getProfile();
+ int compareName = clientProfileEntity.getCreditName().compareTo(otherClientProfileEntity.getCreditName());
if (compareName != 0) {
return compareName;
}
Date thisDateCreated = getDateCreated();
if (thisDateCreated != null) {
Date otherDateCreated = other.getDateCreated();
if (otherDateCreated != null) {
int compareDateCreated = thisDateCreated.compareTo(otherDateCreated);
if (compareDateCreated != 0) {
return compareDateCreated;
}
}
}
return tokenValue.compareTo(other.tokenValue);
}
}
| true | true | public int compareTo(OrcidOauth2TokenDetail other) {
ProfileEntity otherProfileEntity = other.getProfile();
int compareName = profile.getCreditName().compareTo(otherProfileEntity.getCreditName());
if (compareName != 0) {
return compareName;
}
Date thisDateCreated = getDateCreated();
if (thisDateCreated != null) {
Date otherDateCreated = other.getDateCreated();
if (otherDateCreated != null) {
int compareDateCreated = thisDateCreated.compareTo(otherDateCreated);
if (compareDateCreated != 0) {
return compareDateCreated;
}
}
}
return tokenValue.compareTo(other.tokenValue);
}
| public int compareTo(OrcidOauth2TokenDetail other) {
ProfileEntity clientProfileEntity = clientDetailsEntity.getProfile();
ProfileEntity otherClientProfileEntity = other.getClientDetailsEntity().getProfile();
int compareName = clientProfileEntity.getCreditName().compareTo(otherClientProfileEntity.getCreditName());
if (compareName != 0) {
return compareName;
}
Date thisDateCreated = getDateCreated();
if (thisDateCreated != null) {
Date otherDateCreated = other.getDateCreated();
if (otherDateCreated != null) {
int compareDateCreated = thisDateCreated.compareTo(otherDateCreated);
if (compareDateCreated != 0) {
return compareDateCreated;
}
}
}
return tokenValue.compareTo(other.tokenValue);
}
|
diff --git a/CBDT/src/cbdt/view/analysis/tree/treemodel/NodeLine.java b/CBDT/src/cbdt/view/analysis/tree/treemodel/NodeLine.java
index 5b1117c..def807d 100644
--- a/CBDT/src/cbdt/view/analysis/tree/treemodel/NodeLine.java
+++ b/CBDT/src/cbdt/view/analysis/tree/treemodel/NodeLine.java
@@ -1,24 +1,24 @@
package cbdt.view.analysis.tree.treemodel;
import cbdt.view.analysis.tree.TreePApplet;
public class NodeLine {
NodeCircle from;
NodeCircle to;
private TreePApplet pApplet;
public NodeLine(TreePApplet pApplet, NodeCircle from, NodeCircle to) {
this.pApplet = pApplet;
this.from = from;
this.to = to;
}
public void draw(){
int x1 = pApplet.getZoomConverter().convertToWindowCoordinatesX(from.getDocumentCoordinateX());
int y1 = pApplet.getZoomConverter().convertToWindowCoordinatesY(from.getDocumentCoordinateY()) + NodeCircle.radius;
int x2 = pApplet.getZoomConverter().convertToWindowCoordinatesX(to.getDocumentCoordinateX());
- int y2 = pApplet.getZoomConverter().convertToWindowCoordinatesX(to.getDocumentCoordinateY()) - NodeCircle.radius;
+ int y2 = pApplet.getZoomConverter().convertToWindowCoordinatesY(to.getDocumentCoordinateY()) - NodeCircle.radius;
pApplet.line(x1, y1, x2, y2);
}
}
| true | true | public void draw(){
int x1 = pApplet.getZoomConverter().convertToWindowCoordinatesX(from.getDocumentCoordinateX());
int y1 = pApplet.getZoomConverter().convertToWindowCoordinatesY(from.getDocumentCoordinateY()) + NodeCircle.radius;
int x2 = pApplet.getZoomConverter().convertToWindowCoordinatesX(to.getDocumentCoordinateX());
int y2 = pApplet.getZoomConverter().convertToWindowCoordinatesX(to.getDocumentCoordinateY()) - NodeCircle.radius;
pApplet.line(x1, y1, x2, y2);
}
| public void draw(){
int x1 = pApplet.getZoomConverter().convertToWindowCoordinatesX(from.getDocumentCoordinateX());
int y1 = pApplet.getZoomConverter().convertToWindowCoordinatesY(from.getDocumentCoordinateY()) + NodeCircle.radius;
int x2 = pApplet.getZoomConverter().convertToWindowCoordinatesX(to.getDocumentCoordinateX());
int y2 = pApplet.getZoomConverter().convertToWindowCoordinatesY(to.getDocumentCoordinateY()) - NodeCircle.radius;
pApplet.line(x1, y1, x2, y2);
}
|
diff --git a/test/tekai/test/ParserTest.java b/test/tekai/test/ParserTest.java
index e007a1b..4f9b663 100644
--- a/test/tekai/test/ParserTest.java
+++ b/test/tekai/test/ParserTest.java
@@ -1,422 +1,422 @@
package tekai.test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import java.util.regex.Pattern;
import org.junit.Test;
import tekai.Expression;
import tekai.Parselet;
import tekai.Parser;
import tekai.standard.AtomParselet;
import tekai.standard.InfixParselet;
import tekai.standard.GroupingParselet;
import tekai.standard.PrefixParselet;
import tekai.standard.BeforeMiddleAfterParselet;
public class ParserTest {
@Test
public void justAnAtom() {
assertParsing("Just a number", "[1]:NUMBER", "1");
assertParsing("Just an identifier", "[abc]:IDENTIFIER", "abc");
}
@Test
public void simpleExpression() {
assertParsing("Simple infix", "([+]:ARITHMETIC [1]:NUMBER [2]:NUMBER)", "1 + 2");
assertParsing("Double infix (left associativity)", "([+]:ARITHMETIC ([+]:ARITHMETIC [1]:NUMBER [2]:NUMBER) [3]:NUMBER)", "1 + 2 + 3");
assertParsing("Double infix with parenthesis", "([+]:ARITHMETIC [1]:NUMBER ([+]:ARITHMETIC [2]:NUMBER [3]:NUMBER))", "1 + (2 + 3)");
}
@Test
public void functions() {
assertParsing("[abc]:FUNCTION", "abc()");
assertParsing("([abc]:FUNCTION [1]:NUMBER)", "abc(1)");
assertParsing("([abc]:FUNCTION [1]:NUMBER [2]:NUMBER)", "abc(1, 2)");
assertParsing("([abc]:FUNCTION [1]:NUMBER [2]:NUMBER [3]:NUMBER)", "abc(1, 2, 3)");
assertParsing("([+]:ARITHMETIC ([abc]:FUNCTION [4]:NUMBER) ([def]:FUNCTION [3]:NUMBER [2]:NUMBER))", "abc(4) + def(3, 2)");
assertParsing("([abc]:FUNCTION ([+]:ARITHMETIC ([+]:ARITHMETIC [2]:NUMBER [1]:NUMBER) [3]:NUMBER))", "abc((2 + 1) + 3)");
assertParsing("([+]:ARITHMETIC ([+]:ARITHMETIC ([+]:ARITHMETIC [1]:NUMBER ([abc]:FUNCTION ([+]:ARITHMETIC [2]:NUMBER [3]:NUMBER) [4]:NUMBER)) [5]:NUMBER) [6]:NUMBER)", "(1 + abc(2 + 3, 4) + 5) + 6");
assertParsing("([abc]:FUNCTION ([def]:FUNCTION [1]:NUMBER) ([ghi]:FUNCTION [2]:NUMBER))", "abc(def(1), ghi(2))");
}
@Test
public void selectFrom() {
assertParsing("([SQL]:SQL ([SELECT]:SELECT [campo1]:IDENTIFIER [campo2]:IDENTIFIER) ([FROM]:FROM [tabela]:IDENTIFIER [tabela2]:IDENTIFIER))", "SELECT campo1, campo2 FROM tabela, tabela2");
assertParsing("([SQL]:SQL ([SELECT]:SELECT [*]:IDENTIFIER) ([FROM]:FROM [tabela]:IDENTIFIER))", "SELECT * FROM tabela");
assertParsing("([SQL]:SQL ([SELECT]:SELECT [*]:IDENTIFIER) ([FROM]:FROM [tabela]:IDENTIFIER ([INNER JOIN]:JOIN [outra_tabela]:IDENTIFIER [xxx]:IDENTIFIER)))", "SELECT * FROM tabela INNER JOIN outra_tabela ON xxx");
}
@Test
public void selectWithWhere(){
assertParsing("([SQL]:SQL ([SELECT]:SELECT [*]:IDENTIFIER) ([FROM]:FROM [tabela]:IDENTIFIER) ([WHERE]:WHERE ([+]:ARITHMETIC [campo]:IDENTIFIER [2]:NUMBER)))", "SELECT * FROM tabela WHERE campo + 2");
assertParsing("([SQL]:SQL ([SELECT]:SELECT [*]:IDENTIFIER) ([FROM]:FROM [tabela]:IDENTIFIER) ([WHERE]:WHERE ([=]:OPERATOR [tabela.campo1]:IDENTIFIER [tabela.campo2]:IDENTIFIER)))", "SELECT * FROM tabela WHERE tabela.campo1 = tabela.campo2");
assertParsing("([SQL]:SQL ([SELECT]:SELECT [*]:IDENTIFIER) ([FROM]:FROM [tabela]:IDENTIFIER) ([WHERE]:WHERE ([AND]:BOOLEAN ([=]:OPERATOR [campo]:IDENTIFIER [2]:NUMBER) ([=]:OPERATOR [id]:IDENTIFIER [3]:NUMBER))))",
"SELECT * FROM tabela WHERE campo = 2 AND id = 3");
assertParsing("([SQL]:SQL ([SELECT]:SELECT [*]:IDENTIFIER) ([FROM]:FROM [tabela]:IDENTIFIER) ([WHERE]:WHERE ([OR]:BOOLEAN ([AND]:BOOLEAN ([=]:OPERATOR [campo]:IDENTIFIER [2]:NUMBER) ([=]:OPERATOR [id]:IDENTIFIER [3]:NUMBER)) ([=]:OPERATOR [campo]:IDENTIFIER [5.5]:NUMBER))))",
"SELECT * FROM tabela WHERE campo = 2 AND id = 3 OR campo = 5.5");
assertParsing("([SQL]:SQL ([SELECT]:SELECT [*]:IDENTIFIER) ([FROM]:FROM [tabela]:IDENTIFIER) ([WHERE]:WHERE ([OR]:BOOLEAN ([AND]:BOOLEAN ([=]:OPERATOR [campo]:IDENTIFIER [2]:NUMBER) ([=]:OPERATOR [id]:IDENTIFIER [35.89]:NUMBER)) ([=]:OPERATOR [campo]:IDENTIFIER [5]:NUMBER))))",
"SELECT * FROM tabela WHERE (campo = 2) AND id = 35.89 OR (campo = 5)");
}
@Test
public void selectWithAlias(){
assertParsing("([SQL]:SQL ([SELECT]:SELECT [tb.campo1]:IDENTIFIER) ([FROM]:FROM [tabela]:IDENTIFIER))", "SELECT tb.campo1 FROM tabela");
assertParsing("([SQL]:SQL ([SELECT]:SELECT ([AS]:ALIAS [campo]:IDENTIFIER [nome]:IDENTIFIER)) ([FROM]:FROM [tabela]:IDENTIFIER))", "SELECT campo AS nome FROM tabela");
assertParsing("([SQL]:SQL ([SELECT]:SELECT ([AS]:ALIAS [tb.campo1]:IDENTIFIER [nome]:IDENTIFIER)) ([FROM]:FROM [tabela]:IDENTIFIER))", "SELECT tb.campo1 AS nome FROM tabela");
}
@Test
public void selectWithConcat(){
assertParsing("([SQL]:SQL ([SELECT]:SELECT ([||]:CONCAT [campo1]:IDENTIFIER [campo2]:IDENTIFIER)) ([FROM]:FROM [tabela]:IDENTIFIER))", "SELECT campo1 || campo2 FROM tabela");
assertParsing("([SQL]:SQL ([SELECT]:SELECT ([||]:CONCAT [campo1]:IDENTIFIER [campo2]:IDENTIFIER [campo3]:IDENTIFIER)) ([FROM]:FROM [tabela]:IDENTIFIER))",
"SELECT campo1 || campo2 || campo3 FROM tabela");
assertParsing("([SQL]:SQL ([SELECT]:SELECT ([||]:CONCAT [campo1]:IDENTIFIER [campo2]:IDENTIFIER ([abc]:FUNCTION [campo3]:IDENTIFIER [campo4]:IDENTIFIER))) ([FROM]:FROM [tabela]:IDENTIFIER))",
"SELECT campo1 || campo2 || abc(campo3, campo4) FROM tabela");
assertParsing("([SQL]:SQL ([SELECT]:SELECT ([||]:CONCAT [campo1]:IDENTIFIER ['string']:STRING ([abc]:FUNCTION [campo3]:IDENTIFIER [campo4]:IDENTIFIER))) ([FROM]:FROM [tabela]:IDENTIFIER))",
"SELECT campo1 || 'string' || abc(campo3, campo4) FROM tabela");
}
@Test
public void selectWithJoin(){
String expected =
"([SQL]:SQL\n" +
" ([SELECT]:SELECT\n" +
" [C120.idcomercial]:IDENTIFIER\n" +
" [C120.idnome]:IDENTIFIER\n" +
" [X040.razsoc]:IDENTIFIER\n" +
" ([as]:ALIAS [X040.docto1]:IDENTIFIER [cnpj]:IDENTIFIER)\n" +
" ([AS]:ALIAS [X030.nomcid]:IDENTIFIER [municipio]:IDENTIFIER)\n" +
" ([AS]:ALIAS [X030.uf]:IDENTIFIER [uf]:IDENTIFIER)\n" +
" ([=]:ALIAS [chave_acesso]:IDENTIFIER [' ']:STRING)\n" +
" ([=]:ALIAS [data_acesso]:IDENTIFIER ['00/00/0000 00:00:00']:STRING)\n" +
" ([AS]:ALIAS [X040.docto2]:IDENTIFIER [inscricao]:IDENTIFIER))\n" +
" ([FROM]:FROM\n" +
" ([AS]:ALIAS [ACT12000]:IDENTIFIER [C120]:IDENTIFIER)\n" +
" ([INNER JOIN]:JOIN\n" +
" ([AS]:ALIAS [AXT04000]:IDENTIFIER [X040]:IDENTIFIER)\n" +
" ([=]:OPERATOR [X040.idnome]:IDENTIFIER [C120.idnome]:IDENTIFIER))\n" +
" ([INNER JOIN]:JOIN\n" +
" ([AS]:ALIAS [AXT02000]:IDENTIFIER [X020A]:IDENTIFIER)\n" +
" ([=]:OPERATOR [X020A.idparametro]:IDENTIFIER [C120.sitsis]:IDENTIFIER))\n" +
" ([INNER JOIN]:JOIN\n" +
" ([AS]:ALIAS [AXT02000]:IDENTIFIER [X020B]:IDENTIFIER)\n" +
" ([=]:OPERATOR [X020B.idparametro]:IDENTIFIER [C120.sitcom]:IDENTIFIER))\n" +
" ([INNER JOIN]:JOIN\n" +
" ([AS]:ALIAS [AXT02000]:IDENTIFIER [X020C]:IDENTIFIER)\n" +
" ([=]:OPERATOR [X020C.idparametro]:IDENTIFIER [C120.sitlas]:IDENTIFIER))\n" +
" ([INNER JOIN]:JOIN\n" +
" ([AS]:ALIAS [AXT03000]:IDENTIFIER [X030]:IDENTIFIER)\n" +
" ([=]:OPERATOR [X030.idcidade]:IDENTIFIER [X040.idcidade]:IDENTIFIER))))";
Pattern spaces = Pattern.compile("\n\\s+", Pattern.MULTILINE);
assertParsing(spaces.matcher(expected).replaceAll(" "), " SELECT C120.idcomercial, "
+ " C120.idnome, "
+ " X040.razsoc, "
+ " X040.docto1 as cnpj, "
+ " X030.nomcid AS municipio, "
+ " X030.uf AS uf, "
+ " chave_acesso = ' ', "
+ " data_acesso = '00/00/0000 00:00:00', "
+ " X040.docto2 AS inscricao "
+ " FROM ACT12000 AS C120 "
+ " INNER JOIN AXT04000 AS X040 ON X040.idnome = C120.idnome "
+ " INNER JOIN AXT02000 AS X020A ON X020A.idparametro = C120.sitsis "
+ " INNER JOIN AXT02000 AS X020B ON X020B.idparametro = C120.sitcom "
+ " INNER JOIN AXT02000 AS X020C ON X020C.idparametro = C120.sitlas "
+ " INNER JOIN AXT03000 AS X030 ON X030.idcidade = X040.idcidade ");
}
@Test
public void selectOrder(){
assertParsing("([SQL]:SQL ([SELECT]:SELECT [*]:IDENTIFIER) ([FROM]:FROM [tabela]:IDENTIFIER) ([WHERE]:WHERE ([=]:OPERATOR [campo]:IDENTIFIER [2]:NUMBER)) ([ORDER BY]:ORDER [campo2]:IDENTIFIER))", "SELECT * FROM tabela WHERE campo = 2 ORDER BY campo2");
assertParsing("([SQL]:SQL ([SELECT]:SELECT [*]:IDENTIFIER) ([FROM]:FROM [tabela]:IDENTIFIER) ([WHERE]:WHERE ([=]:OPERATOR [campo]:IDENTIFIER [2]:NUMBER)) ([ORDER BY]:ORDER [campo2]:IDENTIFIER [campo3]:IDENTIFIER [campo4]:IDENTIFIER))", "SELECT * FROM tabela WHERE campo = 2 ORDER BY campo2, campo3, campo4");
assertParsing("([SQL]:SQL ([SELECT]:SELECT [*]:IDENTIFIER) ([FROM]:FROM [tabela]:IDENTIFIER) ([ORDER BY]:ORDER [campo2]:IDENTIFIER [campo3]:IDENTIFIER [campo4]:IDENTIFIER [ASC]:ORDERING))", "SELECT * FROM tabela ORDER BY campo2, campo3, campo4 ASC");
}
@Test
public void selectLimit(){
assertParsing("([SQL]:SQL ([SELECT]:SELECT [*]:IDENTIFIER) ([FROM]:FROM [tabela]:IDENTIFIER) ([WHERE]:WHERE ([=]:OPERATOR [campo]:IDENTIFIER [2]:NUMBER)) ([LIMIT]:LIMIT [10]:NUMBER))", "SELECT * FROM tabela WHERE campo = 2 LIMIT 10");
assertParsing("([SQL]:SQL ([SELECT]:SELECT [*]:IDENTIFIER) ([FROM]:FROM [tabela]:IDENTIFIER) ([WHERE]:WHERE ([=]:OPERATOR [campo]:IDENTIFIER [2]:NUMBER)) ([ORDER BY]:ORDER [campo2]:IDENTIFIER) ([LIMIT]:LIMIT [10]:NUMBER ([OFFSET]:OFFSET [0]:NUMBER)))", "SELECT * FROM tabela WHERE campo = 2 ORDER BY campo2 LIMIT 10 OFFSET 0");
}
@Test
public void TestCase(){
assertParsing("([SQL]:SQL ([SELECT]:SELECT ([CASE]:CASE [campo]:IDENTIFIER ([WHEN]:WHEN [1]:NUMBER ([THEN]:THEN ['Aguarda Distribuição']:STRING)) ([WHEN]:WHEN [2]:NUMBER ([THEN]:THEN ['Em Análise']:STRING)) ([ELSE]:ELSE ['']:STRING))) ([FROM]:FROM ([as]:ALIAS [sat00100]:IDENTIFIER [sa001]:IDENTIFIER)))",
" SELECT CASE campo"
+ " WHEN 1 THEN 'Aguarda Distribuição'"
+ " WHEN 2 THEN 'Em Análise'"
+ " ELSE '' END "
+ " FROM sat00100 as sa001");
assertParsing("([SQL]:SQL ([SELECT]:SELECT ([CASE]:CASE ([*]:ARITHMETIC [x]:IDENTIFIER [5]:NUMBER) ([WHEN]:WHEN [1]:NUMBER ([THEN]:THEN ([=]:OPERATOR [msg]:IDENTIFIER ['one or two']:STRING))) ([ELSE]:ELSE ([=]:OPERATOR [msg]:IDENTIFIER ['other value than one or two']:STRING)))) ([FROM]:FROM [TABELA]:IDENTIFIER))",
"SELECT CASE x*5 "
+ "WHEN 1 THEN msg = 'one or two' "
+ "ELSE msg = 'other value than one or two'"
+ "END "
+ "FROM TABELA");
}
@Test
public void subSelect(){
assertParsing("([SQL]:SQL ([SELECT]:SELECT [DISTINCT]:DISTINCT [ax050.idinterno]:IDENTIFIER [ax050.descricao]:IDENTIFIER ([||]:CONCAT ([=]:OPERATOR ['sistema']:STRING ([RTRIM]:FUNCTION [ax050.idinterno]:IDENTIFIER)) [' - ']:STRING ([RTRIM]:FUNCTION [ax050.descricao]:IDENTIFIER))) ([FROM]:FROM ([AS]:ALIAS [AXT05000]:IDENTIFIER [ax050]:IDENTIFIER)) ([WHERE]:WHERE ([like]:LIKE [ax050.Descricao]:IDENTIFIER ['SERVIÇOS DE TI%']:STRING)))",
"SELECT DISTINCT ax050.idinterno, ax050.descricao, "
+ " 'sistema' = RTRIM(ax050.idinterno) || ' - ' || RTRIM(ax050.descricao) "
+ " FROM AXT05000 AS ax050 "
+ " WHERE ax050.Descricao like 'SERVIÇOS DE TI%' ");
}
@Test
public void SelectGroup(){
assertParsing("([SQL]:SQL ([SELECT]:SELECT [DISTINCT]:DISTINCT [ax050.idinterno]:IDENTIFIER [ax050.descricao]:IDENTIFIER ([||]:CONCAT ([=]:OPERATOR ['sistema']:STRING ([RTRIM]:FUNCTION [ax050.idinterno]:IDENTIFIER)) [' - ']:STRING ([RTRIM]:FUNCTION [ax050.descricao]:IDENTIFIER))) ([FROM]:FROM ([AS]:ALIAS [AXT05000]:IDENTIFIER [ax050]:IDENTIFIER)) ([WHERE]:WHERE ([like]:LIKE [ax050.Descricao]:IDENTIFIER ['SERVIÇOS DE TI%']:STRING)) ([GROUP BY]:GROUP [campo1]:IDENTIFIER [campo2]:IDENTIFIER))",
"SELECT DISTINCT ax050.idinterno, ax050.descricao, "
+ " 'sistema' = RTRIM(ax050.idinterno) || ' - ' || RTRIM(ax050.descricao) "
+ " FROM AXT05000 AS ax050 "
+ " WHERE ax050.Descricao like 'SERVIÇOS DE TI%' "
+ " GROUP BY campo1, campo2");
}
@Test
public void exceptions() {
// TODO Launch specific exception to specific problems
// TODO Add more and more contextual information to error messages
try {
parse("1 +");
fail("Expected not able to parse an incomplete expression \"1 +\"");
} catch (Exception e) {
// success
}
}
// == Helpers ==
private void assertParsing(String expected, String source) {
assertParsing(null, expected, source);
}
private void assertParsing(String message, String expected, String source) {
Expression expression = parse(source);
assertEquals(message, expected, expression.toString());
}
private Expression parse(String source) {
Parser parser = new Parser(source);
configureParser(parser);
Expression expression = parser.parse();
return expression;
}
private void configureParser(Parser parser) {
// PRECEDENCE (What to parse first. Higher numbers means more precedence)
int x = 1;
final int ATOM = x++;
final int OR = x++;
final int AND = x++;
final int NOT = x++;
final int LIKE = x++;
final int EQUALS = x++;
final int MULTIPLY = x++;
final int SUM = x++;
final int GROUPING = x++;
final int GROUP = x++;
final int FUNCTION = x++;
final int CASE = x++;
final int ORDER = x++;
final int SELECT = x++;
// SQL
parser.register(new Parselet(SELECT) {
@Override
public boolean isPrefixParselet() {
return true;
}
@Override
public String startingRegularExpression() {
return "\\b((?i)SELECT)\\b";
}
@Override
public Expression parse() {
Expression result = new Expression("SQL", "SQL");
Expression fields = new Expression("SELECT", lastMatchTrimmed());
if(canConsume("\\b((?i)DISTINCT)\\b")){
fields.addChildren(new Expression("DISTINCT", lastMatchTrimmed()));
}
do {
Expression field = nextExpression();
if (field.isType("OPERATOR")) {
Expression substitute = new Expression("ALIAS", field.getValue());
substitute.addChildren(field.getChildren());
field = substitute;
}
fields.addChildren(field);
} while (canConsume("\\,"));
consumeIf("\\b((?i)FROM)\\b");
Expression from = new Expression("FROM", "FROM");
do {
from.addChildren(nextExpression());
} while(canConsume("\\,"));
while (canConsume("\\b((?i)INNER(?: OUTER|RIGHT|LEFT)? JOIN)\\b")) {
Expression join = new Expression("JOIN", lastMatchTrimmed());
join.addChildren(nextExpression());
consumeIf("ON");
join.addChildren(nextExpression());
from.addChildren(join);
}
result.addChildren(fields, from);
if(canConsume("\\b((?i)WHERE)\\b")){
Expression where = new Expression("WHERE", "WHERE");
where.addChildren(nextExpression());
result.addChildren(where);
}
if(canConsume("\\b((?i)GROUP\\s+BY)\\b")){
Expression group = new Expression("GROUP", "GROUP BY");
do{
group.addChildren(nextExpression());
}while(canConsume("\\,"));
result.addChildren(group);
}
// result.addChildren(nextExpression());
/* if(canConsume("\\b((?i)HAVING)\\b")){
Expression having = new Expression("HAVING", "HAVING");
do{
having.addChildren(nextExpression());
}while(canConsume("\\,"));
result.addChildren(having);
}*/
if(canConsume("\\b((?i)ORDER\\s+BY)\\b")){
Expression order = new Expression("ORDER", "ORDER BY");
do {
order.addChildren(nextExpression());
} while(canConsume("\\,"));
- if(canConsume("\\ASC|DESC"))
+ if(canConsume("\\b((?i)ASC|DESC)\\b"))
order.addChildren(new Expression("ORDERING", lastMatchTrimmed()));
result.addChildren(order);
}
if(canConsume("\\b((?i)LIMIT)\\b")){
Expression limit = new Expression("LIMIT", "LIMIT");
limit.addChildren(nextExpression());
if(canConsume("\\b((?i)OFFSET)\\b")){
Expression offset = new Expression("OFFSET", "OFFSET");
offset.addChildren(nextExpression());
limit.addChildren(offset);
}
result.addChildren(limit);
}
return result;
}
});
//CASE
parser.register(new Parselet(CASE) {
@Override
public boolean isPrefixParselet() {
return true;
}
@Override
public String startingRegularExpression() {
return "\\b((?i)CASE)\\b";
}
@Override
protected Expression parse() {
Expression ecase = new Expression("CASE", lastMatchTrimmed());
do{
if(canConsume("\\b((?i)WHEN)\\b")){
Expression when = new Expression("WHEN", "WHEN");
when.addChildren(nextExpression());
consumeIf("\\b((?i)THEN)\\b");
Expression then = new Expression("THEN", "THEN");
then.addChildren(nextExpression());
when.addChildren(then);
ecase.addChildren(when);
}else if(canConsume("\\b((?i)ELSE)\\b")){
Expression eelse = new Expression("ELSE", "ELSE");
eelse.addChildren(nextExpression());
ecase.addChildren(eelse);
}else
ecase.addChildren(nextExpression());
}while(cannotConsume("\\b((?i)END)\\b"));
return ecase;
}
});
// BOOLEAN
parser.register(new InfixParselet(OR, "\\b((?i)OR)\\b", "BOOLEAN"));
parser.register(new InfixParselet(AND, "\\b((?i)AND)\\b", "BOOLEAN"));
parser.register(new PrefixParselet(NOT, "\\b((?i)NOT)\\b", "BOOLEAN"));
//LIKE
parser.register(new InfixParselet(LIKE, "\\b((?i)LIKE)\\b", "LIKE"));
// ARITHMETIC
parser.register(new InfixParselet(MULTIPLY, "(\\*|/|%)", "ARITHMETIC"));
parser.register(new InfixParselet(SUM, "(\\+|-)", "ARITHMETIC"));
//ALIAS
parser.register(new InfixParselet(ATOM, "\\b((?i)AS)\\b", "ALIAS"));
//EQUALS (OPERATOR)
parser.register(new InfixParselet(EQUALS, "=", "OPERATOR"));
//CONCAT
parser.register(new BeforeMiddleAfterParselet(ATOM, null, "\\|\\|", null, "CONCAT"));
//GROUP BY
parser.register(new BeforeMiddleAfterParselet(GROUP, "\\b((?i)GROUP\\s+BY)\\b", "\\,", null, "GROUPBY"));
//parser.register(new BeforeMiddleAfterParselet(ORDER, "\\b((?i)HAVING)\\b", "\\,", null, "HAVING"));
// GROUPING (parenthesis)
parser.register(new GroupingParselet(GROUPING, "\\(", "\\)"));
// FUNCTION
parser.register(new BeforeMiddleAfterParselet(FUNCTION, "(\\w+)\\s*\\(", ",", "\\)", "FUNCTION"));
//ORDER BY
//parser.register(new BeforeMiddleAfterParselet(ORDER, "\\b((?i)ORDER\\s+BY)\\b", ",", "(\\b((?i)ASC)\\b|\\b((?i)DESC)\\b)?", "ORDER BY"));
//NUMBER
parser.register(new AtomParselet(ATOM, "\\d+(?:\\.\\d+)?", "NUMBER"));
//STRING
parser.register(new AtomParselet(ATOM, "\\'[^\\']*?\\'", "STRING"));
//IDENTIFIER
parser.register(new AtomParselet(ATOM, "(\\w+\\.\\w+|\\w+|\\*)", "IDENTIFIER"));
}
}
| true | true | private void configureParser(Parser parser) {
// PRECEDENCE (What to parse first. Higher numbers means more precedence)
int x = 1;
final int ATOM = x++;
final int OR = x++;
final int AND = x++;
final int NOT = x++;
final int LIKE = x++;
final int EQUALS = x++;
final int MULTIPLY = x++;
final int SUM = x++;
final int GROUPING = x++;
final int GROUP = x++;
final int FUNCTION = x++;
final int CASE = x++;
final int ORDER = x++;
final int SELECT = x++;
// SQL
parser.register(new Parselet(SELECT) {
@Override
public boolean isPrefixParselet() {
return true;
}
@Override
public String startingRegularExpression() {
return "\\b((?i)SELECT)\\b";
}
@Override
public Expression parse() {
Expression result = new Expression("SQL", "SQL");
Expression fields = new Expression("SELECT", lastMatchTrimmed());
if(canConsume("\\b((?i)DISTINCT)\\b")){
fields.addChildren(new Expression("DISTINCT", lastMatchTrimmed()));
}
do {
Expression field = nextExpression();
if (field.isType("OPERATOR")) {
Expression substitute = new Expression("ALIAS", field.getValue());
substitute.addChildren(field.getChildren());
field = substitute;
}
fields.addChildren(field);
} while (canConsume("\\,"));
consumeIf("\\b((?i)FROM)\\b");
Expression from = new Expression("FROM", "FROM");
do {
from.addChildren(nextExpression());
} while(canConsume("\\,"));
while (canConsume("\\b((?i)INNER(?: OUTER|RIGHT|LEFT)? JOIN)\\b")) {
Expression join = new Expression("JOIN", lastMatchTrimmed());
join.addChildren(nextExpression());
consumeIf("ON");
join.addChildren(nextExpression());
from.addChildren(join);
}
result.addChildren(fields, from);
if(canConsume("\\b((?i)WHERE)\\b")){
Expression where = new Expression("WHERE", "WHERE");
where.addChildren(nextExpression());
result.addChildren(where);
}
if(canConsume("\\b((?i)GROUP\\s+BY)\\b")){
Expression group = new Expression("GROUP", "GROUP BY");
do{
group.addChildren(nextExpression());
}while(canConsume("\\,"));
result.addChildren(group);
}
// result.addChildren(nextExpression());
/* if(canConsume("\\b((?i)HAVING)\\b")){
Expression having = new Expression("HAVING", "HAVING");
do{
having.addChildren(nextExpression());
}while(canConsume("\\,"));
result.addChildren(having);
}*/
if(canConsume("\\b((?i)ORDER\\s+BY)\\b")){
Expression order = new Expression("ORDER", "ORDER BY");
do {
order.addChildren(nextExpression());
} while(canConsume("\\,"));
if(canConsume("\\ASC|DESC"))
order.addChildren(new Expression("ORDERING", lastMatchTrimmed()));
result.addChildren(order);
}
if(canConsume("\\b((?i)LIMIT)\\b")){
Expression limit = new Expression("LIMIT", "LIMIT");
limit.addChildren(nextExpression());
if(canConsume("\\b((?i)OFFSET)\\b")){
Expression offset = new Expression("OFFSET", "OFFSET");
offset.addChildren(nextExpression());
limit.addChildren(offset);
}
result.addChildren(limit);
}
return result;
}
});
| private void configureParser(Parser parser) {
// PRECEDENCE (What to parse first. Higher numbers means more precedence)
int x = 1;
final int ATOM = x++;
final int OR = x++;
final int AND = x++;
final int NOT = x++;
final int LIKE = x++;
final int EQUALS = x++;
final int MULTIPLY = x++;
final int SUM = x++;
final int GROUPING = x++;
final int GROUP = x++;
final int FUNCTION = x++;
final int CASE = x++;
final int ORDER = x++;
final int SELECT = x++;
// SQL
parser.register(new Parselet(SELECT) {
@Override
public boolean isPrefixParselet() {
return true;
}
@Override
public String startingRegularExpression() {
return "\\b((?i)SELECT)\\b";
}
@Override
public Expression parse() {
Expression result = new Expression("SQL", "SQL");
Expression fields = new Expression("SELECT", lastMatchTrimmed());
if(canConsume("\\b((?i)DISTINCT)\\b")){
fields.addChildren(new Expression("DISTINCT", lastMatchTrimmed()));
}
do {
Expression field = nextExpression();
if (field.isType("OPERATOR")) {
Expression substitute = new Expression("ALIAS", field.getValue());
substitute.addChildren(field.getChildren());
field = substitute;
}
fields.addChildren(field);
} while (canConsume("\\,"));
consumeIf("\\b((?i)FROM)\\b");
Expression from = new Expression("FROM", "FROM");
do {
from.addChildren(nextExpression());
} while(canConsume("\\,"));
while (canConsume("\\b((?i)INNER(?: OUTER|RIGHT|LEFT)? JOIN)\\b")) {
Expression join = new Expression("JOIN", lastMatchTrimmed());
join.addChildren(nextExpression());
consumeIf("ON");
join.addChildren(nextExpression());
from.addChildren(join);
}
result.addChildren(fields, from);
if(canConsume("\\b((?i)WHERE)\\b")){
Expression where = new Expression("WHERE", "WHERE");
where.addChildren(nextExpression());
result.addChildren(where);
}
if(canConsume("\\b((?i)GROUP\\s+BY)\\b")){
Expression group = new Expression("GROUP", "GROUP BY");
do{
group.addChildren(nextExpression());
}while(canConsume("\\,"));
result.addChildren(group);
}
// result.addChildren(nextExpression());
/* if(canConsume("\\b((?i)HAVING)\\b")){
Expression having = new Expression("HAVING", "HAVING");
do{
having.addChildren(nextExpression());
}while(canConsume("\\,"));
result.addChildren(having);
}*/
if(canConsume("\\b((?i)ORDER\\s+BY)\\b")){
Expression order = new Expression("ORDER", "ORDER BY");
do {
order.addChildren(nextExpression());
} while(canConsume("\\,"));
if(canConsume("\\b((?i)ASC|DESC)\\b"))
order.addChildren(new Expression("ORDERING", lastMatchTrimmed()));
result.addChildren(order);
}
if(canConsume("\\b((?i)LIMIT)\\b")){
Expression limit = new Expression("LIMIT", "LIMIT");
limit.addChildren(nextExpression());
if(canConsume("\\b((?i)OFFSET)\\b")){
Expression offset = new Expression("OFFSET", "OFFSET");
offset.addChildren(nextExpression());
limit.addChildren(offset);
}
result.addChildren(limit);
}
return result;
}
});
|
diff --git a/src/main/java/org/apache/james/jspf/DNSServiceXBillImpl.java b/src/main/java/org/apache/james/jspf/DNSServiceXBillImpl.java
index f72f27f..d1c113b 100644
--- a/src/main/java/org/apache/james/jspf/DNSServiceXBillImpl.java
+++ b/src/main/java/org/apache/james/jspf/DNSServiceXBillImpl.java
@@ -1,185 +1,187 @@
/****************************************************************
* 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.james.jspf;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import org.apache.james.jspf.core.DNSService;
import org.apache.james.jspf.core.IPAddr;
import org.apache.james.jspf.core.Logger;
import org.xbill.DNS.AAAARecord;
import org.xbill.DNS.ARecord;
import org.xbill.DNS.Lookup;
import org.xbill.DNS.MXRecord;
import org.xbill.DNS.PTRRecord;
import org.xbill.DNS.Record;
import org.xbill.DNS.TXTRecord;
import org.xbill.DNS.TextParseException;
import org.xbill.DNS.Type;
/**
* This class contains helper to get all neccassary DNS infos that are needed
* for SPF
*/
public class DNSServiceXBillImpl implements DNSService {
// Set seconds after which we return and TempError
private static int timeOut = 20;
// The logger
private Logger log;
// The record limit for lookups
private int recordLimit;
/**
* Default Constructor
*/
public DNSServiceXBillImpl(Logger logger) {
this.log = logger;
// Default record limit is 10
this.recordLimit = 10;
}
/**
* @see org.apache.james.jspf.core.DNSService#setTimeOut(int)
*/
public synchronized void setTimeOut(int timeOut) {
DNSServiceXBillImpl.timeOut = timeOut;
}
/**
* @see org.apache.james.jspf.core.DNSService#getLocalDomainNames();
*/
public List getLocalDomainNames() {
List names = new ArrayList();
log.debug("Start Local ipaddress lookup");
try {
InetAddress ia[] = InetAddress.getAllByName(InetAddress
.getLocalHost().getHostName());
for (int i = 0; i < ia.length; i++) {
String host = ia[i].getHostName();
names.add(host);
log.debug("Add hostname " + host + " to list");
}
} catch (UnknownHostException e) {
// just ignore this..
}
return names;
}
/**
* @return the current record limit
*/
public int getRecordLimit() {
return recordLimit;
}
/**
* Set a new limit for the number of records for MX and PTR lookups.
* @param recordLimit
*/
public void setRecordLimit(int recordLimit) {
this.recordLimit = recordLimit;
}
/**
* @see org.apache.james.jspf.core.DNSService#getRecords(java.lang.String, int)
*/
public List getRecords(String hostname, int recordType)
throws TimeoutException {
String recordTypeDescription;
int dnsJavaType;
+ int recordCount = 0;
switch (recordType) {
case A: recordTypeDescription = "A"; dnsJavaType = Type.A; break;
case AAAA: recordTypeDescription = "AAAA"; dnsJavaType = Type.AAAA; break;
case MX: recordTypeDescription = "MX"; dnsJavaType = Type.MX; break;
case PTR: recordTypeDescription = "PTR"; dnsJavaType = Type.PTR; break;
case TXT: recordTypeDescription = "TXT"; dnsJavaType = Type.TXT; break;
// case SPF: recordTypeDescString = "SPF"; dnsJavaType = Type.SPF; break;
default: // TODO fail!
return null;
}
List records;
try {
log.debug("Start "+recordTypeDescription+"-Record lookup for : " + hostname);
Lookup.getDefaultResolver().setTimeout(timeOut);
Lookup query = new Lookup(hostname, dnsJavaType);
Record[] rr = query.run();
int queryResult = query.getResult();
if (queryResult == Lookup.TRY_AGAIN) {
throw new TimeoutException();
}
if (rr != null && rr.length > 0) {
records = new ArrayList();
for (int i = 0; i < rr.length; i++) {
String res;
switch (recordType) {
case A:
ARecord a = (ARecord) rr[i];
res = a.getAddress().getHostAddress();
break;
case AAAA:
AAAARecord aaaa = (AAAARecord) rr[i];
res = aaaa.getAddress().getHostAddress();
break;
case MX:
MXRecord mx = (MXRecord) rr[i];
res = mx.getTarget().toString();
break;
case PTR:
PTRRecord ptr = (PTRRecord) rr[i];
res = IPAddr.stripDot(ptr.getTarget().toString());
break;
case TXT:
TXTRecord txt = (TXTRecord) rr[i];
res = txt.rdataToString();
break;
default:
return null;
}
records.add(res);
}
+ recordCount = rr.length;
} else {
records = null;
}
- log.debug("Found " + rr.length + " "+recordTypeDescription+"-Records");
+ log.debug("Found " + recordCount + " "+recordTypeDescription+"-Records");
} catch (TextParseException e) {
// i think this is the best we could do
log.debug("No "+recordTypeDescription+" Record found for host: " + hostname);
records = null;
}
return records;
}
}
| false | true | public List getRecords(String hostname, int recordType)
throws TimeoutException {
String recordTypeDescription;
int dnsJavaType;
switch (recordType) {
case A: recordTypeDescription = "A"; dnsJavaType = Type.A; break;
case AAAA: recordTypeDescription = "AAAA"; dnsJavaType = Type.AAAA; break;
case MX: recordTypeDescription = "MX"; dnsJavaType = Type.MX; break;
case PTR: recordTypeDescription = "PTR"; dnsJavaType = Type.PTR; break;
case TXT: recordTypeDescription = "TXT"; dnsJavaType = Type.TXT; break;
// case SPF: recordTypeDescString = "SPF"; dnsJavaType = Type.SPF; break;
default: // TODO fail!
return null;
}
List records;
try {
log.debug("Start "+recordTypeDescription+"-Record lookup for : " + hostname);
Lookup.getDefaultResolver().setTimeout(timeOut);
Lookup query = new Lookup(hostname, dnsJavaType);
Record[] rr = query.run();
int queryResult = query.getResult();
if (queryResult == Lookup.TRY_AGAIN) {
throw new TimeoutException();
}
if (rr != null && rr.length > 0) {
records = new ArrayList();
for (int i = 0; i < rr.length; i++) {
String res;
switch (recordType) {
case A:
ARecord a = (ARecord) rr[i];
res = a.getAddress().getHostAddress();
break;
case AAAA:
AAAARecord aaaa = (AAAARecord) rr[i];
res = aaaa.getAddress().getHostAddress();
break;
case MX:
MXRecord mx = (MXRecord) rr[i];
res = mx.getTarget().toString();
break;
case PTR:
PTRRecord ptr = (PTRRecord) rr[i];
res = IPAddr.stripDot(ptr.getTarget().toString());
break;
case TXT:
TXTRecord txt = (TXTRecord) rr[i];
res = txt.rdataToString();
break;
default:
return null;
}
records.add(res);
}
} else {
records = null;
}
log.debug("Found " + rr.length + " "+recordTypeDescription+"-Records");
} catch (TextParseException e) {
// i think this is the best we could do
log.debug("No "+recordTypeDescription+" Record found for host: " + hostname);
records = null;
}
return records;
}
| public List getRecords(String hostname, int recordType)
throws TimeoutException {
String recordTypeDescription;
int dnsJavaType;
int recordCount = 0;
switch (recordType) {
case A: recordTypeDescription = "A"; dnsJavaType = Type.A; break;
case AAAA: recordTypeDescription = "AAAA"; dnsJavaType = Type.AAAA; break;
case MX: recordTypeDescription = "MX"; dnsJavaType = Type.MX; break;
case PTR: recordTypeDescription = "PTR"; dnsJavaType = Type.PTR; break;
case TXT: recordTypeDescription = "TXT"; dnsJavaType = Type.TXT; break;
// case SPF: recordTypeDescString = "SPF"; dnsJavaType = Type.SPF; break;
default: // TODO fail!
return null;
}
List records;
try {
log.debug("Start "+recordTypeDescription+"-Record lookup for : " + hostname);
Lookup.getDefaultResolver().setTimeout(timeOut);
Lookup query = new Lookup(hostname, dnsJavaType);
Record[] rr = query.run();
int queryResult = query.getResult();
if (queryResult == Lookup.TRY_AGAIN) {
throw new TimeoutException();
}
if (rr != null && rr.length > 0) {
records = new ArrayList();
for (int i = 0; i < rr.length; i++) {
String res;
switch (recordType) {
case A:
ARecord a = (ARecord) rr[i];
res = a.getAddress().getHostAddress();
break;
case AAAA:
AAAARecord aaaa = (AAAARecord) rr[i];
res = aaaa.getAddress().getHostAddress();
break;
case MX:
MXRecord mx = (MXRecord) rr[i];
res = mx.getTarget().toString();
break;
case PTR:
PTRRecord ptr = (PTRRecord) rr[i];
res = IPAddr.stripDot(ptr.getTarget().toString());
break;
case TXT:
TXTRecord txt = (TXTRecord) rr[i];
res = txt.rdataToString();
break;
default:
return null;
}
records.add(res);
}
recordCount = rr.length;
} else {
records = null;
}
log.debug("Found " + recordCount + " "+recordTypeDescription+"-Records");
} catch (TextParseException e) {
// i think this is the best we could do
log.debug("No "+recordTypeDescription+" Record found for host: " + hostname);
records = null;
}
return records;
}
|
diff --git a/cvs/trunk/src/version1/src/com/rohanclan/cfml/views/snips/SnipVarParser.java b/cvs/trunk/src/version1/src/com/rohanclan/cfml/views/snips/SnipVarParser.java
index 96b1e6ff..d89c63c7 100644
--- a/cvs/trunk/src/version1/src/com/rohanclan/cfml/views/snips/SnipVarParser.java
+++ b/cvs/trunk/src/version1/src/com/rohanclan/cfml/views/snips/SnipVarParser.java
@@ -1,168 +1,174 @@
/*
* Created on May 6, 2004
*
* TODO To change the template for this generated file go to
* Window - Preferences - Java - Code Generation - Code and Comments
*/
package com.rohanclan.cfml.views.snips;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Calendar;
import java.text.SimpleDateFormat;
import org.eclipse.core.resources.IFile;
import org.eclipse.jface.dialogs.InputDialog;
import org.eclipse.swt.widgets.Shell;
import java.io.File;
/**
* @author Stephen Milligan
*
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Generation - Code and Comments
*/
public class SnipVarParser {
/**
*
*/
public SnipVarParser() {
super();
}
public static String parse(String str, IFile activeFile, Shell shell ) {
String currentFile = "";
String currentFolder = "";
String currentPath = "";
String currentProjectPath = "";
/* not sure why this next block is needed, but it causes the snippet
* insert to fail on QA. Hope I am not misunderstanding something...
* */
if (activeFile != null) {
try {
currentFile = activeFile.getName();
currentPath = activeFile.getRawLocation().toFile().getAbsolutePath();
File fullPath = new File(currentPath);
currentFolder = fullPath.getParent();
currentProjectPath = activeFile.getParent().toString();
String[] path = currentProjectPath.split("/");
if (path.length > 0) {
currentProjectPath = path[path.length-1];
}
// Get your laughing gear round this little lot :)
currentFile = currentFile.replaceAll("\\\\","\\\\\\\\");
currentPath = currentPath.replaceAll("\\\\","\\\\\\\\");
currentFolder = currentFolder.replaceAll("\\\\","\\\\\\\\");
currentProjectPath = currentProjectPath.replaceAll("\\\\","\\\\\\\\");
}
catch (Exception e) {
e.printStackTrace(System.err);
}
}
/*
* $${DATE}
* $${MONTH}
* $${TIME}
* $${DATETIME}
* $${DAYOFWEEK}
* $${CURRENTFILE} - Current file name (just the file)
* $${CURRENTFOLDER} - Current folder (The path to the containing folder)
* $${CURRENTPATH} - Current path (full file name)
* $${CURRENTPRJPATH} - Just the folder
* $${USERNAME} - Current user
* $${MONTHNUMBER} - Month as a number
* $${DAYOFMONTH} - Day of month as a number
* $${DAYOFWEEKNUMBER} - Day of week (the week starts on Sunday)
* $${DATETIME24} - DateTime24 - a 24 hour clock version of datetime.
* $${YEAR} - Current year.
* $${YEAR2DIGIT} - Current two digit year.
*/
Calendar calendar = new GregorianCalendar();
Date currentTime = new Date();
calendar.setTime(currentTime);
String newStr = str;
newStr = newStr.replaceAll("\\$\\$\\{FULLDATE\\}",currentTime.toString());
SimpleDateFormat formatter = new SimpleDateFormat("M/d/yyyy");
String formattedDate = formatter.format(currentTime);
newStr = newStr.replaceAll("\\$\\$\\{DATE\\}",formattedDate);
formatter = new SimpleDateFormat("MMMM");
String formattedMonth = formatter.format(currentTime);
newStr = newStr.replaceAll("\\$\\$\\{MONTH\\}",formattedMonth);
formatter = new SimpleDateFormat("k:mm:ss a");
String formattedTime = formatter.format(currentTime);
newStr = newStr.replaceAll("\\$\\$\\{TIME\\}",formattedTime);
formatter = new SimpleDateFormat("M/d/yyyy K:mm:ss a");
String formattedDateTime = formatter.format(currentTime);
newStr = newStr.replaceAll("\\$\\$\\{DATETIME\\}",formattedDateTime);
formatter = new SimpleDateFormat("EEEE");
String formattedDayOfWeek = formatter.format(currentTime);
newStr = newStr.replaceAll("\\$\\$\\{DAYOFWEEK\\}",formattedDayOfWeek);
newStr = newStr.replaceAll("\\$\\$\\{CURRENTFILE\\}",currentFile);
newStr = newStr.replaceAll("\\$\\$\\{CURRENTFOLDER\\}",currentFolder);
newStr = newStr.replaceAll("\\$\\$\\{CURRENTPATH\\}",currentPath);
newStr = newStr.replaceAll("\\$\\$\\{CURRENTPRJPATH\\}",currentProjectPath);
newStr = newStr.replaceAll("\\$\\$\\{USERNAME\\}",System.getProperty("user.name"));
formatter = new SimpleDateFormat("MM");
String formattedMonthNumber = formatter.format(currentTime);
newStr = newStr.replaceAll("\\$\\$\\{MONTHNUMBER\\}",formattedMonthNumber);
formatter = new SimpleDateFormat("dd");
String formattedDayOfMonth = formatter.format(currentTime);
newStr = newStr.replaceAll("\\$\\$\\{DAYOFMONTH\\}",formattedDayOfMonth);
newStr = newStr.replaceAll("\\$\\$\\{DAYOFWEEKNUMBER\\}",Integer.toString(calendar.get(Calendar.DAY_OF_WEEK)));
formatter = new SimpleDateFormat("M/d/yyyy kk:mm:ss");
String formattedDateTime24 = formatter.format(currentTime);
newStr = newStr.replaceAll("\\$\\$\\{DATETIME24\\}",formattedDateTime24);
formatter = new SimpleDateFormat("yyyy");
String formattedYear = formatter.format(currentTime);
newStr = newStr.replaceAll("\\$\\$\\{YEAR\\}",formattedYear);
formatter = new SimpleDateFormat("yy");
String formattedYear2Digit = formatter.format(currentTime);
newStr = newStr.replaceAll("\\$\\$\\{YEAR2DIGIT\\}",formattedYear2Digit);
- while(newStr.indexOf("$${") > 0) {
+ while(newStr.indexOf("$${") >= 0) {
int expressionStart = newStr.indexOf("$${")+3;
int expressionEnd = newStr.indexOf("}",expressionStart);
String expression = newStr.substring(expressionStart,expressionEnd);
- InputDialog replacementDialog = new InputDialog(shell,"Replace variable",expression,"",null);
+ String stringArray[] = expression.split(":");
+ String variable = stringArray[0];
+ String defaultValue = "";
+ if (stringArray.length > 1) {
+ defaultValue = stringArray[1];
+ }
+ InputDialog replacementDialog = new InputDialog(shell,"Replace variable",variable,defaultValue,null);
if (replacementDialog.open() == org.eclipse.jface.window.Window.OK) {
String replacement = replacementDialog.getValue();
String pattern = "\\$\\$\\{"+expression+"\\}";
newStr = newStr.replaceAll(pattern,replacement);
}
else {
return null;
}
}
return newStr;
}
}
| false | true | public static String parse(String str, IFile activeFile, Shell shell ) {
String currentFile = "";
String currentFolder = "";
String currentPath = "";
String currentProjectPath = "";
/* not sure why this next block is needed, but it causes the snippet
* insert to fail on QA. Hope I am not misunderstanding something...
* */
if (activeFile != null) {
try {
currentFile = activeFile.getName();
currentPath = activeFile.getRawLocation().toFile().getAbsolutePath();
File fullPath = new File(currentPath);
currentFolder = fullPath.getParent();
currentProjectPath = activeFile.getParent().toString();
String[] path = currentProjectPath.split("/");
if (path.length > 0) {
currentProjectPath = path[path.length-1];
}
// Get your laughing gear round this little lot :)
currentFile = currentFile.replaceAll("\\\\","\\\\\\\\");
currentPath = currentPath.replaceAll("\\\\","\\\\\\\\");
currentFolder = currentFolder.replaceAll("\\\\","\\\\\\\\");
currentProjectPath = currentProjectPath.replaceAll("\\\\","\\\\\\\\");
}
catch (Exception e) {
e.printStackTrace(System.err);
}
}
/*
* $${DATE}
* $${MONTH}
* $${TIME}
* $${DATETIME}
* $${DAYOFWEEK}
* $${CURRENTFILE} - Current file name (just the file)
* $${CURRENTFOLDER} - Current folder (The path to the containing folder)
* $${CURRENTPATH} - Current path (full file name)
* $${CURRENTPRJPATH} - Just the folder
* $${USERNAME} - Current user
* $${MONTHNUMBER} - Month as a number
* $${DAYOFMONTH} - Day of month as a number
* $${DAYOFWEEKNUMBER} - Day of week (the week starts on Sunday)
* $${DATETIME24} - DateTime24 - a 24 hour clock version of datetime.
* $${YEAR} - Current year.
* $${YEAR2DIGIT} - Current two digit year.
*/
Calendar calendar = new GregorianCalendar();
Date currentTime = new Date();
calendar.setTime(currentTime);
String newStr = str;
newStr = newStr.replaceAll("\\$\\$\\{FULLDATE\\}",currentTime.toString());
SimpleDateFormat formatter = new SimpleDateFormat("M/d/yyyy");
String formattedDate = formatter.format(currentTime);
newStr = newStr.replaceAll("\\$\\$\\{DATE\\}",formattedDate);
formatter = new SimpleDateFormat("MMMM");
String formattedMonth = formatter.format(currentTime);
newStr = newStr.replaceAll("\\$\\$\\{MONTH\\}",formattedMonth);
formatter = new SimpleDateFormat("k:mm:ss a");
String formattedTime = formatter.format(currentTime);
newStr = newStr.replaceAll("\\$\\$\\{TIME\\}",formattedTime);
formatter = new SimpleDateFormat("M/d/yyyy K:mm:ss a");
String formattedDateTime = formatter.format(currentTime);
newStr = newStr.replaceAll("\\$\\$\\{DATETIME\\}",formattedDateTime);
formatter = new SimpleDateFormat("EEEE");
String formattedDayOfWeek = formatter.format(currentTime);
newStr = newStr.replaceAll("\\$\\$\\{DAYOFWEEK\\}",formattedDayOfWeek);
newStr = newStr.replaceAll("\\$\\$\\{CURRENTFILE\\}",currentFile);
newStr = newStr.replaceAll("\\$\\$\\{CURRENTFOLDER\\}",currentFolder);
newStr = newStr.replaceAll("\\$\\$\\{CURRENTPATH\\}",currentPath);
newStr = newStr.replaceAll("\\$\\$\\{CURRENTPRJPATH\\}",currentProjectPath);
newStr = newStr.replaceAll("\\$\\$\\{USERNAME\\}",System.getProperty("user.name"));
formatter = new SimpleDateFormat("MM");
String formattedMonthNumber = formatter.format(currentTime);
newStr = newStr.replaceAll("\\$\\$\\{MONTHNUMBER\\}",formattedMonthNumber);
formatter = new SimpleDateFormat("dd");
String formattedDayOfMonth = formatter.format(currentTime);
newStr = newStr.replaceAll("\\$\\$\\{DAYOFMONTH\\}",formattedDayOfMonth);
newStr = newStr.replaceAll("\\$\\$\\{DAYOFWEEKNUMBER\\}",Integer.toString(calendar.get(Calendar.DAY_OF_WEEK)));
formatter = new SimpleDateFormat("M/d/yyyy kk:mm:ss");
String formattedDateTime24 = formatter.format(currentTime);
newStr = newStr.replaceAll("\\$\\$\\{DATETIME24\\}",formattedDateTime24);
formatter = new SimpleDateFormat("yyyy");
String formattedYear = formatter.format(currentTime);
newStr = newStr.replaceAll("\\$\\$\\{YEAR\\}",formattedYear);
formatter = new SimpleDateFormat("yy");
String formattedYear2Digit = formatter.format(currentTime);
newStr = newStr.replaceAll("\\$\\$\\{YEAR2DIGIT\\}",formattedYear2Digit);
while(newStr.indexOf("$${") > 0) {
int expressionStart = newStr.indexOf("$${")+3;
int expressionEnd = newStr.indexOf("}",expressionStart);
String expression = newStr.substring(expressionStart,expressionEnd);
InputDialog replacementDialog = new InputDialog(shell,"Replace variable",expression,"",null);
if (replacementDialog.open() == org.eclipse.jface.window.Window.OK) {
String replacement = replacementDialog.getValue();
String pattern = "\\$\\$\\{"+expression+"\\}";
newStr = newStr.replaceAll(pattern,replacement);
}
else {
return null;
}
}
return newStr;
}
| public static String parse(String str, IFile activeFile, Shell shell ) {
String currentFile = "";
String currentFolder = "";
String currentPath = "";
String currentProjectPath = "";
/* not sure why this next block is needed, but it causes the snippet
* insert to fail on QA. Hope I am not misunderstanding something...
* */
if (activeFile != null) {
try {
currentFile = activeFile.getName();
currentPath = activeFile.getRawLocation().toFile().getAbsolutePath();
File fullPath = new File(currentPath);
currentFolder = fullPath.getParent();
currentProjectPath = activeFile.getParent().toString();
String[] path = currentProjectPath.split("/");
if (path.length > 0) {
currentProjectPath = path[path.length-1];
}
// Get your laughing gear round this little lot :)
currentFile = currentFile.replaceAll("\\\\","\\\\\\\\");
currentPath = currentPath.replaceAll("\\\\","\\\\\\\\");
currentFolder = currentFolder.replaceAll("\\\\","\\\\\\\\");
currentProjectPath = currentProjectPath.replaceAll("\\\\","\\\\\\\\");
}
catch (Exception e) {
e.printStackTrace(System.err);
}
}
/*
* $${DATE}
* $${MONTH}
* $${TIME}
* $${DATETIME}
* $${DAYOFWEEK}
* $${CURRENTFILE} - Current file name (just the file)
* $${CURRENTFOLDER} - Current folder (The path to the containing folder)
* $${CURRENTPATH} - Current path (full file name)
* $${CURRENTPRJPATH} - Just the folder
* $${USERNAME} - Current user
* $${MONTHNUMBER} - Month as a number
* $${DAYOFMONTH} - Day of month as a number
* $${DAYOFWEEKNUMBER} - Day of week (the week starts on Sunday)
* $${DATETIME24} - DateTime24 - a 24 hour clock version of datetime.
* $${YEAR} - Current year.
* $${YEAR2DIGIT} - Current two digit year.
*/
Calendar calendar = new GregorianCalendar();
Date currentTime = new Date();
calendar.setTime(currentTime);
String newStr = str;
newStr = newStr.replaceAll("\\$\\$\\{FULLDATE\\}",currentTime.toString());
SimpleDateFormat formatter = new SimpleDateFormat("M/d/yyyy");
String formattedDate = formatter.format(currentTime);
newStr = newStr.replaceAll("\\$\\$\\{DATE\\}",formattedDate);
formatter = new SimpleDateFormat("MMMM");
String formattedMonth = formatter.format(currentTime);
newStr = newStr.replaceAll("\\$\\$\\{MONTH\\}",formattedMonth);
formatter = new SimpleDateFormat("k:mm:ss a");
String formattedTime = formatter.format(currentTime);
newStr = newStr.replaceAll("\\$\\$\\{TIME\\}",formattedTime);
formatter = new SimpleDateFormat("M/d/yyyy K:mm:ss a");
String formattedDateTime = formatter.format(currentTime);
newStr = newStr.replaceAll("\\$\\$\\{DATETIME\\}",formattedDateTime);
formatter = new SimpleDateFormat("EEEE");
String formattedDayOfWeek = formatter.format(currentTime);
newStr = newStr.replaceAll("\\$\\$\\{DAYOFWEEK\\}",formattedDayOfWeek);
newStr = newStr.replaceAll("\\$\\$\\{CURRENTFILE\\}",currentFile);
newStr = newStr.replaceAll("\\$\\$\\{CURRENTFOLDER\\}",currentFolder);
newStr = newStr.replaceAll("\\$\\$\\{CURRENTPATH\\}",currentPath);
newStr = newStr.replaceAll("\\$\\$\\{CURRENTPRJPATH\\}",currentProjectPath);
newStr = newStr.replaceAll("\\$\\$\\{USERNAME\\}",System.getProperty("user.name"));
formatter = new SimpleDateFormat("MM");
String formattedMonthNumber = formatter.format(currentTime);
newStr = newStr.replaceAll("\\$\\$\\{MONTHNUMBER\\}",formattedMonthNumber);
formatter = new SimpleDateFormat("dd");
String formattedDayOfMonth = formatter.format(currentTime);
newStr = newStr.replaceAll("\\$\\$\\{DAYOFMONTH\\}",formattedDayOfMonth);
newStr = newStr.replaceAll("\\$\\$\\{DAYOFWEEKNUMBER\\}",Integer.toString(calendar.get(Calendar.DAY_OF_WEEK)));
formatter = new SimpleDateFormat("M/d/yyyy kk:mm:ss");
String formattedDateTime24 = formatter.format(currentTime);
newStr = newStr.replaceAll("\\$\\$\\{DATETIME24\\}",formattedDateTime24);
formatter = new SimpleDateFormat("yyyy");
String formattedYear = formatter.format(currentTime);
newStr = newStr.replaceAll("\\$\\$\\{YEAR\\}",formattedYear);
formatter = new SimpleDateFormat("yy");
String formattedYear2Digit = formatter.format(currentTime);
newStr = newStr.replaceAll("\\$\\$\\{YEAR2DIGIT\\}",formattedYear2Digit);
while(newStr.indexOf("$${") >= 0) {
int expressionStart = newStr.indexOf("$${")+3;
int expressionEnd = newStr.indexOf("}",expressionStart);
String expression = newStr.substring(expressionStart,expressionEnd);
String stringArray[] = expression.split(":");
String variable = stringArray[0];
String defaultValue = "";
if (stringArray.length > 1) {
defaultValue = stringArray[1];
}
InputDialog replacementDialog = new InputDialog(shell,"Replace variable",variable,defaultValue,null);
if (replacementDialog.open() == org.eclipse.jface.window.Window.OK) {
String replacement = replacementDialog.getValue();
String pattern = "\\$\\$\\{"+expression+"\\}";
newStr = newStr.replaceAll(pattern,replacement);
}
else {
return null;
}
}
return newStr;
}
|
diff --git a/src/org/nutz/ioc/loader/annotation/AnnotationIocLoader.java b/src/org/nutz/ioc/loader/annotation/AnnotationIocLoader.java
index e4fe98d8b..bdd3f9f8e 100644
--- a/src/org/nutz/ioc/loader/annotation/AnnotationIocLoader.java
+++ b/src/org/nutz/ioc/loader/annotation/AnnotationIocLoader.java
@@ -1,253 +1,257 @@
package org.nutz.ioc.loader.annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import org.nutz.castor.Castors;
import org.nutz.ioc.IocException;
import org.nutz.ioc.IocLoader;
import org.nutz.ioc.IocLoading;
import org.nutz.ioc.ObjectLoadException;
import org.nutz.ioc.annotation.InjectName;
import org.nutz.ioc.meta.IocEventSet;
import org.nutz.ioc.meta.IocField;
import org.nutz.ioc.meta.IocObject;
import org.nutz.ioc.meta.IocValue;
import org.nutz.json.Json;
import org.nutz.lang.Lang;
import org.nutz.lang.Mirror;
import org.nutz.lang.Strings;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.resource.Scans;
/**
* 基于注解的Ioc配置
*
* @author wendal([email protected])
*
*/
public class AnnotationIocLoader implements IocLoader {
private static final Log log = Logs.get();
private HashMap<String, IocObject> map = new HashMap<String, IocObject>();
public AnnotationIocLoader(String... packages) {
for (String packageZ : packages)
for (Class<?> classZ : Scans.me().scanPackage(packageZ))
addClass(classZ);
if (map.size() > 0) {
if (log.isInfoEnabled())
log.infof("Scan complete ! Found %s classes in %s base-packages!\nbeans = %s",
map.size(),
packages.length,
Castors.me().castToString(map.keySet()));
} else {
log.warn("NONE Annotation-Class found!! Check your configure or report a bug!! packages="
+ Arrays.toString(packages));
}
}
private void addClass(Class<?> classZ) {
if (classZ.isInterface()
|| classZ.isMemberClass()
|| classZ.isEnum()
|| classZ.isAnnotation()
|| classZ.isAnonymousClass())
return;
int modify = classZ.getModifiers();
if (Modifier.isAbstract(modify) || (!Modifier.isPublic(modify)))
return;
IocBean iocBean = classZ.getAnnotation(IocBean.class);
if (iocBean != null) {
if (log.isDebugEnabled())
log.debugf("Found a Class with Ioc-Annotation : %s", classZ);
// 采用 @IocBean->name
String beanName = iocBean.name();
if (Strings.isBlank(beanName)) {
// 否则采用 @InjectName
InjectName innm = classZ.getAnnotation(InjectName.class);
if (null != innm && !Strings.isBlank(innm.value())) {
beanName = innm.value();
}
// 大哥(姐),您都不设啊!? 那就用 simpleName 吧
else {
beanName = Strings.lowerFirst(classZ.getSimpleName());
}
}
if (map.containsKey(beanName))
throw Lang.makeThrow(IocException.class,
"Duplicate beanName=%s, by %s !! Have been define by %s !!",
beanName,
classZ,
map.get(beanName).getClass());
IocObject iocObject = new IocObject();
iocObject.setType(classZ);
map.put(beanName, iocObject);
iocObject.setSingleton(iocBean.singleton());
if (!Strings.isBlank(iocBean.scope()))
iocObject.setScope(iocBean.scope());
// 看看构造函数都需要什么函数
String[] args = iocBean.args();
// if (null == args || args.length == 0)
// args = iocBean.param();
if (null != args && args.length > 0)
for (String value : args)
iocObject.addArg(convert(value));
// 设置Events
IocEventSet eventSet = new IocEventSet();
iocObject.setEvents(eventSet);
if (!Strings.isBlank(iocBean.create()))
eventSet.setCreate(iocBean.create().trim().intern());
if (!Strings.isBlank(iocBean.depose()))
eventSet.setDepose(iocBean.depose().trim().intern());
if (!Strings.isBlank(iocBean.fetch()))
eventSet.setFetch(iocBean.fetch().trim().intern());
// 处理字段(以@Inject方式,位于字段)
List<String> fieldList = new ArrayList<String>();
Mirror<?> mirror = Mirror.me(classZ);
Field[] fields = mirror.getFields(Inject.class);
for (Field field : fields) {
Inject inject = field.getAnnotation(Inject.class);
// 无需检查,因为字段名是唯一的
// if(fieldList.contains(field.getName()))
// throw duplicateField(classZ,field.getName());
IocField iocField = new IocField();
iocField.setName(field.getName());
IocValue iocValue;
if (Strings.isBlank(inject.value())) {
iocValue = new IocValue();
iocValue.setType(IocValue.TYPE_REFER);
iocValue.setValue(field.getName());
} else
iocValue = convert(inject.value());
iocField.setValue(iocValue);
iocObject.addField(iocField);
fieldList.add(iocField.getName());
}
// 处理字段(以@Inject方式,位于set方法)
Method[] methods;
try {
methods = classZ.getMethods();
}
catch (Exception e) {
// 如果获取失败,就忽略之
- log.info("Fail to call getMethods(), miss class or Security Limit, ignore it", e);
+ log.infof("Fail to call getMethods() in Class=%s, miss class or Security Limit, ignore it", classZ, e);
methods = new Method[0];
}
+ catch (NoClassDefFoundError e) {
+ log.infof("Fail to call getMethods() in Class=%s, miss class or Security Limit, ignore it", classZ, e);
+ methods = new Method[0];
+ }
for (Method method : methods) {
Inject inject = method.getAnnotation(Inject.class);
if (inject == null)
continue;
// 过滤特殊方法
int m = method.getModifiers();
if (Modifier.isAbstract(m) || (!Modifier.isPublic(m)) || Modifier.isStatic(m))
continue;
String methodName = method.getName();
if (methodName.startsWith("set")
&& methodName.length() > 3
&& method.getParameterTypes().length == 1) {
IocField iocField = new IocField();
iocField.setName(Strings.lowerFirst(methodName.substring(3)));
if (fieldList.contains(iocField.getName()))
throw duplicateField(classZ, iocField.getName());
IocValue iocValue;
if (Strings.isBlank(inject.value())) {
iocValue = new IocValue();
iocValue.setType(IocValue.TYPE_REFER);
iocValue.setValue(Strings.lowerFirst(methodName.substring(3)));
} else
iocValue = convert(inject.value());
iocField.setValue(iocValue);
iocObject.addField(iocField);
fieldList.add(iocField.getName());
}
}
// 处理字段(以@IocBean.field方式)
String[] flds = iocBean.fields();
if (flds != null && flds.length > 0) {
for (String fieldInfo : flds) {
if (fieldList.contains(fieldInfo))
throw duplicateField(classZ, fieldInfo);
IocField iocField = new IocField();
if (fieldInfo.contains(":")) { // dao:jndi:dataSource/jdbc形式
String[] datas = fieldInfo.split(":", 2);
// 完整形式, 与@Inject完全一致了
iocField.setName(datas[0]);
iocField.setValue(convert(datas[1]));
iocObject.addField(iocField);
} else {
// 基本形式, 引用与自身同名的bean
iocField.setName(fieldInfo);
IocValue iocValue = new IocValue();
iocValue.setType(IocValue.TYPE_REFER);
iocValue.setValue(fieldInfo);
iocField.setValue(iocValue);
iocObject.addField(iocField);
}
fieldList.add(iocField.getName());
}
}
} else {
if (log.isWarnEnabled()) {
Field[] fields = classZ.getDeclaredFields();
for (Field field : fields)
if (field.getAnnotation(Inject.class) != null) {
log.warnf("class(%s) don't has @IocBean, but field(%s) has @Inject! Miss @IocBean ??",
classZ.getName(),
field.getName());
break;
}
}
}
}
protected IocValue convert(String value) {
IocValue iocValue = new IocValue();
if (value.contains(":")) {
iocValue.setType(value.substring(0, value.indexOf(':')));
iocValue.setValue(value.substring(value.indexOf(':') + 1));
} else {
iocValue.setValue(value); // TODO 是否应该改为默认refer呢?
}
return iocValue;
}
public String[] getName() {
return map.keySet().toArray(new String[map.size()]);
}
public boolean has(String name) {
return map.containsKey(name);
}
public IocObject load(IocLoading loading, String name) throws ObjectLoadException {
if (has(name))
return map.get(name);
throw new ObjectLoadException("Object '" + name + "' without define!");
}
private static final IocException duplicateField(Class<?> classZ, String name) {
return Lang.makeThrow(IocException.class,
"Duplicate filed defined! Class=%s,FileName=%s",
classZ,
name);
}
public String toString() {
return "/*AnnotationIocLoader*/\n" + Json.toJson(map);
}
}
| false | true | private void addClass(Class<?> classZ) {
if (classZ.isInterface()
|| classZ.isMemberClass()
|| classZ.isEnum()
|| classZ.isAnnotation()
|| classZ.isAnonymousClass())
return;
int modify = classZ.getModifiers();
if (Modifier.isAbstract(modify) || (!Modifier.isPublic(modify)))
return;
IocBean iocBean = classZ.getAnnotation(IocBean.class);
if (iocBean != null) {
if (log.isDebugEnabled())
log.debugf("Found a Class with Ioc-Annotation : %s", classZ);
// 采用 @IocBean->name
String beanName = iocBean.name();
if (Strings.isBlank(beanName)) {
// 否则采用 @InjectName
InjectName innm = classZ.getAnnotation(InjectName.class);
if (null != innm && !Strings.isBlank(innm.value())) {
beanName = innm.value();
}
// 大哥(姐),您都不设啊!? 那就用 simpleName 吧
else {
beanName = Strings.lowerFirst(classZ.getSimpleName());
}
}
if (map.containsKey(beanName))
throw Lang.makeThrow(IocException.class,
"Duplicate beanName=%s, by %s !! Have been define by %s !!",
beanName,
classZ,
map.get(beanName).getClass());
IocObject iocObject = new IocObject();
iocObject.setType(classZ);
map.put(beanName, iocObject);
iocObject.setSingleton(iocBean.singleton());
if (!Strings.isBlank(iocBean.scope()))
iocObject.setScope(iocBean.scope());
// 看看构造函数都需要什么函数
String[] args = iocBean.args();
// if (null == args || args.length == 0)
// args = iocBean.param();
if (null != args && args.length > 0)
for (String value : args)
iocObject.addArg(convert(value));
// 设置Events
IocEventSet eventSet = new IocEventSet();
iocObject.setEvents(eventSet);
if (!Strings.isBlank(iocBean.create()))
eventSet.setCreate(iocBean.create().trim().intern());
if (!Strings.isBlank(iocBean.depose()))
eventSet.setDepose(iocBean.depose().trim().intern());
if (!Strings.isBlank(iocBean.fetch()))
eventSet.setFetch(iocBean.fetch().trim().intern());
// 处理字段(以@Inject方式,位于字段)
List<String> fieldList = new ArrayList<String>();
Mirror<?> mirror = Mirror.me(classZ);
Field[] fields = mirror.getFields(Inject.class);
for (Field field : fields) {
Inject inject = field.getAnnotation(Inject.class);
// 无需检查,因为字段名是唯一的
// if(fieldList.contains(field.getName()))
// throw duplicateField(classZ,field.getName());
IocField iocField = new IocField();
iocField.setName(field.getName());
IocValue iocValue;
if (Strings.isBlank(inject.value())) {
iocValue = new IocValue();
iocValue.setType(IocValue.TYPE_REFER);
iocValue.setValue(field.getName());
} else
iocValue = convert(inject.value());
iocField.setValue(iocValue);
iocObject.addField(iocField);
fieldList.add(iocField.getName());
}
// 处理字段(以@Inject方式,位于set方法)
Method[] methods;
try {
methods = classZ.getMethods();
}
catch (Exception e) {
// 如果获取失败,就忽略之
log.info("Fail to call getMethods(), miss class or Security Limit, ignore it", e);
methods = new Method[0];
}
for (Method method : methods) {
Inject inject = method.getAnnotation(Inject.class);
if (inject == null)
continue;
// 过滤特殊方法
int m = method.getModifiers();
if (Modifier.isAbstract(m) || (!Modifier.isPublic(m)) || Modifier.isStatic(m))
continue;
String methodName = method.getName();
if (methodName.startsWith("set")
&& methodName.length() > 3
&& method.getParameterTypes().length == 1) {
IocField iocField = new IocField();
iocField.setName(Strings.lowerFirst(methodName.substring(3)));
if (fieldList.contains(iocField.getName()))
throw duplicateField(classZ, iocField.getName());
IocValue iocValue;
if (Strings.isBlank(inject.value())) {
iocValue = new IocValue();
iocValue.setType(IocValue.TYPE_REFER);
iocValue.setValue(Strings.lowerFirst(methodName.substring(3)));
} else
iocValue = convert(inject.value());
iocField.setValue(iocValue);
iocObject.addField(iocField);
fieldList.add(iocField.getName());
}
}
// 处理字段(以@IocBean.field方式)
String[] flds = iocBean.fields();
if (flds != null && flds.length > 0) {
for (String fieldInfo : flds) {
if (fieldList.contains(fieldInfo))
throw duplicateField(classZ, fieldInfo);
IocField iocField = new IocField();
if (fieldInfo.contains(":")) { // dao:jndi:dataSource/jdbc形式
String[] datas = fieldInfo.split(":", 2);
// 完整形式, 与@Inject完全一致了
iocField.setName(datas[0]);
iocField.setValue(convert(datas[1]));
iocObject.addField(iocField);
} else {
// 基本形式, 引用与自身同名的bean
iocField.setName(fieldInfo);
IocValue iocValue = new IocValue();
iocValue.setType(IocValue.TYPE_REFER);
iocValue.setValue(fieldInfo);
iocField.setValue(iocValue);
iocObject.addField(iocField);
}
fieldList.add(iocField.getName());
}
}
} else {
if (log.isWarnEnabled()) {
Field[] fields = classZ.getDeclaredFields();
for (Field field : fields)
if (field.getAnnotation(Inject.class) != null) {
log.warnf("class(%s) don't has @IocBean, but field(%s) has @Inject! Miss @IocBean ??",
classZ.getName(),
field.getName());
break;
}
}
}
}
| private void addClass(Class<?> classZ) {
if (classZ.isInterface()
|| classZ.isMemberClass()
|| classZ.isEnum()
|| classZ.isAnnotation()
|| classZ.isAnonymousClass())
return;
int modify = classZ.getModifiers();
if (Modifier.isAbstract(modify) || (!Modifier.isPublic(modify)))
return;
IocBean iocBean = classZ.getAnnotation(IocBean.class);
if (iocBean != null) {
if (log.isDebugEnabled())
log.debugf("Found a Class with Ioc-Annotation : %s", classZ);
// 采用 @IocBean->name
String beanName = iocBean.name();
if (Strings.isBlank(beanName)) {
// 否则采用 @InjectName
InjectName innm = classZ.getAnnotation(InjectName.class);
if (null != innm && !Strings.isBlank(innm.value())) {
beanName = innm.value();
}
// 大哥(姐),您都不设啊!? 那就用 simpleName 吧
else {
beanName = Strings.lowerFirst(classZ.getSimpleName());
}
}
if (map.containsKey(beanName))
throw Lang.makeThrow(IocException.class,
"Duplicate beanName=%s, by %s !! Have been define by %s !!",
beanName,
classZ,
map.get(beanName).getClass());
IocObject iocObject = new IocObject();
iocObject.setType(classZ);
map.put(beanName, iocObject);
iocObject.setSingleton(iocBean.singleton());
if (!Strings.isBlank(iocBean.scope()))
iocObject.setScope(iocBean.scope());
// 看看构造函数都需要什么函数
String[] args = iocBean.args();
// if (null == args || args.length == 0)
// args = iocBean.param();
if (null != args && args.length > 0)
for (String value : args)
iocObject.addArg(convert(value));
// 设置Events
IocEventSet eventSet = new IocEventSet();
iocObject.setEvents(eventSet);
if (!Strings.isBlank(iocBean.create()))
eventSet.setCreate(iocBean.create().trim().intern());
if (!Strings.isBlank(iocBean.depose()))
eventSet.setDepose(iocBean.depose().trim().intern());
if (!Strings.isBlank(iocBean.fetch()))
eventSet.setFetch(iocBean.fetch().trim().intern());
// 处理字段(以@Inject方式,位于字段)
List<String> fieldList = new ArrayList<String>();
Mirror<?> mirror = Mirror.me(classZ);
Field[] fields = mirror.getFields(Inject.class);
for (Field field : fields) {
Inject inject = field.getAnnotation(Inject.class);
// 无需检查,因为字段名是唯一的
// if(fieldList.contains(field.getName()))
// throw duplicateField(classZ,field.getName());
IocField iocField = new IocField();
iocField.setName(field.getName());
IocValue iocValue;
if (Strings.isBlank(inject.value())) {
iocValue = new IocValue();
iocValue.setType(IocValue.TYPE_REFER);
iocValue.setValue(field.getName());
} else
iocValue = convert(inject.value());
iocField.setValue(iocValue);
iocObject.addField(iocField);
fieldList.add(iocField.getName());
}
// 处理字段(以@Inject方式,位于set方法)
Method[] methods;
try {
methods = classZ.getMethods();
}
catch (Exception e) {
// 如果获取失败,就忽略之
log.infof("Fail to call getMethods() in Class=%s, miss class or Security Limit, ignore it", classZ, e);
methods = new Method[0];
}
catch (NoClassDefFoundError e) {
log.infof("Fail to call getMethods() in Class=%s, miss class or Security Limit, ignore it", classZ, e);
methods = new Method[0];
}
for (Method method : methods) {
Inject inject = method.getAnnotation(Inject.class);
if (inject == null)
continue;
// 过滤特殊方法
int m = method.getModifiers();
if (Modifier.isAbstract(m) || (!Modifier.isPublic(m)) || Modifier.isStatic(m))
continue;
String methodName = method.getName();
if (methodName.startsWith("set")
&& methodName.length() > 3
&& method.getParameterTypes().length == 1) {
IocField iocField = new IocField();
iocField.setName(Strings.lowerFirst(methodName.substring(3)));
if (fieldList.contains(iocField.getName()))
throw duplicateField(classZ, iocField.getName());
IocValue iocValue;
if (Strings.isBlank(inject.value())) {
iocValue = new IocValue();
iocValue.setType(IocValue.TYPE_REFER);
iocValue.setValue(Strings.lowerFirst(methodName.substring(3)));
} else
iocValue = convert(inject.value());
iocField.setValue(iocValue);
iocObject.addField(iocField);
fieldList.add(iocField.getName());
}
}
// 处理字段(以@IocBean.field方式)
String[] flds = iocBean.fields();
if (flds != null && flds.length > 0) {
for (String fieldInfo : flds) {
if (fieldList.contains(fieldInfo))
throw duplicateField(classZ, fieldInfo);
IocField iocField = new IocField();
if (fieldInfo.contains(":")) { // dao:jndi:dataSource/jdbc形式
String[] datas = fieldInfo.split(":", 2);
// 完整形式, 与@Inject完全一致了
iocField.setName(datas[0]);
iocField.setValue(convert(datas[1]));
iocObject.addField(iocField);
} else {
// 基本形式, 引用与自身同名的bean
iocField.setName(fieldInfo);
IocValue iocValue = new IocValue();
iocValue.setType(IocValue.TYPE_REFER);
iocValue.setValue(fieldInfo);
iocField.setValue(iocValue);
iocObject.addField(iocField);
}
fieldList.add(iocField.getName());
}
}
} else {
if (log.isWarnEnabled()) {
Field[] fields = classZ.getDeclaredFields();
for (Field field : fields)
if (field.getAnnotation(Inject.class) != null) {
log.warnf("class(%s) don't has @IocBean, but field(%s) has @Inject! Miss @IocBean ??",
classZ.getName(),
field.getName());
break;
}
}
}
}
|
diff --git a/src/edu/sc/seis/sod/database/DatabaseManager.java b/src/edu/sc/seis/sod/database/DatabaseManager.java
index 7a95bfed1..d6294ffbb 100644
--- a/src/edu/sc/seis/sod/database/DatabaseManager.java
+++ b/src/edu/sc/seis/sod/database/DatabaseManager.java
@@ -1,52 +1,55 @@
package edu.sc.seis.sod.database;
import java.lang.reflect.*;
import java.sql.*;
import java.util.*;
/**
* DatabaseManager.java
*
*
* Created: Thu Oct 3 14:27:47 2002
*
* @author <a href="mailto:">Srinivasa Telukutla</a>
* @version
*/
public class DatabaseManager {
private DatabaseManager() {
}
public static AbstractDatabaseManager getDatabaseManager(Properties props, String type) {
+ String className = null;
try {
if(databaseManager != null) return databaseManager;
//use reflection to get the appropriate Database Manager.
- String className = getDatabaseType(props);
+ className = getDatabaseType(props);
Class[] constructorArgTypes = new Class[1];
constructorArgTypes[0] = Properties.class;
Class externalClass = Class.forName(className);
Constructor constructor =
externalClass.getConstructor(constructorArgTypes);
Object[] constructorArgs = new Object[1];
constructorArgs[0] = props;
Object obj =
constructor.newInstance(constructorArgs);
databaseManager = (AbstractDatabaseManager)obj;
return databaseManager;
} catch(Exception e) {
e.printStackTrace();
- return null;
+ System.out.println("Unable to load "+className);
+ System.exit(0);
+ return null;
}
}
private static String getDatabaseType(Properties props) {
if(props == null) return "edu.sc.seis.sod.database.HSqlDbManager";
String rtnValue = props.getProperty("edu.sc.seis.sod.databasetype");
if(rtnValue != null) return rtnValue;
return "edu.sc.seis.sod.database.HSqlDbManager";
}
private static AbstractDatabaseManager databaseManager;
}// DatabaseManager
| false | true | public static AbstractDatabaseManager getDatabaseManager(Properties props, String type) {
try {
if(databaseManager != null) return databaseManager;
//use reflection to get the appropriate Database Manager.
String className = getDatabaseType(props);
Class[] constructorArgTypes = new Class[1];
constructorArgTypes[0] = Properties.class;
Class externalClass = Class.forName(className);
Constructor constructor =
externalClass.getConstructor(constructorArgTypes);
Object[] constructorArgs = new Object[1];
constructorArgs[0] = props;
Object obj =
constructor.newInstance(constructorArgs);
databaseManager = (AbstractDatabaseManager)obj;
return databaseManager;
} catch(Exception e) {
e.printStackTrace();
return null;
}
}
| public static AbstractDatabaseManager getDatabaseManager(Properties props, String type) {
String className = null;
try {
if(databaseManager != null) return databaseManager;
//use reflection to get the appropriate Database Manager.
className = getDatabaseType(props);
Class[] constructorArgTypes = new Class[1];
constructorArgTypes[0] = Properties.class;
Class externalClass = Class.forName(className);
Constructor constructor =
externalClass.getConstructor(constructorArgTypes);
Object[] constructorArgs = new Object[1];
constructorArgs[0] = props;
Object obj =
constructor.newInstance(constructorArgs);
databaseManager = (AbstractDatabaseManager)obj;
return databaseManager;
} catch(Exception e) {
e.printStackTrace();
System.out.println("Unable to load "+className);
System.exit(0);
return null;
}
}
|
diff --git a/GUI.java b/GUI.java
index e6a55abb..34d1f8bf 100644
--- a/GUI.java
+++ b/GUI.java
@@ -1,2690 +1,2690 @@
////////////////////////////////////////////////////////////////////////////////
//
// RMG - Reaction Mechanism Generator
//
// Copyright (c) 2002-2009 Prof. William H. Green ([email protected]) and the
// RMG Team ([email protected])
//
// 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.
//
////////////////////////////////////////////////////////////////////////////////
/**
* @author User1
*
*/
/*
* GUI.java creates a Graphical User Interface (GUI) for Prof.
* Green's Group's Reaction Mechanism Generator (RMG). More information
* on RMG may be found at: http://www.sourceforge.net/projects/rmg
*
* Michael Harper Jr.
* MIT Chemical Engineering
* Green Group
*
* Last updated: March 3, 2009
* - Modified reactants & inert gas input table (Initial Conditions tab)
* -- If user adds "Inert Gas", the entry must be "N2", "Ar", or "Ne"; otherwise, an error message is displayed to the user (but the GUI's entries remain untouched).
* - Modified how RMG-GUI writes the "condition.txt" file
* -- If user does not add all of the necessary information for the condition.txt file, an error message is displayed (the GUI's entries remain untouched) and no condition.txt file will be written.
* -- If user does not add any "Comments" to be placed in the header of the condition.txt file, a warning if displayed
* - Modified how RMG-GUI reads the "condition.txt" file
* -- If condition.txt file is missing a field, GUI instructs user which field is missing (and where it should be located in file)
* -- If condition.txt file contains unknown entries (e.g. units of Temperature not equal to K, F, or C), GUI informs user that entry is incorrect and gives user available options
* Last updated: February 17, 2009
* - Adapted GUI to handle new condition.txt file format
* -- Different location of SpectroscopicDataEstimator
* -- PressureDependence replacing ModelEnlarger + PDepKineticsEstimator
* -- No FinishController options
*
* Currently:
* - creates & displays GUI
* - creates .txt file related to running RMG
* * condition.txt : file containing all inputs (species, tolerances, etc.)
*
* Improvements:
*
*/
import jing.gui.*;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.JFormattedTextField;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.ListCellRenderer;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.io.*;
import java.util.*;
import jing.chem.PrimaryThermoLibrary;
import jing.chem.Species;
import jing.chemParser.ChemParser;
public class GUI extends JPanel implements ActionListener {
public static void main(String[] args) {
String workingDir = System.getenv("RMG");
System.setProperty("RMG.workingDirectory", workingDir);
theApp = new GUI();
theApp.createAndShowGUI();
}
private void createAndShowGUI() {
GUIWindow frame = new GUIWindow("RMG", this);
frame.setContentPane(theApp.mainPanel);
Dimension wndSize = frame.getToolkit().getScreenSize();
frame.setBounds(wndSize.width*3/16, wndSize.height/16, wndSize.width*5/8, wndSize.height*7/8);
frame.setVisible(true);
}
public GUI() {
super(new GridLayout(1,1));
// Create main panel + individual tabs
JTabbedPane tabbedPanel = new JTabbedPane();
JComponent tabInputs = createTabInputs();
JComponent tabInitialization = createTabInitialization();
JComponent tabTermination = createTabTermination();
JComponent tabSolver = createTabSolver();
JComponent tabOptions = createTabOptions();
JComponent tabSensitivity = createTabSensitivity();
// Add the individual tabs to the main panel
tabbedPanel.addTab("Initial Conditions", null, tabInputs, "Specify Reactants, Inerts, & Temperature/Pressure Model");
tabbedPanel.addTab("Thermochemical Libraries", null, tabInitialization, "Specify Thermochemical Library");
tabbedPanel.addTab("Termination", null, tabTermination, "Specify Simulation Termination Conditions");
tabbedPanel.addTab("Dynamic Simulator", null, tabSolver, "Specify Solver Tolerances");
tabbedPanel.addTab("Additional Options", null, tabOptions, "Specify Other Options");
tabbedPanel.addTab("Sensitivity Analysis", null, tabSensitivity, "Specify Error/Sensitivity Analysis Criteria");
tabbedPanel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
// Create the main panel to contain the main tabbed panel
mainPanel = new JPanel();
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.PAGE_AXIS));
mainPanel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
// Create & fill boxes to display panels
Box Main1 = Box.createHorizontalBox();
Box Main2 = Box.createHorizontalBox();
Box Main3 = Box.createVerticalBox();
Main1.add(tabbedPanel);
JPanel submitConditionFile = new JPanel();
Main2.add(submitConditionFile);
Main3.add(Main1);
Main3.add(Main2);
mainPanel.add(Main3);
// Change preferences on Submit button
JPanel comments = new JPanel();
comments.add(new JLabel("Comments to add to file's header:"));
headerComments = new JTextArea(3,20);
JScrollPane headerScroll = new JScrollPane(headerComments);
comments.add(headerScroll);
comments.add(save = new JButton("Save"));
save.addActionListener(this);
save.setActionCommand("saveCondition");
save.setToolTipText("Press to save file");
comments.add(saveAndRun = new JButton("Save and Run"));
saveAndRun.addActionListener(this);
saveAndRun.setActionCommand("runCondition");
saveAndRun.setToolTipText("Press to save and run file");
submitConditionFile.add(comments);
submitConditionFile.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createTitledBorder
("Create Initialization File: condition.txt"), BorderFactory.createEmptyBorder(5,5,5,5)));
}
public void initializeJCB(JComboBox[] all) {
ListCellRenderer centerJComboBoxRenderer = new CenterJCBRenderer();
//TableCellRenderer centerTableRenderer = new CenterTRenderer();
for (int i=0; i<all.length; i++) {
all[i].addActionListener(this);
all[i].setRenderer(centerJComboBoxRenderer);
all[i].setSelectedIndex(0);
}
}
/* TabInputs: Initial Conditions
This tab allows the user to input the initial conditions
(species, temperature, & pressure) of the system
The user must input the following information:
- Each species
* Identity
* Concentration
* Units
- Temperature & Pressure
* Model: Constant
* Value(s) and Units(s)
Additionally, the user is asked to specify the reactivity of each species:
- Reactive: Normal species that RMG will react based on library
- Unreactive: Species that RMG will only react based on IncludeSpecies.txt (see GJB work for more details)
- Inert Gas:
The user is asked to supply an adjacency list for the species if it is reactive.
*/
public JComponent createTabInputs() {
// Create cell renderers for JComboBox/JTable - CENTER text
ListCellRenderer centerJComboBoxRenderer = new CenterJCBRenderer();
TableCellRenderer centerRenderer = new CenterTRenderer();
/* Create the "Species" panel
- This panel will allow the user to enter information about each species.
- Each species must be given a name, concentration, units, and reactivity
- If the reactivity is "Reactive," the user must supply an adjacency list for the molecule
This may be done by giving the location of the species .mol file or InChI
- If the reactivity is "Unreactive," the user must supply the location of the IncludeSpecies.txt file
- All of this information is stored in a table which the user can add/remove data
*/
JPanel Species = new JPanel();
// Create the "speciesData" subpanel
// This subpanel holds the data for each species
JPanel speciesData = new JPanel();
// Create labels
JLabel labelName = new JLabel("Name");
JLabel labelInChI = new JLabel("InChI");
JLabel labelConc = new JLabel("Concentration");
JLabel labelUnit = new JLabel("Units");
JLabel labelReact = new JLabel("Reactivity");
// Create boxes to store each of the pieces of data
Box boxName = Box.createVerticalBox();
Box boxInchi = Box.createVerticalBox();
Box boxConc = Box.createVerticalBox();
Box boxUnit = Box.createVerticalBox();
Box boxReact = Box.createVerticalBox();
// Add labels and data fields to boxes
boxName.add(labelName);
boxName.add(NameInput = new JTextField());
NameInput.setPreferredSize(new Dimension (75,25));
NameInput.setHorizontalAlignment(JTextField.CENTER);
NameInput.addActionListener(this);
boxInchi.add(labelInChI);
boxInchi.add(InChIInput = new JTextField());
InChIInput.setPreferredSize(new Dimension (150,25));
InChIInput.setHorizontalAlignment(JTextField.CENTER);
InChIInput.addActionListener(this);
boxConc.add(labelConc);
boxConc.add(ConcInput = new JTextField());
ConcInput.setPreferredSize(new Dimension(30,25));
ConcInput.setHorizontalAlignment(JTextField.CENTER);
ConcInput.addActionListener(this);
boxUnit.add(labelUnit);
boxUnit.add(UnitsInput = new JComboBox(concUnits));
UnitsInput.setSelectedIndex(0);
UnitsInput.setRenderer(centerJComboBoxRenderer);
UnitsInput.addActionListener(this);
boxReact.add(labelReact);
boxReact.add(ReactiveInput = new JComboBox(reactive));
ReactiveInput.setRenderer(centerJComboBoxRenderer);
ReactiveInput.setSelectedIndex(0);
ReactiveInput.addActionListener(this);
// Add the boxes to the "speciesData" subpanel
speciesData.add(boxName);
speciesData.add(boxInchi);
speciesData.add(boxConc);
speciesData.add(boxUnit);
speciesData.add(boxReact);
// Create the "speciesButton" panel
// This subpanel holds the add/remove buttons
JPanel speciesButton = new JPanel();
// Create the buttons: "Add" and "Remove"
JButton AddInput = new JButton("Add");
AddButtonListener addListenerInput = new AddButtonListener();
AddInput.addActionListener(addListenerInput);
AddInput.setActionCommand("AddInput");
AddInput.setToolTipText("Press to submit data for molecule");
JButton DeleteInput = new JButton("Remove");
DeleteButtonListener deleteListenerInput = new DeleteButtonListener();
DeleteInput.addActionListener(deleteListenerInput);
DeleteInput.setActionCommand("DeleteInput");
DeleteInput.setToolTipText("Press to delete molecule's data");
// Add the box to the "speciesButton" subpanel
speciesButton.add(AddInput);
speciesButton.add(DeleteInput);
// Create the "speciesTable" subpanel
JPanel speciesTable = new JPanel();
// Create table to hold the species data
tableInput = new JTable(tmodelInput = new MyTableModelInput());
tableInput.setPreferredScrollableViewportSize(new Dimension(500,50));
tableInput.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
tableInput.getColumnModel().getColumn(0).setPreferredWidth(75);
tableInput.getColumnModel().getColumn(1).setPreferredWidth(100);
tableInput.getColumnModel().getColumn(2).setPreferredWidth(75);
tableInput.getColumnModel().getColumn(3).setPreferredWidth(100);
tableInput.getColumnModel().getColumn(4).setPreferredWidth(150);
// Create a scroll panel and add it to "speciesTable" subpanel
JScrollPane scrollInput = new JScrollPane(tableInput);
scrollInput.setBorder(BorderFactory.createLoweredBevelBorder());
for (int i=0; i<tableInput.getColumnCount(); i++) {
TableColumn column = tableInput.getColumnModel().getColumn(i);
column.setCellRenderer(centerRenderer);
}
speciesTable.add(scrollInput);
// Create the "speciesAList" subpanel
JPanel speciesAList = new JPanel();
// Create text field where the user can visualize the adjacency list
speciesAdjList = new JTextArea(5,13);
// Add text field to a scroll panel
JScrollPane scrollAdjList = new JScrollPane(speciesAdjList);
scrollAdjList.setBorder(BorderFactory.createLoweredBevelBorder());
Box adj = Box.createVerticalBox();
adj.add(new JLabel("Adjacency List"));
adj.add(scrollAdjList);
speciesAList.add(adj);
// Create the "speciesIS" subpanel
// If at least one of the species is "Unreactive," the user must specify the path of IncludeSpecies.txt
JPanel speciesIS = new JPanel();
// Create the label for the speciesIS subpanel
JLabel labelIS = new JLabel("Location of IncludeSpecies.txt: ");
// Populate the speicesIS subpanel
speciesIS.add(labelIS);
speciesIS.add(isPath = new JTextField(20));
speciesIS.add(isButton = new JButton("Change"));
ChangeButtonListener addListenerIS = new ChangeButtonListener();
isButton.addActionListener(addListenerIS);
isButton.setActionCommand("isPath");
// Update the subpanel's properties
isPath.addActionListener(this);
isPath.setEditable(false);
// Create boxes to store all of the species subpanels
Box species1 = Box.createHorizontalBox();
Box species2 = Box.createHorizontalBox();
Box species3 = Box.createHorizontalBox();
Box species4 = Box.createHorizontalBox();
Box species5 = Box.createHorizontalBox();
Box speciesTotal = Box.createVerticalBox();
// Add the subpanels to the boxes
species1.add(speciesData);
species2.add(speciesButton);
species2.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
species3.add(speciesTable);
species4.add(speciesAList);
species4.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
species5.add(speciesIS);
speciesTotal.add(species1);
speciesTotal.add(species4);
speciesTotal.add(species2);
speciesTotal.add(species3);
speciesTotal.add(species5);
// Add the boxes to the main panel "Species"
Species.add(speciesTotal);
Species.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createTitledBorder("Species"),
BorderFactory.createEmptyBorder(5,5,5,5)));
/* Create the "Temperature" panel
The user must specify which temperature model to use.
Note: As of 10-Feb-2009, the only option is "Constant"
The user must also specify a list of temperatures to build the model
*/
JPanel Temperature = new JPanel();
// Create the "tempModel" subpanel
JPanel tempModel = new JPanel();
tempModel.setBorder(BorderFactory.createEmptyBorder(0,0,10,0));
// Create the labels
JLabel tempModelLabel = new JLabel("Select Model: ");
// Add the labels to the panel
tempModel.add(tempModelLabel);
tempModel.add(tempModelCombo = new JComboBox(tpModel));
// Adjust the labels properties
tempModelCombo.setSelectedIndex(0);
tempModelCombo.addActionListener(this);
tempModelCombo.setRenderer(centerJComboBoxRenderer);
// Create the "tempValues" subpanel
JPanel tempValues = new JPanel();
// Create the labels
JLabel valueTLabel = new JLabel("List of Temperatures");
JLabel unitTLabel = new JLabel("Units");
// Create the data entries and edit their properties
tempConstant = new JTextArea(3,10);
tempConstantUnit = new JComboBox(tempUnits);
tempConstantUnit.addActionListener(this);
tempConstantUnit.setRenderer(centerJComboBoxRenderer);
tempConstantUnit.setSelectedIndex(0);
// Create scroll panel for list of temperatures
JScrollPane tempScroll = new JScrollPane(tempConstant);
tempScroll.setBorder(BorderFactory.createLoweredBevelBorder());
// Create boxes to store labels and data
Box leftT = Box.createVerticalBox();
Box rightT = Box.createVerticalBox();
// Add labels and data to boxes
leftT.add(valueTLabel);
leftT.add(tempScroll);
rightT.add(unitTLabel);
rightT.add(tempConstantUnit);
// Add boxes to "tempValues" subpanel
tempValues.add(leftT);
tempValues.add(rightT);
// Create boxes for Temperature panel
Box temp1 = Box.createHorizontalBox();
Box temp2 = Box.createHorizontalBox();
Box temp = Box.createVerticalBox();
// Populate boxes
temp1.add(tempModel);
temp2.add(tempValues);
temp.add(temp1);
temp.add(temp2);
// Add box to "Temperature" panel
Temperature.add(temp);
Temperature.setBorder(BorderFactory.createTitledBorder("Temperature"));
/* Create the "Pressure" panel
The user must specify which pressure model to use.
Note: As of 10-Feb-2009, the only option is "Constant"
The user must also specify a list of pressures to build the model
*/
JPanel Pressure = new JPanel();
// Create the "pressModel" subpanel
JPanel pressModel = new JPanel();
pressModel.setBorder(BorderFactory.createEmptyBorder(0,0,10,0));
// Create the labels
JLabel pressModelLabel = new JLabel("Select Model: ");
// Add the labels to the panel
pressModel.add(pressModelLabel);
pressModel.add(pressModelCombo = new JComboBox(tpModel));
// Adjust the labels properties
pressModelCombo.setSelectedIndex(0);
pressModelCombo.addActionListener(this);
pressModelCombo.setRenderer(centerJComboBoxRenderer);
// Create the "pressValues" subpanel
JPanel pressValues = new JPanel();
// Create the labels
JLabel valuePLabel = new JLabel("List of Pressures");
JLabel unitPLabel = new JLabel("Units");
// Create the data entries and edit their properties
pressConstant = new JTextArea(3,10);
pressConstantUnit = new JComboBox(pressUnits);
pressConstantUnit.addActionListener(this);
pressConstantUnit.setRenderer(centerJComboBoxRenderer);
pressConstantUnit.setSelectedIndex(0);
// Create scroll panel for list of pressures
JScrollPane pressScroll = new JScrollPane(pressConstant);
pressScroll.setBorder(BorderFactory.createLoweredBevelBorder());
// Create boxes to store labels and data
Box leftP = Box.createVerticalBox();
Box rightP = Box.createVerticalBox();
// Add labels and data to boxes
leftP.add(valuePLabel);
leftP.add(pressScroll);
rightP.add(unitPLabel);
rightP.add(pressConstantUnit);
// Add boxes to "pressValues" subpanel
pressValues.add(leftP);
pressValues.add(rightP);
// Create boxes for Pressure panel
Box press1 = Box.createHorizontalBox();
Box press2 = Box.createHorizontalBox();
Box press = Box.createVerticalBox();
// Populate boxes
press1.add(pressModel);
press2.add(pressValues);
press.add(press1);
press.add(press2);
// Add box to "Pressure" panel
Pressure.add(press);
Pressure.setBorder(BorderFactory.createTitledBorder("Pressure"));
// Create boxes for the PressAndTemp combined panel
Box PressAndTemp = Box.createHorizontalBox();
PressAndTemp.add(Temperature);
PressAndTemp.add(Pressure);
// Create the PressAndTemp combined panel
JPanel tempandpress = new JPanel();
tempandpress.add(PressAndTemp);
tempandpress.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createTitledBorder("Temperature & Pressure"),
BorderFactory.createEmptyBorder(5,5,5,5)));
// Create boxes for the entire Inputs tab
Box TabTotal = Box.createVerticalBox();
TabTotal.add(Species);
TabTotal.add(tempandpress);
// Create the panel for the entire Input tab
JPanel input = new JPanel();
input.add(TabTotal);
input.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createTitledBorder("Initial Conditions"),
BorderFactory.createEmptyBorder(5,5,5,5)));
JScrollPane scrolltab2 = new JScrollPane(input);
scrolltab2.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
return scrolltab2;
}
/* Tab0: Initialization
This tab allows the user to input the initialization specifications of the simulation.
The user must input the following information:
- Whether to restart the prior simulation
- The database
- The primary thermodynamic library
- The reaction model enlarger
- The dynamic simulator
* The time steps for integration
* The absolute tolerance
* The relative tolerance
- The primary reaction library
* Name
* Location
*/
public JComponent createTabInitialization() {
// Create cellrenderers for JComboBox/JTable - CENTER text
TableCellRenderer centerTableRenderer = new CenterTRenderer();
// Create the "Database" panel
JPanel Database = new JPanel();
Database.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createTitledBorder("Main database"),
BorderFactory.createEmptyBorder(5,5,5,5)));
// Populate the "Database" panel
JLabel databaseLabel = new JLabel("Choose database");
Database.add(databaseLabel);
databaseLabel.setToolTipText("Default = RMG/databases/RMG_database");
Database.add(databasePath = new JTextField(25));
databasePath.setText(System.getProperty("RMG.workingDirectory") +
"/databases/RMG_database");
databasePath.setEditable(false);
Database.add(databaseButton = new JButton("Select"));
ChangeButtonListener addListenerDatabase = new ChangeButtonListener();
databaseButton.addActionListener(addListenerDatabase);
databaseButton.setActionCommand("databasePath");
// Create the Primary Thermodynamic Library (PTL) panel
JPanel PTL = new JPanel();
PTL.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createTitledBorder("Primary Thermo Library"),
BorderFactory.createEmptyBorder(5,5,5,5)));
// Create PTL Name label
JPanel ptlName = new JPanel();
ptlName.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
// Populate the label
JLabel ptlNameLabel = new JLabel("Name:");
ptlName.add(ptlNameLabel);
ptlName.add(ptlLibName = new JTextField(20));
// Create PTL Location label
JPanel ptlLoc = new JPanel();
ptlLoc.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
// Populate the label
JLabel ptlLocationLabel = new JLabel("Location:");
ptlLoc.add(ptlLocationLabel);
ptlLocationLabel.setToolTipText("Default = " +
"RMG/databases/RMG_database/thermo/primaryThermoLibrary");
ptlLoc.add(ptlPath = new JTextField(20));
ptlLoc.add(ptlButton = new JButton("Select"));
ChangeButtonListener ptlAddListenerLib = new ChangeButtonListener();
ptlButton.addActionListener(ptlAddListenerLib);
ptlButton.setActionCommand("ptlPath");
// Create table and scroll panel to store PTL(s)
tablePTL = new JTable(tmodelPTL = new MyTableModelPRL());
tablePTL.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
tablePTL.setPreferredScrollableViewportSize(new Dimension(600,50));
tablePTL.getColumnModel().getColumn(0).setPreferredWidth(100);
tablePTL.getColumnModel().getColumn(1).setPreferredWidth(500);
for (int i=0; i<tablePTL.getColumnCount(); i++) {
TableColumn column = tablePTL.getColumnModel().getColumn(i);
column.setCellRenderer(centerTableRenderer);
}
JScrollPane scrollPTL = new JScrollPane(tablePTL);
scrollPTL.setBorder(BorderFactory.createLoweredBevelBorder());
// Create boxes to display the PTL table
Box PTLtable1 = Box.createHorizontalBox();
Box PTLtable2 = Box.createHorizontalBox();
Box PTLtable3 = Box.createHorizontalBox();
Box PTLtable4 = Box.createHorizontalBox();
Box PTLtable5 = Box.createVerticalBox();
// Fill the boxes with the appropriate components of the table
PTLtable1.add(AddPTL = new JButton("Add"));
AddButtonListener addListenerPTL = new AddButtonListener();
AddPTL.addActionListener(addListenerPTL);
AddPTL.setActionCommand("AddPTL");
AddPTL.setToolTipText("Press to submit PTL Name & Location");
PTLtable1.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
PTLtable2.add(DeletePTL = new JButton("Remove"));
DeleteButtonListener deleteListenerPTL = new DeleteButtonListener();
DeletePTL.addActionListener(deleteListenerPTL);
DeletePTL.setActionCommand("DeletePTL");
DeletePTL.setToolTipText("Press to remove PTL Name & Location");
PTLtable3.add(PTLtable1);
PTLtable3.add(PTLtable2);
PTLtable4.add(scrollPTL);
PTLtable5.add(ptlName);
PTLtable5.add(ptlLoc);
PTLtable5.add(PTLtable3);
PTLtable5.add(PTLtable4);
PTL.add(PTLtable5);
// Initialize the PTL with the RMG default library
// This library contains H and H2, which cannot be estimated using Benson's group additivity scheme
PRLVector initialPTL = new PRLVector(0, "Default_H_H2", databasePath.getText()+"/thermo/primaryThermoLibrary");
tmodelPTL.updatePRL(initialPTL);
// Create the Primary Reaction Library (PRL) panel
JPanel PRL = new JPanel();
PRL.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createTitledBorder("Primary Reaction Library"),
BorderFactory.createEmptyBorder(5,5,5,5)));
// Create PRL Name label
JPanel prlName = new JPanel();
prlName.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
// Populate the label
JLabel prlNameLabel = new JLabel("Name:");
prlName.add(prlNameLabel);
prlName.add(prlLibName = new JTextField(20));
// Create PRL Location label
JPanel prlLoc = new JPanel();
prlLoc.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
// Populate the label
JLabel prlLocationLabel = new JLabel("Location:");
prlLoc.add(prlLocationLabel);
prlLocationLabel.setToolTipText("Default = " +
"RMG/databases/RMG_database/primaryReactionLibrary/");
prlLoc.add(prlPath = new JTextField(20));
prlLoc.add(prlButton = new JButton("Select"));
ChangeButtonListener prlAddListenerLib = new ChangeButtonListener();
prlButton.addActionListener(prlAddListenerLib);
prlButton.setActionCommand("prlPath");
// Create table and scroll panel to store PRL(s)
tablePRL = new JTable(tmodelPRL = new MyTableModelPRL());
tablePRL.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
tablePRL.setPreferredScrollableViewportSize(new Dimension(600,50));
tablePRL.getColumnModel().getColumn(0).setPreferredWidth(100);
tablePRL.getColumnModel().getColumn(1).setPreferredWidth(500);
for (int i=0; i<tablePRL.getColumnCount(); i++) {
TableColumn column = tablePRL.getColumnModel().getColumn(i);
column.setCellRenderer(centerTableRenderer);
}
JScrollPane scrollPRL = new JScrollPane(tablePRL);
scrollPRL.setBorder(BorderFactory.createLoweredBevelBorder());
// Create boxes to display the PRL table
Box PRLtable1 = Box.createHorizontalBox();
Box PRLtable2 = Box.createHorizontalBox();
Box PRLtable3 = Box.createHorizontalBox();
Box PRLtable4 = Box.createHorizontalBox();
Box PRLtable5 = Box.createVerticalBox();
// Fill the boxes with the appropriate components of the table
PRLtable1.add(AddPRL = new JButton("Add"));
AddButtonListener addListenerPRL = new AddButtonListener();
AddPRL.addActionListener(addListenerPRL);
AddPRL.setActionCommand("AddPRL");
AddPRL.setToolTipText("Press to submit PRL Name & Location");
PRLtable1.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
PRLtable2.add(DeletePRL = new JButton("Remove"));
DeleteButtonListener deleteListenerPRL = new DeleteButtonListener();
DeletePRL.addActionListener(deleteListenerPRL);
DeletePRL.setActionCommand("DeletePRL");
DeletePRL.setToolTipText("Press to remove PRL Name & Location");
PRLtable3.add(PRLtable1);
PRLtable3.add(PRLtable2);
PRLtable4.add(scrollPRL);
PRLtable5.add(prlName);
PRLtable5.add(prlLoc);
PRLtable5.add(PRLtable3);
PRLtable5.add(PRLtable4);
PRL.add(PRLtable5);
// Create the Seed Mechanism (SM) panel
JPanel SM = new JPanel();
SM.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createTitledBorder("Seed Mechanism"),
BorderFactory.createEmptyBorder(5,5,5,5)));
// Create SM Name label
JPanel smName = new JPanel();
smName.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
// Populate the label
JLabel smNameLabel = new JLabel("Name:");
smName.add(smNameLabel);
smName.add(smLibName = new JTextField(20));
// Create SM Location label
JPanel smLoc = new JPanel();
smLoc.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
// Populate the label
JLabel smLocationLabel = new JLabel("Location:");
smLoc.add(smLocationLabel);
smLocationLabel.setToolTipText("Default = " +
"RMG/databases/RMG_database/SeedMechanism/combustion_core/version5");
smLoc.add(smPath = new JTextField(20));
smLoc.add(smButton = new JButton("Select"));
ChangeButtonListener smAddListenerLib = new ChangeButtonListener();
smButton.addActionListener(smAddListenerLib);
smButton.setActionCommand("smPath");
// Create table and scroll panel to store SM(s)
tableSM = new JTable(tmodelSM = new MyTableModelPRL());
tableSM.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
tableSM.setPreferredScrollableViewportSize(new Dimension(600,50));
tableSM.getColumnModel().getColumn(0).setPreferredWidth(100);
tableSM.getColumnModel().getColumn(1).setPreferredWidth(500);
for (int i=0; i<tableSM.getColumnCount(); i++) {
TableColumn column = tableSM.getColumnModel().getColumn(i);
column.setCellRenderer(centerTableRenderer);
}
JScrollPane scrollSM = new JScrollPane(tableSM);
scrollSM.setBorder(BorderFactory.createLoweredBevelBorder());
// Create boxes to display the PRL table
Box SMtable1 = Box.createHorizontalBox();
Box SMtable2 = Box.createHorizontalBox();
Box SMtable3 = Box.createHorizontalBox();
Box SMtable4 = Box.createHorizontalBox();
Box SMtable5 = Box.createVerticalBox();
// Fill the boxes with the appropriate components of the table
SMtable1.add(AddSM = new JButton("Add"));
AddButtonListener addListenerSM = new AddButtonListener();
AddSM.addActionListener(addListenerSM);
AddSM.setActionCommand("AddSM");
AddSM.setToolTipText("Press to submit Seed Mechanism Name & Location");
SMtable1.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
SMtable2.add(DeleteSM = new JButton("Remove"));
DeleteButtonListener deleteListenerSM = new DeleteButtonListener();
DeleteSM.addActionListener(deleteListenerSM);
DeleteSM.setActionCommand("DeleteSM");
DeleteSM.setToolTipText("Press to remove Seed Mechanism Name & Location");
SMtable3.add(SMtable1);
SMtable3.add(SMtable2);
SMtable4.add(scrollSM);
SMtable5.add(smName);
SMtable5.add(smLoc);
SMtable5.add(SMtable3);
SMtable5.add(SMtable4);
SM.add(SMtable5);
// Create & fill box for Initialization tab
Box TabTotal = Box.createVerticalBox();
TabTotal.add(Database);
TabTotal.add(PTL);
TabTotal.add(PRL);
TabTotal.add(SM);
// Create the thermochemLibrary panel
JPanel thermochemLibrary = new JPanel();
thermochemLibrary.add(TabTotal);
thermochemLibrary.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createTitledBorder(
"Thermochemistry Libraries"), BorderFactory.createEmptyBorder(10,10,10,10)));
// Embed the thermochemistry panel in a scroll panel
JScrollPane scrolltab = new JScrollPane(thermochemLibrary);
scrolltab.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
return scrolltab;
}
public JComponent createTabSolver() {
// Create cellrenderers for JComboBox/JTable - CENTER text
ListCellRenderer centerJComboBoxRenderer = new CenterJCBRenderer();
// Create the Dynamic Simulator (DS) panel
JPanel DS = new JPanel();
DS.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createTitledBorder("Dynamic Simulator"),
BorderFactory.createEmptyBorder(5,5,5,5)));
// Create the DS subpanel: Solver
JPanel dsSolver = new JPanel();
dsSolver.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
// Populate the Solver subpanel
JLabel solverLabel = new JLabel("Select Dynamic Simulator");
dsSolver.add(solverLabel);
solverLabel.setToolTipText("Default = DASSL");
dsSolver.add(simulatorCombo = new JComboBox(simOptions));
simulatorCombo.addActionListener(this);
simulatorCombo.setRenderer(centerJComboBoxRenderer);
simulatorCombo.setSelectedIndex(0);
simulatorCombo.setActionCommand("saOnOff");
// Create the DS subpanel: aTolPanel
JPanel aTolPanel = new JPanel();
aTolPanel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
// Populate the aTolPanel subpanel
JLabel aToleranceLabel = new JLabel("Select absolute tolerance");
aTolPanel.add(aToleranceLabel);
aToleranceLabel.setToolTipText("Suggested value = 1E-12");
aTolPanel.add(aTolerance = new JTextField());
aTolerance.setPreferredSize(new Dimension(100,25));
aTolerance.addActionListener(this);
aTolerance.setHorizontalAlignment(JTextField.CENTER);
aTolerance.setText("1E-12");
// Create the DS subpanel: rTolPanel
JPanel rTolPanel = new JPanel();
rTolPanel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
// Populate the rTolPanel subpanel
JLabel rToleranceLabel = new JLabel("Select relative tolerance");
rTolPanel.add(rToleranceLabel);
rToleranceLabel.setToolTipText("Suggested value = 1E-3");
rTolPanel.add(rTolerance = new JTextField());
rTolerance.setPreferredSize(new Dimension(100,25));
rTolerance.addActionListener(this);
rTolerance.setHorizontalAlignment(JTextField.CENTER);
rTolerance.setText("1E-3");
// Create the DS subpanel: interConv
JPanel interConv = new JPanel();
interConv.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
// Populate the subpanel
JLabel multiConvLabel = new JLabel("Intermediate Conversions");
interConv.add(multiConvLabel);
multiConvLabel.setToolTipText("Default = AUTO");
interConv.add(multiConv = new JTextArea(2,15));
multiConv.setText("AUTO");
// Create the DS subpanel: interTS
JPanel interTS = new JPanel();
interTS.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
// Populate the subpanel
JLabel multiTSLabel = new JLabel("Intermediate Time Steps");
interTS.add(multiTSLabel);
multiTSLabel.setToolTipText("Default = AUTO");
interTS.add(multiTS = new JTextArea(2,15));
multiTS.setEnabled(false);
multiTS.setText("AUTO");
// Create boxes for DS panel
Box ds = Box.createVerticalBox();
// Populate the boxes
ds.add(dsSolver);
ds.add(aTolPanel);
ds.add(rTolPanel);
ds.add(interConv);
ds.add(interTS);
DS.add(ds);
// Create the total pressure dependence panel
JPanel totalPDep = new JPanel();
totalPDep.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createTitledBorder("Pressure dependence"),
BorderFactory.createEmptyBorder(5,5,5,5)));
// Create the Pressure dependence (Pdep) model panel
JPanel Pdep = new JPanel();
Pdep.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
// Populate the ME panel
JLabel modelLabel = new JLabel("Choose pressure dependence model");
Pdep.add(modelLabel);
modelLabel.setToolTipText("Default = Off");
Pdep.add(pdepCombo = new JComboBox(pdepOptions));
pdepCombo.setActionCommand("pDep");
// Create the Spectroscopic Data Estimator (SDE) subpanel
JPanel SDE = new JPanel();
SDE.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
// Populate the subpanel
JLabel sdeLabel = new JLabel("Spectroscopic Data Estimator");
SDE.add(sdeLabel);
SDE.add(sdeCombo = new JComboBox(sdeOptions));
sdeCombo.setEnabled(false);
// Create the PDep Kinetics Model (PDKM) subpanel
JPanel PDKM = new JPanel();
PDKM.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
// Populate the subpanel
JLabel pdkmLabel = new JLabel("PDep Kinetics Model");
PDKM.add(pdkmLabel);
PDKM.add(pdkmCombo = new JComboBox(pdkmOptions));
pdkmCombo.setEnabled(false);
pdkmCombo.setActionCommand("pdkm");
JPanel Cheby = new JPanel();
Cheby.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
// Create boxes to store each of the pieces of data
Box boxTP = Box.createVerticalBox();
Box boxMin = Box.createVerticalBox();
Box boxMax = Box.createVerticalBox();
Box boxUnits = Box.createVerticalBox();
Box boxNumGenerate = Box.createVerticalBox();
Box boxNumReport = Box.createVerticalBox();
// Add labels and data fields to boxes
boxTP.add(new JLabel(" "));
boxTP.add(new JLabel("Temperature"));
boxTP.add(new JLabel(" "));
boxTP.add(new JLabel("Pressure"));
boxMin.add(new JLabel("Min. Value"));
boxMin.add(chebyTMin = new JTextField());
boxMin.add(new JLabel(" "));
boxMin.add(chebyPMin = new JTextField());
chebyTMin.setPreferredSize(new Dimension (25,25));
chebyTMin.setHorizontalAlignment(JTextField.CENTER);
chebyTMin.addActionListener(this);
chebyPMin.setPreferredSize(new Dimension (25,25));
chebyPMin.setHorizontalAlignment(JTextField.CENTER);
chebyPMin.addActionListener(this);
boxMax.add(new JLabel("Max. Value"));
boxMax.add(chebyTMax = new JTextField());
boxMax.add(new JLabel(" "));
boxMax.add(chebyPMax = new JTextField());
chebyTMax.setPreferredSize(new Dimension (25,25));
chebyTMax.setHorizontalAlignment(JTextField.CENTER);
chebyTMax.addActionListener(this);
chebyPMax.setPreferredSize(new Dimension (25,25));
chebyPMax.setHorizontalAlignment(JTextField.CENTER);
chebyPMax.addActionListener(this);
boxUnits.add(new JLabel("Units"));
boxUnits.add(chebyTUnits = new JComboBox(tempUnits));
boxUnits.add(new JLabel(" "));
boxUnits.add(chebyPUnits = new JComboBox(pressUnits));
boxNumGenerate.add(new JLabel("# to Generate"));
boxNumGenerate.add(chebyTGen = new JTextField());
boxNumGenerate.add(new JLabel(" "));
boxNumGenerate.add(chebyPGen = new JTextField());
chebyTGen.setPreferredSize(new Dimension (25,25));
chebyTGen.setHorizontalAlignment(JTextField.CENTER);
chebyTGen.addActionListener(this);
chebyPGen.setPreferredSize(new Dimension (25,25));
chebyPGen.setHorizontalAlignment(JTextField.CENTER);
chebyPGen.addActionListener(this);
boxNumReport.add(new JLabel("# to Report"));
boxNumReport.add(chebyTRep = new JTextField());
boxNumReport.add(new JLabel(" "));
boxNumReport.add(chebyPRep = new JTextField());
chebyTRep.setPreferredSize(new Dimension (25,25));
chebyTRep.setHorizontalAlignment(JTextField.CENTER);
chebyTRep.addActionListener(this);
chebyPRep.setPreferredSize(new Dimension (25,25));
chebyPRep.setHorizontalAlignment(JTextField.CENTER);
chebyPRep.addActionListener(this);
// Add the boxes to the "Cheby" subpanel
Cheby.add(boxTP);
Cheby.add(boxMin);
Cheby.add(boxMax);
Cheby.add(boxUnits);
Cheby.add(boxNumGenerate);
Cheby.add(boxNumReport);
Box pDepBox = Box.createVerticalBox();
pDepBox.add(Pdep);
pDepBox.add(SDE);
pDepBox.add(PDKM);
pDepBox.add(Cheby);
totalPDep.add(pDepBox);
JComboBox[] allTab = {pdepCombo, sdeCombo, pdkmCombo, chebyTUnits, chebyPUnits};
initializeJCB(allTab);
JComponent[] pdkmComps = {chebyTMin, chebyTMax, chebyTUnits, chebyTGen, chebyTRep,
chebyPMin, chebyPMax, chebyPUnits, chebyPGen, chebyPRep};
disableComponents(pdkmComps);
Box TabTotal = Box.createVerticalBox();
TabTotal.add(DS);
TabTotal.add(totalPDep);
// Create the dynamicSimulator panel
JPanel dynamicSimulator = new JPanel();
dynamicSimulator.add(TabTotal);
dynamicSimulator.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createTitledBorder(
"Solver Options"), BorderFactory.createEmptyBorder(10,10,10,10)));
// Embed the dynamicSimulator panel in a scroll panel
JScrollPane scrolltab = new JScrollPane(dynamicSimulator);
scrolltab.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
return scrolltab;
}
/* Tab1: Termination Sequence
This tab allows the user to input the terminating sequence of the simulation.
The user must input the followig information:
- The goal of the reaction
* The limiting reactant & its associated conversion
* The time of reaction
- The error tolerance
*/
public JComponent createTabTermination() {
// Create cellrenderers for JComboBox/JTable - CENTER text
ListCellRenderer centerJComboBoxRenderer = new CenterJCBRenderer();
// Create "Goal" panel
JPanel Goal = new JPanel();
Goal.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createTitledBorder("Termination Goal"),
BorderFactory.createEmptyBorder(5,5,5,5)));
// Populate the panel
JLabel controllerLabel = new JLabel("Goal of reaction");
Goal.add(controllerLabel);
Goal.add(controllerCombo = new JComboBox(goalOptions));
controllerCombo.setActionCommand("GoalofReaction");
controllerCombo.addActionListener(this);
controllerCombo.setRenderer(centerJComboBoxRenderer);
// "If Goal = Conversion" subpanel
JPanel Conversion = new JPanel();
Conversion.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createTitledBorder("Conversion"),
BorderFactory.createEmptyBorder(5,5,5,5)));
// Create conversionName subpanel
JPanel conversionName = new JPanel();
JLabel nameCLabel = new JLabel("Species");
conversionName.add(nameCLabel);
conversionName.add(SpeciesConvName = new JComboBox(species_blank));
// Create conversionValue subpanel
JPanel conversionValue = new JPanel();
JLabel convCLabel = new JLabel("Fractional Conversion");
conversionValue.add(convCLabel);
conversionValue.add(conversion = new JTextField());
conversion.setPreferredSize(new Dimension(50,25));
conversion.addActionListener(this);
conversion.setHorizontalAlignment(JTextField.CENTER);
Box convBox = Box.createVerticalBox();
convBox.add(conversionName);
convBox.add(conversionValue);
Conversion.add(convBox);
// "If Goal = ReactionTime" subpanel
JPanel ReactionTime = new JPanel();
ReactionTime.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createTitledBorder("Reaction Time"),
BorderFactory.createEmptyBorder(5,5,5,5)));
// Populate the subpanel
ReactionTime.add(new JLabel("Input reaction time"));
ReactionTime.add(time = new JTextField());
time.setPreferredSize(new Dimension(50,25));
time.setEnabled(false);
time.addActionListener(this);
time.setHorizontalAlignment(JTextField.CENTER);
ReactionTime.add(timeCombo = new JComboBox(timeUnits));
timeCombo.setEnabled(false);
timeCombo.addActionListener(this);
timeCombo.setRenderer(centerJComboBoxRenderer);
timeCombo.setSelectedIndex(1);
// Error tolerance subpanel
JPanel eTolPanel = new JPanel();
eTolPanel.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createTitledBorder("Error tolerance"),
BorderFactory.createEmptyBorder(5,5,5,5)));
// Populate subpanel
JLabel eToleranceLabel = new JLabel("Select error tolerance");
eToleranceLabel.setToolTipText("Suggested value = 0.1");
eTolPanel.add(eToleranceLabel);
eTolPanel.add(eTolerance = new JTextField());
eTolerance.setPreferredSize(new Dimension(100,25));
eTolerance.addActionListener(this);
eTolerance.setHorizontalAlignment(JTextField.CENTER);
eTolerance.setText("0.1");
// Create boxes to store subpanels
Box term = Box.createVerticalBox();
Box goalTypes = Box.createHorizontalBox();
goalTypes.add(Conversion);
goalTypes.add(ReactionTime);
term.add(Goal);
term.add(goalTypes);
term.add(eTolPanel);
JPanel terminationPanel = new JPanel();
terminationPanel.add(term);
terminationPanel.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createTitledBorder("Finish Controller"),
BorderFactory.createEmptyBorder(5,5,5,5)));
JScrollPane scrolltab = new JScrollPane(terminationPanel);
scrolltab.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
return scrolltab;
}
/* Tab3: Error Analysis
This tab allows the user to choose whether error bars & sensitivity coefficients (and for which
speices) are available in the output .txt files
The user must input the following information:
- Whether to display error bars
- Whether to display sensitivity coefficients
* Which species to analyze
*/
public JComponent createTabSensitivity() {
// Create cellrenderers for JComboBox/JTable - CENTER text
ListCellRenderer centerJComboBoxRenderer = new CenterJCBRenderer();
TableCellRenderer centerRenderer = new CenterTRenderer();
// Create errorbars (EB) subpanel
JPanel EB = new JPanel();
EB.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createTitledBorder("Error Bars"),
BorderFactory.createEmptyBorder(10,10,10,10)));
// Populate the subpanel
EB.add(new JLabel("Display error bars"));
EB.add(eBarsCombo = new JComboBox(yesnoOptions));
eBarsCombo.addActionListener(this);
eBarsCombo.setRenderer(centerJComboBoxRenderer);
eBarsCombo.setSelectedIndex(0);
eBarsCombo.setEnabled(false);
// Create Sensitivity Coefficients (SC) panel
JPanel SC = new JPanel();
SC.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createTitledBorder("Sensitivity Coefficients"),
BorderFactory.createEmptyBorder(10,10,10,10)));
// Create SC on/off subpanel
JPanel scOnOff = new JPanel();
scOnOff.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
scOnOff.add(new JLabel("Display sensitivity coefficients"));
scOnOff.add(sensCoeffCombo = new JComboBox(yesnoOptions));
sensCoeffCombo.setSelectedIndex(0);
sensCoeffCombo.setActionCommand("scOnOff");
sensCoeffCombo.addActionListener(this);
sensCoeffCombo.setRenderer(centerJComboBoxRenderer);
sensCoeffCombo.setEnabled(false);
// Create SC list subpanel
JPanel scList = new JPanel();
scList.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
scList.add(new JLabel("Species Name"));
scList.add(scName = new JTextField());
scName.setEnabled(false);
scName.setHorizontalAlignment(JTextField.CENTER);
scName.setPreferredSize(new Dimension(60,25));
// Create sensitivity table, tablemodel, scroll panel
tableSens = new JTable(tmodelSens = new MyTableModelSensitivity());
tableSens.setPreferredScrollableViewportSize(new Dimension(30,50));
tableSens.getColumnModel().getColumn(0).setPreferredWidth(30);
tableSens.setEnabled(false);
JScrollPane scrollSens = new JScrollPane(tableSens);
scrollSens.setBorder(BorderFactory.createLoweredBevelBorder());
// * Set the alignment for all cells in the table to CENTER
for (int i=0; i<tableSens.getColumnCount(); i++) {
TableColumn column = tableSens.getColumnModel().getColumn(i);
column.setCellRenderer(centerRenderer);
}
// Create boxes to display panels
Box sens1 = Box.createHorizontalBox();
Box sens2 = Box.createHorizontalBox();
// Fill boxes
sens1.add(AddSens = new JButton("Add"));
sens1.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
AddButtonListener addListenerSens = new AddButtonListener();
AddSens.addActionListener(addListenerSens);
AddSens.setActionCommand("AddSens");
AddSens.setToolTipText("Press to submit molecule");
AddSens.setEnabled(false);
sens2.add(DeleteSens = new JButton("Remove"));
DeleteButtonListener deleteListenerSens = new DeleteButtonListener();
DeleteSens.addActionListener(deleteListenerSens);
DeleteSens.setActionCommand("DeleteSens");
DeleteSens.setToolTipText("Press to delete molecule");
DeleteSens.setEnabled(false);
JPanel scButtons = new JPanel();
scButtons.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
scButtons.add(sens1);
scButtons.add(sens2);
Box scBox = Box.createVerticalBox();
scBox.add(scOnOff);
scBox.add(scList);
scBox.add(scButtons);
scBox.add(scrollSens);
SC.add(scBox);
// Total tab
Box Tab3Total = Box.createVerticalBox();
Tab3Total.add(EB);
Tab3Total.add(SC);
JPanel SA = new JPanel();
SA.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createTitledBorder("Sensitivity Analysis"),
BorderFactory.createEmptyBorder(5,5,5,5)));
SA.add(Tab3Total);
JScrollPane scrolltab3 = new JScrollPane(SA);
scrolltab3.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
return scrolltab3;
}
class DeleteButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
if ("DeletePRL".equals(e.getActionCommand())) {
int highlightRow = tablePRL.getSelectedRow();
if (highlightRow == -1) {
System.out.println("Please select a row to delete");
} else
tmodelPRL.deleteRow(highlightRow);
} else if ("DeleteInput".equals(e.getActionCommand())) {
int highlightRow = tableInput.getSelectedRow();
if (highlightRow == -1) {
System.out.println("Please select a row to delete");
} else {
tmodelInput.deleteRow(highlightRow);
limitingReactant();
}
} else if ("DeleteSens".equals(e.getActionCommand())) {
int highlightRow = tableSens.getSelectedRow();
if (highlightRow == -1) {
System.out.println("Please select a row to delete");
} else
tmodelSens.deleteRow(highlightRow);
} else if ("DeletePTL".equals(e.getActionCommand())) {
int highlightRow = tablePTL.getSelectedRow();
if (highlightRow == -1) {
System.out.println("Please select a row to delete");
} else
tmodelPTL.deleteRow(highlightRow);
}
else if ("DeleteSM".equals(e.getActionCommand())) {
int highlightRow = tableSM.getSelectedRow();
if (highlightRow == -1) {
System.out.println("Please select a row to delete");
} else
tmodelSM.deleteRow(highlightRow);
}
}
}
class AddButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
// IF the user adds a primary reaction library ...
if ("AddPRL".equals(e.getActionCommand())) {
// Extract the information
int prlInput0 = tmodelPRL.nextEmptyRow+1;
String prlInput1 = prlLibName.getText();
String prlInput2 = prlPath.getText();
// Check that all information is present
if (prlInput1.equals("") || prlInput2.equals("")) {
System.out.println("Please input the Name and Location of a Primary Reaction Library");
} else {
PRLVector prlEntry = new PRLVector(prlInput0, prlInput1, prlInput2);
tmodelPRL.updatePRL(prlEntry);
prlLibName.setText("");
prlPath.setText("");
}
} else if ("AddPTL".equals(e.getActionCommand())) {
// Extract the information
int ptlInput0 = tmodelPTL.nextEmptyRow+1;
String ptlInput1 = ptlLibName.getText();
String ptlInput2 = ptlPath.getText();
// Check that all information is present
if (ptlInput1.equals("") || ptlInput2.equals("")) {
System.out.println("Please input the Name and Location of a Primary Thermo Library");
} else {
PRLVector ptlEntry = new PRLVector(ptlInput0, ptlInput1, ptlInput2);
tmodelPTL.updatePRL(ptlEntry);
ptlLibName.setText("");
ptlPath.setText("");
}
} else if ("AddSM".equals(e.getActionCommand())) {
// Extract the information
int smInput0 = tmodelSM.nextEmptyRow+1;
String smInput1 = smLibName.getText();
String smInput2 = smPath.getText();
// Check that all information is present
if (smInput1.equals("") || smInput2.equals("")) {
System.out.println("Please input the Name and Location of a Seed Mechanism");
} else {
PRLVector smEntry = new PRLVector(smInput0, smInput1, smInput2);
tmodelSM.updatePRL(smEntry);
smLibName.setText("");
smPath.setText("");
}
// ELSE IF the user adds a species ...
} else if ("AddInput".equals(e.getActionCommand())) {
// Extract the information
int icInput0 = tmodelInput.nextEmptyRow+1;
String icInput1 = NameInput.getText();
boolean renameName = false;
try {
int doesNameBeginWithNumber = Integer.parseInt(icInput1.substring(0,1));
renameName = true;
} catch (NumberFormatException e1) {
// We're good
}
String icInput2 = ConcInput.getText();
String icInput3 = (String)UnitsInput.getSelectedItem();
String icInput4 = (String)ReactiveInput.getSelectedItem();
String icInput5 = "";
// Ask user for adjacency list if species is marked "Reactive"
if (!icInput4.equals("Inert")) {
if (!speciesAdjList.getText().equals("")) {
icInput5 = speciesAdjList.getText();
} else if (!InChIInput.getText().equals("")) {
String inchi = InChIInput.getText();
icInput5 = Species.inchi2AdjList(inchi);
} else {
File molFile = null;
molFile = askUserForInput("Select corresponding .mol file", false, null);
if (molFile != null) icInput5 = Species.mol2AdjList(molFile.getAbsolutePath(), molFile.getAbsolutePath());
}
} else {
String[] inerts = {"N2", "Ar", "Ne", "He"};
boolean correctInertFormat = false;
for (int i=0; i<inerts.length; i++) {
if (icInput1.equals(inerts[i])) correctInertFormat = true;
}
if (!correctInertFormat) {
System.out.println("ERROR: Adding Inert Gas species to model - RMG recognizes the following species as Inert Gas (case sensitive): N2, Ar, Ne, He");
return;
}
}
// If a species is marked "Reactive-User", ask user for location of IncludeSpecies.txt file
if (icInput4.equals("Reactive-User")) {
// If the path is not known
if (isPath.getText().equals("")) {
File isFile = null;
isFile = askUserForInput("Select IncludeSpecies.txt file", false, null);
if (isFile != null) {
isPath.setText(isFile.getPath());
isPath.setEnabled(true);
}
}
}
// Check that all information is present
if (icInput1.equals("") || icInput2.equals("") || (icInput5.equals("") & !icInput4.equals("Inert"))) {
System.out.println("Please input the molecule's Name, Concentration, and Adjacency List");
} else if (renameName) {
System.out.println("\nA species name should not begin with a number." +
" Please rename species: " + icInput1 + "\n");
}
else {
ICVector icEntry = new ICVector(icInput0, icInput1, icInput2, icInput3, icInput4, icInput5);
tmodelInput.updateIC(icEntry);
NameInput.setText("");
InChIInput.setText("");
ConcInput.setText("");
UnitsInput.setSelectedIndex(0);
ReactiveInput.setSelectedIndex(0);
speciesAdjList.setText("");
if (!icInput4.equals("Inert")) limitingReactant();
}
// ELSE IF the user adds a species to sensitivity analysis
} else if ("AddSens".equals(e.getActionCommand())) {
// Extract the information
int sensInput0 = tmodelSens.nextEmptyRow+1;
String sensInput1 = scName.getText();
// Check if all information is present
if (sensInput1.equals("")) {
System.out.println("Please input the name of a Molecule");
} else {
SensVector sensEntry = new SensVector(sensInput0, sensInput1);
tmodelSens.updateSens(sensEntry);
scName.setText("");
}
}
}
}
class ChangeButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
// IF the user selects to switch the IncludeSpecies.txt path
if ("isPath".equals(e.getActionCommand())) {
File path = null;
path = askUserForInput("Select IncludeSpecies.txt file", false, null);
if (path != null) isPath.setText(path.getPath());
// ELSE IF user selects to switch the database path
} else if ("databasePath".equals(e.getActionCommand())) {
File path = null;
String workingDirectory = System.getProperty("RMG.workingDirectory");
path = askUserForInput("Select database folder", true, workingDirectory + "/databases");
if (path != null) databasePath.setText(path.getPath());
// If user selects to switch Primary Thermo Library path
} else if ("ptlPath".equals(e.getActionCommand())) {
File path = null;
path = askUserForInput("Select PrimaryThermoLibrary folder", true, databasePath.getText()+"/thermo");
if (path != null) ptlPath.setText(path.getPath());
// If user selects to switch Primary Reaction Library path
} else if ("prlPath".equals(e.getActionCommand())) {
File path = null;
path = askUserForInput("Select PrimaryReactionLibrary folder", true, databasePath.getText()+"/primaryReactionLibrary");
if (path != null) prlPath.setText(path.getPath());
} else if ("smPath".equals(e.getActionCommand())) {
File path = null;
path = askUserForInput("Select SeedMechanism folder", true, databasePath.getText()+"/SeedMechanisms");
if (path != null) smPath.setText(path.getPath());
}
}
}
public File askUserForInput (String popupwindowTitle, boolean folder, String additionalPath) {
String workingDirectory = System.getProperty("RMG.workingDirectory");
String completePath ="";
if (additionalPath != null)
completePath = additionalPath;
else
completePath = workingDirectory;
JFileChooser chooser = new JFileChooser(completePath);
chooser.setApproveButtonText("Select");
chooser.setDialogTitle(popupwindowTitle);
chooser.rescanCurrentDirectory();
if (folder) chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
int result = chooser.showDialog(GUI.this, null);
File file = null;
if (result == chooser.APPROVE_OPTION) {
file = chooser.getSelectedFile();
} else {
chooser.cancelSelection();
}
return file;
}
/*
* This function updates the Limiting Reactant combobox on the Termination
* tab of the GUI - for a termination criteria of expected conversion, only
* an input to the simulation is acceptable
*/
public void limitingReactant() {
int permanentNumber = SpeciesConvName.getItemCount();
for (int i=1; i<permanentNumber; i++) {
SpeciesConvName.removeItemAt(1);
}
int nonInertCount = 0;
for (int j=0; j<tmodelInput.nextEmptyRow; j++) {
if (!tmodelInput.getValueAt(j,3).equals("Inert")) {
++nonInertCount;
SpeciesConvName.insertItemAt(tmodelInput.getValueAt(j,0),nonInertCount);
}
}
}
public void createConditionFile(boolean saveAndRun) {
// Let's create the condition.txt file!
String conditionFile = "";
String[] tempString;
// Add user supplied comments
conditionFile += "// User supplied comments:\r";
if (headerComments.getText().equals("")) System.out.println("Warning: Writing condition.txt file: No comments being read in.");
String[] header4Condition = headerComments.getText().split("[\n]");
for (int i=0; i<header4Condition.length; i++) {
conditionFile += "// " + header4Condition[i] + "\r";
}
// Add date and time to the file
String DATE_FORMAT_NOW = "yyyy-MM-dd HH:mm:ss";
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);
Calendar cal = Calendar.getInstance();
conditionFile += "//\r// File created at: " + sdf.format(cal.getTime()) + "\r\r";
// String storing the folder of the Main Database (w.r.t. $RMG/databases)
String stringMainDatabase = "";
// Add the name of the database and primary thermo library
if (databasePath.getText().equals("")) {
System.out.println("ERROR: Writing condition.txt file: Could not read Main Database (Thermochemical Libraries tab)");
return;
}
else {
tempString = databasePath.getText().split("[\\\\,/]");
stringMainDatabase = tempString[tempString.length-1];
conditionFile += "Database: " + stringMainDatabase + "\r\r";
}
// Add the name(s)/location(s) of the primary thermo library
String rmgEnvVar = System.getProperty("RMG.workingDirectory");
String ptlReferenceDirectory = rmgEnvVar + "/databases/" + stringMainDatabase + "/thermo/";
conditionFile += "PrimaryThermoLibrary:\r";
if (tablePTL.getRowCount()==0) {
System.out.println("Warning: Writing condition.txt file: Could not read Primary Thermo Library (Thermochemical Libraries tab)");
} else {
for (int k=0; k<tablePTL.getRowCount(); k++) {
conditionFile += "Name: " + tablePTL.getValueAt(k,0) + "\r" + "Location: ";
String ptlDir = (String)tablePTL.getValueAt(k,1);
if (ptlDir.startsWith(rmgEnvVar)) {
int startIndex = ptlReferenceDirectory.length();
conditionFile += ptlDir.substring(startIndex) + "\r";
} else {
conditionFile += ptlDir + "\r";
}
}
}
conditionFile += "END\r\r";
// Add the temperature model, list of temperatures, and units
conditionFile += "TemperatureModel: " + tempModelCombo.getSelectedItem() +
" (" + tempConstantUnit.getSelectedItem() + ")";
if (tempConstant.getText().equals("")) {
System.out.println("ERROR: Writing condition.txt file: Could not read list of temperatures (Initial Conditions tab)");
return;
}
else {
String[] tempLines = tempConstant.getText().split("[\n]");
StringTokenizer st = null;
for (int i=0; i<tempLines.length; i++) {
st = new StringTokenizer(tempLines[i]);
while (st.hasMoreTokens()) {
String line = st.nextToken();
if (line.endsWith(",")) line = line.substring(0,line.length()-1);
conditionFile += " " + line;
}
}
}
conditionFile += "\r";
// Add the pressure model, list of pressures, and units
conditionFile += "PressureModel: " + pressModelCombo.getSelectedItem() +
" (" + pressConstantUnit.getSelectedItem() + ")";
if (pressConstant.getText().equals("")) {
System.out.println("ERROR: Writing condition.txt file: Could not read list of pressures (Initial Conditions tab)");
return;
}
else {
String[] pressLines = pressConstant.getText().split("[\n]");
StringTokenizer st = null;
for (int i=0; i<pressLines.length; i++) {
st = new StringTokenizer(pressLines[i]);
while (st.hasMoreTokens()) {
String line = st.nextToken();
if (line.endsWith(",")) line = line.substring(0,line.length()-1);
conditionFile += " " + line;
}
}
}
conditionFile += "\r\r";
// Add the equation of state (if equal to liquid)
if (eosCombo.getSelectedItem().equals("Liquid")) {
conditionFile += "EquationOfState: Liquid\r";
}
// Add the user-specified maximum number of carbons, oxygens, and radicals / species
if (!maxCarbonNum.getText().equals(""))
conditionFile += "MaxCarbonNumberPerSpecies: " + maxCarbonNum.getText() + "\r";
if (!maxOxygenNum.getText().equals(""))
conditionFile += "MaxOxygenNumberPerSpecies: " + maxOxygenNum.getText() + "\r";
if (!maxRadicalNum.getText().equals(""))
conditionFile += "MaxRadicalNumberPerSpecies: " + maxRadicalNum.getText() + "\r";
// Add whether to generate InChIs or not
if (inchiCombo.getSelectedItem().equals("Yes"))
conditionFile += "InChIGeneration: on\r";
// Add whether to turn solvation on or not
// Add whether to run on-the-fly quantum jobs or not
// Determine if each species is reactive, unreactive, or inert
int nonInertCount = 0;
boolean unreactiveStatus = false;
String reactiveSpecies = "";
String inertSpecies = "";
if (tableInput.getRowCount()==0) {
System.out.println("ERROR: Writing condition.txt file: Could not read table of reactants (Initial Conditions tab)");
return;
}
else {
for (int i=0; i<tableInput.getRowCount(); i++) {
if (tableInput.getValueAt(i,3).equals("Inert")) {
inertSpecies += tableInput.getValueAt(i,0) + " " +
tableInput.getValueAt(i,1) + " (" +
tableInput.getValueAt(i,2) + ")\r";
} else if (tableInput.getValueAt(i,3).equals("Reactive-RMG")) {
++nonInertCount;
reactiveSpecies += "(" + nonInertCount + ") " +
tableInput.getValueAt(i,0) + " " +
tableInput.getValueAt(i,1) + " (" +
tableInput.getValueAt(i,2) + ")\r" +
tableInput.getValueAt(i,4) + "\r\r";
} else if (tableInput.getValueAt(i,3).equals("Reactive-User")) {
unreactiveStatus = true;
++nonInertCount;
reactiveSpecies += "(" + nonInertCount + ") " +
tableInput.getValueAt(i,0) + " " +
tableInput.getValueAt(i,1) + " (" +
tableInput.getValueAt(i,2) + ") unreactive\r" +
tableInput.getValueAt(i,4) + "\r\r";
}
}
// Add the non-inert gas species
conditionFile += "\rInitialStatus:\r\r" + reactiveSpecies + "END\r\r";
// Add the inert gas species
conditionFile += "InertGas:\r" + inertSpecies + "END\r\r";
}
// Add the spectroscopic data estimator
conditionFile += "SpectroscopicDataEstimator: ";
if (sdeCombo.getSelectedItem().equals("Frequency Groups")) {
conditionFile += "FrequencyGroups\r";
// } else if (sdeCombo.getSelectedItem().equals("Three Frequency Model")) {
// conditionFile += "ThreeFrequencyModel\r";
} else if (sdeCombo.getSelectedItem().equals("off")) {
conditionFile += "off\r";
}
// Add the pressure dependence model
conditionFile += "PressureDependence: ";
if (pdepCombo.getSelectedItem().equals("Modified Strong Collision")) {
conditionFile += "modifiedstrongcollision\r";
} else if (pdepCombo.getSelectedItem().equals("Reservoir State")) {
conditionFile += "reservoirstate\r";
} else if (pdepCombo.getSelectedItem().equals("off")) {
conditionFile += "off\r";
}
// Add the pdep kinetics model
if (!pdepCombo.getSelectedItem().equals("off")) {
conditionFile += "PDepKineticsModel: ";
if (pdkmCombo.getSelectedItem().equals("CHEB")) {
conditionFile += "Chebyshev\r";
if (!chebyTMin.getText().equals("")) {
if (chebyTMax.getText().equals("") || chebyTGen.getText().equals("") ||
chebyTRep.getText().equals("") || chebyPMin.getText().equals("") ||
chebyPMax.getText().equals("") || chebyPGen.getText().equals("") ||
chebyPRep.getText().equals(""))
System.out.println("ERROR: Writing condition.txt file: All Chebyshev entries must be filled in (Dynamic Simulator tab)");
conditionFile += "TRange: (" + chebyTUnits.getSelectedItem() +
") " + chebyTMin.getText() + " " + chebyTMax.getText() + " " +
chebyTGen.getText() + " " + chebyTRep.getText() + "\r";
conditionFile += "PRange: (" + chebyPUnits.getSelectedItem() +
") " + chebyPMin.getText() + " " + chebyPMax.getText() + " " +
chebyPGen.getText() + " " + chebyPRep.getText() + "\r";
}
} else if (pdkmCombo.getSelectedItem().equals("PLOG"))
conditionFile += "PDepArrhenius\r";
else if (pdkmCombo.getSelectedItem().equals("Rate"))
conditionFile += "Rate\r";
}
conditionFile += "\r";
// Add the path of the IncludeSpecies.txt file (if present)
if (unreactiveStatus) {
conditionFile += "IncludeSpecies: ";
if (isPath.getText().equals("")) {
System.out.println("ERROR: Writing condition.txt file: Could not read location of IncludeSpecies.txt (Initial Conditions tab)");
return;
}
else {
if (isPath.getText().startsWith(rmgEnvVar)) {
int startIndex = rmgEnvVar.length()+1;
conditionFile += isPath.getText().substring(startIndex) + "\r\r";
} else {
conditionFile += isPath.getText() + "\r\r";
}
}
}
// Add the finish controller
conditionFile += "FinishController:\r" + "(1) Goal ";
// If goal is conversion
boolean conversionGoal = true;
if (controllerCombo.getSelectedItem().equals("Conversion")) {
if (SpeciesConvName.getSelectedItem().equals(" ") || conversion.getText().equals("")) {
System.out.println("ERROR: Writing condition.txt file: Could not read limiting reactant and/or fractional conversion (Termination tab)");
return;
}
else {
conditionFile += controllerCombo.getSelectedItem() + " " +
SpeciesConvName.getSelectedItem() + " " + conversion.getText() + "\r";
}
} else if (controllerCombo.getSelectedItem().equals("ReactionTime")) {
if (time.getText().equals("")) {
System.out.println("ERROR: Writing condition.txt file: Could not read time of reaction (Termination tab)");
return;
}
else {
conversionGoal = false;
conditionFile += controllerCombo.getSelectedItem() + " " +
time.getText() + " (" + timeCombo.getSelectedItem() + ")\r";
}
}
if (eTolerance.getText().equals("")) {
System.out.println("ERROR: Writing condition.txt file: Could not read model's error tolerance (Termination tab)");
return;
} else {
conditionFile += "(2) Error Tolerance: " + eTolerance.getText() + "\r\r";
}
// Add the dynamic simulator
conditionFile += "DynamicSimulator: " + simulatorCombo.getSelectedItem() + "\r";
if (conversionGoal) {
conditionFile += "Conversions:";
if (multiConv.getText().equals("")) {
System.out.println("ERROR: Writing condition.txt file: Could not read list of intermediate conversions (Dynamic Simulator tab)");
return;
}
else {
String[] convLines = multiConv.getText().split("[\n]");
for (int i=0; i<convLines.length; i++) {
StringTokenizer st = null;
st = new StringTokenizer(convLines[i]);
while (st.hasMoreTokens()) {
String line = st.nextToken();
if (line.endsWith(",")) line = line.substring(0,line.length()-1);
conditionFile += " " + line;
}
}
}
} else {
conditionFile += "TimeStep:";
if (multiTS.getText().equals("")) {
System.out.println("ERROR: Writing condition.txt file: Could not read list of intermediate time steps (Dynamic Simulator tab)");
return;
}
else {
String[] tsLines = multiTS.getText().split("[\n]");
for (int i=0; i<tsLines.length; i++) {
StringTokenizer st = null;
st = new StringTokenizer(tsLines[i]);
while (st.hasMoreTokens()) {
String line = st.nextToken();
if (line.endsWith(",")) line = line.substring(0,line.length()-1);
conditionFile += " " + line;
}
}
}
}
if (aTolerance.getText().equals("") || rTolerance.getText().equals("")) {
System.out.println("ERROR: Writing condition.txt file: Could not read absolute and/or relative tolerance (Dynamic Simulator tab)");
return;
}
else {
conditionFile += "\rAtol: " + aTolerance.getText() + "\r" + "Rtol: " + rTolerance.getText() + "\r\r";
}
// Add error bars & sensitivity analysis information (if DASPK is selected)
if (simulatorCombo.getSelectedItem().equals("DASPK")) {
conditionFile += "Error bars: ";
if (eBarsCombo.getSelectedItem().equals("Yes")) {
conditionFile += "on\r";
} else if (eBarsCombo.getSelectedItem().equals("No")) {
conditionFile += "off\r";
}
conditionFile += "Display sensitivity coefficients: ";
if (sensCoeffCombo.getSelectedItem().equals("Yes")) {
conditionFile += "on\rDisplay sensitivity information for:\r";
if (tableSens.getRowCount()==0) {
System.out.println("ERROR: Writing condition.txt file: Could not read table of species for which to perform sensitivity analysis (Sensitivity Analysis tab)");
return;
}
for (int j=0; j<tableSens.getRowCount(); j++) {
conditionFile += tableSens.getValueAt(j,0) + "\r";
}
conditionFile += "END\r\r";
} else if (sensCoeffCombo.getSelectedItem().equals("No")) {
conditionFile += "off\r";
}
}
// Add the name(s)/location(s) of the primary reaction library
String prlReferenceDirectory = rmgEnvVar + "/databases/";
conditionFile += "PrimaryReactionLibrary:\r";
if (tablePRL.getRowCount()==0) {
System.out.println("Warning: Writing condition.txt file: Could not read Primary Reaction Library (Thermochemical Libraries tab)");
} else {
for (int k=0; k<tablePRL.getRowCount(); k++) {
conditionFile += "Name: " + tablePRL.getValueAt(k,0) + "\r" + "Location: ";
String prlDir = (String)tablePRL.getValueAt(k,1);
if (prlDir.startsWith(rmgEnvVar)) {
int startIndex = prlReferenceDirectory.length();
conditionFile += prlDir.substring(startIndex) + "\r";
} else {
conditionFile += prlDir + "\r";
}
}
}
conditionFile += "END\r\r";
// Add the name(s)/location(s) of the primary reaction library
conditionFile += "SeedMechanism:\r";
if (tableSM.getRowCount()==0) {
System.out.println("Warning: Writing condition.txt file: Could not read Seed Mechanism (Thermochemical Libraries tab)");
} else {
for (int k=0; k<tableSM.getRowCount(); k++) {
conditionFile += "Name: " + tableSM.getValueAt(k,0) + "\r" + "Location: ";
String smDir = (String)tableSM.getValueAt(k,1);
if (smDir.startsWith(rmgEnvVar)) {
int startIndex = prlReferenceDirectory.length();
conditionFile += smDir.substring(startIndex) + "\r";
} else {
conditionFile += smDir + "\r";
}
}
}
conditionFile += "END\r\r";
// Add the Chemkin chem.inp file options
conditionFile += "ChemkinUnits:\r";
if (chemkinVerbosity.getSelectedItem().equals("Yes"))
conditionFile += "Verbose: on\r";
conditionFile += "A: " + chemkinAUnits.getSelectedItem() + "\r";
conditionFile += "Ea: " + chemkinEaUnits.getSelectedItem() + "\r";
File conditionPath = null;
FileWriter fw = null;
// Write the conditionFile string to user-specified file
try {
conditionPath = askUserForInput("Save file", false, null);
if (conditionPath != null) {
fw = new FileWriter(conditionPath);
fw.write(conditionFile);
fw.close();
}
} catch (IOException e) {
String err = "Error writing condition file: ";
err += e.toString();
System.out.println(err);
}
// Run RMG if "Save and Run" selected
if (saveAndRun && conditionPath != null) {
runConditionFile(conditionPath.getAbsolutePath());
}
}
public void openConditionFile(File filePath) {
int numSpecies = 0;
tmodelPTL.clear();
tmodelPRL.clear();
tmodelSM.clear();
tmodelInput.clear();
tmodelSens.clear();
System.out.println("GUI cannot read in file's header (comments)");
// Read in the .txt file
FileReader in = null;
try {
in = new FileReader(filePath);
} catch (FileNotFoundException e) {
String err = "Error reading file: ";
err += e.toString();
System.out.println(err);
}
BufferedReader reader = new BufferedReader(in);
String line = ChemParser.readMeaningfulLine(reader);
read: while (line != null) {
// Populate the GUI with as much information as possible
StringTokenizer st = null;
String tempString = "";
String[] tempStringVector = null;
if (line.startsWith("Database")) {
// Path of Database
st = new StringTokenizer(line);
tempString = st.nextToken(); // Skip over "Database:"
databasePath.setText(st.nextToken());
}
else if (line.startsWith("PrimaryThermoLibrary")) {
// Name(s)/Path(s) of PrimaryThermoLibrary
line = ChemParser.readMeaningfulLine(reader);
int ptlCounter = 0;
while (!line.equals("END")) {
++ptlCounter;
tempStringVector = line.split("Name: ");
String name = tempStringVector[tempStringVector.length-1].trim();
line = ChemParser.readMeaningfulLine(reader);
tempStringVector = line.split("Location: ");
String path = tempStringVector[tempStringVector.length-1].trim();
PRLVector ptlEntry = new PRLVector(ptlCounter-1,name,path);
tmodelPTL.updatePRL(ptlEntry);
line = ChemParser.readMeaningfulLine(reader);
}
}
else if (line.startsWith("TemperatureModel")) {
// Temperature model
st = new StringTokenizer(line);
tempString = st.nextToken(); // Skip over "TemperatureModel:"
String modelTemp = st.nextToken();
if (!modelTemp.equals("Constant")) {
System.out.println("ERROR: Reading in condition.txt file - Invalid TemperatureModel. RMG recognizes 'Constant' TemperatureModel, but not " + modelTemp + ". GUI does not contain all information present in condition.txt file.");
}
tempModelCombo.setSelectedItem(modelTemp);
String unitTemp = st.nextToken().substring(1,2);
if (unitTemp.equals("K") || unitTemp.equals("F") || unitTemp.equals("C")) {
tempConstantUnit.setSelectedItem(unitTemp);
}
else {
System.out.println("ERROR: Reading in condition.txt file - Invalid temperature unit. RMG recognizes temperature units of 'K', 'C', or 'F', but not " + unitTemp + ". GUI does not contain all information present in condition.txt file.");
}
String temps = st.nextToken();
while (st.hasMoreTokens()) {
temps += " " + st.nextToken();
}
tempConstant.setText(temps);
}
else if (line.startsWith("PressureModel")) {
// Pressure model
st = new StringTokenizer(line);
tempString = st.nextToken(); // Skip over "PressureModel:"
String modelPress = st.nextToken();
if (!modelPress.equals("Constant")) {
System.out.println("ERROR: Reading in condition.txt file - Invalid PressureModel. RMG recognizes 'Constant' PressureModel, but not " + modelPress + ". GUI does not contain all information present in condition.txt file.");
}
else {
pressModelCombo.setSelectedItem(modelPress);
}
String temp = st.nextToken();
String unitPress = temp.substring(1,temp.length()-1);
if (unitPress.equals("atm") || unitPress.equals("Pa") || unitPress.equals("bar") || unitPress.equals("torr")) {
pressConstantUnit.setSelectedItem(unitPress);
}
else {
System.out.println("ERROR: Reading in condition.txt file - Invalid pressure unit. RMG recognizes pressure units of 'atm', 'Pa', 'bar' or 'torr', but not " + unitPress + ". GUI does not contain all information present in condition.txt file.");
}
String presses = st.nextToken();
while (st.hasMoreTokens()) {
presses += " " + st.nextToken();
}
pressConstant.setText(presses);
}
// GUI only recognized Ideal Gas EOS (30Jul2009)
// else if (line.startsWith("EquationOfState")) {
// // Equation of state (if present)
// st = new StringTokenizer(line);
// tempString = st.nextToken(); // Skip over "EquationOfState"
// tempString = st.nextToken();
// if (tempString.equals("Liquid")) {
// eosCombo.setSelectedItem(tempString);
// } else {
// System.out.println("ERROR: Reading in condition.txt file - Invalid equation of state. RMG recognizes 'Liquid', but not " + tempString + ". GUI does not contain all information present in condition.txt file.");
// }
// }
else if (line.startsWith("MaxCarbonNumber")) {
st = new StringTokenizer(line);
tempString = st.nextToken(); // Skip over "MaxCarbonNumberPerSpecies"\
maxCarbonNum.setText(st.nextToken());
}
else if (line.startsWith("MaxOxygenNumber")) {
st = new StringTokenizer(line);
tempString = st.nextToken(); // Skip over "MaxOxygenNumberPerSpecies"\
maxOxygenNum.setText(st.nextToken());
}
else if (line.startsWith("MaxRadicalNumber")) {
st = new StringTokenizer(line);
tempString = st.nextToken(); // Skip over "MaxRadicalNumberPerSpecies"\
maxRadicalNum.setText(st.nextToken());
}
else if (line.startsWith("InChIGeneration")) {
// InChI generation
st = new StringTokenizer(line);
tempString = st.nextToken(); // Skip over "InChIGeneration:"
String inchi = st.nextToken();
if (inchi.toLowerCase().equals("on")) {
inchiCombo.setSelectedItem("Yes");
} else if (inchi.toLowerCase().equals("off")) {
inchiCombo.setSelectedItem("No");
} else {
System.out.println("ERROR: Reading in condition.txt file - Invalid argument for InChIGeneration. RMG recognizes an argument of 'On' or 'Off', but not " + inchi + ". GUI does not contain all information present in condition.txt file.");
}
}
// GUI does not handle Solvation (30Jul2009)
// else if (line.startsWith("Solvation")) {
// // Solvation
// st = new StringTokenizer(line);
// tempString = st.nextToken(); // Skip over "Solvation:"
// String solvation = st.nextToken();
// if (solvation.toLowerCase().equals("on")) {
// solvationCombo.setSelectedItem("Yes");
// } else if (solvation.toLowerCase().equals("off")) {
// solvationCombo.setSelectedItem("No");
// } else {
// System.out.println("ERROR: Reading in condition.txt file - Invalid argument for Solvation. RMG recognizes an argument of 'On' or 'Off', but not " + solvation + ". GUI does not contain all information present in condition.txt file.");
// }
// }
else if (line.startsWith("InitialStatus")) {
String adjList = "";
String name = "";
String conc = "";
String unit = "";
String reactivity = "";
line = ChemParser.readMeaningfulLine(reader);
while (!line.startsWith("END")) {
if (line.startsWith("(")) {
++numSpecies;
st = new StringTokenizer(line);
tempString = st.nextToken(); // Skip over (#)
name = st.nextToken();
conc = st.nextToken();
unit = st.nextToken();
- reactivity = "Reactive";
+ reactivity = "Reactive-RMG";
if (st.hasMoreTokens()) {
- reactivity = "Unreactive";
+ reactivity = "Reactive-User";
}
} else {
adjList += line + "\r";
}
line = ChemParser.readMeaningfulLine(reader);
if (line.startsWith("(") || line.startsWith("END")) {
ICVector icEntry = new ICVector(numSpecies-1,name,conc,unit.substring(1,unit.length()-1),reactivity,adjList);
tmodelInput.updateIC(icEntry);
adjList = "";
}
}
limitingReactant();
}
else if (line.startsWith("InertGas")) {
// Inert gases
String name = "";
String conc = "";
String unit = "";
String reactivity = "";
String adjList = "";
line = ChemParser.readMeaningfulLine(reader);
while (!line.startsWith("END")) {
++numSpecies;
st = new StringTokenizer(line);
name = st.nextToken();
conc = st.nextToken();
unit = st.nextToken();
reactivity = "Inert";
if (name.equals("Ar") || name.equals("Ne") || name.equals("N2") || name.equals("He")) {
ICVector icEntry = new ICVector(numSpecies-1,name,conc,unit.substring(1,unit.length()-1),reactivity,adjList);
tmodelInput.updateIC(icEntry);
} else
System.out.println("Warning: Could not read in one of the inert gas species: " + name + ". The Inert Gas options are 'N2', 'Ar', 'He', and 'Ne' (case sensitive)");
line = ChemParser.readMeaningfulLine(reader);
}
}
else if (line.startsWith("Spectroscopic")) {
// Spectroscopic data estimator
st = new StringTokenizer(line);
tempString = st.nextToken(); // Skip over SpectroscopicDataEstimator
String sde = st.nextToken();
if (sde.toLowerCase().equals("frequencygroups")) {
sdeCombo.setSelectedItem("Frequency Groups");
// } else if (sde.toLowerCase().equals("threefrequencymodel")) {
// sdeCombo.setSelectedItem("Three Frequency Model");
} else if (sde.toLowerCase().equals("off")) {
sdeCombo.setSelectedItem("off");
} else {
System.out.println("ERROR: Reading in condition.txt file - Invalid argument for SpectroscopicDataEstimator. RMG recognizes an argument of 'frequencygroups' or 'off' but not " + sde + ". GUI does not contain all information present in condition.txt file.");
}
}
else if (line.startsWith("PressureDep")) {
// Pressure dependence model
st = new StringTokenizer(line);
tempString = st.nextToken(); // Skip over PressureDependence
String pdep = st.nextToken();
if (pdep.toLowerCase().equals("off")) {
pdepCombo.setSelectedItem("off");
} else if (pdep.toLowerCase().equals("reservoirstate")) {
pdepCombo.setSelectedItem("Reservoir State");
} else if (pdep.toLowerCase().equals("modifiedstrongcollision")) {
pdepCombo.setSelectedItem("Modified Strong Collision");
} else {
System.out.println("ERROR: Reading in condition.txt file - Invalid argument for PressureDependence. RMG recognizes an argument of 'reservoirstate', 'modifiedstrongcollision', or 'off' but not " + pdep + ". GUI does not contain all information present in condition.txt file.");
}
}
else if (line.startsWith("PDepKinetics")) {
// Pressure dependent kinetics model
st = new StringTokenizer(line);
tempString = st.nextToken(); // Skip over PDepKineticsModel
String pdkm = st.nextToken();
if (pdkm.toLowerCase().equals("chebyshev")) {
pdkmCombo.setSelectedItem("CHEB");
} else if (pdkm.toLowerCase().equals("pdeparrhenius")) {
pdkmCombo.setSelectedItem("PLOG");
} else if (pdkm.toLowerCase().equals("rate")) {
pdkmCombo.setSelectedItem("Rate");
} else {
System.out.println("ERROR: Reading in condition.txt file - Invalid argument for PDepKineticsModel. RMG recognizes an argument of 'chebyshev' or 'pdeparrhenius' but not " + pdkm + ". GUI does not contain all information present in condition.txt file.");
}
}
else if (line.startsWith("TRange")) {
st = new StringTokenizer(line);
tempString = st.nextToken(); // Skip over TRange
String units = st.nextToken();
String unit = units.substring(1,units.length()-1);
if (unit.equals("K") || unit.equals("F") || unit.equals("C"))
chebyTUnits.setSelectedItem(unit);
else
System.out.println("ERROR: Reading in condition.txt file - Invalid chebyshev temperature unit. RMG recognizes temperature units of 'K', 'C', or 'F', but not " + unit + ". GUI does not contain all information present in condition.txt file.");
chebyTMin.setText(st.nextToken());
chebyTMax.setText(st.nextToken());
chebyTGen.setText(st.nextToken());
chebyTRep.setText(st.nextToken());
}
else if (line.startsWith("PRange")) {
st = new StringTokenizer(line);
tempString = st.nextToken(); // Skip over PRange
String units = st.nextToken();
String unit = units.substring(1,units.length()-1);
if (unit.equals("atm") || unit.equals("Pa") || unit.equals("bar") || unit.equals("torr"))
chebyPUnits.setSelectedItem(unit);
else
System.out.println("ERROR: Reading in condition.txt file - Invalid chebyshev pressure unit. RMG recognizes pressure units of 'atm', 'bar', 'torr', or 'Pa', but not " + unit + ". GUI does not contain all information present in condition.txt file.");
chebyPMin.setText(st.nextToken());
chebyPMax.setText(st.nextToken());
chebyPGen.setText(st.nextToken());
chebyPRep.setText(st.nextToken());
}
else if (line.startsWith("IncludeSpecies")) {
// IncludeSpecies.txt file (if present)
st = new StringTokenizer(line);
tempString = st.nextToken(); // Skip over IncludeSpecies
isPath.setText(st.nextToken());
}
else if (line.startsWith("(1) Goal")) {
// Goal
st = new StringTokenizer(line);
tempString = st.nextToken(); // Skip over "(1)"
tempString = st.nextToken(); // Skip over "Goal"
String goal = st.nextToken();
if (goal.startsWith("Conversion")) {
controllerCombo.setSelectedItem("Conversion");
SpeciesConvName.setSelectedItem(st.nextToken());
conversion.setText(st.nextToken());
} else if (goal.startsWith("Reaction")) {
controllerCombo.setSelectedItem("ReactionTime");
time.setText(st.nextToken());
String units = st.nextToken();
timeCombo.setSelectedItem(units.substring(1,units.length()-1));
} else {
System.out.println("ERROR: Reading in condition.txt file - Invalid argument for Goal. RMG recognizes an argument of 'Conversion' or 'ReactionTime' but not " + goal + ". GUI does not contain all information present in condition.txt file.");
}
}
else if (line.startsWith("(2) Error")) {
// Error tolerance
st = new StringTokenizer(line);
tempString = st.nextToken(); // Skip over "(2)"
tempString = st.nextToken(); // Skip over "Error"
tempString = st.nextToken(); // Skip over "Tolerance:"
eTolerance.setText(st.nextToken());
}
else if (line.startsWith("DynamicSim")) {
// Dynamic simulator
st = new StringTokenizer(line);
tempString = st.nextToken();
String sim = st.nextToken();
if (sim.equals("DASPK") || sim.equals("DASSL")) {
simulatorCombo.setSelectedItem(sim);
} else {
System.out.println("ERROR: Reading in condition.txt file - Invalid argument for DynamicSimulator. RMG recognizes an argument of 'DASPK' or 'DASSL' but not " + sim + ". GUI does not contain all information present in condition.txt file.");
}
}
else if (line.startsWith("Conversions")) {
// Intermediate integration step
st = new StringTokenizer(line);
String stepName = st.nextToken(); // Skip over Conversions
String steps = st.nextToken();
while (st.hasMoreTokens()) {
steps += " " + st.nextToken();
}
multiConv.setText(steps);
}
else if (line.startsWith("TimeStep")) {
// Intermediate integration step
st = new StringTokenizer(line);
String stepName = st.nextToken(); // Skip over TimeStep
String steps = st.nextToken();
while (st.hasMoreTokens()) {
steps += " " + st.nextToken();
}
multiTS.setText(steps);
}
else if (line.startsWith("Atol")) {
// Absolute tolerance
st = new StringTokenizer(line);
tempString = st.nextToken(); // Skip over Atol
aTolerance.setText(st.nextToken());
}
else if (line.startsWith("Rtol")) {
// Relative tolerance
st = new StringTokenizer(line);
tempString = st.nextToken(); // Skip over Rtol
rTolerance.setText(st.nextToken());
}
else if (line.startsWith("Error bars")) {
// Error bars and Sensitivity analysis (if present)
st = new StringTokenizer(line);
tempString = st.nextToken(); // Skip over "Error"
tempString = st.nextToken(); // Skip over "bars:"
String onoff = st.nextToken();
if (onoff.equals("on")) {
eBarsCombo.setSelectedItem("Yes");
} else if (onoff.equals("off")) {
eBarsCombo.setSelectedItem("No");
} else {
System.out.println("ERROR: Reading in condition.txt file - Invalid argument for Error bars. RMG recognizes an argument of 'Off' or 'On' but not " + onoff + ". GUI does not contain all information present in condition.txt file.");
}
}
else if (line.startsWith("Display sensitivity coefficients")) {
st = new StringTokenizer(line);
tempString = st.nextToken(); // Skip over "Display"
tempString = st.nextToken(); // Skip over "sensitivity"
tempString = st.nextToken(); // Skip over "coefficients:"
String onoff = st.nextToken();
if (onoff.equals("on")) {
sensCoeffCombo.setSelectedItem("Yes");
} else if (onoff.equals("off")) {
sensCoeffCombo.setSelectedItem("No");
} else {
System.out.println("ERROR: Reading in condition.txt file - Invalid argument for Display sensitivity coefficients. RMG recognizes an argument of 'Off' or 'On' but not " + onoff + ". GUI does not contain all information present in condition.txt file.");
}
}
else if (line.startsWith("Display sensitivity information")) {
// Sensitivity coefficients (if present)
line = ChemParser.readMeaningfulLine(reader);
numSpecies = 0;
while (!line.startsWith("END")) {
++numSpecies;
SensVector sensEntry = new SensVector(numSpecies-1,line);
tmodelSens.updateSens(sensEntry);
line = ChemParser.readMeaningfulLine(reader);
}
}
else if (line.startsWith("PrimaryReactionLibrary")) {
// Name(s)/Path(s) of PrimaryReactionLibrary
line = ChemParser.readMeaningfulLine(reader);
int prlCounter = 0;
while (!line.equals("END")) {
++prlCounter;
tempStringVector = line.split("Name: ");
String name = tempStringVector[tempStringVector.length-1].trim();
line = ChemParser.readMeaningfulLine(reader);
tempStringVector = line.split("Location: ");
String path = tempStringVector[tempStringVector.length-1].trim();
PRLVector prlEntry = new PRLVector(prlCounter-1,name,path);
tmodelPRL.updatePRL(prlEntry);
line = ChemParser.readMeaningfulLine(reader);
}
}
else if (line.startsWith("SeedMechanism")) {
// Name(s)/Path(s) of SeedMechanism
line = ChemParser.readMeaningfulLine(reader);
int smCounter = 0;
while (!line.equals("END")) {
++smCounter;
tempStringVector = line.split("Name: ");
String name = tempStringVector[tempStringVector.length-1].trim();
line = ChemParser.readMeaningfulLine(reader);
tempStringVector = line.split("Location: ");
String path = tempStringVector[tempStringVector.length-1].trim();
PRLVector smEntry = new PRLVector(smCounter-1,name,path);
tmodelSM.updatePRL(smEntry);
line = ChemParser.readMeaningfulLine(reader);
}
}
else if (line.startsWith("Verbose")) {
st = new StringTokenizer(line);
tempString = st.nextToken(); // Skip over Verbose
String onoff = st.nextToken();
if (onoff.equals("on")) {
chemkinVerbosity.setSelectedItem("Yes");
} else if (onoff.equals("off")) {
chemkinVerbosity.setSelectedItem("No");
} else {
System.out.println("ERROR: Reading in condition.txt file - Invalid argument for Chemkin Verbosity. RMG recognizes an argument of 'Off' or 'On' but not " + onoff + ". GUI does not contain all information present in condition.txt file.");
}
}
else if (line.startsWith("A:")) {
st = new StringTokenizer(line);
tempString = st.nextToken(); // Skip over A
String units = st.nextToken();
if (units.equals("moles") || units.equals("molecules"))
chemkinAUnits.setSelectedItem(units);
else
System.out.println("ERROR: Reading in condition.txt file - Invalid argument for Chemkin A units. RMG recognizes an argument of 'moles' or 'molecules' but not " + units + ". GUI does not contain all information present in condition.txt file.");
}
else if (line.startsWith("Ea:")) {
st = new StringTokenizer(line);
tempString = st.nextToken(); // Skip over Ea
String units = st.nextToken();
if (units.equals("cal/mol") || units.equals("kcal/mol") || units.equals("kJ/mol") ||
units.equals("J/mol") || units.equals("Kelvins"))
chemkinEaUnits.setSelectedItem(units);
else
System.out.println("ERROR: Reading in condition.txt file - Invalid argument for Chemkin Ea units. RMG recognizes an argument of 'kcal/mol', 'cal/mol', 'kJ/mol', 'J/mol', or 'Kelvins' but not " + units + ". GUI does not contain all information present in condition.txt file.");
}
else
if (!line.startsWith("FinishController") & !line.startsWith("ChemkinUnits"))
System.out.println("Warning: Reading in condition.txt file - Interpreter does not recognize the following line: " + line);
line = ChemParser.readMeaningfulLine(reader);
}
}
public JComponent createTabOptions() {
// Create cellrenderers for JComboBox/JTable - CENTER text
ListCellRenderer centerJComboBoxRenderer = new CenterJCBRenderer();
// Create "Options" panel
JPanel Options = new JPanel();
Options.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createTitledBorder("Additional Options"),
BorderFactory.createEmptyBorder(5,5,5,5)));
// Create the InChI generation subpanel
JPanel inchiPanel = new JPanel();
inchiPanel.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createTitledBorder("InChI Generation"),
BorderFactory.createEmptyBorder(5,5,5,5)));
// Populate the subpanel
JLabel inchiLabel = new JLabel("Generate InChIs");
inchiPanel.add(inchiLabel);
inchiPanel.add(inchiCombo = new JComboBox(yesnoOptions));
// Create the Max carbon/oxygen/radical subpanel
JPanel maxPanel = new JPanel();
maxPanel.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createTitledBorder("Species properties"),
BorderFactory.createEmptyBorder(5,5,5,5)));
// Populate the subpanel
JPanel carbonPanel = new JPanel();
carbonPanel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
JLabel maxCarbonLabel = new JLabel("Maximum Carbon # per species");
carbonPanel.add(maxCarbonLabel);
carbonPanel.add(maxCarbonNum = new JTextField());
maxCarbonNum.setPreferredSize(new Dimension(50,25));
maxCarbonNum.addActionListener(this);
maxCarbonNum.setHorizontalAlignment(JTextField.CENTER);
JPanel oxygenPanel = new JPanel();
oxygenPanel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
JLabel maxOxygenLabel = new JLabel("Maximum Oxygen # per species");
oxygenPanel.add(maxOxygenLabel);
oxygenPanel.add(maxOxygenNum = new JTextField());
maxOxygenNum.setPreferredSize(new Dimension(50,25));
maxOxygenNum.addActionListener(this);
maxOxygenNum.setHorizontalAlignment(JTextField.CENTER);
JPanel radicalPanel = new JPanel();
radicalPanel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
JLabel maxRadicalLabel = new JLabel("Maximum Radical # per species");
radicalPanel.add(maxRadicalLabel);
radicalPanel.add(maxRadicalNum = new JTextField());
maxRadicalNum.setPreferredSize(new Dimension(50,25));
maxRadicalNum.addActionListener(this);
maxRadicalNum.setHorizontalAlignment(JTextField.CENTER);
Box maxSpeciesProps = Box.createVerticalBox();
maxSpeciesProps.add(carbonPanel);
maxSpeciesProps.add(oxygenPanel);
maxSpeciesProps.add(radicalPanel);
maxPanel.add(maxSpeciesProps);
// Create the Max carbon/oxygen/radical subpanel
JPanel chemkinPanel = new JPanel();
chemkinPanel.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createTitledBorder("CHEMKIN chem.inp properties"),
BorderFactory.createEmptyBorder(5,5,5,5)));
// Populate the subpanel
JPanel AUnitsPanel = new JPanel();
AUnitsPanel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
JLabel ALabel = new JLabel("Units of A in chem.inp file");
AUnitsPanel.add(ALabel);
AUnitsPanel.add(chemkinAUnits = new JComboBox(AUnitsOptions));
JPanel EaUnitsPanel = new JPanel();
EaUnitsPanel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
JLabel EaLabel = new JLabel("Units of Ea in chem.inp file");
EaUnitsPanel.add(EaLabel);
EaUnitsPanel.add(chemkinEaUnits = new JComboBox(EaUnitsOptions));
JPanel verbosePanel = new JPanel();
verbosePanel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
JLabel verboseLabel = new JLabel("Detailed kinetics comments");
verbosePanel.add(verboseLabel);
verbosePanel.add(chemkinVerbosity = new JComboBox(yesnoOptions));
Box chemkinProps = Box.createVerticalBox();
chemkinProps.add(AUnitsPanel);
chemkinProps.add(EaUnitsPanel);
chemkinProps.add(verbosePanel);
chemkinPanel.add(chemkinProps);
// Create the Equation Of State (EOS) subpanel
JPanel EOS = new JPanel();
EOS.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createTitledBorder("Equation of State"),
BorderFactory.createEmptyBorder(5,5,5,5)));
// Populate the subpanel
JLabel eosLabel = new JLabel("Equation of State");
EOS.add(eosLabel);
EOS.add(eosCombo = new JComboBox(eosOptions));
Box totalOptionsBox = Box.createVerticalBox();
totalOptionsBox.add(maxPanel);
totalOptionsBox.add(chemkinPanel);
totalOptionsBox.add(inchiPanel);
totalOptionsBox.add(EOS);
Options.add(totalOptionsBox);
JComboBox[] allTab = {eosCombo, inchiCombo, chemkinAUnits,
chemkinEaUnits, chemkinVerbosity};
initializeJCB(allTab);
JScrollPane scrolltab = new JScrollPane(Options);
scrolltab.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
return scrolltab;
}
public void runConditionFile(String c_path) {
String[] rmgArgs = {c_path};
RMG.main(rmgArgs);
System.exit(0);
}
public void enableComponents (JComponent[] allComponents) {
for (int i=0; i<allComponents.length; i++)
allComponents[i].setEnabled(true);
}
public void disableComponents (JComponent[] allComponents) {
for (int i=0; i<allComponents.length; i++)
allComponents[i].setEnabled(false);
}
public void actionPerformed(ActionEvent event) {
// - If Termination sequence is specified, highlight appropriate boxes
if ("GoalofReaction".equals(event.getActionCommand())) {
JComponent[] timeComps = {timeCombo, time, multiTS};
JComponent[] convComps = {SpeciesConvName, conversion, multiConv};
if (controllerCombo.getSelectedItem().equals("ReactionTime")) {
enableComponents(timeComps);
disableComponents(convComps);
} else if (controllerCombo.getSelectedItem().equals("Conversion")) {
enableComponents(convComps);
disableComponents(timeComps);
}
}
// - If Sensitivity analysis is turned on/off, highlight the appropriate boxes
else if ("scOnOff".equals(event.getActionCommand())) {
JComponent[] scComps = {AddSens, DeleteSens, tableSens, scName};
if (sensCoeffCombo.getSelectedItem().equals("Yes")) {
enableComponents(scComps);
} else if (sensCoeffCombo.getSelectedItem().equals("No")){
disableComponents(scComps);
}
}
// If the user enables/disables DASPK
else if ("saOnOff".equals(event.getActionCommand())) {
JComponent[] saComps = {eBarsCombo, sensCoeffCombo};
JComponent[] otherComps = {AddSens, DeleteSens, tableSens, scName};
if (simulatorCombo.getSelectedItem().equals("DASPK")) {
enableComponents(saComps);
if (sensCoeffCombo.getSelectedItem().equals("Yes")) enableComponents(otherComps);
else if (sensCoeffCombo.getSelectedItem().equals("No")) disableComponents(otherComps);
} else if (simulatorCombo.getSelectedItem().equals("DASSL")) {
disableComponents(saComps);
disableComponents(otherComps);
}
}
else if ("pDep".equals(event.getActionCommand())) {
JComponent[] pDepComps = {sdeCombo, pdkmCombo};
JComponent[] pdkmComps = {chebyTMin, chebyTMax, chebyTUnits, chebyTGen, chebyTRep,
chebyPMin, chebyPMax, chebyPUnits, chebyPGen, chebyPRep};
if (pdepCombo.getSelectedItem().equals("off")) {
disableComponents(pDepComps);
disableComponents(pdkmComps);
} else {
enableComponents(pDepComps);
if (pdkmCombo.getSelectedItem().equals("CHEB")) {
enableComponents(pdkmComps);
} else
disableComponents(pdkmComps);
}
}
else if ("pdkm".equals(event.getActionCommand())) {
JComponent[] pdkmComps = {chebyTMin, chebyTMax, chebyTUnits, chebyTGen, chebyTRep,
chebyPMin, chebyPMax, chebyPUnits, chebyPGen, chebyPRep};
if (pdkmCombo.getSelectedItem().equals("CHEB")) {
enableComponents(pdkmComps);
} else
disableComponents(pdkmComps);
}
// Save the condition.txt file
else if ("saveCondition".equals(event.getActionCommand())) {
createConditionFile(false);
}
// Save and run the condition.txt file
else if ("runCondition".equals(event.getActionCommand())) {
createConditionFile(true);
}
}
// Main panel
private static GUI theApp;
// Tab0: Initialization
String[] timeUnits = {"sec", "min", "hr", "day"};
// Tab1: Termination Sequence
String[] species_blank = {" "};
String[] goalOptions = {"Conversion", "ReactionTime"};
// Tab2: Initial Condition
String[] tpModel = {"Constant"};
String[] concUnits = {"mol/cm3", "mol/m3", "mol/liter"};
String[] tempUnits = {"K", "C", "F"};
String[] pressUnits = {"atm", "bar", "Pa", "torr"};
String[] reactive = {"Reactive-RMG", "Reactive-User", "Inert"};
// Tab3: Error Analysis
String[] yesnoOptions = {"No", "Yes"};
// Tab4: Dynamic Simulator
String[] pdepOptions = {"off", "Reservoir State", "Modified Strong Collision"};
String[] simOptions = {"DASSL", "DASPK"}; //"CHEMKIN"
String[] sdeOptions = {"Frequency Groups"}; //"Three Frequency Model"
String[] pdkmOptions = {"CHEB", "PLOG", "Rate"};
// Tab : Additional Options
String[] AUnitsOptions = {"moles", "molecules"};
String[] EaUnitsOptions = {"kcal/mol", "cal/mol", "kJ/mol", "J/mol", "Kelvins"};
String[] eosOptions = {"Ideal Gas"}; // "Liquid"
JPanel
// Main Panel
mainPanel;
JComboBox
// Tab0: Initialization
simulatorCombo, timeStepCombo, libraryCombo,
// Tab1: Termination Sequence
SpeciesConvName, controllerCombo, timeCombo,
// Tab2: Initial Condition
UnitsInput, ReactiveInput, tempModelCombo, tempConstantUnit,
pressModelCombo, pressConstantUnit,
// Tab3: Error Analysis
SpeciesSensName, eBarsCombo, sensCoeffCombo,
// Tab4: Dynamic Simulator
pdepCombo, sdeCombo, pdkmCombo,
// Tab : Additional Options
eosCombo, inchiCombo, chemkinAUnits, chemkinEaUnits, chemkinVerbosity,
//
chebyTUnits, chebyPUnits;
JTextField
// Tab0: Initialization
nameFiller, locationFiller, databasePath, prlPath, ptlPath,
timeStep, aTolerance, rTolerance, ptlLibName, prlLibName,
smLibName, smPath,
// Tab1: Termination Sequence
conversion, time, eTolerance,
// Tab2: Initial Condition
NameInput, InChIInput, isPath, ConcInput,
// Tab3: Error Analysis
scName,
// Tab : Additional Options
maxCarbonNum, maxOxygenNum, maxRadicalNum,
//
chebyTMin, chebyTMax, chebyPMin, chebyPMax, chebyTGen, chebyTRep,
chebyPGen, chebyPRep;
JTextArea
// Main Panel
headerComments,
// Tab2: Initial Condition
speciesAdjList, tempConstant, pressConstant,
// Tab4: Dynamic Simulator
multiTS, multiConv;
JButton
// Main panel
save, saveAndRun,
// Tab0: Initialization
AddPRL, DeletePRL, databaseButton, prlButton, ptlButton,
AddPTL, DeletePTL, smButton, AddSM, DeleteSM,
// Tab1: Termination
// Tab2: Initial Condition
AddInput, DeleteInput, isButton,
// Tab3: Error Analysis
AddSens, DeleteSens;
JTable
// Tab0: Initialization
tablePRL, tablePTL, tableSM,
// Tab1: Termination
// Tab2: Initial Condition
tableInput,
// Tab3: Error Analysis
tableSens;
// Tab0: Initialization
MyTableModelPRL tmodelPRL, tmodelPTL, tmodelSM;
// Tab1: Termination
// Tab2: Initial Condition
MyTableModelInput tmodelInput;
// Tab3: Error Analysis
MyTableModelSensitivity tmodelSens;
}
| false | true | public void openConditionFile(File filePath) {
int numSpecies = 0;
tmodelPTL.clear();
tmodelPRL.clear();
tmodelSM.clear();
tmodelInput.clear();
tmodelSens.clear();
System.out.println("GUI cannot read in file's header (comments)");
// Read in the .txt file
FileReader in = null;
try {
in = new FileReader(filePath);
} catch (FileNotFoundException e) {
String err = "Error reading file: ";
err += e.toString();
System.out.println(err);
}
BufferedReader reader = new BufferedReader(in);
String line = ChemParser.readMeaningfulLine(reader);
read: while (line != null) {
// Populate the GUI with as much information as possible
StringTokenizer st = null;
String tempString = "";
String[] tempStringVector = null;
if (line.startsWith("Database")) {
// Path of Database
st = new StringTokenizer(line);
tempString = st.nextToken(); // Skip over "Database:"
databasePath.setText(st.nextToken());
}
else if (line.startsWith("PrimaryThermoLibrary")) {
// Name(s)/Path(s) of PrimaryThermoLibrary
line = ChemParser.readMeaningfulLine(reader);
int ptlCounter = 0;
while (!line.equals("END")) {
++ptlCounter;
tempStringVector = line.split("Name: ");
String name = tempStringVector[tempStringVector.length-1].trim();
line = ChemParser.readMeaningfulLine(reader);
tempStringVector = line.split("Location: ");
String path = tempStringVector[tempStringVector.length-1].trim();
PRLVector ptlEntry = new PRLVector(ptlCounter-1,name,path);
tmodelPTL.updatePRL(ptlEntry);
line = ChemParser.readMeaningfulLine(reader);
}
}
else if (line.startsWith("TemperatureModel")) {
// Temperature model
st = new StringTokenizer(line);
tempString = st.nextToken(); // Skip over "TemperatureModel:"
String modelTemp = st.nextToken();
if (!modelTemp.equals("Constant")) {
System.out.println("ERROR: Reading in condition.txt file - Invalid TemperatureModel. RMG recognizes 'Constant' TemperatureModel, but not " + modelTemp + ". GUI does not contain all information present in condition.txt file.");
}
tempModelCombo.setSelectedItem(modelTemp);
String unitTemp = st.nextToken().substring(1,2);
if (unitTemp.equals("K") || unitTemp.equals("F") || unitTemp.equals("C")) {
tempConstantUnit.setSelectedItem(unitTemp);
}
else {
System.out.println("ERROR: Reading in condition.txt file - Invalid temperature unit. RMG recognizes temperature units of 'K', 'C', or 'F', but not " + unitTemp + ". GUI does not contain all information present in condition.txt file.");
}
String temps = st.nextToken();
while (st.hasMoreTokens()) {
temps += " " + st.nextToken();
}
tempConstant.setText(temps);
}
else if (line.startsWith("PressureModel")) {
// Pressure model
st = new StringTokenizer(line);
tempString = st.nextToken(); // Skip over "PressureModel:"
String modelPress = st.nextToken();
if (!modelPress.equals("Constant")) {
System.out.println("ERROR: Reading in condition.txt file - Invalid PressureModel. RMG recognizes 'Constant' PressureModel, but not " + modelPress + ". GUI does not contain all information present in condition.txt file.");
}
else {
pressModelCombo.setSelectedItem(modelPress);
}
String temp = st.nextToken();
String unitPress = temp.substring(1,temp.length()-1);
if (unitPress.equals("atm") || unitPress.equals("Pa") || unitPress.equals("bar") || unitPress.equals("torr")) {
pressConstantUnit.setSelectedItem(unitPress);
}
else {
System.out.println("ERROR: Reading in condition.txt file - Invalid pressure unit. RMG recognizes pressure units of 'atm', 'Pa', 'bar' or 'torr', but not " + unitPress + ". GUI does not contain all information present in condition.txt file.");
}
String presses = st.nextToken();
while (st.hasMoreTokens()) {
presses += " " + st.nextToken();
}
pressConstant.setText(presses);
}
// GUI only recognized Ideal Gas EOS (30Jul2009)
// else if (line.startsWith("EquationOfState")) {
// // Equation of state (if present)
// st = new StringTokenizer(line);
// tempString = st.nextToken(); // Skip over "EquationOfState"
// tempString = st.nextToken();
// if (tempString.equals("Liquid")) {
// eosCombo.setSelectedItem(tempString);
// } else {
// System.out.println("ERROR: Reading in condition.txt file - Invalid equation of state. RMG recognizes 'Liquid', but not " + tempString + ". GUI does not contain all information present in condition.txt file.");
// }
// }
else if (line.startsWith("MaxCarbonNumber")) {
st = new StringTokenizer(line);
tempString = st.nextToken(); // Skip over "MaxCarbonNumberPerSpecies"\
maxCarbonNum.setText(st.nextToken());
}
else if (line.startsWith("MaxOxygenNumber")) {
st = new StringTokenizer(line);
tempString = st.nextToken(); // Skip over "MaxOxygenNumberPerSpecies"\
maxOxygenNum.setText(st.nextToken());
}
else if (line.startsWith("MaxRadicalNumber")) {
st = new StringTokenizer(line);
tempString = st.nextToken(); // Skip over "MaxRadicalNumberPerSpecies"\
maxRadicalNum.setText(st.nextToken());
}
else if (line.startsWith("InChIGeneration")) {
// InChI generation
st = new StringTokenizer(line);
tempString = st.nextToken(); // Skip over "InChIGeneration:"
String inchi = st.nextToken();
if (inchi.toLowerCase().equals("on")) {
inchiCombo.setSelectedItem("Yes");
} else if (inchi.toLowerCase().equals("off")) {
inchiCombo.setSelectedItem("No");
} else {
System.out.println("ERROR: Reading in condition.txt file - Invalid argument for InChIGeneration. RMG recognizes an argument of 'On' or 'Off', but not " + inchi + ". GUI does not contain all information present in condition.txt file.");
}
}
// GUI does not handle Solvation (30Jul2009)
// else if (line.startsWith("Solvation")) {
// // Solvation
// st = new StringTokenizer(line);
// tempString = st.nextToken(); // Skip over "Solvation:"
// String solvation = st.nextToken();
// if (solvation.toLowerCase().equals("on")) {
// solvationCombo.setSelectedItem("Yes");
// } else if (solvation.toLowerCase().equals("off")) {
// solvationCombo.setSelectedItem("No");
// } else {
// System.out.println("ERROR: Reading in condition.txt file - Invalid argument for Solvation. RMG recognizes an argument of 'On' or 'Off', but not " + solvation + ". GUI does not contain all information present in condition.txt file.");
// }
// }
else if (line.startsWith("InitialStatus")) {
String adjList = "";
String name = "";
String conc = "";
String unit = "";
String reactivity = "";
line = ChemParser.readMeaningfulLine(reader);
while (!line.startsWith("END")) {
if (line.startsWith("(")) {
++numSpecies;
st = new StringTokenizer(line);
tempString = st.nextToken(); // Skip over (#)
name = st.nextToken();
conc = st.nextToken();
unit = st.nextToken();
reactivity = "Reactive";
if (st.hasMoreTokens()) {
reactivity = "Unreactive";
}
} else {
adjList += line + "\r";
}
line = ChemParser.readMeaningfulLine(reader);
if (line.startsWith("(") || line.startsWith("END")) {
ICVector icEntry = new ICVector(numSpecies-1,name,conc,unit.substring(1,unit.length()-1),reactivity,adjList);
tmodelInput.updateIC(icEntry);
adjList = "";
}
}
limitingReactant();
}
else if (line.startsWith("InertGas")) {
// Inert gases
String name = "";
String conc = "";
String unit = "";
String reactivity = "";
String adjList = "";
line = ChemParser.readMeaningfulLine(reader);
while (!line.startsWith("END")) {
++numSpecies;
st = new StringTokenizer(line);
name = st.nextToken();
conc = st.nextToken();
unit = st.nextToken();
reactivity = "Inert";
if (name.equals("Ar") || name.equals("Ne") || name.equals("N2") || name.equals("He")) {
ICVector icEntry = new ICVector(numSpecies-1,name,conc,unit.substring(1,unit.length()-1),reactivity,adjList);
tmodelInput.updateIC(icEntry);
} else
System.out.println("Warning: Could not read in one of the inert gas species: " + name + ". The Inert Gas options are 'N2', 'Ar', 'He', and 'Ne' (case sensitive)");
line = ChemParser.readMeaningfulLine(reader);
}
}
else if (line.startsWith("Spectroscopic")) {
// Spectroscopic data estimator
st = new StringTokenizer(line);
tempString = st.nextToken(); // Skip over SpectroscopicDataEstimator
String sde = st.nextToken();
if (sde.toLowerCase().equals("frequencygroups")) {
sdeCombo.setSelectedItem("Frequency Groups");
// } else if (sde.toLowerCase().equals("threefrequencymodel")) {
// sdeCombo.setSelectedItem("Three Frequency Model");
} else if (sde.toLowerCase().equals("off")) {
sdeCombo.setSelectedItem("off");
} else {
System.out.println("ERROR: Reading in condition.txt file - Invalid argument for SpectroscopicDataEstimator. RMG recognizes an argument of 'frequencygroups' or 'off' but not " + sde + ". GUI does not contain all information present in condition.txt file.");
}
}
else if (line.startsWith("PressureDep")) {
// Pressure dependence model
st = new StringTokenizer(line);
tempString = st.nextToken(); // Skip over PressureDependence
String pdep = st.nextToken();
if (pdep.toLowerCase().equals("off")) {
pdepCombo.setSelectedItem("off");
} else if (pdep.toLowerCase().equals("reservoirstate")) {
pdepCombo.setSelectedItem("Reservoir State");
} else if (pdep.toLowerCase().equals("modifiedstrongcollision")) {
pdepCombo.setSelectedItem("Modified Strong Collision");
} else {
System.out.println("ERROR: Reading in condition.txt file - Invalid argument for PressureDependence. RMG recognizes an argument of 'reservoirstate', 'modifiedstrongcollision', or 'off' but not " + pdep + ". GUI does not contain all information present in condition.txt file.");
}
}
else if (line.startsWith("PDepKinetics")) {
// Pressure dependent kinetics model
st = new StringTokenizer(line);
tempString = st.nextToken(); // Skip over PDepKineticsModel
String pdkm = st.nextToken();
if (pdkm.toLowerCase().equals("chebyshev")) {
pdkmCombo.setSelectedItem("CHEB");
} else if (pdkm.toLowerCase().equals("pdeparrhenius")) {
pdkmCombo.setSelectedItem("PLOG");
} else if (pdkm.toLowerCase().equals("rate")) {
pdkmCombo.setSelectedItem("Rate");
} else {
System.out.println("ERROR: Reading in condition.txt file - Invalid argument for PDepKineticsModel. RMG recognizes an argument of 'chebyshev' or 'pdeparrhenius' but not " + pdkm + ". GUI does not contain all information present in condition.txt file.");
}
}
else if (line.startsWith("TRange")) {
st = new StringTokenizer(line);
tempString = st.nextToken(); // Skip over TRange
String units = st.nextToken();
String unit = units.substring(1,units.length()-1);
if (unit.equals("K") || unit.equals("F") || unit.equals("C"))
chebyTUnits.setSelectedItem(unit);
else
System.out.println("ERROR: Reading in condition.txt file - Invalid chebyshev temperature unit. RMG recognizes temperature units of 'K', 'C', or 'F', but not " + unit + ". GUI does not contain all information present in condition.txt file.");
chebyTMin.setText(st.nextToken());
chebyTMax.setText(st.nextToken());
chebyTGen.setText(st.nextToken());
chebyTRep.setText(st.nextToken());
}
else if (line.startsWith("PRange")) {
st = new StringTokenizer(line);
tempString = st.nextToken(); // Skip over PRange
String units = st.nextToken();
String unit = units.substring(1,units.length()-1);
if (unit.equals("atm") || unit.equals("Pa") || unit.equals("bar") || unit.equals("torr"))
chebyPUnits.setSelectedItem(unit);
else
System.out.println("ERROR: Reading in condition.txt file - Invalid chebyshev pressure unit. RMG recognizes pressure units of 'atm', 'bar', 'torr', or 'Pa', but not " + unit + ". GUI does not contain all information present in condition.txt file.");
chebyPMin.setText(st.nextToken());
chebyPMax.setText(st.nextToken());
chebyPGen.setText(st.nextToken());
chebyPRep.setText(st.nextToken());
}
else if (line.startsWith("IncludeSpecies")) {
// IncludeSpecies.txt file (if present)
st = new StringTokenizer(line);
tempString = st.nextToken(); // Skip over IncludeSpecies
isPath.setText(st.nextToken());
}
else if (line.startsWith("(1) Goal")) {
// Goal
st = new StringTokenizer(line);
tempString = st.nextToken(); // Skip over "(1)"
tempString = st.nextToken(); // Skip over "Goal"
String goal = st.nextToken();
if (goal.startsWith("Conversion")) {
controllerCombo.setSelectedItem("Conversion");
SpeciesConvName.setSelectedItem(st.nextToken());
conversion.setText(st.nextToken());
} else if (goal.startsWith("Reaction")) {
controllerCombo.setSelectedItem("ReactionTime");
time.setText(st.nextToken());
String units = st.nextToken();
timeCombo.setSelectedItem(units.substring(1,units.length()-1));
} else {
System.out.println("ERROR: Reading in condition.txt file - Invalid argument for Goal. RMG recognizes an argument of 'Conversion' or 'ReactionTime' but not " + goal + ". GUI does not contain all information present in condition.txt file.");
}
}
else if (line.startsWith("(2) Error")) {
// Error tolerance
st = new StringTokenizer(line);
tempString = st.nextToken(); // Skip over "(2)"
tempString = st.nextToken(); // Skip over "Error"
tempString = st.nextToken(); // Skip over "Tolerance:"
eTolerance.setText(st.nextToken());
}
else if (line.startsWith("DynamicSim")) {
// Dynamic simulator
st = new StringTokenizer(line);
tempString = st.nextToken();
String sim = st.nextToken();
if (sim.equals("DASPK") || sim.equals("DASSL")) {
simulatorCombo.setSelectedItem(sim);
} else {
System.out.println("ERROR: Reading in condition.txt file - Invalid argument for DynamicSimulator. RMG recognizes an argument of 'DASPK' or 'DASSL' but not " + sim + ". GUI does not contain all information present in condition.txt file.");
}
}
else if (line.startsWith("Conversions")) {
// Intermediate integration step
st = new StringTokenizer(line);
String stepName = st.nextToken(); // Skip over Conversions
String steps = st.nextToken();
while (st.hasMoreTokens()) {
steps += " " + st.nextToken();
}
multiConv.setText(steps);
}
else if (line.startsWith("TimeStep")) {
// Intermediate integration step
st = new StringTokenizer(line);
String stepName = st.nextToken(); // Skip over TimeStep
String steps = st.nextToken();
while (st.hasMoreTokens()) {
steps += " " + st.nextToken();
}
multiTS.setText(steps);
}
else if (line.startsWith("Atol")) {
// Absolute tolerance
st = new StringTokenizer(line);
tempString = st.nextToken(); // Skip over Atol
aTolerance.setText(st.nextToken());
}
else if (line.startsWith("Rtol")) {
// Relative tolerance
st = new StringTokenizer(line);
tempString = st.nextToken(); // Skip over Rtol
rTolerance.setText(st.nextToken());
}
else if (line.startsWith("Error bars")) {
// Error bars and Sensitivity analysis (if present)
st = new StringTokenizer(line);
tempString = st.nextToken(); // Skip over "Error"
tempString = st.nextToken(); // Skip over "bars:"
String onoff = st.nextToken();
if (onoff.equals("on")) {
eBarsCombo.setSelectedItem("Yes");
} else if (onoff.equals("off")) {
eBarsCombo.setSelectedItem("No");
} else {
System.out.println("ERROR: Reading in condition.txt file - Invalid argument for Error bars. RMG recognizes an argument of 'Off' or 'On' but not " + onoff + ". GUI does not contain all information present in condition.txt file.");
}
}
else if (line.startsWith("Display sensitivity coefficients")) {
st = new StringTokenizer(line);
tempString = st.nextToken(); // Skip over "Display"
tempString = st.nextToken(); // Skip over "sensitivity"
tempString = st.nextToken(); // Skip over "coefficients:"
String onoff = st.nextToken();
if (onoff.equals("on")) {
sensCoeffCombo.setSelectedItem("Yes");
} else if (onoff.equals("off")) {
sensCoeffCombo.setSelectedItem("No");
} else {
System.out.println("ERROR: Reading in condition.txt file - Invalid argument for Display sensitivity coefficients. RMG recognizes an argument of 'Off' or 'On' but not " + onoff + ". GUI does not contain all information present in condition.txt file.");
}
}
else if (line.startsWith("Display sensitivity information")) {
// Sensitivity coefficients (if present)
line = ChemParser.readMeaningfulLine(reader);
numSpecies = 0;
while (!line.startsWith("END")) {
++numSpecies;
SensVector sensEntry = new SensVector(numSpecies-1,line);
tmodelSens.updateSens(sensEntry);
line = ChemParser.readMeaningfulLine(reader);
}
}
else if (line.startsWith("PrimaryReactionLibrary")) {
// Name(s)/Path(s) of PrimaryReactionLibrary
line = ChemParser.readMeaningfulLine(reader);
int prlCounter = 0;
while (!line.equals("END")) {
++prlCounter;
tempStringVector = line.split("Name: ");
String name = tempStringVector[tempStringVector.length-1].trim();
line = ChemParser.readMeaningfulLine(reader);
tempStringVector = line.split("Location: ");
String path = tempStringVector[tempStringVector.length-1].trim();
PRLVector prlEntry = new PRLVector(prlCounter-1,name,path);
tmodelPRL.updatePRL(prlEntry);
line = ChemParser.readMeaningfulLine(reader);
}
}
else if (line.startsWith("SeedMechanism")) {
// Name(s)/Path(s) of SeedMechanism
line = ChemParser.readMeaningfulLine(reader);
int smCounter = 0;
while (!line.equals("END")) {
++smCounter;
tempStringVector = line.split("Name: ");
String name = tempStringVector[tempStringVector.length-1].trim();
line = ChemParser.readMeaningfulLine(reader);
tempStringVector = line.split("Location: ");
String path = tempStringVector[tempStringVector.length-1].trim();
PRLVector smEntry = new PRLVector(smCounter-1,name,path);
tmodelSM.updatePRL(smEntry);
line = ChemParser.readMeaningfulLine(reader);
}
}
else if (line.startsWith("Verbose")) {
st = new StringTokenizer(line);
tempString = st.nextToken(); // Skip over Verbose
String onoff = st.nextToken();
if (onoff.equals("on")) {
chemkinVerbosity.setSelectedItem("Yes");
} else if (onoff.equals("off")) {
chemkinVerbosity.setSelectedItem("No");
} else {
System.out.println("ERROR: Reading in condition.txt file - Invalid argument for Chemkin Verbosity. RMG recognizes an argument of 'Off' or 'On' but not " + onoff + ". GUI does not contain all information present in condition.txt file.");
}
}
else if (line.startsWith("A:")) {
st = new StringTokenizer(line);
tempString = st.nextToken(); // Skip over A
String units = st.nextToken();
if (units.equals("moles") || units.equals("molecules"))
chemkinAUnits.setSelectedItem(units);
else
System.out.println("ERROR: Reading in condition.txt file - Invalid argument for Chemkin A units. RMG recognizes an argument of 'moles' or 'molecules' but not " + units + ". GUI does not contain all information present in condition.txt file.");
}
else if (line.startsWith("Ea:")) {
st = new StringTokenizer(line);
tempString = st.nextToken(); // Skip over Ea
String units = st.nextToken();
if (units.equals("cal/mol") || units.equals("kcal/mol") || units.equals("kJ/mol") ||
units.equals("J/mol") || units.equals("Kelvins"))
chemkinEaUnits.setSelectedItem(units);
else
System.out.println("ERROR: Reading in condition.txt file - Invalid argument for Chemkin Ea units. RMG recognizes an argument of 'kcal/mol', 'cal/mol', 'kJ/mol', 'J/mol', or 'Kelvins' but not " + units + ". GUI does not contain all information present in condition.txt file.");
}
else
if (!line.startsWith("FinishController") & !line.startsWith("ChemkinUnits"))
System.out.println("Warning: Reading in condition.txt file - Interpreter does not recognize the following line: " + line);
line = ChemParser.readMeaningfulLine(reader);
}
}
| public void openConditionFile(File filePath) {
int numSpecies = 0;
tmodelPTL.clear();
tmodelPRL.clear();
tmodelSM.clear();
tmodelInput.clear();
tmodelSens.clear();
System.out.println("GUI cannot read in file's header (comments)");
// Read in the .txt file
FileReader in = null;
try {
in = new FileReader(filePath);
} catch (FileNotFoundException e) {
String err = "Error reading file: ";
err += e.toString();
System.out.println(err);
}
BufferedReader reader = new BufferedReader(in);
String line = ChemParser.readMeaningfulLine(reader);
read: while (line != null) {
// Populate the GUI with as much information as possible
StringTokenizer st = null;
String tempString = "";
String[] tempStringVector = null;
if (line.startsWith("Database")) {
// Path of Database
st = new StringTokenizer(line);
tempString = st.nextToken(); // Skip over "Database:"
databasePath.setText(st.nextToken());
}
else if (line.startsWith("PrimaryThermoLibrary")) {
// Name(s)/Path(s) of PrimaryThermoLibrary
line = ChemParser.readMeaningfulLine(reader);
int ptlCounter = 0;
while (!line.equals("END")) {
++ptlCounter;
tempStringVector = line.split("Name: ");
String name = tempStringVector[tempStringVector.length-1].trim();
line = ChemParser.readMeaningfulLine(reader);
tempStringVector = line.split("Location: ");
String path = tempStringVector[tempStringVector.length-1].trim();
PRLVector ptlEntry = new PRLVector(ptlCounter-1,name,path);
tmodelPTL.updatePRL(ptlEntry);
line = ChemParser.readMeaningfulLine(reader);
}
}
else if (line.startsWith("TemperatureModel")) {
// Temperature model
st = new StringTokenizer(line);
tempString = st.nextToken(); // Skip over "TemperatureModel:"
String modelTemp = st.nextToken();
if (!modelTemp.equals("Constant")) {
System.out.println("ERROR: Reading in condition.txt file - Invalid TemperatureModel. RMG recognizes 'Constant' TemperatureModel, but not " + modelTemp + ". GUI does not contain all information present in condition.txt file.");
}
tempModelCombo.setSelectedItem(modelTemp);
String unitTemp = st.nextToken().substring(1,2);
if (unitTemp.equals("K") || unitTemp.equals("F") || unitTemp.equals("C")) {
tempConstantUnit.setSelectedItem(unitTemp);
}
else {
System.out.println("ERROR: Reading in condition.txt file - Invalid temperature unit. RMG recognizes temperature units of 'K', 'C', or 'F', but not " + unitTemp + ". GUI does not contain all information present in condition.txt file.");
}
String temps = st.nextToken();
while (st.hasMoreTokens()) {
temps += " " + st.nextToken();
}
tempConstant.setText(temps);
}
else if (line.startsWith("PressureModel")) {
// Pressure model
st = new StringTokenizer(line);
tempString = st.nextToken(); // Skip over "PressureModel:"
String modelPress = st.nextToken();
if (!modelPress.equals("Constant")) {
System.out.println("ERROR: Reading in condition.txt file - Invalid PressureModel. RMG recognizes 'Constant' PressureModel, but not " + modelPress + ". GUI does not contain all information present in condition.txt file.");
}
else {
pressModelCombo.setSelectedItem(modelPress);
}
String temp = st.nextToken();
String unitPress = temp.substring(1,temp.length()-1);
if (unitPress.equals("atm") || unitPress.equals("Pa") || unitPress.equals("bar") || unitPress.equals("torr")) {
pressConstantUnit.setSelectedItem(unitPress);
}
else {
System.out.println("ERROR: Reading in condition.txt file - Invalid pressure unit. RMG recognizes pressure units of 'atm', 'Pa', 'bar' or 'torr', but not " + unitPress + ". GUI does not contain all information present in condition.txt file.");
}
String presses = st.nextToken();
while (st.hasMoreTokens()) {
presses += " " + st.nextToken();
}
pressConstant.setText(presses);
}
// GUI only recognized Ideal Gas EOS (30Jul2009)
// else if (line.startsWith("EquationOfState")) {
// // Equation of state (if present)
// st = new StringTokenizer(line);
// tempString = st.nextToken(); // Skip over "EquationOfState"
// tempString = st.nextToken();
// if (tempString.equals("Liquid")) {
// eosCombo.setSelectedItem(tempString);
// } else {
// System.out.println("ERROR: Reading in condition.txt file - Invalid equation of state. RMG recognizes 'Liquid', but not " + tempString + ". GUI does not contain all information present in condition.txt file.");
// }
// }
else if (line.startsWith("MaxCarbonNumber")) {
st = new StringTokenizer(line);
tempString = st.nextToken(); // Skip over "MaxCarbonNumberPerSpecies"\
maxCarbonNum.setText(st.nextToken());
}
else if (line.startsWith("MaxOxygenNumber")) {
st = new StringTokenizer(line);
tempString = st.nextToken(); // Skip over "MaxOxygenNumberPerSpecies"\
maxOxygenNum.setText(st.nextToken());
}
else if (line.startsWith("MaxRadicalNumber")) {
st = new StringTokenizer(line);
tempString = st.nextToken(); // Skip over "MaxRadicalNumberPerSpecies"\
maxRadicalNum.setText(st.nextToken());
}
else if (line.startsWith("InChIGeneration")) {
// InChI generation
st = new StringTokenizer(line);
tempString = st.nextToken(); // Skip over "InChIGeneration:"
String inchi = st.nextToken();
if (inchi.toLowerCase().equals("on")) {
inchiCombo.setSelectedItem("Yes");
} else if (inchi.toLowerCase().equals("off")) {
inchiCombo.setSelectedItem("No");
} else {
System.out.println("ERROR: Reading in condition.txt file - Invalid argument for InChIGeneration. RMG recognizes an argument of 'On' or 'Off', but not " + inchi + ". GUI does not contain all information present in condition.txt file.");
}
}
// GUI does not handle Solvation (30Jul2009)
// else if (line.startsWith("Solvation")) {
// // Solvation
// st = new StringTokenizer(line);
// tempString = st.nextToken(); // Skip over "Solvation:"
// String solvation = st.nextToken();
// if (solvation.toLowerCase().equals("on")) {
// solvationCombo.setSelectedItem("Yes");
// } else if (solvation.toLowerCase().equals("off")) {
// solvationCombo.setSelectedItem("No");
// } else {
// System.out.println("ERROR: Reading in condition.txt file - Invalid argument for Solvation. RMG recognizes an argument of 'On' or 'Off', but not " + solvation + ". GUI does not contain all information present in condition.txt file.");
// }
// }
else if (line.startsWith("InitialStatus")) {
String adjList = "";
String name = "";
String conc = "";
String unit = "";
String reactivity = "";
line = ChemParser.readMeaningfulLine(reader);
while (!line.startsWith("END")) {
if (line.startsWith("(")) {
++numSpecies;
st = new StringTokenizer(line);
tempString = st.nextToken(); // Skip over (#)
name = st.nextToken();
conc = st.nextToken();
unit = st.nextToken();
reactivity = "Reactive-RMG";
if (st.hasMoreTokens()) {
reactivity = "Reactive-User";
}
} else {
adjList += line + "\r";
}
line = ChemParser.readMeaningfulLine(reader);
if (line.startsWith("(") || line.startsWith("END")) {
ICVector icEntry = new ICVector(numSpecies-1,name,conc,unit.substring(1,unit.length()-1),reactivity,adjList);
tmodelInput.updateIC(icEntry);
adjList = "";
}
}
limitingReactant();
}
else if (line.startsWith("InertGas")) {
// Inert gases
String name = "";
String conc = "";
String unit = "";
String reactivity = "";
String adjList = "";
line = ChemParser.readMeaningfulLine(reader);
while (!line.startsWith("END")) {
++numSpecies;
st = new StringTokenizer(line);
name = st.nextToken();
conc = st.nextToken();
unit = st.nextToken();
reactivity = "Inert";
if (name.equals("Ar") || name.equals("Ne") || name.equals("N2") || name.equals("He")) {
ICVector icEntry = new ICVector(numSpecies-1,name,conc,unit.substring(1,unit.length()-1),reactivity,adjList);
tmodelInput.updateIC(icEntry);
} else
System.out.println("Warning: Could not read in one of the inert gas species: " + name + ". The Inert Gas options are 'N2', 'Ar', 'He', and 'Ne' (case sensitive)");
line = ChemParser.readMeaningfulLine(reader);
}
}
else if (line.startsWith("Spectroscopic")) {
// Spectroscopic data estimator
st = new StringTokenizer(line);
tempString = st.nextToken(); // Skip over SpectroscopicDataEstimator
String sde = st.nextToken();
if (sde.toLowerCase().equals("frequencygroups")) {
sdeCombo.setSelectedItem("Frequency Groups");
// } else if (sde.toLowerCase().equals("threefrequencymodel")) {
// sdeCombo.setSelectedItem("Three Frequency Model");
} else if (sde.toLowerCase().equals("off")) {
sdeCombo.setSelectedItem("off");
} else {
System.out.println("ERROR: Reading in condition.txt file - Invalid argument for SpectroscopicDataEstimator. RMG recognizes an argument of 'frequencygroups' or 'off' but not " + sde + ". GUI does not contain all information present in condition.txt file.");
}
}
else if (line.startsWith("PressureDep")) {
// Pressure dependence model
st = new StringTokenizer(line);
tempString = st.nextToken(); // Skip over PressureDependence
String pdep = st.nextToken();
if (pdep.toLowerCase().equals("off")) {
pdepCombo.setSelectedItem("off");
} else if (pdep.toLowerCase().equals("reservoirstate")) {
pdepCombo.setSelectedItem("Reservoir State");
} else if (pdep.toLowerCase().equals("modifiedstrongcollision")) {
pdepCombo.setSelectedItem("Modified Strong Collision");
} else {
System.out.println("ERROR: Reading in condition.txt file - Invalid argument for PressureDependence. RMG recognizes an argument of 'reservoirstate', 'modifiedstrongcollision', or 'off' but not " + pdep + ". GUI does not contain all information present in condition.txt file.");
}
}
else if (line.startsWith("PDepKinetics")) {
// Pressure dependent kinetics model
st = new StringTokenizer(line);
tempString = st.nextToken(); // Skip over PDepKineticsModel
String pdkm = st.nextToken();
if (pdkm.toLowerCase().equals("chebyshev")) {
pdkmCombo.setSelectedItem("CHEB");
} else if (pdkm.toLowerCase().equals("pdeparrhenius")) {
pdkmCombo.setSelectedItem("PLOG");
} else if (pdkm.toLowerCase().equals("rate")) {
pdkmCombo.setSelectedItem("Rate");
} else {
System.out.println("ERROR: Reading in condition.txt file - Invalid argument for PDepKineticsModel. RMG recognizes an argument of 'chebyshev' or 'pdeparrhenius' but not " + pdkm + ". GUI does not contain all information present in condition.txt file.");
}
}
else if (line.startsWith("TRange")) {
st = new StringTokenizer(line);
tempString = st.nextToken(); // Skip over TRange
String units = st.nextToken();
String unit = units.substring(1,units.length()-1);
if (unit.equals("K") || unit.equals("F") || unit.equals("C"))
chebyTUnits.setSelectedItem(unit);
else
System.out.println("ERROR: Reading in condition.txt file - Invalid chebyshev temperature unit. RMG recognizes temperature units of 'K', 'C', or 'F', but not " + unit + ". GUI does not contain all information present in condition.txt file.");
chebyTMin.setText(st.nextToken());
chebyTMax.setText(st.nextToken());
chebyTGen.setText(st.nextToken());
chebyTRep.setText(st.nextToken());
}
else if (line.startsWith("PRange")) {
st = new StringTokenizer(line);
tempString = st.nextToken(); // Skip over PRange
String units = st.nextToken();
String unit = units.substring(1,units.length()-1);
if (unit.equals("atm") || unit.equals("Pa") || unit.equals("bar") || unit.equals("torr"))
chebyPUnits.setSelectedItem(unit);
else
System.out.println("ERROR: Reading in condition.txt file - Invalid chebyshev pressure unit. RMG recognizes pressure units of 'atm', 'bar', 'torr', or 'Pa', but not " + unit + ". GUI does not contain all information present in condition.txt file.");
chebyPMin.setText(st.nextToken());
chebyPMax.setText(st.nextToken());
chebyPGen.setText(st.nextToken());
chebyPRep.setText(st.nextToken());
}
else if (line.startsWith("IncludeSpecies")) {
// IncludeSpecies.txt file (if present)
st = new StringTokenizer(line);
tempString = st.nextToken(); // Skip over IncludeSpecies
isPath.setText(st.nextToken());
}
else if (line.startsWith("(1) Goal")) {
// Goal
st = new StringTokenizer(line);
tempString = st.nextToken(); // Skip over "(1)"
tempString = st.nextToken(); // Skip over "Goal"
String goal = st.nextToken();
if (goal.startsWith("Conversion")) {
controllerCombo.setSelectedItem("Conversion");
SpeciesConvName.setSelectedItem(st.nextToken());
conversion.setText(st.nextToken());
} else if (goal.startsWith("Reaction")) {
controllerCombo.setSelectedItem("ReactionTime");
time.setText(st.nextToken());
String units = st.nextToken();
timeCombo.setSelectedItem(units.substring(1,units.length()-1));
} else {
System.out.println("ERROR: Reading in condition.txt file - Invalid argument for Goal. RMG recognizes an argument of 'Conversion' or 'ReactionTime' but not " + goal + ". GUI does not contain all information present in condition.txt file.");
}
}
else if (line.startsWith("(2) Error")) {
// Error tolerance
st = new StringTokenizer(line);
tempString = st.nextToken(); // Skip over "(2)"
tempString = st.nextToken(); // Skip over "Error"
tempString = st.nextToken(); // Skip over "Tolerance:"
eTolerance.setText(st.nextToken());
}
else if (line.startsWith("DynamicSim")) {
// Dynamic simulator
st = new StringTokenizer(line);
tempString = st.nextToken();
String sim = st.nextToken();
if (sim.equals("DASPK") || sim.equals("DASSL")) {
simulatorCombo.setSelectedItem(sim);
} else {
System.out.println("ERROR: Reading in condition.txt file - Invalid argument for DynamicSimulator. RMG recognizes an argument of 'DASPK' or 'DASSL' but not " + sim + ". GUI does not contain all information present in condition.txt file.");
}
}
else if (line.startsWith("Conversions")) {
// Intermediate integration step
st = new StringTokenizer(line);
String stepName = st.nextToken(); // Skip over Conversions
String steps = st.nextToken();
while (st.hasMoreTokens()) {
steps += " " + st.nextToken();
}
multiConv.setText(steps);
}
else if (line.startsWith("TimeStep")) {
// Intermediate integration step
st = new StringTokenizer(line);
String stepName = st.nextToken(); // Skip over TimeStep
String steps = st.nextToken();
while (st.hasMoreTokens()) {
steps += " " + st.nextToken();
}
multiTS.setText(steps);
}
else if (line.startsWith("Atol")) {
// Absolute tolerance
st = new StringTokenizer(line);
tempString = st.nextToken(); // Skip over Atol
aTolerance.setText(st.nextToken());
}
else if (line.startsWith("Rtol")) {
// Relative tolerance
st = new StringTokenizer(line);
tempString = st.nextToken(); // Skip over Rtol
rTolerance.setText(st.nextToken());
}
else if (line.startsWith("Error bars")) {
// Error bars and Sensitivity analysis (if present)
st = new StringTokenizer(line);
tempString = st.nextToken(); // Skip over "Error"
tempString = st.nextToken(); // Skip over "bars:"
String onoff = st.nextToken();
if (onoff.equals("on")) {
eBarsCombo.setSelectedItem("Yes");
} else if (onoff.equals("off")) {
eBarsCombo.setSelectedItem("No");
} else {
System.out.println("ERROR: Reading in condition.txt file - Invalid argument for Error bars. RMG recognizes an argument of 'Off' or 'On' but not " + onoff + ". GUI does not contain all information present in condition.txt file.");
}
}
else if (line.startsWith("Display sensitivity coefficients")) {
st = new StringTokenizer(line);
tempString = st.nextToken(); // Skip over "Display"
tempString = st.nextToken(); // Skip over "sensitivity"
tempString = st.nextToken(); // Skip over "coefficients:"
String onoff = st.nextToken();
if (onoff.equals("on")) {
sensCoeffCombo.setSelectedItem("Yes");
} else if (onoff.equals("off")) {
sensCoeffCombo.setSelectedItem("No");
} else {
System.out.println("ERROR: Reading in condition.txt file - Invalid argument for Display sensitivity coefficients. RMG recognizes an argument of 'Off' or 'On' but not " + onoff + ". GUI does not contain all information present in condition.txt file.");
}
}
else if (line.startsWith("Display sensitivity information")) {
// Sensitivity coefficients (if present)
line = ChemParser.readMeaningfulLine(reader);
numSpecies = 0;
while (!line.startsWith("END")) {
++numSpecies;
SensVector sensEntry = new SensVector(numSpecies-1,line);
tmodelSens.updateSens(sensEntry);
line = ChemParser.readMeaningfulLine(reader);
}
}
else if (line.startsWith("PrimaryReactionLibrary")) {
// Name(s)/Path(s) of PrimaryReactionLibrary
line = ChemParser.readMeaningfulLine(reader);
int prlCounter = 0;
while (!line.equals("END")) {
++prlCounter;
tempStringVector = line.split("Name: ");
String name = tempStringVector[tempStringVector.length-1].trim();
line = ChemParser.readMeaningfulLine(reader);
tempStringVector = line.split("Location: ");
String path = tempStringVector[tempStringVector.length-1].trim();
PRLVector prlEntry = new PRLVector(prlCounter-1,name,path);
tmodelPRL.updatePRL(prlEntry);
line = ChemParser.readMeaningfulLine(reader);
}
}
else if (line.startsWith("SeedMechanism")) {
// Name(s)/Path(s) of SeedMechanism
line = ChemParser.readMeaningfulLine(reader);
int smCounter = 0;
while (!line.equals("END")) {
++smCounter;
tempStringVector = line.split("Name: ");
String name = tempStringVector[tempStringVector.length-1].trim();
line = ChemParser.readMeaningfulLine(reader);
tempStringVector = line.split("Location: ");
String path = tempStringVector[tempStringVector.length-1].trim();
PRLVector smEntry = new PRLVector(smCounter-1,name,path);
tmodelSM.updatePRL(smEntry);
line = ChemParser.readMeaningfulLine(reader);
}
}
else if (line.startsWith("Verbose")) {
st = new StringTokenizer(line);
tempString = st.nextToken(); // Skip over Verbose
String onoff = st.nextToken();
if (onoff.equals("on")) {
chemkinVerbosity.setSelectedItem("Yes");
} else if (onoff.equals("off")) {
chemkinVerbosity.setSelectedItem("No");
} else {
System.out.println("ERROR: Reading in condition.txt file - Invalid argument for Chemkin Verbosity. RMG recognizes an argument of 'Off' or 'On' but not " + onoff + ". GUI does not contain all information present in condition.txt file.");
}
}
else if (line.startsWith("A:")) {
st = new StringTokenizer(line);
tempString = st.nextToken(); // Skip over A
String units = st.nextToken();
if (units.equals("moles") || units.equals("molecules"))
chemkinAUnits.setSelectedItem(units);
else
System.out.println("ERROR: Reading in condition.txt file - Invalid argument for Chemkin A units. RMG recognizes an argument of 'moles' or 'molecules' but not " + units + ". GUI does not contain all information present in condition.txt file.");
}
else if (line.startsWith("Ea:")) {
st = new StringTokenizer(line);
tempString = st.nextToken(); // Skip over Ea
String units = st.nextToken();
if (units.equals("cal/mol") || units.equals("kcal/mol") || units.equals("kJ/mol") ||
units.equals("J/mol") || units.equals("Kelvins"))
chemkinEaUnits.setSelectedItem(units);
else
System.out.println("ERROR: Reading in condition.txt file - Invalid argument for Chemkin Ea units. RMG recognizes an argument of 'kcal/mol', 'cal/mol', 'kJ/mol', 'J/mol', or 'Kelvins' but not " + units + ". GUI does not contain all information present in condition.txt file.");
}
else
if (!line.startsWith("FinishController") & !line.startsWith("ChemkinUnits"))
System.out.println("Warning: Reading in condition.txt file - Interpreter does not recognize the following line: " + line);
line = ChemParser.readMeaningfulLine(reader);
}
}
|
diff --git a/freeplane/src/org/freeplane/features/common/attribute/AttributeBuilder.java b/freeplane/src/org/freeplane/features/common/attribute/AttributeBuilder.java
index a568496c3..e26cb03f1 100644
--- a/freeplane/src/org/freeplane/features/common/attribute/AttributeBuilder.java
+++ b/freeplane/src/org/freeplane/features/common/attribute/AttributeBuilder.java
@@ -1,230 +1,233 @@
/*
* Freeplane - mind map editor
* Copyright (C) 2008 Dimitry Polivaev
*
* This file author is Dimitry Polivaev
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.freeplane.features.common.attribute;
import java.io.IOException;
import org.freeplane.core.extension.IExtension;
import org.freeplane.core.io.IAttributeHandler;
import org.freeplane.core.io.IElementDOMHandler;
import org.freeplane.core.io.IElementHandler;
import org.freeplane.core.io.IExtensionElementWriter;
import org.freeplane.core.io.ITreeWriter;
import org.freeplane.core.io.ReadManager;
import org.freeplane.core.io.WriteManager;
import org.freeplane.features.common.map.MapModel;
import org.freeplane.features.common.map.MapReader;
import org.freeplane.features.common.map.NodeModel;
import org.freeplane.n3.nanoxml.XMLElement;
class AttributeBuilder implements IElementDOMHandler {
static class AttributeProperties {
String attributeName;
String attributeValue;
}
static class RegisteredAttributeProperties {
String attributeName;
boolean manual = false;
boolean restricted = false;
boolean visible = false;
}
public static final String XML_NODE_ATTRIBUTE = "attribute";
public static final String XML_NODE_ATTRIBUTE_LAYOUT = "attribute_layout";
public static final String XML_NODE_ATTRIBUTE_REGISTRY = "attribute_registry";
public static final String XML_NODE_REGISTERED_ATTRIBUTE_NAME = "attribute_name";
public static final String XML_NODE_REGISTERED_ATTRIBUTE_VALUE = "attribute_value";
final private AttributeController attributeController;
// // final private Controller controller;
final private MapReader mapReader;
public AttributeBuilder(final AttributeController attributeController, final MapReader mapReader) {
this.attributeController = attributeController;
this.mapReader = mapReader;
}
public Object createElement(final Object parent, final String tag, final XMLElement attributes) {
if (tag.equals(AttributeBuilder.XML_NODE_ATTRIBUTE)) {
return new AttributeProperties();
}
if (tag.equals(AttributeBuilder.XML_NODE_REGISTERED_ATTRIBUTE_NAME)) {
return new RegisteredAttributeProperties();
}
if (tag.equals(AttributeBuilder.XML_NODE_REGISTERED_ATTRIBUTE_VALUE)
|| tag.equals(AttributeBuilder.XML_NODE_ATTRIBUTE_REGISTRY)) {
return parent;
}
return null;
}
public void endElement(final Object parent, final String tag, final Object userObject, final XMLElement dom) {
/* attributes */
if (tag.equals(AttributeBuilder.XML_NODE_REGISTERED_ATTRIBUTE_NAME)) {
final RegisteredAttributeProperties rap = (RegisteredAttributeProperties) userObject;
if (rap.visible) {
AttributeRegistry.getRegistry(getMap()).getElement(rap.attributeName).setVisibility(true);
}
if (rap.restricted) {
AttributeRegistry.getRegistry(getMap()).getElement(rap.attributeName).setRestriction(true);
}
if (rap.manual) {
AttributeRegistry.getRegistry(getMap()).getElement(rap.attributeName).setManual(true);
}
return;
}
if (parent instanceof NodeModel) {
final NodeModel node = (NodeModel) parent;
if (tag.equals(AttributeBuilder.XML_NODE_ATTRIBUTE)) {
final AttributeProperties ap = (AttributeProperties) userObject;
final Attribute attribute = new Attribute(ap.attributeName, ap.attributeValue);
attributeController.createAttributeTableModel(node);
final NodeAttributeTableModel model = NodeAttributeTableModel.getModel(node);
model.addRowNoUndo(attribute);
attributeController.setStateIcon(model);
return;
}
return;
}
}
private MapModel getMap() {
return mapReader.getCurrentNodeTreeCreator().getCreatedMap();
}
private void registerAttributeHandlers(final ReadManager reader) {
reader.addAttributeHandler(AttributeBuilder.XML_NODE_REGISTERED_ATTRIBUTE_NAME, "NAME",
new IAttributeHandler() {
public void setAttribute(final Object userObject, final String value) {
final RegisteredAttributeProperties rap = (RegisteredAttributeProperties) userObject;
rap.attributeName = value;
AttributeRegistry.getRegistry(getMap()).registry(value);
}
});
reader.addAttributeHandler(AttributeBuilder.XML_NODE_REGISTERED_ATTRIBUTE_NAME, "VISIBLE",
new IAttributeHandler() {
public void setAttribute(final Object userObject, final String value) {
final RegisteredAttributeProperties rap = (RegisteredAttributeProperties) userObject;
rap.visible = true;
}
});
reader.addAttributeHandler(AttributeBuilder.XML_NODE_REGISTERED_ATTRIBUTE_NAME, "RESTRICTED",
new IAttributeHandler() {
public void setAttribute(final Object userObject, final String value) {
final RegisteredAttributeProperties rap = (RegisteredAttributeProperties) userObject;
rap.restricted = true;
}
});
reader.addAttributeHandler(AttributeBuilder.XML_NODE_REGISTERED_ATTRIBUTE_NAME, "MANUAL",
new IAttributeHandler() {
public void setAttribute(final Object userObject, final String value) {
final RegisteredAttributeProperties rap = (RegisteredAttributeProperties) userObject;
rap.manual = true;
}
});
reader.addAttributeHandler(AttributeBuilder.XML_NODE_REGISTERED_ATTRIBUTE_VALUE, "VALUE",
new IAttributeHandler() {
public void setAttribute(final Object userObject, final String value) {
final RegisteredAttributeProperties rap = (RegisteredAttributeProperties) userObject;
final Attribute attribute = new Attribute(rap.attributeName, value);
final AttributeRegistry r = AttributeRegistry.getRegistry(getMap());
r.registry(attribute);
}
});
reader.addElementHandler(XML_NODE_ATTRIBUTE_LAYOUT, new IElementHandler() {
public Object createElement(final Object parent, final String tag, final XMLElement attributes) {
return parent;
}
});
reader.addAttributeHandler(AttributeBuilder.XML_NODE_ATTRIBUTE_LAYOUT, "NAME_WIDTH", new IAttributeHandler() {
public void setAttribute(final Object userObject, final String value) {
final NodeModel node = (NodeModel) userObject;
attributeController.createAttributeTableModel(node);
final AttributeTableLayoutModel layout = NodeAttributeTableModel.getModel(node).getLayout();
layout.setColumnWidth(0, Integer.parseInt(value));;
}
});
reader.addAttributeHandler(AttributeBuilder.XML_NODE_ATTRIBUTE_LAYOUT, "VALUE_WIDTH", new IAttributeHandler() {
public void setAttribute(final Object userObject, final String value) {
final NodeModel node = (NodeModel) userObject;
attributeController.createAttributeTableModel(node);
final AttributeTableLayoutModel layout = NodeAttributeTableModel.getModel(node).getLayout();
layout.setColumnWidth(1, Integer.parseInt(value));;
}
});
reader.addAttributeHandler(AttributeBuilder.XML_NODE_ATTRIBUTE, "NAME", new IAttributeHandler() {
public void setAttribute(final Object userObject, final String value) {
final AttributeProperties ap = (AttributeProperties) userObject;
ap.attributeName = value.toString();
}
});
reader.addAttributeHandler(AttributeBuilder.XML_NODE_ATTRIBUTE, "VALUE", new IAttributeHandler() {
public void setAttribute(final Object userObject, final String value) {
final AttributeProperties ap = (AttributeProperties) userObject;
ap.attributeValue = value.toString();
}
});
reader.addAttributeHandler(AttributeBuilder.XML_NODE_ATTRIBUTE_REGISTRY, "RESTRICTED", new IAttributeHandler() {
public void setAttribute(final Object userObject, final String value) {
AttributeRegistry.getRegistry(getMap()).setRestricted(true);
}
});
reader.addAttributeHandler(AttributeBuilder.XML_NODE_ATTRIBUTE_REGISTRY, "SHOW_ATTRIBUTES",
new IAttributeHandler() {
public void setAttribute(final Object userObject, final String value) {
+ ModelessAttributeController.getController().setAttributeViewType(getMap(),
+ value.toString());
final AttributeRegistry attributes = AttributeRegistry.getRegistry(getMap());
- attributes.setAttributeViewType(value);
+ if(attributes != null)
+ attributes.setAttributeViewType(value);
}
});
reader.addAttributeHandler(AttributeBuilder.XML_NODE_ATTRIBUTE_REGISTRY, "FONT_SIZE", new IAttributeHandler() {
public void setAttribute(final Object userObject, final String value) {
final int size = Integer.parseInt(value.toString());
AttributeRegistry.getRegistry(getMap()).setFontSize(size);
}
});
}
/**
*/
public void registerBy(final ReadManager reader, final WriteManager writer) {
reader.addElementHandler("attribute_registry", this);
reader.addElementHandler(AttributeBuilder.XML_NODE_ATTRIBUTE, this);
reader.addElementHandler(AttributeBuilder.XML_NODE_REGISTERED_ATTRIBUTE_NAME, this);
reader.addElementHandler(AttributeBuilder.XML_NODE_REGISTERED_ATTRIBUTE_VALUE, this);
writer.addExtensionElementWriter(NodeAttributeTableModel.class, new IExtensionElementWriter() {
public void writeContent(final ITreeWriter writer, final Object node, final IExtension extension)
throws IOException {
final NodeAttributeTableModel attributes = (NodeAttributeTableModel) extension;
attributes.save(writer);
}
});
writer.addExtensionElementWriter(AttributeRegistry.class, new IExtensionElementWriter() {
public void writeContent(final ITreeWriter writer, final Object node, final IExtension extension)
throws IOException {
final AttributeRegistry attributes = (AttributeRegistry) extension;
attributes.write(writer);
}
});
registerAttributeHandlers(reader);
}
public void setAttributes(final String tag, final Object node, final XMLElement attributes) {
}
}
| false | true | private void registerAttributeHandlers(final ReadManager reader) {
reader.addAttributeHandler(AttributeBuilder.XML_NODE_REGISTERED_ATTRIBUTE_NAME, "NAME",
new IAttributeHandler() {
public void setAttribute(final Object userObject, final String value) {
final RegisteredAttributeProperties rap = (RegisteredAttributeProperties) userObject;
rap.attributeName = value;
AttributeRegistry.getRegistry(getMap()).registry(value);
}
});
reader.addAttributeHandler(AttributeBuilder.XML_NODE_REGISTERED_ATTRIBUTE_NAME, "VISIBLE",
new IAttributeHandler() {
public void setAttribute(final Object userObject, final String value) {
final RegisteredAttributeProperties rap = (RegisteredAttributeProperties) userObject;
rap.visible = true;
}
});
reader.addAttributeHandler(AttributeBuilder.XML_NODE_REGISTERED_ATTRIBUTE_NAME, "RESTRICTED",
new IAttributeHandler() {
public void setAttribute(final Object userObject, final String value) {
final RegisteredAttributeProperties rap = (RegisteredAttributeProperties) userObject;
rap.restricted = true;
}
});
reader.addAttributeHandler(AttributeBuilder.XML_NODE_REGISTERED_ATTRIBUTE_NAME, "MANUAL",
new IAttributeHandler() {
public void setAttribute(final Object userObject, final String value) {
final RegisteredAttributeProperties rap = (RegisteredAttributeProperties) userObject;
rap.manual = true;
}
});
reader.addAttributeHandler(AttributeBuilder.XML_NODE_REGISTERED_ATTRIBUTE_VALUE, "VALUE",
new IAttributeHandler() {
public void setAttribute(final Object userObject, final String value) {
final RegisteredAttributeProperties rap = (RegisteredAttributeProperties) userObject;
final Attribute attribute = new Attribute(rap.attributeName, value);
final AttributeRegistry r = AttributeRegistry.getRegistry(getMap());
r.registry(attribute);
}
});
reader.addElementHandler(XML_NODE_ATTRIBUTE_LAYOUT, new IElementHandler() {
public Object createElement(final Object parent, final String tag, final XMLElement attributes) {
return parent;
}
});
reader.addAttributeHandler(AttributeBuilder.XML_NODE_ATTRIBUTE_LAYOUT, "NAME_WIDTH", new IAttributeHandler() {
public void setAttribute(final Object userObject, final String value) {
final NodeModel node = (NodeModel) userObject;
attributeController.createAttributeTableModel(node);
final AttributeTableLayoutModel layout = NodeAttributeTableModel.getModel(node).getLayout();
layout.setColumnWidth(0, Integer.parseInt(value));;
}
});
reader.addAttributeHandler(AttributeBuilder.XML_NODE_ATTRIBUTE_LAYOUT, "VALUE_WIDTH", new IAttributeHandler() {
public void setAttribute(final Object userObject, final String value) {
final NodeModel node = (NodeModel) userObject;
attributeController.createAttributeTableModel(node);
final AttributeTableLayoutModel layout = NodeAttributeTableModel.getModel(node).getLayout();
layout.setColumnWidth(1, Integer.parseInt(value));;
}
});
reader.addAttributeHandler(AttributeBuilder.XML_NODE_ATTRIBUTE, "NAME", new IAttributeHandler() {
public void setAttribute(final Object userObject, final String value) {
final AttributeProperties ap = (AttributeProperties) userObject;
ap.attributeName = value.toString();
}
});
reader.addAttributeHandler(AttributeBuilder.XML_NODE_ATTRIBUTE, "VALUE", new IAttributeHandler() {
public void setAttribute(final Object userObject, final String value) {
final AttributeProperties ap = (AttributeProperties) userObject;
ap.attributeValue = value.toString();
}
});
reader.addAttributeHandler(AttributeBuilder.XML_NODE_ATTRIBUTE_REGISTRY, "RESTRICTED", new IAttributeHandler() {
public void setAttribute(final Object userObject, final String value) {
AttributeRegistry.getRegistry(getMap()).setRestricted(true);
}
});
reader.addAttributeHandler(AttributeBuilder.XML_NODE_ATTRIBUTE_REGISTRY, "SHOW_ATTRIBUTES",
new IAttributeHandler() {
public void setAttribute(final Object userObject, final String value) {
final AttributeRegistry attributes = AttributeRegistry.getRegistry(getMap());
attributes.setAttributeViewType(value);
}
});
reader.addAttributeHandler(AttributeBuilder.XML_NODE_ATTRIBUTE_REGISTRY, "FONT_SIZE", new IAttributeHandler() {
public void setAttribute(final Object userObject, final String value) {
final int size = Integer.parseInt(value.toString());
AttributeRegistry.getRegistry(getMap()).setFontSize(size);
}
});
}
| private void registerAttributeHandlers(final ReadManager reader) {
reader.addAttributeHandler(AttributeBuilder.XML_NODE_REGISTERED_ATTRIBUTE_NAME, "NAME",
new IAttributeHandler() {
public void setAttribute(final Object userObject, final String value) {
final RegisteredAttributeProperties rap = (RegisteredAttributeProperties) userObject;
rap.attributeName = value;
AttributeRegistry.getRegistry(getMap()).registry(value);
}
});
reader.addAttributeHandler(AttributeBuilder.XML_NODE_REGISTERED_ATTRIBUTE_NAME, "VISIBLE",
new IAttributeHandler() {
public void setAttribute(final Object userObject, final String value) {
final RegisteredAttributeProperties rap = (RegisteredAttributeProperties) userObject;
rap.visible = true;
}
});
reader.addAttributeHandler(AttributeBuilder.XML_NODE_REGISTERED_ATTRIBUTE_NAME, "RESTRICTED",
new IAttributeHandler() {
public void setAttribute(final Object userObject, final String value) {
final RegisteredAttributeProperties rap = (RegisteredAttributeProperties) userObject;
rap.restricted = true;
}
});
reader.addAttributeHandler(AttributeBuilder.XML_NODE_REGISTERED_ATTRIBUTE_NAME, "MANUAL",
new IAttributeHandler() {
public void setAttribute(final Object userObject, final String value) {
final RegisteredAttributeProperties rap = (RegisteredAttributeProperties) userObject;
rap.manual = true;
}
});
reader.addAttributeHandler(AttributeBuilder.XML_NODE_REGISTERED_ATTRIBUTE_VALUE, "VALUE",
new IAttributeHandler() {
public void setAttribute(final Object userObject, final String value) {
final RegisteredAttributeProperties rap = (RegisteredAttributeProperties) userObject;
final Attribute attribute = new Attribute(rap.attributeName, value);
final AttributeRegistry r = AttributeRegistry.getRegistry(getMap());
r.registry(attribute);
}
});
reader.addElementHandler(XML_NODE_ATTRIBUTE_LAYOUT, new IElementHandler() {
public Object createElement(final Object parent, final String tag, final XMLElement attributes) {
return parent;
}
});
reader.addAttributeHandler(AttributeBuilder.XML_NODE_ATTRIBUTE_LAYOUT, "NAME_WIDTH", new IAttributeHandler() {
public void setAttribute(final Object userObject, final String value) {
final NodeModel node = (NodeModel) userObject;
attributeController.createAttributeTableModel(node);
final AttributeTableLayoutModel layout = NodeAttributeTableModel.getModel(node).getLayout();
layout.setColumnWidth(0, Integer.parseInt(value));;
}
});
reader.addAttributeHandler(AttributeBuilder.XML_NODE_ATTRIBUTE_LAYOUT, "VALUE_WIDTH", new IAttributeHandler() {
public void setAttribute(final Object userObject, final String value) {
final NodeModel node = (NodeModel) userObject;
attributeController.createAttributeTableModel(node);
final AttributeTableLayoutModel layout = NodeAttributeTableModel.getModel(node).getLayout();
layout.setColumnWidth(1, Integer.parseInt(value));;
}
});
reader.addAttributeHandler(AttributeBuilder.XML_NODE_ATTRIBUTE, "NAME", new IAttributeHandler() {
public void setAttribute(final Object userObject, final String value) {
final AttributeProperties ap = (AttributeProperties) userObject;
ap.attributeName = value.toString();
}
});
reader.addAttributeHandler(AttributeBuilder.XML_NODE_ATTRIBUTE, "VALUE", new IAttributeHandler() {
public void setAttribute(final Object userObject, final String value) {
final AttributeProperties ap = (AttributeProperties) userObject;
ap.attributeValue = value.toString();
}
});
reader.addAttributeHandler(AttributeBuilder.XML_NODE_ATTRIBUTE_REGISTRY, "RESTRICTED", new IAttributeHandler() {
public void setAttribute(final Object userObject, final String value) {
AttributeRegistry.getRegistry(getMap()).setRestricted(true);
}
});
reader.addAttributeHandler(AttributeBuilder.XML_NODE_ATTRIBUTE_REGISTRY, "SHOW_ATTRIBUTES",
new IAttributeHandler() {
public void setAttribute(final Object userObject, final String value) {
ModelessAttributeController.getController().setAttributeViewType(getMap(),
value.toString());
final AttributeRegistry attributes = AttributeRegistry.getRegistry(getMap());
if(attributes != null)
attributes.setAttributeViewType(value);
}
});
reader.addAttributeHandler(AttributeBuilder.XML_NODE_ATTRIBUTE_REGISTRY, "FONT_SIZE", new IAttributeHandler() {
public void setAttribute(final Object userObject, final String value) {
final int size = Integer.parseInt(value.toString());
AttributeRegistry.getRegistry(getMap()).setFontSize(size);
}
});
}
|
diff --git a/fest-swing/src/test/java/org/fest/swing/core/ComponentIsFocusableQuery_isFocusable_Test.java b/fest-swing/src/test/java/org/fest/swing/core/ComponentIsFocusableQuery_isFocusable_Test.java
index ecef9945..f736c9ba 100644
--- a/fest-swing/src/test/java/org/fest/swing/core/ComponentIsFocusableQuery_isFocusable_Test.java
+++ b/fest-swing/src/test/java/org/fest/swing/core/ComponentIsFocusableQuery_isFocusable_Test.java
@@ -1,74 +1,73 @@
/*
* Created on Apr 21, 2010
*
* 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.
*
* Copyright @2010 the original author or authors.
*/
package org.fest.swing.core;
import java.awt.Component;
import java.util.Collection;
import org.junit.*;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import org.fest.mocks.EasyMockTemplate;
import org.fest.swing.test.core.EDTSafeTestCase;
import org.fest.swing.test.data.BooleanProvider;
import static org.easymock.EasyMock.expect;
import static org.easymock.classextension.EasyMock.createMock;
import static org.fest.assertions.Assertions.assertThat;
import static org.fest.util.Collections.list;
/**
* Tests for <code>{@link ComponentIsFocusableQuery#isFocusable(Component)}</code>.
*
* @author Yvonne Wang
*/
@RunWith(Parameterized.class)
public class ComponentIsFocusableQuery_isFocusable_Test extends EDTSafeTestCase {
private final boolean isFocusable;
private Component component;
@Parameters
public static Collection<Object[]> isFocusable() {
return list(BooleanProvider.booleans());
}
public ComponentIsFocusableQuery_isFocusable_Test(boolean isFocusable) {
this.isFocusable = isFocusable;
}
@Before
public void setUp() {
component = createMock(Component.class);
}
@Test
public void should_return_Component_is_focusable() {
new EasyMockTemplate(component) {
protected void expectations() {
expect(component.isFocusable()).andReturn(isFocusable);
}
protected void codeToTest() {
- boolean b = ComponentIsFocusableQuery.isFocusable(component);
- assertThat(b).isEqualTo(isFocusable);
+ assertThat(ComponentIsFocusableQuery.isFocusable(component)).isEqualTo(isFocusable);
}
}.run();
}
}
| true | true | public void should_return_Component_is_focusable() {
new EasyMockTemplate(component) {
protected void expectations() {
expect(component.isFocusable()).andReturn(isFocusable);
}
protected void codeToTest() {
boolean b = ComponentIsFocusableQuery.isFocusable(component);
assertThat(b).isEqualTo(isFocusable);
}
}.run();
}
| public void should_return_Component_is_focusable() {
new EasyMockTemplate(component) {
protected void expectations() {
expect(component.isFocusable()).andReturn(isFocusable);
}
protected void codeToTest() {
assertThat(ComponentIsFocusableQuery.isFocusable(component)).isEqualTo(isFocusable);
}
}.run();
}
|
diff --git a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/util/WTPModulesTranslator.java b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/util/WTPModulesTranslator.java
index 89c03371..4f5f3831 100644
--- a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/util/WTPModulesTranslator.java
+++ b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/util/WTPModulesTranslator.java
@@ -1,120 +1,120 @@
/*******************************************************************************
* Copyright (c) 2005 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.wst.common.componentcore.internal.util;
import org.eclipse.emf.ecore.EStructuralFeature;
import org.eclipse.wst.common.componentcore.internal.ComponentcorePackage;
import org.eclipse.wst.common.internal.emf.resource.GenericTranslator;
import org.eclipse.wst.common.internal.emf.resource.IDTranslator;
import org.eclipse.wst.common.internal.emf.resource.RootTranslator;
import org.eclipse.wst.common.internal.emf.resource.Translator;
public class WTPModulesTranslator extends RootTranslator implements WTPModulesXmlMapperI{
public static WTPModulesTranslator INSTANCE = new WTPModulesTranslator();
private static Translator[] children;
private static final ComponentcorePackage MODULE_CORE_PKG = ComponentcorePackage.eINSTANCE;
/**
* @param domNameAndPath
* @param eClass
*/
public WTPModulesTranslator() {
super(PROJECT_MODULES, ComponentcorePackage.eINSTANCE.getProjectComponents());
}
// public void setMOFValue(Notifier owner, Object value, int newIndex) {
// super.setMOFValue(owner, value, newIndex);
// EObject target = ((EObject)value);
// IProject project = ProjectUtilities.getProject(target);
// if(project != null)
// target.eSet(ComponentcorePackage.eINSTANCE.getProjectComponents_ProjectName(), project.getName());
// }
/* (non-Javadoc)
* @see org.eclipse.wst.common.internal.emf.resource.Translator#getChildren(java.lang.Object, int)
*/
public Translator[] getChildren(Object target, int versionID) {
if(children == null)
children = createWTPModulesTranslator();
return children;
}
private static Translator[] createWTPModulesTranslator() {
return new Translator[] {
IDTranslator.INSTANCE,
createWBModuleTranslator(MODULE_CORE_PKG.getProjectComponents_Components())
};
}
/**
* @return
*/
private static Translator createWBModuleTranslator(EStructuralFeature afeature) {
GenericTranslator result = new GenericTranslator(WORKBENCH_COMPONENT, afeature);
result.setChildren(new Translator[] {
IDTranslator.INSTANCE,
//new Translator(HANDLE, MODULE_CORE_PKG.getWorkbenchComponent_Handle(), DOM_ATTRIBUTE), REMOVED SINCE HANDLE SHOULD NOW BE DERIVED -MDE
new Translator(RUNTIME_NAME, MODULE_CORE_PKG.getWorkbenchComponent_Name(), DOM_ATTRIBUTE),
createModuleTypeTranslator(MODULE_CORE_PKG.getWorkbenchComponent_ComponentType()),
createWBResourceTranslator(MODULE_CORE_PKG.getWorkbenchComponent_Resources()),
createDependentModuleTranslator(MODULE_CORE_PKG.getWorkbenchComponent_ReferencedComponents()),
- new Translator(META_RESOURCES, MODULE_CORE_PKG.getWorkbenchComponent_MetadataResources()),
+ new IPathTranslator(META_RESOURCES, MODULE_CORE_PKG.getWorkbenchComponent_MetadataResources()),
createPropertiesTranslator(MODULE_CORE_PKG.getWorkbenchComponent_Properties())
});
return result;
}
private static Translator createModuleTypeTranslator(EStructuralFeature afeature) {
GenericTranslator result = new GenericTranslator(MODULE_TYPE, afeature);
result.setChildren(new Translator[] {
new Translator(COMPONENT_TYPE_ID, MODULE_CORE_PKG.getComponentType_ComponentTypeId(), DOM_ATTRIBUTE),
new Translator(META_RESOURCES, MODULE_CORE_PKG.getComponentType_MetadataResources()),
new Translator(COMPONENT_TYPE_VERSION, MODULE_CORE_PKG.getComponentType_Version()),
createPropertiesTranslator(MODULE_CORE_PKG.getComponentType_Properties())
});
return result;
}
private static Translator createPropertiesTranslator(EStructuralFeature afeature){
GenericTranslator result = new GenericTranslator(PROPERTY, afeature);
result.setChildren(new Translator[] {
new Translator(PROPERTY_NAME, MODULE_CORE_PKG.getProperty_Name(), DOM_ATTRIBUTE ),
new Translator(PROPERTY_VALUE, MODULE_CORE_PKG.getProperty_Value(), DOM_ATTRIBUTE ),
});
return result;
}
private static Translator createDependentModuleTranslator(EStructuralFeature afeature) {
GenericTranslator result = new GenericTranslator(REFERENCED_COMPONENT, afeature);
result.setChildren(new Translator[] {
new IPathTranslator(RUNTIME_PATH, MODULE_CORE_PKG.getReferencedComponent_RuntimePath(), DOM_ATTRIBUTE),
new URITranslator(HANDLE, MODULE_CORE_PKG.getReferencedComponent_Handle(), DOM_ATTRIBUTE),
new HRefTranslator(DEP_OBJECT,MODULE_CORE_PKG.getReferencedComponent_DependentObject()),
new DependencyTypeTranslator()
});
return result;
}
private static Translator createWBResourceTranslator(EStructuralFeature afeature) {
GenericTranslator result = new GenericTranslator(COMPONENT_RESOURCE, afeature);
result.setChildren(new Translator[] {
IDTranslator.INSTANCE,
new IPathTranslator(SOURCE_PATH, MODULE_CORE_PKG.getComponentResource_SourcePath(), DOM_ATTRIBUTE),
new IPathTranslator(RUNTIME_PATH, MODULE_CORE_PKG.getComponentResource_RuntimePath(), DOM_ATTRIBUTE),
new Translator(RESOURCE_TYPE, MODULE_CORE_PKG.getComponentResource_ResourceType(), DOM_ATTRIBUTE),
new Translator(EXCLUSIONS, MODULE_CORE_PKG.getComponentResource_Exclusions())
});
return result;
}
}
| true | true | private static Translator createWBModuleTranslator(EStructuralFeature afeature) {
GenericTranslator result = new GenericTranslator(WORKBENCH_COMPONENT, afeature);
result.setChildren(new Translator[] {
IDTranslator.INSTANCE,
//new Translator(HANDLE, MODULE_CORE_PKG.getWorkbenchComponent_Handle(), DOM_ATTRIBUTE), REMOVED SINCE HANDLE SHOULD NOW BE DERIVED -MDE
new Translator(RUNTIME_NAME, MODULE_CORE_PKG.getWorkbenchComponent_Name(), DOM_ATTRIBUTE),
createModuleTypeTranslator(MODULE_CORE_PKG.getWorkbenchComponent_ComponentType()),
createWBResourceTranslator(MODULE_CORE_PKG.getWorkbenchComponent_Resources()),
createDependentModuleTranslator(MODULE_CORE_PKG.getWorkbenchComponent_ReferencedComponents()),
new Translator(META_RESOURCES, MODULE_CORE_PKG.getWorkbenchComponent_MetadataResources()),
createPropertiesTranslator(MODULE_CORE_PKG.getWorkbenchComponent_Properties())
});
return result;
}
| private static Translator createWBModuleTranslator(EStructuralFeature afeature) {
GenericTranslator result = new GenericTranslator(WORKBENCH_COMPONENT, afeature);
result.setChildren(new Translator[] {
IDTranslator.INSTANCE,
//new Translator(HANDLE, MODULE_CORE_PKG.getWorkbenchComponent_Handle(), DOM_ATTRIBUTE), REMOVED SINCE HANDLE SHOULD NOW BE DERIVED -MDE
new Translator(RUNTIME_NAME, MODULE_CORE_PKG.getWorkbenchComponent_Name(), DOM_ATTRIBUTE),
createModuleTypeTranslator(MODULE_CORE_PKG.getWorkbenchComponent_ComponentType()),
createWBResourceTranslator(MODULE_CORE_PKG.getWorkbenchComponent_Resources()),
createDependentModuleTranslator(MODULE_CORE_PKG.getWorkbenchComponent_ReferencedComponents()),
new IPathTranslator(META_RESOURCES, MODULE_CORE_PKG.getWorkbenchComponent_MetadataResources()),
createPropertiesTranslator(MODULE_CORE_PKG.getWorkbenchComponent_Properties())
});
return result;
}
|
diff --git a/src/minecraft/net/minecraft/src/GuiIngame.java b/src/minecraft/net/minecraft/src/GuiIngame.java
index a8348c3e..0af2e44b 100644
--- a/src/minecraft/net/minecraft/src/GuiIngame.java
+++ b/src/minecraft/net/minecraft/src/GuiIngame.java
@@ -1,640 +1,640 @@
package net.minecraft.src;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import net.minecraft.client.Minecraft;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL12;
//Spout Start
import org.spoutcraft.client.SpoutClient;
import org.spoutcraft.client.config.ConfigReader;
import org.spoutcraft.client.gui.minimap.ZanMinimap;
import org.spoutcraft.spoutcraftapi.Spoutcraft;
import org.spoutcraft.spoutcraftapi.gui.ChatTextBox;
import org.spoutcraft.spoutcraftapi.gui.Color;
import org.spoutcraft.spoutcraftapi.gui.InGameHUD;
import org.spoutcraft.spoutcraftapi.gui.ServerPlayerList;
//Spout End
import org.spoutcraft.spoutcraftapi.player.ChatMessage;
public class GuiIngame extends Gui
{
private static RenderItem itemRenderer = new RenderItem();
//Spout Start
private final ZanMinimap map = new ZanMinimap();
//Spout End
public static final Random rand = new Random(); //Spout private -> public static final
private Minecraft mc;
private int updateCounter;
/** The string specifying which record music is playing */
private String recordPlaying;
/** How many ticks the record playing message will be displayed */
private int recordPlayingUpFor;
private boolean recordIsPlaying;
/** Damage partial time (GUI) */
public float damageGuiPartialTime;
/** Previous frame vignette brightness (slowly changes by 1% each frame) */
float prevVignetteBrightness;
public GuiIngame(Minecraft par1Minecraft)
{
//rand = new Random(); //Spout removed
updateCounter = 0;
recordPlaying = "";
recordPlayingUpFor = 0;
recordIsPlaying = false;
prevVignetteBrightness = 1.0F;
mc = par1Minecraft;
}
/**
* Render the ingame overlay with quick icon bar, ...
*/
//Spout Start
//TODO Rewrite again, it's in a horrible state, i'm surprised it works...
//Most of function rewritten
public void renderGameOverlay(float f, boolean flag, int i, int j)
{
SpoutClient.getInstance().onTick();
InGameHUD mainScreen = SpoutClient.getInstance().getActivePlayer().getMainScreen();
ScaledResolution scaledRes = new ScaledResolution(this.mc.gameSettings, this.mc.displayWidth, this.mc.displayHeight);
int screenWidth = scaledRes.getScaledWidth();
int screenHeight = scaledRes.getScaledHeight();
FontRenderer font = this.mc.fontRenderer;
this.mc.entityRenderer.setupOverlayRendering();
GL11.glEnable(3042 /*GL_BLEND*/);
if(Minecraft.isFancyGraphicsEnabled()) {
this.renderVignette(this.mc.thePlayer.getBrightness(f), screenWidth, screenHeight);
}
ItemStack helmet = this.mc.thePlayer.inventory.armorItemInSlot(3);
if(this.mc.gameSettings.thirdPersonView == 0 && helmet != null && helmet.itemID == Block.pumpkin.blockID) {
this.renderPumpkinBlur(screenWidth, screenHeight);
}
if(!this.mc.thePlayer.isPotionActive(Potion.confusion)) {
float var10 = this.mc.thePlayer.prevTimeInPortal + (this.mc.thePlayer.timeInPortal - this.mc.thePlayer.prevTimeInPortal) * f;
if(var10 > 0.0F) {
this.renderPortalOverlay(var10, screenWidth, screenHeight);
}
}
GL11.glBlendFunc(770, 771);
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
GL11.glBindTexture(3553 /* GL_TEXTURE_2D */, this.mc.renderEngine.getTexture("/gui/gui.png"));
InventoryPlayer var11 = this.mc.thePlayer.inventory;
this.zLevel = -90.0F;
this.drawTexturedModalRect(screenWidth / 2 - 91, screenHeight - 22, 0, 0, 182, 22);
this.drawTexturedModalRect(screenWidth / 2 - 91 - 1 + var11.currentItem * 20, screenHeight - 22 - 1, 0, 22, 24, 22);
GL11.glBindTexture(3553 /* GL_TEXTURE_2D */, this.mc.renderEngine.getTexture("/gui/icons.png"));
GL11.glEnable(3042 /* GL_BLEND */);
GL11.glBlendFunc(775, 769);
this.drawTexturedModalRect(screenWidth / 2 - 7, screenHeight / 2 - 7, 0, 0, 16, 16);
GL11.glDisable(3042 /* GL_BLEND */);
GuiIngame.rand.setSeed((long) (this.updateCounter * 312871));
int var15;
int var17;
this.renderBossHealth();
//better safe than sorry
SpoutClient.enableSandbox();
//Toggle visibility if needed
if(mainScreen.getHealthBar().isVisible() == mc.playerController.isInCreativeMode()) {
mainScreen.toggleSurvivalHUD(!mc.playerController.isInCreativeMode());
}
// Hunger Bar Begin
mainScreen.getHungerBar().render();
// Hunger Bar End
// Armor Bar Begin
mainScreen.getArmorBar().render();
// Armor Bar End
// Health Bar Begin
mainScreen.getHealthBar().render();
// Health Bar End
// Bubble Bar Begin
mainScreen.getBubbleBar().render();
// Bubble Bar End
// Exp Bar Begin
mainScreen.getExpBar().render();
// Exp Bar End
SpoutClient.disableSandbox();
map.onRenderTick();
GL11.glDisable(3042 /* GL_BLEND */);
GL11.glEnable('\u803a');
GL11.glPushMatrix();
GL11.glRotatef(120.0F, 1.0F, 0.0F, 0.0F);
RenderHelper.enableStandardItemLighting();
GL11.glPopMatrix();
for (var15 = 0; var15 < 9; ++var15) {
int x = screenWidth / 2 - 90 + var15 * 20 + 2;
var17 = screenHeight - 16 - 3;
this.renderInventorySlot(var15, x, var17, f);
}
RenderHelper.disableStandardItemLighting();
GL11.glDisable('\u803a');
if (this.mc.thePlayer.getSleepTimer() > 0) {
GL11.glDisable(2929 /*GL_DEPTH_TEST*/);
GL11.glDisable(3008 /*GL_ALPHA_TEST*/);
var15 = this.mc.thePlayer.getSleepTimer();
float var26 = (float)var15 / 100.0F;
if(var26 > 1.0F) {
var26 = 1.0F - (float)(var15 - 100) / 10.0F;
}
var17 = (int)(220.0F * var26) << 24 | 1052704;
this.drawRect(0, 0, screenWidth, screenHeight, var17);
GL11.glEnable(3008 /*GL_ALPHA_TEST*/);
GL11.glEnable(2929 /*GL_DEPTH_TEST*/);
}
SpoutClient.enableSandbox();
mainScreen.render();
SpoutClient.disableSandbox();
if (this.mc.gameSettings.showDebugInfo) {
this.mc.mcProfiler.startSection("debug");
GL11.glPushMatrix();
font.drawStringWithShadow("Minecraft 1.3.2 (" + this.mc.debug + ")", 2, 2, 16777215);
font.drawStringWithShadow(this.mc.debugInfoRenders(), 2, 12, 16777215);
font.drawStringWithShadow(this.mc.getEntityDebug(), 2, 22, 16777215);
font.drawStringWithShadow(this.mc.debugInfoEntities(), 2, 32, 16777215);
font.drawStringWithShadow(this.mc.getWorldProviderName(), 2, 42, 16777215);
long var41 = Runtime.getRuntime().maxMemory();
long var34 = Runtime.getRuntime().totalMemory();
long var42 = Runtime.getRuntime().freeMemory();
long var43 = var34 - var42;
String var45 = "Used memory: " + var43 * 100L / var41 + "% (" + var43 / 1024L / 1024L + "MB) of " + var41 / 1024L / 1024L + "MB";
this.drawString(font, var45, screenWidth - font.getStringWidth(var45) - 2, 2, 14737632);
var45 = "Allocated memory: " + var34 * 100L / var41 + "% (" + var34 / 1024L / 1024L + "MB)";
this.drawString(font, var45, screenWidth - font.getStringWidth(var45) - 2, 12, 14737632);
- if(!(SpoutClient.getInstance().isCoordsCheat())) {
+ if(SpoutClient.getInstance().isCoordsCheat()) {
this.drawString(font, String.format("x: %.5f", new Object[] {Double.valueOf(this.mc.thePlayer.posX)}), 2, 64, 14737632);
this.drawString(font, String.format("y: %.3f (feet pos, %.3f eyes pos)", new Object[] {Double.valueOf(this.mc.thePlayer.boundingBox.minY), Double.valueOf(this.mc.thePlayer.posY)}), 2, 72, 14737632);
this.drawString(font, String.format("z: %.5f", new Object[] {Double.valueOf(this.mc.thePlayer.posZ)}), 2, 80, 14737632);
this.drawString(font, "f: " + (MathHelper.floor_double((double)(this.mc.thePlayer.rotationYaw * 4.0F / 360.0F) + 0.5D) & 3), 2, 88, 14737632);
}
int var47 = MathHelper.floor_double(this.mc.thePlayer.posX);
int var22 = MathHelper.floor_double(this.mc.thePlayer.posY);
int var233 = MathHelper.floor_double(this.mc.thePlayer.posZ);
if (this.mc.theWorld != null && this.mc.theWorld.blockExists(var47, var22, var233)) {
Chunk var48 = this.mc.theWorld.getChunkFromBlockCoords(var47, var233);
this.drawString(font, "lc: " + (var48.getTopFilledSegment() + 15) + " b: " + var48.getBiomeGenForWorldCoords(var47 & 15, var233 & 15, this.mc.theWorld.getWorldChunkManager()).biomeName + " bl: " + var48.getSavedLightValue(EnumSkyBlock.Block, var47 & 15, var22, var233 & 15) + " sl: " + var48.getSavedLightValue(EnumSkyBlock.Sky, var47 & 15, var22, var233 & 15) + " rl: " + var48.getBlockLightValue(var47 & 15, var22, var233 & 15, 0), 2, 96, 14737632);
}
this.drawString(font, String.format("ws: %.3f, fs: %.3f, g: %b", new Object[] {Float.valueOf(this.mc.thePlayer.capabilities.getWalkSpeed()), Float.valueOf(this.mc.thePlayer.capabilities.getFlySpeed()), Boolean.valueOf(this.mc.thePlayer.onGround)}), 2, 104, 14737632);
GL11.glPopMatrix();
this.mc.mcProfiler.endSection();
}
if(this.recordPlayingUpFor > 0) {
float var24 = (float)this.recordPlayingUpFor - f;
int fontColor = (int)(var24 * 256.0F / 20.0F);
if(fontColor > 255) {
fontColor = 255;
}
if(fontColor > 0) {
GL11.glPushMatrix();
GL11.glTranslatef((float)(screenWidth / 2), (float)(screenHeight - 48), 0.0F);
GL11.glEnable(3042 /*GL_BLEND*/);
GL11.glBlendFunc(770, 771);
var17 = 16777215;
if(this.recordIsPlaying) {
var17 = java.awt.Color.HSBtoRGB(var24 / 50.0F, 0.7F, 0.6F) & 16777215;
}
font.drawString(this.recordPlaying, -font.getStringWidth(this.recordPlaying) / 2, -4, var17 + (fontColor << 24));
GL11.glDisable(3042 /*GL_BLEND*/);
GL11.glPopMatrix();
}
}
SpoutClient.enableSandbox();
//boolean chatOpen = mainScreen.getChatBar().isVisible() && mc.currentScreen instanceof GuiChat;
//int lines = chatOpen ? mainScreen.getChatTextBox().getNumVisibleChatLines() : mainScreen.getChatTextBox().getNumVisibleLines();
// GL11.glEnable(3042 /*GL_BLEND*/);
// GL11.glBlendFunc(770, 771);
// GL11.glDisable(3008 /*GL_ALPHA_TEST*/);
ChatTextBox chatTextWidget = mainScreen.getChatTextBox();
GL11.glPushMatrix();
boolean chatOpen = mainScreen.getChatBar().isVisible() && mc.currentScreen instanceof GuiChat;
if (chatTextWidget.isVisible() || chatOpen) {
chatTextWidget.setChatOpen(chatOpen);
chatTextWidget.render();
}
GL11.glPopMatrix();
// if (chatTextWidget.isVisible()) {
// int viewedLine = 0;
// for (int line = SpoutClient.getInstance().getChatManager().chatScroll; line < Math.min(chatMessageList.size(), (lines + SpoutClient.getInstance().getChatManager().chatScroll)); line++) {
// if (chatOpen || chatMessageList.get(line).updateCounter < chatTextWidget.getFadeoutTicks()) {
// double opacity = 1.0D - chatMessageList.get(line).updateCounter / (double)chatTextWidget.getFadeoutTicks();
// opacity *= 10D;
// if(opacity < 0.0D) {
// opacity = 0.0D;
// }
// if(opacity > 1.0D) {
// opacity = 1.0D;
// }
// opacity *= opacity;
// int color = chatOpen ? 255 : (int)(255D * opacity);
// if (color > 0) {
// int x = 2 + chatTextWidget.getX();
// int y = chatTextWidget.getY() + (-viewedLine * 9);
// String chat = chatMessageList.get(line).message;
// chat = SpoutClient.getInstance().getChatManager().formatChatColors(chat);
//
// boolean mentioned = false;
// if (ConfigReader.highlightMentions) {
// String[] split = chat.toLowerCase().split(":");
// if (split.length == 1) {
// split = chat.toLowerCase().split(">");
// }
// if (split.length > 1) {
// String name = this.mc.thePlayer.username.toLowerCase();
// if (!split[0].contains(name)) {
// for (int part = 1; part < split.length; part++) {
// if (split[part].contains(name)) {
// mentioned = true;
// break;
// }
// }
// }
// }
// }
//
// if (mentioned) {
// drawRect(x, y - 1, x + 320, y + 8, RED);
// }
// else {
// drawRect(x, y - 1, x + 320, y + 8, color / 2 << 24);
// }
// GL11.glEnable(3042 /*GL_BLEND*/);
// font.drawStringWithShadow(chat, x, y, 0xffffff + (color << 24));
// }
// viewedLine++;
// }
// }
// }
SpoutClient.disableSandbox();
ServerPlayerList playerList = mainScreen.getServerPlayerList();
if(this.mc.thePlayer instanceof EntityClientPlayerMP && this.mc.gameSettings.keyBindPlayerList.pressed && playerList.isVisible()) {
NetClientHandler var41 = ((EntityClientPlayerMP)this.mc.thePlayer).sendQueue;
List var44 = var41.playerInfoList;
int var40 = var41.currentServerMaxPlayers;
int var38 = var40;
int var16;
for(var16 = 1; var38 > 20; var38 = (var40 + var16 - 1) / var16) {
++var16;
}
var17 = 300 / var16;
if(var17 > 150) {
var17 = 150;
}
int var18 = (screenWidth - var16 * var17) / 2;
byte var46 = 10;
this.drawRect(var18 - 1, var46 - 1, var18 + var17 * var16, var46 + 9 * var38, Integer.MIN_VALUE);
for(int var20 = 0; var20 < var40; ++var20) {
int var47 = var18 + var20 % var16 * var17;
int var22 = var46 + var20 / var16 * 9;
this.drawRect(var47, var22, var47 + var17 - 1, var22 + 8, 553648127);
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
GL11.glEnable(3008 /*GL_ALPHA_TEST*/);
if(var20 < var44.size()) {
GuiPlayerInfo var50 = (GuiPlayerInfo)var44.get(var20);
font.drawStringWithShadow(var50.name, var47, var22, 16777215);
this.mc.renderEngine.bindTexture(this.mc.renderEngine.getTexture("/gui/icons.png"));
boolean var48 = false;
boolean var53 = false;
byte var49 = 0;
var53 = false;
byte var54;
if(var50.responseTime < 0) {
var54 = 5;
} else if(var50.responseTime < 150) {
var54 = 0;
} else if(var50.responseTime < 300) {
var54 = 1;
} else if(var50.responseTime < 600) {
var54 = 2;
} else if(var50.responseTime < 1000) {
var54 = 3;
} else {
var54 = 4;
}
this.zLevel += 100.0F;
this.drawTexturedModalRect(var47 + var17 - 12, var22, 0 + var49 * 10, 176 + var54 * 8, 10, 8);
this.zLevel -= 100.0F;
}
}
}
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
GL11.glDisable(2896 /*GL_LIGHTING*/);
GL11.glEnable(3008 /*GL_ALPHA_TEST*/);
GL11.glDisable(3042 /*GL_BLEND*/);
}
/**
* Renders dragon's (boss) health on the HUD
*/
private void renderBossHealth()
{
if (RenderDragon.entityDragon == null)
{
return;
}
EntityDragon entitydragon = RenderDragon.entityDragon;
RenderDragon.entityDragon = null;
FontRenderer fontrenderer = mc.fontRenderer;
ScaledResolution scaledresolution = new ScaledResolution(mc.gameSettings, mc.displayWidth, mc.displayHeight);
int i = scaledresolution.getScaledWidth();
char c = '\266';
int j = i / 2 - c / 2;
int k = (int)(((float)entitydragon.getDragonHealth() / (float)entitydragon.getMaxHealth()) * (float)(c + 1));
byte byte0 = 12;
drawTexturedModalRect(j, byte0, 0, 74, c, 5);
drawTexturedModalRect(j, byte0, 0, 74, c, 5);
if (k > 0)
{
drawTexturedModalRect(j, byte0, 0, 79, k, 5);
}
String s = "Boss health";
fontrenderer.drawStringWithShadow(s, i / 2 - fontrenderer.getStringWidth(s) / 2, byte0 - 10, 0xff00ff);
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
GL11.glBindTexture(GL11.GL_TEXTURE_2D, mc.renderEngine.getTexture("/gui/icons.png"));
}
private void renderPumpkinBlur(int par1, int par2)
{
GL11.glDisable(GL11.GL_DEPTH_TEST);
GL11.glDepthMask(false);
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
GL11.glDisable(GL11.GL_ALPHA_TEST);
GL11.glBindTexture(GL11.GL_TEXTURE_2D, mc.renderEngine.getTexture("%blur%/misc/pumpkinblur.png"));
Tessellator tessellator = Tessellator.instance;
tessellator.startDrawingQuads();
tessellator.addVertexWithUV(0.0D, par2, -90D, 0.0D, 1.0D);
tessellator.addVertexWithUV(par1, par2, -90D, 1.0D, 1.0D);
tessellator.addVertexWithUV(par1, 0.0D, -90D, 1.0D, 0.0D);
tessellator.addVertexWithUV(0.0D, 0.0D, -90D, 0.0D, 0.0D);
tessellator.draw();
GL11.glDepthMask(true);
GL11.glEnable(GL11.GL_DEPTH_TEST);
GL11.glEnable(GL11.GL_ALPHA_TEST);
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
}
/**
* Renders the vignette. Args: vignetteBrightness, width, height
*/
private void renderVignette(float par1, int par2, int par3)
{
par1 = 1.0F - par1;
if (par1 < 0.0F)
{
par1 = 0.0F;
}
if (par1 > 1.0F)
{
par1 = 1.0F;
}
prevVignetteBrightness += (double)(par1 - prevVignetteBrightness) * 0.01D;
GL11.glDisable(GL11.GL_DEPTH_TEST);
GL11.glDepthMask(false);
GL11.glBlendFunc(GL11.GL_ZERO, GL11.GL_ONE_MINUS_SRC_COLOR);
GL11.glColor4f(prevVignetteBrightness, prevVignetteBrightness, prevVignetteBrightness, 1.0F);
GL11.glBindTexture(GL11.GL_TEXTURE_2D, mc.renderEngine.getTexture("%blur%/misc/vignette.png"));
Tessellator tessellator = Tessellator.instance;
tessellator.startDrawingQuads();
tessellator.addVertexWithUV(0.0D, par3, -90D, 0.0D, 1.0D);
tessellator.addVertexWithUV(par2, par3, -90D, 1.0D, 1.0D);
tessellator.addVertexWithUV(par2, 0.0D, -90D, 1.0D, 0.0D);
tessellator.addVertexWithUV(0.0D, 0.0D, -90D, 0.0D, 0.0D);
tessellator.draw();
GL11.glDepthMask(true);
GL11.glEnable(GL11.GL_DEPTH_TEST);
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
}
/**
* Renders the portal overlay. Args: portalStrength, width, height
*/
private void renderPortalOverlay(float par1, int par2, int par3)
{
if (par1 < 1.0F)
{
par1 *= par1;
par1 *= par1;
par1 = par1 * 0.8F + 0.2F;
}
GL11.glDisable(GL11.GL_ALPHA_TEST);
GL11.glDisable(GL11.GL_DEPTH_TEST);
GL11.glDepthMask(false);
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
GL11.glColor4f(1.0F, 1.0F, 1.0F, par1);
GL11.glBindTexture(GL11.GL_TEXTURE_2D, mc.renderEngine.getTexture("/terrain.png"));
float f = (float)(Block.portal.blockIndexInTexture % 16) / 16F;
float f1 = (float)(Block.portal.blockIndexInTexture / 16) / 16F;
float f2 = (float)(Block.portal.blockIndexInTexture % 16 + 1) / 16F;
float f3 = (float)(Block.portal.blockIndexInTexture / 16 + 1) / 16F;
Tessellator tessellator = Tessellator.instance;
tessellator.startDrawingQuads();
tessellator.addVertexWithUV(0.0D, par3, -90D, f, f3);
tessellator.addVertexWithUV(par2, par3, -90D, f2, f3);
tessellator.addVertexWithUV(par2, 0.0D, -90D, f2, f1);
tessellator.addVertexWithUV(0.0D, 0.0D, -90D, f, f1);
tessellator.draw();
GL11.glDepthMask(true);
GL11.glEnable(GL11.GL_DEPTH_TEST);
GL11.glEnable(GL11.GL_ALPHA_TEST);
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
}
/**
* Renders the specified item of the inventory slot at the specified location. Args: slot, x, y, partialTick
*/
private void renderInventorySlot(int par1, int par2, int par3, float par4)
{
ItemStack itemstack = mc.thePlayer.inventory.mainInventory[par1];
if (itemstack == null)
{
return;
}
float f = (float)itemstack.animationsToGo - par4;
if (f > 0.0F)
{
GL11.glPushMatrix();
float f1 = 1.0F + f / 5F;
GL11.glTranslatef(par2 + 8, par3 + 12, 0.0F);
GL11.glScalef(1.0F / f1, (f1 + 1.0F) / 2.0F, 1.0F);
GL11.glTranslatef(-(par2 + 8), -(par3 + 12), 0.0F);
}
itemRenderer.renderItemIntoGUI(mc.fontRenderer, mc.renderEngine, itemstack, par2, par3);
if (f > 0.0F)
{
GL11.glPopMatrix();
}
itemRenderer.renderItemOverlayIntoGUI(mc.fontRenderer, mc.renderEngine, itemstack, par2, par3);
}
/**
* The update tick for the ingame UI
*/
public void updateTick()
{
if(Spoutcraft.getActivePlayer() != null) {
Spoutcraft.getActivePlayer().getMainScreen().getChatTextBox().increaseAge();
}
if (recordPlayingUpFor > 0)
{
recordPlayingUpFor--;
}
updateCounter++;
}
/**
* Clear all chat messages.
*/
public void clearChatMessages()
{
ChatTextBox.clearChat();
}
/**
* Adds a chat message to the list of chat messages. Args: msg
*/
public void addChatMessage(String message) {
/* Spout start */
if (!ConfigReader.showJoinMessages && message.toLowerCase().contains("joined the game")) {
return;
}
String mess[] = (mc.fontRenderer.func_50113_d(message, 320)).split("\n");
for(int i=0;i<mess.length;i++)
{
SpoutClient.enableSandbox();
if (Spoutcraft.getActivePlayer() != null) {
ChatTextBox.addChatMessage(ChatMessage.parseMessage(mess[i]));
}
else {
ChatTextBox.addChatMessage(new ChatMessage(mess[i], mess[i]));
}
SpoutClient.disableSandbox();
}
/* Spout end */
}
// public void addChatMessage(String message) {
// /* Spout start */
// if (!ConfigReader.showJoinMessages && message.toLowerCase().contains("joined the game")) {
// return;
// }
// SpoutClient.enableSandbox();
// if (Spoutcraft.getActivePlayer() != null) {
// ChatTextBox.addChatMessage(ChatMessage.parseMessage(message));
// }
// else {
// ChatTextBox.addChatMessage(new ChatMessage(message, message));
// }
// SpoutClient.disableSandbox();
// /* Spout end */
// int i;
// for (; mc.fontRenderer.getStringWidth(message) > 320; message = message.substring(i)) {
// for (i = 1; i < message.length() && mc.fontRenderer.getStringWidth(message.substring(0, i + 1)) <= 320; i++) { }
// addChatMessage(message.substring(0, i));
// }
// }
public void setRecordPlayingMessage(String par1Str)
{
recordPlaying = (new StringBuilder()).append("Now playing: ").append(par1Str).toString();
recordPlayingUpFor = 60;
recordIsPlaying = true;
}
/**
* Adds the string to chat message after translate it with the language file.
*/
public void addChatMessageTranslate(String par1Str, Object ... par2ArrayOfObj)
{
StringTranslate stringtranslate = StringTranslate.getInstance();
String s = stringtranslate.translateKeyFormat(par1Str, par2ArrayOfObj);
addChatMessage(s);
}
public boolean isChatOpen() {
return this.mc.currentScreen instanceof GuiChat;
}
public ChatClickData func_50012_a(int par1, int par2) {
if (!this.isChatOpen()) {
return null;
} else {
ScaledResolution var3 = new ScaledResolution(this.mc.gameSettings, this.mc.displayWidth, this.mc.displayHeight);
int chatScroll = SpoutClient.getInstance().getChatManager().chatScroll;
//don't ask, it's much better than vanilla matching though
par2 = par2 / var3.getScaleFactor() - 33 - ((20 - Math.min(20, chatScroll)) / 2);
par1 = par1 / var3.getScaleFactor() - 3;
if (par1 >= 0 && par2 >= 0) {
int var4 = Math.min(20, ChatTextBox.getNumChatMessages());
if (par1 <= 320 && par2 < this.mc.fontRenderer.FONT_HEIGHT * var4 + var4) {
int var5 = par2 / (this.mc.fontRenderer.FONT_HEIGHT + 1) + chatScroll;
return new ChatClickData(this.mc.fontRenderer, new ChatLine(this.mc.ingameGUI.getUpdateCounter(), ChatTextBox.getChatMessageAt(var5), par2), par1, par2 - (var5 - chatScroll) * this.mc.fontRenderer.FONT_HEIGHT + var5);
} else {
return null;
}
} else {
return null;
}
}
}
public int getUpdateCounter() {
return this.updateCounter++;
}
}
| true | true | public void renderGameOverlay(float f, boolean flag, int i, int j)
{
SpoutClient.getInstance().onTick();
InGameHUD mainScreen = SpoutClient.getInstance().getActivePlayer().getMainScreen();
ScaledResolution scaledRes = new ScaledResolution(this.mc.gameSettings, this.mc.displayWidth, this.mc.displayHeight);
int screenWidth = scaledRes.getScaledWidth();
int screenHeight = scaledRes.getScaledHeight();
FontRenderer font = this.mc.fontRenderer;
this.mc.entityRenderer.setupOverlayRendering();
GL11.glEnable(3042 /*GL_BLEND*/);
if(Minecraft.isFancyGraphicsEnabled()) {
this.renderVignette(this.mc.thePlayer.getBrightness(f), screenWidth, screenHeight);
}
ItemStack helmet = this.mc.thePlayer.inventory.armorItemInSlot(3);
if(this.mc.gameSettings.thirdPersonView == 0 && helmet != null && helmet.itemID == Block.pumpkin.blockID) {
this.renderPumpkinBlur(screenWidth, screenHeight);
}
if(!this.mc.thePlayer.isPotionActive(Potion.confusion)) {
float var10 = this.mc.thePlayer.prevTimeInPortal + (this.mc.thePlayer.timeInPortal - this.mc.thePlayer.prevTimeInPortal) * f;
if(var10 > 0.0F) {
this.renderPortalOverlay(var10, screenWidth, screenHeight);
}
}
GL11.glBlendFunc(770, 771);
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
GL11.glBindTexture(3553 /* GL_TEXTURE_2D */, this.mc.renderEngine.getTexture("/gui/gui.png"));
InventoryPlayer var11 = this.mc.thePlayer.inventory;
this.zLevel = -90.0F;
this.drawTexturedModalRect(screenWidth / 2 - 91, screenHeight - 22, 0, 0, 182, 22);
this.drawTexturedModalRect(screenWidth / 2 - 91 - 1 + var11.currentItem * 20, screenHeight - 22 - 1, 0, 22, 24, 22);
GL11.glBindTexture(3553 /* GL_TEXTURE_2D */, this.mc.renderEngine.getTexture("/gui/icons.png"));
GL11.glEnable(3042 /* GL_BLEND */);
GL11.glBlendFunc(775, 769);
this.drawTexturedModalRect(screenWidth / 2 - 7, screenHeight / 2 - 7, 0, 0, 16, 16);
GL11.glDisable(3042 /* GL_BLEND */);
GuiIngame.rand.setSeed((long) (this.updateCounter * 312871));
int var15;
int var17;
this.renderBossHealth();
//better safe than sorry
SpoutClient.enableSandbox();
//Toggle visibility if needed
if(mainScreen.getHealthBar().isVisible() == mc.playerController.isInCreativeMode()) {
mainScreen.toggleSurvivalHUD(!mc.playerController.isInCreativeMode());
}
// Hunger Bar Begin
mainScreen.getHungerBar().render();
// Hunger Bar End
// Armor Bar Begin
mainScreen.getArmorBar().render();
// Armor Bar End
// Health Bar Begin
mainScreen.getHealthBar().render();
// Health Bar End
// Bubble Bar Begin
mainScreen.getBubbleBar().render();
// Bubble Bar End
// Exp Bar Begin
mainScreen.getExpBar().render();
// Exp Bar End
SpoutClient.disableSandbox();
map.onRenderTick();
GL11.glDisable(3042 /* GL_BLEND */);
GL11.glEnable('\u803a');
GL11.glPushMatrix();
GL11.glRotatef(120.0F, 1.0F, 0.0F, 0.0F);
RenderHelper.enableStandardItemLighting();
GL11.glPopMatrix();
for (var15 = 0; var15 < 9; ++var15) {
int x = screenWidth / 2 - 90 + var15 * 20 + 2;
var17 = screenHeight - 16 - 3;
this.renderInventorySlot(var15, x, var17, f);
}
RenderHelper.disableStandardItemLighting();
GL11.glDisable('\u803a');
if (this.mc.thePlayer.getSleepTimer() > 0) {
GL11.glDisable(2929 /*GL_DEPTH_TEST*/);
GL11.glDisable(3008 /*GL_ALPHA_TEST*/);
var15 = this.mc.thePlayer.getSleepTimer();
float var26 = (float)var15 / 100.0F;
if(var26 > 1.0F) {
var26 = 1.0F - (float)(var15 - 100) / 10.0F;
}
var17 = (int)(220.0F * var26) << 24 | 1052704;
this.drawRect(0, 0, screenWidth, screenHeight, var17);
GL11.glEnable(3008 /*GL_ALPHA_TEST*/);
GL11.glEnable(2929 /*GL_DEPTH_TEST*/);
}
SpoutClient.enableSandbox();
mainScreen.render();
SpoutClient.disableSandbox();
if (this.mc.gameSettings.showDebugInfo) {
this.mc.mcProfiler.startSection("debug");
GL11.glPushMatrix();
font.drawStringWithShadow("Minecraft 1.3.2 (" + this.mc.debug + ")", 2, 2, 16777215);
font.drawStringWithShadow(this.mc.debugInfoRenders(), 2, 12, 16777215);
font.drawStringWithShadow(this.mc.getEntityDebug(), 2, 22, 16777215);
font.drawStringWithShadow(this.mc.debugInfoEntities(), 2, 32, 16777215);
font.drawStringWithShadow(this.mc.getWorldProviderName(), 2, 42, 16777215);
long var41 = Runtime.getRuntime().maxMemory();
long var34 = Runtime.getRuntime().totalMemory();
long var42 = Runtime.getRuntime().freeMemory();
long var43 = var34 - var42;
String var45 = "Used memory: " + var43 * 100L / var41 + "% (" + var43 / 1024L / 1024L + "MB) of " + var41 / 1024L / 1024L + "MB";
this.drawString(font, var45, screenWidth - font.getStringWidth(var45) - 2, 2, 14737632);
var45 = "Allocated memory: " + var34 * 100L / var41 + "% (" + var34 / 1024L / 1024L + "MB)";
this.drawString(font, var45, screenWidth - font.getStringWidth(var45) - 2, 12, 14737632);
if(!(SpoutClient.getInstance().isCoordsCheat())) {
this.drawString(font, String.format("x: %.5f", new Object[] {Double.valueOf(this.mc.thePlayer.posX)}), 2, 64, 14737632);
this.drawString(font, String.format("y: %.3f (feet pos, %.3f eyes pos)", new Object[] {Double.valueOf(this.mc.thePlayer.boundingBox.minY), Double.valueOf(this.mc.thePlayer.posY)}), 2, 72, 14737632);
this.drawString(font, String.format("z: %.5f", new Object[] {Double.valueOf(this.mc.thePlayer.posZ)}), 2, 80, 14737632);
this.drawString(font, "f: " + (MathHelper.floor_double((double)(this.mc.thePlayer.rotationYaw * 4.0F / 360.0F) + 0.5D) & 3), 2, 88, 14737632);
}
int var47 = MathHelper.floor_double(this.mc.thePlayer.posX);
int var22 = MathHelper.floor_double(this.mc.thePlayer.posY);
int var233 = MathHelper.floor_double(this.mc.thePlayer.posZ);
if (this.mc.theWorld != null && this.mc.theWorld.blockExists(var47, var22, var233)) {
Chunk var48 = this.mc.theWorld.getChunkFromBlockCoords(var47, var233);
this.drawString(font, "lc: " + (var48.getTopFilledSegment() + 15) + " b: " + var48.getBiomeGenForWorldCoords(var47 & 15, var233 & 15, this.mc.theWorld.getWorldChunkManager()).biomeName + " bl: " + var48.getSavedLightValue(EnumSkyBlock.Block, var47 & 15, var22, var233 & 15) + " sl: " + var48.getSavedLightValue(EnumSkyBlock.Sky, var47 & 15, var22, var233 & 15) + " rl: " + var48.getBlockLightValue(var47 & 15, var22, var233 & 15, 0), 2, 96, 14737632);
}
this.drawString(font, String.format("ws: %.3f, fs: %.3f, g: %b", new Object[] {Float.valueOf(this.mc.thePlayer.capabilities.getWalkSpeed()), Float.valueOf(this.mc.thePlayer.capabilities.getFlySpeed()), Boolean.valueOf(this.mc.thePlayer.onGround)}), 2, 104, 14737632);
GL11.glPopMatrix();
this.mc.mcProfiler.endSection();
}
if(this.recordPlayingUpFor > 0) {
float var24 = (float)this.recordPlayingUpFor - f;
int fontColor = (int)(var24 * 256.0F / 20.0F);
if(fontColor > 255) {
fontColor = 255;
}
if(fontColor > 0) {
GL11.glPushMatrix();
GL11.glTranslatef((float)(screenWidth / 2), (float)(screenHeight - 48), 0.0F);
GL11.glEnable(3042 /*GL_BLEND*/);
GL11.glBlendFunc(770, 771);
var17 = 16777215;
if(this.recordIsPlaying) {
var17 = java.awt.Color.HSBtoRGB(var24 / 50.0F, 0.7F, 0.6F) & 16777215;
}
font.drawString(this.recordPlaying, -font.getStringWidth(this.recordPlaying) / 2, -4, var17 + (fontColor << 24));
GL11.glDisable(3042 /*GL_BLEND*/);
GL11.glPopMatrix();
}
}
SpoutClient.enableSandbox();
//boolean chatOpen = mainScreen.getChatBar().isVisible() && mc.currentScreen instanceof GuiChat;
//int lines = chatOpen ? mainScreen.getChatTextBox().getNumVisibleChatLines() : mainScreen.getChatTextBox().getNumVisibleLines();
// GL11.glEnable(3042 /*GL_BLEND*/);
// GL11.glBlendFunc(770, 771);
// GL11.glDisable(3008 /*GL_ALPHA_TEST*/);
ChatTextBox chatTextWidget = mainScreen.getChatTextBox();
GL11.glPushMatrix();
boolean chatOpen = mainScreen.getChatBar().isVisible() && mc.currentScreen instanceof GuiChat;
if (chatTextWidget.isVisible() || chatOpen) {
chatTextWidget.setChatOpen(chatOpen);
chatTextWidget.render();
}
GL11.glPopMatrix();
// if (chatTextWidget.isVisible()) {
// int viewedLine = 0;
// for (int line = SpoutClient.getInstance().getChatManager().chatScroll; line < Math.min(chatMessageList.size(), (lines + SpoutClient.getInstance().getChatManager().chatScroll)); line++) {
// if (chatOpen || chatMessageList.get(line).updateCounter < chatTextWidget.getFadeoutTicks()) {
// double opacity = 1.0D - chatMessageList.get(line).updateCounter / (double)chatTextWidget.getFadeoutTicks();
// opacity *= 10D;
// if(opacity < 0.0D) {
// opacity = 0.0D;
// }
// if(opacity > 1.0D) {
// opacity = 1.0D;
// }
// opacity *= opacity;
// int color = chatOpen ? 255 : (int)(255D * opacity);
// if (color > 0) {
// int x = 2 + chatTextWidget.getX();
// int y = chatTextWidget.getY() + (-viewedLine * 9);
// String chat = chatMessageList.get(line).message;
// chat = SpoutClient.getInstance().getChatManager().formatChatColors(chat);
//
// boolean mentioned = false;
// if (ConfigReader.highlightMentions) {
// String[] split = chat.toLowerCase().split(":");
// if (split.length == 1) {
// split = chat.toLowerCase().split(">");
// }
// if (split.length > 1) {
// String name = this.mc.thePlayer.username.toLowerCase();
// if (!split[0].contains(name)) {
// for (int part = 1; part < split.length; part++) {
// if (split[part].contains(name)) {
// mentioned = true;
// break;
// }
// }
// }
// }
// }
//
// if (mentioned) {
// drawRect(x, y - 1, x + 320, y + 8, RED);
// }
// else {
// drawRect(x, y - 1, x + 320, y + 8, color / 2 << 24);
// }
// GL11.glEnable(3042 /*GL_BLEND*/);
// font.drawStringWithShadow(chat, x, y, 0xffffff + (color << 24));
// }
// viewedLine++;
// }
// }
// }
SpoutClient.disableSandbox();
ServerPlayerList playerList = mainScreen.getServerPlayerList();
if(this.mc.thePlayer instanceof EntityClientPlayerMP && this.mc.gameSettings.keyBindPlayerList.pressed && playerList.isVisible()) {
NetClientHandler var41 = ((EntityClientPlayerMP)this.mc.thePlayer).sendQueue;
List var44 = var41.playerInfoList;
int var40 = var41.currentServerMaxPlayers;
int var38 = var40;
int var16;
for(var16 = 1; var38 > 20; var38 = (var40 + var16 - 1) / var16) {
++var16;
}
var17 = 300 / var16;
if(var17 > 150) {
var17 = 150;
}
int var18 = (screenWidth - var16 * var17) / 2;
byte var46 = 10;
this.drawRect(var18 - 1, var46 - 1, var18 + var17 * var16, var46 + 9 * var38, Integer.MIN_VALUE);
for(int var20 = 0; var20 < var40; ++var20) {
int var47 = var18 + var20 % var16 * var17;
int var22 = var46 + var20 / var16 * 9;
this.drawRect(var47, var22, var47 + var17 - 1, var22 + 8, 553648127);
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
GL11.glEnable(3008 /*GL_ALPHA_TEST*/);
if(var20 < var44.size()) {
GuiPlayerInfo var50 = (GuiPlayerInfo)var44.get(var20);
font.drawStringWithShadow(var50.name, var47, var22, 16777215);
this.mc.renderEngine.bindTexture(this.mc.renderEngine.getTexture("/gui/icons.png"));
boolean var48 = false;
boolean var53 = false;
byte var49 = 0;
var53 = false;
byte var54;
if(var50.responseTime < 0) {
var54 = 5;
} else if(var50.responseTime < 150) {
var54 = 0;
} else if(var50.responseTime < 300) {
var54 = 1;
} else if(var50.responseTime < 600) {
var54 = 2;
} else if(var50.responseTime < 1000) {
var54 = 3;
} else {
var54 = 4;
}
this.zLevel += 100.0F;
this.drawTexturedModalRect(var47 + var17 - 12, var22, 0 + var49 * 10, 176 + var54 * 8, 10, 8);
this.zLevel -= 100.0F;
}
}
}
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
GL11.glDisable(2896 /*GL_LIGHTING*/);
GL11.glEnable(3008 /*GL_ALPHA_TEST*/);
GL11.glDisable(3042 /*GL_BLEND*/);
}
| public void renderGameOverlay(float f, boolean flag, int i, int j)
{
SpoutClient.getInstance().onTick();
InGameHUD mainScreen = SpoutClient.getInstance().getActivePlayer().getMainScreen();
ScaledResolution scaledRes = new ScaledResolution(this.mc.gameSettings, this.mc.displayWidth, this.mc.displayHeight);
int screenWidth = scaledRes.getScaledWidth();
int screenHeight = scaledRes.getScaledHeight();
FontRenderer font = this.mc.fontRenderer;
this.mc.entityRenderer.setupOverlayRendering();
GL11.glEnable(3042 /*GL_BLEND*/);
if(Minecraft.isFancyGraphicsEnabled()) {
this.renderVignette(this.mc.thePlayer.getBrightness(f), screenWidth, screenHeight);
}
ItemStack helmet = this.mc.thePlayer.inventory.armorItemInSlot(3);
if(this.mc.gameSettings.thirdPersonView == 0 && helmet != null && helmet.itemID == Block.pumpkin.blockID) {
this.renderPumpkinBlur(screenWidth, screenHeight);
}
if(!this.mc.thePlayer.isPotionActive(Potion.confusion)) {
float var10 = this.mc.thePlayer.prevTimeInPortal + (this.mc.thePlayer.timeInPortal - this.mc.thePlayer.prevTimeInPortal) * f;
if(var10 > 0.0F) {
this.renderPortalOverlay(var10, screenWidth, screenHeight);
}
}
GL11.glBlendFunc(770, 771);
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
GL11.glBindTexture(3553 /* GL_TEXTURE_2D */, this.mc.renderEngine.getTexture("/gui/gui.png"));
InventoryPlayer var11 = this.mc.thePlayer.inventory;
this.zLevel = -90.0F;
this.drawTexturedModalRect(screenWidth / 2 - 91, screenHeight - 22, 0, 0, 182, 22);
this.drawTexturedModalRect(screenWidth / 2 - 91 - 1 + var11.currentItem * 20, screenHeight - 22 - 1, 0, 22, 24, 22);
GL11.glBindTexture(3553 /* GL_TEXTURE_2D */, this.mc.renderEngine.getTexture("/gui/icons.png"));
GL11.glEnable(3042 /* GL_BLEND */);
GL11.glBlendFunc(775, 769);
this.drawTexturedModalRect(screenWidth / 2 - 7, screenHeight / 2 - 7, 0, 0, 16, 16);
GL11.glDisable(3042 /* GL_BLEND */);
GuiIngame.rand.setSeed((long) (this.updateCounter * 312871));
int var15;
int var17;
this.renderBossHealth();
//better safe than sorry
SpoutClient.enableSandbox();
//Toggle visibility if needed
if(mainScreen.getHealthBar().isVisible() == mc.playerController.isInCreativeMode()) {
mainScreen.toggleSurvivalHUD(!mc.playerController.isInCreativeMode());
}
// Hunger Bar Begin
mainScreen.getHungerBar().render();
// Hunger Bar End
// Armor Bar Begin
mainScreen.getArmorBar().render();
// Armor Bar End
// Health Bar Begin
mainScreen.getHealthBar().render();
// Health Bar End
// Bubble Bar Begin
mainScreen.getBubbleBar().render();
// Bubble Bar End
// Exp Bar Begin
mainScreen.getExpBar().render();
// Exp Bar End
SpoutClient.disableSandbox();
map.onRenderTick();
GL11.glDisable(3042 /* GL_BLEND */);
GL11.glEnable('\u803a');
GL11.glPushMatrix();
GL11.glRotatef(120.0F, 1.0F, 0.0F, 0.0F);
RenderHelper.enableStandardItemLighting();
GL11.glPopMatrix();
for (var15 = 0; var15 < 9; ++var15) {
int x = screenWidth / 2 - 90 + var15 * 20 + 2;
var17 = screenHeight - 16 - 3;
this.renderInventorySlot(var15, x, var17, f);
}
RenderHelper.disableStandardItemLighting();
GL11.glDisable('\u803a');
if (this.mc.thePlayer.getSleepTimer() > 0) {
GL11.glDisable(2929 /*GL_DEPTH_TEST*/);
GL11.glDisable(3008 /*GL_ALPHA_TEST*/);
var15 = this.mc.thePlayer.getSleepTimer();
float var26 = (float)var15 / 100.0F;
if(var26 > 1.0F) {
var26 = 1.0F - (float)(var15 - 100) / 10.0F;
}
var17 = (int)(220.0F * var26) << 24 | 1052704;
this.drawRect(0, 0, screenWidth, screenHeight, var17);
GL11.glEnable(3008 /*GL_ALPHA_TEST*/);
GL11.glEnable(2929 /*GL_DEPTH_TEST*/);
}
SpoutClient.enableSandbox();
mainScreen.render();
SpoutClient.disableSandbox();
if (this.mc.gameSettings.showDebugInfo) {
this.mc.mcProfiler.startSection("debug");
GL11.glPushMatrix();
font.drawStringWithShadow("Minecraft 1.3.2 (" + this.mc.debug + ")", 2, 2, 16777215);
font.drawStringWithShadow(this.mc.debugInfoRenders(), 2, 12, 16777215);
font.drawStringWithShadow(this.mc.getEntityDebug(), 2, 22, 16777215);
font.drawStringWithShadow(this.mc.debugInfoEntities(), 2, 32, 16777215);
font.drawStringWithShadow(this.mc.getWorldProviderName(), 2, 42, 16777215);
long var41 = Runtime.getRuntime().maxMemory();
long var34 = Runtime.getRuntime().totalMemory();
long var42 = Runtime.getRuntime().freeMemory();
long var43 = var34 - var42;
String var45 = "Used memory: " + var43 * 100L / var41 + "% (" + var43 / 1024L / 1024L + "MB) of " + var41 / 1024L / 1024L + "MB";
this.drawString(font, var45, screenWidth - font.getStringWidth(var45) - 2, 2, 14737632);
var45 = "Allocated memory: " + var34 * 100L / var41 + "% (" + var34 / 1024L / 1024L + "MB)";
this.drawString(font, var45, screenWidth - font.getStringWidth(var45) - 2, 12, 14737632);
if(SpoutClient.getInstance().isCoordsCheat()) {
this.drawString(font, String.format("x: %.5f", new Object[] {Double.valueOf(this.mc.thePlayer.posX)}), 2, 64, 14737632);
this.drawString(font, String.format("y: %.3f (feet pos, %.3f eyes pos)", new Object[] {Double.valueOf(this.mc.thePlayer.boundingBox.minY), Double.valueOf(this.mc.thePlayer.posY)}), 2, 72, 14737632);
this.drawString(font, String.format("z: %.5f", new Object[] {Double.valueOf(this.mc.thePlayer.posZ)}), 2, 80, 14737632);
this.drawString(font, "f: " + (MathHelper.floor_double((double)(this.mc.thePlayer.rotationYaw * 4.0F / 360.0F) + 0.5D) & 3), 2, 88, 14737632);
}
int var47 = MathHelper.floor_double(this.mc.thePlayer.posX);
int var22 = MathHelper.floor_double(this.mc.thePlayer.posY);
int var233 = MathHelper.floor_double(this.mc.thePlayer.posZ);
if (this.mc.theWorld != null && this.mc.theWorld.blockExists(var47, var22, var233)) {
Chunk var48 = this.mc.theWorld.getChunkFromBlockCoords(var47, var233);
this.drawString(font, "lc: " + (var48.getTopFilledSegment() + 15) + " b: " + var48.getBiomeGenForWorldCoords(var47 & 15, var233 & 15, this.mc.theWorld.getWorldChunkManager()).biomeName + " bl: " + var48.getSavedLightValue(EnumSkyBlock.Block, var47 & 15, var22, var233 & 15) + " sl: " + var48.getSavedLightValue(EnumSkyBlock.Sky, var47 & 15, var22, var233 & 15) + " rl: " + var48.getBlockLightValue(var47 & 15, var22, var233 & 15, 0), 2, 96, 14737632);
}
this.drawString(font, String.format("ws: %.3f, fs: %.3f, g: %b", new Object[] {Float.valueOf(this.mc.thePlayer.capabilities.getWalkSpeed()), Float.valueOf(this.mc.thePlayer.capabilities.getFlySpeed()), Boolean.valueOf(this.mc.thePlayer.onGround)}), 2, 104, 14737632);
GL11.glPopMatrix();
this.mc.mcProfiler.endSection();
}
if(this.recordPlayingUpFor > 0) {
float var24 = (float)this.recordPlayingUpFor - f;
int fontColor = (int)(var24 * 256.0F / 20.0F);
if(fontColor > 255) {
fontColor = 255;
}
if(fontColor > 0) {
GL11.glPushMatrix();
GL11.glTranslatef((float)(screenWidth / 2), (float)(screenHeight - 48), 0.0F);
GL11.glEnable(3042 /*GL_BLEND*/);
GL11.glBlendFunc(770, 771);
var17 = 16777215;
if(this.recordIsPlaying) {
var17 = java.awt.Color.HSBtoRGB(var24 / 50.0F, 0.7F, 0.6F) & 16777215;
}
font.drawString(this.recordPlaying, -font.getStringWidth(this.recordPlaying) / 2, -4, var17 + (fontColor << 24));
GL11.glDisable(3042 /*GL_BLEND*/);
GL11.glPopMatrix();
}
}
SpoutClient.enableSandbox();
//boolean chatOpen = mainScreen.getChatBar().isVisible() && mc.currentScreen instanceof GuiChat;
//int lines = chatOpen ? mainScreen.getChatTextBox().getNumVisibleChatLines() : mainScreen.getChatTextBox().getNumVisibleLines();
// GL11.glEnable(3042 /*GL_BLEND*/);
// GL11.glBlendFunc(770, 771);
// GL11.glDisable(3008 /*GL_ALPHA_TEST*/);
ChatTextBox chatTextWidget = mainScreen.getChatTextBox();
GL11.glPushMatrix();
boolean chatOpen = mainScreen.getChatBar().isVisible() && mc.currentScreen instanceof GuiChat;
if (chatTextWidget.isVisible() || chatOpen) {
chatTextWidget.setChatOpen(chatOpen);
chatTextWidget.render();
}
GL11.glPopMatrix();
// if (chatTextWidget.isVisible()) {
// int viewedLine = 0;
// for (int line = SpoutClient.getInstance().getChatManager().chatScroll; line < Math.min(chatMessageList.size(), (lines + SpoutClient.getInstance().getChatManager().chatScroll)); line++) {
// if (chatOpen || chatMessageList.get(line).updateCounter < chatTextWidget.getFadeoutTicks()) {
// double opacity = 1.0D - chatMessageList.get(line).updateCounter / (double)chatTextWidget.getFadeoutTicks();
// opacity *= 10D;
// if(opacity < 0.0D) {
// opacity = 0.0D;
// }
// if(opacity > 1.0D) {
// opacity = 1.0D;
// }
// opacity *= opacity;
// int color = chatOpen ? 255 : (int)(255D * opacity);
// if (color > 0) {
// int x = 2 + chatTextWidget.getX();
// int y = chatTextWidget.getY() + (-viewedLine * 9);
// String chat = chatMessageList.get(line).message;
// chat = SpoutClient.getInstance().getChatManager().formatChatColors(chat);
//
// boolean mentioned = false;
// if (ConfigReader.highlightMentions) {
// String[] split = chat.toLowerCase().split(":");
// if (split.length == 1) {
// split = chat.toLowerCase().split(">");
// }
// if (split.length > 1) {
// String name = this.mc.thePlayer.username.toLowerCase();
// if (!split[0].contains(name)) {
// for (int part = 1; part < split.length; part++) {
// if (split[part].contains(name)) {
// mentioned = true;
// break;
// }
// }
// }
// }
// }
//
// if (mentioned) {
// drawRect(x, y - 1, x + 320, y + 8, RED);
// }
// else {
// drawRect(x, y - 1, x + 320, y + 8, color / 2 << 24);
// }
// GL11.glEnable(3042 /*GL_BLEND*/);
// font.drawStringWithShadow(chat, x, y, 0xffffff + (color << 24));
// }
// viewedLine++;
// }
// }
// }
SpoutClient.disableSandbox();
ServerPlayerList playerList = mainScreen.getServerPlayerList();
if(this.mc.thePlayer instanceof EntityClientPlayerMP && this.mc.gameSettings.keyBindPlayerList.pressed && playerList.isVisible()) {
NetClientHandler var41 = ((EntityClientPlayerMP)this.mc.thePlayer).sendQueue;
List var44 = var41.playerInfoList;
int var40 = var41.currentServerMaxPlayers;
int var38 = var40;
int var16;
for(var16 = 1; var38 > 20; var38 = (var40 + var16 - 1) / var16) {
++var16;
}
var17 = 300 / var16;
if(var17 > 150) {
var17 = 150;
}
int var18 = (screenWidth - var16 * var17) / 2;
byte var46 = 10;
this.drawRect(var18 - 1, var46 - 1, var18 + var17 * var16, var46 + 9 * var38, Integer.MIN_VALUE);
for(int var20 = 0; var20 < var40; ++var20) {
int var47 = var18 + var20 % var16 * var17;
int var22 = var46 + var20 / var16 * 9;
this.drawRect(var47, var22, var47 + var17 - 1, var22 + 8, 553648127);
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
GL11.glEnable(3008 /*GL_ALPHA_TEST*/);
if(var20 < var44.size()) {
GuiPlayerInfo var50 = (GuiPlayerInfo)var44.get(var20);
font.drawStringWithShadow(var50.name, var47, var22, 16777215);
this.mc.renderEngine.bindTexture(this.mc.renderEngine.getTexture("/gui/icons.png"));
boolean var48 = false;
boolean var53 = false;
byte var49 = 0;
var53 = false;
byte var54;
if(var50.responseTime < 0) {
var54 = 5;
} else if(var50.responseTime < 150) {
var54 = 0;
} else if(var50.responseTime < 300) {
var54 = 1;
} else if(var50.responseTime < 600) {
var54 = 2;
} else if(var50.responseTime < 1000) {
var54 = 3;
} else {
var54 = 4;
}
this.zLevel += 100.0F;
this.drawTexturedModalRect(var47 + var17 - 12, var22, 0 + var49 * 10, 176 + var54 * 8, 10, 8);
this.zLevel -= 100.0F;
}
}
}
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
GL11.glDisable(2896 /*GL_LIGHTING*/);
GL11.glEnable(3008 /*GL_ALPHA_TEST*/);
GL11.glDisable(3042 /*GL_BLEND*/);
}
|
diff --git a/hazelcast/src/main/java/com/hazelcast/impl/ListenerManager.java b/hazelcast/src/main/java/com/hazelcast/impl/ListenerManager.java
index 96cad276..07357450 100644
--- a/hazelcast/src/main/java/com/hazelcast/impl/ListenerManager.java
+++ b/hazelcast/src/main/java/com/hazelcast/impl/ListenerManager.java
@@ -1,400 +1,403 @@
/*
* Copyright (c) 2008-2010, Hazel 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.hazelcast.impl;
import com.hazelcast.cluster.AbstractRemotelyProcessable;
import com.hazelcast.core.*;
import com.hazelcast.impl.base.PacketProcessor;
import com.hazelcast.nio.Address;
import com.hazelcast.nio.Data;
import com.hazelcast.nio.DataSerializable;
import com.hazelcast.nio.Packet;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.logging.Level;
import static com.hazelcast.impl.ClusterOperation.*;
import static com.hazelcast.nio.IOUtil.toData;
public class ListenerManager extends BaseManager {
private List<ListenerItem> listeners = new CopyOnWriteArrayList<ListenerItem>();
ListenerManager(Node node) {
super(node);
registerPacketProcessor(ClusterOperation.EVENT, new PacketProcessor() {
public void process(Packet packet) {
handleEvent(packet);
}
});
registerPacketProcessor(ADD_LISTENER, new AddRemoveListenerOperationHandler());
registerPacketProcessor(REMOVE_LISTENER, new AddRemoveListenerOperationHandler());
registerPacketProcessor(ADD_LISTENER_NO_RESPONSE, new PacketProcessor() {
public void process(Packet packet) {
handleAddRemoveListener(true, packet);
}
});
}
private void handleEvent(Packet packet) {
int eventType = (int) packet.longValue;
Data key = packet.key;
Data value = packet.value;
String name = packet.name;
Address from = packet.conn.getEndPoint();
releasePacket(packet);
enqueueEvent(eventType, name, key, value, from);
}
private void handleAddRemoveListener(boolean add, Packet packet) {
Data key = (packet.key != null) ? packet.key : null;
boolean returnValue = (packet.longValue == 1);
String name = packet.name;
Address address = packet.conn.getEndPoint();
releasePacket(packet);
handleListenerRegistrations(add, name, key, address, returnValue);
}
public void syncForDead(Address deadAddress) {
syncForAdd();
}
public void syncForAdd() {
for (ListenerItem listenerItem : listeners) {
registerListenerWithNoResponse(listenerItem.name, listenerItem.key, listenerItem.includeValue);
}
}
public void syncForAdd(Address newAddress) {
for (ListenerItem listenerItem : listeners) {
Data dataKey = null;
if (listenerItem.key != null) {
dataKey = ThreadContext.get().toData(listenerItem.key);
}
sendAddListener(newAddress, listenerItem.name, dataKey, listenerItem.includeValue);
}
}
class AddRemoveListenerOperationHandler extends TargetAwareOperationHandler {
boolean isRightRemoteTarget(Request request) {
return (null == request.key) || thisAddress.equals(getKeyOwner(request.key));
}
void doOperation(Request request) {
Address from = request.caller;
logger.log(Level.FINEST, "AddListenerOperation from " + from + ", local=" + request.local + " key:" + request.key + " op:" + request.operation);
if (from == null) throw new RuntimeException("Listener origin is not known!");
boolean add = (request.operation == ADD_LISTENER);
boolean includeValue = (request.longValue == 1);
handleListenerRegistrations(add, request.name, request.key, request.caller, includeValue);
request.response = Boolean.TRUE;
}
}
public class AddRemoveListener extends MultiCall<Boolean> {
final String name;
final boolean add;
final boolean includeValue;
public AddRemoveListener(String name, boolean add, boolean includeValue) {
this.name = name;
this.add = add;
this.includeValue = includeValue;
}
TargetAwareOp createNewTargetAwareOp(Address target) {
return new AddListenerAtTarget(target);
}
boolean onResponse(Object response) {
return true;
}
Object returnResult() {
return Boolean.TRUE;
}
class AddListenerAtTarget extends TargetAwareOp {
public AddListenerAtTarget(Address target) {
request.reset();
this.target = target;
ClusterOperation operation = (add) ? ADD_LISTENER : REMOVE_LISTENER;
setLocal(operation, name, null, null, -1, -1);
request.setBooleanRequest();
request.longValue = (includeValue) ? 1 : 0;
}
@Override
public void setTarget() {
}
}
}
private void registerListener(String name, Object key, boolean add, boolean includeValue) {
if (key == null) {
AddRemoveListener addRemoveListener = new AddRemoveListener(name, add, includeValue);
addRemoveListener.call();
} else {
node.concurrentMapManager.new MAddKeyListener().addListener(name, add, key, includeValue);
}
}
private void registerListenerWithNoResponse(String name, Object key, boolean includeValue) {
Data dataKey = null;
if (key != null) {
dataKey = ThreadContext.get().toData(key);
}
enqueueAndReturn(new ListenerRegistrationProcess(name, dataKey, includeValue));
}
final class ListenerRegistrationProcess implements Processable {
final String name;
final Data key;
final boolean includeValue;
public ListenerRegistrationProcess(String name, Data key, boolean includeValue) {
super();
this.key = key;
this.name = name;
this.includeValue = includeValue;
}
public void process() {
if (key != null) {
processWithKey();
} else {
processWithoutKey();
}
}
private void processWithKey() {
Address owner = node.concurrentMapManager.getKeyOwner(key);
if (owner.equals(thisAddress)) {
handleListenerRegistrations(true, name, key, thisAddress, includeValue);
} else {
Packet packet = obtainPacket();
packet.set(name, ADD_LISTENER_NO_RESPONSE, key, null);
packet.longValue = (includeValue) ? 1 : 0;
boolean sent = send(packet, owner);
if (!sent) {
releasePacket(packet);
}
}
}
private void processWithoutKey() {
for (MemberImpl member : lsMembers) {
if (member.localMember()) {
handleListenerRegistrations(true, name, null, thisAddress, includeValue);
} else {
sendAddListener(member.getAddress(), name, null, includeValue);
}
}
}
}
public void collectInitialProcess(List<AbstractRemotelyProcessable> lsProcessables) {
for (ListenerItem listenerItem : listeners) {
lsProcessables.add(listenerItem);
}
}
void sendAddListener(Address toAddress, String name, Data key,
boolean includeValue) {
Packet packet = obtainPacket();
packet.set(name, ClusterOperation.ADD_LISTENER_NO_RESPONSE, key, null);
packet.longValue = (includeValue) ? 1 : 0;
boolean sent = send(packet, toAddress);
if (!sent) {
releasePacket(packet);
}
}
public void addListener(String name, Object listener, Object key, boolean includeValue,
Instance.InstanceType instanceType) {
/**
* check if already registered send this lockAddress to the key owner as a
* listener add this listener to the local listeners map
*/
boolean remotelyRegister = true;
for (ListenerItem listenerItem : listeners) {
if (remotelyRegister) {
if (listenerItem.listener == listener) {
if (listenerItem.name.equals(name)) {
if (key == null) {
if (listenerItem.key == null) {
if (!includeValue || listenerItem.includeValue == includeValue) {
remotelyRegister = false;
}
}
} else {
if (listenerItem.key != null) {
if (listenerItem.key.equals(key)) {
if (!includeValue
|| listenerItem.includeValue == includeValue) {
remotelyRegister = false;
}
}
}
}
}
}
}
}
if (remotelyRegister) {
registerListener(name, key, true, includeValue);
}
ListenerItem listenerItem = new ListenerItem(name, key, listener, includeValue,
instanceType);
listeners.add(listenerItem);
}
public synchronized void removeListener(String name, Object listener, Object key) {
/**
* send this lockAddress to the key owner as a listener add this listener to
* the local listeners map
*/
Iterator<ListenerItem> it = listeners.iterator();
for (; it.hasNext();) {
ListenerItem listenerItem = it.next();
if (listener == listenerItem.listener) {
if (key == null) {
if (listenerItem.key == null) {
registerListener(name, null, false, false);
listeners.remove(listenerItem);
}
} else if (key.equals(listenerItem.key)) {
registerListener(name, key, false, false);
listeners.remove(listenerItem);
}
}
}
}
void callListeners(EventTask event) {
for (ListenerItem listenerItem : listeners) {
if (listenerItem.listens(event)) {
callListener(listenerItem, event);
}
}
}
private void callListener(ListenerItem listenerItem, EntryEvent event) {
Object listener = listenerItem.listener;
EntryEventType entryEventType = event.getEventType();
if (listenerItem.instanceType == Instance.InstanceType.MAP) {
if (!listenerItem.name.startsWith("c:__hz_")) {
- MProxy mProxy = (MProxy) node.factory.getOrCreateProxyByName(listenerItem.name);
- mProxy.getMapOperationStats().incrementReceivedEvents();
+ Object proxy = node.factory.getOrCreateProxyByName(listenerItem.name);
+ if (proxy instanceof MProxy) {
+ MProxy mProxy = (MProxy) proxy;
+ mProxy.getMapOperationStats().incrementReceivedEvents();
+ }
}
}
switch (listenerItem.instanceType) {
case MAP:
case MULTIMAP:
EntryListener entryListener = (EntryListener) listener;
switch (entryEventType) {
case ADDED:
entryListener.entryAdded(event);
break;
case REMOVED:
entryListener.entryRemoved(event);
break;
case UPDATED:
entryListener.entryUpdated(event);
break;
case EVICTED:
entryListener.entryEvicted(event);
break;
}
break;
case SET:
case LIST:
ItemListener itemListener = (ItemListener) listener;
switch (entryEventType) {
case ADDED:
itemListener.itemAdded(event.getKey());
break;
case REMOVED:
itemListener.itemRemoved(event.getKey());
break;
}
break;
case TOPIC:
MessageListener messageListener = (MessageListener) listener;
messageListener.onMessage(event.getValue());
break;
case QUEUE:
ItemListener queueItemListener = (ItemListener) listener;
switch (entryEventType) {
case ADDED:
queueItemListener.itemAdded(event.getValue());
break;
case REMOVED:
queueItemListener.itemRemoved(event.getValue());
break;
}
break;
}
}
public static class ListenerItem extends AbstractRemotelyProcessable implements DataSerializable {
public String name;
public Object key;
public Object listener;
public boolean includeValue;
public Instance.InstanceType instanceType;
public ListenerItem() {
}
public ListenerItem(String name, Object key, Object listener, boolean includeValue,
Instance.InstanceType instanceType) {
super();
this.key = key;
this.listener = listener;
this.name = name;
this.includeValue = includeValue;
this.instanceType = instanceType;
}
public boolean listens(EventTask event) {
String name = event.getName();
return this.name.equals(name) && (this.key == null || event.getKey().equals(this.key));
}
public void writeData(DataOutput out) throws IOException {
out.writeUTF(name);
writeObject(out, key);
out.writeBoolean(includeValue);
}
public void readData(DataInput in) throws IOException {
name = in.readUTF();
key = readObject(in);
includeValue = in.readBoolean();
}
public void process() {
getNode().listenerManager.handleListenerRegistrations(true, name, toData(key), getConnection().getEndPoint(), includeValue);
}
}
}
| true | true | private void callListener(ListenerItem listenerItem, EntryEvent event) {
Object listener = listenerItem.listener;
EntryEventType entryEventType = event.getEventType();
if (listenerItem.instanceType == Instance.InstanceType.MAP) {
if (!listenerItem.name.startsWith("c:__hz_")) {
MProxy mProxy = (MProxy) node.factory.getOrCreateProxyByName(listenerItem.name);
mProxy.getMapOperationStats().incrementReceivedEvents();
}
}
switch (listenerItem.instanceType) {
case MAP:
case MULTIMAP:
EntryListener entryListener = (EntryListener) listener;
switch (entryEventType) {
case ADDED:
entryListener.entryAdded(event);
break;
case REMOVED:
entryListener.entryRemoved(event);
break;
case UPDATED:
entryListener.entryUpdated(event);
break;
case EVICTED:
entryListener.entryEvicted(event);
break;
}
break;
case SET:
case LIST:
ItemListener itemListener = (ItemListener) listener;
switch (entryEventType) {
case ADDED:
itemListener.itemAdded(event.getKey());
break;
case REMOVED:
itemListener.itemRemoved(event.getKey());
break;
}
break;
case TOPIC:
MessageListener messageListener = (MessageListener) listener;
messageListener.onMessage(event.getValue());
break;
case QUEUE:
ItemListener queueItemListener = (ItemListener) listener;
switch (entryEventType) {
case ADDED:
queueItemListener.itemAdded(event.getValue());
break;
case REMOVED:
queueItemListener.itemRemoved(event.getValue());
break;
}
break;
}
}
| private void callListener(ListenerItem listenerItem, EntryEvent event) {
Object listener = listenerItem.listener;
EntryEventType entryEventType = event.getEventType();
if (listenerItem.instanceType == Instance.InstanceType.MAP) {
if (!listenerItem.name.startsWith("c:__hz_")) {
Object proxy = node.factory.getOrCreateProxyByName(listenerItem.name);
if (proxy instanceof MProxy) {
MProxy mProxy = (MProxy) proxy;
mProxy.getMapOperationStats().incrementReceivedEvents();
}
}
}
switch (listenerItem.instanceType) {
case MAP:
case MULTIMAP:
EntryListener entryListener = (EntryListener) listener;
switch (entryEventType) {
case ADDED:
entryListener.entryAdded(event);
break;
case REMOVED:
entryListener.entryRemoved(event);
break;
case UPDATED:
entryListener.entryUpdated(event);
break;
case EVICTED:
entryListener.entryEvicted(event);
break;
}
break;
case SET:
case LIST:
ItemListener itemListener = (ItemListener) listener;
switch (entryEventType) {
case ADDED:
itemListener.itemAdded(event.getKey());
break;
case REMOVED:
itemListener.itemRemoved(event.getKey());
break;
}
break;
case TOPIC:
MessageListener messageListener = (MessageListener) listener;
messageListener.onMessage(event.getValue());
break;
case QUEUE:
ItemListener queueItemListener = (ItemListener) listener;
switch (entryEventType) {
case ADDED:
queueItemListener.itemAdded(event.getValue());
break;
case REMOVED:
queueItemListener.itemRemoved(event.getValue());
break;
}
break;
}
}
|
diff --git a/impl/src/java/uk/ac/ox/oucs/oxam/logic/SakaiLocation.java b/impl/src/java/uk/ac/ox/oucs/oxam/logic/SakaiLocation.java
index 00ec9c5..0960050 100644
--- a/impl/src/java/uk/ac/ox/oucs/oxam/logic/SakaiLocation.java
+++ b/impl/src/java/uk/ac/ox/oucs/oxam/logic/SakaiLocation.java
@@ -1,63 +1,66 @@
package uk.ac.ox.oucs.oxam.logic;
import org.sakaiproject.component.api.ServerConfigurationService;
import org.sakaiproject.content.api.ContentHostingService;
import org.sakaiproject.exception.IdUnusedException;
import org.sakaiproject.exception.PermissionException;
import org.sakaiproject.exception.TypeException;
import uk.ac.ox.oucs.oxam.utils.Utils;
/**
* This is a Sakai implementation for locating uploaded paper files.
* @author buckett
*
*/
public class SakaiLocation implements Location {
private ServerConfigurationService serverConfigurationService;
private ContentHostingService contentHostingService;
private String sitePath;
private String prefix;
public void setServerConfigurationService(
ServerConfigurationService serverConfigurationService) {
this.serverConfigurationService = serverConfigurationService;
}
public void setContentHostingService(ContentHostingService contentHostingService) {
this.contentHostingService = contentHostingService;
}
public void init() {
String siteId = serverConfigurationService.getString(SakaiValueSource.OXAM_CONTENT_SITE_ID);
if (siteId == null) {
// Oh poo.
}
sitePath = contentHostingService.getSiteCollection(siteId);
}
public String getPrefix() {
if (prefix == null) {
try {
- prefix = contentHostingService.getCollection(sitePath).getUrl(true);
+ // This is so that we can have a relative path, without the hostname.
+ String siteUrl = contentHostingService.getCollection(sitePath).getUrl(true);
+ String prefix = serverConfigurationService.getString("accessPath", "/access");
+ this.prefix = Utils.joinPaths("/", prefix, siteUrl);
// Ignore all the exceptions.
} catch (PermissionException e) {
//
} catch (IdUnusedException e) {
//
} catch (TypeException e) {
//
}
}
return prefix;
}
public String getPath(String path) {
String fullPath = Utils.joinPaths("/", sitePath, path);
return fullPath;
}
}
| true | true | public String getPrefix() {
if (prefix == null) {
try {
prefix = contentHostingService.getCollection(sitePath).getUrl(true);
// Ignore all the exceptions.
} catch (PermissionException e) {
//
} catch (IdUnusedException e) {
//
} catch (TypeException e) {
//
}
}
return prefix;
}
| public String getPrefix() {
if (prefix == null) {
try {
// This is so that we can have a relative path, without the hostname.
String siteUrl = contentHostingService.getCollection(sitePath).getUrl(true);
String prefix = serverConfigurationService.getString("accessPath", "/access");
this.prefix = Utils.joinPaths("/", prefix, siteUrl);
// Ignore all the exceptions.
} catch (PermissionException e) {
//
} catch (IdUnusedException e) {
//
} catch (TypeException e) {
//
}
}
return prefix;
}
|
diff --git a/src/net/azib/ipscan/gui/PreferencesDialog.java b/src/net/azib/ipscan/gui/PreferencesDialog.java
index a44213d..6467caf 100755
--- a/src/net/azib/ipscan/gui/PreferencesDialog.java
+++ b/src/net/azib/ipscan/gui/PreferencesDialog.java
@@ -1,511 +1,511 @@
/**
* This file is a part of Angry IP Scanner source code,
* see http://www.angryip.org/ for more information.
* Licensed under GPLv2.
*/
package net.azib.ipscan.gui;
import net.azib.ipscan.config.GUIConfig;
import net.azib.ipscan.config.GUIConfig.DisplayMethod;
import net.azib.ipscan.config.Labels;
import net.azib.ipscan.config.ScannerConfig;
import net.azib.ipscan.core.PortIterator;
import net.azib.ipscan.core.net.PingerRegistry;
import net.azib.ipscan.fetchers.FetcherException;
import net.azib.ipscan.gui.util.LayoutHelper;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.layout.RowData;
import org.eclipse.swt.layout.RowLayout;
import org.eclipse.swt.widgets.*;
/**
* Preferences Dialog
*
* @author Anton Keks
*/
public class PreferencesDialog extends AbstractModalDialog {
private PingerRegistry pingerRegistry;
private ScannerConfig scannerConfig;
private GUIConfig guiConfig;
private ConfigDetectorDialog configDetectorDialog;
private Button okButton;
private Button cancelButton;
private TabFolder tabFolder;
private Composite scanningTab;
private TabItem scanningTabItem;
private Composite displayTab;
private Text threadDelayText;
private Text maxThreadsText;
private Button deadHostsCheckbox;
private Text pingingTimeoutText;
private Text pingingCountText;
private Combo pingersCombo;
private Button skipBroadcastsCheckbox;
// private Composite fetchersTab;
private Composite portsTab;
private TabItem portsTabItem;
private Text portTimeoutText;
private Button adaptTimeoutCheckbox;
private Button addRequestedPortsCheckbox;
private Text minPortTimeoutText;
private Text portsText;
private Text notAvailableText;
private Text notScannedText;
private Button[] displayMethod;
private Button showInfoCheckbox;
private Button askConfirmationCheckbox;
public PreferencesDialog(PingerRegistry pingerRegistry, ScannerConfig scannerConfig, GUIConfig guiConfig, ConfigDetectorDialog configDetectorDialog) {
this.pingerRegistry = pingerRegistry;
this.scannerConfig = scannerConfig;
this.guiConfig = guiConfig;
this.configDetectorDialog = configDetectorDialog;
}
@Override
public void open() {
openTab(0);
}
/**
* Opens the specified tab of preferences dialog
* @param tabIndex
*/
public void openTab(int tabIndex) {
// widgets are created on demand
createShell();
loadPreferences();
tabFolder.setSelection(tabIndex);
// select ports text by default if ports tab is opened
// this is needed for PortsFetcher that uses this tab as its preferences
if (tabFolder.getItem(tabIndex) == portsTabItem) {
portsText.forceFocus();
}
super.open();
}
@Override
protected void populateShell() {
shell.setText(Labels.getLabel("title.preferences"));
shell.setLayout(LayoutHelper.formLayout(10, 10, 4));
createTabFolder();
okButton = new Button(shell, SWT.NONE);
okButton.setText(Labels.getLabel("button.OK"));
cancelButton = new Button(shell, SWT.NONE);
cancelButton.setText(Labels.getLabel("button.cancel"));
positionButtonsInFormLayout(okButton, cancelButton, tabFolder);
shell.pack();
okButton.setFocus();
okButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
savePreferences();
shell.close();
}
});
cancelButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
shell.close();
}
});
}
/**
* This method initializes tabFolder
*/
private void createTabFolder() {
tabFolder = new TabFolder(shell, SWT.NONE);
createScanningTab();
TabItem tabItem = new TabItem(tabFolder, SWT.NONE);
tabItem.setText(Labels.getLabel("title.preferences.scanning"));
tabItem.setControl(scanningTab);
scanningTabItem = tabItem;
createPortsTab();
tabItem = new TabItem(tabFolder, SWT.NONE);
tabItem.setText(Labels.getLabel("title.preferences.ports"));
tabItem.setControl(portsTab);
portsTabItem = tabItem;
createDisplayTab();
tabItem = new TabItem(tabFolder, SWT.NONE);
tabItem.setText(Labels.getLabel("title.preferences.display"));
tabItem.setControl(displayTab);
// createFetchersTab();
// tabItem = new TabItem(tabFolder, SWT.NONE);
// tabItem.setText(Labels.getLabel("title.preferences.fetchers"));
// tabItem.setControl(fetchersTab);
tabFolder.pack();
}
/**
* This method initializes scanningTab
*/
private void createScanningTab() {
RowLayout rowLayout = createRowLayout();
scanningTab = new Composite(tabFolder, SWT.NONE);
scanningTab.setLayout(rowLayout);
GridLayout groupLayout = new GridLayout();
groupLayout.numColumns = 2;
Group threadsGroup = new Group(scanningTab, SWT.NONE);
threadsGroup.setText(Labels.getLabel("preferences.threads"));
threadsGroup.setLayout(groupLayout);
GridData gridData = new GridData(80, SWT.DEFAULT);
Label label;
label = new Label(threadsGroup, SWT.NONE);
label.setText(Labels.getLabel("preferences.threads.delay"));
threadDelayText = new Text(threadsGroup, SWT.BORDER);
threadDelayText.setLayoutData(gridData);
label = new Label(threadsGroup, SWT.NONE);
label.setText(Labels.getLabel("preferences.threads.maxThreads"));
maxThreadsText = new Text(threadsGroup, SWT.BORDER);
maxThreadsText.setLayoutData(gridData);
// new Label(threadsGroup, SWT.NONE);
// Button checkButton = new Button(threadsGroup, SWT.NONE);
// checkButton.setText(Labels.getLabel("button.check"));
// checkButton.setLayoutData(gridData);
// checkButton.addListener(SWT.Selection, new CheckButtonListener());
Group pingingGroup = new Group(scanningTab, SWT.NONE);
pingingGroup.setLayout(groupLayout);
pingingGroup.setText(Labels.getLabel("preferences.pinging"));
label = new Label(pingingGroup, SWT.NONE);
label.setText(Labels.getLabel("preferences.pinging.type"));
pingersCombo = new Combo(pingingGroup, SWT.DROP_DOWN | SWT.READ_ONLY);
pingersCombo.setLayoutData(gridData);
String[] pingerNames = pingerRegistry.getRegisteredNames();
for (int i = 0; i < pingerNames.length; i++) {
pingersCombo.add(Labels.getLabel(pingerNames[i]));
// this is used by savePreferences()
pingersCombo.setData(Integer.toString(i), pingerNames[i]);
}
pingersCombo.select(0);
label = new Label(pingingGroup, SWT.NONE);
label.setText(Labels.getLabel("preferences.pinging.count"));
pingingCountText = new Text(pingingGroup, SWT.BORDER);
pingingCountText.setLayoutData(gridData);
label = new Label(pingingGroup, SWT.NONE);
label.setText(Labels.getLabel("preferences.pinging.timeout"));
pingingTimeoutText = new Text(pingingGroup, SWT.BORDER);
pingingTimeoutText.setLayoutData(gridData);
GridData gridDataWithSpan = new GridData();
gridDataWithSpan.horizontalSpan = 2;
deadHostsCheckbox = new Button(pingingGroup, SWT.CHECK);
deadHostsCheckbox.setText(Labels.getLabel("preferences.pinging.deadHosts"));
deadHostsCheckbox.setLayoutData(gridDataWithSpan);
- Group broadcastGroup = new Group(scanningTab, SWT.NONE);
- broadcastGroup.setLayout(groupLayout);
- broadcastGroup.setText(Labels.getLabel("preferences.broadcast"));
+ Group skippingGroup = new Group(scanningTab, SWT.NONE);
+ skippingGroup.setLayout(groupLayout);
+ skippingGroup.setText(Labels.getLabel("preferences.skipping"));
- skipBroadcastsCheckbox = new Button(broadcastGroup, SWT.CHECK);
- skipBroadcastsCheckbox.setText(Labels.getLabel("preferences.broadcast.skip"));
+ skipBroadcastsCheckbox = new Button(skippingGroup, SWT.CHECK);
+ skipBroadcastsCheckbox.setText(Labels.getLabel("preferences.skipping.broadcast"));
GridData gridDataWithSpan2 = new GridData();
gridDataWithSpan2.horizontalSpan = 2;
skipBroadcastsCheckbox.setLayoutData(gridDataWithSpan2);
}
/**
* This method initializes displayTab
*/
private void createDisplayTab() {
RowLayout rowLayout = createRowLayout();
displayTab = new Composite(tabFolder, SWT.NONE);
displayTab.setLayout(rowLayout);
GridLayout groupLayout = new GridLayout();
groupLayout.numColumns = 1;
Group listGroup = new Group(displayTab, SWT.NONE);
listGroup.setText(Labels.getLabel("preferences.display.list"));
listGroup.setLayout(groupLayout);
listGroup.setLayoutData(new RowData(260, SWT.DEFAULT));
displayMethod = new Button[DisplayMethod.values().length];
Button allRadio = new Button(listGroup, SWT.RADIO);
allRadio.setText(Labels.getLabel("preferences.display.list" + '.' + DisplayMethod.ALL));
displayMethod[DisplayMethod.ALL.ordinal()] = allRadio;
Button aliveRadio = new Button(listGroup, SWT.RADIO);
aliveRadio.setText(Labels.getLabel("preferences.display.list" + '.' + DisplayMethod.ALIVE));
displayMethod[DisplayMethod.ALIVE.ordinal()] = aliveRadio;
Button portsRadio = new Button(listGroup, SWT.RADIO);
portsRadio.setText(Labels.getLabel("preferences.display.list" + '.' + DisplayMethod.PORTS));
displayMethod[DisplayMethod.PORTS.ordinal()] = portsRadio;
groupLayout = new GridLayout();
groupLayout.numColumns = 2;
Group labelsGroup = new Group(displayTab, SWT.NONE);
labelsGroup.setText(Labels.getLabel("preferences.display.labels"));
labelsGroup.setLayout(groupLayout);
GridData gridData = new GridData();
gridData.widthHint = 50;
Label label = new Label(labelsGroup, SWT.NONE);
label.setText(Labels.getLabel("preferences.display.labels.notAvailable"));
notAvailableText = new Text(labelsGroup, SWT.BORDER);
notAvailableText.setLayoutData(gridData);
label = new Label(labelsGroup, SWT.NONE);
label.setText(Labels.getLabel("preferences.display.labels.notScanned"));
notScannedText = new Text(labelsGroup, SWT.BORDER);
notScannedText.setLayoutData(gridData);
groupLayout = new GridLayout();
groupLayout.numColumns = 1;
Group showStatsGroup = new Group(displayTab, SWT.NONE);
showStatsGroup.setLayout(groupLayout);
showStatsGroup.setText(Labels.getLabel("preferences.display.confirmation"));
askConfirmationCheckbox = new Button(showStatsGroup, SWT.CHECK);
askConfirmationCheckbox.setText(Labels.getLabel("preferences.display.confirmation.newScan"));
showInfoCheckbox = new Button(showStatsGroup, SWT.CHECK);
showInfoCheckbox.setText(Labels.getLabel("preferences.display.confirmation.showInfo"));
}
/**
* This method initializes portsTab
*/
private void createPortsTab() {
RowLayout rowLayout = createRowLayout();
portsTab = new Composite(tabFolder, SWT.NONE);
portsTab.setLayout(rowLayout);
GridLayout groupLayout = new GridLayout();
groupLayout.numColumns = 2;
Group timingGroup = new Group(portsTab, SWT.NONE);
timingGroup.setText(Labels.getLabel("preferences.ports.timing"));
timingGroup.setLayout(groupLayout);
GridData gridData = new GridData();
gridData.widthHint = 50;
Label label = new Label(timingGroup, SWT.NONE);
label.setText(Labels.getLabel("preferences.ports.timing.timeout"));
portTimeoutText = new Text(timingGroup, SWT.BORDER);
portTimeoutText.setLayoutData(gridData);
GridData gridData1 = new GridData();
gridData1.horizontalSpan = 2;
adaptTimeoutCheckbox = new Button(timingGroup, SWT.CHECK);
adaptTimeoutCheckbox.setText(Labels.getLabel("preferences.ports.timing.adaptTimeout"));
adaptTimeoutCheckbox.setLayoutData(gridData1);
adaptTimeoutCheckbox.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event event) {
minPortTimeoutText.setEnabled(adaptTimeoutCheckbox.getSelection());
}
});
label = new Label(timingGroup, SWT.NONE);
label.setText(Labels.getLabel("preferences.ports.timing.minTimeout"));
minPortTimeoutText = new Text(timingGroup, SWT.BORDER);
minPortTimeoutText.setLayoutData(gridData);
RowLayout portsLayout = new RowLayout(SWT.VERTICAL);
portsLayout.fill = true;
portsLayout.marginHeight = 2;
portsLayout.marginWidth = 2;
Group portsGroup = new Group(portsTab, SWT.NONE);
portsGroup.setText(Labels.getLabel("preferences.ports.ports"));
portsGroup.setLayout(portsLayout);
label = new Label(portsGroup, SWT.WRAP);
label.setText(Labels.getLabel("preferences.ports.portsDescription"));
//label.setLayoutData(new RowData(300, SWT.DEFAULT));
portsText = new Text(portsGroup, SWT.MULTI | SWT.BORDER | SWT.V_SCROLL);
portsText.setLayoutData(new RowData(SWT.DEFAULT, 60));
portsText.addKeyListener(new PortsTextValidationListener());
addRequestedPortsCheckbox = new Button(portsGroup, SWT.CHECK);
addRequestedPortsCheckbox.setText(Labels.getLabel("preferences.ports.addRequested"));
addRequestedPortsCheckbox.setToolTipText(Labels.getLabel("preferences.ports.addRequested.info"));
}
/**
* This method initializes fetchersTab
*/
// private void createFetchersTab() {
// GridLayout gridLayout = new GridLayout();
// gridLayout.numColumns = 1;
// fetchersTab = new Composite(tabFolder, SWT.NONE);
// fetchersTab.setLayout(gridLayout);
// Label label = new Label(fetchersTab, SWT.NONE);
// label.setText(Labels.getLabel("preferences.fetchers.info"));
// }
/**
* @return a pre-initialized RowLayout suitable for option tabs.
*/
private RowLayout createRowLayout() {
RowLayout rowLayout = new RowLayout();
rowLayout.type = org.eclipse.swt.SWT.VERTICAL;
rowLayout.spacing = 9;
rowLayout.marginHeight = 9;
rowLayout.marginWidth = 11;
rowLayout.fill = true;
return rowLayout;
}
private void loadPreferences() {
pingerRegistry.checkSelectedPinger();
maxThreadsText.setText(Integer.toString(scannerConfig.maxThreads));
threadDelayText.setText(Integer.toString(scannerConfig.threadDelay));
String[] pingerNames = pingerRegistry.getRegisteredNames();
for (int i = 0; i < pingerNames.length; i++) {
if (scannerConfig.selectedPinger.equals(pingerNames[i])) {
pingersCombo.select(i);
}
}
pingingCountText.setText(Integer.toString(scannerConfig.pingCount));
pingingTimeoutText.setText(Integer.toString(scannerConfig.pingTimeout));
deadHostsCheckbox.setSelection(scannerConfig.scanDeadHosts);
skipBroadcastsCheckbox.setSelection(scannerConfig.skipBroadcastAddresses);
portTimeoutText.setText(Integer.toString(scannerConfig.portTimeout));
adaptTimeoutCheckbox.setSelection(scannerConfig.adaptPortTimeout);
minPortTimeoutText.setText(Integer.toString(scannerConfig.minPortTimeout));
minPortTimeoutText.setEnabled(scannerConfig.adaptPortTimeout);
portsText.setText(scannerConfig.portString);
addRequestedPortsCheckbox.setSelection(scannerConfig.useRequestedPorts);
notAvailableText.setText(scannerConfig.notAvailableText);
notScannedText.setText(scannerConfig.notScannedText);
displayMethod[guiConfig.displayMethod.ordinal()].setSelection(true);
showInfoCheckbox.setSelection(guiConfig.showScanStats);
askConfirmationCheckbox.setSelection(guiConfig.askScanConfirmation);
}
private void savePreferences() {
// validate port string
try {
new PortIterator(portsText.getText());
}
catch (Exception e) {
tabFolder.setSelection(portsTabItem);
portsText.forceFocus();
throw new FetcherException("unparseablePortString", e);
}
scannerConfig.selectedPinger = (String) pingersCombo.getData(Integer.toString(pingersCombo.getSelectionIndex()));
if (!pingerRegistry.checkSelectedPinger()) {
tabFolder.setSelection(scanningTabItem);
pingersCombo.forceFocus();
throw new FetcherException("unsupportedPinger");
}
scannerConfig.maxThreads = parseIntValue(maxThreadsText);
scannerConfig.threadDelay = parseIntValue(threadDelayText);
scannerConfig.pingCount = parseIntValue(pingingCountText);
scannerConfig.pingTimeout = parseIntValue(pingingTimeoutText);
scannerConfig.scanDeadHosts = deadHostsCheckbox.getSelection();
scannerConfig.skipBroadcastAddresses = skipBroadcastsCheckbox.getSelection();
scannerConfig.portTimeout = parseIntValue(portTimeoutText);
scannerConfig.adaptPortTimeout = adaptTimeoutCheckbox.getSelection();
scannerConfig.minPortTimeout = parseIntValue(minPortTimeoutText);
scannerConfig.portString = portsText.getText();
scannerConfig.useRequestedPorts = addRequestedPortsCheckbox.getSelection();
scannerConfig.notAvailableText = notAvailableText.getText();
scannerConfig.notScannedText = notScannedText.getText();
for (int i = 0; i < displayMethod.length; i++) {
if (displayMethod[i].getSelection())
guiConfig.displayMethod = DisplayMethod.values()[i];
}
guiConfig.showScanStats = showInfoCheckbox.getSelection();
guiConfig.askScanConfirmation = askConfirmationCheckbox.getSelection();
}
/**
* @return an int from the passed Text control.
*/
private static int parseIntValue(Text text) {
try {
return Integer.parseInt(text.getText());
}
catch (NumberFormatException e) {
text.forceFocus();
throw e;
}
}
static class PortsTextValidationListener implements KeyListener {
public void keyPressed(KeyEvent e) {
Text portsText = (Text) e.getSource();
if (e.keyCode == SWT.TAB) {
portsText.getShell().traverse(SWT.TRAVERSE_TAB_NEXT);
e.doit = false;
return;
}
else
if (e.keyCode == SWT.CR) {
if ((e.stateMask & SWT.MOD1) > 0) {
// allow ctrl+enter to insert newlines
e.stateMask = 0;
}
else {
// single-enter will traverse
portsText.getShell().traverse(SWT.TRAVERSE_RETURN);
e.doit = false;
return;
}
}
else
if (Character.isISOControl(e.character)) {
return;
}
e.doit = validateChar(e.character, portsText.getText(), portsText.getCaretPosition());
}
boolean validateChar(char c, String text, int caretPos) {
// previous
char pc = 0;
for (int i = caretPos-1; i >= 0; i--) {
pc = text.charAt(i);
if (!Character.isWhitespace(pc))
break;
}
boolean isCurDigit = c >= '0' && c <= '9';
boolean isPrevDigit = pc >= '0' && pc <= '9';
return isPrevDigit && (isCurDigit || c == '-' || c == ',') ||
isCurDigit && (pc == '-' || pc == ',' || pc == 0) ||
Character.isWhitespace(c) && pc == ',';
}
public void keyReleased(KeyEvent e) {
}
}
class CheckButtonListener implements Listener {
public void handleEvent(Event event) {
scannerConfig.maxThreads = Integer.parseInt(maxThreadsText.getText());
configDetectorDialog.open();
}
}
}
| false | true | private void createScanningTab() {
RowLayout rowLayout = createRowLayout();
scanningTab = new Composite(tabFolder, SWT.NONE);
scanningTab.setLayout(rowLayout);
GridLayout groupLayout = new GridLayout();
groupLayout.numColumns = 2;
Group threadsGroup = new Group(scanningTab, SWT.NONE);
threadsGroup.setText(Labels.getLabel("preferences.threads"));
threadsGroup.setLayout(groupLayout);
GridData gridData = new GridData(80, SWT.DEFAULT);
Label label;
label = new Label(threadsGroup, SWT.NONE);
label.setText(Labels.getLabel("preferences.threads.delay"));
threadDelayText = new Text(threadsGroup, SWT.BORDER);
threadDelayText.setLayoutData(gridData);
label = new Label(threadsGroup, SWT.NONE);
label.setText(Labels.getLabel("preferences.threads.maxThreads"));
maxThreadsText = new Text(threadsGroup, SWT.BORDER);
maxThreadsText.setLayoutData(gridData);
// new Label(threadsGroup, SWT.NONE);
// Button checkButton = new Button(threadsGroup, SWT.NONE);
// checkButton.setText(Labels.getLabel("button.check"));
// checkButton.setLayoutData(gridData);
// checkButton.addListener(SWT.Selection, new CheckButtonListener());
Group pingingGroup = new Group(scanningTab, SWT.NONE);
pingingGroup.setLayout(groupLayout);
pingingGroup.setText(Labels.getLabel("preferences.pinging"));
label = new Label(pingingGroup, SWT.NONE);
label.setText(Labels.getLabel("preferences.pinging.type"));
pingersCombo = new Combo(pingingGroup, SWT.DROP_DOWN | SWT.READ_ONLY);
pingersCombo.setLayoutData(gridData);
String[] pingerNames = pingerRegistry.getRegisteredNames();
for (int i = 0; i < pingerNames.length; i++) {
pingersCombo.add(Labels.getLabel(pingerNames[i]));
// this is used by savePreferences()
pingersCombo.setData(Integer.toString(i), pingerNames[i]);
}
pingersCombo.select(0);
label = new Label(pingingGroup, SWT.NONE);
label.setText(Labels.getLabel("preferences.pinging.count"));
pingingCountText = new Text(pingingGroup, SWT.BORDER);
pingingCountText.setLayoutData(gridData);
label = new Label(pingingGroup, SWT.NONE);
label.setText(Labels.getLabel("preferences.pinging.timeout"));
pingingTimeoutText = new Text(pingingGroup, SWT.BORDER);
pingingTimeoutText.setLayoutData(gridData);
GridData gridDataWithSpan = new GridData();
gridDataWithSpan.horizontalSpan = 2;
deadHostsCheckbox = new Button(pingingGroup, SWT.CHECK);
deadHostsCheckbox.setText(Labels.getLabel("preferences.pinging.deadHosts"));
deadHostsCheckbox.setLayoutData(gridDataWithSpan);
Group broadcastGroup = new Group(scanningTab, SWT.NONE);
broadcastGroup.setLayout(groupLayout);
broadcastGroup.setText(Labels.getLabel("preferences.broadcast"));
skipBroadcastsCheckbox = new Button(broadcastGroup, SWT.CHECK);
skipBroadcastsCheckbox.setText(Labels.getLabel("preferences.broadcast.skip"));
GridData gridDataWithSpan2 = new GridData();
gridDataWithSpan2.horizontalSpan = 2;
skipBroadcastsCheckbox.setLayoutData(gridDataWithSpan2);
}
| private void createScanningTab() {
RowLayout rowLayout = createRowLayout();
scanningTab = new Composite(tabFolder, SWT.NONE);
scanningTab.setLayout(rowLayout);
GridLayout groupLayout = new GridLayout();
groupLayout.numColumns = 2;
Group threadsGroup = new Group(scanningTab, SWT.NONE);
threadsGroup.setText(Labels.getLabel("preferences.threads"));
threadsGroup.setLayout(groupLayout);
GridData gridData = new GridData(80, SWT.DEFAULT);
Label label;
label = new Label(threadsGroup, SWT.NONE);
label.setText(Labels.getLabel("preferences.threads.delay"));
threadDelayText = new Text(threadsGroup, SWT.BORDER);
threadDelayText.setLayoutData(gridData);
label = new Label(threadsGroup, SWT.NONE);
label.setText(Labels.getLabel("preferences.threads.maxThreads"));
maxThreadsText = new Text(threadsGroup, SWT.BORDER);
maxThreadsText.setLayoutData(gridData);
// new Label(threadsGroup, SWT.NONE);
// Button checkButton = new Button(threadsGroup, SWT.NONE);
// checkButton.setText(Labels.getLabel("button.check"));
// checkButton.setLayoutData(gridData);
// checkButton.addListener(SWT.Selection, new CheckButtonListener());
Group pingingGroup = new Group(scanningTab, SWT.NONE);
pingingGroup.setLayout(groupLayout);
pingingGroup.setText(Labels.getLabel("preferences.pinging"));
label = new Label(pingingGroup, SWT.NONE);
label.setText(Labels.getLabel("preferences.pinging.type"));
pingersCombo = new Combo(pingingGroup, SWT.DROP_DOWN | SWT.READ_ONLY);
pingersCombo.setLayoutData(gridData);
String[] pingerNames = pingerRegistry.getRegisteredNames();
for (int i = 0; i < pingerNames.length; i++) {
pingersCombo.add(Labels.getLabel(pingerNames[i]));
// this is used by savePreferences()
pingersCombo.setData(Integer.toString(i), pingerNames[i]);
}
pingersCombo.select(0);
label = new Label(pingingGroup, SWT.NONE);
label.setText(Labels.getLabel("preferences.pinging.count"));
pingingCountText = new Text(pingingGroup, SWT.BORDER);
pingingCountText.setLayoutData(gridData);
label = new Label(pingingGroup, SWT.NONE);
label.setText(Labels.getLabel("preferences.pinging.timeout"));
pingingTimeoutText = new Text(pingingGroup, SWT.BORDER);
pingingTimeoutText.setLayoutData(gridData);
GridData gridDataWithSpan = new GridData();
gridDataWithSpan.horizontalSpan = 2;
deadHostsCheckbox = new Button(pingingGroup, SWT.CHECK);
deadHostsCheckbox.setText(Labels.getLabel("preferences.pinging.deadHosts"));
deadHostsCheckbox.setLayoutData(gridDataWithSpan);
Group skippingGroup = new Group(scanningTab, SWT.NONE);
skippingGroup.setLayout(groupLayout);
skippingGroup.setText(Labels.getLabel("preferences.skipping"));
skipBroadcastsCheckbox = new Button(skippingGroup, SWT.CHECK);
skipBroadcastsCheckbox.setText(Labels.getLabel("preferences.skipping.broadcast"));
GridData gridDataWithSpan2 = new GridData();
gridDataWithSpan2.horizontalSpan = 2;
skipBroadcastsCheckbox.setLayoutData(gridDataWithSpan2);
}
|
diff --git a/apps/xgap/plugins/reportbuilder/Statistics.java b/apps/xgap/plugins/reportbuilder/Statistics.java
index 5d18a4d93..fbf229e3b 100644
--- a/apps/xgap/plugins/reportbuilder/Statistics.java
+++ b/apps/xgap/plugins/reportbuilder/Statistics.java
@@ -1,170 +1,170 @@
package plugins.reportbuilder;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import matrix.DataMatrixInstance;
import org.apache.commons.math.stat.correlation.SpearmansCorrelation;
public class Statistics
{
public static TreeMap<String, Double> getSpearManCorr(DataMatrixInstance i, String name, boolean isRow)
throws Exception
{
HashMap<String, Double> map = new HashMap<String, Double>();
ValueComparator bvc = new ValueComparator(map);
boolean decimals = i.getData().getValueType().equals("Decimal") ? true : false;
// could do per row, but is slower? dont do on big sets anyway..
Object[][] elements = i.getElements();
List<String> dimNames;
int self = -1;
if (isRow)
{
dimNames = i.getRowNames();
- i.getRowIndexForName(name);
+ self = i.getRowIndexForName(name);
}
else
{
// reassign
dimNames = i.getColNames();
self = i.getColIndexForName(name);
// swap row and col, easier to iterate
elements = transposeMatrix(elements);
}
double[] selfDoubles;
if (decimals)
{
selfDoubles = getAsDoubles(elements[self]);
}
else
{
selfDoubles = getTextAsDoubles(elements[self]);
}
for (int index = 0; index < i.getNumberOfRows(); index++)
{
if (index != self)
{
double[] doubles;
if (decimals)
{
doubles = getAsDoubles(elements[index]);
}
else
{
doubles = getTextAsDoubles(elements[index]);
}
double corr = new SpearmansCorrelation().correlation(doubles, selfDoubles);
map.put(dimNames.get(index), corr);
}
}
TreeMap<String, Double> sorted_map = new TreeMap(bvc);
sorted_map.putAll(map);
for (String key : sorted_map.keySet())
{
System.out.println("k: " + key + ", v: " + sorted_map.get(key));
}
return sorted_map;
}
public static Object[][] transposeMatrix(Object[][] m)
{
int r = m.length;
int c = m[0].length;
Object[][] t = new Object[c][r];
for (int i = 0; i < r; ++i)
{
for (int j = 0; j < c; ++j)
{
t[j][i] = m[i][j];
}
}
return t;
}
public static double[] getAsDoubles(Object[] e)
{
double[] res = new double[e.length];
for (int i = 0; i < e.length; i++)
{
if (e[i] == null)
{
res[i] = 0;
}
else
{
res[i] = Double.parseDouble(e[i].toString());
}
}
return res;
}
public static double[] getTextAsDoubles(Object[] e)
{
double[] res = new double[e.length];
for (int i = 0; i < e.length; i++)
{
if (e[i] == null)
{
res[i] = 0;
}
else
{
double r = 0;
for (char c : e[i].toString().toCharArray())
{
r += (byte) c;
}
res[i] = r;
}
}
return res;
}
static class ValueComparator implements Comparator
{
Map base;
public ValueComparator(Map base)
{
this.base = base;
}
public int compare(Object a, Object b)
{
if ((Double) base.get(a) < (Double) base.get(b))
{
return 1;
}
else if ((Double) base.get(a) == (Double) base.get(b))
{
return 0;
}
else
{
return -1;
}
}
}
}
| true | true | public static TreeMap<String, Double> getSpearManCorr(DataMatrixInstance i, String name, boolean isRow)
throws Exception
{
HashMap<String, Double> map = new HashMap<String, Double>();
ValueComparator bvc = new ValueComparator(map);
boolean decimals = i.getData().getValueType().equals("Decimal") ? true : false;
// could do per row, but is slower? dont do on big sets anyway..
Object[][] elements = i.getElements();
List<String> dimNames;
int self = -1;
if (isRow)
{
dimNames = i.getRowNames();
i.getRowIndexForName(name);
}
else
{
// reassign
dimNames = i.getColNames();
self = i.getColIndexForName(name);
// swap row and col, easier to iterate
elements = transposeMatrix(elements);
}
double[] selfDoubles;
if (decimals)
{
selfDoubles = getAsDoubles(elements[self]);
}
else
{
selfDoubles = getTextAsDoubles(elements[self]);
}
for (int index = 0; index < i.getNumberOfRows(); index++)
{
if (index != self)
{
double[] doubles;
if (decimals)
{
doubles = getAsDoubles(elements[index]);
}
else
{
doubles = getTextAsDoubles(elements[index]);
}
double corr = new SpearmansCorrelation().correlation(doubles, selfDoubles);
map.put(dimNames.get(index), corr);
}
}
TreeMap<String, Double> sorted_map = new TreeMap(bvc);
sorted_map.putAll(map);
for (String key : sorted_map.keySet())
{
System.out.println("k: " + key + ", v: " + sorted_map.get(key));
}
return sorted_map;
}
| public static TreeMap<String, Double> getSpearManCorr(DataMatrixInstance i, String name, boolean isRow)
throws Exception
{
HashMap<String, Double> map = new HashMap<String, Double>();
ValueComparator bvc = new ValueComparator(map);
boolean decimals = i.getData().getValueType().equals("Decimal") ? true : false;
// could do per row, but is slower? dont do on big sets anyway..
Object[][] elements = i.getElements();
List<String> dimNames;
int self = -1;
if (isRow)
{
dimNames = i.getRowNames();
self = i.getRowIndexForName(name);
}
else
{
// reassign
dimNames = i.getColNames();
self = i.getColIndexForName(name);
// swap row and col, easier to iterate
elements = transposeMatrix(elements);
}
double[] selfDoubles;
if (decimals)
{
selfDoubles = getAsDoubles(elements[self]);
}
else
{
selfDoubles = getTextAsDoubles(elements[self]);
}
for (int index = 0; index < i.getNumberOfRows(); index++)
{
if (index != self)
{
double[] doubles;
if (decimals)
{
doubles = getAsDoubles(elements[index]);
}
else
{
doubles = getTextAsDoubles(elements[index]);
}
double corr = new SpearmansCorrelation().correlation(doubles, selfDoubles);
map.put(dimNames.get(index), corr);
}
}
TreeMap<String, Double> sorted_map = new TreeMap(bvc);
sorted_map.putAll(map);
for (String key : sorted_map.keySet())
{
System.out.println("k: " + key + ", v: " + sorted_map.get(key));
}
return sorted_map;
}
|
diff --git a/src/jpcsp/HLE/modules150/sceSasCore.java b/src/jpcsp/HLE/modules150/sceSasCore.java
index 20022646..a70dccda 100644
--- a/src/jpcsp/HLE/modules150/sceSasCore.java
+++ b/src/jpcsp/HLE/modules150/sceSasCore.java
@@ -1,1222 +1,1229 @@
/*
This file is part of jpcsp.
Jpcsp is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Jpcsp 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 Jpcsp. If not, see <http://www.gnu.org/licenses/>.
*/
package jpcsp.HLE.modules150;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;
import jpcsp.HLE.Modules;
import jpcsp.HLE.ThreadMan;
import jpcsp.HLE.kernel.managers.SceUidManager;
import jpcsp.HLE.modules.HLEModule;
import jpcsp.HLE.modules.HLEModuleFunction;
import jpcsp.HLE.modules.HLEModuleManager;
import jpcsp.Memory;
import jpcsp.Processor;
import jpcsp.Allegrex.CpuState;
public class sceSasCore implements HLEModule {
@Override
public String getName() {
return "sceSasCore";
}
@Override
public void installModule(HLEModuleManager mm, int version) {
if (version >= 150) {
mm.addFunction(__sceSasSetADSRFunction, 0x019B25EB);
mm.addFunction(__sceSasRevParamFunction, 0x267A6DD2);
mm.addFunction(__sceSasGetPauseFlagFunction, 0x2C8E6AB3);
mm.addFunction(__sceSasRevTypeFunction, 0x33D4AB37);
mm.addFunction(__sceSasInitFunction, 0x42778A9F);
mm.addFunction(__sceSasSetVolumeFunction, 0x440CA7D8);
mm.addFunction(__sceSasCoreWithMixFunction, 0x50A14DFC);
mm.addFunction(__sceSasSetSLFunction, 0x5F9529F6);
mm.addFunction(__sceSasGetEndFlagFunction, 0x68A46B95);
mm.addFunction(__sceSasGetEnvelopeHeightFunction, 0x74AE582A);
mm.addFunction(__sceSasSetKeyOnFunction, 0x76F01ACA);
mm.addFunction(__sceSasSetPauseFunction, 0x787D04D5);
mm.addFunction(__sceSasSetVoiceFunction, 0x99944089);
mm.addFunction(__sceSasSetADSRmodeFunction, 0x9EC3676A);
mm.addFunction(__sceSasSetKeyOffFunction, 0xA0CF2FA4);
mm.addFunction(__sceSasSetTrianglarWaveFunction, 0xA232CBE6);
mm.addFunction(__sceSasCoreFunction, 0xA3589D81);
mm.addFunction(__sceSasSetPitchFunction, 0xAD84D37F);
mm.addFunction(__sceSasSetNoiseFunction, 0xB7660A23);
mm.addFunction(__sceSasGetGrainFunction, 0xBD11B7C2);
mm.addFunction(__sceSasSetSimpleADSRFunction, 0xCBCD4F79);
mm.addFunction(__sceSasSetGrainFunction, 0xD1E0A01E);
mm.addFunction(__sceSasRevEVOLFunction, 0xD5A229C9);
mm.addFunction(__sceSasSetSteepWaveFunction, 0xD5EBBBCD);
mm.addFunction(__sceSasGetOutputmodeFunction, 0xE175EF66);
mm.addFunction(__sceSasSetOutputmodeFunction, 0xE855BF76);
mm.addFunction(__sceSasRevVONFunction, 0xF983B186);
}
sasCoreUid = -1;
sampleRate = 48000;
voices = new pspVoice[32];
for (int i = 0; i < voices.length; i++) {
voices[i] = new pspVoice();
}
if (voicesCheckerThread == null) {
voicesCheckerThread = new VoicesCheckerThread(500);
voicesCheckerThread.setDaemon(true);
voicesCheckerThread.setName("sceSasCore Voices Checker");
voicesCheckerThread.start();
}
}
@Override
public void uninstallModule(HLEModuleManager mm, int version) {
if (version >= 150) {
mm.removeFunction(__sceSasSetADSRFunction);
mm.removeFunction(__sceSasRevParamFunction);
mm.removeFunction(__sceSasGetPauseFlagFunction);
mm.removeFunction(__sceSasRevTypeFunction);
mm.removeFunction(__sceSasInitFunction);
mm.removeFunction(__sceSasSetVolumeFunction);
mm.removeFunction(__sceSasCoreWithMixFunction);
mm.removeFunction(__sceSasSetSLFunction);
mm.removeFunction(__sceSasGetEndFlagFunction);
mm.removeFunction(__sceSasGetEnvelopeHeightFunction);
mm.removeFunction(__sceSasSetKeyOnFunction);
mm.removeFunction(__sceSasSetPauseFunction);
mm.removeFunction(__sceSasSetVoiceFunction);
mm.removeFunction(__sceSasSetADSRmodeFunction);
mm.removeFunction(__sceSasSetKeyOffFunction);
mm.removeFunction(__sceSasSetTrianglarWaveFunction);
mm.removeFunction(__sceSasCoreFunction);
mm.removeFunction(__sceSasSetPitchFunction);
mm.removeFunction(__sceSasSetNoiseFunction);
mm.removeFunction(__sceSasGetGrainFunction);
mm.removeFunction(__sceSasSetSimpleADSRFunction);
mm.removeFunction(__sceSasSetGrainFunction);
mm.removeFunction(__sceSasRevEVOLFunction);
mm.removeFunction(__sceSasSetSteepWaveFunction);
mm.removeFunction(__sceSasGetOutputmodeFunction);
mm.removeFunction(__sceSasSetOutputmodeFunction);
mm.removeFunction(__sceSasRevVONFunction);
}
}
protected class pspVoice {
public SourceDataLine outputDataLine;
public float outputDataLineSampleRate;
public int leftVolume;
public int rightVolume;
public short[] samples;
public int loopMode;
public int pitch;
public final int NORMAL_PITCH = 0x1000;
public byte[] buffer;
public int bufferIndex;
public pspVoice() {
outputDataLine = null;
leftVolume = 0x8000;
rightVolume = 0x8000;
samples = null;
loopMode = 0;
pitch = NORMAL_PITCH;
buffer = null;
bufferIndex = 0;
}
private float getSampleRate() {
return (sampleRate * pitch) / (float) NORMAL_PITCH;
}
private void init() {
float wantedSampleRate = getSampleRate();
int wantedBufferSize = 0;
if (samples != null) {
wantedBufferSize = samples.length * 4;
} else {
wantedBufferSize = outputDataLine.getBufferSize();
}
if (outputDataLine == null || wantedSampleRate != outputDataLineSampleRate || wantedBufferSize > outputDataLine.getBufferSize()) {
if (outputDataLine != null) {
outputDataLine.close();
outputDataLine = null;
}
try {
AudioFormat format = new AudioFormat(wantedSampleRate, 16, 2, true, false);
outputDataLine = AudioSystem.getSourceDataLine(format);
outputDataLineSampleRate = wantedSampleRate;
if (!audioMuted) {
if (wantedBufferSize > 0) {
outputDataLine.open(format, wantedBufferSize);
} else {
outputDataLine.open(format);
}
}
} catch (LineUnavailableException e) {
Modules.log.error("sceSasCore.pspVoice.init: " + e.toString());
}
}
}
public synchronized int on() {
init();
if (samples != null) {
outputDataLine.stop();
buffer = encodeSamples();
int length = Math.min(outputDataLine.available(), buffer.length);
bufferIndex = length;
outputDataLine.write(buffer, 0, length);
outputDataLine.start();
}
return 0; // TODO Check the return value
}
public synchronized int off() {
if (outputDataLine != null) {
outputDataLine.stop();
}
return 0; // TODO Check the return value
}
public synchronized boolean IsEnded() {
if (outputDataLine == null) {
return true;
}
if (!outputDataLine.isRunning()) {
return true;
}
if (buffer != null && bufferIndex < buffer.length) {
return false;
}
if (outputDataLine.available() >= outputDataLine.getBufferSize()) {
return true;
}
return false;
}
private byte[] encodeSamples() {
int numSamples = samples.length;
byte[] buffer = new byte[numSamples * 4];
for (int i = 0; i < numSamples; i++) {
short sample = samples[i];
short lval = (short) ((sample * leftVolume ) >> 16);
short rval = (short) ((sample * rightVolume) >> 16);
buffer[i*4+0] = (byte) (lval);
buffer[i*4+1] = (byte) (lval >> 8);
buffer[i*4+2] = (byte) (rval);
buffer[i*4+3] = (byte) (rval >> 8);
}
return buffer;
}
public synchronized void check() {
if (outputDataLine == null || !outputDataLine.isActive() || buffer == null) {
return;
}
if (bufferIndex < buffer.length) {
int length = Math.min(outputDataLine.available(), buffer.length - bufferIndex);
if (length > 0) {
outputDataLine.write(buffer, bufferIndex, length);
bufferIndex += length;
}
} else if (IsEnded()) {
outputDataLine.stop();
}
}
}
protected class VoicesCheckerThread extends Thread {
private long delayMillis;
public VoicesCheckerThread(long delayMillis) {
this.delayMillis = delayMillis;
}
@Override
public void run() {
while (true) {
for (int i = 0; i < voices.length; i++) {
voices[i].check();
}
try {
sleep(delayMillis);
} catch (InterruptedException e) {
// Ignore the Exception
}
}
}
}
private static VoicesCheckerThread voicesCheckerThread = null;
protected int sasCoreUid;
protected pspVoice[] voices;
protected int sampleRate;
protected boolean audioMuted;
public void setAudioMuted(boolean muted) {
audioMuted = muted;
}
protected String makeLogParams(CpuState cpu) {
return String.format("%08x %08x %08x %08x",
cpu.gpr[4], cpu.gpr[5], cpu.gpr[6], cpu.gpr[7]);
}
/** If sasCore isn't a valid handle this function will print a log message and set $v0 to -1.
* @return true if sasCore is good. */
protected boolean isSasHandleGood(int sasCore, String functionName, CpuState cpu) {
if (Processor.memory.isAddressGood(sasCore)) {
if (Processor.memory.read32(sasCore) == sasCoreUid) {
return true;
} else {
Modules.log.warn(functionName + " bad sasCoreUid 0x" + Integer.toHexString(Processor.memory.read32(sasCore)));
}
} else {
Modules.log.warn(functionName + " bad sasCore Address 0x" + Integer.toHexString(sasCore));
}
cpu.gpr[2] = -1;
return false;
}
protected boolean isVoiceNumberGood(int voice, String functionName, CpuState cpu) {
if (voice >= 0 && voice < voices.length) {
return true;
}
Modules.log.warn(functionName + " bad voice number " + voice);
cpu.gpr[2] = -1;
return false;
}
public void __sceSasSetADSR(Processor processor) {
CpuState cpu = processor.cpu; // New-Style Processor
// Processor cpu = processor; // Old-Style Processor
Memory mem = Processor.memory;
/* put your own code here instead */
int sasCore = cpu.gpr[4];
int voice = cpu.gpr[5];
//int unk2 = cpu.gpr[6]; // 8, 0xf
//int unk3 = cpu.gpr[7]; // 0, 0x40000000
//int unk4 = cpu.gpr[8]; // 0x64
//int unk5 = cpu.gpr[9]; // 0x64
//int unk6 = cpu.gpr[10]; // 0x10000000
Modules.log.warn("Unimplemented NID function __sceSasSetADSR [0x019B25EB] "
+ String.format("sasCore=%08x, voice=%d %08x %08x %08x %08x %08x",
sasCore, voice, cpu.gpr[6], cpu.gpr[7], cpu.gpr[8], cpu.gpr[9], cpu.gpr[10]));
cpu.gpr[2] = 0xDEADC0DE;
// cpu.gpr[2] = (int)(result & 0xffffffff); cpu.gpr[3] = (int)(result >>> 32); cpu.fpr[0] = result;
}
public void __sceSasRevParam(Processor processor) {
CpuState cpu = processor.cpu; // New-Style Processor
// Processor cpu = processor; // Old-Style Processor
Memory mem = Processor.memory;
/* put your own code here instead */
int sasCore = cpu.gpr[4];
int unk1 = cpu.gpr[5]; // 0, 64
int unk2 = cpu.gpr[6]; // 0, 64
// 99% sure there are no more parameters
Modules.log.warn("IGNORING:__sceSasRevParam("
+ String.format("sasCore=0x%08x,unk1=0x%x,unk2=0x%x)", sasCore, unk1, unk2));
cpu.gpr[2] = 0;
}
// we could do some trickery in here too
// 2C8E6AB3
public void __sceSasGetPauseFlag(Processor processor) {
CpuState cpu = processor.cpu; // New-Style Processor
// Processor cpu = processor; // Old-Style Processor
Memory mem = Processor.memory;
int sasCore = cpu.gpr[4];
//int unk1 = cpu.gpr[5]; // set to 1, if this matches __sceSasSetPause then it's a voice bitfield
//int unk2 = cpu.gpr[6]; // looks like a heap address, but so far 0x10000 aligned
// 99% sure there are no more parameters
// probably matches __sceSasGetEndFlag
Modules.log.debug("IGNORING:__sceSasGetPauseFlag(sasCore=0x" + Integer.toHexString(sasCore) + ") " + makeLogParams(cpu));
if (isSasHandleGood(sasCore, "__sceSasGetPauseFlag", cpu)) {
// Fake all voices NOT paused
cpu.gpr[2] = 0x0;
}
}
public void __sceSasRevType(Processor processor) {
CpuState cpu = processor.cpu; // New-Style Processor
// Processor cpu = processor; // Old-Style Processor
Memory mem = Processor.memory;
/* put your own code here instead */
int sasCore = cpu.gpr[4];
// -1 = any?
// 0 = ?
// 1 = ?
// 2 = ?
// 3 = ?
// 4 = ?
// 5 = ?
// 6 = ?
int type = cpu.gpr[5];
//int unk2 = cpu.gpr[6]; // unused or 1 or the return code from some other function (0xdeadc0de)
//int unk3 = cpu.gpr[7]; // unused or 0, 1, 0x1000
Modules.log.warn("IGNORING:__sceSasRevType(type=" + type + ") " + makeLogParams(cpu));
cpu.gpr[2] = 0;
}
public void __sceSasInit(Processor processor) {
CpuState cpu = processor.cpu;
Memory mem = Processor.memory;
int sasCore = cpu.gpr[4];
// int unk1 = cpu.gpr[5]; // 0x00000100
// int unk2 = cpu.gpr[6]; // 0x00000020
// int unk3 = cpu.gpr[7]; // 0x00000000
int sampleRate = cpu.gpr[8]; // 0x0000AC44 (44100 Hz)
// 100% sure there are no more parameters
Modules.log.info("PARTIAL __sceSasInit: "
+ String.format("sasCore=0x%08x, unk1=0x%08x, unk2=0x%08x, unk3=0x%08x, sampleRate=%d",
sasCore, cpu.gpr[5], cpu.gpr[6], cpu.gpr[7], sampleRate));
// we'll support only 1 sascore instance at a time, we can fix this later if needed
if (sasCoreUid != -1) {
Modules.log.warn("UNIMPLEMENTED:__sceSasInit multiple instances not yet supported");
cpu.gpr[2] = -1;
} else {
if (mem.isAddressGood(sasCore)) {
sasCoreUid = SceUidManager.getNewUid("sceMpeg-Mpeg");
mem.write32(sasCore, sasCoreUid);
}
this.sampleRate = sampleRate;
cpu.gpr[2] = 0;
}
}
public void __sceSasSetVolume(Processor processor) {
CpuState cpu = processor.cpu;
int sasCore = cpu.gpr[4];
int voice = cpu.gpr[5];
int leftVolume = cpu.gpr[6]; // left channel volume 0 - 0x1000
int rightVolume = cpu.gpr[7]; // right channel volume 0 - 0x1000
if (isSasHandleGood(sasCore, "__sceSasSetVolume", cpu) && isVoiceNumberGood(voice, "__sceSasSetVolume", cpu)) {
voices[voice].leftVolume = leftVolume << 3; // 0 - 0x8000
voices[voice].rightVolume = rightVolume << 3; // 0 - 0x8000
cpu.gpr[2] = 0;
}
}
// 50A14DFC
public void __sceSasCoreWithMix(Processor processor) {
CpuState cpu = processor.cpu; // New-Style Processor
// Processor cpu = processor; // Old-Style Processor
Memory mem = Processor.memory;
int sasCore = cpu.gpr[4];
//int unk1 = cpu.gpr[5]; // looks like a heap address
//int unk2 = cpu.gpr[6]; // looks like a bitfield
Modules.log.debug("IGNORING:__sceSasCoreWithMix " + makeLogParams(cpu));
if (isSasHandleGood(sasCore, "__sceSasCoreWithMix", cpu)) {
// nothing to do ... ?
cpu.gpr[2] = 0;
}
}
public void __sceSasSetSL(Processor processor) {
CpuState cpu = processor.cpu; // New-Style Processor
// Processor cpu = processor; // Old-Style Processor
Memory mem = Processor.memory;
/* put your own code here instead */
// int a0 = cpu.gpr[4]; int a1 = cpu.gpr[5]; ... int t3 = cpu.gpr[11];
// float f12 = cpu.fpr[12]; float f13 = cpu.fpr[13]; ... float f19 = cpu.fpr[19];
Modules.log.warn("Unimplemented NID function __sceSasSetSL [0x5F9529F6] " + makeLogParams(cpu));
cpu.gpr[2] = 0xDEADC0DE;
// cpu.gpr[2] = (int)(result & 0xffffffff); cpu.gpr[3] = (int)(result >>> 32); cpu.fpr[0] = result;
}
// 68A46B95
public void __sceSasGetEndFlag(Processor processor) {
CpuState cpu = processor.cpu; // New-Style Processor
// Processor cpu = processor; // Old-Style Processor
int sasCore = cpu.gpr[4];
// 99% sure there are no more parameters
if (isSasHandleGood(sasCore, "__sceSasGetEndFlag", cpu)) {
// Returns a 32 bits bitfield (tested using "if (result & (1 << n))")
int endFlag = 0;
for (int i = 0; i < voices.length; i++) {
if (voices[i].IsEnded()) {
endFlag |= (1 << i);
}
}
Modules.log.info("__sceSasGetEndFlag(sasCore=0x" + Integer.toHexString(sasCore) + "): 0x" + Integer.toHexString(endFlag));
cpu.gpr[2] = endFlag;
}
}
public void __sceSasGetEnvelopeHeight(Processor processor) {
CpuState cpu = processor.cpu; // New-Style Processor
// Processor cpu = processor; // Old-Style Processor
Memory mem = Processor.memory;
/* put your own code here instead */
int sasCore = cpu.gpr[4];
int voice = cpu.gpr[5];
int unk1 = cpu.gpr[6]; // set to 1
// 99% sure there are no more parameters
Modules.log.warn("IGNORING:__sceSasGetEnvelopeHeight(sasCore=0x" + Integer.toHexString(sasCore) + ",voice=" + voice + ",unk1=0x" + Integer.toHexString(unk1) + ")");
cpu.gpr[2] = 0xDEADC0DE;
}
// I think this means start playing this channel, key off would then mean stop or pause the playback (fiveofhearts)
public void __sceSasSetKeyOn(Processor processor) {
CpuState cpu = processor.cpu;
int sasCore = cpu.gpr[4];
int voice = cpu.gpr[5];
Modules.log.info("PARTIAL __sceSasSetKeyOn: "
+ String.format("sasCore=%08x, voice=%d",
sasCore, voice));
if (isSasHandleGood(sasCore, "__sceSasSetKeyOn", cpu) && isVoiceNumberGood(voice, "__sceSasSetKeyOn", cpu)) {
cpu.gpr[2] = voices[voice].on();
}
}
public void __sceSasSetPause(Processor processor) {
CpuState cpu = processor.cpu; // New-Style Processor
Memory mem = Processor.memory;
/* put your own code here instead */
int sasCore = cpu.gpr[4];
int voice_bit = cpu.gpr[5]; // bitfield instead of index, example: 0x08 is voice 3
int pause = cpu.gpr[6]; // 0
Modules.log.warn("Unimplemented NID function __sceSasSetPause [0x787D04D5] " + makeLogParams(cpu));
cpu.gpr[2] = 0xDEADC0DE;
}
protected short[] decodeSamples(Processor processor, int vagAddr, int size) {
Memory mem = Processor.memory;
// Based on vgmstream
short[] samples = new short[size / 16 * 28];
int numSamples = 0;
int headerCheck = mem.read32(vagAddr);
if ((headerCheck & 0x00FFFFFF) == 0x00474156) { // VAGx
vagAddr += 0x30; // Skip the VAG header
}
int[] unpackedSamples = new int[28];
int hist1 = 0;
int hist2 = 0;
final double[][] VAG_f = {
{ 0.0 , 0.0 },
{ 60.0 / 64.0, 0.0 },
{ 115.0 / 64.0, -52.0 / 64.0 },
{ 98.0 / 64.0, -55.0 / 64.0 },
{ 122.0 / 64.0, -60.0 / 64.0 }
};
for (int i = 0; i <= (size - 16); ) {
int n = mem.read8(vagAddr + i);
i++;
int predict_nr = n >> 4;
+ if (predict_nr >= VAG_f.length) {
+ // predict_nr is supposed to be included in [0..4].
+ // TODO The game "Tenchu: TOTA" is using a value "predict_nr = 7", I could not find out how this value should be interpreted...
+ Modules.log.warn("sceSasCore.decodeSamples: Unknown value for predict_nr: " + predict_nr);
+ // Avoid ArrayIndexOutOfBoundsException
+ predict_nr = 0;
+ }
int shift_factor = n & 0x0F;
int flag = mem.read8(vagAddr + i);
i++;
if (flag == 0x07) {
break; // End of stream flag
}
for (int j = 0; j < 28; j += 2) {
int d = mem.read8(vagAddr + i);
i++;
int s = (short) ((d & 0x0F) << 12);
unpackedSamples[j] = s >> shift_factor;
s = (short) ((d & 0xF0) << 8);
unpackedSamples[j + 1] = s >> shift_factor;
}
for (int j = 0; j < 28; j++) {
int sample = (int) (unpackedSamples[j] + hist1 * VAG_f[predict_nr][0] + hist2 * VAG_f[predict_nr][1]);
hist2 = hist1;
hist1 = sample;
if (sample < -32768) {
samples[numSamples] = -32768;
} else if (sample > 0x7FFF) {
samples[numSamples] = 0x7FFF;
} else {
samples[numSamples] = (short) sample;
}
numSamples++;
}
}
if (samples.length != numSamples) {
short[] resizedSamples = new short[numSamples];
for (int i = 0; i < numSamples; i++) {
resizedSamples[i] = samples[i];
}
samples = resizedSamples;
}
return samples;
}
public void __sceSasSetVoice(Processor processor) {
CpuState cpu = processor.cpu; // New-Style Processor
Memory mem = Processor.memory;
int sasCore = cpu.gpr[4];
int voice = cpu.gpr[5];
int vagAddr = cpu.gpr[6]; // may have uncached bit set
int size = cpu.gpr[7];
int loopmode = cpu.gpr[8];
Modules.log.info("PARTIAL __sceSasSetVoice: "
+ String.format("sasCore=0x%08x, voice=%d, vagAddr=0x%08x, size=0x%08x, loopmode=%d",
sasCore, voice, vagAddr, size, loopmode));
if (isSasHandleGood(sasCore, "__sceSasSetVoice", cpu) && isVoiceNumberGood(voice, "__sceSasSetVoice", cpu)) {
voices[voice].samples = decodeSamples(processor, vagAddr, size);
voices[voice].loopMode = loopmode;
cpu.gpr[2] = 0;
}
}
public void __sceSasSetADSRmode(Processor processor) {
CpuState cpu = processor.cpu; // New-Style Processor
// Processor cpu = processor; // Old-Style Processor
Memory mem = Processor.memory;
/* put your own code here instead */
int sasCore = cpu.gpr[4];
int voice = cpu.gpr[5];
//int unk2 = cpu.gpr[6]; // 8/0xf
//int unk3 = cpu.gpr[7]; // 0
// may be more parameters
Modules.log.warn("Unimplemented NID function __sceSasSetADSRmode [0x9EC3676A] "
+ String.format("%08x %08x %08x %08x %08x %08x",
cpu.gpr[4], cpu.gpr[5], cpu.gpr[6], cpu.gpr[7], cpu.gpr[8], cpu.gpr[9]));
cpu.gpr[2] = 0xDEADC0DE;
// cpu.gpr[2] = (int)(result & 0xffffffff); cpu.gpr[3] = (int)(result >>> 32); cpu.fpr[0] = result;
}
public void __sceSasSetKeyOff(Processor processor) {
CpuState cpu = processor.cpu;
int sasCore = cpu.gpr[4];
int voice = cpu.gpr[5];
Modules.log.info("PARTIAL __sceSasSetKeyOff: "
+ String.format("sasCore=%08x, voice=%d",
sasCore, voice));
if (isSasHandleGood(sasCore, "__sceSasSetKeyOff", cpu) && isVoiceNumberGood(voice, "__sceSasSetKeyOff", cpu)) {
cpu.gpr[2] = voices[voice].off();
}
}
public void __sceSasSetTrianglarWave(Processor processor) {
CpuState cpu = processor.cpu; // New-Style Processor
// Processor cpu = processor; // Old-Style Processor
Memory mem = Processor.memory;
/* put your own code here instead */
// int a0 = cpu.gpr[4]; int a1 = cpu.gpr[5]; ... int t3 = cpu.gpr[11];
// float f12 = cpu.fpr[12]; float f13 = cpu.fpr[13]; ... float f19 = cpu.fpr[19];
Modules.log.warn("Unimplemented NID function __sceSasSetTrianglarWave [0xA232CBE6] " + makeLogParams(cpu));
cpu.gpr[2] = 0xDEADC0DE;
// cpu.gpr[2] = (int)(result & 0xffffffff); cpu.gpr[3] = (int)(result >>> 32); cpu.fpr[0] = result;
}
// A3589D81
public void __sceSasCore(Processor processor) {
CpuState cpu = processor.cpu; // New-Style Processor
// Processor cpu = processor; // Old-Style Processor
int sasCore = cpu.gpr[4];
//int unk1 = cpu.gpr[5]; // looks like a heap address, bss, 0x40 aligned
// 99% sure there are no more parameters
Modules.log.debug("IGNORING:__sceSasCore " + makeLogParams(cpu));
if (isSasHandleGood(sasCore, "__sceSasCore", cpu)) {
// noxa/pspplayer blocks in __sceSasCore
// some games protect __sceSasCore with locks, suggesting it may context switch.
// Games seems to run better when delaying the thread instead of just yielding.
cpu.gpr[2] = 0;
ThreadMan.getInstance().hleKernelDelayThread(1000000, false);
// ThreadMan.getInstance().yieldCurrentThread();
}
}
public void __sceSasSetPitch(Processor processor) {
CpuState cpu = processor.cpu;
int sasCore = cpu.gpr[4];
int voice = cpu.gpr[5];
int pitch = cpu.gpr[6]; // 0x6e4/0x800/0x1000/0x2000 large values may be clamped
Modules.log.info("PARTIAL __sceSasSetPitch: "
+ String.format("sasCore=%08x, voice=%d, pitch=0x%04x",
sasCore, voice, pitch));
if (isSasHandleGood(sasCore, "__sceSasSetPitch", cpu) && isVoiceNumberGood(voice, "__sceSasSetPitch", cpu)) {
voices[voice].pitch = pitch;
cpu.gpr[2] = 0;
}
}
public void __sceSasSetNoise(Processor processor) {
CpuState cpu = processor.cpu; // New-Style Processor
// Processor cpu = processor; // Old-Style Processor
Memory mem = Processor.memory;
/* put your own code here instead */
// int a0 = cpu.gpr[4]; int a1 = cpu.gpr[5]; ... int t3 = cpu.gpr[11];
// float f12 = cpu.fpr[12]; float f13 = cpu.fpr[13]; ... float f19 = cpu.fpr[19];
Modules.log.warn("Unimplemented NID function __sceSasSetNoise [0xB7660A23] " + makeLogParams(cpu));
cpu.gpr[2] = 0xDEADC0DE;
// cpu.gpr[2] = (int)(result & 0xffffffff); cpu.gpr[3] = (int)(result >>> 32); cpu.fpr[0] = result;
}
public void __sceSasGetGrain(Processor processor) {
CpuState cpu = processor.cpu; // New-Style Processor
// Processor cpu = processor; // Old-Style Processor
Memory mem = Processor.memory;
/* put your own code here instead */
// int a0 = cpu.gpr[4]; int a1 = cpu.gpr[5]; ... int t3 = cpu.gpr[11];
// float f12 = cpu.fpr[12]; float f13 = cpu.fpr[13]; ... float f19 = cpu.fpr[19];
Modules.log.warn("Unimplemented NID function __sceSasGetGrain [0xBD11B7C2] " + makeLogParams(cpu));
cpu.gpr[2] = 0xDEADC0DE;
// cpu.gpr[2] = (int)(result & 0xffffffff); cpu.gpr[3] = (int)(result >>> 32); cpu.fpr[0] = result;
}
public void __sceSasSetSimpleADSR(Processor processor) {
CpuState cpu = processor.cpu; // New-Style Processor
// Processor cpu = processor; // Old-Style Processor
Memory mem = Processor.memory;
/* put your own code here instead */
int sasCore = cpu.gpr[4];
int voice = cpu.gpr[5];
//int unk1 = cpu.gpr[6]; // 0xff
//int unk2 = cpu.gpr[7]; // 0x1fc6
// doesn't look like any more parameters, they look like error codes
Modules.log.warn("Unimplemented NID function __sceSasSetSimpleADSR [0xCBCD4F79] "
+ String.format("%08x %08x %08x %08x %08x %08x",
cpu.gpr[4], cpu.gpr[5], cpu.gpr[6], cpu.gpr[7], cpu.gpr[8], cpu.gpr[9]));
cpu.gpr[2] = 0xDEADC0DE;
// cpu.gpr[2] = (int)(result & 0xffffffff); cpu.gpr[3] = (int)(result >>> 32); cpu.fpr[0] = result;
}
public void __sceSasSetGrain(Processor processor) {
CpuState cpu = processor.cpu; // New-Style Processor
// Processor cpu = processor; // Old-Style Processor
Memory mem = Processor.memory;
int sasCore = cpu.gpr[4];
int grain = cpu.gpr[5]; // 0x400
Modules.log.warn("Unimplemented NID function __sceSasSetGrain [0xD1E0A01E] " + makeLogParams(cpu));
cpu.gpr[2] = 0xDEADC0DE;
}
public void __sceSasRevEVOL(Processor processor) {
CpuState cpu = processor.cpu; // New-Style Processor
// Processor cpu = processor; // Old-Style Processor
int sasCore = cpu.gpr[4];
int left = cpu.gpr[5]; // left channel volume 0 - 0x1000
int right = cpu.gpr[6]; // right channel volume 0 - 0x1000
Modules.log.debug("IGNORING:__sceSasRevEVOL("
+ String.format("sasCore=0x%08x,left=0x%04x,right=0x%04x)", sasCore, left, right));
cpu.gpr[2] = 0;
}
public void __sceSasSetSteepWave(Processor processor) {
CpuState cpu = processor.cpu; // New-Style Processor
// Processor cpu = processor; // Old-Style Processor
Memory mem = Processor.memory;
/* put your own code here instead */
// int a0 = cpu.gpr[4]; int a1 = cpu.gpr[5]; ... int t3 = cpu.gpr[11];
// float f12 = cpu.fpr[12]; float f13 = cpu.fpr[13]; ... float f19 = cpu.fpr[19];
Modules.log.warn("Unimplemented NID function __sceSasSetSteepWave [0xD5EBBBCD] " + makeLogParams(cpu));
cpu.gpr[2] = 0xDEADC0DE;
// cpu.gpr[2] = (int)(result & 0xffffffff); cpu.gpr[3] = (int)(result >>> 32); cpu.fpr[0] = result;
}
public void __sceSasGetOutputmode(Processor processor) {
CpuState cpu = processor.cpu; // New-Style Processor
// Processor cpu = processor; // Old-Style Processor
Memory mem = Processor.memory;
int sasCore = cpu.gpr[4];
//int unk1 = cpu.gpr[5]; // 0, 1 (most common), 0x1f
// 99% sure there are no more parameters
Modules.log.warn("Unimplemented NID function __sceSasGetOutputmode [0xE175EF66] " + makeLogParams(cpu));
// beq t0 (t0=1)
cpu.gpr[2] = 0xDEADC0DE;
// cpu.gpr[2] = (int)(result & 0xffffffff); cpu.gpr[3] = (int)(result >>> 32); cpu.fpr[0] = result;
}
public void __sceSasSetOutputmode(Processor processor) {
CpuState cpu = processor.cpu; // New-Style Processor
// Processor cpu = processor; // Old-Style Processor
Memory mem = Processor.memory;
/* put your own code here instead */
// int a0 = cpu.gpr[4]; int a1 = cpu.gpr[5]; ... int t3 = cpu.gpr[11];
// float f12 = cpu.fpr[12]; float f13 = cpu.fpr[13]; ... float f19 = cpu.fpr[19];
Modules.log.warn("Unimplemented NID function __sceSasSetOutputmode [0xE855BF76] " + makeLogParams(cpu));
cpu.gpr[2] = 0xDEADC0DE;
// cpu.gpr[2] = (int)(result & 0xffffffff); cpu.gpr[3] = (int)(result >>> 32); cpu.fpr[0] = result;
}
public void __sceSasRevVON(Processor processor) {
CpuState cpu = processor.cpu; // New-Style Processor
// Processor cpu = processor; // Old-Style Processor
int sasCore = cpu.gpr[4];
int unk1 = cpu.gpr[5]; // set to 1
int unk2 = cpu.gpr[6]; // 0 or 1
// 99% sure there are no more parameters
Modules.log.debug("IGNORING:__sceSasRevVON("
+ String.format("sasCore=0x%08x,unk1=0x%x,unk2=0x%x)", sasCore, unk1, unk2));
cpu.gpr[2] = 0;
}
public final HLEModuleFunction __sceSasSetADSRFunction = new HLEModuleFunction("sceSasCore", "__sceSasSetADSR") {
@Override
public final void execute(Processor processor) {
__sceSasSetADSR(processor);
}
@Override
public final String compiledString() {
return "jpcsp.HLE.Modules.sceSasCoreModule.__sceSasSetADSR(processor);";
}
};
public final HLEModuleFunction __sceSasRevParamFunction = new HLEModuleFunction("sceSasCore", "__sceSasRevParam") {
@Override
public final void execute(Processor processor) {
__sceSasRevParam(processor);
}
@Override
public final String compiledString() {
return "jpcsp.HLE.Modules.sceSasCoreModule.__sceSasRevParam(processor);";
}
};
public final HLEModuleFunction __sceSasGetPauseFlagFunction = new HLEModuleFunction("sceSasCore", "__sceSasGetPauseFlag") {
@Override
public final void execute(Processor processor) {
__sceSasGetPauseFlag(processor);
}
@Override
public final String compiledString() {
return "jpcsp.HLE.Modules.sceSasCoreModule.__sceSasGetPauseFlag(processor);";
}
};
public final HLEModuleFunction __sceSasRevTypeFunction = new HLEModuleFunction("sceSasCore", "__sceSasRevType") {
@Override
public final void execute(Processor processor) {
__sceSasRevType(processor);
}
@Override
public final String compiledString() {
return "jpcsp.HLE.Modules.sceSasCoreModule.__sceSasRevType(processor);";
}
};
public final HLEModuleFunction __sceSasInitFunction = new HLEModuleFunction("sceSasCore", "__sceSasInit") {
@Override
public final void execute(Processor processor) {
__sceSasInit(processor);
}
@Override
public final String compiledString() {
return "jpcsp.HLE.Modules.sceSasCoreModule.__sceSasInit(processor);";
}
};
public final HLEModuleFunction __sceSasSetVolumeFunction = new HLEModuleFunction("sceSasCore", "__sceSasSetVolume") {
@Override
public final void execute(Processor processor) {
__sceSasSetVolume(processor);
}
@Override
public final String compiledString() {
return "jpcsp.HLE.Modules.sceSasCoreModule.__sceSasSetVolume(processor);";
}
};
public final HLEModuleFunction __sceSasCoreWithMixFunction = new HLEModuleFunction("sceSasCore", "__sceSasCoreWithMix") {
@Override
public final void execute(Processor processor) {
__sceSasCoreWithMix(processor);
}
@Override
public final String compiledString() {
return "jpcsp.HLE.Modules.sceSasCoreModule.__sceSasCoreWithMix(processor);";
}
};
public final HLEModuleFunction __sceSasSetSLFunction = new HLEModuleFunction("sceSasCore", "__sceSasSetSL") {
@Override
public final void execute(Processor processor) {
__sceSasSetSL(processor);
}
@Override
public final String compiledString() {
return "jpcsp.HLE.Modules.sceSasCoreModule.__sceSasSetSL(processor);";
}
};
public final HLEModuleFunction __sceSasGetEndFlagFunction = new HLEModuleFunction("sceSasCore", "__sceSasGetEndFlag") {
@Override
public final void execute(Processor processor) {
__sceSasGetEndFlag(processor);
}
@Override
public final String compiledString() {
return "jpcsp.HLE.Modules.sceSasCoreModule.__sceSasGetEndFlag(processor);";
}
};
public final HLEModuleFunction __sceSasGetEnvelopeHeightFunction = new HLEModuleFunction("sceSasCore", "__sceSasGetEnvelopeHeight") {
@Override
public final void execute(Processor processor) {
__sceSasGetEnvelopeHeight(processor);
}
@Override
public final String compiledString() {
return "jpcsp.HLE.Modules.sceSasCoreModule.__sceSasGetEnvelopeHeight(processor);";
}
};
public final HLEModuleFunction __sceSasSetKeyOnFunction = new HLEModuleFunction("sceSasCore", "__sceSasSetKeyOn") {
@Override
public final void execute(Processor processor) {
__sceSasSetKeyOn(processor);
}
@Override
public final String compiledString() {
return "jpcsp.HLE.Modules.sceSasCoreModule.__sceSasSetKeyOn(processor);";
}
};
public final HLEModuleFunction __sceSasSetPauseFunction = new HLEModuleFunction("sceSasCore", "__sceSasSetPause") {
@Override
public final void execute(Processor processor) {
__sceSasSetPause(processor);
}
@Override
public final String compiledString() {
return "jpcsp.HLE.Modules.sceSasCoreModule.__sceSasSetPause(processor);";
}
};
public final HLEModuleFunction __sceSasSetVoiceFunction = new HLEModuleFunction("sceSasCore", "__sceSasSetVoice") {
@Override
public final void execute(Processor processor) {
__sceSasSetVoice(processor);
}
@Override
public final String compiledString() {
return "jpcsp.HLE.Modules.sceSasCoreModule.__sceSasSetVoice(processor);";
}
};
public final HLEModuleFunction __sceSasSetADSRmodeFunction = new HLEModuleFunction("sceSasCore", "__sceSasSetADSRmode") {
@Override
public final void execute(Processor processor) {
__sceSasSetADSRmode(processor);
}
@Override
public final String compiledString() {
return "jpcsp.HLE.Modules.sceSasCoreModule.__sceSasSetADSRmode(processor);";
}
};
public final HLEModuleFunction __sceSasSetKeyOffFunction = new HLEModuleFunction("sceSasCore", "__sceSasSetKeyOff") {
@Override
public final void execute(Processor processor) {
__sceSasSetKeyOff(processor);
}
@Override
public final String compiledString() {
return "jpcsp.HLE.Modules.sceSasCoreModule.__sceSasSetKeyOff(processor);";
}
};
public final HLEModuleFunction __sceSasSetTrianglarWaveFunction = new HLEModuleFunction("sceSasCore", "__sceSasSetTrianglarWave") {
@Override
public final void execute(Processor processor) {
__sceSasSetTrianglarWave(processor);
}
@Override
public final String compiledString() {
return "jpcsp.HLE.Modules.sceSasCoreModule.__sceSasSetTrianglarWave(processor);";
}
};
public final HLEModuleFunction __sceSasCoreFunction = new HLEModuleFunction("sceSasCore", "__sceSasCore") {
@Override
public final void execute(Processor processor) {
__sceSasCore(processor);
}
@Override
public final String compiledString() {
return "jpcsp.HLE.Modules.sceSasCoreModule.__sceSasCore(processor);";
}
};
public final HLEModuleFunction __sceSasSetPitchFunction = new HLEModuleFunction("sceSasCore", "__sceSasSetPitch") {
@Override
public final void execute(Processor processor) {
__sceSasSetPitch(processor);
}
@Override
public final String compiledString() {
return "jpcsp.HLE.Modules.sceSasCoreModule.__sceSasSetPitch(processor);";
}
};
public final HLEModuleFunction __sceSasSetNoiseFunction = new HLEModuleFunction("sceSasCore", "__sceSasSetNoise") {
@Override
public final void execute(Processor processor) {
__sceSasSetNoise(processor);
}
@Override
public final String compiledString() {
return "jpcsp.HLE.Modules.sceSasCoreModule.__sceSasSetNoise(processor);";
}
};
public final HLEModuleFunction __sceSasGetGrainFunction = new HLEModuleFunction("sceSasCore", "__sceSasGetGrain") {
@Override
public final void execute(Processor processor) {
__sceSasGetGrain(processor);
}
@Override
public final String compiledString() {
return "jpcsp.HLE.Modules.sceSasCoreModule.__sceSasGetGrain(processor);";
}
};
public final HLEModuleFunction __sceSasSetSimpleADSRFunction = new HLEModuleFunction("sceSasCore", "__sceSasSetSimpleADSR") {
@Override
public final void execute(Processor processor) {
__sceSasSetSimpleADSR(processor);
}
@Override
public final String compiledString() {
return "jpcsp.HLE.Modules.sceSasCoreModule.__sceSasSetSimpleADSR(processor);";
}
};
public final HLEModuleFunction __sceSasSetGrainFunction = new HLEModuleFunction("sceSasCore", "__sceSasSetGrain") {
@Override
public final void execute(Processor processor) {
__sceSasSetGrain(processor);
}
@Override
public final String compiledString() {
return "jpcsp.HLE.Modules.sceSasCoreModule.__sceSasSetGrain(processor);";
}
};
public final HLEModuleFunction __sceSasRevEVOLFunction = new HLEModuleFunction("sceSasCore", "__sceSasRevEVOL") {
@Override
public final void execute(Processor processor) {
__sceSasRevEVOL(processor);
}
@Override
public final String compiledString() {
return "jpcsp.HLE.Modules.sceSasCoreModule.__sceSasRevEVOL(processor);";
}
};
public final HLEModuleFunction __sceSasSetSteepWaveFunction = new HLEModuleFunction("sceSasCore", "__sceSasSetSteepWave") {
@Override
public final void execute(Processor processor) {
__sceSasSetSteepWave(processor);
}
@Override
public final String compiledString() {
return "jpcsp.HLE.Modules.sceSasCoreModule.__sceSasSetSteepWave(processor);";
}
};
public final HLEModuleFunction __sceSasGetOutputmodeFunction = new HLEModuleFunction("sceSasCore", "__sceSasGetOutputmode") {
@Override
public final void execute(Processor processor) {
__sceSasGetOutputmode(processor);
}
@Override
public final String compiledString() {
return "jpcsp.HLE.Modules.sceSasCoreModule.__sceSasGetOutputmode(processor);";
}
};
public final HLEModuleFunction __sceSasSetOutputmodeFunction = new HLEModuleFunction("sceSasCore", "__sceSasSetOutputmode") {
@Override
public final void execute(Processor processor) {
__sceSasSetOutputmode(processor);
}
@Override
public final String compiledString() {
return "jpcsp.HLE.Modules.sceSasCoreModule.__sceSasSetOutputmode(processor);";
}
};
public final HLEModuleFunction __sceSasRevVONFunction = new HLEModuleFunction("sceSasCore", "__sceSasRevVON") {
@Override
public final void execute(Processor processor) {
__sceSasRevVON(processor);
}
@Override
public final String compiledString() {
return "jpcsp.HLE.Modules.sceSasCoreModule.__sceSasRevVON(processor);";
}
};
};
| true | true | protected short[] decodeSamples(Processor processor, int vagAddr, int size) {
Memory mem = Processor.memory;
// Based on vgmstream
short[] samples = new short[size / 16 * 28];
int numSamples = 0;
int headerCheck = mem.read32(vagAddr);
if ((headerCheck & 0x00FFFFFF) == 0x00474156) { // VAGx
vagAddr += 0x30; // Skip the VAG header
}
int[] unpackedSamples = new int[28];
int hist1 = 0;
int hist2 = 0;
final double[][] VAG_f = {
{ 0.0 , 0.0 },
{ 60.0 / 64.0, 0.0 },
{ 115.0 / 64.0, -52.0 / 64.0 },
{ 98.0 / 64.0, -55.0 / 64.0 },
{ 122.0 / 64.0, -60.0 / 64.0 }
};
for (int i = 0; i <= (size - 16); ) {
int n = mem.read8(vagAddr + i);
i++;
int predict_nr = n >> 4;
int shift_factor = n & 0x0F;
int flag = mem.read8(vagAddr + i);
i++;
if (flag == 0x07) {
break; // End of stream flag
}
for (int j = 0; j < 28; j += 2) {
int d = mem.read8(vagAddr + i);
i++;
int s = (short) ((d & 0x0F) << 12);
unpackedSamples[j] = s >> shift_factor;
s = (short) ((d & 0xF0) << 8);
unpackedSamples[j + 1] = s >> shift_factor;
}
for (int j = 0; j < 28; j++) {
int sample = (int) (unpackedSamples[j] + hist1 * VAG_f[predict_nr][0] + hist2 * VAG_f[predict_nr][1]);
hist2 = hist1;
hist1 = sample;
if (sample < -32768) {
samples[numSamples] = -32768;
} else if (sample > 0x7FFF) {
samples[numSamples] = 0x7FFF;
} else {
samples[numSamples] = (short) sample;
}
numSamples++;
}
}
if (samples.length != numSamples) {
short[] resizedSamples = new short[numSamples];
for (int i = 0; i < numSamples; i++) {
resizedSamples[i] = samples[i];
}
samples = resizedSamples;
}
return samples;
}
| protected short[] decodeSamples(Processor processor, int vagAddr, int size) {
Memory mem = Processor.memory;
// Based on vgmstream
short[] samples = new short[size / 16 * 28];
int numSamples = 0;
int headerCheck = mem.read32(vagAddr);
if ((headerCheck & 0x00FFFFFF) == 0x00474156) { // VAGx
vagAddr += 0x30; // Skip the VAG header
}
int[] unpackedSamples = new int[28];
int hist1 = 0;
int hist2 = 0;
final double[][] VAG_f = {
{ 0.0 , 0.0 },
{ 60.0 / 64.0, 0.0 },
{ 115.0 / 64.0, -52.0 / 64.0 },
{ 98.0 / 64.0, -55.0 / 64.0 },
{ 122.0 / 64.0, -60.0 / 64.0 }
};
for (int i = 0; i <= (size - 16); ) {
int n = mem.read8(vagAddr + i);
i++;
int predict_nr = n >> 4;
if (predict_nr >= VAG_f.length) {
// predict_nr is supposed to be included in [0..4].
// TODO The game "Tenchu: TOTA" is using a value "predict_nr = 7", I could not find out how this value should be interpreted...
Modules.log.warn("sceSasCore.decodeSamples: Unknown value for predict_nr: " + predict_nr);
// Avoid ArrayIndexOutOfBoundsException
predict_nr = 0;
}
int shift_factor = n & 0x0F;
int flag = mem.read8(vagAddr + i);
i++;
if (flag == 0x07) {
break; // End of stream flag
}
for (int j = 0; j < 28; j += 2) {
int d = mem.read8(vagAddr + i);
i++;
int s = (short) ((d & 0x0F) << 12);
unpackedSamples[j] = s >> shift_factor;
s = (short) ((d & 0xF0) << 8);
unpackedSamples[j + 1] = s >> shift_factor;
}
for (int j = 0; j < 28; j++) {
int sample = (int) (unpackedSamples[j] + hist1 * VAG_f[predict_nr][0] + hist2 * VAG_f[predict_nr][1]);
hist2 = hist1;
hist1 = sample;
if (sample < -32768) {
samples[numSamples] = -32768;
} else if (sample > 0x7FFF) {
samples[numSamples] = 0x7FFF;
} else {
samples[numSamples] = (short) sample;
}
numSamples++;
}
}
if (samples.length != numSamples) {
short[] resizedSamples = new short[numSamples];
for (int i = 0; i < numSamples; i++) {
resizedSamples[i] = samples[i];
}
samples = resizedSamples;
}
return samples;
}
|
diff --git a/src/org/cchmc/bmi/snpomics/annotation/interactive/HgvsProtName.java b/src/org/cchmc/bmi/snpomics/annotation/interactive/HgvsProtName.java
index 9f7b190..3bdae0b 100644
--- a/src/org/cchmc/bmi/snpomics/annotation/interactive/HgvsProtName.java
+++ b/src/org/cchmc/bmi/snpomics/annotation/interactive/HgvsProtName.java
@@ -1,269 +1,273 @@
package org.cchmc.bmi.snpomics.annotation.interactive;
import java.util.ArrayList;
import java.util.List;
import org.cchmc.bmi.snpomics.annotation.reference.TranscriptAnnotation;
import org.cchmc.bmi.snpomics.translation.AminoAcid;
public class HgvsProtName {
public HgvsProtName(TranscriptAnnotation tx) {
this.tx = tx;
name = null;
startCoord = 0;
ref = null;
alt = null;
extension = null;
isFrameshift = false;
}
public String getName() {
if (name == null)
buildName();
return name;
}
/**
* The coordinate of the first amino acid specified to setRef(). The initiating Met has coordinate
* 1, and then you count up. This is much easier than cDNA :)
* @param startCoord
*/
public void setStartCoord(int startCoord) {
this.startCoord = startCoord;
}
/**
* The reference allele (in amino acids), including the AA before and after the change.
* Do not extend beyond the coding sequence - so if the variation affects Met1, don't include
* the preceding AA.
*/
public void setRef(List<AminoAcid> ref) {
this.ref = ref;
}
/**
* The alternate allele corresponding to the same region as the ref allele. If the mutation
* is a frameshift, the alt allele should include translated sequence as far as possible (ie,
* to the end of transcription). The same is true if the mutation destroys a stop codon
* @param alt
*/
public void setAlt(List<AminoAcid> alt) {
this.alt = alt;
}
/**
* The protein sequence (for the reference) starting just after the allele set in setRef(). If
* setFrameshift(true) has been called, the allele specified in setAlt() should also include this
* DNA sequence (though it will of course be a different protein sequence due to the frameshift)
* @param ext
*/
public void setExtension(List<AminoAcid> ext) {
this.extension = ext;
}
public void setFrameshift(boolean isFrameshift) {
this.isFrameshift = isFrameshift;
}
private void buildName() {
if (startCoord == 0) {
name = "";
return;
}
/*
* Challenging cases:
*
* gCATga => gga
* A* => G
* p.Ala#_*#delinsGlyext*# (need to catch the readthrough and calculate the ext)
*
* caacgatcg => caTTGacgatcg
* QRS => H*RS
* p.Gln#delinsH*
*
* atgcgg => atCATgcgg
* MR => ?MR
* p.= (The insertion extends the UTR, but doesn't change the protein product)
*/
StringBuilder sb = new StringBuilder();
String protein = tx.getProtID();
if (protein != null && !protein.isEmpty()) {
sb.append(protein);
sb.append(":");
}
sb.append("p.(");
if (ref.equals(alt))
//Synonymous
sb.append("=");
else {
if (extension != null) {
ref.addAll(extension);
if (!isFrameshift) alt.addAll(extension);
}
//Find the region that actually changed
int leftFlank = 0;
int rightFlank = 0;
boolean isPotentialDuplicate = false;
while (leftFlank < ref.size() &&
leftFlank < alt.size() &&
ref.get(leftFlank) == alt.get(leftFlank)) {
leftFlank++;
}
while (rightFlank < ref.size() &&
rightFlank < alt.size() &&
ref.get(ref.size()-rightFlank-1) == alt.get(alt.size()-rightFlank-1)) {
rightFlank++;
}
//If a duplicating insertion is made (or a deletion from a rpt region),
//both leftFlank and rightFlank will go through the repeat region
//Ex:
//ABXXCD => ABXXXCD
//leftFlank and rightFlank will both be 4
if (leftFlank+rightFlank > ref.size() || leftFlank+rightFlank > alt.size()) {
rightFlank = Math.min(ref.size(), alt.size())-leftFlank;
if (alt.size() > ref.size()) isPotentialDuplicate = true;
}
//Now make a new list containing just the changes
//All of these manipulations are necessary because we need to know the flanking
//AAs for an insertion - otherwise, we could have just started with the change
List<AminoAcid> refAllele = new ArrayList<AminoAcid>(ref.subList(leftFlank, ref.size()-rightFlank));
List<AminoAcid> altAllele = new ArrayList<AminoAcid>(alt.subList(leftFlank, alt.size()-rightFlank));
String extType = "";
int extension = -1;
//Some of these special conditions can be caused by indels or substitutions,
//and we're worried about effect here, not cause.
//So identify some of the overarching conditions, and caress the extraneous data
//accordingly
if (!isFrameshift && refAllele.contains(AminoAcid.STOP)) {
//readthrough - everything after the old stop is unimportant, except that
//we need to find the new stop
if (altAllele.size() > 1) {
//We'll only report the first new amino acid (altAllele might be empty here, so the if is important!)
altAllele.clear();
altAllele.add(alt.get(leftFlank));
}
extType = "ext";
extension = alt.subList(leftFlank, alt.size()).indexOf(AminoAcid.STOP);
if (extension > 0) extension++; //If we found it, make it one-based
} else if (!altAllele.isEmpty() && altAllele.get(0) == AminoAcid.STOP) {
//nonsense - this is reported simply as a substitution, so just make sure
//that it looks like a subst when we get to it later. Importantly, if the first
//AA modified by frameshift is a stop, don't report it as a fs
if (refAllele.size() > 1) {
//Analogous to the modification to altAllele in the readthrough case
refAllele.clear();
refAllele.add(ref.get(leftFlank));
}
+ if (altAllele.size() > 1) {
+ altAllele.clear();
+ altAllele.add(alt.get(leftFlank));
+ }
} else if (!refAllele.isEmpty() && refAllele.get(0) == AminoAcid.MET && startCoord+leftFlank == 1) {
//start-loss
altAllele.clear();
if (refAllele.size() > 1)
refAllele.subList(1, refAllele.size()).clear();
} else if (isFrameshift) {
if (refAllele.size() > 1) {
refAllele.clear();
refAllele.add(ref.get(leftFlank));
}
if (altAllele.size() > 1) {
altAllele.clear();
altAllele.add(alt.get(leftFlank));
}
extType = "fs";
extension = alt.subList(leftFlank, alt.size()).indexOf(AminoAcid.STOP);
if (extension > 0) extension++; //If we found it, make it one-based
}
//Now that the messy conditions have been cleaned up, it's pretty easy to describe the changes
if (refAllele.size() == 1 && altAllele.size() == 1) {
//substitution
sb.append(refAllele.get(0).abbrev());
sb.append(startCoord+leftFlank);
sb.append(altAllele.get(0).abbrev());
} else if (refAllele.isEmpty()) {
//straight insertion - special because the site is identified by flanks
if (startCoord+leftFlank == 1) {
//Special case: Insertions before the initial Met are not real
name = "";
return;
} else if (isPotentialDuplicate &&
ref.subList(leftFlank-altAllele.size(), leftFlank).equals(altAllele)) {
int dupLen = altAllele.size();
if (leftFlank <= dupLen)
sb.append("Unk");
else
sb.append(ref.get(leftFlank-dupLen).abbrev());
sb.append(startCoord+leftFlank-dupLen);
if (dupLen > 1) {
sb.append("_");
if (leftFlank == 0)
sb.append("Unk");
else
sb.append(ref.get(leftFlank-1).abbrev());
sb.append(startCoord+leftFlank-1);
}
sb.append("dup");
} else {
if (leftFlank == 0)
sb.append("Unk");
else
sb.append(ref.get(leftFlank-1).abbrev());
sb.append(startCoord+leftFlank-1);
sb.append("_");
if (rightFlank == 0)
sb.append("Unk");
else
sb.append(ref.get(ref.size()-rightFlank).abbrev());
sb.append(startCoord+leftFlank);
sb.append("ins");
for (AminoAcid aa : altAllele)
sb.append(aa.abbrev());
}
} else {
//Straight deletion or indel
if (startCoord+leftFlank == 1 &&
altAllele.isEmpty() &&
refAllele.get(0) == AminoAcid.MET) {
//Special case: Start loss (normalized to this form above)
sb.append("Met1?");
} else {
sb.append(refAllele.get(0).abbrev());
sb.append(startCoord+leftFlank);
if (refAllele.size() > 1) {
sb.append("_");
sb.append(refAllele.get(refAllele.size()-1).abbrev());
sb.append(startCoord+leftFlank+refAllele.size()-1);
}
sb.append("del");
if (!altAllele.isEmpty()) {
sb.append("ins");
for (AminoAcid aa : altAllele)
sb.append(aa.abbrev());
}
}
}
if (!extType.equals("")) {
sb.append(extType);
sb.append("*");
if (extension > 0)
sb.append(extension);
else
sb.append("?");
}
}
sb.append(")");
name = sb.toString();
}
private TranscriptAnnotation tx;
private String name;
private int startCoord;
private List<AminoAcid> ref;
private List<AminoAcid> alt;
private List<AminoAcid> extension;
private boolean isFrameshift;
}
| true | true | private void buildName() {
if (startCoord == 0) {
name = "";
return;
}
/*
* Challenging cases:
*
* gCATga => gga
* A* => G
* p.Ala#_*#delinsGlyext*# (need to catch the readthrough and calculate the ext)
*
* caacgatcg => caTTGacgatcg
* QRS => H*RS
* p.Gln#delinsH*
*
* atgcgg => atCATgcgg
* MR => ?MR
* p.= (The insertion extends the UTR, but doesn't change the protein product)
*/
StringBuilder sb = new StringBuilder();
String protein = tx.getProtID();
if (protein != null && !protein.isEmpty()) {
sb.append(protein);
sb.append(":");
}
sb.append("p.(");
if (ref.equals(alt))
//Synonymous
sb.append("=");
else {
if (extension != null) {
ref.addAll(extension);
if (!isFrameshift) alt.addAll(extension);
}
//Find the region that actually changed
int leftFlank = 0;
int rightFlank = 0;
boolean isPotentialDuplicate = false;
while (leftFlank < ref.size() &&
leftFlank < alt.size() &&
ref.get(leftFlank) == alt.get(leftFlank)) {
leftFlank++;
}
while (rightFlank < ref.size() &&
rightFlank < alt.size() &&
ref.get(ref.size()-rightFlank-1) == alt.get(alt.size()-rightFlank-1)) {
rightFlank++;
}
//If a duplicating insertion is made (or a deletion from a rpt region),
//both leftFlank and rightFlank will go through the repeat region
//Ex:
//ABXXCD => ABXXXCD
//leftFlank and rightFlank will both be 4
if (leftFlank+rightFlank > ref.size() || leftFlank+rightFlank > alt.size()) {
rightFlank = Math.min(ref.size(), alt.size())-leftFlank;
if (alt.size() > ref.size()) isPotentialDuplicate = true;
}
//Now make a new list containing just the changes
//All of these manipulations are necessary because we need to know the flanking
//AAs for an insertion - otherwise, we could have just started with the change
List<AminoAcid> refAllele = new ArrayList<AminoAcid>(ref.subList(leftFlank, ref.size()-rightFlank));
List<AminoAcid> altAllele = new ArrayList<AminoAcid>(alt.subList(leftFlank, alt.size()-rightFlank));
String extType = "";
int extension = -1;
//Some of these special conditions can be caused by indels or substitutions,
//and we're worried about effect here, not cause.
//So identify some of the overarching conditions, and caress the extraneous data
//accordingly
if (!isFrameshift && refAllele.contains(AminoAcid.STOP)) {
//readthrough - everything after the old stop is unimportant, except that
//we need to find the new stop
if (altAllele.size() > 1) {
//We'll only report the first new amino acid (altAllele might be empty here, so the if is important!)
altAllele.clear();
altAllele.add(alt.get(leftFlank));
}
extType = "ext";
extension = alt.subList(leftFlank, alt.size()).indexOf(AminoAcid.STOP);
if (extension > 0) extension++; //If we found it, make it one-based
} else if (!altAllele.isEmpty() && altAllele.get(0) == AminoAcid.STOP) {
//nonsense - this is reported simply as a substitution, so just make sure
//that it looks like a subst when we get to it later. Importantly, if the first
//AA modified by frameshift is a stop, don't report it as a fs
if (refAllele.size() > 1) {
//Analogous to the modification to altAllele in the readthrough case
refAllele.clear();
refAllele.add(ref.get(leftFlank));
}
} else if (!refAllele.isEmpty() && refAllele.get(0) == AminoAcid.MET && startCoord+leftFlank == 1) {
//start-loss
altAllele.clear();
if (refAllele.size() > 1)
refAllele.subList(1, refAllele.size()).clear();
} else if (isFrameshift) {
if (refAllele.size() > 1) {
refAllele.clear();
refAllele.add(ref.get(leftFlank));
}
if (altAllele.size() > 1) {
altAllele.clear();
altAllele.add(alt.get(leftFlank));
}
extType = "fs";
extension = alt.subList(leftFlank, alt.size()).indexOf(AminoAcid.STOP);
if (extension > 0) extension++; //If we found it, make it one-based
}
//Now that the messy conditions have been cleaned up, it's pretty easy to describe the changes
if (refAllele.size() == 1 && altAllele.size() == 1) {
//substitution
sb.append(refAllele.get(0).abbrev());
sb.append(startCoord+leftFlank);
sb.append(altAllele.get(0).abbrev());
} else if (refAllele.isEmpty()) {
//straight insertion - special because the site is identified by flanks
if (startCoord+leftFlank == 1) {
//Special case: Insertions before the initial Met are not real
name = "";
return;
} else if (isPotentialDuplicate &&
ref.subList(leftFlank-altAllele.size(), leftFlank).equals(altAllele)) {
int dupLen = altAllele.size();
if (leftFlank <= dupLen)
sb.append("Unk");
else
sb.append(ref.get(leftFlank-dupLen).abbrev());
sb.append(startCoord+leftFlank-dupLen);
if (dupLen > 1) {
sb.append("_");
if (leftFlank == 0)
sb.append("Unk");
else
sb.append(ref.get(leftFlank-1).abbrev());
sb.append(startCoord+leftFlank-1);
}
sb.append("dup");
} else {
if (leftFlank == 0)
sb.append("Unk");
else
sb.append(ref.get(leftFlank-1).abbrev());
sb.append(startCoord+leftFlank-1);
sb.append("_");
if (rightFlank == 0)
sb.append("Unk");
else
sb.append(ref.get(ref.size()-rightFlank).abbrev());
sb.append(startCoord+leftFlank);
sb.append("ins");
for (AminoAcid aa : altAllele)
sb.append(aa.abbrev());
}
} else {
//Straight deletion or indel
if (startCoord+leftFlank == 1 &&
altAllele.isEmpty() &&
refAllele.get(0) == AminoAcid.MET) {
//Special case: Start loss (normalized to this form above)
sb.append("Met1?");
} else {
sb.append(refAllele.get(0).abbrev());
sb.append(startCoord+leftFlank);
if (refAllele.size() > 1) {
sb.append("_");
sb.append(refAllele.get(refAllele.size()-1).abbrev());
sb.append(startCoord+leftFlank+refAllele.size()-1);
}
sb.append("del");
if (!altAllele.isEmpty()) {
sb.append("ins");
for (AminoAcid aa : altAllele)
sb.append(aa.abbrev());
}
}
}
if (!extType.equals("")) {
sb.append(extType);
sb.append("*");
if (extension > 0)
sb.append(extension);
else
sb.append("?");
}
}
sb.append(")");
name = sb.toString();
}
| private void buildName() {
if (startCoord == 0) {
name = "";
return;
}
/*
* Challenging cases:
*
* gCATga => gga
* A* => G
* p.Ala#_*#delinsGlyext*# (need to catch the readthrough and calculate the ext)
*
* caacgatcg => caTTGacgatcg
* QRS => H*RS
* p.Gln#delinsH*
*
* atgcgg => atCATgcgg
* MR => ?MR
* p.= (The insertion extends the UTR, but doesn't change the protein product)
*/
StringBuilder sb = new StringBuilder();
String protein = tx.getProtID();
if (protein != null && !protein.isEmpty()) {
sb.append(protein);
sb.append(":");
}
sb.append("p.(");
if (ref.equals(alt))
//Synonymous
sb.append("=");
else {
if (extension != null) {
ref.addAll(extension);
if (!isFrameshift) alt.addAll(extension);
}
//Find the region that actually changed
int leftFlank = 0;
int rightFlank = 0;
boolean isPotentialDuplicate = false;
while (leftFlank < ref.size() &&
leftFlank < alt.size() &&
ref.get(leftFlank) == alt.get(leftFlank)) {
leftFlank++;
}
while (rightFlank < ref.size() &&
rightFlank < alt.size() &&
ref.get(ref.size()-rightFlank-1) == alt.get(alt.size()-rightFlank-1)) {
rightFlank++;
}
//If a duplicating insertion is made (or a deletion from a rpt region),
//both leftFlank and rightFlank will go through the repeat region
//Ex:
//ABXXCD => ABXXXCD
//leftFlank and rightFlank will both be 4
if (leftFlank+rightFlank > ref.size() || leftFlank+rightFlank > alt.size()) {
rightFlank = Math.min(ref.size(), alt.size())-leftFlank;
if (alt.size() > ref.size()) isPotentialDuplicate = true;
}
//Now make a new list containing just the changes
//All of these manipulations are necessary because we need to know the flanking
//AAs for an insertion - otherwise, we could have just started with the change
List<AminoAcid> refAllele = new ArrayList<AminoAcid>(ref.subList(leftFlank, ref.size()-rightFlank));
List<AminoAcid> altAllele = new ArrayList<AminoAcid>(alt.subList(leftFlank, alt.size()-rightFlank));
String extType = "";
int extension = -1;
//Some of these special conditions can be caused by indels or substitutions,
//and we're worried about effect here, not cause.
//So identify some of the overarching conditions, and caress the extraneous data
//accordingly
if (!isFrameshift && refAllele.contains(AminoAcid.STOP)) {
//readthrough - everything after the old stop is unimportant, except that
//we need to find the new stop
if (altAllele.size() > 1) {
//We'll only report the first new amino acid (altAllele might be empty here, so the if is important!)
altAllele.clear();
altAllele.add(alt.get(leftFlank));
}
extType = "ext";
extension = alt.subList(leftFlank, alt.size()).indexOf(AminoAcid.STOP);
if (extension > 0) extension++; //If we found it, make it one-based
} else if (!altAllele.isEmpty() && altAllele.get(0) == AminoAcid.STOP) {
//nonsense - this is reported simply as a substitution, so just make sure
//that it looks like a subst when we get to it later. Importantly, if the first
//AA modified by frameshift is a stop, don't report it as a fs
if (refAllele.size() > 1) {
//Analogous to the modification to altAllele in the readthrough case
refAllele.clear();
refAllele.add(ref.get(leftFlank));
}
if (altAllele.size() > 1) {
altAllele.clear();
altAllele.add(alt.get(leftFlank));
}
} else if (!refAllele.isEmpty() && refAllele.get(0) == AminoAcid.MET && startCoord+leftFlank == 1) {
//start-loss
altAllele.clear();
if (refAllele.size() > 1)
refAllele.subList(1, refAllele.size()).clear();
} else if (isFrameshift) {
if (refAllele.size() > 1) {
refAllele.clear();
refAllele.add(ref.get(leftFlank));
}
if (altAllele.size() > 1) {
altAllele.clear();
altAllele.add(alt.get(leftFlank));
}
extType = "fs";
extension = alt.subList(leftFlank, alt.size()).indexOf(AminoAcid.STOP);
if (extension > 0) extension++; //If we found it, make it one-based
}
//Now that the messy conditions have been cleaned up, it's pretty easy to describe the changes
if (refAllele.size() == 1 && altAllele.size() == 1) {
//substitution
sb.append(refAllele.get(0).abbrev());
sb.append(startCoord+leftFlank);
sb.append(altAllele.get(0).abbrev());
} else if (refAllele.isEmpty()) {
//straight insertion - special because the site is identified by flanks
if (startCoord+leftFlank == 1) {
//Special case: Insertions before the initial Met are not real
name = "";
return;
} else if (isPotentialDuplicate &&
ref.subList(leftFlank-altAllele.size(), leftFlank).equals(altAllele)) {
int dupLen = altAllele.size();
if (leftFlank <= dupLen)
sb.append("Unk");
else
sb.append(ref.get(leftFlank-dupLen).abbrev());
sb.append(startCoord+leftFlank-dupLen);
if (dupLen > 1) {
sb.append("_");
if (leftFlank == 0)
sb.append("Unk");
else
sb.append(ref.get(leftFlank-1).abbrev());
sb.append(startCoord+leftFlank-1);
}
sb.append("dup");
} else {
if (leftFlank == 0)
sb.append("Unk");
else
sb.append(ref.get(leftFlank-1).abbrev());
sb.append(startCoord+leftFlank-1);
sb.append("_");
if (rightFlank == 0)
sb.append("Unk");
else
sb.append(ref.get(ref.size()-rightFlank).abbrev());
sb.append(startCoord+leftFlank);
sb.append("ins");
for (AminoAcid aa : altAllele)
sb.append(aa.abbrev());
}
} else {
//Straight deletion or indel
if (startCoord+leftFlank == 1 &&
altAllele.isEmpty() &&
refAllele.get(0) == AminoAcid.MET) {
//Special case: Start loss (normalized to this form above)
sb.append("Met1?");
} else {
sb.append(refAllele.get(0).abbrev());
sb.append(startCoord+leftFlank);
if (refAllele.size() > 1) {
sb.append("_");
sb.append(refAllele.get(refAllele.size()-1).abbrev());
sb.append(startCoord+leftFlank+refAllele.size()-1);
}
sb.append("del");
if (!altAllele.isEmpty()) {
sb.append("ins");
for (AminoAcid aa : altAllele)
sb.append(aa.abbrev());
}
}
}
if (!extType.equals("")) {
sb.append(extType);
sb.append("*");
if (extension > 0)
sb.append(extension);
else
sb.append("?");
}
}
sb.append(")");
name = sb.toString();
}
|
diff --git a/plugins/org.eclipse.mylyn.docs.intent.client.ui/src/org/eclipse/mylyn/docs/intent/client/ui/editor/quickfix/IntentSynchronizationCompletionProposal.java b/plugins/org.eclipse.mylyn.docs.intent.client.ui/src/org/eclipse/mylyn/docs/intent/client/ui/editor/quickfix/IntentSynchronizationCompletionProposal.java
index a46083fd..d5719de0 100644
--- a/plugins/org.eclipse.mylyn.docs.intent.client.ui/src/org/eclipse/mylyn/docs/intent/client/ui/editor/quickfix/IntentSynchronizationCompletionProposal.java
+++ b/plugins/org.eclipse.mylyn.docs.intent.client.ui/src/org/eclipse/mylyn/docs/intent/client/ui/editor/quickfix/IntentSynchronizationCompletionProposal.java
@@ -1,442 +1,442 @@
/*******************************************************************************
* Copyright (c) 2010, 2011 Obeo.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Obeo - initial API and implementation
*******************************************************************************/
package org.eclipse.mylyn.docs.intent.client.ui.editor.quickfix;
import java.util.Collection;
import org.eclipse.compare.CompareConfiguration;
import org.eclipse.compare.CompareUI;
import org.eclipse.core.commands.Command;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.commands.IHandler;
import org.eclipse.core.commands.NotEnabledException;
import org.eclipse.core.commands.NotHandledException;
import org.eclipse.core.commands.ParameterizedCommand;
import org.eclipse.core.commands.common.NotDefinedException;
import org.eclipse.core.expressions.Expression;
import org.eclipse.core.expressions.IEvaluationContext;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.compare.diff.metamodel.ComparisonResourceSnapshot;
import org.eclipse.emf.compare.diff.metamodel.ComparisonSnapshot;
import org.eclipse.emf.compare.diff.metamodel.DiffFactory;
import org.eclipse.emf.compare.diff.metamodel.DiffModel;
import org.eclipse.emf.compare.diff.service.DiffService;
import org.eclipse.emf.compare.match.metamodel.MatchModel;
import org.eclipse.emf.compare.match.service.MatchService;
import org.eclipse.emf.compare.ui.editor.ModelCompareEditorInput;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.contentassist.ICompletionProposal;
import org.eclipse.jface.text.contentassist.IContextInformation;
import org.eclipse.jface.text.source.Annotation;
import org.eclipse.mylyn.docs.intent.client.ui.IntentEditorActivator;
import org.eclipse.mylyn.docs.intent.client.ui.editor.annotation.IntentAnnotation;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.widgets.Event;
import org.eclipse.ui.ISourceProvider;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.handlers.IHandlerActivation;
import org.eclipse.ui.handlers.IHandlerService;
import org.eclipse.ui.services.IServiceLocator;
/**
* {@link ICompletionProposal} used to fix a Synchronization issue by opening the compare Editor.
*
* @author <a href="mailto:[email protected]">Alex Lagarde</a>
*/
public class IntentSynchronizationCompletionProposal implements ICompletionProposal {
private static final String COMPARE_EDITOR_TITLE = "Comparing Intent Document and Working Copy";
private IntentAnnotation syncAnnotation;
/**
* Default constructor.
*
* @param annotation
* the {@link IntentAnnotation} describing the synchronization issue.
*/
public IntentSynchronizationCompletionProposal(Annotation annotation) {
this.syncAnnotation = (IntentAnnotation)annotation;
}
/**
* {@inheritDoc}
*
* @see org.eclipse.jface.text.contentassist.ICompletionProposal#apply(org.eclipse.jface.text.IDocument)
*/
public void apply(IDocument document) {
// Step 1 : getting the resources to compare URI
- String generatedResourceURI = syncAnnotation.getAdditionalInformations().iterator().next()
+ String workingCopyResourceURI = syncAnnotation.getAdditionalInformations().iterator().next()
.replace("\"", "");
- String workingCopyResourceURI = ((String)syncAnnotation.getAdditionalInformations().toArray()[1])
+ String generatedResourceURI = ((String)syncAnnotation.getAdditionalInformations().toArray()[1])
.replace("\"", "");
// Step 2 : loading the resources
ResourceSetImpl rs = new ResourceSetImpl();
Resource generatedResource = rs.getResource(URI.createURI(generatedResourceURI), true);
Resource workingCopyResource = rs.getResource(URI.createURI(workingCopyResourceURI), true);
// Step 3 : opening a new Compare Editor on these two resources
try {
// Step 3.1 : making match and diff
MatchModel match = MatchService.doResourceMatch(generatedResource, workingCopyResource, null);
DiffModel diff = DiffService.doDiff(match, false);
// Step 3.2 : creating a comparaison snapshot from this diff
ComparisonResourceSnapshot snapshot = DiffFactory.eINSTANCE.createComparisonResourceSnapshot();
snapshot.setDiff(diff);
snapshot.setMatch(match);
// Step 3.3 : open a compare dialog
final CompareConfiguration compareConfig = new IntentCompareConfiguration(generatedResource,
workingCopyResource);
ModelCompareEditorInput input = new IntentCompareEditorInput(snapshot, compareConfig);
compareConfig.setContainer(input);
input.setTitle(COMPARE_EDITOR_TITLE + " (" + workingCopyResourceURI + ")");
CompareUI.openCompareDialog(input);
} catch (InterruptedException e) {
// Editor will not be opened
}
}
/**
* {@inheritDoc}
*
* @see org.eclipse.jface.text.contentassist.ICompletionProposal#getSelection(org.eclipse.jface.text.IDocument)
*/
public Point getSelection(IDocument document) {
return null;
}
/**
* {@inheritDoc}
*
* @see org.eclipse.jface.text.contentassist.ICompletionProposal#getAdditionalProposalInfo()
*/
public String getAdditionalProposalInfo() {
return "";
}
/**
* {@inheritDoc}
*
* @see org.eclipse.jface.text.contentassist.ICompletionProposal#getDisplayString()
*/
public String getDisplayString() {
return "See differences in Compare Editor";
}
/**
* {@inheritDoc}
*
* @see org.eclipse.jface.text.contentassist.ICompletionProposal#getImage()
*/
public Image getImage() {
return IntentEditorActivator.getDefault().getImage("icon/annotation/sync-warning.gif");
}
/**
* {@inheritDoc}
*
* @see org.eclipse.jface.text.contentassist.ICompletionProposal#getContextInformation()
*/
public IContextInformation getContextInformation() {
return null;
}
/**
* A custom CompareEditorInput for Intent.
*
* @author alagarde
*/
private class IntentCompareEditorInput extends ModelCompareEditorInput {
private CompareConfiguration compareConfig;
/**
* This constructor takes a {@link ComparisonSnapshot} as input.
*
* @param snapshot
* The ComparisonSnapshot loaded from an emfdiff.
* @param compareConfig
* the compare config
*/
public IntentCompareEditorInput(ComparisonSnapshot snapshot, CompareConfiguration compareConfig) {
super(snapshot);
this.compareConfig = compareConfig;
}
/**
* {@inheritDoc}
*
* @see org.eclipse.compare.CompareEditorInput#getCompareConfiguration()
*/
@Override
public CompareConfiguration getCompareConfiguration() {
return compareConfig;
}
/**
* {@inheritDoc}
*
* @see org.eclipse.compare.CompareEditorInput#getWorkbenchPart()
*/
@Override
public IWorkbenchPart getWorkbenchPart() {
return PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActiveEditor();
}
/**
* {@inheritDoc}
*
* @see org.eclipse.compare.CompareEditorInput#getServiceLocator()
*/
@Override
public IServiceLocator getServiceLocator() {
return new IServiceLocator() {
public boolean hasService(Class api) {
if (api.equals(IHandlerService.class)) {
return true;
}
return false;
}
public Object getService(Class api) {
if (api.equals(IHandlerService.class)) {
return new IntentCompareHandlerService();
}
return null;
}
};
}
}
/**
* A IHandlerService for Intent.
*
* @author alagarde
*/
private class IntentCompareHandlerService implements IHandlerService {
/**
* {@inheritDoc}
*
* @see org.eclipse.ui.services.IDisposable#dispose()
*/
public void dispose() {
}
/**
* {@inheritDoc}
*
* @see org.eclipse.ui.services.IServiceWithSources#removeSourceProvider(org.eclipse.ui.ISourceProvider)
*/
public void removeSourceProvider(ISourceProvider provider) {
}
/**
* {@inheritDoc}
*
* @see org.eclipse.ui.services.IServiceWithSources#addSourceProvider(org.eclipse.ui.ISourceProvider)
*/
public void addSourceProvider(ISourceProvider provider) {
}
/**
* {@inheritDoc}
*
* @see org.eclipse.ui.handlers.IHandlerService#setHelpContextId(org.eclipse.core.commands.IHandler,
* java.lang.String)
*/
public void setHelpContextId(IHandler handler, String helpContextId) {
}
/**
* {@inheritDoc}
*
* @see org.eclipse.ui.handlers.IHandlerService#readRegistry()
*/
public void readRegistry() {
}
/**
* {@inheritDoc}
*
* @see org.eclipse.ui.handlers.IHandlerService#getCurrentState()
*/
public IEvaluationContext getCurrentState() {
return null;
}
/**
* {@inheritDoc}
*
* @see org.eclipse.ui.handlers.IHandlerService#executeCommandInContext(org.eclipse.core.commands.ParameterizedCommand,
* org.eclipse.swt.widgets.Event, org.eclipse.core.expressions.IEvaluationContext)
*/
// CHECKSTYLE:OFF
public Object executeCommandInContext(ParameterizedCommand command, Event event,
IEvaluationContext context) throws ExecutionException, NotDefinedException,
NotEnabledException, NotHandledException {
return null;
}
/**
* {@inheritDoc}
*
* @see org.eclipse.ui.handlers.IHandlerService#executeCommand(org.eclipse.core.commands.ParameterizedCommand,
* org.eclipse.swt.widgets.Event)
*/
public Object executeCommand(ParameterizedCommand command, Event event) throws ExecutionException,
NotDefinedException, NotEnabledException, NotHandledException {
return null;
}
/**
* {@inheritDoc}
*
* @see org.eclipse.ui.handlers.IHandlerService#executeCommand(java.lang.String,
* org.eclipse.swt.widgets.Event)
*/
public Object executeCommand(String commandId, Event event) throws ExecutionException,
NotDefinedException, NotEnabledException, NotHandledException {
return null;
}
// CHECKSTYLE:ON
/**
* {@inheritDoc}
*
* @see org.eclipse.ui.handlers.IHandlerService#deactivateHandlers(java.util.Collection)
*/
public void deactivateHandlers(Collection activations) {
}
/**
* {@inheritDoc}
*
* @see org.eclipse.ui.handlers.IHandlerService#deactivateHandler(org.eclipse.ui.handlers.IHandlerActivation)
*/
public void deactivateHandler(IHandlerActivation activation) {
}
/**
* {@inheritDoc}
*
* @see org.eclipse.ui.handlers.IHandlerService#createExecutionEvent(org.eclipse.core.commands.ParameterizedCommand,
* org.eclipse.swt.widgets.Event)
*/
public ExecutionEvent createExecutionEvent(ParameterizedCommand command, Event event) {
return null;
}
/**
* {@inheritDoc}
*
* @see org.eclipse.ui.handlers.IHandlerService#createExecutionEvent(org.eclipse.core.commands.Command,
* org.eclipse.swt.widgets.Event)
*/
public ExecutionEvent createExecutionEvent(Command command, Event event) {
return null;
}
/**
* {@inheritDoc}
*
* @see org.eclipse.ui.handlers.IHandlerService#createContextSnapshot(boolean)
*/
public IEvaluationContext createContextSnapshot(boolean includeSelection) {
return null;
}
/**
* {@inheritDoc}
*
* @see org.eclipse.ui.handlers.IHandlerService#activateHandler(java.lang.String,
* org.eclipse.core.commands.IHandler, org.eclipse.core.expressions.Expression, int)
*/
public IHandlerActivation activateHandler(String commandId, IHandler handler, Expression expression,
int sourcePriorities) {
return null;
}
/**
* {@inheritDoc}
*
* @see org.eclipse.ui.handlers.IHandlerService#activateHandler(java.lang.String,
* org.eclipse.core.commands.IHandler, org.eclipse.core.expressions.Expression, boolean)
*/
public IHandlerActivation activateHandler(String commandId, IHandler handler, Expression expression,
boolean global) {
return null;
}
/**
* {@inheritDoc}
*
* @see org.eclipse.ui.handlers.IHandlerService#activateHandler(java.lang.String,
* org.eclipse.core.commands.IHandler, org.eclipse.core.expressions.Expression)
*/
public IHandlerActivation activateHandler(String commandId, IHandler handler, Expression expression) {
return null;
}
/**
* {@inheritDoc}
*
* @see org.eclipse.ui.handlers.IHandlerService#activateHandler(java.lang.String,
* org.eclipse.core.commands.IHandler)
*/
public IHandlerActivation activateHandler(String commandId, IHandler handler) {
return null;
}
/**
* {@inheritDoc}
*
* @see org.eclipse.ui.handlers.IHandlerService#activateHandler(org.eclipse.ui.handlers.IHandlerActivation)
*/
public IHandlerActivation activateHandler(IHandlerActivation activation) {
return null;
}
}
}
| false | true | public void apply(IDocument document) {
// Step 1 : getting the resources to compare URI
String generatedResourceURI = syncAnnotation.getAdditionalInformations().iterator().next()
.replace("\"", "");
String workingCopyResourceURI = ((String)syncAnnotation.getAdditionalInformations().toArray()[1])
.replace("\"", "");
// Step 2 : loading the resources
ResourceSetImpl rs = new ResourceSetImpl();
Resource generatedResource = rs.getResource(URI.createURI(generatedResourceURI), true);
Resource workingCopyResource = rs.getResource(URI.createURI(workingCopyResourceURI), true);
// Step 3 : opening a new Compare Editor on these two resources
try {
// Step 3.1 : making match and diff
MatchModel match = MatchService.doResourceMatch(generatedResource, workingCopyResource, null);
DiffModel diff = DiffService.doDiff(match, false);
// Step 3.2 : creating a comparaison snapshot from this diff
ComparisonResourceSnapshot snapshot = DiffFactory.eINSTANCE.createComparisonResourceSnapshot();
snapshot.setDiff(diff);
snapshot.setMatch(match);
// Step 3.3 : open a compare dialog
final CompareConfiguration compareConfig = new IntentCompareConfiguration(generatedResource,
workingCopyResource);
ModelCompareEditorInput input = new IntentCompareEditorInput(snapshot, compareConfig);
compareConfig.setContainer(input);
input.setTitle(COMPARE_EDITOR_TITLE + " (" + workingCopyResourceURI + ")");
CompareUI.openCompareDialog(input);
} catch (InterruptedException e) {
// Editor will not be opened
}
}
| public void apply(IDocument document) {
// Step 1 : getting the resources to compare URI
String workingCopyResourceURI = syncAnnotation.getAdditionalInformations().iterator().next()
.replace("\"", "");
String generatedResourceURI = ((String)syncAnnotation.getAdditionalInformations().toArray()[1])
.replace("\"", "");
// Step 2 : loading the resources
ResourceSetImpl rs = new ResourceSetImpl();
Resource generatedResource = rs.getResource(URI.createURI(generatedResourceURI), true);
Resource workingCopyResource = rs.getResource(URI.createURI(workingCopyResourceURI), true);
// Step 3 : opening a new Compare Editor on these two resources
try {
// Step 3.1 : making match and diff
MatchModel match = MatchService.doResourceMatch(generatedResource, workingCopyResource, null);
DiffModel diff = DiffService.doDiff(match, false);
// Step 3.2 : creating a comparaison snapshot from this diff
ComparisonResourceSnapshot snapshot = DiffFactory.eINSTANCE.createComparisonResourceSnapshot();
snapshot.setDiff(diff);
snapshot.setMatch(match);
// Step 3.3 : open a compare dialog
final CompareConfiguration compareConfig = new IntentCompareConfiguration(generatedResource,
workingCopyResource);
ModelCompareEditorInput input = new IntentCompareEditorInput(snapshot, compareConfig);
compareConfig.setContainer(input);
input.setTitle(COMPARE_EDITOR_TITLE + " (" + workingCopyResourceURI + ")");
CompareUI.openCompareDialog(input);
} catch (InterruptedException e) {
// Editor will not be opened
}
}
|
diff --git a/src/net/sf/drftpd/master/command/plugins/Dir.java b/src/net/sf/drftpd/master/command/plugins/Dir.java
index 557f3118..0ed748cc 100644
--- a/src/net/sf/drftpd/master/command/plugins/Dir.java
+++ b/src/net/sf/drftpd/master/command/plugins/Dir.java
@@ -1,970 +1,969 @@
/*
* This file is part of DrFTPD, Distributed FTP Daemon.
*
* DrFTPD is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* DrFTPD 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 DrFTPD; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package net.sf.drftpd.master.command.plugins;
import net.sf.drftpd.Checksum;
import net.sf.drftpd.FileExistsException;
import net.sf.drftpd.NoAvailableSlaveException;
import net.sf.drftpd.event.DirectoryFtpEvent;
import net.sf.drftpd.master.BaseFtpConnection;
import net.sf.drftpd.master.FtpRequest;
import net.sf.drftpd.master.GroupPosition;
import net.sf.drftpd.master.UploaderPosition;
import net.sf.drftpd.master.command.CommandManager;
import net.sf.drftpd.master.command.CommandManagerFactory;
import net.sf.drftpd.util.ListUtils;
import net.sf.drftpd.util.ReplacerUtils;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.drftpd.Bytes;
import org.drftpd.SFVFile;
import org.drftpd.commands.CommandHandler;
import org.drftpd.commands.CommandHandlerFactory;
import org.drftpd.commands.Reply;
import org.drftpd.commands.UnhandledCommandException;
import org.drftpd.commands.UserManagment;
import org.drftpd.id3.ID3Tag;
import org.drftpd.plugins.SiteBot;
import org.drftpd.remotefile.LinkedRemoteFile;
import org.drftpd.remotefile.LinkedRemoteFileInterface;
import org.drftpd.remotefile.StaticRemoteFile;
import org.drftpd.remotefile.LinkedRemoteFile.NonExistingFile;
import org.drftpd.usermanager.NoSuchUserException;
import org.drftpd.usermanager.User;
import org.drftpd.usermanager.UserFileException;
import org.tanesha.replacer.FormatterException;
import org.tanesha.replacer.ReplacerEnvironment;
import org.tanesha.replacer.ReplacerFormat;
import org.tanesha.replacer.SimplePrintf;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.Properties;
import java.util.StringTokenizer;
/**
* @author mog
* @version $Id$
*/
public class Dir implements CommandHandlerFactory, CommandHandler, Cloneable {
private final static SimpleDateFormat DATE_FMT = new SimpleDateFormat(
"yyyyMMddHHmmss.SSS");
private static final Logger logger = Logger.getLogger(Dir.class);
protected LinkedRemoteFileInterface _renameFrom = null;
public Dir() {
super();
}
/**
* <code>CDUP <CRLF></code><br>
*
* This command is a special case of CWD, and is included to
* simplify the implementation of programs for transferring
* directory trees between operating systems having different
* syntaxes for naming the parent directory. The reply codes
* shall be identical to the reply codes of CWD.
*/
private Reply doCDUP(BaseFtpConnection conn) {
// change directory
try {
conn.setCurrentDirectory(conn.getCurrentDirectory().getParentFile());
} catch (FileNotFoundException ex) {
}
return new Reply(200,
"Directory changed to " + conn.getCurrentDirectory().getPath());
}
/**
* <code>CWD <SP> <pathname> <CRLF></code><br>
*
* This command allows the user to work with a different
* directory for file storage or retrieval without
* altering his login or accounting information. Transfer
* parameters are similarly unchanged. The argument is a
* pathname specifying a directory.
*/
private Reply doCWD(BaseFtpConnection conn) {
FtpRequest request = conn.getRequest();
if (!request.hasArgument()) {
return Reply.RESPONSE_501_SYNTAX_ERROR;
}
LinkedRemoteFile newCurrentDirectory;
try {
newCurrentDirectory = conn.getCurrentDirectory().lookupFile(request.getArgument());
} catch (FileNotFoundException ex) {
return new Reply(550, ex.getMessage());
}
if (!conn.getGlobalContext().getConfig().checkPrivPath(conn.getUserNull(),
newCurrentDirectory)) {
return new Reply(550, request.getArgument() + ": Not found");
// reply identical to FileNotFoundException.getMessage() above
}
if (!newCurrentDirectory.isDirectory()) {
return new Reply(550, request.getArgument() +
": Not a directory");
}
conn.setCurrentDirectory(newCurrentDirectory);
Reply response = new Reply(250,
"Directory changed to " + newCurrentDirectory.getPath());
conn.getGlobalContext().getConfig().directoryMessage(response,
conn.getUserNull(), newCurrentDirectory);
Properties zsCfg = new Properties();
try {
FileInputStream zsFile = new FileInputStream("conf/zipscript.conf");
zsCfg.load(zsFile);
zsFile.close();
} catch (FileNotFoundException e4) {
response.setMessage("Missing file conf/zipscript.conf");
response.addComment(e4);
} catch (IOException e4) {
response.setMessage("IOException opening conf/zipscript.conf");
response.addComment(e4);
}
// show cwd_mp3.txt if this is an mp3 release
boolean id3Enabled = zsCfg.getProperty("cwd.id3info.enabled").equalsIgnoreCase("true");;
if (id3Enabled) {
try {
ID3Tag id3tag = newCurrentDirectory.lookupFile(newCurrentDirectory.lookupMP3File())
.getID3v1Tag();
String mp3text = zsCfg.getProperty("cwd.id3info.text");
ReplacerEnvironment env = BaseFtpConnection.getReplacerEnvironment(null,
conn.getUserNull());
ReplacerFormat id3format = null;
try {
id3format = ReplacerFormat.createFormat(mp3text);
} catch (FormatterException e1) {
logger.warn(e1);
}
env.add("artist", id3tag.getArtist().trim());
env.add("album", id3tag.getAlbum().trim());
env.add("genre", id3tag.getGenre());
env.add("year", id3tag.getYear());
try {
if (id3format == null) {
response.addComment("broken 1");
} else {
response.addComment(SimplePrintf.jprintf(id3format, env));
}
} catch (FormatterException e) {
response.addComment("broken 2");
logger.warn("", e);
}
} catch (FileNotFoundException e) {
// no mp3 found
//logger.warn("",e);
} catch (IOException e) {
logger.warn("", e);
} catch (NoAvailableSlaveException e) {
logger.warn("", e);
}
}
//show race stats
boolean racestatsEnabled = zsCfg.getProperty("cwd.racestats.enabled").equalsIgnoreCase("true");
if (racestatsEnabled) {
try {
SFVFile sfvfile = newCurrentDirectory.lookupSFVFile();
Collection racers = SiteBot.userSort(sfvfile.getFiles(),
"bytes", "high");
Collection groups = SiteBot.topFileGroup(sfvfile.getFiles());
String racerline = zsCfg.getProperty("cwd.racers.body");
String groupline = zsCfg.getProperty("cwd.groups.body");
ReplacerEnvironment env = BaseFtpConnection.getReplacerEnvironment(null,
conn.getUserNull());
//Start building race message
String racetext = zsCfg.getProperty("cwd.racestats.header") + "\n";
racetext += zsCfg.getProperty("cwd.racers.header") + "\n";
ReplacerFormat raceformat = null;
//Add racer stats
int position = 1;
for (Iterator iter = racers.iterator(); iter.hasNext();) {
UploaderPosition stat = (UploaderPosition) iter.next();
User raceuser;
try {
raceuser = conn.getGlobalContext().getUserManager()
.getUserByName(stat.getUsername());
} catch (NoSuchUserException e2) {
continue;
} catch (UserFileException e2) {
logger.log(Level.FATAL, "Error reading userfile", e2);
continue;
}
ReplacerEnvironment raceenv = new ReplacerEnvironment();
raceenv.add("speed",
Bytes.formatBytes(stat.getXferspeed()) + "/s");
raceenv.add("user", stat.getUsername());
raceenv.add("group", raceuser.getGroup());
raceenv.add("files", "" + stat.getFiles());
raceenv.add("bytes", Bytes.formatBytes(stat.getBytes()));
raceenv.add("position", String.valueOf(position));
raceenv.add("percent",
Integer.toString(
(stat.getFiles() * 100) / sfvfile.size()) + "%");
try {
racetext += (SimplePrintf.jprintf(racerline,
raceenv) + "\n");
position++;
} catch (FormatterException e) {
logger.warn(e);
}
}
racetext += (zsCfg.getProperty("cwd.racers.footer") + "\n");
racetext += (zsCfg.getProperty("cwd.groups.header") + "\n");
//add groups stats
position = 1;
for (Iterator iter = groups.iterator(); iter.hasNext();) {
GroupPosition stat = (GroupPosition) iter.next();
ReplacerEnvironment raceenv = new ReplacerEnvironment();
raceenv.add("group", stat.getGroupname());
raceenv.add("position", new Integer(position++));
raceenv.add("bytes", Bytes.formatBytes(stat.getBytes()));
raceenv.add("files", Integer.toString(stat.getFiles()));
raceenv.add("percent",
Integer.toString(
(stat.getFiles() * 100) / sfvfile.size()) + "%");
raceenv.add("speed",
Bytes.formatBytes(stat.getXferspeed()) + "/s");
try {
racetext += (SimplePrintf.jprintf(groupline,
raceenv) + "\n");
position++;
} catch (FormatterException e) {
logger.warn(e);
}
}
- racetext += (ReplacerUtils.jprintf("cwd.groups.footer", env,
- Dir.class) + "\n");
+ racetext += (zsCfg.getProperty("cwd.groups.footer") + "\n");
env.add("totalfiles", Integer.toString(sfvfile.size()));
env.add("totalbytes", Bytes.formatBytes(sfvfile.getTotalBytes()));
env.add("totalspeed",
Bytes.formatBytes(sfvfile.getXferspeed()) + "/s");
env.add("totalpercent",
Integer.toString(
(sfvfile.getStatus().getPresent() * 100) / sfvfile.size()) +
"%");
racetext += (zsCfg.getProperty("cwd.totals.body") + "\n");
racetext += (zsCfg.getProperty("cwd.racestats.footer") + "\n");
try {
raceformat = ReplacerFormat.createFormat(racetext);
} catch (FormatterException e1) {
logger.warn(e1);
}
try {
if (raceformat == null) {
response.addComment("cwd.uploaders");
} else {
response.addComment(SimplePrintf.jprintf(raceformat, env));
}
} catch (FormatterException e) {
response.addComment("cwd.uploaders");
logger.warn("", e);
}
} catch (RuntimeException ex) {
logger.error("", ex);
} catch (IOException e) {
//Error fetching SFV, ignore
} catch (NoAvailableSlaveException e) {
//Error fetching SFV, ignore
}
}
return response;
}
/**
* <code>DELE <SP> <pathname> <CRLF></code><br>
*
* This command causes the file specified in the pathname to be
* deleted at the server site.
*/
private Reply doDELE(BaseFtpConnection conn) {
FtpRequest request = conn.getRequest();
// argument check
if (!request.hasArgument()) {
//out.print(FtpResponse.RESPONSE_501_SYNTAX_ERROR);
return Reply.RESPONSE_501_SYNTAX_ERROR;
}
// get filenames
String fileName = request.getArgument();
LinkedRemoteFile requestedFile;
try {
//requestedFile = getVirtualDirectory().lookupFile(fileName);
requestedFile = conn.getCurrentDirectory().lookupFile(fileName);
} catch (FileNotFoundException ex) {
return new Reply(550, "File not found: " + ex.getMessage());
}
// check permission
if (requestedFile.getUsername().equals(conn.getUserNull().getName())) {
if (!conn.getGlobalContext().getConfig().checkDeleteOwn(conn.getUserNull(),
requestedFile)) {
return Reply.RESPONSE_530_ACCESS_DENIED;
}
} else if (!conn.getGlobalContext().getConfig().checkDelete(conn.getUserNull(),
requestedFile)) {
return Reply.RESPONSE_530_ACCESS_DENIED;
}
Reply reply = (Reply) Reply.RESPONSE_250_ACTION_OKAY.clone();
User uploader;
try {
uploader = conn.getGlobalContext().getUserManager().getUserByName(requestedFile.getUsername());
uploader.updateCredits((long) -(requestedFile.length() * uploader.getKeyedMap().getObjectFloat(UserManagment.RATIO)));
uploader.updateUploadedBytes(-requestedFile.length());
} catch (UserFileException e) {
reply.addComment("Error removing credits & stats: " + e.getMessage());
} catch (NoSuchUserException e) {
reply.addComment("Error removing credits & stats: " + e.getMessage());
}
conn.getGlobalContext().getConnectionManager().dispatchFtpEvent(new DirectoryFtpEvent(
conn, "DELE", requestedFile));
requestedFile.delete();
return reply;
}
/**
* <code>MDTM <SP> <pathname> <CRLF></code><br>
*
* Returns the date and time of when a file was modified.
*/
private Reply doMDTM(BaseFtpConnection conn) {
FtpRequest request = conn.getRequest();
// argument check
if (!request.hasArgument()) {
return Reply.RESPONSE_501_SYNTAX_ERROR;
}
// get filenames
String fileName = request.getArgument();
LinkedRemoteFile reqFile;
try {
reqFile = conn.getCurrentDirectory().lookupFile(fileName);
} catch (FileNotFoundException ex) {
return Reply.RESPONSE_550_REQUESTED_ACTION_NOT_TAKEN;
}
//fileName = user.getVirtualDirectory().getAbsoluteName(fileName);
//String physicalName =
// user.getVirtualDirectory().getPhysicalName(fileName);
//File reqFile = new File(physicalName);
// now print date
//if (reqFile.exists()) {
return new Reply(213,
DATE_FMT.format(new Date(reqFile.lastModified())));
//out.print(ftpStatus.getResponse(213, request, user, args));
//} else {
// out.write(ftpStatus.getResponse(550, request, user, null));
//}
}
/**
* <code>MKD <SP> <pathname> <CRLF></code><br>
*
* This command causes the directory specified in the pathname
* to be created as a directory (if the pathname is absolute)
* or as a subdirectory of the current working directory (if
* the pathname is relative).
*
*
* MKD
* 257
* 500, 501, 502, 421, 530, 550
*/
private Reply doMKD(BaseFtpConnection conn) {
FtpRequest request = conn.getRequest();
// argument check
if (!request.hasArgument()) {
return Reply.RESPONSE_501_SYNTAX_ERROR;
}
if (!conn.getGlobalContext().getSlaveManager().hasAvailableSlaves()) {
return Reply.RESPONSE_450_SLAVE_UNAVAILABLE;
}
LinkedRemoteFile.NonExistingFile ret = conn.getCurrentDirectory()
.lookupNonExistingFile(request.getArgument());
LinkedRemoteFile dir = ret.getFile();
if (ret.exists()) {
return new Reply(550,
"Requested action not taken. " + request.getArgument() +
" already exists");
}
String createdDirName = conn.getGlobalContext().getConfig().getDirName(ret.getPath());
if (!ListUtils.isLegalFileName(createdDirName)) {
return Reply.RESPONSE_553_REQUESTED_ACTION_NOT_TAKEN;
}
if (!conn.getGlobalContext().getConfig().checkMakeDir(conn.getUserNull(),
dir)) {
return Reply.RESPONSE_530_ACCESS_DENIED;
}
try {
LinkedRemoteFile createdDir = dir.createDirectory(conn.getUserNull()
.getName(),
conn.getUserNull().getGroup(), createdDirName);
conn.getGlobalContext().getConnectionManager().dispatchFtpEvent(new DirectoryFtpEvent(
conn, "MKD", createdDir));
return new Reply(257, "\"" + createdDir.getPath() +
"\" created.");
} catch (FileExistsException ex) {
return new Reply(550,
"directory " + createdDirName + " already exists");
}
}
/**
* <code>PWD <CRLF></code><br>
*
* This command causes the name of the current working
* directory to be returned in the reply.
*/
private Reply doPWD(BaseFtpConnection conn) {
return new Reply(257,
"\"" + conn.getCurrentDirectory().getPath() +
"\" is current directory");
}
/**
* <code>RMD <SP> <pathname> <CRLF></code><br>
*
* This command causes the directory specified in the pathname
* to be removed as a directory (if the pathname is absolute)
* or as a subdirectory of the current working directory (if
* the pathname is relative).
*/
private Reply doRMD(BaseFtpConnection conn) {
FtpRequest request = conn.getRequest();
// argument check
if (!request.hasArgument()) {
return Reply.RESPONSE_501_SYNTAX_ERROR;
}
// get file names
String fileName = request.getArgument();
LinkedRemoteFile requestedFile;
try {
requestedFile = conn.getCurrentDirectory().lookupFile(fileName);
} catch (FileNotFoundException e) {
return new Reply(550, fileName + ": " + e.getMessage());
}
if (requestedFile.getUsername().equals(conn.getUserNull().getName())) {
if (!conn.getGlobalContext().getConfig().checkDeleteOwn(conn.getUserNull(),
requestedFile)) {
return Reply.RESPONSE_530_ACCESS_DENIED;
}
} else if (!conn.getGlobalContext().getConfig().checkDelete(conn.getUserNull(),
requestedFile)) {
return Reply.RESPONSE_530_ACCESS_DENIED;
}
if (!requestedFile.isDirectory()) {
return new Reply(550, fileName + ": Not a directory");
}
if (requestedFile.dirSize() != 0) {
return new Reply(550, fileName + ": Directory not empty");
}
// now delete
//if (conn.getConfig().checkDirLog(conn.getUserNull(), requestedFile)) {
conn.getGlobalContext().getConnectionManager().dispatchFtpEvent(new DirectoryFtpEvent(
conn, "RMD", requestedFile));
//}
requestedFile.delete();
return Reply.RESPONSE_250_ACTION_OKAY;
}
/**
* <code>RNFR <SP> <pathname> <CRLF></code><br>
*
* This command specifies the old pathname of the file which is
* to be renamed. This command must be immediately followed by
* a "rename to" command specifying the new file pathname.
*
* RNFR
450, 550
500, 501, 502, 421, 530
350
*/
private Reply doRNFR(BaseFtpConnection conn) {
FtpRequest request = conn.getRequest();
// argument check
if (!request.hasArgument()) {
return Reply.RESPONSE_501_SYNTAX_ERROR;
}
// set state variable
// get filenames
//String fileName = request.getArgument();
//fileName = user.getVirtualDirectory().getAbsoluteName(fileName);
//mstRenFr = user.getVirtualDirectory().getPhysicalName(fileName);
try {
_renameFrom = conn.getCurrentDirectory().lookupFile(request.getArgument());
} catch (FileNotFoundException e) {
return Reply.RESPONSE_550_REQUESTED_ACTION_NOT_TAKEN;
}
//check permission
if (_renameFrom.getUsername().equals(conn.getUserNull().getName())) {
if (!conn.getGlobalContext().getConfig().checkRenameOwn(conn.getUserNull(),
_renameFrom)) {
return Reply.RESPONSE_530_ACCESS_DENIED;
}
} else if (!conn.getGlobalContext().getConfig().checkRename(conn.getUserNull(),
_renameFrom)) {
return Reply.RESPONSE_530_ACCESS_DENIED;
}
return new Reply(350, "File exists, ready for destination name");
}
/**
* <code>RNTO <SP> <pathname> <CRLF></code><br>
*
* This command specifies the new pathname of the file
* specified in the immediately preceding "rename from"
* command. Together the two commands cause a file to be
* renamed.
*/
private Reply doRNTO(BaseFtpConnection conn) {
FtpRequest request = conn.getRequest();
// argument check
if (!request.hasArgument()) {
return Reply.RESPONSE_501_SYNTAX_ERROR;
}
// set state variables
if (_renameFrom == null) {
return Reply.RESPONSE_503_BAD_SEQUENCE_OF_COMMANDS;
}
NonExistingFile ret = conn.getCurrentDirectory().lookupNonExistingFile(request.getArgument());
LinkedRemoteFileInterface toDir = ret.getFile();
String name = ret.getPath();
LinkedRemoteFileInterface fromFile = _renameFrom;
if (name == null) {
name = fromFile.getName();
}
// check permission
if (_renameFrom.getUsername().equals(conn.getUserNull().getName())) {
if (!conn.getGlobalContext().getConfig().checkRenameOwn(conn.getUserNull(),
toDir)) {
return Reply.RESPONSE_530_ACCESS_DENIED;
}
} else if (!conn.getGlobalContext().getConfig().checkRename(conn.getUserNull(),
toDir)) {
return Reply.RESPONSE_530_ACCESS_DENIED;
}
try {
fromFile.renameTo(toDir.getPath(), name);
} catch (FileNotFoundException e) {
logger.info("FileNotFoundException on renameTo()", e);
return new Reply(500, "FileNotFound - " + e.getMessage());
} catch (IOException e) {
logger.info("IOException on renameTo()", e);
return new Reply(500, "IOException - " + e.getMessage());
}
//out.write(FtpResponse.RESPONSE_250_ACTION_OKAY.toString());
return new Reply(250, request.getCommand() +
" command successful.");
}
private Reply doSITE_CHOWN(BaseFtpConnection conn)
throws UnhandledCommandException {
FtpRequest req = conn.getRequest();
StringTokenizer st = new StringTokenizer(conn.getRequest().getArgument());
String owner = st.nextToken();
String group = null;
int pos = owner.indexOf('.');
if (pos != -1) {
group = owner.substring(pos + 1);
owner = owner.substring(0, pos);
} else if ("SITE CHGRP".equals(req.getCommand())) {
group = owner;
owner = null;
} else if (!"SITE CHOWN".equals(req.getCommand())) {
throw UnhandledCommandException.create(Dir.class, req);
}
Reply reply = new Reply(200);
while (st.hasMoreTokens()) {
try {
LinkedRemoteFileInterface file = conn.getCurrentDirectory()
.lookupFile(st.nextToken());
if (owner != null) {
file.setOwner(owner);
}
if (group != null) {
file.setGroup(group);
}
} catch (FileNotFoundException e) {
reply.addComment(e.getMessage());
}
}
return Reply.RESPONSE_200_COMMAND_OK;
}
private Reply doSITE_LINK(BaseFtpConnection conn) {
if (!conn.getUserNull().isAdmin()) {
return Reply.RESPONSE_530_ACCESS_DENIED;
}
if (!conn.getRequest().hasArgument()) {
return Reply.RESPONSE_501_SYNTAX_ERROR;
}
StringTokenizer st = new StringTokenizer(conn.getRequest().getArgument(),
" ");
if (st.countTokens() != 2) {
return Reply.RESPONSE_501_SYNTAX_ERROR;
}
String targetName = st.nextToken();
String linkName = st.nextToken();
LinkedRemoteFile target;
try {
target = conn.getCurrentDirectory().lookupFile(targetName);
} catch (FileNotFoundException e) {
return Reply.RESPONSE_550_REQUESTED_ACTION_NOT_TAKEN;
}
if (!target.isDirectory()) {
return new Reply(501, "Only link to directories for now.");
}
StaticRemoteFile link = new StaticRemoteFile(linkName, null, targetName);
conn.getCurrentDirectory().addFile(link);
return Reply.RESPONSE_200_COMMAND_OK;
}
/**
* USAGE: site wipe [-r] <file/directory>
*
* This is similar to the UNIX rm command.
* In glftpd, if you just delete a file, the uploader loses credits and
* upload stats for it. There are many people who didn't like that and
* were unable/too lazy to write a shell script to do it for them, so I
* wrote this command to get them off my back.
*
* If the argument is a file, it will simply be deleted. If it's a
* directory, it and the files it contains will be deleted. If the
* directory contains other directories, the deletion will be aborted.
*
* To remove a directory containing subdirectories, you need to use
* "site wipe -r dirname". BE CAREFUL WHO YOU GIVE ACCESS TO THIS COMMAND.
* Glftpd will check if the parent directory of the file/directory you're
* trying to delete is writable by its owner. If not, wipe will not
* execute, so to protect directories from being wiped, make their parent
* 555.
*
* Also, wipe will only work where you have the right to delete (in
* glftpd.conf). Delete right and parent directory's mode of 755/777/etc
* will cause glftpd to SWITCH TO ROOT UID and wipe the file/directory.
* "site wipe -r /" will not work, but "site wipe -r /incoming" WILL, SO
* BE CAREFUL.
*
* This command will remove the deleted files/directories from the dirlog
* and dupefile databases.
*
* To give access to this command, add "-wipe -user flag =group" to the
* config file (similar to other site commands).
*
* @param request
* @param out
*/
private Reply doSITE_WIPE(BaseFtpConnection conn) {
if (!conn.getUserNull().isAdmin()) {
return Reply.RESPONSE_530_ACCESS_DENIED;
}
if (!conn.getRequest().hasArgument()) {
return Reply.RESPONSE_501_SYNTAX_ERROR;
}
String arg = conn.getRequest().getArgument();
boolean recursive;
if (arg.startsWith("-r ")) {
arg = arg.substring(3);
recursive = true;
} else {
recursive = false;
}
LinkedRemoteFile wipeFile;
try {
wipeFile = conn.getCurrentDirectory().lookupFile(arg);
} catch (FileNotFoundException e) {
return new Reply(200,
"Can't wipe: " + arg +
" does not exist or it's not a plain file/directory");
}
if (wipeFile.isDirectory() && (wipeFile.dirSize() != 0) && !recursive) {
return new Reply(200, "Can't wipe, directory not empty");
}
//if (conn.getConfig().checkDirLog(conn.getUserNull(), wipeFile)) {
conn.getGlobalContext().getConnectionManager().dispatchFtpEvent(new DirectoryFtpEvent(
conn, "WIPE", wipeFile));
//}
wipeFile.delete();
return Reply.RESPONSE_200_COMMAND_OK;
}
/**
* <code>SIZE <SP> <pathname> <CRLF></code><br>
*
* Returns the size of the file in bytes.
*/
private Reply doSIZE(BaseFtpConnection conn) {
FtpRequest request = conn.getRequest();
if (!request.hasArgument()) {
return Reply.RESPONSE_501_SYNTAX_ERROR;
}
LinkedRemoteFile file;
try {
file = conn.getCurrentDirectory().lookupFile(request.getArgument());
} catch (FileNotFoundException ex) {
return Reply.RESPONSE_550_REQUESTED_ACTION_NOT_TAKEN;
}
return new Reply(213, Long.toString(file.length()));
}
/**
* http://www.southrivertech.com/support/titanftp/webhelp/xcrc.htm
*
* Originally implemented by CuteFTP Pro and Globalscape FTP Server
*/
private Reply doXCRC(BaseFtpConnection conn) {
FtpRequest request = conn.getRequest();
if (!request.hasArgument()) {
return Reply.RESPONSE_501_SYNTAX_ERROR;
}
StringTokenizer st = new StringTokenizer(request.getArgument());
LinkedRemoteFile myFile;
try {
myFile = conn.getCurrentDirectory().lookupFile(st.nextToken());
} catch (FileNotFoundException e) {
return Reply.RESPONSE_550_REQUESTED_ACTION_NOT_TAKEN;
}
if (st.hasMoreTokens()) {
if (!st.nextToken().equals("0") ||
!st.nextToken().equals(Long.toString(myFile.length()))) {
return Reply.RESPONSE_504_COMMAND_NOT_IMPLEMENTED_FOR_PARM;
}
}
try {
return new Reply(250,
"XCRC Successful. " +
Checksum.formatChecksum(myFile.getCheckSum()));
} catch (NoAvailableSlaveException e1) {
logger.warn("", e1);
return new Reply(550,
"NoAvailableSlaveException: " + e1.getMessage());
}
}
public Reply execute(BaseFtpConnection conn)
throws UnhandledCommandException {
FtpRequest request = conn.getRequest();
String cmd = request.getCommand();
if ("CDUP".equals(cmd)) {
return doCDUP(conn);
}
if ("CWD".equals(cmd)) {
return doCWD(conn);
}
if ("MKD".equals(cmd)) {
return doMKD(conn);
}
if ("PWD".equals(cmd)) {
return doPWD(conn);
}
if ("RMD".equals(cmd)) {
return doRMD(conn);
}
if ("RNFR".equals(cmd)) {
return doRNFR(conn);
}
if ("RNTO".equals(cmd)) {
return doRNTO(conn);
}
if ("SITE LINK".equals(cmd)) {
return doSITE_LINK(conn);
}
if ("SITE WIPE".equals(cmd)) {
return doSITE_WIPE(conn);
}
if ("XCRC".equals(cmd)) {
return doXCRC(conn);
}
if ("MDTM".equals(cmd)) {
return doMDTM(conn);
}
if ("SIZE".equals(cmd)) {
return doSIZE(conn);
}
if ("DELE".equals(cmd)) {
return doDELE(conn);
}
if ("SITE CHOWN".equals(cmd) || "SITE CHGRP".equals(cmd)) {
return doSITE_CHOWN(conn);
}
throw UnhandledCommandException.create(Dir.class, request);
}
public String[] getFeatReplies() {
return null;
}
public CommandHandler initialize(BaseFtpConnection conn,
CommandManager initializer) {
try {
return (Dir) clone();
} catch (CloneNotSupportedException e) {
throw new RuntimeException(e);
}
}
public void load(CommandManagerFactory initializer) {
}
public void unload() {
}
}
| true | true | private Reply doCWD(BaseFtpConnection conn) {
FtpRequest request = conn.getRequest();
if (!request.hasArgument()) {
return Reply.RESPONSE_501_SYNTAX_ERROR;
}
LinkedRemoteFile newCurrentDirectory;
try {
newCurrentDirectory = conn.getCurrentDirectory().lookupFile(request.getArgument());
} catch (FileNotFoundException ex) {
return new Reply(550, ex.getMessage());
}
if (!conn.getGlobalContext().getConfig().checkPrivPath(conn.getUserNull(),
newCurrentDirectory)) {
return new Reply(550, request.getArgument() + ": Not found");
// reply identical to FileNotFoundException.getMessage() above
}
if (!newCurrentDirectory.isDirectory()) {
return new Reply(550, request.getArgument() +
": Not a directory");
}
conn.setCurrentDirectory(newCurrentDirectory);
Reply response = new Reply(250,
"Directory changed to " + newCurrentDirectory.getPath());
conn.getGlobalContext().getConfig().directoryMessage(response,
conn.getUserNull(), newCurrentDirectory);
Properties zsCfg = new Properties();
try {
FileInputStream zsFile = new FileInputStream("conf/zipscript.conf");
zsCfg.load(zsFile);
zsFile.close();
} catch (FileNotFoundException e4) {
response.setMessage("Missing file conf/zipscript.conf");
response.addComment(e4);
} catch (IOException e4) {
response.setMessage("IOException opening conf/zipscript.conf");
response.addComment(e4);
}
// show cwd_mp3.txt if this is an mp3 release
boolean id3Enabled = zsCfg.getProperty("cwd.id3info.enabled").equalsIgnoreCase("true");;
if (id3Enabled) {
try {
ID3Tag id3tag = newCurrentDirectory.lookupFile(newCurrentDirectory.lookupMP3File())
.getID3v1Tag();
String mp3text = zsCfg.getProperty("cwd.id3info.text");
ReplacerEnvironment env = BaseFtpConnection.getReplacerEnvironment(null,
conn.getUserNull());
ReplacerFormat id3format = null;
try {
id3format = ReplacerFormat.createFormat(mp3text);
} catch (FormatterException e1) {
logger.warn(e1);
}
env.add("artist", id3tag.getArtist().trim());
env.add("album", id3tag.getAlbum().trim());
env.add("genre", id3tag.getGenre());
env.add("year", id3tag.getYear());
try {
if (id3format == null) {
response.addComment("broken 1");
} else {
response.addComment(SimplePrintf.jprintf(id3format, env));
}
} catch (FormatterException e) {
response.addComment("broken 2");
logger.warn("", e);
}
} catch (FileNotFoundException e) {
// no mp3 found
//logger.warn("",e);
} catch (IOException e) {
logger.warn("", e);
} catch (NoAvailableSlaveException e) {
logger.warn("", e);
}
}
//show race stats
boolean racestatsEnabled = zsCfg.getProperty("cwd.racestats.enabled").equalsIgnoreCase("true");
if (racestatsEnabled) {
try {
SFVFile sfvfile = newCurrentDirectory.lookupSFVFile();
Collection racers = SiteBot.userSort(sfvfile.getFiles(),
"bytes", "high");
Collection groups = SiteBot.topFileGroup(sfvfile.getFiles());
String racerline = zsCfg.getProperty("cwd.racers.body");
String groupline = zsCfg.getProperty("cwd.groups.body");
ReplacerEnvironment env = BaseFtpConnection.getReplacerEnvironment(null,
conn.getUserNull());
//Start building race message
String racetext = zsCfg.getProperty("cwd.racestats.header") + "\n";
racetext += zsCfg.getProperty("cwd.racers.header") + "\n";
ReplacerFormat raceformat = null;
//Add racer stats
int position = 1;
for (Iterator iter = racers.iterator(); iter.hasNext();) {
UploaderPosition stat = (UploaderPosition) iter.next();
User raceuser;
try {
raceuser = conn.getGlobalContext().getUserManager()
.getUserByName(stat.getUsername());
} catch (NoSuchUserException e2) {
continue;
} catch (UserFileException e2) {
logger.log(Level.FATAL, "Error reading userfile", e2);
continue;
}
ReplacerEnvironment raceenv = new ReplacerEnvironment();
raceenv.add("speed",
Bytes.formatBytes(stat.getXferspeed()) + "/s");
raceenv.add("user", stat.getUsername());
raceenv.add("group", raceuser.getGroup());
raceenv.add("files", "" + stat.getFiles());
raceenv.add("bytes", Bytes.formatBytes(stat.getBytes()));
raceenv.add("position", String.valueOf(position));
raceenv.add("percent",
Integer.toString(
(stat.getFiles() * 100) / sfvfile.size()) + "%");
try {
racetext += (SimplePrintf.jprintf(racerline,
raceenv) + "\n");
position++;
} catch (FormatterException e) {
logger.warn(e);
}
}
racetext += (zsCfg.getProperty("cwd.racers.footer") + "\n");
racetext += (zsCfg.getProperty("cwd.groups.header") + "\n");
//add groups stats
position = 1;
for (Iterator iter = groups.iterator(); iter.hasNext();) {
GroupPosition stat = (GroupPosition) iter.next();
ReplacerEnvironment raceenv = new ReplacerEnvironment();
raceenv.add("group", stat.getGroupname());
raceenv.add("position", new Integer(position++));
raceenv.add("bytes", Bytes.formatBytes(stat.getBytes()));
raceenv.add("files", Integer.toString(stat.getFiles()));
raceenv.add("percent",
Integer.toString(
(stat.getFiles() * 100) / sfvfile.size()) + "%");
raceenv.add("speed",
Bytes.formatBytes(stat.getXferspeed()) + "/s");
try {
racetext += (SimplePrintf.jprintf(groupline,
raceenv) + "\n");
position++;
} catch (FormatterException e) {
logger.warn(e);
}
}
racetext += (ReplacerUtils.jprintf("cwd.groups.footer", env,
Dir.class) + "\n");
env.add("totalfiles", Integer.toString(sfvfile.size()));
env.add("totalbytes", Bytes.formatBytes(sfvfile.getTotalBytes()));
env.add("totalspeed",
Bytes.formatBytes(sfvfile.getXferspeed()) + "/s");
env.add("totalpercent",
Integer.toString(
(sfvfile.getStatus().getPresent() * 100) / sfvfile.size()) +
"%");
racetext += (zsCfg.getProperty("cwd.totals.body") + "\n");
racetext += (zsCfg.getProperty("cwd.racestats.footer") + "\n");
try {
raceformat = ReplacerFormat.createFormat(racetext);
} catch (FormatterException e1) {
logger.warn(e1);
}
try {
if (raceformat == null) {
response.addComment("cwd.uploaders");
} else {
response.addComment(SimplePrintf.jprintf(raceformat, env));
}
} catch (FormatterException e) {
response.addComment("cwd.uploaders");
logger.warn("", e);
}
} catch (RuntimeException ex) {
logger.error("", ex);
} catch (IOException e) {
//Error fetching SFV, ignore
} catch (NoAvailableSlaveException e) {
//Error fetching SFV, ignore
}
}
return response;
}
| private Reply doCWD(BaseFtpConnection conn) {
FtpRequest request = conn.getRequest();
if (!request.hasArgument()) {
return Reply.RESPONSE_501_SYNTAX_ERROR;
}
LinkedRemoteFile newCurrentDirectory;
try {
newCurrentDirectory = conn.getCurrentDirectory().lookupFile(request.getArgument());
} catch (FileNotFoundException ex) {
return new Reply(550, ex.getMessage());
}
if (!conn.getGlobalContext().getConfig().checkPrivPath(conn.getUserNull(),
newCurrentDirectory)) {
return new Reply(550, request.getArgument() + ": Not found");
// reply identical to FileNotFoundException.getMessage() above
}
if (!newCurrentDirectory.isDirectory()) {
return new Reply(550, request.getArgument() +
": Not a directory");
}
conn.setCurrentDirectory(newCurrentDirectory);
Reply response = new Reply(250,
"Directory changed to " + newCurrentDirectory.getPath());
conn.getGlobalContext().getConfig().directoryMessage(response,
conn.getUserNull(), newCurrentDirectory);
Properties zsCfg = new Properties();
try {
FileInputStream zsFile = new FileInputStream("conf/zipscript.conf");
zsCfg.load(zsFile);
zsFile.close();
} catch (FileNotFoundException e4) {
response.setMessage("Missing file conf/zipscript.conf");
response.addComment(e4);
} catch (IOException e4) {
response.setMessage("IOException opening conf/zipscript.conf");
response.addComment(e4);
}
// show cwd_mp3.txt if this is an mp3 release
boolean id3Enabled = zsCfg.getProperty("cwd.id3info.enabled").equalsIgnoreCase("true");;
if (id3Enabled) {
try {
ID3Tag id3tag = newCurrentDirectory.lookupFile(newCurrentDirectory.lookupMP3File())
.getID3v1Tag();
String mp3text = zsCfg.getProperty("cwd.id3info.text");
ReplacerEnvironment env = BaseFtpConnection.getReplacerEnvironment(null,
conn.getUserNull());
ReplacerFormat id3format = null;
try {
id3format = ReplacerFormat.createFormat(mp3text);
} catch (FormatterException e1) {
logger.warn(e1);
}
env.add("artist", id3tag.getArtist().trim());
env.add("album", id3tag.getAlbum().trim());
env.add("genre", id3tag.getGenre());
env.add("year", id3tag.getYear());
try {
if (id3format == null) {
response.addComment("broken 1");
} else {
response.addComment(SimplePrintf.jprintf(id3format, env));
}
} catch (FormatterException e) {
response.addComment("broken 2");
logger.warn("", e);
}
} catch (FileNotFoundException e) {
// no mp3 found
//logger.warn("",e);
} catch (IOException e) {
logger.warn("", e);
} catch (NoAvailableSlaveException e) {
logger.warn("", e);
}
}
//show race stats
boolean racestatsEnabled = zsCfg.getProperty("cwd.racestats.enabled").equalsIgnoreCase("true");
if (racestatsEnabled) {
try {
SFVFile sfvfile = newCurrentDirectory.lookupSFVFile();
Collection racers = SiteBot.userSort(sfvfile.getFiles(),
"bytes", "high");
Collection groups = SiteBot.topFileGroup(sfvfile.getFiles());
String racerline = zsCfg.getProperty("cwd.racers.body");
String groupline = zsCfg.getProperty("cwd.groups.body");
ReplacerEnvironment env = BaseFtpConnection.getReplacerEnvironment(null,
conn.getUserNull());
//Start building race message
String racetext = zsCfg.getProperty("cwd.racestats.header") + "\n";
racetext += zsCfg.getProperty("cwd.racers.header") + "\n";
ReplacerFormat raceformat = null;
//Add racer stats
int position = 1;
for (Iterator iter = racers.iterator(); iter.hasNext();) {
UploaderPosition stat = (UploaderPosition) iter.next();
User raceuser;
try {
raceuser = conn.getGlobalContext().getUserManager()
.getUserByName(stat.getUsername());
} catch (NoSuchUserException e2) {
continue;
} catch (UserFileException e2) {
logger.log(Level.FATAL, "Error reading userfile", e2);
continue;
}
ReplacerEnvironment raceenv = new ReplacerEnvironment();
raceenv.add("speed",
Bytes.formatBytes(stat.getXferspeed()) + "/s");
raceenv.add("user", stat.getUsername());
raceenv.add("group", raceuser.getGroup());
raceenv.add("files", "" + stat.getFiles());
raceenv.add("bytes", Bytes.formatBytes(stat.getBytes()));
raceenv.add("position", String.valueOf(position));
raceenv.add("percent",
Integer.toString(
(stat.getFiles() * 100) / sfvfile.size()) + "%");
try {
racetext += (SimplePrintf.jprintf(racerline,
raceenv) + "\n");
position++;
} catch (FormatterException e) {
logger.warn(e);
}
}
racetext += (zsCfg.getProperty("cwd.racers.footer") + "\n");
racetext += (zsCfg.getProperty("cwd.groups.header") + "\n");
//add groups stats
position = 1;
for (Iterator iter = groups.iterator(); iter.hasNext();) {
GroupPosition stat = (GroupPosition) iter.next();
ReplacerEnvironment raceenv = new ReplacerEnvironment();
raceenv.add("group", stat.getGroupname());
raceenv.add("position", new Integer(position++));
raceenv.add("bytes", Bytes.formatBytes(stat.getBytes()));
raceenv.add("files", Integer.toString(stat.getFiles()));
raceenv.add("percent",
Integer.toString(
(stat.getFiles() * 100) / sfvfile.size()) + "%");
raceenv.add("speed",
Bytes.formatBytes(stat.getXferspeed()) + "/s");
try {
racetext += (SimplePrintf.jprintf(groupline,
raceenv) + "\n");
position++;
} catch (FormatterException e) {
logger.warn(e);
}
}
racetext += (zsCfg.getProperty("cwd.groups.footer") + "\n");
env.add("totalfiles", Integer.toString(sfvfile.size()));
env.add("totalbytes", Bytes.formatBytes(sfvfile.getTotalBytes()));
env.add("totalspeed",
Bytes.formatBytes(sfvfile.getXferspeed()) + "/s");
env.add("totalpercent",
Integer.toString(
(sfvfile.getStatus().getPresent() * 100) / sfvfile.size()) +
"%");
racetext += (zsCfg.getProperty("cwd.totals.body") + "\n");
racetext += (zsCfg.getProperty("cwd.racestats.footer") + "\n");
try {
raceformat = ReplacerFormat.createFormat(racetext);
} catch (FormatterException e1) {
logger.warn(e1);
}
try {
if (raceformat == null) {
response.addComment("cwd.uploaders");
} else {
response.addComment(SimplePrintf.jprintf(raceformat, env));
}
} catch (FormatterException e) {
response.addComment("cwd.uploaders");
logger.warn("", e);
}
} catch (RuntimeException ex) {
logger.error("", ex);
} catch (IOException e) {
//Error fetching SFV, ignore
} catch (NoAvailableSlaveException e) {
//Error fetching SFV, ignore
}
}
return response;
}
|
diff --git a/src/org/apache/xerces/impl/XMLVersionDetector.java b/src/org/apache/xerces/impl/XMLVersionDetector.java
index ad16a1ea..9fa44308 100644
--- a/src/org/apache/xerces/impl/XMLVersionDetector.java
+++ b/src/org/apache/xerces/impl/XMLVersionDetector.java
@@ -1,266 +1,268 @@
/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 1999-2003 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 acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xerces" 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 [email protected].
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* 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 and was
* originally based on software copyright (c) 2003, International
* Business Machines, Inc., http://www.apache.org. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.xerces.impl;
import java.io.EOFException;
import java.io.IOException;
import org.apache.xerces.impl.msg.XMLMessageFormatter;
import org.apache.xerces.util.SymbolTable;
import org.apache.xerces.xni.XMLString;
import org.apache.xerces.xni.parser.XMLComponentManager;
import org.apache.xerces.xni.parser.XMLConfigurationException;
import org.apache.xerces.xni.parser.XMLInputSource;
/**
* This class scans the version of the document to determine
* which scanner to use: XML 1.1 or XML 1.0.
* The version is scanned using XML 1.1. scanner.
*
* @author Neil Graham, IBM
* @author Elena Litani, IBM
* @version $Id$
*/
public class XMLVersionDetector {
//
// Constants
//
private final static char[] XML11_VERSION = new char[]{'1', '.', '1'};
// property identifiers
/** Property identifier: symbol table. */
protected static final String SYMBOL_TABLE =
Constants.XERCES_PROPERTY_PREFIX + Constants.SYMBOL_TABLE_PROPERTY;
/** Property identifier: error reporter. */
protected static final String ERROR_REPORTER =
Constants.XERCES_PROPERTY_PREFIX + Constants.ERROR_REPORTER_PROPERTY;
/** Property identifier: entity manager. */
protected static final String ENTITY_MANAGER =
Constants.XERCES_PROPERTY_PREFIX + Constants.ENTITY_MANAGER_PROPERTY;
//
// Data
//
/** Symbol: "version". */
protected final static String fVersionSymbol = "version".intern();
// symbol: [xml]:
protected static final String fXMLSymbol = "[xml]".intern();
/** Symbol table. */
protected SymbolTable fSymbolTable;
/** Error reporter. */
protected XMLErrorReporter fErrorReporter;
/** Entity manager. */
protected XMLEntityManager fEntityManager;
protected String fEncoding = null;
private XMLString fVersionNum = new XMLString();
private final char [] fExpectedVersionString = {'<', '?', 'x', 'm', 'l', ' ', 'v', 'e', 'r', 's',
'i', 'o', 'n', '=', ' ', ' ', ' ', ' ', ' '};
/**
*
*
* @param componentManager The component manager.
*
* @throws SAXException Throws exception if required features and
* properties cannot be found.
*/
public void reset(XMLComponentManager componentManager)
throws XMLConfigurationException {
// Xerces properties
fSymbolTable = (SymbolTable)componentManager.getProperty(SYMBOL_TABLE);
fErrorReporter = (XMLErrorReporter)componentManager.getProperty(ERROR_REPORTER);
fEntityManager = (XMLEntityManager)componentManager.getProperty(ENTITY_MANAGER);
for(int i=14; i<fExpectedVersionString.length; i++ )
fExpectedVersionString[i] = ' ';
} // reset(XMLComponentManager)
/**
* Reset the reference to the appropriate scanner given the version of the
* document and start document scanning.
* @param scanner - the scanner to use
* @param version - the version of the document (XML 1.1 or XML 1.0).
*/
public void startDocumentParsing(XMLEntityHandler scanner, short version){
if (version == Constants.XML_VERSION_1_0){
fEntityManager.setScannerVersion(Constants.XML_VERSION_1_0);
}
else {
fEntityManager.setScannerVersion(Constants.XML_VERSION_1_1);
}
// Make sure the locator used by the error reporter is the current entity scanner.
fErrorReporter.setDocumentLocator(fEntityManager.getEntityScanner());
// Note: above we reset fEntityScanner in the entity manager, thus in startEntity
// in each scanner fEntityScanner field must be reset to reflect the change.
//
fEntityManager.setEntityHandler(scanner);
scanner.startEntity(fXMLSymbol, fEntityManager.getCurrentResourceIdentifier(), fEncoding);
}
/**
* This methods scans the XML declaration to find out the version
* (and provisional encoding) of the document.
* The scanning is doing using XML 1.1 scanner.
* @param inputSource
* @return short - Constants.XML_VERSION_1_1 if document version 1.1,
* otherwise Constants.XML_VERSION_1_0
* @throws IOException
*/
public short determineDocVersion(XMLInputSource inputSource) throws IOException {
fEncoding = fEntityManager.setupCurrentEntity(fXMLSymbol, inputSource, false, true);
// must assume 1.1 at this stage so that whitespace
// handling is correct in the XML decl...
fEntityManager.setScannerVersion(Constants.XML_VERSION_1_1);
XMLEntityScanner scanner = fEntityManager.getEntityScanner();
try {
if (!scanner.skipString("<?xml")) {
// definitely not a well-formed 1.1 doc!
return Constants.XML_VERSION_1_0;
}
if (!scanner.skipSpaces()) {
fixupCurrentEntity(fEntityManager, fExpectedVersionString, 5);
return Constants.XML_VERSION_1_0;
}
if (!scanner.skipString("version")) {
fixupCurrentEntity(fEntityManager, fExpectedVersionString, 6);
return Constants.XML_VERSION_1_0;
}
scanner.skipSpaces();
- if (scanner.scanChar() != '=') {
+ // Check if the next character is '='. If it is then consume it.
+ if (scanner.peekChar() != '=') {
fixupCurrentEntity(fEntityManager, fExpectedVersionString, 13);
return Constants.XML_VERSION_1_0;
}
+ scanner.scanChar();
scanner.skipSpaces();
int quoteChar = scanner.scanChar();
fExpectedVersionString[14] = (char) quoteChar;
for (int versionPos = 0; versionPos < XML11_VERSION.length; versionPos++) {
fExpectedVersionString[15 + versionPos] = (char) scanner.scanChar();
}
// REVISIT: should we check whether this equals quoteChar?
fExpectedVersionString[18] = (char) scanner.scanChar();
fixupCurrentEntity(fEntityManager, fExpectedVersionString, 19);
int matched = 0;
for (; matched < XML11_VERSION.length; matched++) {
if (fExpectedVersionString[15 + matched] != XML11_VERSION[matched])
break;
}
if (matched == XML11_VERSION.length)
return Constants.XML_VERSION_1_1;
return Constants.XML_VERSION_1_0;
// premature end of file
}
catch (EOFException e) {
fErrorReporter.reportError(
XMLMessageFormatter.XML_DOMAIN,
"PrematureEOF",
null,
XMLErrorReporter.SEVERITY_FATAL_ERROR);
return Constants.XML_VERSION_1_0;
}
}
// This method prepends "length" chars from the char array,
// from offset 0, to the manager's fCurrentEntity.ch.
private void fixupCurrentEntity(XMLEntityManager manager,
char [] scannedChars, int length) {
XMLEntityManager.ScannedEntity currentEntity = manager.getCurrentEntity();
if(currentEntity.count-currentEntity.position+length > currentEntity.ch.length) {
//resize array; this case is hard to imagine...
char[] tempCh = currentEntity.ch;
currentEntity.ch = new char[length+currentEntity.count-currentEntity.position+1];
System.arraycopy(tempCh, 0, currentEntity.ch, 0, tempCh.length);
}
if(currentEntity.position < length) {
// have to move sensitive stuff out of the way...
System.arraycopy(currentEntity.ch, currentEntity.position, currentEntity.ch, length, currentEntity.count-currentEntity.position);
currentEntity.count += length-currentEntity.position;
} else {
// have to reintroduce some whitespace so this parses:
for(int i=length; i<currentEntity.position; i++)
currentEntity.ch[i]=' ';
}
// prepend contents...
System.arraycopy(scannedChars, 0, currentEntity.ch, 0, length);
currentEntity.position = 0;
currentEntity.columnNumber = currentEntity.lineNumber = 1;
}
} // class XMLVersionDetector
| false | true | public short determineDocVersion(XMLInputSource inputSource) throws IOException {
fEncoding = fEntityManager.setupCurrentEntity(fXMLSymbol, inputSource, false, true);
// must assume 1.1 at this stage so that whitespace
// handling is correct in the XML decl...
fEntityManager.setScannerVersion(Constants.XML_VERSION_1_1);
XMLEntityScanner scanner = fEntityManager.getEntityScanner();
try {
if (!scanner.skipString("<?xml")) {
// definitely not a well-formed 1.1 doc!
return Constants.XML_VERSION_1_0;
}
if (!scanner.skipSpaces()) {
fixupCurrentEntity(fEntityManager, fExpectedVersionString, 5);
return Constants.XML_VERSION_1_0;
}
if (!scanner.skipString("version")) {
fixupCurrentEntity(fEntityManager, fExpectedVersionString, 6);
return Constants.XML_VERSION_1_0;
}
scanner.skipSpaces();
if (scanner.scanChar() != '=') {
fixupCurrentEntity(fEntityManager, fExpectedVersionString, 13);
return Constants.XML_VERSION_1_0;
}
scanner.skipSpaces();
int quoteChar = scanner.scanChar();
fExpectedVersionString[14] = (char) quoteChar;
for (int versionPos = 0; versionPos < XML11_VERSION.length; versionPos++) {
fExpectedVersionString[15 + versionPos] = (char) scanner.scanChar();
}
// REVISIT: should we check whether this equals quoteChar?
fExpectedVersionString[18] = (char) scanner.scanChar();
fixupCurrentEntity(fEntityManager, fExpectedVersionString, 19);
int matched = 0;
for (; matched < XML11_VERSION.length; matched++) {
if (fExpectedVersionString[15 + matched] != XML11_VERSION[matched])
break;
}
if (matched == XML11_VERSION.length)
return Constants.XML_VERSION_1_1;
return Constants.XML_VERSION_1_0;
// premature end of file
}
catch (EOFException e) {
fErrorReporter.reportError(
XMLMessageFormatter.XML_DOMAIN,
"PrematureEOF",
null,
XMLErrorReporter.SEVERITY_FATAL_ERROR);
return Constants.XML_VERSION_1_0;
}
}
| public short determineDocVersion(XMLInputSource inputSource) throws IOException {
fEncoding = fEntityManager.setupCurrentEntity(fXMLSymbol, inputSource, false, true);
// must assume 1.1 at this stage so that whitespace
// handling is correct in the XML decl...
fEntityManager.setScannerVersion(Constants.XML_VERSION_1_1);
XMLEntityScanner scanner = fEntityManager.getEntityScanner();
try {
if (!scanner.skipString("<?xml")) {
// definitely not a well-formed 1.1 doc!
return Constants.XML_VERSION_1_0;
}
if (!scanner.skipSpaces()) {
fixupCurrentEntity(fEntityManager, fExpectedVersionString, 5);
return Constants.XML_VERSION_1_0;
}
if (!scanner.skipString("version")) {
fixupCurrentEntity(fEntityManager, fExpectedVersionString, 6);
return Constants.XML_VERSION_1_0;
}
scanner.skipSpaces();
// Check if the next character is '='. If it is then consume it.
if (scanner.peekChar() != '=') {
fixupCurrentEntity(fEntityManager, fExpectedVersionString, 13);
return Constants.XML_VERSION_1_0;
}
scanner.scanChar();
scanner.skipSpaces();
int quoteChar = scanner.scanChar();
fExpectedVersionString[14] = (char) quoteChar;
for (int versionPos = 0; versionPos < XML11_VERSION.length; versionPos++) {
fExpectedVersionString[15 + versionPos] = (char) scanner.scanChar();
}
// REVISIT: should we check whether this equals quoteChar?
fExpectedVersionString[18] = (char) scanner.scanChar();
fixupCurrentEntity(fEntityManager, fExpectedVersionString, 19);
int matched = 0;
for (; matched < XML11_VERSION.length; matched++) {
if (fExpectedVersionString[15 + matched] != XML11_VERSION[matched])
break;
}
if (matched == XML11_VERSION.length)
return Constants.XML_VERSION_1_1;
return Constants.XML_VERSION_1_0;
// premature end of file
}
catch (EOFException e) {
fErrorReporter.reportError(
XMLMessageFormatter.XML_DOMAIN,
"PrematureEOF",
null,
XMLErrorReporter.SEVERITY_FATAL_ERROR);
return Constants.XML_VERSION_1_0;
}
}
|
diff --git a/code/server/app/Import.java b/code/server/app/Import.java
index 852dfe5..f769ed7 100644
--- a/code/server/app/Import.java
+++ b/code/server/app/Import.java
@@ -1,86 +1,87 @@
import models.Transaction;
import models.User;
import org.apache.commons.io.IOUtils;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import play.jobs.Job;
import play.jobs.OnApplicationStart;
import play.test.Fixtures;
import play.vfs.VirtualFile;
import utils.FmtUtil;
import utils.ModelHelper;
import java.io.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
@OnApplicationStart
public class Import extends Job {
private static final Logger logger = Logger.getLogger(
Import.class.getName());
private final SimpleDateFormat dateFormat = new SimpleDateFormat(
"dd.MM.yyyy");
public void doJob() {
loadUsersFromFixture();
loadTransactionsFromCsv();
}
private void loadUsersFromFixture() {
if (User.count() == 0) {
Fixtures.load("fixtures-local.yml");
}
}
private void loadTransactionsFromCsv() {
if (Transaction.count() == 0) {
File f = VirtualFile.fromRelativePath(
"/conf/fixture-transactions-full.csv").getRealFile();
User user = User.all().first();
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(new FileInputStream(f)));
String line;
while ((line = reader.readLine()) != null) {
Transaction t = parseTransaction(line);
if (t != null) {
t.user = user;
t.save();
}
}
} catch (IOException e) {
logger.log(Level.ERROR, e);
} finally {
IOUtils.closeQuietly(reader);
}
}
}
private Transaction parseTransaction(String line) {
String[] s = line.split("_");
try {
Date accountingDate = dateFormat.parse(s[0]);
String text = s[4];
Double out = Double.parseDouble(s[5]);
Double in = Double.parseDouble(s[6]);
Transaction t = new Transaction();
t.accountingDate = accountingDate;
t.type = ModelHelper.insertIgnoreType(s[3]);
t.text = text;
t.trimmedText = FmtUtil.trimTransactionText(text).trim();
t.amountOut = out;
t.amountIn = in;
t.tag = ModelHelper.insertIgnoreTag(s[7]);
t.tag.imageId = Integer.parseInt(s[8], 16);
+ t.tag.save();
t.internal = false;
t.dirty = false;
t.timestamp = t.accountingDate.getTime();
return t;
} catch (ParseException e) {
logger.log(Level.ERROR, e);
}
return null;
}
}
| true | true | private Transaction parseTransaction(String line) {
String[] s = line.split("_");
try {
Date accountingDate = dateFormat.parse(s[0]);
String text = s[4];
Double out = Double.parseDouble(s[5]);
Double in = Double.parseDouble(s[6]);
Transaction t = new Transaction();
t.accountingDate = accountingDate;
t.type = ModelHelper.insertIgnoreType(s[3]);
t.text = text;
t.trimmedText = FmtUtil.trimTransactionText(text).trim();
t.amountOut = out;
t.amountIn = in;
t.tag = ModelHelper.insertIgnoreTag(s[7]);
t.tag.imageId = Integer.parseInt(s[8], 16);
t.internal = false;
t.dirty = false;
t.timestamp = t.accountingDate.getTime();
return t;
} catch (ParseException e) {
logger.log(Level.ERROR, e);
}
return null;
}
| private Transaction parseTransaction(String line) {
String[] s = line.split("_");
try {
Date accountingDate = dateFormat.parse(s[0]);
String text = s[4];
Double out = Double.parseDouble(s[5]);
Double in = Double.parseDouble(s[6]);
Transaction t = new Transaction();
t.accountingDate = accountingDate;
t.type = ModelHelper.insertIgnoreType(s[3]);
t.text = text;
t.trimmedText = FmtUtil.trimTransactionText(text).trim();
t.amountOut = out;
t.amountIn = in;
t.tag = ModelHelper.insertIgnoreTag(s[7]);
t.tag.imageId = Integer.parseInt(s[8], 16);
t.tag.save();
t.internal = false;
t.dirty = false;
t.timestamp = t.accountingDate.getTime();
return t;
} catch (ParseException e) {
logger.log(Level.ERROR, e);
}
return null;
}
|
diff --git a/examples/fixengine/examples/console/commands/Config.java b/examples/fixengine/examples/console/commands/Config.java
index 1f4d4d01..6abacb3d 100644
--- a/examples/fixengine/examples/console/commands/Config.java
+++ b/examples/fixengine/examples/console/commands/Config.java
@@ -1,73 +1,73 @@
/*
* Copyright 2010 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 fixengine.examples.console.commands;
import java.util.Scanner;
import fixengine.Version;
import fixengine.examples.console.ConsoleClient;
public class Config implements Command {
public void execute(ConsoleClient client, Scanner scanner) throws CommandArgException {
client.setConfig(config(scanner));
}
private fixengine.Config config(Scanner scanner) throws CommandArgException {
fixengine.Config config = new fixengine.Config();
config.setVersion(version(scanner));
config.setSenderCompId(senderCompID(scanner));
config.setTargetCompId(targetCompID(scanner));
config.setSenderSubID(senderSubID(scanner));
config.setTargetSubID(targetSubID(scanner));
return config;
}
private Version version(Scanner scanner) throws CommandArgException {
if (!scanner.hasNext())
throw new CommandArgException("version must be specified");
String value = scanner.next();
for (Version version : Version.values()) {
if (version.value().equals(value.toUpperCase())) {
return version;
}
}
- throw new CommandArgException("unknown version: '%s'".format(value));
+ throw new CommandArgException("unknown version: '" + value + "'");
}
private String senderCompID(Scanner scanner) throws CommandArgException {
if (!scanner.hasNext())
throw new CommandArgException("senderCompID must be specified");
return scanner.next();
}
private String targetCompID(Scanner scanner) throws CommandArgException {
if (!scanner.hasNext())
throw new CommandArgException("targetCompID must be specified");
return scanner.next();
}
private String senderSubID(Scanner scanner) throws CommandArgException {
if (!scanner.hasNext())
return null;
return scanner.next();
}
private String targetSubID(Scanner scanner) throws CommandArgException {
if (!scanner.hasNext())
return null;
return scanner.next();
}
}
| true | true | private Version version(Scanner scanner) throws CommandArgException {
if (!scanner.hasNext())
throw new CommandArgException("version must be specified");
String value = scanner.next();
for (Version version : Version.values()) {
if (version.value().equals(value.toUpperCase())) {
return version;
}
}
throw new CommandArgException("unknown version: '%s'".format(value));
}
| private Version version(Scanner scanner) throws CommandArgException {
if (!scanner.hasNext())
throw new CommandArgException("version must be specified");
String value = scanner.next();
for (Version version : Version.values()) {
if (version.value().equals(value.toUpperCase())) {
return version;
}
}
throw new CommandArgException("unknown version: '" + value + "'");
}
|
diff --git a/src/com/strategy/havannah/logic/PathsIter.java b/src/com/strategy/havannah/logic/PathsIter.java
index b1d294a..b373e2b 100644
--- a/src/com/strategy/havannah/logic/PathsIter.java
+++ b/src/com/strategy/havannah/logic/PathsIter.java
@@ -1,178 +1,183 @@
package com.strategy.havannah.logic;
import net.sf.javabdd.BDD;
import net.sf.javabdd.BDDFactory;
import com.strategy.api.board.Board;
import com.strategy.api.logic.PathCalculator;
import com.strategy.api.logic.Position;
import com.strategy.util.Debug;
import com.strategy.util.StoneColor;
import com.strategy.util.operation.Logging;
import com.strategy.util.preferences.Preferences;
/**
* TODO matrices are symmetrical - can be exploited to save memory
*
* @author Ralph Dürig
*/
public class PathsIter implements PathCalculator {
private BDDFactory fac;
private Board board;
private Logging logPandQ = Logging.create("iterative: p and q");
private Logging logNPandNQ = Logging.create("iterative: not p and not q");
private Logging logPMandMQ = Logging.create("iterative: pm and mq");
private Logging logPQorPMMQ = Logging
.create("iterative: pq or (pm and mq)");
private BDD[] reachWhite;
private BDD[] reachBlack;
private int rec;
/**
*
*/
public PathsIter(BDDFactory fac, Board board) {
this.fac = fac;
this.board = board;
this.rec = 0;
Debug initlog = Debug.create("iteratively creating reachability");
initReachability();
initlog.log();
}
public BDD getPath(Position p, Position q, StoneColor color) {
Integer indexP = board.getField(p.getRow(), p.getCol()).getIndex();
Integer indexQ = board.getField(q.getRow(), q.getCol()).getIndex();
int V = board.getRows() * board.getColumns();
BDD path;
if (color.equals(StoneColor.WHITE)) {
path = reachWhite[V * indexP + indexQ].id();
} else {
path = reachBlack[V * indexP + indexQ].id();
}
return path;
}
public void log() {
if (null != Preferences.getInstance().getOut()) {
Preferences.getInstance().getOut()
.println("all iterations: " + rec);
}
logPandQ.log();
logNPandNQ.log();
logPMandMQ.log();
logPQorPMMQ.log();
}
public void done() {
freeMatrix(reachWhite);
freeMatrix(reachBlack);
}
// ************************************************************************
private void initReachability() {
// number of vertices
int V = board.getColumns() * board.getRows();
// adjacency matrix with bdd style
reachWhite = new BDD[V * V];
reachBlack = new BDD[V * V];
for (int p = 0; p < V; p++) {
if (!board.isValidField(p)) {
continue;
}
for (int q = 0; q < V; q++) {
if (!board.isValidField(q)) {
continue;
}
Position posP = board.getField(p).getPosition();
Position posQ = board.getField(q).getPosition();
if (posP.isNeighbour(posQ)) {
reachWhite[V * p + q] = logPandQ.andLog(fac.ithVar(p),
fac.ithVar(q));
reachBlack[V * p + q] = logNPandNQ.andLog(fac.nithVar(p),
fac.nithVar(q));
} else {
- reachWhite[V * p + q] = fac.zero();
- reachBlack[V * p + q] = fac.zero();
+ if (posP.equals(posQ)) {
+ reachWhite[V * p + q] = fac.one();
+ reachBlack[V * p + q] = fac.one();
+ } else {
+ reachWhite[V * p + q] = fac.zero();
+ reachBlack[V * p + q] = fac.zero();
+ }
}
}
}
// printMatrix(reachWhite);
// reachability matrix with floyd-warshall-algorithm and bdd style also
for (int k = 0; k < V; k++) {
if (!board.isValidField(k)) {
continue;
}
// Pick all vertices as source one by one
for (int i = 0; i < V; i++) {
if (!board.isValidField(i) || i == k) {
continue;
}
// Pick all vertices as destination for the
// above picked source
for (int j = 0; j < V; j++) {
if (!board.isValidField(j) || j == k || j == i) {
continue;
}
rec++;
// If vertex k is on a path from i to j,
// then make sure that the value of reach[i][j] is 1
doReach(reachWhite, k, i, j, board);
doReach(reachBlack, k, i, j, board);
}
}
}
}
private void doReach(BDD[] todo, int m, int p, int q, Board b) {
int V = board.getRows() * board.getColumns();
BDD reachpq = todo[V * p + q];
BDD reachpm = todo[V * p + m];
BDD reachmq = todo[V * m + q];
// todo[p][q] = reachpq.or(reachpm.and(reachmq));
// System.out.println("p=" + p + ", q=" + q + ", m=" + m);
todo[V * p + q] = logPQorPMMQ.orLog(reachpq,
logPMandMQ.andLog(reachpm.id(), reachmq.id()));
}
private void freeMatrix(BDD[] reach) {
for (int i = 0; i < reach.length; i++) {
if (null != reach[i]) {
reach[i].free();
}
}
}
private void printMatrix(BDD[] reach) {
System.out
.println("Following matrix is transitive closure of the given graph");
int limit = board.getRows() * board.getColumns();
for (int i = 0; i < reach.length; i++) {
if (i % limit == 0) {
System.out.println();
}
if (null != reach[i]) {
System.out.print(i / limit + "x" + i % limit + " O ");
} else {
System.out.print(" null ");
}
}
System.out.println();
}
}
| true | true | private void initReachability() {
// number of vertices
int V = board.getColumns() * board.getRows();
// adjacency matrix with bdd style
reachWhite = new BDD[V * V];
reachBlack = new BDD[V * V];
for (int p = 0; p < V; p++) {
if (!board.isValidField(p)) {
continue;
}
for (int q = 0; q < V; q++) {
if (!board.isValidField(q)) {
continue;
}
Position posP = board.getField(p).getPosition();
Position posQ = board.getField(q).getPosition();
if (posP.isNeighbour(posQ)) {
reachWhite[V * p + q] = logPandQ.andLog(fac.ithVar(p),
fac.ithVar(q));
reachBlack[V * p + q] = logNPandNQ.andLog(fac.nithVar(p),
fac.nithVar(q));
} else {
reachWhite[V * p + q] = fac.zero();
reachBlack[V * p + q] = fac.zero();
}
}
}
// printMatrix(reachWhite);
// reachability matrix with floyd-warshall-algorithm and bdd style also
for (int k = 0; k < V; k++) {
if (!board.isValidField(k)) {
continue;
}
// Pick all vertices as source one by one
for (int i = 0; i < V; i++) {
if (!board.isValidField(i) || i == k) {
continue;
}
// Pick all vertices as destination for the
// above picked source
for (int j = 0; j < V; j++) {
if (!board.isValidField(j) || j == k || j == i) {
continue;
}
rec++;
// If vertex k is on a path from i to j,
// then make sure that the value of reach[i][j] is 1
doReach(reachWhite, k, i, j, board);
doReach(reachBlack, k, i, j, board);
}
}
}
}
| private void initReachability() {
// number of vertices
int V = board.getColumns() * board.getRows();
// adjacency matrix with bdd style
reachWhite = new BDD[V * V];
reachBlack = new BDD[V * V];
for (int p = 0; p < V; p++) {
if (!board.isValidField(p)) {
continue;
}
for (int q = 0; q < V; q++) {
if (!board.isValidField(q)) {
continue;
}
Position posP = board.getField(p).getPosition();
Position posQ = board.getField(q).getPosition();
if (posP.isNeighbour(posQ)) {
reachWhite[V * p + q] = logPandQ.andLog(fac.ithVar(p),
fac.ithVar(q));
reachBlack[V * p + q] = logNPandNQ.andLog(fac.nithVar(p),
fac.nithVar(q));
} else {
if (posP.equals(posQ)) {
reachWhite[V * p + q] = fac.one();
reachBlack[V * p + q] = fac.one();
} else {
reachWhite[V * p + q] = fac.zero();
reachBlack[V * p + q] = fac.zero();
}
}
}
}
// printMatrix(reachWhite);
// reachability matrix with floyd-warshall-algorithm and bdd style also
for (int k = 0; k < V; k++) {
if (!board.isValidField(k)) {
continue;
}
// Pick all vertices as source one by one
for (int i = 0; i < V; i++) {
if (!board.isValidField(i) || i == k) {
continue;
}
// Pick all vertices as destination for the
// above picked source
for (int j = 0; j < V; j++) {
if (!board.isValidField(j) || j == k || j == i) {
continue;
}
rec++;
// If vertex k is on a path from i to j,
// then make sure that the value of reach[i][j] is 1
doReach(reachWhite, k, i, j, board);
doReach(reachBlack, k, i, j, board);
}
}
}
}
|
diff --git a/src/net/java/sip/communicator/plugin/updatechecker/UpdateCheckActivator.java b/src/net/java/sip/communicator/plugin/updatechecker/UpdateCheckActivator.java
index ee8c36574..07772109b 100644
--- a/src/net/java/sip/communicator/plugin/updatechecker/UpdateCheckActivator.java
+++ b/src/net/java/sip/communicator/plugin/updatechecker/UpdateCheckActivator.java
@@ -1,751 +1,750 @@
/*
* SIP Communicator, the OpenSource Java VoIP and Instant Messaging client.
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
package net.java.sip.communicator.plugin.updatechecker;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Toolkit;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import java.security.cert.*;
import java.util.*;
import javax.net.ssl.*;
import javax.swing.*;
import net.java.sip.communicator.service.browserlauncher.*;
import net.java.sip.communicator.service.configuration.*;
import net.java.sip.communicator.service.contactlist.*;
import net.java.sip.communicator.service.gui.*;
import net.java.sip.communicator.service.protocol.*;
import net.java.sip.communicator.service.resources.*;
import net.java.sip.communicator.service.version.*;
import net.java.sip.communicator.util.*;
import net.java.sip.communicator.util.swing.*;
import org.osgi.framework.*;
/**
* Activates the UpdateCheck plugin
*
* @author Damian Minkov
*/
public class UpdateCheckActivator
implements BundleActivator
{
private static final Logger logger
= Logger.getLogger(UpdateCheckActivator.class);
private static BundleContext bundleContext = null;
private static BrowserLauncherService browserLauncherService;
private static ResourceManagementService resourcesService;
private static ConfigurationService configService;
private static UIService uiService = null;
private String downloadLink = null;
private String lastVersion = null;
private String changesLink = null;
private static UserCredentials userCredentials = null;
private static final String UPDATE_USERNAME_CONFIG =
"net.java.sip.communicator.plugin.updatechecker.UPDATE_SITE_USERNAME";
private static final String UPDATE_PASSWORD_CONFIG =
"net.java.sip.communicator.plugin.updatechecker.UPDATE_SITE_PASSWORD";
static
{
removeDownloadRestrictions();
}
/**
* Starts this bundle
*
* @param bundleContext BundleContext
* @throws Exception
*/
public void start(BundleContext bundleContext) throws Exception
{
try
{
logger.logEntry();
UpdateCheckActivator.bundleContext = bundleContext;
}
finally
{
logger.logExit();
}
String osName = System.getProperty("os.name");
if (osName.startsWith("Windows"))
{
// register update button
Hashtable<String, String> toolsMenuFilter
= new Hashtable<String, String>();
toolsMenuFilter.put( Container.CONTAINER_ID,
Container.CONTAINER_HELP_MENU.getID());
bundleContext.registerService(
PluginComponent.class.getName(),
new UpdateMenuButtonComponent(
Container.CONTAINER_HELP_MENU),
toolsMenuFilter);
}
if(isNewestVersion())
return;
if (osName.startsWith("Windows"))
{
windowsUpdaterShow();
return;
}
final JDialog dialog = new SIPCommDialog()
{
protected void close(boolean isEscaped)
{
}
};
dialog.setTitle(
getResources().getI18NString("plugin.updatechecker.DIALOG_TITLE"));
JEditorPane contentMessage = new JEditorPane();
contentMessage.setContentType("text/html");
contentMessage.setOpaque(false);
contentMessage.setEditable(false);
String dialogMsg =
getResources().getI18NString("plugin.updatechecker.DIALOG_MESSAGE",
new String[]{getResources()
.getSettingsString("service.gui.APPLICATION_NAME")});
if(lastVersion != null)
dialogMsg +=
getResources().getI18NString(
"plugin.updatechecker.DIALOG_MESSAGE_2",
new String[]{
getResources().getSettingsString(
"service.gui.APPLICATION_NAME"),
lastVersion});
contentMessage.setText(dialogMsg);
JPanel contentPane = new TransparentPanel(new BorderLayout(5,5));
contentPane.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
contentPane.add(contentMessage, BorderLayout.CENTER);
JPanel buttonPanel
= new TransparentPanel(new FlowLayout(FlowLayout.CENTER, 10, 10));
JButton closeButton = new JButton(
getResources().getI18NString("plugin.updatechecker.BUTTON_CLOSE"));
closeButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
dialog.setVisible(false);
}
});
if(downloadLink != null)
{
JButton downloadButton = new JButton(getResources().getI18NString(
"plugin.updatechecker.BUTTON_DOWNLOAD"));
downloadButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
getBrowserLauncher().openURL(downloadLink);
dialog.dispose();
}
});
buttonPanel.add(downloadButton);
}
buttonPanel.add(closeButton);
contentPane.add(buttonPanel, BorderLayout.SOUTH);
dialog.setContentPane(contentPane);
dialog.pack();
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
dialog.setLocation(
screenSize.width/2 - dialog.getWidth()/2,
screenSize.height/2 - dialog.getHeight()/2
);
dialog.setVisible(true);
}
/**
* stop the bundle
*/
public void stop(BundleContext bundleContext) throws Exception
{
}
/**
* Returns the <tt>BrowserLauncherService</tt> obtained from the bundle
* context.
* @return the <tt>BrowserLauncherService</tt> obtained from the bundle
* context
*/
public static BrowserLauncherService getBrowserLauncher()
{
if (browserLauncherService == null)
{
ServiceReference serviceReference = bundleContext
.getServiceReference(BrowserLauncherService.class.getName());
browserLauncherService = (BrowserLauncherService) bundleContext
.getService(serviceReference);
}
return browserLauncherService;
}
/**
* Returns the <tt>ConfigurationService</tt> obtained from the bundle
* context.
*
* @return the <tt>ConfigurationService</tt> obtained from the bundle
* context
*/
public static ConfigurationService getConfigurationService()
{
if (configService == null)
{
ServiceReference configReference =
bundleContext.getServiceReference(ConfigurationService.class
.getName());
configService =
(ConfigurationService) bundleContext
.getService(configReference);
}
return configService;
}
/**
* Returns a reference to the UIService implementation currently registered
* in the bundle context or null if no such implementation was found.
*
* @return a reference to a UIService implementation currently registered
* in the bundle context or null if no such implementation was found.
*/
public static UIService getUIService()
{
if(uiService == null)
{
ServiceReference uiServiceReference
= bundleContext.getServiceReference(
UIService.class.getName());
uiService = (UIService)bundleContext
.getService(uiServiceReference);
}
return uiService;
}
public static ResourceManagementService getResources()
{
if (resourcesService == null)
{
ServiceReference serviceReference = bundleContext
.getServiceReference(ResourceManagementService.class.getName());
if(serviceReference == null)
return null;
resourcesService = (ResourceManagementService) bundleContext
.getService(serviceReference);
}
return resourcesService;
}
/**
* Check the first link as files on the web are sorted by date
* @param currentVersionStr
* @return
*/
private boolean isNewestVersion()
{
try
{
ServiceReference serviceReference = bundleContext
.getServiceReference( net.java.sip.communicator.service.version.
VersionService.class.getName());
VersionService verService = (VersionService) bundleContext
.getService(serviceReference);
net.java.sip.communicator.service.version.Version
ver = verService.getCurrentVersion();
String configString = Resources.getConfigString("update_link");
if(configString == null)
{
logger.debug("Updates are disabled. Faking latest version.");
return true;
}
URL url = new URL(configString);
Properties props = new Properties();
props.load(url.openStream());
lastVersion = props.getProperty("last_version");
downloadLink = props.getProperty("download_link");
changesLink =
configString.substring(0, configString.lastIndexOf("/") + 1) +
props.getProperty("changes_html");
return lastVersion.compareTo(ver.toString()) <= 0;
}
catch (Exception e)
{
logger.warn("Cannot get and compare versions!");
logger.debug("Error was: ", e);
// if we get an exception this mean we were unable to compare versions
// will return that current is newest to prevent opening info dialog
// about new version
return true;
}
}
/**
* Shows dialog informing about new version with button Install
* which trigers the update process.
*/
private void windowsUpdaterShow()
{
final JDialog dialog = new SIPCommDialog()
{
protected void close(boolean isEscaped)
{
}
};
dialog.setTitle(
getResources().getI18NString("plugin.updatechecker.DIALOG_TITLE"));
JEditorPane contentMessage = new JEditorPane();
contentMessage.setContentType("text/html");
contentMessage.setOpaque(false);
contentMessage.setEditable(false);
String dialogMsg =
getResources().getI18NString("plugin.updatechecker.DIALOG_MESSAGE",
new String[]{getResources()
.getSettingsString("service.gui.APPLICATION_NAME")});
if(lastVersion != null)
dialogMsg +=
getResources().getI18NString(
"plugin.updatechecker.DIALOG_MESSAGE_2",
new String[]{
getResources().getSettingsString(
"service.gui.APPLICATION_NAME"),
lastVersion});
contentMessage.setText(dialogMsg);
JPanel contentPane = new SIPCommFrame.MainContentPane();
contentMessage.setBorder(BorderFactory.createEmptyBorder(10, 0, 20, 0));
contentPane.setBorder(BorderFactory.createEmptyBorder(0, 10, 0, 10));
contentPane.add(contentMessage, BorderLayout.NORTH);
JScrollPane scrollChanges = new JScrollPane();
scrollChanges.setPreferredSize(new Dimension(400, 200));
JEditorPane changesHtml = new JEditorPane();
changesHtml.setContentType("text/html");
changesHtml.setEditable(false);
changesHtml.setBorder(BorderFactory.createLoweredBevelBorder());
scrollChanges.setViewportView(changesHtml);
contentPane.add(scrollChanges, BorderLayout.CENTER);
try
{
changesHtml.setPage(new URL(changesLink));
} catch (Exception e)
{
logger.error("Cannot set changes Page", e);
}
JPanel buttonPanel
= new TransparentPanel(new FlowLayout(FlowLayout.CENTER, 10, 10));
JButton closeButton = new JButton(
getResources().getI18NString("plugin.updatechecker.BUTTON_CLOSE"));
closeButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
dialog.setVisible(false);
}
});
if(downloadLink != null)
{
JButton installButton = new JButton(getResources().getI18NString(
"plugin.updatechecker.BUTTON_INSTALL"));
installButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
dialog.dispose();
windowsUpdate();
}
});
buttonPanel.add(installButton);
}
buttonPanel.add(closeButton);
contentPane.add(buttonPanel, BorderLayout.SOUTH);
dialog.setContentPane(contentPane);
dialog.pack();
dialog.setLocation(
Toolkit.getDefaultToolkit().getScreenSize().width/2
- dialog.getWidth()/2,
Toolkit.getDefaultToolkit().getScreenSize().height/2
- dialog.getHeight()/2
);
dialog.setVisible(true);
}
/**
* The update process itself.
* - Downloads the installer in a temp directory.
* - Warns that update will shutdown.
* - Triggers update (installer) in separate process with the help
* of update.exe and shutdowns.
*/
private void windowsUpdate()
{
File tempF = null;
try
{
final File temp = File.createTempFile("sc-install", ".exe");
tempF = temp;
URL u = new URL(downloadLink);
URLConnection uc = u.openConnection();
if (uc instanceof HttpURLConnection)
{
int responseCode = ((HttpURLConnection) uc).getResponseCode();
if(responseCode == HttpURLConnection.HTTP_UNAUTHORIZED)
{
new Thread(new Runnable()
{
public void run()
{
ExportedWindow authWindow =
getUIService().getExportedWindow(
ExportedWindow.AUTHENTICATION_WINDOW);
UserCredentials cred = new UserCredentials();
authWindow.setParams(new Object[]{cred});
authWindow.setVisible(true);
userCredentials = cred;
if(cred.getUserName() == null)
{
userCredentials = null;
}
else
windowsUpdate();
}
}).start();
}
else if(responseCode == HttpURLConnection.HTTP_OK
&& userCredentials != null
&& userCredentials.getUserName() != null
&& userCredentials.isPasswordPersistent())
{
// if save password is checked save the pass
getConfigurationService().setProperty(
UPDATE_USERNAME_CONFIG, userCredentials.getUserName());
getConfigurationService().setProperty(
UPDATE_PASSWORD_CONFIG, new String(Base64.encode(
userCredentials.getPasswordAsString().getBytes())));
}
}
InputStream in = uc.getInputStream();
// Chain a ProgressMonitorInputStream to the
// URLConnection's InputStream
final ProgressMonitorInputStream pin
= new ProgressMonitorInputStream(null, u.toString(), in);
// Set the maximum value of the ProgressMonitor
ProgressMonitor pm = pin.getProgressMonitor();
pm.setMaximum(uc.getContentLength());
final BufferedOutputStream out =
new BufferedOutputStream(new FileOutputStream(temp));
new Thread(new Runnable()
{
public void run()
{
try
{
int read = -1;
byte[] buff = new byte[1024];
while((read = pin.read(buff)) != -1)
{
out.write(buff, 0, read);
}
pin.close();
out.flush();
out.close();
if(getUIService().getPopupDialog().showConfirmPopupDialog(
getResources().getI18NString(
"plugin.updatechecker.DIALOG_WARN"),
getResources().getI18NString(
"plugin.updatechecker.DIALOG_TITLE"),
PopupDialog.YES_NO_OPTION,
PopupDialog.QUESTION_MESSAGE
) != PopupDialog.YES_OPTION)
{
return;
}
// file saved. Now start updater and shutdown.
String workingDir = System.getProperty("user.dir");
ProcessBuilder processBuilder
= new ProcessBuilder(
new String[]
{
- workingDir + File.separator + "updater.exe",
- temp.getCanonicalPath()
+ workingDir + File.separator + "up2date.exe",
+ "--allow-elevation",
+ temp.getCanonicalPath(),
+ workingDir
});
- processBuilder.environment().put(
- "SIP_COMMUNICATOR_AUTOUPDATE_INSTALLDIR",
- workingDir);
processBuilder.start();
getUIService().beginShutdown();
} catch (Exception e)
{
logger.error("Error saving", e);
try
{
pin.close();
out.close();
} catch (Exception e1)
{}
}
}
}).start();
}
catch(FileNotFoundException e)
{
getUIService().getPopupDialog().showMessagePopupDialog(
getResources().getI18NString("plugin.updatechecker.DIALOG_MISSING_UPDATE"),
getResources().getI18NString("plugin.updatechecker.DIALOG_NOUPDATE_TITLE"),
PopupDialog.INFORMATION_MESSAGE);
tempF.delete();
}
catch (Exception e)
{
logger.info("Error starting update process!", e);
tempF.delete();
}
}
/**
* Invokes action for checking for updates.
*/
private void checkForUpdate()
{
if(isNewestVersion())
{
getUIService().getPopupDialog().showMessagePopupDialog(
getResources().getI18NString("plugin.updatechecker.DIALOG_NOUPDATE"),
getResources().getI18NString("plugin.updatechecker.DIALOG_NOUPDATE_TITLE"),
PopupDialog.INFORMATION_MESSAGE);
}
else
windowsUpdaterShow();
}
/**
* Installs Dummy TrustManager will not try to validate self-signed certs.
* Fix some problems with not proper use of certs.
*/
private static void removeDownloadRestrictions()
{
try
{
SSLContext sc = SSLContext.getInstance("SSLv3");
TrustManager[] tma = {new DummyTrustManager()};
sc.init(null, tma, null);
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
}
catch (Exception e)
{
logger.warn("Failed to init dummy trust magaer", e);
}
HostnameVerifier hv = new HostnameVerifier()
{
public boolean verify(String urlHostName, SSLSession session)
{
logger.warn("Warning: URL Host: " + urlHostName +
" vs. " + session.getPeerHost());
return true;
}
};
HttpsURLConnection.setDefaultHostnameVerifier(hv);
Authenticator.setDefault(new Authenticator()
{
protected PasswordAuthentication getPasswordAuthentication()
{
// if there is something save return it
String uName = (String)getConfigurationService().
getProperty(UPDATE_USERNAME_CONFIG);
if(uName != null)
{
String pass = (String)getConfigurationService().
getProperty(UPDATE_PASSWORD_CONFIG);
if(pass != null)
return new PasswordAuthentication(uName,
new String(Base64.decode(pass)).toCharArray());
}
if(userCredentials != null)
{
return new PasswordAuthentication(
userCredentials.getUserName(),
userCredentials.getPassword());
}
else
{
return null;
}
}
});
}
/**
* The menu entry under tools menu.
*/
private class UpdateMenuButtonComponent
implements PluginComponent
{
private final Container container;
private final JMenuItem updateMenuItem
= new JMenuItem(getResources().
getI18NString("plugin.updatechecker.UPDATE_MENU_ENTRY"));
UpdateMenuButtonComponent(Container c)
{
this.container = c;
updateMenuItem.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
checkForUpdate();
}
});
}
public String getName()
{
return getResources().getI18NString(
"plugin.updatechecker.UPDATE_MENU_ENTRY");
}
public Container getContainer()
{
return this.container;
}
public String getConstraints()
{
return null;
}
public int getPositionIndex()
{
return -1;
}
public Object getComponent()
{
return updateMenuItem;
}
public void setCurrentContact(MetaContact metaContact)
{
}
public void setCurrentContactGroup(MetaContactGroup metaGroup)
{
}
public boolean isNativeComponent()
{
return false;
}
}
/**
* Dummy trust manager, trusts everything.
*/
private static class DummyTrustManager
implements X509TrustManager
{
public void checkClientTrusted(X509Certificate[] arg0, String arg1)
throws CertificateException
{
}
public void checkServerTrusted(X509Certificate[] arg0, String arg1)
throws CertificateException
{
}
public X509Certificate[] getAcceptedIssuers()
{
return null;
}
}
}
| false | true | private void windowsUpdate()
{
File tempF = null;
try
{
final File temp = File.createTempFile("sc-install", ".exe");
tempF = temp;
URL u = new URL(downloadLink);
URLConnection uc = u.openConnection();
if (uc instanceof HttpURLConnection)
{
int responseCode = ((HttpURLConnection) uc).getResponseCode();
if(responseCode == HttpURLConnection.HTTP_UNAUTHORIZED)
{
new Thread(new Runnable()
{
public void run()
{
ExportedWindow authWindow =
getUIService().getExportedWindow(
ExportedWindow.AUTHENTICATION_WINDOW);
UserCredentials cred = new UserCredentials();
authWindow.setParams(new Object[]{cred});
authWindow.setVisible(true);
userCredentials = cred;
if(cred.getUserName() == null)
{
userCredentials = null;
}
else
windowsUpdate();
}
}).start();
}
else if(responseCode == HttpURLConnection.HTTP_OK
&& userCredentials != null
&& userCredentials.getUserName() != null
&& userCredentials.isPasswordPersistent())
{
// if save password is checked save the pass
getConfigurationService().setProperty(
UPDATE_USERNAME_CONFIG, userCredentials.getUserName());
getConfigurationService().setProperty(
UPDATE_PASSWORD_CONFIG, new String(Base64.encode(
userCredentials.getPasswordAsString().getBytes())));
}
}
InputStream in = uc.getInputStream();
// Chain a ProgressMonitorInputStream to the
// URLConnection's InputStream
final ProgressMonitorInputStream pin
= new ProgressMonitorInputStream(null, u.toString(), in);
// Set the maximum value of the ProgressMonitor
ProgressMonitor pm = pin.getProgressMonitor();
pm.setMaximum(uc.getContentLength());
final BufferedOutputStream out =
new BufferedOutputStream(new FileOutputStream(temp));
new Thread(new Runnable()
{
public void run()
{
try
{
int read = -1;
byte[] buff = new byte[1024];
while((read = pin.read(buff)) != -1)
{
out.write(buff, 0, read);
}
pin.close();
out.flush();
out.close();
if(getUIService().getPopupDialog().showConfirmPopupDialog(
getResources().getI18NString(
"plugin.updatechecker.DIALOG_WARN"),
getResources().getI18NString(
"plugin.updatechecker.DIALOG_TITLE"),
PopupDialog.YES_NO_OPTION,
PopupDialog.QUESTION_MESSAGE
) != PopupDialog.YES_OPTION)
{
return;
}
// file saved. Now start updater and shutdown.
String workingDir = System.getProperty("user.dir");
ProcessBuilder processBuilder
= new ProcessBuilder(
new String[]
{
workingDir + File.separator + "updater.exe",
temp.getCanonicalPath()
});
processBuilder.environment().put(
"SIP_COMMUNICATOR_AUTOUPDATE_INSTALLDIR",
workingDir);
processBuilder.start();
getUIService().beginShutdown();
} catch (Exception e)
{
logger.error("Error saving", e);
try
{
pin.close();
out.close();
} catch (Exception e1)
{}
}
}
}).start();
}
catch(FileNotFoundException e)
{
getUIService().getPopupDialog().showMessagePopupDialog(
getResources().getI18NString("plugin.updatechecker.DIALOG_MISSING_UPDATE"),
getResources().getI18NString("plugin.updatechecker.DIALOG_NOUPDATE_TITLE"),
PopupDialog.INFORMATION_MESSAGE);
tempF.delete();
}
catch (Exception e)
{
logger.info("Error starting update process!", e);
tempF.delete();
}
}
| private void windowsUpdate()
{
File tempF = null;
try
{
final File temp = File.createTempFile("sc-install", ".exe");
tempF = temp;
URL u = new URL(downloadLink);
URLConnection uc = u.openConnection();
if (uc instanceof HttpURLConnection)
{
int responseCode = ((HttpURLConnection) uc).getResponseCode();
if(responseCode == HttpURLConnection.HTTP_UNAUTHORIZED)
{
new Thread(new Runnable()
{
public void run()
{
ExportedWindow authWindow =
getUIService().getExportedWindow(
ExportedWindow.AUTHENTICATION_WINDOW);
UserCredentials cred = new UserCredentials();
authWindow.setParams(new Object[]{cred});
authWindow.setVisible(true);
userCredentials = cred;
if(cred.getUserName() == null)
{
userCredentials = null;
}
else
windowsUpdate();
}
}).start();
}
else if(responseCode == HttpURLConnection.HTTP_OK
&& userCredentials != null
&& userCredentials.getUserName() != null
&& userCredentials.isPasswordPersistent())
{
// if save password is checked save the pass
getConfigurationService().setProperty(
UPDATE_USERNAME_CONFIG, userCredentials.getUserName());
getConfigurationService().setProperty(
UPDATE_PASSWORD_CONFIG, new String(Base64.encode(
userCredentials.getPasswordAsString().getBytes())));
}
}
InputStream in = uc.getInputStream();
// Chain a ProgressMonitorInputStream to the
// URLConnection's InputStream
final ProgressMonitorInputStream pin
= new ProgressMonitorInputStream(null, u.toString(), in);
// Set the maximum value of the ProgressMonitor
ProgressMonitor pm = pin.getProgressMonitor();
pm.setMaximum(uc.getContentLength());
final BufferedOutputStream out =
new BufferedOutputStream(new FileOutputStream(temp));
new Thread(new Runnable()
{
public void run()
{
try
{
int read = -1;
byte[] buff = new byte[1024];
while((read = pin.read(buff)) != -1)
{
out.write(buff, 0, read);
}
pin.close();
out.flush();
out.close();
if(getUIService().getPopupDialog().showConfirmPopupDialog(
getResources().getI18NString(
"plugin.updatechecker.DIALOG_WARN"),
getResources().getI18NString(
"plugin.updatechecker.DIALOG_TITLE"),
PopupDialog.YES_NO_OPTION,
PopupDialog.QUESTION_MESSAGE
) != PopupDialog.YES_OPTION)
{
return;
}
// file saved. Now start updater and shutdown.
String workingDir = System.getProperty("user.dir");
ProcessBuilder processBuilder
= new ProcessBuilder(
new String[]
{
workingDir + File.separator + "up2date.exe",
"--allow-elevation",
temp.getCanonicalPath(),
workingDir
});
processBuilder.start();
getUIService().beginShutdown();
} catch (Exception e)
{
logger.error("Error saving", e);
try
{
pin.close();
out.close();
} catch (Exception e1)
{}
}
}
}).start();
}
catch(FileNotFoundException e)
{
getUIService().getPopupDialog().showMessagePopupDialog(
getResources().getI18NString("plugin.updatechecker.DIALOG_MISSING_UPDATE"),
getResources().getI18NString("plugin.updatechecker.DIALOG_NOUPDATE_TITLE"),
PopupDialog.INFORMATION_MESSAGE);
tempF.delete();
}
catch (Exception e)
{
logger.info("Error starting update process!", e);
tempF.delete();
}
}
|
diff --git a/src/org/jruby/debug/DebugEventHook.java b/src/org/jruby/debug/DebugEventHook.java
index 40157ae..6d7e5e6 100644
--- a/src/org/jruby/debug/DebugEventHook.java
+++ b/src/org/jruby/debug/DebugEventHook.java
@@ -1,625 +1,625 @@
/*
* header & license
* Copyright (c) 2007-2008 Martin Krauskopf
* Copyright (c) 2007 Peter Brant
*
* 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 org.jruby.debug;
import java.io.File;
import org.jruby.MetaClass;
import org.jruby.Ruby;
import org.jruby.RubyArray;
import org.jruby.RubyBinding;
import org.jruby.RubyBoolean;
import org.jruby.RubyFile;
import org.jruby.RubyFixnum;
import org.jruby.RubyFloat;
import org.jruby.RubyKernel;
import org.jruby.RubyModule;
import org.jruby.RubyNil;
import org.jruby.RubyObject;
import org.jruby.RubyString;
import org.jruby.RubySymbol;
import org.jruby.RubyThread;
import org.jruby.debug.DebugContext.StopReason;
import org.jruby.debug.DebugFrame.Info;
import org.jruby.debug.Debugger.DebugContextPair;
import org.jruby.exceptions.RaiseException;
import org.jruby.runtime.Block;
import org.jruby.runtime.EventHook;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.builtin.IRubyObject;
final class DebugEventHook implements EventHook {
private final Debugger debugger;
private final Ruby runtime;
private int hookCount;
private int lastDebuggedThnum;
private int lastCheck;
private boolean inDebugger;
public DebugEventHook(final Debugger debugger, final Ruby runtime) {
this.debugger = debugger;
lastDebuggedThnum = -1;
this.runtime = runtime;
}
public void event(final ThreadContext tCtx, final int event, final String file, final int line0,
final String methodName, final IRubyObject klass) {
boolean needsSuspend = false;
RubyThread currThread = tCtx.getThread();
DebugContextPair contexts = debugger.threadContextLookup(currThread, true);
// return if thread is marked as 'ignored'. debugger's threads are marked this way
if (contexts.debugContext.isIgnored()) {
return;
}
/* ignore a skipped section of code */
if (contexts.debugContext.isSkipped()) {
cleanUp(contexts.debugContext);
return;
}
/** Ignore JRuby core classes by default. Consider option for enabling it. */
if (Util.isJRubyCore(file)) {
return;
}
needsSuspend = contexts.debugContext.isSuspended();
if (needsSuspend) {
RubyThread.stop(currThread);
}
synchronized (this) {
if (isInDebugger()) {
return;
}
setInDebugger(true);
try {
processEvent(tCtx, event, Util.relativizeToPWD(file), line0, methodName, klass, contexts);
} finally {
setInDebugger(false);
}
}
}
@SuppressWarnings("fallthrough")
private void processEvent(final ThreadContext tCtx, final int event, final String file, final int line0,
final String methodName, final IRubyObject klass, DebugContextPair contexts) {
if (debugger.isDebug()) {
Util.logEvent(event, file, line0, methodName, klass);
}
// one-based; jruby by default passes zero-based
int line = line0 + 1;
hookCount++;
Ruby runtime = tCtx.getRuntime();
IRubyObject breakpoint = getNil();
IRubyObject binding = getNil();
IRubyObject context = contexts.context;
DebugContext debugContext = contexts.debugContext;
// debug("jrubydebug> %s:%d [%s] %s\n", file, line, EVENT_NAMES[event], methodName);
boolean moved = false;
if (debugContext.getLastLine() != line || debugContext.getLastFile() == null || !Util.areSameFiles(debugContext.getLastFile(), file)) {
debugContext.setEnableBreakpoint(true);
moved = true;
}
// else if(event != RUBY_EVENT_RETURN && event != RUBY_EVENT_C_RETURN) {
// if(debug == Qtrue)
// fprintf(stderr, "nodeless [%s] %s\n", get_event_name(event), rb_id2name(methodName));
// goto cleanup;
// } else {
// if(debug == Qtrue)
// fprintf(stderr, "nodeless [%s] %s\n", get_event_name(event), rb_id2name(methodName));
// }
if (event != RUBY_EVENT_LINE) {
debugContext.setStepped(true);
}
switch (event) {
case RUBY_EVENT_LINE:
if (debugContext.getStackSize() == 0) {
saveCallFrame(event, tCtx, file, line, methodName, debugContext);
} else {
updateTopFrame(event, debugContext, tCtx, file, line, methodName);
}
if (debugger.isTracing() || debugContext.isTracing()) {
IRubyObject[] args = new IRubyObject[]{
runtime.newString(file),
runtime.newFixnum(line)
};
context.callMethod(tCtx, DebugContext.AT_TRACING, args);
}
if (debugContext.getDestFrame() == -1 || debugContext.getStackSize() == debugContext.getDestFrame()) {
if (moved || !debugContext.isForceMove()) {
debugContext.setStopNext(debugContext.getStopNext() - 1);
}
if (debugContext.getStopNext() < 0) {
debugContext.setStopNext(-1);
}
if (moved || (debugContext.isStepped() && !debugContext.isForceMove())) {
debugContext.setStopLine(debugContext.getStopLine() - 1);
debugContext.setStepped(false);
}
} else if (debugContext.getStackSize() < debugContext.getDestFrame()) {
debugContext.setStopNext(0);
}
if (debugContext.getStopNext() == 0 || debugContext.getStopLine() == 0 ||
!(breakpoint = checkBreakpointsByPos(debugContext, file, line)).isNil()) {
binding = (tCtx != null ? RubyBinding.newBinding(runtime) : getNil());
saveTopBinding(debugContext, binding);
debugContext.setStopReason(DebugContext.StopReason.STEP);
/* Check breakpoint expression. */
if (!breakpoint.isNil()) {
if (!checkBreakpointExpression(tCtx, breakpoint, binding)) {
break;
}
if (!checkBreakpointHitCondition(breakpoint)) {
break;
}
if (breakpoint != debugContext.getBreakpoint()) {
debugContext.setStopReason(DebugContext.StopReason.BREAKPOINT);
context.callMethod(tCtx, DebugContext.AT_BREAKPOINT, breakpoint);
} else {
debugContext.setBreakpoint(getNil());
}
}
/* reset all pointers */
debugContext.setDestFrame(-1);
debugContext.setStopLine(-1);
debugContext.setStopNext(-1);
callAtLine(tCtx, context, debugContext, runtime, file, line);
}
break;
case RUBY_EVENT_CALL:
saveCallFrame(event, tCtx, file, line, methodName, debugContext);
breakpoint = checkBreakpointsByMethod(debugContext, klass, methodName);
if (!breakpoint.isNil()) {
DebugFrame debugFrame = getTopFrame(debugContext);
if (debugFrame != null) {
binding = debugFrame.getBinding();
}
if (tCtx != null && binding.isNil()) {
binding = RubyBinding.newBinding(runtime);
}
saveTopBinding(debugContext, binding);
if(!checkBreakpointExpression(tCtx, breakpoint, binding)) {
break;
}
if(!checkBreakpointHitCondition(breakpoint)) {
break;
}
if (breakpoint != debugContext.getBreakpoint()) {
debugContext.setStopReason(DebugContext.StopReason.BREAKPOINT);
context.callMethod(tCtx, DebugContext.AT_BREAKPOINT, breakpoint);
} else {
debugContext.setBreakpoint(getNil());
}
callAtLine(tCtx, context, debugContext, runtime, file, line);
}
break;
case RUBY_EVENT_C_CALL:
if(cCallNewFrameP(klass)) {
saveCallFrame(event, tCtx, file, line, methodName, debugContext);
} else {
updateTopFrame(event, debugContext, tCtx, file, line, methodName);
}
break;
case RUBY_EVENT_C_RETURN:
/* note if a block is given we fall through! */
if (!cCallNewFrameP(klass)) {
break;
}
case RUBY_EVENT_RETURN:
case RUBY_EVENT_END:
if (debugContext.getStackSize() == debugContext.getStopFrame()) {
debugContext.setStopNext(1);
debugContext.setStopFrame(0);
}
while (debugContext.getStackSize() > 0) {
DebugFrame topFrame = debugContext.popFrame();
String origMethodName = topFrame.getOrigMethodName();
if ((origMethodName == null && methodName == null) ||
(origMethodName != null && origMethodName.equals(methodName))) {
break;
}
}
debugContext.setEnableBreakpoint(true);
break;
case RUBY_EVENT_CLASS:
resetTopFrameMethodName(debugContext);
saveCallFrame(event, tCtx, file, line, methodName, debugContext);
break;
case RUBY_EVENT_RAISE:
updateTopFrame(event, debugContext, tCtx, file, line, methodName);
// XXX Implement post mortem debugging
IRubyObject exception = runtime.getGlobalVariables().get("$!");
// Might happen if the current ThreadContext is within 'defined?'
if (exception.isNil()) {
assert tCtx.isWithinDefined() : "$! should be nil only when within defined?";
break;
}
if (runtime.getClass("SystemExit").isInstance(exception)) {
// Can't do this because this unhooks the event hook causing
// a ConcurrentModificationException because the runtime
// is still iterating over event hooks. Shouldn't really
// matter. We're on our way out regardless.
// debugger.stop(runtime);
break;
}
if (debugger.getCatchpoints().isNil() || debugger.getCatchpoints().isEmpty()) {
break;
}
RubyArray ancestors = exception.getType().ancestors();
int l = ancestors.getLength();
for (int i = 0; i < l; i++) {
RubyModule module = (RubyModule)ancestors.get(i);
IRubyObject modName = module.name();
IRubyObject hitCount = debugger.getCatchpoints().op_aref(tCtx, modName);
if (!hitCount.isNil()) {
hitCount = runtime.newFixnum(RubyFixnum.fix2int(hitCount) + 1);
debugger.getCatchpoints().op_aset(tCtx, modName, hitCount);
debugContext.setStopReason(DebugContext.StopReason.CATCHPOINT);
- context.callMethod(tCtx, DebugContext.AT_CATCHPOINT, breakpoint);
+ context.callMethod(tCtx, DebugContext.AT_CATCHPOINT, exception);
DebugFrame debugFrame = getTopFrame(debugContext);
if (debugFrame != null) {
binding = debugFrame.getBinding();
}
if (tCtx != null && binding.isNil()) {
binding = RubyBinding.newBinding(runtime);
}
saveTopBinding(debugContext, binding);
callAtLine(tCtx, context, debugContext, runtime, file, line);
break;
}
}
break;
}
cleanUp(debugContext);
}
private IRubyObject getNil() {
return runtime.getNil();
}
private IRubyObject getBreakpoints() {
return debugger.getBreakpoints();
}
private void cleanUp(DebugContext debugContext) {
debugContext.setStopReason(StopReason.NONE);
/* check that all contexts point to alive threads */
if(hookCount - lastCheck > 3000) {
debugger.checkThreadContexts(runtime);
lastCheck = hookCount;
}
}
public boolean isInterestedInEvent(int event) {
return true;
}
private void saveCallFrame(final int event, final ThreadContext tCtx, final String file,
final int line, final String methodName, final DebugContext debugContext) {
IRubyObject binding = (debugger.isKeepFrameBinding()) ? RubyBinding.newBinding(tCtx.getRuntime()) : tCtx.getRuntime().getNil();
DebugFrame debugFrame = new DebugFrame();
debugFrame.setFile(file);
debugFrame.setLine(line);
debugFrame.setBinding(binding);
debugFrame.setMethodName(methodName);
debugFrame.setOrigMethodName(methodName);
debugFrame.setDead(false);
debugFrame.setSelf(tCtx.getFrameSelf());
Info info = debugFrame.getInfo();
info.setFrame(tCtx.getCurrentFrame());
info.setScope(tCtx.getCurrentScope().getStaticScope());
info.setDynaVars(event == RUBY_EVENT_LINE ? tCtx.getCurrentScope() : null);
debugContext.addFrame(debugFrame);
if (debugger.isTrackFrameArgs()) {
copyScalarArgs(tCtx, debugFrame);
} else {
debugFrame.setArgValues(runtime.getNil());
}
}
private boolean isArgValueSmall(IRubyObject value) {
return value == RubyObject.UNDEF ||
value instanceof RubyFixnum ||
value instanceof RubyFloat ||
value instanceof RubyNil ||
value instanceof RubyModule ||
value instanceof RubyFile ||
value instanceof RubyBoolean ||
value instanceof RubySymbol;
}
/** Save scalar arguments or a class name. */
private void copyScalarArgs(ThreadContext tCtx, DebugFrame debugFrame) {
RubyArray args = runtime.newArray(tCtx.getCurrentScope().getArgValues());
int len = args.getLength();
for (int i = 0; i < len; i++) {
IRubyObject obj = args.entry(i);
if (! isArgValueSmall(obj)) {
args.store(i, runtime.newString(obj.getType().getName()));
}
}
debugFrame.setArgValues(args);
}
private void updateTopFrame(int event, DebugContext debug_context, ThreadContext tCtx,
String file, int line, String methodName) {
DebugFrame topFrame = getTopFrame(debug_context);
if (topFrame != null) {
topFrame.setSelf(tCtx.getFrameSelf());
topFrame.setFile(file);
topFrame.setLine(line);
topFrame.setMethodName(methodName);
topFrame.getInfo().setDynaVars(event == RUBY_EVENT_C_CALL ? null : tCtx.getCurrentScope());
}
}
private DebugFrame getTopFrame(final DebugContext debugContext) {
if (debugContext.getStackSize() == 0) {
return null;
} else {
return debugContext.getTopFrame();
}
}
private IRubyObject checkBreakpointsByPos(DebugContext debugContext, String file, int line) {
if (!debugContext.isEnableBreakpoint()) {
return getNil();
}
if (checkBreakpointByPos(debugContext.getBreakpoint(), file, line)) {
return debugContext.getBreakpoint();
}
RubyArray arr = getBreakpoints().convertToArray();
if (arr.isEmpty()) {
return getNil();
}
for (int i = 0; i < arr.size(); i++) {
IRubyObject breakpoint = arr.entry(i);
if (checkBreakpointByPos(breakpoint, file, line)) {
return breakpoint;
}
}
return getNil();
}
private boolean checkBreakpointByPos(IRubyObject breakpoint, String file, int line) {
if (breakpoint.isNil()) {
return false;
}
DebugBreakpoint debugBreakpoint = (DebugBreakpoint) breakpoint.dataGetStruct();
if (!debugBreakpoint.isEnabled()) {
return false;
}
if (debugBreakpoint.getType() != DebugBreakpoint.Type.POS) {
return false;
}
if (debugBreakpoint.getPos().getLine() != line) {
return false;
}
String source = ((RubyString) debugBreakpoint.getSource()).toString();
String sourceName = new File(source).getName();
String fileName = new File(file).getName();
if (sourceName.equals(fileName)) {
return true;
}
return false;
}
private IRubyObject checkBreakpointsByMethod(DebugContext debugContext,
IRubyObject klass, String methodName) {
if (!debugContext.isEnableBreakpoint()) {
return getNil();
}
if (checkBreakpointByMethod(debugContext.getBreakpoint(), klass, methodName)) {
return debugContext.getBreakpoint();
}
RubyArray arr = getBreakpoints().convertToArray();
if (arr.isEmpty()) {
return getNil();
}
for (int i = 0; i < arr.size(); i++) {
IRubyObject breakpoint = arr.entry(i);
if (checkBreakpointByMethod(breakpoint, klass, methodName)) {
return breakpoint;
}
}
return getNil();
}
private boolean checkBreakpointByMethod(IRubyObject breakpoint, IRubyObject klass,
String methodName) {
if (breakpoint.isNil()) {
return false;
}
DebugBreakpoint debugBreakpoint = (DebugBreakpoint) breakpoint.dataGetStruct();
if (!debugBreakpoint.isEnabled()) {
return false;
}
if (debugBreakpoint.getType() != DebugBreakpoint.Type.METHOD) {
return false;
}
if (! debugBreakpoint.getPos().getMethodName().equals(methodName)) {
return false;
}
if (debugBreakpoint.getSource().asString().eql(klass.asString())) {
return true;
}
return false;
}
private boolean checkBreakpointExpression(ThreadContext tCtx, IRubyObject breakpoint, IRubyObject binding) {
DebugBreakpoint debugBreakpoint = (DebugBreakpoint) breakpoint.dataGetStruct();
if (debugBreakpoint.getExpr().isNil()) {
return true;
}
try {
IRubyObject result = RubyKernel.eval(
tCtx,
breakpoint,
new IRubyObject[] { debugBreakpoint.getExpr(), binding },
Block.NULL_BLOCK);
return result.isTrue();
} catch (RaiseException e) {
// XXX Seems like we should tell the user about this, but this how
// ruby-debug behaves
return false;
}
}
private boolean checkBreakpointHitCondition(IRubyObject breakpoint) {
DebugBreakpoint debugBreakpoint = (DebugBreakpoint) breakpoint.dataGetStruct();
debugBreakpoint.setHitCount(debugBreakpoint.getHitCount()+1);
if (debugBreakpoint.getHitCondition() == null) {
return true;
}
switch (debugBreakpoint.getHitCondition()) {
case NONE:
return true;
case GE:
if (debugBreakpoint.getHitCount() >= debugBreakpoint.getHitValue()) {
return true;
}
break;
case EQ:
if (debugBreakpoint.getHitCount() == debugBreakpoint.getHitValue()) {
return true;
}
break;
case MOD:
if (debugBreakpoint.getHitCount() % debugBreakpoint.getHitValue() == 0) {
return true;
}
break;
}
return false;
}
private void saveTopBinding(DebugContext context, IRubyObject binding) {
DebugFrame debugFrame = getTopFrame(context);
if (debugFrame != null) {
debugFrame.setBinding(binding);
}
}
private IRubyObject callAtLine(ThreadContext tCtx,
IRubyObject context, DebugContext debugContext,
Ruby runtime, String file, int line) {
return callAtLine(tCtx, context, debugContext,
runtime.newString(file), runtime.newFixnum(line));
}
private IRubyObject callAtLine(ThreadContext tCtx,
IRubyObject context, DebugContext debugContext,
IRubyObject file, IRubyObject line) {
lastDebuggedThnum = debugContext.getThnum();
saveCurrentPosition(debugContext);
IRubyObject[] args = new IRubyObject[]{
file,
line
};
return context.callMethod(tCtx, DebugContext.AT_LINE, args);
}
private void saveCurrentPosition(final DebugContext debugContext) {
DebugFrame debugFrame = getTopFrame(debugContext);
if (debugFrame == null) {
return;
}
debugContext.setLastFile(debugFrame.getFile());
debugContext.setLastLine(debugFrame.getLine());
debugContext.setEnableBreakpoint(false);
debugContext.setStepped(false);
debugContext.setForceMove(false);
}
private boolean cCallNewFrameP(IRubyObject klass) {
klass = realClass(klass);
// TODO - block_given?
// if(rb_block_given_p()) return true;
String cName = klass.getType().getName();
return "Proc".equals(cName) || "RubyKernel".equals(cName) || "Module".equals(cName);
}
private IRubyObject realClass(IRubyObject klass) {
if (klass instanceof MetaClass) {
return ((MetaClass)klass).getRealClass();
}
return klass;
}
private void resetTopFrameMethodName(DebugContext debugContext) {
DebugFrame topFrame = getTopFrame(debugContext);
if (topFrame != null) {
topFrame.setMethodName("");
}
}
private boolean isInDebugger() {
return inDebugger;
}
private void setInDebugger(boolean inDebugger) {
this.inDebugger = inDebugger;
}
int getLastDebuggedThnum() {
return lastDebuggedThnum;
}
}
| true | true | private void processEvent(final ThreadContext tCtx, final int event, final String file, final int line0,
final String methodName, final IRubyObject klass, DebugContextPair contexts) {
if (debugger.isDebug()) {
Util.logEvent(event, file, line0, methodName, klass);
}
// one-based; jruby by default passes zero-based
int line = line0 + 1;
hookCount++;
Ruby runtime = tCtx.getRuntime();
IRubyObject breakpoint = getNil();
IRubyObject binding = getNil();
IRubyObject context = contexts.context;
DebugContext debugContext = contexts.debugContext;
// debug("jrubydebug> %s:%d [%s] %s\n", file, line, EVENT_NAMES[event], methodName);
boolean moved = false;
if (debugContext.getLastLine() != line || debugContext.getLastFile() == null || !Util.areSameFiles(debugContext.getLastFile(), file)) {
debugContext.setEnableBreakpoint(true);
moved = true;
}
// else if(event != RUBY_EVENT_RETURN && event != RUBY_EVENT_C_RETURN) {
// if(debug == Qtrue)
// fprintf(stderr, "nodeless [%s] %s\n", get_event_name(event), rb_id2name(methodName));
// goto cleanup;
// } else {
// if(debug == Qtrue)
// fprintf(stderr, "nodeless [%s] %s\n", get_event_name(event), rb_id2name(methodName));
// }
if (event != RUBY_EVENT_LINE) {
debugContext.setStepped(true);
}
switch (event) {
case RUBY_EVENT_LINE:
if (debugContext.getStackSize() == 0) {
saveCallFrame(event, tCtx, file, line, methodName, debugContext);
} else {
updateTopFrame(event, debugContext, tCtx, file, line, methodName);
}
if (debugger.isTracing() || debugContext.isTracing()) {
IRubyObject[] args = new IRubyObject[]{
runtime.newString(file),
runtime.newFixnum(line)
};
context.callMethod(tCtx, DebugContext.AT_TRACING, args);
}
if (debugContext.getDestFrame() == -1 || debugContext.getStackSize() == debugContext.getDestFrame()) {
if (moved || !debugContext.isForceMove()) {
debugContext.setStopNext(debugContext.getStopNext() - 1);
}
if (debugContext.getStopNext() < 0) {
debugContext.setStopNext(-1);
}
if (moved || (debugContext.isStepped() && !debugContext.isForceMove())) {
debugContext.setStopLine(debugContext.getStopLine() - 1);
debugContext.setStepped(false);
}
} else if (debugContext.getStackSize() < debugContext.getDestFrame()) {
debugContext.setStopNext(0);
}
if (debugContext.getStopNext() == 0 || debugContext.getStopLine() == 0 ||
!(breakpoint = checkBreakpointsByPos(debugContext, file, line)).isNil()) {
binding = (tCtx != null ? RubyBinding.newBinding(runtime) : getNil());
saveTopBinding(debugContext, binding);
debugContext.setStopReason(DebugContext.StopReason.STEP);
/* Check breakpoint expression. */
if (!breakpoint.isNil()) {
if (!checkBreakpointExpression(tCtx, breakpoint, binding)) {
break;
}
if (!checkBreakpointHitCondition(breakpoint)) {
break;
}
if (breakpoint != debugContext.getBreakpoint()) {
debugContext.setStopReason(DebugContext.StopReason.BREAKPOINT);
context.callMethod(tCtx, DebugContext.AT_BREAKPOINT, breakpoint);
} else {
debugContext.setBreakpoint(getNil());
}
}
/* reset all pointers */
debugContext.setDestFrame(-1);
debugContext.setStopLine(-1);
debugContext.setStopNext(-1);
callAtLine(tCtx, context, debugContext, runtime, file, line);
}
break;
case RUBY_EVENT_CALL:
saveCallFrame(event, tCtx, file, line, methodName, debugContext);
breakpoint = checkBreakpointsByMethod(debugContext, klass, methodName);
if (!breakpoint.isNil()) {
DebugFrame debugFrame = getTopFrame(debugContext);
if (debugFrame != null) {
binding = debugFrame.getBinding();
}
if (tCtx != null && binding.isNil()) {
binding = RubyBinding.newBinding(runtime);
}
saveTopBinding(debugContext, binding);
if(!checkBreakpointExpression(tCtx, breakpoint, binding)) {
break;
}
if(!checkBreakpointHitCondition(breakpoint)) {
break;
}
if (breakpoint != debugContext.getBreakpoint()) {
debugContext.setStopReason(DebugContext.StopReason.BREAKPOINT);
context.callMethod(tCtx, DebugContext.AT_BREAKPOINT, breakpoint);
} else {
debugContext.setBreakpoint(getNil());
}
callAtLine(tCtx, context, debugContext, runtime, file, line);
}
break;
case RUBY_EVENT_C_CALL:
if(cCallNewFrameP(klass)) {
saveCallFrame(event, tCtx, file, line, methodName, debugContext);
} else {
updateTopFrame(event, debugContext, tCtx, file, line, methodName);
}
break;
case RUBY_EVENT_C_RETURN:
/* note if a block is given we fall through! */
if (!cCallNewFrameP(klass)) {
break;
}
case RUBY_EVENT_RETURN:
case RUBY_EVENT_END:
if (debugContext.getStackSize() == debugContext.getStopFrame()) {
debugContext.setStopNext(1);
debugContext.setStopFrame(0);
}
while (debugContext.getStackSize() > 0) {
DebugFrame topFrame = debugContext.popFrame();
String origMethodName = topFrame.getOrigMethodName();
if ((origMethodName == null && methodName == null) ||
(origMethodName != null && origMethodName.equals(methodName))) {
break;
}
}
debugContext.setEnableBreakpoint(true);
break;
case RUBY_EVENT_CLASS:
resetTopFrameMethodName(debugContext);
saveCallFrame(event, tCtx, file, line, methodName, debugContext);
break;
case RUBY_EVENT_RAISE:
updateTopFrame(event, debugContext, tCtx, file, line, methodName);
// XXX Implement post mortem debugging
IRubyObject exception = runtime.getGlobalVariables().get("$!");
// Might happen if the current ThreadContext is within 'defined?'
if (exception.isNil()) {
assert tCtx.isWithinDefined() : "$! should be nil only when within defined?";
break;
}
if (runtime.getClass("SystemExit").isInstance(exception)) {
// Can't do this because this unhooks the event hook causing
// a ConcurrentModificationException because the runtime
// is still iterating over event hooks. Shouldn't really
// matter. We're on our way out regardless.
// debugger.stop(runtime);
break;
}
if (debugger.getCatchpoints().isNil() || debugger.getCatchpoints().isEmpty()) {
break;
}
RubyArray ancestors = exception.getType().ancestors();
int l = ancestors.getLength();
for (int i = 0; i < l; i++) {
RubyModule module = (RubyModule)ancestors.get(i);
IRubyObject modName = module.name();
IRubyObject hitCount = debugger.getCatchpoints().op_aref(tCtx, modName);
if (!hitCount.isNil()) {
hitCount = runtime.newFixnum(RubyFixnum.fix2int(hitCount) + 1);
debugger.getCatchpoints().op_aset(tCtx, modName, hitCount);
debugContext.setStopReason(DebugContext.StopReason.CATCHPOINT);
context.callMethod(tCtx, DebugContext.AT_CATCHPOINT, breakpoint);
DebugFrame debugFrame = getTopFrame(debugContext);
if (debugFrame != null) {
binding = debugFrame.getBinding();
}
if (tCtx != null && binding.isNil()) {
binding = RubyBinding.newBinding(runtime);
}
saveTopBinding(debugContext, binding);
callAtLine(tCtx, context, debugContext, runtime, file, line);
break;
}
}
break;
}
cleanUp(debugContext);
}
| private void processEvent(final ThreadContext tCtx, final int event, final String file, final int line0,
final String methodName, final IRubyObject klass, DebugContextPair contexts) {
if (debugger.isDebug()) {
Util.logEvent(event, file, line0, methodName, klass);
}
// one-based; jruby by default passes zero-based
int line = line0 + 1;
hookCount++;
Ruby runtime = tCtx.getRuntime();
IRubyObject breakpoint = getNil();
IRubyObject binding = getNil();
IRubyObject context = contexts.context;
DebugContext debugContext = contexts.debugContext;
// debug("jrubydebug> %s:%d [%s] %s\n", file, line, EVENT_NAMES[event], methodName);
boolean moved = false;
if (debugContext.getLastLine() != line || debugContext.getLastFile() == null || !Util.areSameFiles(debugContext.getLastFile(), file)) {
debugContext.setEnableBreakpoint(true);
moved = true;
}
// else if(event != RUBY_EVENT_RETURN && event != RUBY_EVENT_C_RETURN) {
// if(debug == Qtrue)
// fprintf(stderr, "nodeless [%s] %s\n", get_event_name(event), rb_id2name(methodName));
// goto cleanup;
// } else {
// if(debug == Qtrue)
// fprintf(stderr, "nodeless [%s] %s\n", get_event_name(event), rb_id2name(methodName));
// }
if (event != RUBY_EVENT_LINE) {
debugContext.setStepped(true);
}
switch (event) {
case RUBY_EVENT_LINE:
if (debugContext.getStackSize() == 0) {
saveCallFrame(event, tCtx, file, line, methodName, debugContext);
} else {
updateTopFrame(event, debugContext, tCtx, file, line, methodName);
}
if (debugger.isTracing() || debugContext.isTracing()) {
IRubyObject[] args = new IRubyObject[]{
runtime.newString(file),
runtime.newFixnum(line)
};
context.callMethod(tCtx, DebugContext.AT_TRACING, args);
}
if (debugContext.getDestFrame() == -1 || debugContext.getStackSize() == debugContext.getDestFrame()) {
if (moved || !debugContext.isForceMove()) {
debugContext.setStopNext(debugContext.getStopNext() - 1);
}
if (debugContext.getStopNext() < 0) {
debugContext.setStopNext(-1);
}
if (moved || (debugContext.isStepped() && !debugContext.isForceMove())) {
debugContext.setStopLine(debugContext.getStopLine() - 1);
debugContext.setStepped(false);
}
} else if (debugContext.getStackSize() < debugContext.getDestFrame()) {
debugContext.setStopNext(0);
}
if (debugContext.getStopNext() == 0 || debugContext.getStopLine() == 0 ||
!(breakpoint = checkBreakpointsByPos(debugContext, file, line)).isNil()) {
binding = (tCtx != null ? RubyBinding.newBinding(runtime) : getNil());
saveTopBinding(debugContext, binding);
debugContext.setStopReason(DebugContext.StopReason.STEP);
/* Check breakpoint expression. */
if (!breakpoint.isNil()) {
if (!checkBreakpointExpression(tCtx, breakpoint, binding)) {
break;
}
if (!checkBreakpointHitCondition(breakpoint)) {
break;
}
if (breakpoint != debugContext.getBreakpoint()) {
debugContext.setStopReason(DebugContext.StopReason.BREAKPOINT);
context.callMethod(tCtx, DebugContext.AT_BREAKPOINT, breakpoint);
} else {
debugContext.setBreakpoint(getNil());
}
}
/* reset all pointers */
debugContext.setDestFrame(-1);
debugContext.setStopLine(-1);
debugContext.setStopNext(-1);
callAtLine(tCtx, context, debugContext, runtime, file, line);
}
break;
case RUBY_EVENT_CALL:
saveCallFrame(event, tCtx, file, line, methodName, debugContext);
breakpoint = checkBreakpointsByMethod(debugContext, klass, methodName);
if (!breakpoint.isNil()) {
DebugFrame debugFrame = getTopFrame(debugContext);
if (debugFrame != null) {
binding = debugFrame.getBinding();
}
if (tCtx != null && binding.isNil()) {
binding = RubyBinding.newBinding(runtime);
}
saveTopBinding(debugContext, binding);
if(!checkBreakpointExpression(tCtx, breakpoint, binding)) {
break;
}
if(!checkBreakpointHitCondition(breakpoint)) {
break;
}
if (breakpoint != debugContext.getBreakpoint()) {
debugContext.setStopReason(DebugContext.StopReason.BREAKPOINT);
context.callMethod(tCtx, DebugContext.AT_BREAKPOINT, breakpoint);
} else {
debugContext.setBreakpoint(getNil());
}
callAtLine(tCtx, context, debugContext, runtime, file, line);
}
break;
case RUBY_EVENT_C_CALL:
if(cCallNewFrameP(klass)) {
saveCallFrame(event, tCtx, file, line, methodName, debugContext);
} else {
updateTopFrame(event, debugContext, tCtx, file, line, methodName);
}
break;
case RUBY_EVENT_C_RETURN:
/* note if a block is given we fall through! */
if (!cCallNewFrameP(klass)) {
break;
}
case RUBY_EVENT_RETURN:
case RUBY_EVENT_END:
if (debugContext.getStackSize() == debugContext.getStopFrame()) {
debugContext.setStopNext(1);
debugContext.setStopFrame(0);
}
while (debugContext.getStackSize() > 0) {
DebugFrame topFrame = debugContext.popFrame();
String origMethodName = topFrame.getOrigMethodName();
if ((origMethodName == null && methodName == null) ||
(origMethodName != null && origMethodName.equals(methodName))) {
break;
}
}
debugContext.setEnableBreakpoint(true);
break;
case RUBY_EVENT_CLASS:
resetTopFrameMethodName(debugContext);
saveCallFrame(event, tCtx, file, line, methodName, debugContext);
break;
case RUBY_EVENT_RAISE:
updateTopFrame(event, debugContext, tCtx, file, line, methodName);
// XXX Implement post mortem debugging
IRubyObject exception = runtime.getGlobalVariables().get("$!");
// Might happen if the current ThreadContext is within 'defined?'
if (exception.isNil()) {
assert tCtx.isWithinDefined() : "$! should be nil only when within defined?";
break;
}
if (runtime.getClass("SystemExit").isInstance(exception)) {
// Can't do this because this unhooks the event hook causing
// a ConcurrentModificationException because the runtime
// is still iterating over event hooks. Shouldn't really
// matter. We're on our way out regardless.
// debugger.stop(runtime);
break;
}
if (debugger.getCatchpoints().isNil() || debugger.getCatchpoints().isEmpty()) {
break;
}
RubyArray ancestors = exception.getType().ancestors();
int l = ancestors.getLength();
for (int i = 0; i < l; i++) {
RubyModule module = (RubyModule)ancestors.get(i);
IRubyObject modName = module.name();
IRubyObject hitCount = debugger.getCatchpoints().op_aref(tCtx, modName);
if (!hitCount.isNil()) {
hitCount = runtime.newFixnum(RubyFixnum.fix2int(hitCount) + 1);
debugger.getCatchpoints().op_aset(tCtx, modName, hitCount);
debugContext.setStopReason(DebugContext.StopReason.CATCHPOINT);
context.callMethod(tCtx, DebugContext.AT_CATCHPOINT, exception);
DebugFrame debugFrame = getTopFrame(debugContext);
if (debugFrame != null) {
binding = debugFrame.getBinding();
}
if (tCtx != null && binding.isNil()) {
binding = RubyBinding.newBinding(runtime);
}
saveTopBinding(debugContext, binding);
callAtLine(tCtx, context, debugContext, runtime, file, line);
break;
}
}
break;
}
cleanUp(debugContext);
}
|
diff --git a/java/modules/core/src/main/java/org/apache/synapse/core/axis2/SynapseCallbackReceiver.java b/java/modules/core/src/main/java/org/apache/synapse/core/axis2/SynapseCallbackReceiver.java
index 6de7af8f3..02621fdec 100644
--- a/java/modules/core/src/main/java/org/apache/synapse/core/axis2/SynapseCallbackReceiver.java
+++ b/java/modules/core/src/main/java/org/apache/synapse/core/axis2/SynapseCallbackReceiver.java
@@ -1,198 +1,200 @@
/*
* 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.synapse.core.axis2;
import org.apache.axis2.engine.MessageReceiver;
import org.apache.axis2.client.async.Callback;
import org.apache.axis2.context.MessageContext;
import org.apache.axis2.AxisFault;
import org.apache.axis2.addressing.RelatesTo;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.synapse.Constants;
import org.apache.synapse.FaultHandler;
import org.apache.synapse.endpoints.Endpoint;
import org.apache.axiom.soap.SOAPFault;
import java.util.*;
public class SynapseCallbackReceiver implements MessageReceiver {
private static final Log log = LogFactory.getLog(SynapseCallbackReceiver.class);
private Map callbackStore; // this will be made thread safe within the constructor
public SynapseCallbackReceiver() {
callbackStore = Collections.synchronizedMap(new HashMap());
}
public void addCallback(String MsgID, Callback callback) {
callbackStore.put(MsgID, callback);
}
public void receive(MessageContext messageCtx) throws AxisFault {
if (messageCtx.getOptions() != null && messageCtx.getOptions().getRelatesTo() != null) {
String messageID = messageCtx.getOptions().getRelatesTo().getValue();
Callback callback = (Callback) callbackStore.remove(messageID);
RelatesTo[] relates = messageCtx.getRelationships();
if (relates.length > 1) {
// we set a relates to to the response message so that if WSA is not used, we
// could still link back to the original message. But if WSA was used, this
// gets duplicated, and we should remove it
removeDuplicateRelatesTo(messageCtx, relates);
}
if (callback != null) {
handleMessage(messageCtx, ((AsyncCallback) callback).getSynapseOutMsgCtx());
} else {
// TODO invoke a generic synapse error handler for this message
log.warn("Synapse received a response for the request with message Id : " +
messageID + " But a callback has not been registered to process this response");
}
} else {
// TODO invoke a generic synapse error handler for this message
log.warn("Synapse received a response message without a message Id");
}
}
/**
* Handle the response or error (during a failed send) message received for an outgoing request
*
* @param response the Axis2 MessageContext that has been received and has to be handled
* @param synapseOutMsgCtx the corresponding (outgoing) Synapse MessageContext for the above
* Axis2 MC, that holds Synapse specific information such as the error handler stack and
* local properties etc.
*/
private void handleMessage(MessageContext response,
org.apache.synapse.MessageContext synapseOutMsgCtx) {
Object o = response.getProperty("sending_fault");
if (o != null && Boolean.TRUE.equals(o)) {
// there is a sending fault. propagate the fault to fault handlers.
Stack faultStack = synapseOutMsgCtx.getFaultStack();
if (faultStack != null && !faultStack.isEmpty()) {
SOAPFault fault = response.getEnvelope().getBody().getFault();
Exception e = fault.getException();
if (e == null) {
e = new Exception(fault.toString());
}
((FaultHandler) faultStack.pop()).handleFault(synapseOutMsgCtx,e);
}
} else {
// there can always be only one instance of an Endpoint in the faultStack of a message
// if the send was successful, so remove it before we proceed any further
Stack faultStack = synapseOutMsgCtx.getFaultStack();
if (!faultStack.isEmpty() && faultStack.peek() instanceof Endpoint) {
faultStack.pop();
}
if (log.isDebugEnabled()) {
log.debug("Synapse received an asynchronous response message");
log.debug("Received To: " +
(response.getTo() != null ? response.getTo().getAddress() : "null"));
log.debug("SOAPAction: " +
(response.getSoapAction() != null ? response.getSoapAction() : "null"));
log.debug("Body : \n" + response.getEnvelope());
}
MessageContext axisOutMsgCtx =
((Axis2MessageContext)synapseOutMsgCtx).getAxis2MessageContext();
response.setOperationContext(axisOutMsgCtx.getOperationContext());
+ response.getAxisMessage().setParent(
+ axisOutMsgCtx.getOperationContext().getAxisOperation());
response.setAxisService(axisOutMsgCtx.getAxisService());
// set properties on response
response.setServerSide(true);
response.setProperty(Constants.ISRESPONSE_PROPERTY, Boolean.TRUE);
response.setProperty(MessageContext.TRANSPORT_OUT,
axisOutMsgCtx.getProperty(MessageContext.TRANSPORT_OUT));
response.setProperty(org.apache.axis2.Constants.OUT_TRANSPORT_INFO,
axisOutMsgCtx.getProperty(org.apache.axis2.Constants.OUT_TRANSPORT_INFO));
response.setTransportIn(axisOutMsgCtx.getTransportIn());
response.setTransportOut(axisOutMsgCtx.getTransportOut());
// If request is REST assume that the response is REST too
response.setDoingREST(axisOutMsgCtx.isDoingREST());
if (axisOutMsgCtx.getMessageID() != null) {
response.setRelationships(
new RelatesTo[] {new RelatesTo(axisOutMsgCtx.getMessageID())});
}
// create the synapse message context for the response
Axis2MessageContext synapseInMessageContext =
new Axis2MessageContext(
response,
synapseOutMsgCtx.getConfiguration(),
synapseOutMsgCtx.getEnvironment());
synapseInMessageContext.setResponse(true);
synapseInMessageContext.setTo(null);
// set the properties of the original MC to the new MC
Iterator iter = synapseOutMsgCtx.getPropertyKeySet().iterator();
while (iter.hasNext()) {
Object key = iter.next();
synapseInMessageContext.setProperty(
(String) key, synapseOutMsgCtx.getProperty((String) key));
}
// send the response message through the synapse mediation flow
synapseOutMsgCtx.getEnvironment().
injectMessage(synapseInMessageContext);
}
}
private void removeDuplicateRelatesTo(MessageContext mc, RelatesTo[] relates) {
int insertPos = 0;
RelatesTo[] newRelates = new RelatesTo[relates.length];
for (int i=0; i<relates.length; i++) {
RelatesTo current = relates[i];
boolean found = false;
for (int j=0; j<newRelates.length && j<insertPos; j++) {
if (newRelates[j].equals(current) ||
newRelates[j].getValue().equals(current.getValue())) {
found = true;
break;
}
}
if (!found) {
newRelates[insertPos++] = current;
}
}
RelatesTo[] trimmedRelates = new RelatesTo[insertPos];
System.arraycopy(newRelates, 0, trimmedRelates, 0, insertPos);
mc.setRelationships(trimmedRelates);
}
}
| true | true | private void handleMessage(MessageContext response,
org.apache.synapse.MessageContext synapseOutMsgCtx) {
Object o = response.getProperty("sending_fault");
if (o != null && Boolean.TRUE.equals(o)) {
// there is a sending fault. propagate the fault to fault handlers.
Stack faultStack = synapseOutMsgCtx.getFaultStack();
if (faultStack != null && !faultStack.isEmpty()) {
SOAPFault fault = response.getEnvelope().getBody().getFault();
Exception e = fault.getException();
if (e == null) {
e = new Exception(fault.toString());
}
((FaultHandler) faultStack.pop()).handleFault(synapseOutMsgCtx,e);
}
} else {
// there can always be only one instance of an Endpoint in the faultStack of a message
// if the send was successful, so remove it before we proceed any further
Stack faultStack = synapseOutMsgCtx.getFaultStack();
if (!faultStack.isEmpty() && faultStack.peek() instanceof Endpoint) {
faultStack.pop();
}
if (log.isDebugEnabled()) {
log.debug("Synapse received an asynchronous response message");
log.debug("Received To: " +
(response.getTo() != null ? response.getTo().getAddress() : "null"));
log.debug("SOAPAction: " +
(response.getSoapAction() != null ? response.getSoapAction() : "null"));
log.debug("Body : \n" + response.getEnvelope());
}
MessageContext axisOutMsgCtx =
((Axis2MessageContext)synapseOutMsgCtx).getAxis2MessageContext();
response.setOperationContext(axisOutMsgCtx.getOperationContext());
response.setAxisService(axisOutMsgCtx.getAxisService());
// set properties on response
response.setServerSide(true);
response.setProperty(Constants.ISRESPONSE_PROPERTY, Boolean.TRUE);
response.setProperty(MessageContext.TRANSPORT_OUT,
axisOutMsgCtx.getProperty(MessageContext.TRANSPORT_OUT));
response.setProperty(org.apache.axis2.Constants.OUT_TRANSPORT_INFO,
axisOutMsgCtx.getProperty(org.apache.axis2.Constants.OUT_TRANSPORT_INFO));
response.setTransportIn(axisOutMsgCtx.getTransportIn());
response.setTransportOut(axisOutMsgCtx.getTransportOut());
// If request is REST assume that the response is REST too
response.setDoingREST(axisOutMsgCtx.isDoingREST());
if (axisOutMsgCtx.getMessageID() != null) {
response.setRelationships(
new RelatesTo[] {new RelatesTo(axisOutMsgCtx.getMessageID())});
}
// create the synapse message context for the response
Axis2MessageContext synapseInMessageContext =
new Axis2MessageContext(
response,
synapseOutMsgCtx.getConfiguration(),
synapseOutMsgCtx.getEnvironment());
synapseInMessageContext.setResponse(true);
synapseInMessageContext.setTo(null);
// set the properties of the original MC to the new MC
Iterator iter = synapseOutMsgCtx.getPropertyKeySet().iterator();
while (iter.hasNext()) {
Object key = iter.next();
synapseInMessageContext.setProperty(
(String) key, synapseOutMsgCtx.getProperty((String) key));
}
// send the response message through the synapse mediation flow
synapseOutMsgCtx.getEnvironment().
injectMessage(synapseInMessageContext);
}
}
| private void handleMessage(MessageContext response,
org.apache.synapse.MessageContext synapseOutMsgCtx) {
Object o = response.getProperty("sending_fault");
if (o != null && Boolean.TRUE.equals(o)) {
// there is a sending fault. propagate the fault to fault handlers.
Stack faultStack = synapseOutMsgCtx.getFaultStack();
if (faultStack != null && !faultStack.isEmpty()) {
SOAPFault fault = response.getEnvelope().getBody().getFault();
Exception e = fault.getException();
if (e == null) {
e = new Exception(fault.toString());
}
((FaultHandler) faultStack.pop()).handleFault(synapseOutMsgCtx,e);
}
} else {
// there can always be only one instance of an Endpoint in the faultStack of a message
// if the send was successful, so remove it before we proceed any further
Stack faultStack = synapseOutMsgCtx.getFaultStack();
if (!faultStack.isEmpty() && faultStack.peek() instanceof Endpoint) {
faultStack.pop();
}
if (log.isDebugEnabled()) {
log.debug("Synapse received an asynchronous response message");
log.debug("Received To: " +
(response.getTo() != null ? response.getTo().getAddress() : "null"));
log.debug("SOAPAction: " +
(response.getSoapAction() != null ? response.getSoapAction() : "null"));
log.debug("Body : \n" + response.getEnvelope());
}
MessageContext axisOutMsgCtx =
((Axis2MessageContext)synapseOutMsgCtx).getAxis2MessageContext();
response.setOperationContext(axisOutMsgCtx.getOperationContext());
response.getAxisMessage().setParent(
axisOutMsgCtx.getOperationContext().getAxisOperation());
response.setAxisService(axisOutMsgCtx.getAxisService());
// set properties on response
response.setServerSide(true);
response.setProperty(Constants.ISRESPONSE_PROPERTY, Boolean.TRUE);
response.setProperty(MessageContext.TRANSPORT_OUT,
axisOutMsgCtx.getProperty(MessageContext.TRANSPORT_OUT));
response.setProperty(org.apache.axis2.Constants.OUT_TRANSPORT_INFO,
axisOutMsgCtx.getProperty(org.apache.axis2.Constants.OUT_TRANSPORT_INFO));
response.setTransportIn(axisOutMsgCtx.getTransportIn());
response.setTransportOut(axisOutMsgCtx.getTransportOut());
// If request is REST assume that the response is REST too
response.setDoingREST(axisOutMsgCtx.isDoingREST());
if (axisOutMsgCtx.getMessageID() != null) {
response.setRelationships(
new RelatesTo[] {new RelatesTo(axisOutMsgCtx.getMessageID())});
}
// create the synapse message context for the response
Axis2MessageContext synapseInMessageContext =
new Axis2MessageContext(
response,
synapseOutMsgCtx.getConfiguration(),
synapseOutMsgCtx.getEnvironment());
synapseInMessageContext.setResponse(true);
synapseInMessageContext.setTo(null);
// set the properties of the original MC to the new MC
Iterator iter = synapseOutMsgCtx.getPropertyKeySet().iterator();
while (iter.hasNext()) {
Object key = iter.next();
synapseInMessageContext.setProperty(
(String) key, synapseOutMsgCtx.getProperty((String) key));
}
// send the response message through the synapse mediation flow
synapseOutMsgCtx.getEnvironment().
injectMessage(synapseInMessageContext);
}
}
|
diff --git a/src/main/java/org/jboss/loom/migrators/_ext/ExternalMigratorsLoader.java b/src/main/java/org/jboss/loom/migrators/_ext/ExternalMigratorsLoader.java
index 4bdb538..45bec12 100644
--- a/src/main/java/org/jboss/loom/migrators/_ext/ExternalMigratorsLoader.java
+++ b/src/main/java/org/jboss/loom/migrators/_ext/ExternalMigratorsLoader.java
@@ -1,222 +1,223 @@
package org.jboss.loom.migrators._ext;
import groovy.lang.GroovyClassLoader;
import groovy.lang.GroovyCodeSource;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.codehaus.groovy.control.CompilationFailedException;
import org.jboss.loom.conf.GlobalConfiguration;
import org.jboss.loom.ex.MigrationException;
import org.jboss.loom.ex.MigrationExceptions;
import org.jboss.loom.migrators.IMigratorFilter;
import org.jboss.loom.migrators._ext.MigratorDefinition.JaxbClassDef;
import org.jboss.loom.spi.IConfigFragment;
import org.jboss.loom.utils.Utils;
import org.jboss.loom.utils.XmlUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Loads migrators externalized to *.mig.xml descriptors and *.groovy JAXB beans.
*
* @author Ondrej Zizka, ozizka at redhat.com
*/
public class ExternalMigratorsLoader {
private static final Logger log = LoggerFactory.getLogger( ExternalMigratorsLoader.class );
// Migrator descriptors.
private List<MigratorDefinition> descriptors;
// Map of JAXB class name -> class - not to lead them multiple times.
private Map<String, Class<? extends IConfigFragment>> fragmentJaxbClasses = new HashMap();
// Map of migragor class name -> class
private Map<String, Class<? extends DefinitionBasedMigrator>> migratorsClasses = new HashMap();
/**
* Reads migrator descriptors from *.mig.xml in the given dir and returns them.
*
* 1) Reads the definitions from the XML files.
* 2) Loads the Groovy classes referenced in these definitions.
* 3) Creates the classes of the Migrators.
* 4) Instantiates the classes and returns the list of instances.
*/
public Map<Class<? extends DefinitionBasedMigrator>, DefinitionBasedMigrator> loadMigrators(
File dir, IMigratorFilter filter, GlobalConfiguration globConf ) throws MigrationException
{
// Read the definitions from the XML files.
this.descriptors = loadMigratorDefinitions( dir, globConf );
// Filter out those which we don't want.
for( Iterator<MigratorDefinition> it = descriptors.iterator(); it.hasNext(); ) {
if( ! filter.filterDefinition( it.next() ) )
it.remove();
}
// Load the Groovy classes referenced in these definitions.
//this.fragmentJaxbClasses = loadJaxbClasses( this.descriptors );
// Create the classes of the Migrators.
//this.migratorsClasses = createMigratorsClasses();
// Instantiates the classes and returns the list of instances.
Map<Class<? extends DefinitionBasedMigrator>, DefinitionBasedMigrator> migs = instantiateMigratorsFromDefinitions( this.descriptors, this.fragmentJaxbClasses, globConf );
return migs;
}
/**
* Reads migrator descriptors from *.mig.xml in the given dir and returns them.
*/
public static List<MigratorDefinition> loadMigratorDefinitions( File dir, GlobalConfiguration gc ) throws MigrationException {
List<MigratorDefinition> retDefs = new LinkedList();
List<Exception> problems = new LinkedList();
// For each *.mig.xml file...
for( File xmlFile : FileUtils.listFiles( dir, new String[]{"mig.xml"}, true ) ){
try{
List<MigratorDefinition> defs = XmlUtils.unmarshallBeans( xmlFile, "/migration/migrator", MigratorDefinition.class );
retDefs.addAll( defs );
// Validate
for( MigratorDefinition def : defs ) {
try { Utils.validate( def ); }
catch( MigrationException ex ){ problems.add( ex ); }
}
}
catch( Exception ex ){
problems.add(ex);
}
}
String msg = "Errors occured when reading migrator descriptors from " + dir + ":\n ";
MigrationExceptions.wrapExceptions( problems, msg );
return retDefs;
}
/**
* Loads the Groovy classes referenced in these definitions.
*/
private static Map<String, Class<? extends IConfigFragment>> loadJaxbClasses(
MigratorDefinition desc ) throws MigrationException
{
Map<String, Class<? extends IConfigFragment>> jaxbClasses = new HashMap();
List<Exception> problems = new LinkedList();
// JAXB class...
+ if( desc.jaxbBeansClasses != null )
for( JaxbClassDef jaxbClsBean : desc.jaxbBeansClasses ) {
try {
// Look up in the map: "TestJaxbBean" -> class
String className = StringUtils.removeEnd( jaxbClsBean.getFile().getName(), ".groovy" );
Class cls = jaxbClasses.get( className );
if( cls == null ){
// Use the directory where the definition XML file is from.
log.debug(" Loading JAXB class from dir " + desc.getOrigin() );
//File dir = new File( desc.getLocation().getSystemId() ).getParentFile();
File dir = desc.getOrigin().getFile().getParentFile();
final File groovyFile = new File( dir, jaxbClsBean.getFile().getPath() );
log.debug(" Loading JAXB class from " + groovyFile );
cls = loadGroovyClass( groovyFile );
if( ! IConfigFragment.class.isAssignableFrom( cls ) ){
problems.add( new MigrationException("Groovy class from '"+groovyFile.getPath()+
"' doesn't implement " + IConfigFragment.class.getSimpleName() + ": " + cls.getName()));
continue;
}
jaxbClasses.put( className, cls );
}
//mig.addJaxbClass( cls );
}
catch( Exception ex ){
problems.add(ex);
}
}
MigrationExceptions.wrapExceptions( problems, "Failed loading JAXB classes. ");
return jaxbClasses;
}// loadJaxbClasses()
/**
* Processes the definitions - loads the used classes and creates the migrator objects.
*/
public static Map<Class<? extends DefinitionBasedMigrator>, DefinitionBasedMigrator> instantiateMigratorsFromDefinitions (
List<MigratorDefinition> defs,
Map<String, Class<? extends IConfigFragment>> fragClasses,
GlobalConfiguration globConf
) throws MigrationException
{
//List<Class<? extends DefinitionBasedMigrator>> migClasses = new LinkedList();
Map<Class<? extends DefinitionBasedMigrator>, DefinitionBasedMigrator> migrators = new HashMap();
List<Exception> problems = new LinkedList();
// For each <migrator ...> definition...
for( MigratorDefinition migDef : defs ) {
log.debug("Instantiating " + migDef);
try {
// JAXB classes.
Map<String, Class<? extends IConfigFragment>> jaxbClasses = loadJaxbClasses( migDef );
// Migrator class.
Class<? extends DefinitionBasedMigrator> migClass = MigratorSubclassMaker.createClass( migDef.name );
//migClasses.add( migClass );
// Instance.
DefinitionBasedMigrator mig = MigratorSubclassMaker.instantiate( migClass, migDef, globConf );
mig.setJaxbClasses( jaxbClasses );
migrators.put( migClass, mig );
} catch( Exception ex ) {
problems.add( ex );
}
}
MigrationExceptions.wrapExceptions( problems, "Failed processing migrator definitions. ");
return migrators;
}
/**
* Loads a groovy class from given file.
*/
private static Class loadGroovyClass( File file ) throws MigrationException {
try {
GroovyClassLoader gcl = new GroovyClassLoader( ExternalMigratorsLoader.class.getClassLoader() );
// Try to add this class' directory on classpath. For the purposes of test runs. Should be conditional?
/*File clsFile = ClassUtils.findClassOriginFile( ExternalMigratorsLoader.class );
log.debug("This class' file: " + clsFile);
if( clsFile != null && clsFile.isFile() && clsFile.getName().endsWith(".class") ){
log.info("Adding to GroovyClassLoader's classpath: " + clsFile.getParent() );
gcl.addClasspath( clsFile.getParent() );
}/*
final String cpRoot = ClassUtils.findClassPathRootFor( ExternalMigratorsLoader.class );
if( cpRoot != null ){
log.info("Adding to GroovyClassLoader's classpath: " + clsFile.getParent() );
gcl.addClasspath( cpRoot );
}/**/
//InputStream groovyClassIS = new FileInputStream( file );
//Class clazz = gcl.parseClass( groovyClassIS, StringUtils.substringBefore(file.getName(),"."));
//FileReader fr = new FileReader( file );
GroovyCodeSource src = new GroovyCodeSource( file );
Class clazz = gcl.parseClass( src );
return clazz;
}
catch( CompilationFailedException | IOException ex ){
throw new MigrationException("Failed creating class from " + file.getPath() + ":\n " + ex.getMessage(), ex);
}
}
}// class
| true | true | private static Map<String, Class<? extends IConfigFragment>> loadJaxbClasses(
MigratorDefinition desc ) throws MigrationException
{
Map<String, Class<? extends IConfigFragment>> jaxbClasses = new HashMap();
List<Exception> problems = new LinkedList();
// JAXB class...
for( JaxbClassDef jaxbClsBean : desc.jaxbBeansClasses ) {
try {
// Look up in the map: "TestJaxbBean" -> class
String className = StringUtils.removeEnd( jaxbClsBean.getFile().getName(), ".groovy" );
Class cls = jaxbClasses.get( className );
if( cls == null ){
// Use the directory where the definition XML file is from.
log.debug(" Loading JAXB class from dir " + desc.getOrigin() );
//File dir = new File( desc.getLocation().getSystemId() ).getParentFile();
File dir = desc.getOrigin().getFile().getParentFile();
final File groovyFile = new File( dir, jaxbClsBean.getFile().getPath() );
log.debug(" Loading JAXB class from " + groovyFile );
cls = loadGroovyClass( groovyFile );
if( ! IConfigFragment.class.isAssignableFrom( cls ) ){
problems.add( new MigrationException("Groovy class from '"+groovyFile.getPath()+
"' doesn't implement " + IConfigFragment.class.getSimpleName() + ": " + cls.getName()));
continue;
}
jaxbClasses.put( className, cls );
}
//mig.addJaxbClass( cls );
}
catch( Exception ex ){
problems.add(ex);
}
}
MigrationExceptions.wrapExceptions( problems, "Failed loading JAXB classes. ");
return jaxbClasses;
}// loadJaxbClasses()
| private static Map<String, Class<? extends IConfigFragment>> loadJaxbClasses(
MigratorDefinition desc ) throws MigrationException
{
Map<String, Class<? extends IConfigFragment>> jaxbClasses = new HashMap();
List<Exception> problems = new LinkedList();
// JAXB class...
if( desc.jaxbBeansClasses != null )
for( JaxbClassDef jaxbClsBean : desc.jaxbBeansClasses ) {
try {
// Look up in the map: "TestJaxbBean" -> class
String className = StringUtils.removeEnd( jaxbClsBean.getFile().getName(), ".groovy" );
Class cls = jaxbClasses.get( className );
if( cls == null ){
// Use the directory where the definition XML file is from.
log.debug(" Loading JAXB class from dir " + desc.getOrigin() );
//File dir = new File( desc.getLocation().getSystemId() ).getParentFile();
File dir = desc.getOrigin().getFile().getParentFile();
final File groovyFile = new File( dir, jaxbClsBean.getFile().getPath() );
log.debug(" Loading JAXB class from " + groovyFile );
cls = loadGroovyClass( groovyFile );
if( ! IConfigFragment.class.isAssignableFrom( cls ) ){
problems.add( new MigrationException("Groovy class from '"+groovyFile.getPath()+
"' doesn't implement " + IConfigFragment.class.getSimpleName() + ": " + cls.getName()));
continue;
}
jaxbClasses.put( className, cls );
}
//mig.addJaxbClass( cls );
}
catch( Exception ex ){
problems.add(ex);
}
}
MigrationExceptions.wrapExceptions( problems, "Failed loading JAXB classes. ");
return jaxbClasses;
}// loadJaxbClasses()
|
diff --git a/src/main/java/com/treasure_data/td_import/reader/NonFixnumColumnsFileReader.java b/src/main/java/com/treasure_data/td_import/reader/NonFixnumColumnsFileReader.java
index 913e7ed..c3ee31a 100644
--- a/src/main/java/com/treasure_data/td_import/reader/NonFixnumColumnsFileReader.java
+++ b/src/main/java/com/treasure_data/td_import/reader/NonFixnumColumnsFileReader.java
@@ -1,167 +1,169 @@
//
// Treasure Data Bulk-Import Tool in Java
//
// Copyright (C) 2012 - 2013 Muga Nishizawa
//
// 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.treasure_data.td_import.reader;
import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.treasure_data.td_import.Configuration;
import com.treasure_data.td_import.model.AliasTimeColumnValue;
import com.treasure_data.td_import.model.ColumnType;
import com.treasure_data.td_import.model.TimeColumnValue;
import com.treasure_data.td_import.model.TimeValueTimeColumnValue;
import com.treasure_data.td_import.prepare.PrepareConfiguration;
import com.treasure_data.td_import.prepare.PreparePartsException;
import com.treasure_data.td_import.prepare.Task;
import com.treasure_data.td_import.writer.FileWriter;
public abstract class NonFixnumColumnsFileReader<T extends PrepareConfiguration> extends FileReader<T> {
private static final Logger LOG = Logger.getLogger(NonFixnumColumnsFileReader.class.getName());
protected String aliasTimeColumnName = null;
public NonFixnumColumnsFileReader(T conf, FileWriter writer) {
super(conf, writer);
}
@Override
public void configure(Task task) throws PreparePartsException {
super.configure(task);
if (conf.getAliasTimeColumn() != null &&
!conf.getAliasTimeColumn().equals(Configuration.BI_PREPARE_PARTS_TIMECOLUMN_DEFAULTVALUE)) {
aliasTimeColumnName = conf.getAliasTimeColumn();
}
columnNames = new String[0];
columnTypes = new ColumnType[0];
skipColumns = new HashSet<String>();
timeColumnValue = new TimeColumnValue(-1, null);
}
public void setColumnNames() {
throw new UnsupportedOperationException();
}
public void setColumnTypes() {
throw new UnsupportedOperationException();
}
public ColumnType toColumnType(Object value) {
if (value instanceof Integer) {
return ColumnType.INT;
} else if (value instanceof Double) {
return ColumnType.DOUBLE;
} else if (value instanceof String) {
return ColumnType.STRING;
} else if (value instanceof Long) {
return ColumnType.LONG;
} else if (value instanceof List) {
return ColumnType.ARRAY;
} else if (value instanceof Map) {
return ColumnType.MAP;
} else {
throw new UnsupportedOperationException("During toColumnType() execution");
}
}
@Override
public void setSkipColumns() {
skipColumns.clear();
super.setSkipColumns();
}
public void setTimeColumnValue() throws PreparePartsException {
int timeColumnIndex = -1;
int aliasTimeColumnIndex = -1;
for (int i = 0; i < columnNames.length; i++) {
if (columnNames[i].equals(Configuration.BI_PREPARE_PARTS_TIMECOLUMN_DEFAULTVALUE)) {
timeColumnIndex = i;
break;
}
if (aliasTimeColumnName != null && columnNames[i].equals(aliasTimeColumnName)) {
aliasTimeColumnIndex = i;
}
}
if (timeColumnIndex >= 0) {
timeColumnValue = new TimeColumnValue(timeColumnIndex, conf.getTimeFormat());
} else if (aliasTimeColumnIndex >= 0) {
timeColumnValue = new AliasTimeColumnValue(aliasTimeColumnIndex, conf.getTimeFormat());
} else if (conf.getTimeValue() >= 0) {
timeColumnValue = new TimeValueTimeColumnValue(conf.getTimeValue());
} else {
// TODO should change message more user-friendly
throw new PreparePartsException("the row doesn't have time column");
}
}
@Override
public boolean next() throws PreparePartsException {
try {
if (!readRow()) {
return false;
}
setColumnNames();
writer.setColumnNames(getColumnNames());
setColumnTypes();
writer.setColumnTypes(getColumnTypes());
setSkipColumns();
writer.setColumnTypes(getColumnTypes());
setTimeColumnValue();
writer.setTimeColumnValue(getTimeColumnValue());
// convert each column in row
convertTypesOfColumns();
// write each column value
writer.next(convertedRow);
writer.incrementRowNum();
} catch (IOException e) {
// if reader throw I/O error, parseRow throws PreparePartsException.
String msg = String.format("Cannot read raw data: line %d in %s", lineNum, source);
LOG.log(Level.WARNING, msg, e);
throw new PreparePartsException(e);
} catch (PreparePartsException e) {
writer.incrementErrorRowNum();
+ // the untokenized raw row is written to error rows file
+ writeErrorRecord(getCurrentRow());
// the row data should be written to error rows file
String msg = String.format("line %d in %s: %s", lineNum, source, getCurrentRow());
LOG.log(Level.WARNING, msg, e);
handleError(e);
}
return true;
}
@Override
public boolean readRow() throws IOException {
throw new UnsupportedOperationException();
}
@Override
public void convertTypesOfColumns() throws PreparePartsException {
throw new UnsupportedOperationException();
}
}
| true | true | public boolean next() throws PreparePartsException {
try {
if (!readRow()) {
return false;
}
setColumnNames();
writer.setColumnNames(getColumnNames());
setColumnTypes();
writer.setColumnTypes(getColumnTypes());
setSkipColumns();
writer.setColumnTypes(getColumnTypes());
setTimeColumnValue();
writer.setTimeColumnValue(getTimeColumnValue());
// convert each column in row
convertTypesOfColumns();
// write each column value
writer.next(convertedRow);
writer.incrementRowNum();
} catch (IOException e) {
// if reader throw I/O error, parseRow throws PreparePartsException.
String msg = String.format("Cannot read raw data: line %d in %s", lineNum, source);
LOG.log(Level.WARNING, msg, e);
throw new PreparePartsException(e);
} catch (PreparePartsException e) {
writer.incrementErrorRowNum();
// the row data should be written to error rows file
String msg = String.format("line %d in %s: %s", lineNum, source, getCurrentRow());
LOG.log(Level.WARNING, msg, e);
handleError(e);
}
return true;
}
| public boolean next() throws PreparePartsException {
try {
if (!readRow()) {
return false;
}
setColumnNames();
writer.setColumnNames(getColumnNames());
setColumnTypes();
writer.setColumnTypes(getColumnTypes());
setSkipColumns();
writer.setColumnTypes(getColumnTypes());
setTimeColumnValue();
writer.setTimeColumnValue(getTimeColumnValue());
// convert each column in row
convertTypesOfColumns();
// write each column value
writer.next(convertedRow);
writer.incrementRowNum();
} catch (IOException e) {
// if reader throw I/O error, parseRow throws PreparePartsException.
String msg = String.format("Cannot read raw data: line %d in %s", lineNum, source);
LOG.log(Level.WARNING, msg, e);
throw new PreparePartsException(e);
} catch (PreparePartsException e) {
writer.incrementErrorRowNum();
// the untokenized raw row is written to error rows file
writeErrorRecord(getCurrentRow());
// the row data should be written to error rows file
String msg = String.format("line %d in %s: %s", lineNum, source, getCurrentRow());
LOG.log(Level.WARNING, msg, e);
handleError(e);
}
return true;
}
|
diff --git a/src/uk/ac/ebi/age/log/Log2JSON.java b/src/uk/ac/ebi/age/log/Log2JSON.java
index 4323fea..ca551e8 100644
--- a/src/uk/ac/ebi/age/log/Log2JSON.java
+++ b/src/uk/ac/ebi/age/log/Log2JSON.java
@@ -1,67 +1,67 @@
package uk.ac.ebi.age.log;
import uk.ac.ebi.age.log.LogNode.Level;
import com.pri.util.StringUtils;
public class Log2JSON
{
public static String convert( LogNode nd )
{
StringBuilder sb = new StringBuilder();
setLevels( nd );
convertNode(nd, sb, 0);
return sb.toString();
}
private static void convertNode( LogNode ln, StringBuilder sb, int lyr )
{
sb.append("{\n");
sb.append(" level: \"").append(ln.getLevel().name()).append("\",\n");
if( ln.getMessage() != null )
{
sb.append(" message: \"");
- StringUtils.appendSlashed(sb, ln.getMessage());
+ StringUtils.appendBackslashed(sb, ln.getMessage(),'"');
sb.append("\",\n");
}
if( ln.getSubNodes() != null )
{
sb.append(" subnodes: [");
for( LogNode snd : ln.getSubNodes() )
{
convertNode(snd,sb,lyr+1);
sb.append(",\n");
}
sb.append("]\n");
}
sb.append("}");
}
private static void setLevels( LogNode ln )
{
if( ln.getSubNodes() == null )
return;
LogNode.Level maxLevel = Level.getMinLevel();
for( LogNode snd : ln.getSubNodes() )
{
setLevels(snd);
if( snd.getLevel().getPriority() > maxLevel.getPriority() )
maxLevel = snd.getLevel();
}
ln.setLevel(maxLevel);
}
}
| true | true | private static void convertNode( LogNode ln, StringBuilder sb, int lyr )
{
sb.append("{\n");
sb.append(" level: \"").append(ln.getLevel().name()).append("\",\n");
if( ln.getMessage() != null )
{
sb.append(" message: \"");
StringUtils.appendSlashed(sb, ln.getMessage());
sb.append("\",\n");
}
if( ln.getSubNodes() != null )
{
sb.append(" subnodes: [");
for( LogNode snd : ln.getSubNodes() )
{
convertNode(snd,sb,lyr+1);
sb.append(",\n");
}
sb.append("]\n");
}
sb.append("}");
}
| private static void convertNode( LogNode ln, StringBuilder sb, int lyr )
{
sb.append("{\n");
sb.append(" level: \"").append(ln.getLevel().name()).append("\",\n");
if( ln.getMessage() != null )
{
sb.append(" message: \"");
StringUtils.appendBackslashed(sb, ln.getMessage(),'"');
sb.append("\",\n");
}
if( ln.getSubNodes() != null )
{
sb.append(" subnodes: [");
for( LogNode snd : ln.getSubNodes() )
{
convertNode(snd,sb,lyr+1);
sb.append(",\n");
}
sb.append("]\n");
}
sb.append("}");
}
|
diff --git a/src/com/androzic/Splash.java b/src/com/androzic/Splash.java
index 62ec7d0..d6e5e19 100644
--- a/src/com/androzic/Splash.java
+++ b/src/com/androzic/Splash.java
@@ -1,618 +1,619 @@
/*
* Androzic - android navigation client that uses OziExplorer maps (ozf2, ozfx3).
* Copyright (C) 2010-2012 Andrey Novikov <http://andreynovikov.info/>
*
* This file is part of Androzic application.
*
* Androzic is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* Androzic 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 Androzic. If not, see <http://www.gnu.org/licenses/>.
*/
package com.androzic;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnKeyListener;
import android.content.SharedPreferences.Editor;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.text.Html;
import android.text.SpannableString;
import android.text.method.LinkMovementMethod;
import android.text.util.Linkify;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.androzic.data.Route;
import com.androzic.overlay.CurrentTrackOverlay;
import com.androzic.util.FileList;
import com.androzic.util.GpxFiles;
import com.androzic.util.KmlFiles;
import com.androzic.util.OziExplorerFiles;
import com.androzic.util.RouteFilenameFilter;
public class Splash extends Activity implements OnClickListener
{
private static final int MSG_FINISH = 1;
private static final int MSG_ERROR = 2;
private static final int MSG_STATUS = 3;
private static final int MSG_PROGRESS = 4;
private static final int MSG_ASK = 5;
private static final int MSG_SAY = 6;
private static final int RES_YES = 1;
private static final int RES_NO = 2;
private static final int DOWNLOAD_SIZE = 207216;
private static final int PROGRESS_STEP = 10000;
private int result;
private boolean wait;
protected String savedMessage;
private ProgressBar progress;
private TextView message;
private Button gotit;
private Button yes;
private Button no;
private Button quit;
protected Androzic application;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
application = (Androzic) getApplication();
PreferenceManager.setDefaultValues(this, R.xml.pref_behavior, true);
PreferenceManager.setDefaultValues(this, R.xml.pref_folder, true);
PreferenceManager.setDefaultValues(this, R.xml.pref_location, true);
PreferenceManager.setDefaultValues(this, R.xml.pref_display, true);
PreferenceManager.setDefaultValues(this, R.xml.pref_unit, true);
PreferenceManager.setDefaultValues(this, R.xml.pref_grid, true);
PreferenceManager.setDefaultValues(this, R.xml.pref_tracking, true);
PreferenceManager.setDefaultValues(this, R.xml.pref_waypoint, true);
PreferenceManager.setDefaultValues(this, R.xml.pref_route, true);
PreferenceManager.setDefaultValues(this, R.xml.pref_navigation, true);
PreferenceManager.setDefaultValues(this, R.xml.pref_general, true);
setContentView(R.layout.act_splash);
if (application.isPaid)
{
findViewById(R.id.paid).setVisibility(View.VISIBLE);
}
progress = (ProgressBar) findViewById(R.id.progress);
message = (TextView) findViewById(R.id.message);
message.setText(getString(R.string.msg_connectingtoserver));
progress.setMax(DOWNLOAD_SIZE + PROGRESS_STEP * 4);
yes = (Button) findViewById(R.id.yes);
yes.setOnClickListener(this);
no = (Button) findViewById(R.id.no);
no.setOnClickListener(this);
gotit = (Button) findViewById(R.id.gotit);
gotit.setOnClickListener(this);
quit = (Button) findViewById(R.id.quit);
quit.setOnClickListener(this);
wait = true;
showEula();
if (! application.mapsInited)
{
new InitializationThread(progressHandler).start();
}
else
{
progressHandler.sendEmptyMessage(MSG_FINISH);
}
}
private void showEula()
{
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
boolean hasBeenShown = prefs.getBoolean(getString(R.string.app_eulaaccepted), false);
if (hasBeenShown == false)
{
final SpannableString message = new SpannableString(Html.fromHtml(getString(R.string.app_eula).replace("/n", "<br/>")));
Linkify.addLinks(message, Linkify.WEB_URLS);
AlertDialog.Builder builder = new AlertDialog.Builder(this)
.setTitle(getString(R.string.app_name))
.setIcon(R.drawable.icon)
.setMessage(message)
.setPositiveButton(android.R.string.ok, new Dialog.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i)
{
prefs.edit().putBoolean(getString(R.string.app_eulaaccepted), true).commit();
wait = false;
dialogInterface.dismiss();
}})
.setOnKeyListener(new OnKeyListener() {
@Override
public boolean onKey(DialogInterface dialoginterface, int keyCode, KeyEvent event)
{
return ! (keyCode == KeyEvent.KEYCODE_HOME);
}})
.setCancelable(false);
AlertDialog d = builder.create();
d.show();
// Make the textview clickable. Must be called after show()
((TextView) d.findViewById(android.R.id.message)).setMovementMethod(LinkMovementMethod.getInstance());
}
else
{
wait = false;
}
}
final Handler progressHandler = new Handler() {
public void handleMessage(Message msg)
{
switch (msg.what)
{
case MSG_STATUS:
message.setText(msg.getData().getString("message"));
break;
case MSG_PROGRESS:
int total = msg.getData().getInt("total");
progress.setProgress(total);
break;
case MSG_ASK:
progress.setVisibility(View.GONE);
savedMessage = message.getText().toString();
message.setText(msg.getData().getString("message"));
result = 0;
yes.setVisibility(View.VISIBLE);
no.setVisibility(View.VISIBLE);
break;
case MSG_SAY:
progress.setVisibility(View.GONE);
savedMessage = message.getText().toString();
message.setText(msg.getData().getString("message"));
result = 0;
gotit.setVisibility(View.VISIBLE);
break;
case MSG_FINISH:
startActivity(new Intent(Splash.this, MapActivity.class).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK).putExtras(getIntent()));
finish();
break;
case MSG_ERROR:
progress.setVisibility(View.INVISIBLE);
message.setText(msg.getData().getString("message"));
quit.setVisibility(View.VISIBLE);
break;
}
}
};
private class InitializationThread extends Thread
{
Handler mHandler;
int total;
InitializationThread(Handler h)
{
mHandler = h;
}
public void run()
{
while (wait)
{
try
{
sleep(100);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
total = 0;
Message msg = mHandler.obtainMessage(MSG_STATUS);
Bundle b = new Bundle();
b.putString("message", getString(R.string.msg_initializingdata));
msg.setData(b);
mHandler.sendMessage(msg);
Resources resources = getResources();
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(Splash.this);
application.enableLocating(settings.getBoolean(getString(R.string.lc_locate), true));
application.enableTracking(settings.getBoolean(getString(R.string.lc_track), true));
// set root folder and check if it has to be created
String rootPath = settings.getString(getString(R.string.pref_folder_root), Environment.getExternalStorageDirectory() + File.separator + resources.getString(R.string.def_folder_prefix));
File root = new File(rootPath);
if (!root.exists())
{
try
{
root.mkdirs();
File nomedia = new File(root, ".nomedia");
nomedia.createNewFile();
}
catch (IOException e)
{
msg = mHandler.obtainMessage(MSG_ERROR);
b = new Bundle();
b.putString("message", getString(R.string.err_nosdcard));
msg.setData(b);
mHandler.sendMessage(msg);
return;
}
}
// check maps folder existence
File mapdir = new File(settings.getString(getString(R.string.pref_folder_map), Environment.getExternalStorageDirectory() + File.separator + resources.getString(R.string.def_folder_map)));
String oldmap = settings.getString(getString(R.string.pref_folder_map_old), null);
if (oldmap != null)
{
File oldmapdir = new File(root, oldmap);
if (! oldmapdir.equals(mapdir))
{
mapdir = oldmapdir;
Editor editor = settings.edit();
editor.putString(getString(R.string.pref_folder_map), mapdir.getAbsolutePath());
+ editor.putString(getString(R.string.pref_folder_map_old), null);
editor.commit();
}
}
if (!mapdir.exists())
{
mapdir.mkdirs();
}
// check data folder existence
File datadir = new File(settings.getString(getString(R.string.pref_folder_data), Environment.getExternalStorageDirectory() + File.separator + resources.getString(R.string.def_folder_data)));
if (!datadir.exists())
{
// check if there was an old data structure
String wptdir = settings.getString(getString(R.string.pref_folder_waypoint), null);
System.err.println("wpt: " + wptdir);
if (wptdir != null)
{
wait = true;
msg = mHandler.obtainMessage(MSG_SAY);
b = new Bundle();
b.putString("message", getString(R.string.msg_newdatafolder, datadir.getAbsolutePath()));
msg.setData(b);
mHandler.sendMessage(msg);
while (wait)
{
try
{
sleep(100);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
datadir.mkdirs();
}
// initialize paths
application.setRootPath(root.getAbsolutePath());
application.setMapPath(mapdir.getAbsolutePath());
application.setDataPath(Androzic.PATH_DATA, datadir.getAbsolutePath());
application.setDataPath(Androzic.PATH_ICONS, settings.getString(getString(R.string.pref_folder_icon), Environment.getExternalStorageDirectory() + File.separator + resources.getString(R.string.def_folder_icon)));
// initialize data
application.installData();
// read default waypoints
File wptFile = new File(application.dataPath, "myWaypoints.wpt");
if (wptFile.exists() && wptFile.canRead())
{
try
{
application.addWaypoints(OziExplorerFiles.loadWaypointsFromFile(wptFile));
}
catch (IOException e)
{
e.printStackTrace();
}
}
// read track tail
if (settings.getBoolean(getString(R.string.pref_showcurrenttrack), true))
{
application.currentTrackOverlay = new CurrentTrackOverlay(Splash.this);
if (settings.getBoolean(getString(R.string.pref_tracking_currentload), resources.getBoolean(R.bool.def_tracking_currentload)))
{
String name = settings.getString(getString(R.string.trk_current), "myTrack.plt");
File trkFile = new File(application.dataPath, name);
if (trkFile.exists() && trkFile.canRead())
{
try
{
application.currentTrackOverlay.setTrack(OziExplorerFiles.loadTrackFromFile(trkFile, Integer.parseInt(settings.getString(getString(R.string.pref_tracking_currentlength), getString(R.string.def_tracking_currentlength)))));
}
catch (IllegalArgumentException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
}
// load routes
if (settings.getBoolean(getString(R.string.pref_route_preload), resources.getBoolean(R.bool.def_route_preload)))
{
List<File> files = FileList.getFileListing(new File(application.dataPath), new RouteFilenameFilter());
for (File file : files)
{
List<Route> routes = null;
try
{
String lc = file.getName().toLowerCase();
if (lc.endsWith(".rt2") || lc.endsWith(".rte"))
{
routes = OziExplorerFiles.loadRoutesFromFile(file);
}
else if (lc.endsWith(".kml"))
{
routes = KmlFiles.loadRoutesFromFile(file);
}
else if (lc.endsWith(".gpx"))
{
routes = GpxFiles.loadRoutesFromFile(file);
}
application.addRoutes(routes);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
total += PROGRESS_STEP;
msg = mHandler.obtainMessage(MSG_PROGRESS);
b = new Bundle();
b.putInt("total", total);
msg.setData(b);
mHandler.sendMessage(msg);
// load maps if no any found
if (mapdir.list().length == 0)
{
wait = true;
msg = mHandler.obtainMessage(MSG_ASK);
b = new Bundle();
b.putString("message", getString(R.string.nomaps_explained, application.getMapPath()));
msg.setData(b);
mHandler.sendMessage(msg);
while (wait)
{
try
{
sleep(100);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
if (result == RES_YES)
{
try
{
// URL u = new URL("http://androzic.googlecode.com/files/world.ozfx3");
URL u = new URL("https://docs.google.com/uc?export=download&id=0Bxnm5oGXU2cja2lQMzVvWFNpZjQ");
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
FileOutputStream f = new FileOutputStream(new File(application.getMapPath(), "world.ozf2"));
InputStream in = c.getInputStream();
msg = mHandler.obtainMessage(MSG_STATUS);
b = new Bundle();
b.putString("message", getString(R.string.msg_loadingimagefile));
msg.setData(b);
mHandler.sendMessage(msg);
byte[] buffer = new byte[1024];
int len = 0;
while ((len = in.read(buffer)) > 0)
{
f.write(buffer, 0, len);
total += len;
msg = mHandler.obtainMessage(MSG_PROGRESS);
b = new Bundle();
b.putInt("total", total);
msg.setData(b);
mHandler.sendMessage(msg);
}
f.close();
msg = mHandler.obtainMessage(MSG_STATUS);
b = new Bundle();
b.putString("message", getString(R.string.msg_loadingmapfile));
msg.setData(b);
mHandler.sendMessage(msg);
//u = new URL("http://androzic.googlecode.com/files/world.map");
u = new URL("https://docs.google.com/uc?export=download&id=0Bxnm5oGXU2cjWllteG4tSDBxekU");
c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
f = new FileOutputStream(new File(application.getMapPath(), "world.map"));
in = c.getInputStream();
buffer = new byte[1024];
len = 0;
while ((len = in.read(buffer)) > 0)
{
f.write(buffer, 0, len);
total += len;
msg = mHandler.obtainMessage(MSG_PROGRESS);
b = new Bundle();
b.putInt("total", total);
msg.setData(b);
mHandler.sendMessage(msg);
}
f.close();
}
catch (IOException e)
{
e.printStackTrace();
msg = mHandler.obtainMessage(MSG_ERROR);
b = new Bundle();
b.putString("message", getString(R.string.err_noconnection));
msg.setData(b);
mHandler.sendMessage(msg);
File dir = new File(application.getMapPath());
File[] files = dir.listFiles();
if (files != null)
{
for (int i = 0; i < files.length; i++)
{
files[i].delete();
}
}
return;
}
}
}
else
{
total += DOWNLOAD_SIZE;
msg = mHandler.obtainMessage(MSG_PROGRESS);
b = new Bundle();
b.putInt("total", total);
msg.setData(b);
mHandler.sendMessage(msg);
}
msg = mHandler.obtainMessage(MSG_STATUS);
b = new Bundle();
b.putString("message", getString(R.string.msg_initializingmaps));
msg.setData(b);
mHandler.sendMessage(msg);
// initialize maps
application.initializeMaps();
total += PROGRESS_STEP;
msg = mHandler.obtainMessage(MSG_PROGRESS);
b = new Bundle();
b.putInt("total", total);
msg.setData(b);
mHandler.sendMessage(msg);
msg = mHandler.obtainMessage(MSG_STATUS);
b = new Bundle();
b.putString("message", getString(R.string.msg_initializingplugins));
msg.setData(b);
mHandler.sendMessage(msg);
// initialize plugins
application.initializePlugins();
total += PROGRESS_STEP;
msg = mHandler.obtainMessage(MSG_PROGRESS);
b = new Bundle();
b.putInt("total", total);
msg.setData(b);
mHandler.sendMessage(msg);
msg = mHandler.obtainMessage(MSG_STATUS);
b = new Bundle();
b.putString("message", getString(R.string.msg_initializingview));
msg.setData(b);
mHandler.sendMessage(msg);
// initialize current map
application.initializeMapCenter();
total += PROGRESS_STEP;
msg = mHandler.obtainMessage(MSG_PROGRESS);
b = new Bundle();
b.putInt("total", total);
msg.setData(b);
mHandler.sendMessage(msg);
mHandler.sendEmptyMessage(MSG_FINISH);
}
}
@Override
public void onClick(View v)
{
switch (v.getId())
{
case R.id.yes:
result = RES_YES;
break;
case R.id.no:
result = RES_NO;
break;
case R.id.quit:
finish();
break;
}
gotit.setVisibility(View.GONE);
yes.setVisibility(View.GONE);
no.setVisibility(View.GONE);
progress.setVisibility(View.VISIBLE);
message.setText(savedMessage);
wait = false;
}
}
| true | true | public void run()
{
while (wait)
{
try
{
sleep(100);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
total = 0;
Message msg = mHandler.obtainMessage(MSG_STATUS);
Bundle b = new Bundle();
b.putString("message", getString(R.string.msg_initializingdata));
msg.setData(b);
mHandler.sendMessage(msg);
Resources resources = getResources();
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(Splash.this);
application.enableLocating(settings.getBoolean(getString(R.string.lc_locate), true));
application.enableTracking(settings.getBoolean(getString(R.string.lc_track), true));
// set root folder and check if it has to be created
String rootPath = settings.getString(getString(R.string.pref_folder_root), Environment.getExternalStorageDirectory() + File.separator + resources.getString(R.string.def_folder_prefix));
File root = new File(rootPath);
if (!root.exists())
{
try
{
root.mkdirs();
File nomedia = new File(root, ".nomedia");
nomedia.createNewFile();
}
catch (IOException e)
{
msg = mHandler.obtainMessage(MSG_ERROR);
b = new Bundle();
b.putString("message", getString(R.string.err_nosdcard));
msg.setData(b);
mHandler.sendMessage(msg);
return;
}
}
// check maps folder existence
File mapdir = new File(settings.getString(getString(R.string.pref_folder_map), Environment.getExternalStorageDirectory() + File.separator + resources.getString(R.string.def_folder_map)));
String oldmap = settings.getString(getString(R.string.pref_folder_map_old), null);
if (oldmap != null)
{
File oldmapdir = new File(root, oldmap);
if (! oldmapdir.equals(mapdir))
{
mapdir = oldmapdir;
Editor editor = settings.edit();
editor.putString(getString(R.string.pref_folder_map), mapdir.getAbsolutePath());
editor.commit();
}
}
if (!mapdir.exists())
{
mapdir.mkdirs();
}
// check data folder existence
File datadir = new File(settings.getString(getString(R.string.pref_folder_data), Environment.getExternalStorageDirectory() + File.separator + resources.getString(R.string.def_folder_data)));
if (!datadir.exists())
{
// check if there was an old data structure
String wptdir = settings.getString(getString(R.string.pref_folder_waypoint), null);
System.err.println("wpt: " + wptdir);
if (wptdir != null)
{
wait = true;
msg = mHandler.obtainMessage(MSG_SAY);
b = new Bundle();
b.putString("message", getString(R.string.msg_newdatafolder, datadir.getAbsolutePath()));
msg.setData(b);
mHandler.sendMessage(msg);
while (wait)
{
try
{
sleep(100);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
datadir.mkdirs();
}
// initialize paths
application.setRootPath(root.getAbsolutePath());
application.setMapPath(mapdir.getAbsolutePath());
application.setDataPath(Androzic.PATH_DATA, datadir.getAbsolutePath());
application.setDataPath(Androzic.PATH_ICONS, settings.getString(getString(R.string.pref_folder_icon), Environment.getExternalStorageDirectory() + File.separator + resources.getString(R.string.def_folder_icon)));
// initialize data
application.installData();
// read default waypoints
File wptFile = new File(application.dataPath, "myWaypoints.wpt");
if (wptFile.exists() && wptFile.canRead())
{
try
{
application.addWaypoints(OziExplorerFiles.loadWaypointsFromFile(wptFile));
}
catch (IOException e)
{
e.printStackTrace();
}
}
// read track tail
if (settings.getBoolean(getString(R.string.pref_showcurrenttrack), true))
{
application.currentTrackOverlay = new CurrentTrackOverlay(Splash.this);
if (settings.getBoolean(getString(R.string.pref_tracking_currentload), resources.getBoolean(R.bool.def_tracking_currentload)))
{
String name = settings.getString(getString(R.string.trk_current), "myTrack.plt");
File trkFile = new File(application.dataPath, name);
if (trkFile.exists() && trkFile.canRead())
{
try
{
application.currentTrackOverlay.setTrack(OziExplorerFiles.loadTrackFromFile(trkFile, Integer.parseInt(settings.getString(getString(R.string.pref_tracking_currentlength), getString(R.string.def_tracking_currentlength)))));
}
catch (IllegalArgumentException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
}
// load routes
if (settings.getBoolean(getString(R.string.pref_route_preload), resources.getBoolean(R.bool.def_route_preload)))
{
List<File> files = FileList.getFileListing(new File(application.dataPath), new RouteFilenameFilter());
for (File file : files)
{
List<Route> routes = null;
try
{
String lc = file.getName().toLowerCase();
if (lc.endsWith(".rt2") || lc.endsWith(".rte"))
{
routes = OziExplorerFiles.loadRoutesFromFile(file);
}
else if (lc.endsWith(".kml"))
{
routes = KmlFiles.loadRoutesFromFile(file);
}
else if (lc.endsWith(".gpx"))
{
routes = GpxFiles.loadRoutesFromFile(file);
}
application.addRoutes(routes);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
total += PROGRESS_STEP;
msg = mHandler.obtainMessage(MSG_PROGRESS);
b = new Bundle();
b.putInt("total", total);
msg.setData(b);
mHandler.sendMessage(msg);
// load maps if no any found
if (mapdir.list().length == 0)
{
wait = true;
msg = mHandler.obtainMessage(MSG_ASK);
b = new Bundle();
b.putString("message", getString(R.string.nomaps_explained, application.getMapPath()));
msg.setData(b);
mHandler.sendMessage(msg);
while (wait)
{
try
{
sleep(100);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
if (result == RES_YES)
{
try
{
// URL u = new URL("http://androzic.googlecode.com/files/world.ozfx3");
URL u = new URL("https://docs.google.com/uc?export=download&id=0Bxnm5oGXU2cja2lQMzVvWFNpZjQ");
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
FileOutputStream f = new FileOutputStream(new File(application.getMapPath(), "world.ozf2"));
InputStream in = c.getInputStream();
msg = mHandler.obtainMessage(MSG_STATUS);
b = new Bundle();
b.putString("message", getString(R.string.msg_loadingimagefile));
msg.setData(b);
mHandler.sendMessage(msg);
byte[] buffer = new byte[1024];
int len = 0;
while ((len = in.read(buffer)) > 0)
{
f.write(buffer, 0, len);
total += len;
msg = mHandler.obtainMessage(MSG_PROGRESS);
b = new Bundle();
b.putInt("total", total);
msg.setData(b);
mHandler.sendMessage(msg);
}
f.close();
msg = mHandler.obtainMessage(MSG_STATUS);
b = new Bundle();
b.putString("message", getString(R.string.msg_loadingmapfile));
msg.setData(b);
mHandler.sendMessage(msg);
//u = new URL("http://androzic.googlecode.com/files/world.map");
u = new URL("https://docs.google.com/uc?export=download&id=0Bxnm5oGXU2cjWllteG4tSDBxekU");
c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
f = new FileOutputStream(new File(application.getMapPath(), "world.map"));
in = c.getInputStream();
buffer = new byte[1024];
len = 0;
while ((len = in.read(buffer)) > 0)
{
f.write(buffer, 0, len);
total += len;
msg = mHandler.obtainMessage(MSG_PROGRESS);
b = new Bundle();
b.putInt("total", total);
msg.setData(b);
mHandler.sendMessage(msg);
}
f.close();
}
catch (IOException e)
{
e.printStackTrace();
msg = mHandler.obtainMessage(MSG_ERROR);
b = new Bundle();
b.putString("message", getString(R.string.err_noconnection));
msg.setData(b);
mHandler.sendMessage(msg);
File dir = new File(application.getMapPath());
File[] files = dir.listFiles();
if (files != null)
{
for (int i = 0; i < files.length; i++)
{
files[i].delete();
}
}
return;
}
}
}
else
{
total += DOWNLOAD_SIZE;
msg = mHandler.obtainMessage(MSG_PROGRESS);
b = new Bundle();
b.putInt("total", total);
msg.setData(b);
mHandler.sendMessage(msg);
}
msg = mHandler.obtainMessage(MSG_STATUS);
b = new Bundle();
b.putString("message", getString(R.string.msg_initializingmaps));
msg.setData(b);
mHandler.sendMessage(msg);
// initialize maps
application.initializeMaps();
total += PROGRESS_STEP;
msg = mHandler.obtainMessage(MSG_PROGRESS);
b = new Bundle();
b.putInt("total", total);
msg.setData(b);
mHandler.sendMessage(msg);
msg = mHandler.obtainMessage(MSG_STATUS);
b = new Bundle();
b.putString("message", getString(R.string.msg_initializingplugins));
msg.setData(b);
mHandler.sendMessage(msg);
// initialize plugins
application.initializePlugins();
total += PROGRESS_STEP;
msg = mHandler.obtainMessage(MSG_PROGRESS);
b = new Bundle();
b.putInt("total", total);
msg.setData(b);
mHandler.sendMessage(msg);
msg = mHandler.obtainMessage(MSG_STATUS);
b = new Bundle();
b.putString("message", getString(R.string.msg_initializingview));
msg.setData(b);
mHandler.sendMessage(msg);
// initialize current map
application.initializeMapCenter();
total += PROGRESS_STEP;
msg = mHandler.obtainMessage(MSG_PROGRESS);
b = new Bundle();
b.putInt("total", total);
msg.setData(b);
mHandler.sendMessage(msg);
mHandler.sendEmptyMessage(MSG_FINISH);
}
| public void run()
{
while (wait)
{
try
{
sleep(100);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
total = 0;
Message msg = mHandler.obtainMessage(MSG_STATUS);
Bundle b = new Bundle();
b.putString("message", getString(R.string.msg_initializingdata));
msg.setData(b);
mHandler.sendMessage(msg);
Resources resources = getResources();
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(Splash.this);
application.enableLocating(settings.getBoolean(getString(R.string.lc_locate), true));
application.enableTracking(settings.getBoolean(getString(R.string.lc_track), true));
// set root folder and check if it has to be created
String rootPath = settings.getString(getString(R.string.pref_folder_root), Environment.getExternalStorageDirectory() + File.separator + resources.getString(R.string.def_folder_prefix));
File root = new File(rootPath);
if (!root.exists())
{
try
{
root.mkdirs();
File nomedia = new File(root, ".nomedia");
nomedia.createNewFile();
}
catch (IOException e)
{
msg = mHandler.obtainMessage(MSG_ERROR);
b = new Bundle();
b.putString("message", getString(R.string.err_nosdcard));
msg.setData(b);
mHandler.sendMessage(msg);
return;
}
}
// check maps folder existence
File mapdir = new File(settings.getString(getString(R.string.pref_folder_map), Environment.getExternalStorageDirectory() + File.separator + resources.getString(R.string.def_folder_map)));
String oldmap = settings.getString(getString(R.string.pref_folder_map_old), null);
if (oldmap != null)
{
File oldmapdir = new File(root, oldmap);
if (! oldmapdir.equals(mapdir))
{
mapdir = oldmapdir;
Editor editor = settings.edit();
editor.putString(getString(R.string.pref_folder_map), mapdir.getAbsolutePath());
editor.putString(getString(R.string.pref_folder_map_old), null);
editor.commit();
}
}
if (!mapdir.exists())
{
mapdir.mkdirs();
}
// check data folder existence
File datadir = new File(settings.getString(getString(R.string.pref_folder_data), Environment.getExternalStorageDirectory() + File.separator + resources.getString(R.string.def_folder_data)));
if (!datadir.exists())
{
// check if there was an old data structure
String wptdir = settings.getString(getString(R.string.pref_folder_waypoint), null);
System.err.println("wpt: " + wptdir);
if (wptdir != null)
{
wait = true;
msg = mHandler.obtainMessage(MSG_SAY);
b = new Bundle();
b.putString("message", getString(R.string.msg_newdatafolder, datadir.getAbsolutePath()));
msg.setData(b);
mHandler.sendMessage(msg);
while (wait)
{
try
{
sleep(100);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
datadir.mkdirs();
}
// initialize paths
application.setRootPath(root.getAbsolutePath());
application.setMapPath(mapdir.getAbsolutePath());
application.setDataPath(Androzic.PATH_DATA, datadir.getAbsolutePath());
application.setDataPath(Androzic.PATH_ICONS, settings.getString(getString(R.string.pref_folder_icon), Environment.getExternalStorageDirectory() + File.separator + resources.getString(R.string.def_folder_icon)));
// initialize data
application.installData();
// read default waypoints
File wptFile = new File(application.dataPath, "myWaypoints.wpt");
if (wptFile.exists() && wptFile.canRead())
{
try
{
application.addWaypoints(OziExplorerFiles.loadWaypointsFromFile(wptFile));
}
catch (IOException e)
{
e.printStackTrace();
}
}
// read track tail
if (settings.getBoolean(getString(R.string.pref_showcurrenttrack), true))
{
application.currentTrackOverlay = new CurrentTrackOverlay(Splash.this);
if (settings.getBoolean(getString(R.string.pref_tracking_currentload), resources.getBoolean(R.bool.def_tracking_currentload)))
{
String name = settings.getString(getString(R.string.trk_current), "myTrack.plt");
File trkFile = new File(application.dataPath, name);
if (trkFile.exists() && trkFile.canRead())
{
try
{
application.currentTrackOverlay.setTrack(OziExplorerFiles.loadTrackFromFile(trkFile, Integer.parseInt(settings.getString(getString(R.string.pref_tracking_currentlength), getString(R.string.def_tracking_currentlength)))));
}
catch (IllegalArgumentException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
}
// load routes
if (settings.getBoolean(getString(R.string.pref_route_preload), resources.getBoolean(R.bool.def_route_preload)))
{
List<File> files = FileList.getFileListing(new File(application.dataPath), new RouteFilenameFilter());
for (File file : files)
{
List<Route> routes = null;
try
{
String lc = file.getName().toLowerCase();
if (lc.endsWith(".rt2") || lc.endsWith(".rte"))
{
routes = OziExplorerFiles.loadRoutesFromFile(file);
}
else if (lc.endsWith(".kml"))
{
routes = KmlFiles.loadRoutesFromFile(file);
}
else if (lc.endsWith(".gpx"))
{
routes = GpxFiles.loadRoutesFromFile(file);
}
application.addRoutes(routes);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
total += PROGRESS_STEP;
msg = mHandler.obtainMessage(MSG_PROGRESS);
b = new Bundle();
b.putInt("total", total);
msg.setData(b);
mHandler.sendMessage(msg);
// load maps if no any found
if (mapdir.list().length == 0)
{
wait = true;
msg = mHandler.obtainMessage(MSG_ASK);
b = new Bundle();
b.putString("message", getString(R.string.nomaps_explained, application.getMapPath()));
msg.setData(b);
mHandler.sendMessage(msg);
while (wait)
{
try
{
sleep(100);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
if (result == RES_YES)
{
try
{
// URL u = new URL("http://androzic.googlecode.com/files/world.ozfx3");
URL u = new URL("https://docs.google.com/uc?export=download&id=0Bxnm5oGXU2cja2lQMzVvWFNpZjQ");
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
FileOutputStream f = new FileOutputStream(new File(application.getMapPath(), "world.ozf2"));
InputStream in = c.getInputStream();
msg = mHandler.obtainMessage(MSG_STATUS);
b = new Bundle();
b.putString("message", getString(R.string.msg_loadingimagefile));
msg.setData(b);
mHandler.sendMessage(msg);
byte[] buffer = new byte[1024];
int len = 0;
while ((len = in.read(buffer)) > 0)
{
f.write(buffer, 0, len);
total += len;
msg = mHandler.obtainMessage(MSG_PROGRESS);
b = new Bundle();
b.putInt("total", total);
msg.setData(b);
mHandler.sendMessage(msg);
}
f.close();
msg = mHandler.obtainMessage(MSG_STATUS);
b = new Bundle();
b.putString("message", getString(R.string.msg_loadingmapfile));
msg.setData(b);
mHandler.sendMessage(msg);
//u = new URL("http://androzic.googlecode.com/files/world.map");
u = new URL("https://docs.google.com/uc?export=download&id=0Bxnm5oGXU2cjWllteG4tSDBxekU");
c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
f = new FileOutputStream(new File(application.getMapPath(), "world.map"));
in = c.getInputStream();
buffer = new byte[1024];
len = 0;
while ((len = in.read(buffer)) > 0)
{
f.write(buffer, 0, len);
total += len;
msg = mHandler.obtainMessage(MSG_PROGRESS);
b = new Bundle();
b.putInt("total", total);
msg.setData(b);
mHandler.sendMessage(msg);
}
f.close();
}
catch (IOException e)
{
e.printStackTrace();
msg = mHandler.obtainMessage(MSG_ERROR);
b = new Bundle();
b.putString("message", getString(R.string.err_noconnection));
msg.setData(b);
mHandler.sendMessage(msg);
File dir = new File(application.getMapPath());
File[] files = dir.listFiles();
if (files != null)
{
for (int i = 0; i < files.length; i++)
{
files[i].delete();
}
}
return;
}
}
}
else
{
total += DOWNLOAD_SIZE;
msg = mHandler.obtainMessage(MSG_PROGRESS);
b = new Bundle();
b.putInt("total", total);
msg.setData(b);
mHandler.sendMessage(msg);
}
msg = mHandler.obtainMessage(MSG_STATUS);
b = new Bundle();
b.putString("message", getString(R.string.msg_initializingmaps));
msg.setData(b);
mHandler.sendMessage(msg);
// initialize maps
application.initializeMaps();
total += PROGRESS_STEP;
msg = mHandler.obtainMessage(MSG_PROGRESS);
b = new Bundle();
b.putInt("total", total);
msg.setData(b);
mHandler.sendMessage(msg);
msg = mHandler.obtainMessage(MSG_STATUS);
b = new Bundle();
b.putString("message", getString(R.string.msg_initializingplugins));
msg.setData(b);
mHandler.sendMessage(msg);
// initialize plugins
application.initializePlugins();
total += PROGRESS_STEP;
msg = mHandler.obtainMessage(MSG_PROGRESS);
b = new Bundle();
b.putInt("total", total);
msg.setData(b);
mHandler.sendMessage(msg);
msg = mHandler.obtainMessage(MSG_STATUS);
b = new Bundle();
b.putString("message", getString(R.string.msg_initializingview));
msg.setData(b);
mHandler.sendMessage(msg);
// initialize current map
application.initializeMapCenter();
total += PROGRESS_STEP;
msg = mHandler.obtainMessage(MSG_PROGRESS);
b = new Bundle();
b.putInt("total", total);
msg.setData(b);
mHandler.sendMessage(msg);
mHandler.sendEmptyMessage(MSG_FINISH);
}
|
diff --git a/server/src/main/java/imagej/omero/server/DefaultOMEROService.java b/server/src/main/java/imagej/omero/server/DefaultOMEROService.java
index b320804..6c3ebee 100644
--- a/server/src/main/java/imagej/omero/server/DefaultOMEROService.java
+++ b/server/src/main/java/imagej/omero/server/DefaultOMEROService.java
@@ -1,325 +1,325 @@
/*
* #%L
* Call ImageJ commands from OMERO on the server side.
* %%
* Copyright (C) 2013 Board of Regents of the University of
* Wisconsin-Madison.
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-2.0.html>.
* #L%
*/
package imagej.omero.server;
import imagej.data.Dataset;
import imagej.data.display.DatasetView;
import imagej.data.display.ImageDisplay;
import imagej.data.display.ImageDisplayService;
import imagej.display.DisplayService;
import imagej.module.ModuleItem;
import java.lang.reflect.Array;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.scijava.log.LogService;
import org.scijava.plugin.Parameter;
import org.scijava.plugin.Plugin;
import org.scijava.service.AbstractService;
import org.scijava.service.Service;
import org.scijava.util.ClassUtils;
/**
* Default ImageJ service for managing OMERO data conversion.
*
* @author Curtis Rueden
*/
@Plugin(type = Service.class)
public class DefaultOMEROService extends AbstractService implements
OMEROService
{
// -- Parameters --
@Parameter
private LogService log;
@Parameter
private DisplayService displayService;
@Parameter
private ImageDisplayService imageDisplayService;
// -- OMEROService methods --
@Override
public omero.grid.Param getJobParam(final ModuleItem<?> item) {
final omero.grid.Param param = new omero.grid.Param();
param.optional = !item.isRequired();
param.prototype = prototype(item.getType());
param.description = item.getDescription();
return param;
}
@Override
public omero.RType prototype(final Class<?> type) {
// image types
if (Dataset.class.isAssignableFrom(type) ||
DatasetView.class.isAssignableFrom(type) ||
ImageDisplay.class.isAssignableFrom(type))
{
// use a pixels ID
return omero.rtypes.rlong(0);
}
// primitive types
final Class<?> saneType = ClassUtils.getNonprimitiveType(type);
if (Boolean.class.isAssignableFrom(saneType)) {
return omero.rtypes.rbool(false);
}
if (Double.class.isAssignableFrom(saneType)) {
return omero.rtypes.rdouble(Double.NaN);
}
if (Float.class.isAssignableFrom(saneType)) {
return omero.rtypes.rfloat(Float.NaN);
}
if (Integer.class.isAssignableFrom(saneType)) {
return omero.rtypes.rint(0);
}
if (Long.class.isAssignableFrom(saneType)) {
return omero.rtypes.rlong(0L);
}
// data structure types
if (type.isArray()) {
return omero.rtypes.rarray();
}
if (List.class.isAssignableFrom(type)) {
return omero.rtypes.rlist();
}
if (Map.class.isAssignableFrom(type)) {
return omero.rtypes.rmap();
}
if (Set.class.isAssignableFrom(type)) {
return omero.rtypes.rset();
}
// default case: convert to string
// works for many types, including but not limited to:
// - char
// - imagej.util.ColorRGB
// - java.io.File
// - java.lang.Character
// - java.lang.String
// - java.math.BigDecimal
// - java.math.BigInteger
return omero.rtypes.rstring("");
}
@Override
public omero.RType toOMERO(final omero.client client, final Object value) {
if (value instanceof Dataset) {
// upload pixels to OMERO, returning the resultant pixels ID
final long id = uploadPixels(client, (Dataset) value);
return toOMERO(client, id);
}
else if (value instanceof DatasetView) {
final DatasetView datasetView = (DatasetView) value;
// TODO: Verify whether any view-specific metadata can be preserved.
return toOMERO(client, datasetView.getData());
}
else if (value instanceof ImageDisplay) {
final ImageDisplay imageDisplay = (ImageDisplay) value;
// TODO: Support more aspects of image displays; e.g., multiple datasets.
return toOMERO(client, imageDisplayService.getActiveDataset(imageDisplay));
}
else {
// try generic conversion method
try {
return omero.rtypes.rtype(value);
}
catch (final omero.ClientError err) {
// default case: convert to string
return omero.rtypes.rstring(value.toString());
}
}
}
@Override
public Object toImageJ(final omero.client client, final omero.RType value,
final Class<?> type)
{
if (value instanceof omero.RCollection) {
// collection of objects
final Collection<omero.RType> omeroCollection =
((omero.RCollection) value).getValue();
final Collection<Object> collection;
if (value instanceof omero.RArray || value instanceof omero.RList) {
// NB: See special handling for omero.RArray below.
collection = new ArrayList<Object>();
}
else if (value instanceof omero.RSet) {
collection = new HashSet<Object>();
}
else {
log.error("Unsupported collection: " + value.getClass().getName());
return null;
}
// convert elements recursively
Object element = null; // NB: Save 1st non-null element for later use.
for (final omero.RType rType : omeroCollection) {
final Object converted = toImageJ(client, rType, null);
if (element != null) element = converted;
collection.add(converted);
}
if (value instanceof omero.RArray) {
// convert from Collection to array of the appropriate type
if (element == null) {
// unknown type
return collection.toArray();
}
// typed on 1st element
return toArray(collection, element.getClass());
}
// not an array, but a bona fide collection
return collection;
}
if (value instanceof omero.RMap) {
// map of objects
final Map<String, omero.RType> omeroMap = ((omero.RMap) value).getValue();
final Map<String, Object> map = new HashMap<String, Object>();
for (final String key : omeroMap.keySet()) {
map.put(key, toImageJ(client, omeroMap.get(key), null));
}
return map;
}
// Use getValue() method if one exists for this type.
// Reflection is necessary because there is no common interface
// with the getValue() method implemented by each subclass.
try {
final Method method = value.getClass().getMethod("getValue");
final Object result = method.invoke(value);
return convert(client, result, type);
}
catch (final NoSuchMethodException exc) {
log.debug(exc);
}
catch (final IllegalArgumentException exc) {
- log.warn(exc);
+ log.error(exc);
}
catch (final IllegalAccessException exc) {
- log.warn(exc);
+ log.error(exc);
}
catch (final InvocationTargetException exc) {
- log.warn(exc);
+ log.error(exc);
}
log.error("Unsupported type: " + value.getClass().getName());
return null;
}
@Override
public Dataset downloadPixels(final omero.client client, final long id) {
// FIXME: Implement this.
return null;
}
@Override
public long uploadPixels(final omero.client client, final Dataset dataset) {
// FIXME: Implement this.
return 0;
}
// -- Helper methods --
/**
* Converts the given POJO to the specified type (if given).
* <p>
* This method handles coersion of POJOs unwrapped from OMERO into the
* relevant type needed by ImageJ. Examples:
* </p>
* <ol>
* <li>Many ImageJ types (such as {@link imagej.util.ColorRGB}) are mapped to
* {@link String} for use with OMERO. We lean on the SciJava Common
* {@link ClassUtils#convert(Object, Class)} method to handle conversion of
* such types back to ImageJ's expected type for the parameter.</li>
* <li>ImageJ's image types (i.e., {@link Dataset}, {@link DatasetView} and
* {@link ImageDisplay}) are mapped to {@code long} since OMERO communicates
* about images using pixel IDs. Work must be done to download pixels from a
* specified ID and converting the result to the appropriate ImageJ image type
* such as {@link Dataset}.</li>
* </ol>
*/
private <T> T convert(final omero.client client, final Object result,
final Class<T> type)
{
if (result == null) return null;
if (type == null) {
// no type given; try a simple cast
@SuppressWarnings("unchecked")
final T typedResult = (T) result;
return typedResult;
}
// special case for converting an OMERO pixels ID to an ImageJ image type
if (ClassUtils.isNumber(result.getClass())) {
if (Dataset.class.isAssignableFrom(type)) {
final long id = ((Number) result).longValue();
// TODO: Consider consequences of this cast more carefully.
@SuppressWarnings("unchecked")
final T dataset = (T) downloadPixels(client, id);
return dataset;
}
if (DatasetView.class.isAssignableFrom(type)) {
final Dataset dataset = convert(client, result, Dataset.class);
@SuppressWarnings("unchecked")
final T dataView = (T) imageDisplayService.createDataView(dataset);
return dataView;
}
if (ImageDisplay.class.isAssignableFrom(type)) {
final Dataset dataset = convert(client, result, Dataset.class);
@SuppressWarnings("unchecked")
final T display = (T) displayService.createDisplay(dataset);
return display;
}
}
// use SciJava Common's automagical conversion routine
final T converted = ClassUtils.convert(result, type);
if (converted == null) {
log.error("Cannot convert: " + result.getClass().getName() + " to " +
type.getName());
}
return converted;
}
/** Converts a {@link Collection} to an array of the given type. */
private <T> T[] toArray(final Collection<Object> collection,
final Class<T> type)
{
final Object array = Array.newInstance(type, 0);
@SuppressWarnings("unchecked")
final T[] typedArray = (T[]) array;
return collection.toArray(typedArray);
}
}
| false | true | public Object toImageJ(final omero.client client, final omero.RType value,
final Class<?> type)
{
if (value instanceof omero.RCollection) {
// collection of objects
final Collection<omero.RType> omeroCollection =
((omero.RCollection) value).getValue();
final Collection<Object> collection;
if (value instanceof omero.RArray || value instanceof omero.RList) {
// NB: See special handling for omero.RArray below.
collection = new ArrayList<Object>();
}
else if (value instanceof omero.RSet) {
collection = new HashSet<Object>();
}
else {
log.error("Unsupported collection: " + value.getClass().getName());
return null;
}
// convert elements recursively
Object element = null; // NB: Save 1st non-null element for later use.
for (final omero.RType rType : omeroCollection) {
final Object converted = toImageJ(client, rType, null);
if (element != null) element = converted;
collection.add(converted);
}
if (value instanceof omero.RArray) {
// convert from Collection to array of the appropriate type
if (element == null) {
// unknown type
return collection.toArray();
}
// typed on 1st element
return toArray(collection, element.getClass());
}
// not an array, but a bona fide collection
return collection;
}
if (value instanceof omero.RMap) {
// map of objects
final Map<String, omero.RType> omeroMap = ((omero.RMap) value).getValue();
final Map<String, Object> map = new HashMap<String, Object>();
for (final String key : omeroMap.keySet()) {
map.put(key, toImageJ(client, omeroMap.get(key), null));
}
return map;
}
// Use getValue() method if one exists for this type.
// Reflection is necessary because there is no common interface
// with the getValue() method implemented by each subclass.
try {
final Method method = value.getClass().getMethod("getValue");
final Object result = method.invoke(value);
return convert(client, result, type);
}
catch (final NoSuchMethodException exc) {
log.debug(exc);
}
catch (final IllegalArgumentException exc) {
log.warn(exc);
}
catch (final IllegalAccessException exc) {
log.warn(exc);
}
catch (final InvocationTargetException exc) {
log.warn(exc);
}
log.error("Unsupported type: " + value.getClass().getName());
return null;
}
| public Object toImageJ(final omero.client client, final omero.RType value,
final Class<?> type)
{
if (value instanceof omero.RCollection) {
// collection of objects
final Collection<omero.RType> omeroCollection =
((omero.RCollection) value).getValue();
final Collection<Object> collection;
if (value instanceof omero.RArray || value instanceof omero.RList) {
// NB: See special handling for omero.RArray below.
collection = new ArrayList<Object>();
}
else if (value instanceof omero.RSet) {
collection = new HashSet<Object>();
}
else {
log.error("Unsupported collection: " + value.getClass().getName());
return null;
}
// convert elements recursively
Object element = null; // NB: Save 1st non-null element for later use.
for (final omero.RType rType : omeroCollection) {
final Object converted = toImageJ(client, rType, null);
if (element != null) element = converted;
collection.add(converted);
}
if (value instanceof omero.RArray) {
// convert from Collection to array of the appropriate type
if (element == null) {
// unknown type
return collection.toArray();
}
// typed on 1st element
return toArray(collection, element.getClass());
}
// not an array, but a bona fide collection
return collection;
}
if (value instanceof omero.RMap) {
// map of objects
final Map<String, omero.RType> omeroMap = ((omero.RMap) value).getValue();
final Map<String, Object> map = new HashMap<String, Object>();
for (final String key : omeroMap.keySet()) {
map.put(key, toImageJ(client, omeroMap.get(key), null));
}
return map;
}
// Use getValue() method if one exists for this type.
// Reflection is necessary because there is no common interface
// with the getValue() method implemented by each subclass.
try {
final Method method = value.getClass().getMethod("getValue");
final Object result = method.invoke(value);
return convert(client, result, type);
}
catch (final NoSuchMethodException exc) {
log.debug(exc);
}
catch (final IllegalArgumentException exc) {
log.error(exc);
}
catch (final IllegalAccessException exc) {
log.error(exc);
}
catch (final InvocationTargetException exc) {
log.error(exc);
}
log.error("Unsupported type: " + value.getClass().getName());
return null;
}
|
diff --git a/teo/teo/isgci/drawing/GraphEvent.java b/teo/teo/isgci/drawing/GraphEvent.java
index 87bec2a..a60e840 100644
--- a/teo/teo/isgci/drawing/GraphEvent.java
+++ b/teo/teo/isgci/drawing/GraphEvent.java
@@ -1,29 +1,30 @@
package teo.isgci.drawing;
import java.awt.event.MouseAdapter;
import com.mxgraph.swing.mxGraphComponent;
/**
* Dumbed down version of the original, WIP GraphEvent
* TODO: replace this with the final one
*/
class GraphEvent implements GraphEventInterface {
private mxGraphComponent graphComponent;
protected GraphEvent(mxGraphComponent graphComponent) {
this.graphComponent = graphComponent;
}
/**
* Register a MouseAdapter to receive events from the graph panel.
*
* @param adapter MouseAdapter
*/
@Override
public void registerMouseAdapter(MouseAdapter adapter) {
graphComponent.addMouseListener(adapter);
+ graphComponent.getGraphControl().addMouseListener(adapter);
graphComponent.addMouseWheelListener(adapter);
}
}
| true | true | public void registerMouseAdapter(MouseAdapter adapter) {
graphComponent.addMouseListener(adapter);
graphComponent.addMouseWheelListener(adapter);
}
| public void registerMouseAdapter(MouseAdapter adapter) {
graphComponent.addMouseListener(adapter);
graphComponent.getGraphControl().addMouseListener(adapter);
graphComponent.addMouseWheelListener(adapter);
}
|
diff --git a/src/main/java/ch/o2it/weblounge/contentrepository/impl/endpoint/FilesEndpointDocs.java b/src/main/java/ch/o2it/weblounge/contentrepository/impl/endpoint/FilesEndpointDocs.java
index ce63d42b1..515151e94 100644
--- a/src/main/java/ch/o2it/weblounge/contentrepository/impl/endpoint/FilesEndpointDocs.java
+++ b/src/main/java/ch/o2it/weblounge/contentrepository/impl/endpoint/FilesEndpointDocs.java
@@ -1,171 +1,171 @@
/*
* Weblounge: Web Content Management System
* Copyright (c) 2010 The Weblounge Team
* http://weblounge.o2it.ch
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package ch.o2it.weblounge.contentrepository.impl.endpoint;
import static ch.o2it.weblounge.common.impl.util.doc.Status.conflict;
import static ch.o2it.weblounge.common.impl.util.doc.Status.methodNotAllowed;
import static ch.o2it.weblounge.common.impl.util.doc.Status.preconditionFailed;
import static ch.o2it.weblounge.common.impl.util.doc.Status.badRequest;
import static ch.o2it.weblounge.common.impl.util.doc.Status.notFound;
import static ch.o2it.weblounge.common.impl.util.doc.Status.ok;
import static ch.o2it.weblounge.common.impl.util.doc.Status.serviceUnavailable;
import ch.o2it.weblounge.common.impl.util.doc.Endpoint;
import ch.o2it.weblounge.common.impl.util.doc.EndpointDocumentation;
import ch.o2it.weblounge.common.impl.util.doc.EndpointDocumentationGenerator;
import ch.o2it.weblounge.common.impl.util.doc.Format;
import ch.o2it.weblounge.common.impl.util.doc.Parameter;
import ch.o2it.weblounge.common.impl.util.doc.TestForm;
import ch.o2it.weblounge.common.impl.util.doc.Endpoint.Method;
/**
* File endpoint documentation generator.
*/
public final class FilesEndpointDocs {
/**
* Creates the documentation.
*
* @param endpointUrl
* the endpoint address
* @return the endpoint documentation
*/
public static String createDocumentation(String endpointUrl) {
EndpointDocumentation docs = new EndpointDocumentation(endpointUrl, "files");
docs.setTitle("Weblounge Files");
// GET /?path=
- Endpoint getFileByPathEndpoint = new Endpoint("/{resource}", Method.GET, "getfile");
+ Endpoint getFileByPathEndpoint = new Endpoint("/", Method.GET, "getfile");
getFileByPathEndpoint.setDescription("Returns the file that is located at the given path");
getFileByPathEndpoint.addFormat(Format.xml());
getFileByPathEndpoint.addStatus(ok("the file was found and is returned as part of the response"));
getFileByPathEndpoint.addStatus(notFound("the file was not found or could not be loaded"));
getFileByPathEndpoint.addStatus(badRequest("an invalid path was received"));
getFileByPathEndpoint.addStatus(serviceUnavailable("the site or its content repository is temporarily offline"));
getFileByPathEndpoint.addRequiredParameter(new Parameter("path", Parameter.Type.String, "The resource path"));
getFileByPathEndpoint.setTestForm(new TestForm());
docs.addEndpoint(Endpoint.Type.READ, getFileByPathEndpoint);
// GET /{resource}
Endpoint getFileByURIEndpoint = new Endpoint("/{resource}", Method.GET, "getfile");
getFileByURIEndpoint.setDescription("Returns the file with the given id");
getFileByURIEndpoint.addFormat(Format.xml());
getFileByURIEndpoint.addStatus(ok("the file was found and is returned as part of the response"));
getFileByURIEndpoint.addStatus(notFound("the file was not found or could not be loaded"));
getFileByURIEndpoint.addStatus(badRequest("an invalid file identifier was received"));
getFileByURIEndpoint.addStatus(serviceUnavailable("the site or its content repository is temporarily offline"));
getFileByURIEndpoint.addPathParameter(new Parameter("resource", Parameter.Type.String, "The resource identifier"));
getFileByURIEndpoint.setTestForm(new TestForm());
docs.addEndpoint(Endpoint.Type.READ, getFileByURIEndpoint);
// GET /{resource}/content/{language}
Endpoint getFileContentEndpoint = new Endpoint("/{resource}/content/{language}", Method.GET, "getfilecontent");
getFileContentEndpoint.setDescription("Returns the localized file contents with the given id");
getFileContentEndpoint.addFormat(Format.xml());
getFileContentEndpoint.addStatus(ok("the file content was found and is returned as part of the response"));
getFileContentEndpoint.addStatus(notFound("the file was not found or could not be loaded"));
getFileContentEndpoint.addStatus(notFound("the file content don't exist in the specified language"));
getFileContentEndpoint.addStatus(badRequest("an invalid file identifier was received"));
getFileContentEndpoint.addStatus(serviceUnavailable("the site or its content repository is temporarily offline"));
getFileContentEndpoint.addPathParameter(new Parameter("resource", Parameter.Type.String, "The file identifier"));
getFileContentEndpoint.addPathParameter(new Parameter("language", Parameter.Type.String, "The language identifier"));
getFileContentEndpoint.setTestForm(new TestForm());
docs.addEndpoint(Endpoint.Type.READ, getFileContentEndpoint);
// POST /{resource}
Endpoint createFileEndpoint = new Endpoint("/", Method.POST, "createfile");
createFileEndpoint.setDescription("Creates a new file, either at the given path or at a random location and returns the REST url of the created resource.");
createFileEndpoint.addFormat(Format.xml());
createFileEndpoint.addStatus(ok("the file was created and the response body contains it's resource url"));
createFileEndpoint.addStatus(badRequest("the path was not specified"));
createFileEndpoint.addStatus(badRequest("the file content is malformed"));
createFileEndpoint.addStatus(conflict("a file already exists at the specified path"));
createFileEndpoint.addStatus(methodNotAllowed("the site or its content repository is read-only"));
createFileEndpoint.addStatus(serviceUnavailable("the site or its content repository is temporarily offline"));
createFileEndpoint.addOptionalParameter(new Parameter("path", Parameter.Type.String, "The target path"));
createFileEndpoint.addOptionalParameter(new Parameter("content", Parameter.Type.Text, "The resource data"));
createFileEndpoint.setTestForm(new TestForm());
docs.addEndpoint(Endpoint.Type.WRITE, createFileEndpoint);
// PUT /{resource}
Endpoint updateFileEndpoint = new Endpoint("/{resource}", Method.PUT, "updatefile");
updateFileEndpoint.setDescription("Updates the specified file. If the client supplies an If-Match header, the update is processed only if the header value matches the file's ETag");
updateFileEndpoint.addFormat(Format.xml());
updateFileEndpoint.addStatus(ok("the file was updated"));
updateFileEndpoint.addStatus(badRequest("the file content was not specified"));
updateFileEndpoint.addStatus(badRequest("the file content is malformed"));
updateFileEndpoint.addStatus(preconditionFailed("the file's etag does not match the value specified in the If-Match header"));
updateFileEndpoint.addStatus(methodNotAllowed("the site or its content repository is read-only"));
updateFileEndpoint.addStatus(serviceUnavailable("the site or its content repository is temporarily offline"));
updateFileEndpoint.addPathParameter(new Parameter("resource", Parameter.Type.String, "The file identifier"));
updateFileEndpoint.addOptionalParameter(new Parameter("content", Parameter.Type.Text, "The resource data"));
updateFileEndpoint.setTestForm(new TestForm());
docs.addEndpoint(Endpoint.Type.WRITE, updateFileEndpoint);
// DELETE /{resource}
Endpoint deleteFileEndpoint = new Endpoint("/{resource}", Method.DELETE, "deletefile");
deleteFileEndpoint.setDescription("Deletes the specified file.");
deleteFileEndpoint.addFormat(Format.xml());
deleteFileEndpoint.addStatus(ok("the file was deleted"));
deleteFileEndpoint.addStatus(badRequest("the file was not specified"));
deleteFileEndpoint.addStatus(notFound("the file was not found"));
deleteFileEndpoint.addStatus(methodNotAllowed("the site or its content repository is read-only"));
deleteFileEndpoint.addStatus(serviceUnavailable("the site or its content repository is temporarily offline"));
deleteFileEndpoint.addPathParameter(new Parameter("resource", Parameter.Type.String, "The file identifier"));
deleteFileEndpoint.setTestForm(new TestForm());
docs.addEndpoint(Endpoint.Type.WRITE, deleteFileEndpoint);
// PUT /{resource}/content/{language}
Endpoint updateFileContentEndpoint = new Endpoint("/{resource}/content/{language}", Method.PUT, "updatefilecontent");
updateFileContentEndpoint.setDescription("Updates the specified file contents. If the client supplies an If-Match header, the update is processed only if the header value matches the file's ETag");
updateFileContentEndpoint.addFormat(Format.xml());
updateFileContentEndpoint.addStatus(ok("the file content was updated"));
updateFileContentEndpoint.addStatus(badRequest("the file content was not specified"));
updateFileContentEndpoint.addStatus(badRequest("the language does not exist"));
updateFileContentEndpoint.addStatus(badRequest("the file content is malformed"));
updateFileContentEndpoint.addStatus(preconditionFailed("the file's etag does not match the value specified in the If-Match header"));
updateFileContentEndpoint.addStatus(methodNotAllowed("the site or it's content repository is read-only"));
updateFileContentEndpoint.addStatus(serviceUnavailable("the site or it's content repository is temporarily offline"));
updateFileContentEndpoint.addPathParameter(new Parameter("resource", Parameter.Type.String, "The file identifier"));
updateFileContentEndpoint.addPathParameter(new Parameter("language", Parameter.Type.String, "The language"));
updateFileContentEndpoint.addOptionalParameter(new Parameter("content", Parameter.Type.File, "The resource content"));
updateFileContentEndpoint.setTestForm(new TestForm());
docs.addEndpoint(Endpoint.Type.WRITE, updateFileContentEndpoint);
// DELETE /{resource}/content/{language}
Endpoint deleteFileContentEndpoint = new Endpoint("/{resource}/content/{language}", Method.DELETE, "deletefilecontent");
deleteFileContentEndpoint.setDescription("Deletes the specified file content.");
deleteFileContentEndpoint.addFormat(Format.xml());
deleteFileContentEndpoint.addStatus(ok("the file content was deleted"));
deleteFileContentEndpoint.addStatus(badRequest("the file content was not specified"));
deleteFileContentEndpoint.addStatus(notFound("the file was not found"));
deleteFileContentEndpoint.addStatus(notFound("the file content was not found"));
deleteFileContentEndpoint.addStatus(methodNotAllowed("the site or its content repository is read-only"));
deleteFileContentEndpoint.addStatus(serviceUnavailable("the site or its content repository is temporarily offline"));
deleteFileContentEndpoint.addPathParameter(new Parameter("resource", Parameter.Type.String, "The file identifier"));
deleteFileContentEndpoint.addPathParameter(new Parameter("language", Parameter.Type.String, "The language identifier"));
deleteFileContentEndpoint.setTestForm(new TestForm());
docs.addEndpoint(Endpoint.Type.WRITE, deleteFileContentEndpoint);
return EndpointDocumentationGenerator.generate(docs);
}
}
| true | true | public static String createDocumentation(String endpointUrl) {
EndpointDocumentation docs = new EndpointDocumentation(endpointUrl, "files");
docs.setTitle("Weblounge Files");
// GET /?path=
Endpoint getFileByPathEndpoint = new Endpoint("/{resource}", Method.GET, "getfile");
getFileByPathEndpoint.setDescription("Returns the file that is located at the given path");
getFileByPathEndpoint.addFormat(Format.xml());
getFileByPathEndpoint.addStatus(ok("the file was found and is returned as part of the response"));
getFileByPathEndpoint.addStatus(notFound("the file was not found or could not be loaded"));
getFileByPathEndpoint.addStatus(badRequest("an invalid path was received"));
getFileByPathEndpoint.addStatus(serviceUnavailable("the site or its content repository is temporarily offline"));
getFileByPathEndpoint.addRequiredParameter(new Parameter("path", Parameter.Type.String, "The resource path"));
getFileByPathEndpoint.setTestForm(new TestForm());
docs.addEndpoint(Endpoint.Type.READ, getFileByPathEndpoint);
// GET /{resource}
Endpoint getFileByURIEndpoint = new Endpoint("/{resource}", Method.GET, "getfile");
getFileByURIEndpoint.setDescription("Returns the file with the given id");
getFileByURIEndpoint.addFormat(Format.xml());
getFileByURIEndpoint.addStatus(ok("the file was found and is returned as part of the response"));
getFileByURIEndpoint.addStatus(notFound("the file was not found or could not be loaded"));
getFileByURIEndpoint.addStatus(badRequest("an invalid file identifier was received"));
getFileByURIEndpoint.addStatus(serviceUnavailable("the site or its content repository is temporarily offline"));
getFileByURIEndpoint.addPathParameter(new Parameter("resource", Parameter.Type.String, "The resource identifier"));
getFileByURIEndpoint.setTestForm(new TestForm());
docs.addEndpoint(Endpoint.Type.READ, getFileByURIEndpoint);
// GET /{resource}/content/{language}
Endpoint getFileContentEndpoint = new Endpoint("/{resource}/content/{language}", Method.GET, "getfilecontent");
getFileContentEndpoint.setDescription("Returns the localized file contents with the given id");
getFileContentEndpoint.addFormat(Format.xml());
getFileContentEndpoint.addStatus(ok("the file content was found and is returned as part of the response"));
getFileContentEndpoint.addStatus(notFound("the file was not found or could not be loaded"));
getFileContentEndpoint.addStatus(notFound("the file content don't exist in the specified language"));
getFileContentEndpoint.addStatus(badRequest("an invalid file identifier was received"));
getFileContentEndpoint.addStatus(serviceUnavailable("the site or its content repository is temporarily offline"));
getFileContentEndpoint.addPathParameter(new Parameter("resource", Parameter.Type.String, "The file identifier"));
getFileContentEndpoint.addPathParameter(new Parameter("language", Parameter.Type.String, "The language identifier"));
getFileContentEndpoint.setTestForm(new TestForm());
docs.addEndpoint(Endpoint.Type.READ, getFileContentEndpoint);
// POST /{resource}
Endpoint createFileEndpoint = new Endpoint("/", Method.POST, "createfile");
createFileEndpoint.setDescription("Creates a new file, either at the given path or at a random location and returns the REST url of the created resource.");
createFileEndpoint.addFormat(Format.xml());
createFileEndpoint.addStatus(ok("the file was created and the response body contains it's resource url"));
createFileEndpoint.addStatus(badRequest("the path was not specified"));
createFileEndpoint.addStatus(badRequest("the file content is malformed"));
createFileEndpoint.addStatus(conflict("a file already exists at the specified path"));
createFileEndpoint.addStatus(methodNotAllowed("the site or its content repository is read-only"));
createFileEndpoint.addStatus(serviceUnavailable("the site or its content repository is temporarily offline"));
createFileEndpoint.addOptionalParameter(new Parameter("path", Parameter.Type.String, "The target path"));
createFileEndpoint.addOptionalParameter(new Parameter("content", Parameter.Type.Text, "The resource data"));
createFileEndpoint.setTestForm(new TestForm());
docs.addEndpoint(Endpoint.Type.WRITE, createFileEndpoint);
// PUT /{resource}
Endpoint updateFileEndpoint = new Endpoint("/{resource}", Method.PUT, "updatefile");
updateFileEndpoint.setDescription("Updates the specified file. If the client supplies an If-Match header, the update is processed only if the header value matches the file's ETag");
updateFileEndpoint.addFormat(Format.xml());
updateFileEndpoint.addStatus(ok("the file was updated"));
updateFileEndpoint.addStatus(badRequest("the file content was not specified"));
updateFileEndpoint.addStatus(badRequest("the file content is malformed"));
updateFileEndpoint.addStatus(preconditionFailed("the file's etag does not match the value specified in the If-Match header"));
updateFileEndpoint.addStatus(methodNotAllowed("the site or its content repository is read-only"));
updateFileEndpoint.addStatus(serviceUnavailable("the site or its content repository is temporarily offline"));
updateFileEndpoint.addPathParameter(new Parameter("resource", Parameter.Type.String, "The file identifier"));
updateFileEndpoint.addOptionalParameter(new Parameter("content", Parameter.Type.Text, "The resource data"));
updateFileEndpoint.setTestForm(new TestForm());
docs.addEndpoint(Endpoint.Type.WRITE, updateFileEndpoint);
// DELETE /{resource}
Endpoint deleteFileEndpoint = new Endpoint("/{resource}", Method.DELETE, "deletefile");
deleteFileEndpoint.setDescription("Deletes the specified file.");
deleteFileEndpoint.addFormat(Format.xml());
deleteFileEndpoint.addStatus(ok("the file was deleted"));
deleteFileEndpoint.addStatus(badRequest("the file was not specified"));
deleteFileEndpoint.addStatus(notFound("the file was not found"));
deleteFileEndpoint.addStatus(methodNotAllowed("the site or its content repository is read-only"));
deleteFileEndpoint.addStatus(serviceUnavailable("the site or its content repository is temporarily offline"));
deleteFileEndpoint.addPathParameter(new Parameter("resource", Parameter.Type.String, "The file identifier"));
deleteFileEndpoint.setTestForm(new TestForm());
docs.addEndpoint(Endpoint.Type.WRITE, deleteFileEndpoint);
// PUT /{resource}/content/{language}
Endpoint updateFileContentEndpoint = new Endpoint("/{resource}/content/{language}", Method.PUT, "updatefilecontent");
updateFileContentEndpoint.setDescription("Updates the specified file contents. If the client supplies an If-Match header, the update is processed only if the header value matches the file's ETag");
updateFileContentEndpoint.addFormat(Format.xml());
updateFileContentEndpoint.addStatus(ok("the file content was updated"));
updateFileContentEndpoint.addStatus(badRequest("the file content was not specified"));
updateFileContentEndpoint.addStatus(badRequest("the language does not exist"));
updateFileContentEndpoint.addStatus(badRequest("the file content is malformed"));
updateFileContentEndpoint.addStatus(preconditionFailed("the file's etag does not match the value specified in the If-Match header"));
updateFileContentEndpoint.addStatus(methodNotAllowed("the site or it's content repository is read-only"));
updateFileContentEndpoint.addStatus(serviceUnavailable("the site or it's content repository is temporarily offline"));
updateFileContentEndpoint.addPathParameter(new Parameter("resource", Parameter.Type.String, "The file identifier"));
updateFileContentEndpoint.addPathParameter(new Parameter("language", Parameter.Type.String, "The language"));
updateFileContentEndpoint.addOptionalParameter(new Parameter("content", Parameter.Type.File, "The resource content"));
updateFileContentEndpoint.setTestForm(new TestForm());
docs.addEndpoint(Endpoint.Type.WRITE, updateFileContentEndpoint);
// DELETE /{resource}/content/{language}
Endpoint deleteFileContentEndpoint = new Endpoint("/{resource}/content/{language}", Method.DELETE, "deletefilecontent");
deleteFileContentEndpoint.setDescription("Deletes the specified file content.");
deleteFileContentEndpoint.addFormat(Format.xml());
deleteFileContentEndpoint.addStatus(ok("the file content was deleted"));
deleteFileContentEndpoint.addStatus(badRequest("the file content was not specified"));
deleteFileContentEndpoint.addStatus(notFound("the file was not found"));
deleteFileContentEndpoint.addStatus(notFound("the file content was not found"));
deleteFileContentEndpoint.addStatus(methodNotAllowed("the site or its content repository is read-only"));
deleteFileContentEndpoint.addStatus(serviceUnavailable("the site or its content repository is temporarily offline"));
deleteFileContentEndpoint.addPathParameter(new Parameter("resource", Parameter.Type.String, "The file identifier"));
deleteFileContentEndpoint.addPathParameter(new Parameter("language", Parameter.Type.String, "The language identifier"));
deleteFileContentEndpoint.setTestForm(new TestForm());
docs.addEndpoint(Endpoint.Type.WRITE, deleteFileContentEndpoint);
return EndpointDocumentationGenerator.generate(docs);
}
| public static String createDocumentation(String endpointUrl) {
EndpointDocumentation docs = new EndpointDocumentation(endpointUrl, "files");
docs.setTitle("Weblounge Files");
// GET /?path=
Endpoint getFileByPathEndpoint = new Endpoint("/", Method.GET, "getfile");
getFileByPathEndpoint.setDescription("Returns the file that is located at the given path");
getFileByPathEndpoint.addFormat(Format.xml());
getFileByPathEndpoint.addStatus(ok("the file was found and is returned as part of the response"));
getFileByPathEndpoint.addStatus(notFound("the file was not found or could not be loaded"));
getFileByPathEndpoint.addStatus(badRequest("an invalid path was received"));
getFileByPathEndpoint.addStatus(serviceUnavailable("the site or its content repository is temporarily offline"));
getFileByPathEndpoint.addRequiredParameter(new Parameter("path", Parameter.Type.String, "The resource path"));
getFileByPathEndpoint.setTestForm(new TestForm());
docs.addEndpoint(Endpoint.Type.READ, getFileByPathEndpoint);
// GET /{resource}
Endpoint getFileByURIEndpoint = new Endpoint("/{resource}", Method.GET, "getfile");
getFileByURIEndpoint.setDescription("Returns the file with the given id");
getFileByURIEndpoint.addFormat(Format.xml());
getFileByURIEndpoint.addStatus(ok("the file was found and is returned as part of the response"));
getFileByURIEndpoint.addStatus(notFound("the file was not found or could not be loaded"));
getFileByURIEndpoint.addStatus(badRequest("an invalid file identifier was received"));
getFileByURIEndpoint.addStatus(serviceUnavailable("the site or its content repository is temporarily offline"));
getFileByURIEndpoint.addPathParameter(new Parameter("resource", Parameter.Type.String, "The resource identifier"));
getFileByURIEndpoint.setTestForm(new TestForm());
docs.addEndpoint(Endpoint.Type.READ, getFileByURIEndpoint);
// GET /{resource}/content/{language}
Endpoint getFileContentEndpoint = new Endpoint("/{resource}/content/{language}", Method.GET, "getfilecontent");
getFileContentEndpoint.setDescription("Returns the localized file contents with the given id");
getFileContentEndpoint.addFormat(Format.xml());
getFileContentEndpoint.addStatus(ok("the file content was found and is returned as part of the response"));
getFileContentEndpoint.addStatus(notFound("the file was not found or could not be loaded"));
getFileContentEndpoint.addStatus(notFound("the file content don't exist in the specified language"));
getFileContentEndpoint.addStatus(badRequest("an invalid file identifier was received"));
getFileContentEndpoint.addStatus(serviceUnavailable("the site or its content repository is temporarily offline"));
getFileContentEndpoint.addPathParameter(new Parameter("resource", Parameter.Type.String, "The file identifier"));
getFileContentEndpoint.addPathParameter(new Parameter("language", Parameter.Type.String, "The language identifier"));
getFileContentEndpoint.setTestForm(new TestForm());
docs.addEndpoint(Endpoint.Type.READ, getFileContentEndpoint);
// POST /{resource}
Endpoint createFileEndpoint = new Endpoint("/", Method.POST, "createfile");
createFileEndpoint.setDescription("Creates a new file, either at the given path or at a random location and returns the REST url of the created resource.");
createFileEndpoint.addFormat(Format.xml());
createFileEndpoint.addStatus(ok("the file was created and the response body contains it's resource url"));
createFileEndpoint.addStatus(badRequest("the path was not specified"));
createFileEndpoint.addStatus(badRequest("the file content is malformed"));
createFileEndpoint.addStatus(conflict("a file already exists at the specified path"));
createFileEndpoint.addStatus(methodNotAllowed("the site or its content repository is read-only"));
createFileEndpoint.addStatus(serviceUnavailable("the site or its content repository is temporarily offline"));
createFileEndpoint.addOptionalParameter(new Parameter("path", Parameter.Type.String, "The target path"));
createFileEndpoint.addOptionalParameter(new Parameter("content", Parameter.Type.Text, "The resource data"));
createFileEndpoint.setTestForm(new TestForm());
docs.addEndpoint(Endpoint.Type.WRITE, createFileEndpoint);
// PUT /{resource}
Endpoint updateFileEndpoint = new Endpoint("/{resource}", Method.PUT, "updatefile");
updateFileEndpoint.setDescription("Updates the specified file. If the client supplies an If-Match header, the update is processed only if the header value matches the file's ETag");
updateFileEndpoint.addFormat(Format.xml());
updateFileEndpoint.addStatus(ok("the file was updated"));
updateFileEndpoint.addStatus(badRequest("the file content was not specified"));
updateFileEndpoint.addStatus(badRequest("the file content is malformed"));
updateFileEndpoint.addStatus(preconditionFailed("the file's etag does not match the value specified in the If-Match header"));
updateFileEndpoint.addStatus(methodNotAllowed("the site or its content repository is read-only"));
updateFileEndpoint.addStatus(serviceUnavailable("the site or its content repository is temporarily offline"));
updateFileEndpoint.addPathParameter(new Parameter("resource", Parameter.Type.String, "The file identifier"));
updateFileEndpoint.addOptionalParameter(new Parameter("content", Parameter.Type.Text, "The resource data"));
updateFileEndpoint.setTestForm(new TestForm());
docs.addEndpoint(Endpoint.Type.WRITE, updateFileEndpoint);
// DELETE /{resource}
Endpoint deleteFileEndpoint = new Endpoint("/{resource}", Method.DELETE, "deletefile");
deleteFileEndpoint.setDescription("Deletes the specified file.");
deleteFileEndpoint.addFormat(Format.xml());
deleteFileEndpoint.addStatus(ok("the file was deleted"));
deleteFileEndpoint.addStatus(badRequest("the file was not specified"));
deleteFileEndpoint.addStatus(notFound("the file was not found"));
deleteFileEndpoint.addStatus(methodNotAllowed("the site or its content repository is read-only"));
deleteFileEndpoint.addStatus(serviceUnavailable("the site or its content repository is temporarily offline"));
deleteFileEndpoint.addPathParameter(new Parameter("resource", Parameter.Type.String, "The file identifier"));
deleteFileEndpoint.setTestForm(new TestForm());
docs.addEndpoint(Endpoint.Type.WRITE, deleteFileEndpoint);
// PUT /{resource}/content/{language}
Endpoint updateFileContentEndpoint = new Endpoint("/{resource}/content/{language}", Method.PUT, "updatefilecontent");
updateFileContentEndpoint.setDescription("Updates the specified file contents. If the client supplies an If-Match header, the update is processed only if the header value matches the file's ETag");
updateFileContentEndpoint.addFormat(Format.xml());
updateFileContentEndpoint.addStatus(ok("the file content was updated"));
updateFileContentEndpoint.addStatus(badRequest("the file content was not specified"));
updateFileContentEndpoint.addStatus(badRequest("the language does not exist"));
updateFileContentEndpoint.addStatus(badRequest("the file content is malformed"));
updateFileContentEndpoint.addStatus(preconditionFailed("the file's etag does not match the value specified in the If-Match header"));
updateFileContentEndpoint.addStatus(methodNotAllowed("the site or it's content repository is read-only"));
updateFileContentEndpoint.addStatus(serviceUnavailable("the site or it's content repository is temporarily offline"));
updateFileContentEndpoint.addPathParameter(new Parameter("resource", Parameter.Type.String, "The file identifier"));
updateFileContentEndpoint.addPathParameter(new Parameter("language", Parameter.Type.String, "The language"));
updateFileContentEndpoint.addOptionalParameter(new Parameter("content", Parameter.Type.File, "The resource content"));
updateFileContentEndpoint.setTestForm(new TestForm());
docs.addEndpoint(Endpoint.Type.WRITE, updateFileContentEndpoint);
// DELETE /{resource}/content/{language}
Endpoint deleteFileContentEndpoint = new Endpoint("/{resource}/content/{language}", Method.DELETE, "deletefilecontent");
deleteFileContentEndpoint.setDescription("Deletes the specified file content.");
deleteFileContentEndpoint.addFormat(Format.xml());
deleteFileContentEndpoint.addStatus(ok("the file content was deleted"));
deleteFileContentEndpoint.addStatus(badRequest("the file content was not specified"));
deleteFileContentEndpoint.addStatus(notFound("the file was not found"));
deleteFileContentEndpoint.addStatus(notFound("the file content was not found"));
deleteFileContentEndpoint.addStatus(methodNotAllowed("the site or its content repository is read-only"));
deleteFileContentEndpoint.addStatus(serviceUnavailable("the site or its content repository is temporarily offline"));
deleteFileContentEndpoint.addPathParameter(new Parameter("resource", Parameter.Type.String, "The file identifier"));
deleteFileContentEndpoint.addPathParameter(new Parameter("language", Parameter.Type.String, "The language identifier"));
deleteFileContentEndpoint.setTestForm(new TestForm());
docs.addEndpoint(Endpoint.Type.WRITE, deleteFileContentEndpoint);
return EndpointDocumentationGenerator.generate(docs);
}
|
diff --git a/src/org/sparvnastet/rnf/GameThread.java b/src/org/sparvnastet/rnf/GameThread.java
index 6d3ca40..34664af 100644
--- a/src/org/sparvnastet/rnf/GameThread.java
+++ b/src/org/sparvnastet/rnf/GameThread.java
@@ -1,103 +1,104 @@
/**
* Copyright (c) 2012 Anders Sundman <[email protected]>
*
* This file is part of 'Rise and Fall' (RnF).
*
* RnF is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* RnF 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 RnF. If not, see <http://www.gnu.org/licenses/>.
*/
package org.sparvnastet.rnf;
import java.util.concurrent.atomic.AtomicBoolean;
import android.view.MotionEvent;
/**
* An IGameThread represents an asynchronous path of execution that runs the
* game. It should handle inputs, advance and then render the game state.
*/
interface IGameThread extends Runnable {
public void doStart();
public void doStop();
}
/**
* A concrete game thread that handles input, advances the game state through a
* physics simulation and renders the state to a renderer.
*
* Once started and stopped, the same instance can not be started again. A new
* instance is required to continue.
*/
class GameThread extends Thread implements IGameThread {
private AtomicBoolean running_ = new AtomicBoolean(false);
private IRenderer renderer_;
private IInputBroker inputBroker_;
private IPhysicsSimulator physicsSimulator_;
private GameState gameState_;
private long lastTime_;
public GameThread(IPhysicsSimulator physicsSimulator, IRenderer renderer, IInputBroker inputBroker,
GameState gameState) {
physicsSimulator_ = physicsSimulator;
renderer_ = renderer;
inputBroker_ = inputBroker;
gameState_ = gameState;
}
/**
* Start the game thread.
*/
@Override
public void doStart() {
running_.set(true);
lastTime_ = System.currentTimeMillis();
start();
}
/**
* Stop the game thread as soon as possible. The method returns directly and
* doesn't wait for the thread to stop.
*/
@Override
public void doStop() {
running_.set(false);
}
/**
* Run the game loop. 1. Get input, 2. Do physics, 3. Render.
*
* While this method is public, it should not be called directly. Use the
* doStart/doStop to control execution.
*/
@Override
public void run() {
while (running_.get()) {
MotionEvent[] motionEvents = inputBroker_.takeBundle();
// Check how much to advance the simulation
long now = System.currentTimeMillis();
float elapsed = (float) ((now - lastTime_) / 1000.0);
+ lastTime_ = now;
gameState_ = physicsSimulator_.run(elapsed, gameState_, motionEvents);
renderer_.render(gameState_);
}
}
}
| true | true | public void run() {
while (running_.get()) {
MotionEvent[] motionEvents = inputBroker_.takeBundle();
// Check how much to advance the simulation
long now = System.currentTimeMillis();
float elapsed = (float) ((now - lastTime_) / 1000.0);
gameState_ = physicsSimulator_.run(elapsed, gameState_, motionEvents);
renderer_.render(gameState_);
}
}
| public void run() {
while (running_.get()) {
MotionEvent[] motionEvents = inputBroker_.takeBundle();
// Check how much to advance the simulation
long now = System.currentTimeMillis();
float elapsed = (float) ((now - lastTime_) / 1000.0);
lastTime_ = now;
gameState_ = physicsSimulator_.run(elapsed, gameState_, motionEvents);
renderer_.render(gameState_);
}
}
|
diff --git a/src/org/ohmage/controls/ActionBarControl.java b/src/org/ohmage/controls/ActionBarControl.java
index 35cca76..189e1e6 100644
--- a/src/org/ohmage/controls/ActionBarControl.java
+++ b/src/org/ohmage/controls/ActionBarControl.java
@@ -1,222 +1,223 @@
package org.ohmage.controls;
import org.ohmage.R;
import org.ohmage.activity.DashboardActivity;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class ActionBarControl extends LinearLayout {
private final Activity mActivity;
// view references
private final TextView mTitleText;
private final ImageButton mHomeButton;
private final ProgressBar mProgressSpinner;
private ImageView mHomeSeparator;
// functionality
private final List<ImageButton> mActionButtons;
private final List<ImageView> mSeparators;
private ActionListener mActionBarClickedListener;
private final OnClickListener mActionButtonClickListener;
// style flags
private boolean mShowLogo;
private boolean mShowHome;
public ActionBarControl(Context context, AttributeSet attrs) {
super(context, attrs);
mActivity = (Activity)context;
// load up the elements of the actionbar from controls_actionbar.xml
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(R.layout.controls_actionbar, this, true);
// set up some basic layout parameters, like width x height and background
this.setBackgroundResource(R.drawable.title_bkgnd);
// gather member references
mTitleText = (TextView) findViewById(R.id.controls_actionbar_title);
mHomeButton = (ImageButton) findViewById(R.id.controls_actionbar_home);
mProgressSpinner = (ProgressBar) findViewById(R.id.controls_actionbar_progress);
// hook up buttons
mHomeButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mActivity.startActivity(new Intent(mActivity, DashboardActivity.class).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
+ mActivity.finish();
}
});
// serves as a single handler for routing all action button presses to a user-supplied callback
mActionButtonClickListener = new OnClickListener() {
@Override
public void onClick(View v) {
// route clicks on the action bar to the user-supplied action handler, if present
if (mActionBarClickedListener != null)
mActionBarClickedListener.onActionClicked(v.getId());
}
};
// holds a list of buttons that we manage
mActionButtons = new ArrayList<ImageButton>();
mSeparators = new ArrayList<ImageView>();
// apply the xml-specified attributes, too
initStyles(attrs);
}
public ActionBarControl(Context context) {
this(context, null);
}
/**
* Initializes the appearance of the control based on the attributes passed from the xml.
* @param attrs the collection of attributes, usually provided in the control's constructor
*/
protected void initStyles(AttributeSet attrs) {
TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.ActivityBarControl);
mShowLogo = a.getBoolean(R.styleable.ActivityBarControl_showlogo, false);
String titleText = a.getString(R.styleable.ActivityBarControl_title);
mHomeSeparator = (ImageView) findViewById(R.id.controls_actionbar_homebutton_separator);
mTitleText.setText(titleText);
setShowLogo(mShowLogo);
// and set whether or not the home button appears
setHomeVisibility(a.getBoolean(R.styleable.ActivityBarControl_showhome, true));
}
public void setShowLogo(boolean showLogo) {
ImageView logo = (ImageView) findViewById(R.id.controls_actionbar_logo);
if (showLogo) {
logo.setVisibility(VISIBLE);
mHomeSeparator.setVisibility(GONE);
mHomeButton.setVisibility(GONE);
mTitleText.setVisibility(INVISIBLE);
} else {
logo.setVisibility(GONE);
mHomeSeparator.setVisibility(VISIBLE);
mHomeButton.setVisibility(VISIBLE);
mTitleText.setVisibility(VISIBLE);
}
}
/**
* Set the visibility of the home button. Note that this is overridden by "showlogo";
* if the logo is visible, the home button will never appear.
*
* @param isVisible if true, home button is shown; if false, home button is hidden
*/
public void setHomeVisibility(boolean isVisible) {
if (!isVisible || mShowLogo) {
mHomeSeparator.setVisibility(GONE);
mHomeButton.setVisibility(GONE);
mShowHome = false;
}
else {
mHomeSeparator.setVisibility(VISIBLE);
mHomeButton.setVisibility(VISIBLE);
mShowHome = true;
}
}
/**
* Sets the title for the action bar, which is displayed when showlogo is false.
*
* @param text the text to display in the action bar
*/
public void setTitle(CharSequence text) {
mTitleText.setText(text);
}
/**
* Shows or hides a progress bar "spinner" depending on the value of isVisible. Generally shown
* to indicate that a lengthy background operation is in progress and hidden once it's done.
*
* @param isVisible shows spinner if true, hides it if false
*/
public void setProgressVisible(boolean isVisible) {
mProgressSpinner.setVisibility(isVisible?VISIBLE:GONE);
}
/**
* Adds a command to the action bar, identified in callbacks by buttonID. Note that buttonID will be used
* as the ID of the ImageButton that this method creates.
*
* @param buttonID an id which should uniquely identify this command, up to the caller to create
* @param description a string which defines this command, used for accessibility
* @param resid a drawable to render as the icon. should be the same size as the action bar (i.e. 40x40px hdpi)
*/
public void addActionBarCommand(int buttonID, String description, int resID) {
// inflate a new separator and button from the dashboard templates
// we're doing this mostly to add a predefined style to the view/button, which is currently impossible without xml
ImageView newSeparator = (ImageView) mActivity.getLayoutInflater().inflate(R.layout.controls_actionbar_separator, null);
ImageButton newButton = (ImageButton) mActivity.getLayoutInflater().inflate(R.layout.controls_actionbar_button, null);
newButton.setId(buttonID);
newButton.setContentDescription(description);
newButton.setImageResource(resID);
// attach to our existing listener for routing clicks through the callback
newButton.setOnClickListener(mActionButtonClickListener);
mSeparators.add(newSeparator);
mActionButtons.add(newButton);
// add to the parent layout now
this.addView(newSeparator, new LayoutParams(1, LayoutParams.FILL_PARENT));
this.addView(newButton, new LayoutParams(dpToPixels(45), LayoutParams.FILL_PARENT));
}
/**
* Removes all the action bar commands. This is somewhat useful if you want to recompose the action bar from scratch.
*/
public void clearActionBarCommands() {
for (ImageButton button : mActionButtons)
removeView(button);
for (ImageView sep : mSeparators)
removeView(sep);
}
/**
* Set a callback to be invoked when the user presses any button in the action bar.
*
* @param listener a listener whose {@link ActionListener#onActionClicked(int)} method will be called when a click occurs.
*/
public void setOnActionListener(ActionListener listener) {
mActionBarClickedListener = listener;
}
/**
* Callback that receives action bar button presses when registered with {@link ActionBarControl#setOnActionListener(ActionListener)}
* @author faisal
*
*/
public interface ActionListener {
void onActionClicked(int commandID);
}
// utility method for converting dp to pixels, since the setters only take pixel values :\
private int dpToPixels(int dp) {
final float scale = getResources().getDisplayMetrics().density;
return (int) (dp * scale + 0.5f);
}
}
| true | true | public ActionBarControl(Context context, AttributeSet attrs) {
super(context, attrs);
mActivity = (Activity)context;
// load up the elements of the actionbar from controls_actionbar.xml
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(R.layout.controls_actionbar, this, true);
// set up some basic layout parameters, like width x height and background
this.setBackgroundResource(R.drawable.title_bkgnd);
// gather member references
mTitleText = (TextView) findViewById(R.id.controls_actionbar_title);
mHomeButton = (ImageButton) findViewById(R.id.controls_actionbar_home);
mProgressSpinner = (ProgressBar) findViewById(R.id.controls_actionbar_progress);
// hook up buttons
mHomeButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mActivity.startActivity(new Intent(mActivity, DashboardActivity.class).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
}
});
// serves as a single handler for routing all action button presses to a user-supplied callback
mActionButtonClickListener = new OnClickListener() {
@Override
public void onClick(View v) {
// route clicks on the action bar to the user-supplied action handler, if present
if (mActionBarClickedListener != null)
mActionBarClickedListener.onActionClicked(v.getId());
}
};
// holds a list of buttons that we manage
mActionButtons = new ArrayList<ImageButton>();
mSeparators = new ArrayList<ImageView>();
// apply the xml-specified attributes, too
initStyles(attrs);
}
| public ActionBarControl(Context context, AttributeSet attrs) {
super(context, attrs);
mActivity = (Activity)context;
// load up the elements of the actionbar from controls_actionbar.xml
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(R.layout.controls_actionbar, this, true);
// set up some basic layout parameters, like width x height and background
this.setBackgroundResource(R.drawable.title_bkgnd);
// gather member references
mTitleText = (TextView) findViewById(R.id.controls_actionbar_title);
mHomeButton = (ImageButton) findViewById(R.id.controls_actionbar_home);
mProgressSpinner = (ProgressBar) findViewById(R.id.controls_actionbar_progress);
// hook up buttons
mHomeButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mActivity.startActivity(new Intent(mActivity, DashboardActivity.class).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
mActivity.finish();
}
});
// serves as a single handler for routing all action button presses to a user-supplied callback
mActionButtonClickListener = new OnClickListener() {
@Override
public void onClick(View v) {
// route clicks on the action bar to the user-supplied action handler, if present
if (mActionBarClickedListener != null)
mActionBarClickedListener.onActionClicked(v.getId());
}
};
// holds a list of buttons that we manage
mActionButtons = new ArrayList<ImageButton>();
mSeparators = new ArrayList<ImageView>();
// apply the xml-specified attributes, too
initStyles(attrs);
}
|
diff --git a/tests/DumpRenderTree/src/com/android/dumprendertree/LayoutTestsAutoRunner.java b/tests/DumpRenderTree/src/com/android/dumprendertree/LayoutTestsAutoRunner.java
index 8f968b4397..ebdc9c7230 100755
--- a/tests/DumpRenderTree/src/com/android/dumprendertree/LayoutTestsAutoRunner.java
+++ b/tests/DumpRenderTree/src/com/android/dumprendertree/LayoutTestsAutoRunner.java
@@ -1,73 +1,73 @@
/*
* Copyright (C) 2008 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.android.dumprendertree;
import junit.framework.TestSuite;
import com.android.dumprendertree.LayoutTestsAutoTest;
import android.test.InstrumentationTestRunner;
import android.test.InstrumentationTestSuite;
import android.util.Log;
import android.content.Intent;
import android.os.Bundle;
/**
* Instrumentation Test Runner for all DumpRenderTree tests.
*
* Running all tests:
*
* adb shell am instrument \
* -w com.android.dumprendertree.LayoutTestsAutoRunner
*/
public class LayoutTestsAutoRunner extends InstrumentationTestRunner {
@Override
public TestSuite getAllTests() {
TestSuite suite = new InstrumentationTestSuite(this);
suite.addTestSuite(LayoutTestsAutoTest.class);
suite.addTestSuite(LoadTestsAutoTest.class);
return suite;
}
@Override
public ClassLoader getLoader() {
return LayoutTestsAutoRunner.class.getClassLoader();
}
@Override
public void onCreate(Bundle icicle) {
- super.onCreate(icicle);
this.mTestPath = (String) icicle.get("path");
String timeout_str = (String) icicle.get("timeout");
if (timeout_str != null) {
try {
this.mTimeoutInMillis = Integer.parseInt(timeout_str);
} catch (Exception e) {
e.printStackTrace();
}
}
String r = (String)icicle.get("rebaseline");
this.mRebaseline = (r != null && r.toLowerCase().equals("true"));
+ super.onCreate(icicle);
}
public String mTestPath = null;
public int mTimeoutInMillis = 0;
public boolean mRebaseline = false;
}
| false | true | public void onCreate(Bundle icicle) {
super.onCreate(icicle);
this.mTestPath = (String) icicle.get("path");
String timeout_str = (String) icicle.get("timeout");
if (timeout_str != null) {
try {
this.mTimeoutInMillis = Integer.parseInt(timeout_str);
} catch (Exception e) {
e.printStackTrace();
}
}
String r = (String)icicle.get("rebaseline");
this.mRebaseline = (r != null && r.toLowerCase().equals("true"));
}
| public void onCreate(Bundle icicle) {
this.mTestPath = (String) icicle.get("path");
String timeout_str = (String) icicle.get("timeout");
if (timeout_str != null) {
try {
this.mTimeoutInMillis = Integer.parseInt(timeout_str);
} catch (Exception e) {
e.printStackTrace();
}
}
String r = (String)icicle.get("rebaseline");
this.mRebaseline = (r != null && r.toLowerCase().equals("true"));
super.onCreate(icicle);
}
|
diff --git a/cyklotron-ui/src/main/java/net/cyklotron/cms/modules/actions/structure/UpdateProposedDocument.java b/cyklotron-ui/src/main/java/net/cyklotron/cms/modules/actions/structure/UpdateProposedDocument.java
index 1f5ddcaaa..31f79af9c 100644
--- a/cyklotron-ui/src/main/java/net/cyklotron/cms/modules/actions/structure/UpdateProposedDocument.java
+++ b/cyklotron-ui/src/main/java/net/cyklotron/cms/modules/actions/structure/UpdateProposedDocument.java
@@ -1,175 +1,174 @@
package net.cyklotron.cms.modules.actions.structure;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import org.jcontainer.dna.Logger;
import org.objectledge.context.Context;
import org.objectledge.coral.security.Permission;
import org.objectledge.coral.security.Subject;
import org.objectledge.coral.session.CoralSession;
import org.objectledge.coral.store.Resource;
import org.objectledge.html.HTMLService;
import org.objectledge.parameters.Parameters;
import org.objectledge.parameters.RequestParameters;
import org.objectledge.pipeline.ProcessingException;
import org.objectledge.templating.TemplatingContext;
import org.objectledge.upload.FileUpload;
import org.objectledge.utils.StackTrace;
import org.objectledge.web.HttpContext;
import org.objectledge.web.mvc.MVCContext;
import net.cyklotron.cms.CmsData;
import net.cyklotron.cms.CmsDataFactory;
import net.cyklotron.cms.documents.DocumentNodeResource;
import net.cyklotron.cms.documents.DocumentNodeResourceImpl;
import net.cyklotron.cms.documents.DocumentService;
import net.cyklotron.cms.files.DirectoryResource;
import net.cyklotron.cms.files.FileResource;
import net.cyklotron.cms.files.FilesService;
import net.cyklotron.cms.related.RelatedService;
import net.cyklotron.cms.structure.NavigationNodeResourceImpl;
import net.cyklotron.cms.structure.StructureService;
import net.cyklotron.cms.structure.internal.ProposedDocumentData;
import net.cyklotron.cms.style.StyleService;
public class UpdateProposedDocument
extends BaseProposeDocumentAction
{
private final RelatedService relatedService;
private final HTMLService htmlService;
private final DocumentService documentService;
public UpdateProposedDocument(Logger logger, StructureService structureService,
CmsDataFactory cmsDataFactory, StyleService styleService, FileUpload fileUpload,
FilesService filesService, RelatedService relatedService, HTMLService htmlService,
DocumentService documentService)
{
super(logger, structureService, cmsDataFactory, styleService, filesService, fileUpload);
this.relatedService = relatedService;
this.htmlService = htmlService;
this.documentService = documentService;
}
@Override
public void execute(Context context, Parameters parameters, MVCContext mvcContext,
TemplatingContext templatingContext, HttpContext httpContext, CoralSession coralSession)
throws ProcessingException
{
boolean valid = true;
try
{
long docId = parameters.getLong("doc_id");
DocumentNodeResource node = DocumentNodeResourceImpl.getDocumentNodeResource(
coralSession, docId);
CmsData cmsData = cmsDataFactory.getCmsData(context);
Parameters screenConfig = cmsData.getEmbeddedScreenConfig();
ProposedDocumentData data = new ProposedDocumentData(screenConfig,
documentService.getPreferredImageSizes(), logger);
data.fromParameters(parameters, coralSession);
data.setOrigin(cmsData.getNode());
// check required parameters
if(!data.isValid(htmlService))
{
valid = false;
templatingContext.put("result", data.getValidationFailure());
}
// file upload - checking
if(valid && !data.isFileUploadValid(coralSession, uploadService, filesService))
{
valid = false;
templatingContext.put("result", data.getValidationFailure());
}
if(valid && data.isAttachmentsEnabled())
{
DirectoryResource dir = data.getAttachmenDirectory(coralSession);
- for(int i = 0; i < data.getNewAttachmentsCount()
- && data.getCurrentAttachments().size() + i < data.getAttachmentsMaxCount(); i++)
+ for(int i = data.getCurrentAttachments().size(); i < data.getNewAttachmentsCount()
+ && i < data.getAttachmentsMaxCount(); i++)
{
- FileResource attachment = createAttachment(data, data.getCurrentAttachments()
- .size() + i, dir, coralSession);
+ FileResource attachment = createAttachment(data, i, dir, coralSession);
data.addAttachment(attachment);
}
Set<Resource> publishedAttachments = new HashSet<Resource>(Arrays
.asList(relatedService.getRelatedTo(coralSession, node, node
.getRelatedResourcesSequence(), null)));
for(long id : parameters.getLongs("remove_attachment"))
{
FileResource file = data.removeAttachment(id, coralSession);
if(!publishedAttachments.contains(file) && !node.getThumbnail().equals(file))
{
filesService.deleteFile(coralSession, file);
}
}
}
if(valid)
{
data.toProposal(node);
node.update();
}
}
catch(Exception e)
{
logger.error("excception", e);
templatingContext.put("result", "exception");
templatingContext.put("trace", new StackTrace(e));
valid = false;
}
if(valid)
{
templatingContext.put("result", "update_request_submitted");
}
else
{
parameters.set("state", "EditDocument");
}
}
@Override
public boolean requiresAuthenticatedUser(Context context)
throws Exception
{
return true;
}
@Override
public boolean checkAccessRights(Context context)
throws Exception
{
Parameters requestParameters = context.getAttribute(RequestParameters.class);
CoralSession coralSession = context.getAttribute(CoralSession.class);
Subject userSubject = coralSession.getUserSubject();
long id = requestParameters.getLong("doc_id", -1);
Resource node = NavigationNodeResourceImpl.getNavigationNodeResource(coralSession,
id);
Permission modifyPermission = coralSession.getSecurity().getUniquePermission(
"cms.structure.modify");
Permission modifyOwnPermission = coralSession.getSecurity().getUniquePermission(
"cms.structure.modify_own");
if(userSubject.hasPermission(node, modifyPermission))
{
return true;
}
if(node.getOwner().equals(userSubject)
&& userSubject.hasPermission(node, modifyOwnPermission))
{
return true;
}
if(node.getCreatedBy().equals(userSubject)
&& userSubject.hasPermission(node, modifyOwnPermission))
{
return true;
}
return false;
}
}
| false | true | public void execute(Context context, Parameters parameters, MVCContext mvcContext,
TemplatingContext templatingContext, HttpContext httpContext, CoralSession coralSession)
throws ProcessingException
{
boolean valid = true;
try
{
long docId = parameters.getLong("doc_id");
DocumentNodeResource node = DocumentNodeResourceImpl.getDocumentNodeResource(
coralSession, docId);
CmsData cmsData = cmsDataFactory.getCmsData(context);
Parameters screenConfig = cmsData.getEmbeddedScreenConfig();
ProposedDocumentData data = new ProposedDocumentData(screenConfig,
documentService.getPreferredImageSizes(), logger);
data.fromParameters(parameters, coralSession);
data.setOrigin(cmsData.getNode());
// check required parameters
if(!data.isValid(htmlService))
{
valid = false;
templatingContext.put("result", data.getValidationFailure());
}
// file upload - checking
if(valid && !data.isFileUploadValid(coralSession, uploadService, filesService))
{
valid = false;
templatingContext.put("result", data.getValidationFailure());
}
if(valid && data.isAttachmentsEnabled())
{
DirectoryResource dir = data.getAttachmenDirectory(coralSession);
for(int i = 0; i < data.getNewAttachmentsCount()
&& data.getCurrentAttachments().size() + i < data.getAttachmentsMaxCount(); i++)
{
FileResource attachment = createAttachment(data, data.getCurrentAttachments()
.size() + i, dir, coralSession);
data.addAttachment(attachment);
}
Set<Resource> publishedAttachments = new HashSet<Resource>(Arrays
.asList(relatedService.getRelatedTo(coralSession, node, node
.getRelatedResourcesSequence(), null)));
for(long id : parameters.getLongs("remove_attachment"))
{
FileResource file = data.removeAttachment(id, coralSession);
if(!publishedAttachments.contains(file) && !node.getThumbnail().equals(file))
{
filesService.deleteFile(coralSession, file);
}
}
}
if(valid)
{
data.toProposal(node);
node.update();
}
}
catch(Exception e)
{
logger.error("excception", e);
templatingContext.put("result", "exception");
templatingContext.put("trace", new StackTrace(e));
valid = false;
}
if(valid)
{
templatingContext.put("result", "update_request_submitted");
}
else
{
parameters.set("state", "EditDocument");
}
}
| public void execute(Context context, Parameters parameters, MVCContext mvcContext,
TemplatingContext templatingContext, HttpContext httpContext, CoralSession coralSession)
throws ProcessingException
{
boolean valid = true;
try
{
long docId = parameters.getLong("doc_id");
DocumentNodeResource node = DocumentNodeResourceImpl.getDocumentNodeResource(
coralSession, docId);
CmsData cmsData = cmsDataFactory.getCmsData(context);
Parameters screenConfig = cmsData.getEmbeddedScreenConfig();
ProposedDocumentData data = new ProposedDocumentData(screenConfig,
documentService.getPreferredImageSizes(), logger);
data.fromParameters(parameters, coralSession);
data.setOrigin(cmsData.getNode());
// check required parameters
if(!data.isValid(htmlService))
{
valid = false;
templatingContext.put("result", data.getValidationFailure());
}
// file upload - checking
if(valid && !data.isFileUploadValid(coralSession, uploadService, filesService))
{
valid = false;
templatingContext.put("result", data.getValidationFailure());
}
if(valid && data.isAttachmentsEnabled())
{
DirectoryResource dir = data.getAttachmenDirectory(coralSession);
for(int i = data.getCurrentAttachments().size(); i < data.getNewAttachmentsCount()
&& i < data.getAttachmentsMaxCount(); i++)
{
FileResource attachment = createAttachment(data, i, dir, coralSession);
data.addAttachment(attachment);
}
Set<Resource> publishedAttachments = new HashSet<Resource>(Arrays
.asList(relatedService.getRelatedTo(coralSession, node, node
.getRelatedResourcesSequence(), null)));
for(long id : parameters.getLongs("remove_attachment"))
{
FileResource file = data.removeAttachment(id, coralSession);
if(!publishedAttachments.contains(file) && !node.getThumbnail().equals(file))
{
filesService.deleteFile(coralSession, file);
}
}
}
if(valid)
{
data.toProposal(node);
node.update();
}
}
catch(Exception e)
{
logger.error("excception", e);
templatingContext.put("result", "exception");
templatingContext.put("trace", new StackTrace(e));
valid = false;
}
if(valid)
{
templatingContext.put("result", "update_request_submitted");
}
else
{
parameters.set("state", "EditDocument");
}
}
|
diff --git a/pace-base/src/main/java/com/pace/base/project/utils/PafExcelUtil.java b/pace-base/src/main/java/com/pace/base/project/utils/PafExcelUtil.java
index b96cdf67..866f5ea0 100644
--- a/pace-base/src/main/java/com/pace/base/project/utils/PafExcelUtil.java
+++ b/pace-base/src/main/java/com/pace/base/project/utils/PafExcelUtil.java
@@ -1,1477 +1,1478 @@
/**
*
*/
package com.pace.base.project.utils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.log4j.Logger;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.FormulaEvaluator;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import com.pace.base.PafErrSeverity;
import com.pace.base.PafException;
import com.pace.base.project.ExcelPaceProjectConstants;
import com.pace.base.project.ExcelProjectDataErrorException;
import com.pace.base.project.ProjectDataError;
import com.pace.base.project.ProjectElementId;
import com.pace.base.project.excel.PafExcelInput;
import com.pace.base.project.excel.PafExcelRow;
import com.pace.base.project.excel.PafExcelValueObject;
import com.pace.base.utility.CollectionsUtil;
import com.pace.base.utility.StringUtils;
/**
* @author jmilliron
*
*/
public class PafExcelUtil {
private static final Logger logger = Logger.getLogger(PafExcelUtil.class);
/**
*
* A user can read from an existing workbook via the input, or pass have this method create a new
* workbook reference and read from that. The main objective of this method is to read in a sheet from
* an existing workbook and to convert the data from that sheet into a model pace can use.
*
* If input doesn't have a column limit, a default of 100 columns will be read.
*
* @param input input meta data used by method to read in sheet
* @return a list of paf row's.
* @throws PafException
*/
public static List<PafExcelRow> readExcelSheet(PafExcelInput input) throws PafException {
validateReadInput(input);
Workbook wb = null;
if ( input.getWorkbook() != null ) {
wb = input.getWorkbook();
} else {
wb = readWorkbook(input.getFullWorkbookName());
}
List<PafExcelRow> pafRowList = new ArrayList<PafExcelRow>();
if (wb ==null) logger.info("Workbook(WB) is null");
if ( wb != null ) {
logger.info("Workbook(WB) exists");
Sheet sheet = wb.getSheet(input.getSheetId());
if (sheet ==null) logger.info("Sheet is null");
if ( sheet != null ) {
logger.info("Sheet is not null");
int sheetLastRowNumber = sheet.getLastRowNum();
//if row limit is less than max row number on sheet, reset last row number to row limit.
if ( input.getRowLimit() > 0 && input.getRowLimit() < sheetLastRowNumber ) {
sheetLastRowNumber = input.getRowLimit();
//subtract one to aline with 0 based indexes
sheetLastRowNumber--;
}
int startColumnIndex = 0;
if ( input.getStartDataReadColumnIndex() != null && input.getStartDataReadColumnIndex() < input.getColumnLimit()) {
startColumnIndex = input.getStartDataReadColumnIndex();
}
PafExcelRow pafRow = null;
OUTTER_LOOP:
for (int i = 0; i <= sheetLastRowNumber; i++) {
Row row = sheet.getRow(i);
//if entire row is blank
if ( row == null ) {
//by default, include empty row
if ( ! input.isExcludeEmptyRows() ) {
logger.info("Adding PafExcelRow");
pafRowList.add(new PafExcelRow());
}
continue;
}
int endColumnIndex = input.getColumnLimit();
//Add pace row items to pace row
for (int t = startColumnIndex; t < endColumnIndex; t++) {
Cell cell = row.getCell(t);
//if cell is null, have row create blank cell
if ( cell == null ) {
logger.debug("Null Blank: " + i + ", " + t);
//since cell is null, have row create cell
cell = row.createCell(t, Cell.CELL_TYPE_BLANK);
}
PafExcelValueObject pafExcelValueObject = PafExcelValueObject.createFromCell(wb, cell);
//if 1st column item
if ( t == startColumnIndex ) {
//if user flagged end of sheet data with a string and string matches here, stop reading data
if ( pafExcelValueObject.isString() && input.getEndOfSheetIdnt() != null &&
pafExcelValueObject.getString().equalsIgnoreCase(input.getEndOfSheetIdnt())) {
break OUTTER_LOOP;
}
//if not multi data row or it is but 1st item isn't a blank, create a new row
if ( ! input.isMultiDataRow() || (input.isMultiDataRow() && ! pafExcelValueObject.isBlank()) ) {
pafRow = new PafExcelRow();
}
}
pafRow.addRowItem(t, pafExcelValueObject);
}
//if the list already contains the row, remove.
if (pafRowList.contains(pafRow) && pafRowList.indexOf(pafRow) == (pafRowList.size() - 1)) {
pafRowList.remove(pafRow);
}
pafRowList.add(pafRow);
//header row
if ( isHeaderRow(input, pafRow) ) {
//if exclude header, then remove from list of pace rows
if ( input.isExcludeHeaderRows() ) {
pafRowList.remove(pafRow);
sheetLastRowNumber++;
//else set the header attribute
} else {
pafRow.setHeader(true);
}
//blank row
} else if ( isBlankRow(input, pafRow)) {
if ( input.isExcludeEmptyRows() ) {
pafRowList.remove(pafRow);
sheetLastRowNumber++;
} else {
pafRow.setBlank(true);
}
//data row
} else {
//exclude data rows? if yes, remove
if ( input.isExcludeDataRows()) {
pafRowList.remove(pafRow);
}
}
}
}
}
return pafRowList;
}
private static void validateReadInput(PafExcelInput input) throws PafException {
if ( input == null ) {
String error = "Paf Excel Input cannot be null";
logger.error(error);
throw new NullPointerException(error);
} else if ( input.getFullWorkbookName() == null && input.getWorkbook() == null ) {
String error = "Paf excel input has not been configured property.";
logger.error(error);
throw new NullPointerException(error);
}
Workbook wb = null;
if ( input.getWorkbook() != null ) {
wb = input.getWorkbook();
} else {
wb = readWorkbook(input.getFullWorkbookName());
}
if ( wb == null ) {
String error = "Workbook " + input.getFullWorkbookName() + " could not be read.";
logger.error(error);
throw new PafException(error, PafErrSeverity.Error);
} else {
Sheet sheet = wb.getSheet(input.getSheetId());
if ( sheet == null && input.isSheetRequired() ) {
String error = "Sheet " + input.getSheetId() + " does not exist.";
logger.error(error);
throw new PafException(error, PafErrSeverity.Error);
}
}
}
public static List<String> getWorkbookSheetNames(Workbook workbook) throws PafException {
List<String> sheetNameList = new ArrayList<String>();
if ( workbook != null ) {
for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
sheetNameList.add(workbook.getSheetName(i));
}
}
if ( logger.isDebugEnabled() ) {
logger.debug("Sheets: " + sheetNameList);
}
return sheetNameList;
}
public static List<String> getWorkbookSheetNames(String workbookLocation) throws PafException {
Workbook wb = readWorkbook(workbookLocation);
return getWorkbookSheetNames(wb);
}
private static boolean isBlankRow(PafExcelInput input, PafExcelRow pafRow) {
if ( pafRow != null ) {
for (Integer index : pafRow.getPafExcelValueObjectListMap().keySet()) {
for (PafExcelValueObject valueObject : pafRow.getPafExcelValueObjectListMap().get(index) ) {
if ( ! valueObject.isBlank() ) {
return false;
}
}
}
}
return true;
}
protected static boolean isHeaderRow(PafExcelInput input, PafExcelRow pafRow) {
boolean isHeader = false;
logger.debug("Checking if row is header row.");
if ( input != null && pafRow != null ) {
int startIndex = 0;
if ( input.getStartDataReadColumnIndex() != null && input.getStartDataReadColumnIndex() > 0 ) {
startIndex = input.getStartDataReadColumnIndex();
}
int endIndex = input.getColumnLimit();
//continue if start index is less than end index
if ( startIndex < endIndex ) {
List<Integer> rowColumnIndexList = pafRow.getRowItemOrderedIndexes();
//loop through header list and see if the row matches any of the header list
OUTTER_LOOP:
for (String headerKey : input.getHeaderListMap().keySet()) {
List<String> headerList = input.getHeaderListMap().get(headerKey);
//see if header row or not
if ( headerList != null && headerList.size() > 0 ) {
try {
headerList = headerList.subList(startIndex, endIndex);
} catch (IndexOutOfBoundsException e) {
continue;
}
List<Integer> updateRowColumnIndexList = new ArrayList<Integer>();
try {
updateRowColumnIndexList.addAll(rowColumnIndexList.subList(0, endIndex-startIndex));
} catch (IndexOutOfBoundsException e) {
continue;
}
//if header list size does not equal the number of row item indexes, continue to next header;
if ( updateRowColumnIndexList.size() != headerList.size()) {
continue;
}
isHeader = true;
//loop through all pace row items
for (Integer rowItemIndex : updateRowColumnIndexList ) {
List<PafExcelValueObject> paceRowItemList = pafRow.getRowItem(rowItemIndex);
logger.debug("\tProcessing Row Item List (element 0): " + paceRowItemList.get(0).getValueAsString());
int headerIndex = updateRowColumnIndexList.indexOf(rowItemIndex);
//items to compare
String headerItem = headerList.get(headerIndex);
String paceRowItem = paceRowItemList.get(0).getValueAsString();
//if pace row item is a header ignore field, set as blank
if ( headerItem.equals(ExcelPaceProjectConstants.HEADER_IGNORE_IDENT)) {
paceRowItem = ExcelPaceProjectConstants.HEADER_IGNORE_IDENT;
}
//if string returns something and the header list does not match
if ( paceRowItemList.size() > 1 || (paceRowItemList.size() == 1 && ! headerItem.equalsIgnoreCase(paceRowItem))) {
isHeader = false;
continue OUTTER_LOOP;
}
}
//if header, break look and don't check next header
if ( isHeader ) {
pafRow.setHeaderIdent(headerKey);
break OUTTER_LOOP;
}
}
}
}
}
logger.debug("Row is header: " + isHeader);
return isHeader;
}
public static void writeExcelSheet(PafExcelInput input, List<PafExcelRow> paceRowList) throws PafException {
if ( input == null ) {
throw new IllegalArgumentException("Pace Excel Input cannot be null");
} else if ( input.getFullWorkbookName() == null && input.getWorkbook() == null ) {
throw new IllegalArgumentException("A Full workbook name and a workbook haven't not been provided. One is required.");
}
Workbook wb = null;
if ( input.getWorkbook() != null ) {
wb = input.getWorkbook();
} else {
wb = readWorkbook(input.getFullWorkbookName());
}
if ( wb == null ) {
throw new PafException("Couldn't get a reference to the workbook " + input.getFullWorkbookName() , PafErrSeverity.Error);
}
Sheet sheet = wb.getSheet(input.getSheetId());
if ( sheet == null ) {
sheet = wb.createSheet(input.getSheetId());
} else {
sheet = clearSheetValues(sheet);
}
if ( paceRowList != null ) {
FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
int rowNdx = 0;
int maxNumberOfColumns = 0;
CellStyle boldCellStyle = null;
boolean isFirstHeader = true;
for (PafExcelRow paceRow : paceRowList ) {
if ( paceRow != null ) {
//if row is header and need to exclude, continue to next row
if ( paceRow.isHeader() && input.isExcludeHeaderRows()) {
continue;
}
if ( paceRow.numberOfColumns() > maxNumberOfColumns) {
maxNumberOfColumns = paceRow.numberOfColumns();
}
for (int i = 0; i < paceRow.numberOfCompressedRows(); i++ ) {
Row row = sheet.createRow(rowNdx++);
if ( isFirstHeader && paceRow.isHeader() ) {
//freeze 1st header row
sheet.createFreezePane(0, 1);
isFirstHeader = false;
}
for ( Integer index : paceRow.getRowItemOrderedIndexes() ) {
List<PafExcelValueObject> rowItemList = paceRow.getPafExcelValueObjectListMap().get(index);
//Cell cell = row.createCell(rowItemNdx++);;
Cell cell = row.createCell(index);
if ( i < rowItemList.size()) {
PafExcelValueObject rowItem = rowItemList.get(i);
if ( rowItem == null ) {
cell.setCellType(Cell.CELL_TYPE_BLANK);
} else {
//if header, bold item
if ( paceRow.isHeader() || rowItem.isBoldItem() ) {
if ( boldCellStyle == null ) {
boldCellStyle = getBoldCellStyle(wb);
//turn word wrap on
boldCellStyle.setWrapText(true);
}
cell.setCellStyle(boldCellStyle);
}
switch ( rowItem.getType() ) {
case Blank:
cell.setCellType(Cell.CELL_TYPE_BLANK);
break;
case Boolean:
if ( rowItem.getBoolean() != null ) {
Boolean boolValue = rowItem.getBoolean();
if ( input.isExcludeDefaultValuesOnWrite()) {
//if default, clear value
if ( boolValue.equals(Boolean.FALSE)) {
boolValue = null;
}
}
//true or false
if ( boolValue != null ) {
cell.setCellType(Cell.CELL_TYPE_BOOLEAN);
cell.setCellValue(boolValue);
}
}
break;
case Double:
if ( rowItem.getDouble() != null ) {
Double doubleVal = rowItem.getDouble();
if ( doubleVal != null && input.isExcludeDefaultValuesOnWrite()) {
if ( doubleVal == 0 ) {
doubleVal = null;
}
}
if ( doubleVal != null ) {
cell.setCellType(Cell.CELL_TYPE_NUMERIC);
cell.setCellValue(doubleVal);
}
}
break;
case Integer:
if ( rowItem.getInteger() != null ) {
Integer intValue = rowItem.getInteger();
if ( intValue != null && input.isExcludeDefaultValuesOnWrite()) {
if ( intValue == 0 ) {
intValue = null;
}
}
if ( intValue != null ) {
cell.setCellType(Cell.CELL_TYPE_NUMERIC);
cell.setCellValue(intValue);
}
}
break;
case Formula:
cell.setCellType(Cell.CELL_TYPE_FORMULA);
String formula = rowItem.getFormula();
String formulas[] = formula.split(" & \" \\| \" & ");
if( formulas.length >= 1 ) { //there is only 1 formula
+ formula = formulas[0];
String tokens[] = formula.split("!");
String sheetName = tokens[0];
if( ! sheetName.matches("[a-zA-Z0123456789]*") ) {
formula = "'" + sheetName + "'!" + tokens[1];
}
}
if ( formulas.length > 1 ) { // more than 1 formula concatenated
String tmp = "";
for( int j=1;j<formulas.length;j++ ) {
tmp = formulas[j];
String tokens[] = formulas[j].split("!");
String sheetName = tokens[0];
if( ! sheetName.matches("[a-zA-Z0123456789]*") ) {
tmp = "'" + sheetName + "'!" + tokens[1];
}
formula = formula + " & \" | \" & " + tmp;
}
}
cell.setCellFormula(formula);
evaluator.evaluateFormulaCell(cell);
break;
case String:
cell.setCellType(Cell.CELL_TYPE_STRING);
cell.setCellValue(rowItem.getString());
break;
}
}
} else {
cell.setCellType(Cell.CELL_TYPE_BLANK);
}
}
}
}
}
//add end of sheet ident
if ( input.getEndOfSheetIdnt() != null ) {
int lastSheetRowNumber = sheet.getLastRowNum() + 1;
Row lastRow = sheet.createRow(lastSheetRowNumber);
Cell eosCell = lastRow.createCell(0, Cell.CELL_TYPE_STRING);
eosCell.setCellValue(input.getEndOfSheetIdnt());
//set bold style
eosCell.setCellStyle(getBoldCellStyle(wb));
}
//auto size columns?
if ( input.isAutoSizeColumns() ) {
for (int i = 0; i <= maxNumberOfColumns; i++) {
sheet.autoSizeColumn((short) i);
}
}
}
logger.info("\tSaving sheet: " + input.getSheetId() );
wb.setActiveSheet(wb.getSheetIndex(sheet.getSheetName()));
//if write to filesystem, close workbook
if ( input.isAutoWriteToFileSystem() ) {
writeWorkbook(wb, input.getFullWorkbookName());
}
}
private static CellStyle getBoldCellStyle(Workbook workbook) {
CellStyle cellStyle = null;
if ( workbook != null ) {
cellStyle = workbook.createCellStyle();
Font font = workbook.createFont();
font.setBoldweight(Font.BOLDWEIGHT_BOLD);
cellStyle.setFont(font);
}
return cellStyle;
}
private static Sheet clearSheetValues(Sheet sheet) {
if ( sheet != null ) {
Workbook wb = sheet.getWorkbook();
String sheetName = sheet.getSheetName();
int sheetNdx = wb.getSheetIndex(sheetName);
wb.removeSheetAt(sheetNdx);
sheet = wb.createSheet(sheetName);
wb.setSheetOrder(sheetName, sheetNdx);
}
return sheet;
}
public static String createExcelReference(String sheetId, String address) {
String excelReference = null;
if ( sheetId != null && address != null ) {
if ( sheetId.contains(" ") ) {
sheetId = "'" + sheetId.trim() + "'";
}
excelReference = sheetId + "!" + address;
}
return excelReference;
}
/**
*
* Replaces all blanks with null
*
* @param list list of paf excel value objects
* @return a list of excel value objects will all blank's converted into null items in list
*/
public static List<PafExcelValueObject> convertBlanksToNullInList(List<PafExcelValueObject> list) {
List<PafExcelValueObject> updatedList = new ArrayList<PafExcelValueObject>();
if ( list != null ) {
for (PafExcelValueObject listValueObject : list ) {
if ( listValueObject.isBlank() ) {
updatedList.add(null);
} else {
updatedList.add(listValueObject);
}
}
}
return updatedList;
}
public static String getString(ProjectElementId projectElementId, PafExcelValueObject valueObject, boolean isRequired) throws ExcelProjectDataErrorException {
return getString(projectElementId, valueObject, isRequired, null);
}
public static String getString(ProjectElementId projectElementId, PafExcelValueObject valueObject, List<String> validValueList) throws ExcelProjectDataErrorException {
return getString(projectElementId, valueObject, false, validValueList);
}
public static String getString(ProjectElementId projectElementId, PafExcelValueObject valueObject, boolean isRequired, List<String> validValueList) throws ExcelProjectDataErrorException {
String str = null;
//if null or blank
if ( valueObject == null || valueObject.isBlank() ) {
if ( isRequired ) {
throw new ExcelProjectDataErrorException(ProjectDataError.createRequiredProjectDataError(projectElementId, valueObject));
}
} else if ( valueObject.isString() || valueObject.isFormula() || valueObject.isNumeric() ) {
if ( validValueList == null ) {
str = valueObject.getValueAsString();
} else if (validValueList != null && CollectionsUtil.containsIgnoreCase(validValueList, valueObject.getValueAsString())) {
for (String validValue : validValueList ) {
if ( valueObject.getValueAsString().equalsIgnoreCase(validValue)) {
str = validValue;
break;
}
}
} else {
throw new ExcelProjectDataErrorException(ProjectDataError.createInvalidValueProjectDataError(projectElementId, valueObject, validValueList));
}
} else {
throw new ExcelProjectDataErrorException(ProjectDataError.createInvalidValueProjectDataError(projectElementId, valueObject, validValueList));
}
return str;
}
public static Integer getInteger(ProjectElementId projectElementId, PafExcelValueObject valueObject) throws ExcelProjectDataErrorException {
return getInteger(projectElementId, valueObject, false);
}
public static Integer getInteger(ProjectElementId projectElementId, PafExcelValueObject valueObject, boolean isRequired) throws ExcelProjectDataErrorException {
Integer intValue = null;
//if not blank
if ( valueObject != null && ! valueObject.isBlank() ) {
//if numeric, get int value
if ( valueObject.isNumeric() ) {
intValue = valueObject.getInteger();
//throw invalid exception
} else {
throw new ExcelProjectDataErrorException(ProjectDataError.createInvalidNumberProjectDataError(projectElementId, valueObject));
}
//if blank
} else {
//if required and blank
if ( isRequired ) {
throw new ExcelProjectDataErrorException(ProjectDataError.createRequiredProjectDataError(projectElementId, valueObject));
}
}
return intValue;
}
public static Boolean getBoolean(ProjectElementId projectElementId, PafExcelValueObject valueObject) throws ExcelProjectDataErrorException {
return getBoolean(projectElementId, valueObject, false);
}
public static Boolean getBoolean(ProjectElementId projectElementId, PafExcelValueObject valueObject, boolean returnDefaultIfNull) throws ExcelProjectDataErrorException {
Boolean boolValue = null;
if ( ! valueObject.isBlank() ) {
if ( valueObject.isBoolean() ) {
boolValue = valueObject.getBoolean();
} else {
throw new ExcelProjectDataErrorException(ProjectDataError.createBooleanProjectDataError(projectElementId, valueObject));
}
}
if ( returnDefaultIfNull && boolValue == null) {
boolValue = Boolean.FALSE;
}
return boolValue;
}
public static String[] getStringAr(ProjectElementId projectElementId, List<PafExcelValueObject> valueObjectList) throws ExcelProjectDataErrorException {
return getStringAr(projectElementId, valueObjectList, false);
}
public static String[] getStringAr(ProjectElementId projectElementId, List<PafExcelValueObject> valueObjectList, boolean isRequired ) throws ExcelProjectDataErrorException {
String[] stringAr = null;
List<String> stringList = new ArrayList<String>();
if ( valueObjectList != null ) {
for (PafExcelValueObject excelValueObject : valueObjectList ) {
stringList.add(getString(projectElementId, excelValueObject));
}
}
//if list has elements, convert into a string array
if ( stringList.size() > 0 ) {
stringAr = stringList.toArray(new String[0]);
}
//if required
if ( isRequired ) {
//if required and null or array converted to list with nulls pruned and size of 0, then throw project data error.
if ( stringAr == null || CollectionsUtil.arrayToListPruneNulls(stringAr).size() == 0 ) {
//throw new exception using 1st excel value object in list, should be blank
throw new ExcelProjectDataErrorException(ProjectDataError.createRequiredProjectDataError(projectElementId, valueObjectList.get(0)));
}
}
return stringAr;
}
public static String[] getStringArFromDelimValueObject(ProjectElementId projectElementId, PafExcelValueObject valueObject) throws ExcelProjectDataErrorException {
return getStringArFromDelimValueObject(projectElementId, valueObject, false);
}
public static String[] getStringArFromDelimValueObject(ProjectElementId projectElementId, PafExcelValueObject valueObject, boolean isRequired) throws ExcelProjectDataErrorException {
String[] strAr = null;
//if null or blank
if ( valueObject == null || valueObject.isBlank() ) {
//if required, throw error if null or blank
if ( isRequired ) {
throw new ExcelProjectDataErrorException(ProjectDataError.createRequiredProjectDataError(projectElementId, valueObject));
}
} else if ( valueObject.isString() || valueObject.isFormula() || valueObject.isNumeric() ) {
List<String> listFromString = StringUtils.stringToList(PafExcelUtil.getString(projectElementId, valueObject), ExcelPaceProjectConstants.EXCEL_STRING_FIELD_DELIM);
if ( listFromString.size() > 0 ) {
strAr = listFromString.toArray(new String[0]);
}
}
return strAr;
}
public static String getString(ProjectElementId projectElementId, PafExcelValueObject valueObject) throws ExcelProjectDataErrorException {
return getString(projectElementId, valueObject, false, null);
}
public static String getHexNumber(ProjectElementId projectElementId, PafExcelValueObject valueObject) throws ExcelProjectDataErrorException {
if ( valueObject != null ) {
if ( ! valueObject.isBlank() ) {
String hexNumber = null;
if ( valueObject.isNumeric()) {
hexNumber = valueObject.getInteger().toString();
} else {
hexNumber = valueObject.getValueAsString();
}
//hex values are length of 6
if ( hexNumber.length() != 6 ) {
throw new ExcelProjectDataErrorException(ProjectDataError.createInvalidValueProjectDataError(projectElementId, valueObject));
} else {
Pattern p = Pattern.compile(ExcelPaceProjectConstants.HEX_FONT_PATTERN);
Matcher m = p.matcher(hexNumber);
if ( m.matches() ) {
return hexNumber.toUpperCase();
} else {
throw new ExcelProjectDataErrorException(ProjectDataError.createInvalidValueProjectDataError(projectElementId, valueObject));
}
}
}
}
return null;
}
public static Workbook readWorkbook(String workbookLocation) throws PafException {
if ( workbookLocation == null ) {
throw new IllegalArgumentException("Workbook location can not be null.");
}
Workbook wb = null;
File fullFileWorkbookLocation = new File(workbookLocation);
if ( fullFileWorkbookLocation.isFile() ) {
InputStream inp = null;
try {
inp = new FileInputStream(workbookLocation);
wb = WorkbookFactory.create(inp);
} catch (FileNotFoundException e) {
throw new PafException(e.getMessage(), PafErrSeverity.Error);
} catch (InvalidFormatException e) {
throw new PafException(e.getMessage(), PafErrSeverity.Error);
} catch (IOException e) {
throw new PafException(e.getMessage(), PafErrSeverity.Error);
}
} else {
wb = new XSSFWorkbook();
}
if ( wb == null ) {
logger.error("Couldn't get a refernece to workbook " + workbookLocation);
throw new PafException("Workbook reference " + workbookLocation + " is null.", PafErrSeverity.Error);
}
return wb;
}
public static void writeWorkbook(Workbook wb, String fullWorkbookName) throws PafException {
// Write the output to a file
FileOutputStream fileOut = null;
try {
fileOut = new FileOutputStream(fullWorkbookName);
wb.write(fileOut);
} catch (FileNotFoundException e) {
logger.error(e.getMessage());
throw new PafException(e.getMessage(), PafErrSeverity.Fatal);
} catch (IOException e) {
logger.error(e.getMessage());
throw new PafException(e.getMessage(), PafErrSeverity.Error);
} finally {
if ( fileOut != null ) {
try {
fileOut.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
/**
*
* Creats a cell reference map, key is actual value, value is sheet/cell reference
*
* @param input
* @return
* @throws PafException
*/
public static Map<String, String> createCellReferenceMap ( PafExcelInput input ) throws PafException {
validateReadInput(input);
Map<String, String> cellReferenceMap = new HashMap<String, String>();
List<PafExcelRow> excelRowList = readExcelSheet(input);
int startColumnIndex = 0;
if ( input.getStartDataReadColumnIndex() != null ) {
startColumnIndex = input.getStartDataReadColumnIndex();
}
if ( excelRowList != null ) {
for ( PafExcelRow excelRow : excelRowList ) {
if ( excelRow.getRowItemOrderedIndexes().contains(startColumnIndex)) {
List<PafExcelValueObject> valueObjectList = excelRow.getRowItem(startColumnIndex);
if ( valueObjectList != null && valueObjectList.size() > 0 ) {
//get 1st element
PafExcelValueObject valueObject = valueObjectList.get(0);
if ( valueObject.getCellAddress() != null ) {
cellReferenceMap.put(valueObject.getString(), createExcelReference(input.getSheetId(), valueObject.getCellAddress(true)));
}
}
}
}
}
return cellReferenceMap;
}
public static PafExcelRow createHeaderRow(List<String> headerList) {
PafExcelRow row = new PafExcelRow();
if ( headerList != null) {
row.setHeader(true);
int headerNdx = 0;
for ( String header : headerList ) {
row.addRowItem(headerNdx++, PafExcelValueObject.createFromString(header));
}
}
return row;
}
public static void orderSheets(String fullWorkbookName, List<ProjectElementId> sheetOrderList) throws PafException {
try {
Workbook wb = readWorkbook(fullWorkbookName);
if ( wb != null ) {
Map<ProjectElementId, Integer> sheetOrderMap = new HashMap<ProjectElementId, Integer>();
for ( ProjectElementId projectElementId : sheetOrderList ) {
int sheetIndex = wb.getSheetIndex(projectElementId.toString());
logger.info(projectElementId.toString() + " : sheet index = " + sheetIndex);
}
}
} catch (PafException e) {
throw e;
}
}
public static PafExcelValueObject getDelimValueObjectFromStringAr(String[] stringAr) {
PafExcelValueObject valueObject = null;
if ( stringAr != null && stringAr.length > 0 ) {
List<PafExcelValueObject> list = new ArrayList<PafExcelValueObject>();
for ( String string : stringAr ) {
list.add(PafExcelValueObject.createFromString(string));
}
valueObject = PafExcelUtil.getDelimValueObjectFromList(list);
} else {
valueObject = PafExcelValueObject.createBlank();
}
return valueObject;
}
/**
*
* Converts a list of PafExcelValueObjects into a single PafExcelValueObject that is delimited
* by |'s between the values. If all items are string, then the PafExcelValueObject will be a
* string with the |'s between the string values, but if formula, the entire list is parsed
* into formula segements like this: =RuleSet_ContribPct!$A$2 & "|" & "StoreSales"
*
* @param list list of paf excel value objects
* @return
*/
public static PafExcelValueObject getDelimValueObjectFromList(List<PafExcelValueObject> list) {
PafExcelValueObject valueObject = null;
if ( list != null && list.size() > 0 ) {
boolean allStringValueObjects = true;
for (PafExcelValueObject stringValueObject : list ) {
if ( ! stringValueObject.isString() ) {
allStringValueObjects = false;
break;
}
}
StringBuilder sb = new StringBuilder();
int strNdx = 0;
for (PafExcelValueObject buildValueObject : list ) {
if ( allStringValueObjects ) {
sb.append(buildValueObject.getString());
} else {
if ( buildValueObject.isFormula()) {
sb.append(buildValueObject.getFormula());
} else {
sb.append("\"" + buildValueObject.getString() + "\"");
}
}
if ( ++strNdx != list.size() ) {
if ( allStringValueObjects ) {
sb.append(" " + ExcelPaceProjectConstants.EXCEL_STRING_FIELD_DELIM + " ");
} else {
sb.append(" & \" " + ExcelPaceProjectConstants.EXCEL_STRING_FIELD_DELIM + " \" & ");
}
}
}
if ( allStringValueObjects ) {
valueObject = PafExcelValueObject.createFromString(sb.toString());
} else {
valueObject = PafExcelValueObject.createFromFormula(sb.toString());
}
} else {
valueObject = PafExcelValueObject.createBlank();
}
return valueObject;
}
/**
*
* Deletes a sheet from a workbook
*
* @param workbook workbook to delete sheet from
* @param sheetName name of sheet to delete
*/
public static void deleteSheet(Workbook workbook, String sheetName) {
if ( workbook != null && sheetName != null ) {
int sheetIndex = workbook.getSheetIndex(sheetName);
if ( sheetIndex >= 0 ) {
logger.info("Deleting sheet: " + sheetName);
workbook.removeSheetAt(sheetIndex);
}
}
}
}
| true | true | public static void writeExcelSheet(PafExcelInput input, List<PafExcelRow> paceRowList) throws PafException {
if ( input == null ) {
throw new IllegalArgumentException("Pace Excel Input cannot be null");
} else if ( input.getFullWorkbookName() == null && input.getWorkbook() == null ) {
throw new IllegalArgumentException("A Full workbook name and a workbook haven't not been provided. One is required.");
}
Workbook wb = null;
if ( input.getWorkbook() != null ) {
wb = input.getWorkbook();
} else {
wb = readWorkbook(input.getFullWorkbookName());
}
if ( wb == null ) {
throw new PafException("Couldn't get a reference to the workbook " + input.getFullWorkbookName() , PafErrSeverity.Error);
}
Sheet sheet = wb.getSheet(input.getSheetId());
if ( sheet == null ) {
sheet = wb.createSheet(input.getSheetId());
} else {
sheet = clearSheetValues(sheet);
}
if ( paceRowList != null ) {
FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
int rowNdx = 0;
int maxNumberOfColumns = 0;
CellStyle boldCellStyle = null;
boolean isFirstHeader = true;
for (PafExcelRow paceRow : paceRowList ) {
if ( paceRow != null ) {
//if row is header and need to exclude, continue to next row
if ( paceRow.isHeader() && input.isExcludeHeaderRows()) {
continue;
}
if ( paceRow.numberOfColumns() > maxNumberOfColumns) {
maxNumberOfColumns = paceRow.numberOfColumns();
}
for (int i = 0; i < paceRow.numberOfCompressedRows(); i++ ) {
Row row = sheet.createRow(rowNdx++);
if ( isFirstHeader && paceRow.isHeader() ) {
//freeze 1st header row
sheet.createFreezePane(0, 1);
isFirstHeader = false;
}
for ( Integer index : paceRow.getRowItemOrderedIndexes() ) {
List<PafExcelValueObject> rowItemList = paceRow.getPafExcelValueObjectListMap().get(index);
//Cell cell = row.createCell(rowItemNdx++);;
Cell cell = row.createCell(index);
if ( i < rowItemList.size()) {
PafExcelValueObject rowItem = rowItemList.get(i);
if ( rowItem == null ) {
cell.setCellType(Cell.CELL_TYPE_BLANK);
} else {
//if header, bold item
if ( paceRow.isHeader() || rowItem.isBoldItem() ) {
if ( boldCellStyle == null ) {
boldCellStyle = getBoldCellStyle(wb);
//turn word wrap on
boldCellStyle.setWrapText(true);
}
cell.setCellStyle(boldCellStyle);
}
switch ( rowItem.getType() ) {
case Blank:
cell.setCellType(Cell.CELL_TYPE_BLANK);
break;
case Boolean:
if ( rowItem.getBoolean() != null ) {
Boolean boolValue = rowItem.getBoolean();
if ( input.isExcludeDefaultValuesOnWrite()) {
//if default, clear value
if ( boolValue.equals(Boolean.FALSE)) {
boolValue = null;
}
}
//true or false
if ( boolValue != null ) {
cell.setCellType(Cell.CELL_TYPE_BOOLEAN);
cell.setCellValue(boolValue);
}
}
break;
case Double:
if ( rowItem.getDouble() != null ) {
Double doubleVal = rowItem.getDouble();
if ( doubleVal != null && input.isExcludeDefaultValuesOnWrite()) {
if ( doubleVal == 0 ) {
doubleVal = null;
}
}
if ( doubleVal != null ) {
cell.setCellType(Cell.CELL_TYPE_NUMERIC);
cell.setCellValue(doubleVal);
}
}
break;
case Integer:
if ( rowItem.getInteger() != null ) {
Integer intValue = rowItem.getInteger();
if ( intValue != null && input.isExcludeDefaultValuesOnWrite()) {
if ( intValue == 0 ) {
intValue = null;
}
}
if ( intValue != null ) {
cell.setCellType(Cell.CELL_TYPE_NUMERIC);
cell.setCellValue(intValue);
}
}
break;
case Formula:
cell.setCellType(Cell.CELL_TYPE_FORMULA);
String formula = rowItem.getFormula();
String formulas[] = formula.split(" & \" \\| \" & ");
if( formulas.length >= 1 ) { //there is only 1 formula
String tokens[] = formula.split("!");
String sheetName = tokens[0];
if( ! sheetName.matches("[a-zA-Z0123456789]*") ) {
formula = "'" + sheetName + "'!" + tokens[1];
}
}
if ( formulas.length > 1 ) { // more than 1 formula concatenated
String tmp = "";
for( int j=1;j<formulas.length;j++ ) {
tmp = formulas[j];
String tokens[] = formulas[j].split("!");
String sheetName = tokens[0];
if( ! sheetName.matches("[a-zA-Z0123456789]*") ) {
tmp = "'" + sheetName + "'!" + tokens[1];
}
formula = formula + " & \" | \" & " + tmp;
}
}
cell.setCellFormula(formula);
evaluator.evaluateFormulaCell(cell);
break;
case String:
cell.setCellType(Cell.CELL_TYPE_STRING);
cell.setCellValue(rowItem.getString());
break;
}
}
} else {
cell.setCellType(Cell.CELL_TYPE_BLANK);
}
}
}
}
}
//add end of sheet ident
if ( input.getEndOfSheetIdnt() != null ) {
int lastSheetRowNumber = sheet.getLastRowNum() + 1;
Row lastRow = sheet.createRow(lastSheetRowNumber);
Cell eosCell = lastRow.createCell(0, Cell.CELL_TYPE_STRING);
eosCell.setCellValue(input.getEndOfSheetIdnt());
//set bold style
eosCell.setCellStyle(getBoldCellStyle(wb));
}
//auto size columns?
if ( input.isAutoSizeColumns() ) {
for (int i = 0; i <= maxNumberOfColumns; i++) {
sheet.autoSizeColumn((short) i);
}
}
}
logger.info("\tSaving sheet: " + input.getSheetId() );
wb.setActiveSheet(wb.getSheetIndex(sheet.getSheetName()));
//if write to filesystem, close workbook
if ( input.isAutoWriteToFileSystem() ) {
writeWorkbook(wb, input.getFullWorkbookName());
}
}
| public static void writeExcelSheet(PafExcelInput input, List<PafExcelRow> paceRowList) throws PafException {
if ( input == null ) {
throw new IllegalArgumentException("Pace Excel Input cannot be null");
} else if ( input.getFullWorkbookName() == null && input.getWorkbook() == null ) {
throw new IllegalArgumentException("A Full workbook name and a workbook haven't not been provided. One is required.");
}
Workbook wb = null;
if ( input.getWorkbook() != null ) {
wb = input.getWorkbook();
} else {
wb = readWorkbook(input.getFullWorkbookName());
}
if ( wb == null ) {
throw new PafException("Couldn't get a reference to the workbook " + input.getFullWorkbookName() , PafErrSeverity.Error);
}
Sheet sheet = wb.getSheet(input.getSheetId());
if ( sheet == null ) {
sheet = wb.createSheet(input.getSheetId());
} else {
sheet = clearSheetValues(sheet);
}
if ( paceRowList != null ) {
FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
int rowNdx = 0;
int maxNumberOfColumns = 0;
CellStyle boldCellStyle = null;
boolean isFirstHeader = true;
for (PafExcelRow paceRow : paceRowList ) {
if ( paceRow != null ) {
//if row is header and need to exclude, continue to next row
if ( paceRow.isHeader() && input.isExcludeHeaderRows()) {
continue;
}
if ( paceRow.numberOfColumns() > maxNumberOfColumns) {
maxNumberOfColumns = paceRow.numberOfColumns();
}
for (int i = 0; i < paceRow.numberOfCompressedRows(); i++ ) {
Row row = sheet.createRow(rowNdx++);
if ( isFirstHeader && paceRow.isHeader() ) {
//freeze 1st header row
sheet.createFreezePane(0, 1);
isFirstHeader = false;
}
for ( Integer index : paceRow.getRowItemOrderedIndexes() ) {
List<PafExcelValueObject> rowItemList = paceRow.getPafExcelValueObjectListMap().get(index);
//Cell cell = row.createCell(rowItemNdx++);;
Cell cell = row.createCell(index);
if ( i < rowItemList.size()) {
PafExcelValueObject rowItem = rowItemList.get(i);
if ( rowItem == null ) {
cell.setCellType(Cell.CELL_TYPE_BLANK);
} else {
//if header, bold item
if ( paceRow.isHeader() || rowItem.isBoldItem() ) {
if ( boldCellStyle == null ) {
boldCellStyle = getBoldCellStyle(wb);
//turn word wrap on
boldCellStyle.setWrapText(true);
}
cell.setCellStyle(boldCellStyle);
}
switch ( rowItem.getType() ) {
case Blank:
cell.setCellType(Cell.CELL_TYPE_BLANK);
break;
case Boolean:
if ( rowItem.getBoolean() != null ) {
Boolean boolValue = rowItem.getBoolean();
if ( input.isExcludeDefaultValuesOnWrite()) {
//if default, clear value
if ( boolValue.equals(Boolean.FALSE)) {
boolValue = null;
}
}
//true or false
if ( boolValue != null ) {
cell.setCellType(Cell.CELL_TYPE_BOOLEAN);
cell.setCellValue(boolValue);
}
}
break;
case Double:
if ( rowItem.getDouble() != null ) {
Double doubleVal = rowItem.getDouble();
if ( doubleVal != null && input.isExcludeDefaultValuesOnWrite()) {
if ( doubleVal == 0 ) {
doubleVal = null;
}
}
if ( doubleVal != null ) {
cell.setCellType(Cell.CELL_TYPE_NUMERIC);
cell.setCellValue(doubleVal);
}
}
break;
case Integer:
if ( rowItem.getInteger() != null ) {
Integer intValue = rowItem.getInteger();
if ( intValue != null && input.isExcludeDefaultValuesOnWrite()) {
if ( intValue == 0 ) {
intValue = null;
}
}
if ( intValue != null ) {
cell.setCellType(Cell.CELL_TYPE_NUMERIC);
cell.setCellValue(intValue);
}
}
break;
case Formula:
cell.setCellType(Cell.CELL_TYPE_FORMULA);
String formula = rowItem.getFormula();
String formulas[] = formula.split(" & \" \\| \" & ");
if( formulas.length >= 1 ) { //there is only 1 formula
formula = formulas[0];
String tokens[] = formula.split("!");
String sheetName = tokens[0];
if( ! sheetName.matches("[a-zA-Z0123456789]*") ) {
formula = "'" + sheetName + "'!" + tokens[1];
}
}
if ( formulas.length > 1 ) { // more than 1 formula concatenated
String tmp = "";
for( int j=1;j<formulas.length;j++ ) {
tmp = formulas[j];
String tokens[] = formulas[j].split("!");
String sheetName = tokens[0];
if( ! sheetName.matches("[a-zA-Z0123456789]*") ) {
tmp = "'" + sheetName + "'!" + tokens[1];
}
formula = formula + " & \" | \" & " + tmp;
}
}
cell.setCellFormula(formula);
evaluator.evaluateFormulaCell(cell);
break;
case String:
cell.setCellType(Cell.CELL_TYPE_STRING);
cell.setCellValue(rowItem.getString());
break;
}
}
} else {
cell.setCellType(Cell.CELL_TYPE_BLANK);
}
}
}
}
}
//add end of sheet ident
if ( input.getEndOfSheetIdnt() != null ) {
int lastSheetRowNumber = sheet.getLastRowNum() + 1;
Row lastRow = sheet.createRow(lastSheetRowNumber);
Cell eosCell = lastRow.createCell(0, Cell.CELL_TYPE_STRING);
eosCell.setCellValue(input.getEndOfSheetIdnt());
//set bold style
eosCell.setCellStyle(getBoldCellStyle(wb));
}
//auto size columns?
if ( input.isAutoSizeColumns() ) {
for (int i = 0; i <= maxNumberOfColumns; i++) {
sheet.autoSizeColumn((short) i);
}
}
}
logger.info("\tSaving sheet: " + input.getSheetId() );
wb.setActiveSheet(wb.getSheetIndex(sheet.getSheetName()));
//if write to filesystem, close workbook
if ( input.isAutoWriteToFileSystem() ) {
writeWorkbook(wb, input.getFullWorkbookName());
}
}
|
diff --git a/SampleWebApplication/src/edu/gac/mcs270/ui/client/SampleWebApplication.java b/SampleWebApplication/src/edu/gac/mcs270/ui/client/SampleWebApplication.java
index 880b20c..809fac0 100644
--- a/SampleWebApplication/src/edu/gac/mcs270/ui/client/SampleWebApplication.java
+++ b/SampleWebApplication/src/edu/gac/mcs270/ui/client/SampleWebApplication.java
@@ -1,152 +1,152 @@
package edu.gac.mcs270.ui.client;
import edu.gac.mcs270.ui.shared.FieldVerifier;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
/**
* Entry point classes define <code>onModuleLoad()</code>.
*/
public class SampleWebApplication implements EntryPoint {
/**
* The message displayed to the user when the server cannot be reached or
* returns an error.
*/
private static final String SERVER_ERROR = "An error occurred while "
+ "attempting to contact the server. Please check your network "
+ "connection and try again.";
/**
* Create a remote service proxy to talk to the server-side Greeting service.
*/
private final GreetingServiceAsync greetingService = GWT
.create(GreetingService.class);
/**
* This is the entry point method.
*/
public void onModuleLoad() {
final Button sendButton = new Button("Send");
final TextBox nameField = new TextBox();
nameField.setText("GWT User");
final Label errorLabel = new Label();
// We can add style names to widgets
sendButton.addStyleName("sendButton");
// Add the nameField and sendButton to the RootPanel
// Use RootPanel.get() to get the entire body element
RootPanel.get("nameFieldContainer").add(nameField);
RootPanel.get("sendButtonContainer").add(sendButton);
RootPanel.get("errorLabelContainer").add(errorLabel);
// Focus the cursor on the name field when the app loads
nameField.setFocus(true);
nameField.selectAll();
// Create the popup dialog box
final DialogBox dialogBox = new DialogBox();
dialogBox.setText("Remote Procedure Call");
dialogBox.setAnimationEnabled(true);
final Button closeButton = new Button("Close");
// We can set the id of a widget by accessing its Element
closeButton.getElement().setId("closeButton");
final Label textToServerLabel = new Label();
final HTML serverResponseLabel = new HTML();
VerticalPanel dialogVPanel = new VerticalPanel();
dialogVPanel.addStyleName("dialogVPanel");
dialogVPanel.add(new HTML("<b>Sending name to the server:</b>"));
dialogVPanel.add(textToServerLabel);
dialogVPanel.add(new HTML("<br><b>Server replies:</b>"));
dialogVPanel.add(serverResponseLabel);
dialogVPanel.setHorizontalAlignment(VerticalPanel.ALIGN_RIGHT);
dialogVPanel.add(closeButton);
dialogBox.setWidget(dialogVPanel);
// Add a handler to close the DialogBox
closeButton.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
dialogBox.hide();
sendButton.setEnabled(true);
sendButton.setFocus(true);
}
});
// Create a handler for the sendButton and nameField
class MyHandler implements ClickHandler, KeyUpHandler {
/**
* Fired when the user clicks on the sendButton.
*/
public void onClick(ClickEvent event) {
sendNameToServer();
}
/**
* Fired when the user types in the nameField.
*/
public void onKeyUp(KeyUpEvent event) {
if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
sendNameToServer();
}
}
/**
* Send the name from the nameField to the server and wait for a response.
*/
private void sendNameToServer() {
// First, we validate the input.
errorLabel.setText("");
String textToServer = nameField.getText();
if (!FieldVerifier.isValidName(textToServer)) {
errorLabel.setText("Please enter at least four characters");
return;
}
// Then, we send the input to the server.
sendButton.setEnabled(false);
textToServerLabel.setText(textToServer);
serverResponseLabel.setText("");
greetingService.greetServer(textToServer,
new AsyncCallback<String>() {
public void onFailure(Throwable caught) {
// Show the RPC error message to the user
dialogBox
.setText("Remote Procedure Call - Failure");
serverResponseLabel
- .addStyleName("serverResponseLabelError");
+ .addStyleName("error");
serverResponseLabel.setHTML(SERVER_ERROR);
dialogBox.center();
closeButton.setFocus(true);
}
public void onSuccess(String result) {
dialogBox.setText("Remote Procedure Call");
serverResponseLabel
- .removeStyleName("serverResponseLabelError");
+ .removeStyleName("error");
serverResponseLabel.setHTML(result);
dialogBox.center();
closeButton.setFocus(true);
}
});
}
}
// Add a handler to send the name to the server
MyHandler handler = new MyHandler();
sendButton.addClickHandler(handler);
nameField.addKeyUpHandler(handler);
}
}
| false | true | public void onModuleLoad() {
final Button sendButton = new Button("Send");
final TextBox nameField = new TextBox();
nameField.setText("GWT User");
final Label errorLabel = new Label();
// We can add style names to widgets
sendButton.addStyleName("sendButton");
// Add the nameField and sendButton to the RootPanel
// Use RootPanel.get() to get the entire body element
RootPanel.get("nameFieldContainer").add(nameField);
RootPanel.get("sendButtonContainer").add(sendButton);
RootPanel.get("errorLabelContainer").add(errorLabel);
// Focus the cursor on the name field when the app loads
nameField.setFocus(true);
nameField.selectAll();
// Create the popup dialog box
final DialogBox dialogBox = new DialogBox();
dialogBox.setText("Remote Procedure Call");
dialogBox.setAnimationEnabled(true);
final Button closeButton = new Button("Close");
// We can set the id of a widget by accessing its Element
closeButton.getElement().setId("closeButton");
final Label textToServerLabel = new Label();
final HTML serverResponseLabel = new HTML();
VerticalPanel dialogVPanel = new VerticalPanel();
dialogVPanel.addStyleName("dialogVPanel");
dialogVPanel.add(new HTML("<b>Sending name to the server:</b>"));
dialogVPanel.add(textToServerLabel);
dialogVPanel.add(new HTML("<br><b>Server replies:</b>"));
dialogVPanel.add(serverResponseLabel);
dialogVPanel.setHorizontalAlignment(VerticalPanel.ALIGN_RIGHT);
dialogVPanel.add(closeButton);
dialogBox.setWidget(dialogVPanel);
// Add a handler to close the DialogBox
closeButton.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
dialogBox.hide();
sendButton.setEnabled(true);
sendButton.setFocus(true);
}
});
// Create a handler for the sendButton and nameField
class MyHandler implements ClickHandler, KeyUpHandler {
/**
* Fired when the user clicks on the sendButton.
*/
public void onClick(ClickEvent event) {
sendNameToServer();
}
/**
* Fired when the user types in the nameField.
*/
public void onKeyUp(KeyUpEvent event) {
if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
sendNameToServer();
}
}
/**
* Send the name from the nameField to the server and wait for a response.
*/
private void sendNameToServer() {
// First, we validate the input.
errorLabel.setText("");
String textToServer = nameField.getText();
if (!FieldVerifier.isValidName(textToServer)) {
errorLabel.setText("Please enter at least four characters");
return;
}
// Then, we send the input to the server.
sendButton.setEnabled(false);
textToServerLabel.setText(textToServer);
serverResponseLabel.setText("");
greetingService.greetServer(textToServer,
new AsyncCallback<String>() {
public void onFailure(Throwable caught) {
// Show the RPC error message to the user
dialogBox
.setText("Remote Procedure Call - Failure");
serverResponseLabel
.addStyleName("serverResponseLabelError");
serverResponseLabel.setHTML(SERVER_ERROR);
dialogBox.center();
closeButton.setFocus(true);
}
public void onSuccess(String result) {
dialogBox.setText("Remote Procedure Call");
serverResponseLabel
.removeStyleName("serverResponseLabelError");
serverResponseLabel.setHTML(result);
dialogBox.center();
closeButton.setFocus(true);
}
});
}
}
// Add a handler to send the name to the server
MyHandler handler = new MyHandler();
sendButton.addClickHandler(handler);
nameField.addKeyUpHandler(handler);
}
| public void onModuleLoad() {
final Button sendButton = new Button("Send");
final TextBox nameField = new TextBox();
nameField.setText("GWT User");
final Label errorLabel = new Label();
// We can add style names to widgets
sendButton.addStyleName("sendButton");
// Add the nameField and sendButton to the RootPanel
// Use RootPanel.get() to get the entire body element
RootPanel.get("nameFieldContainer").add(nameField);
RootPanel.get("sendButtonContainer").add(sendButton);
RootPanel.get("errorLabelContainer").add(errorLabel);
// Focus the cursor on the name field when the app loads
nameField.setFocus(true);
nameField.selectAll();
// Create the popup dialog box
final DialogBox dialogBox = new DialogBox();
dialogBox.setText("Remote Procedure Call");
dialogBox.setAnimationEnabled(true);
final Button closeButton = new Button("Close");
// We can set the id of a widget by accessing its Element
closeButton.getElement().setId("closeButton");
final Label textToServerLabel = new Label();
final HTML serverResponseLabel = new HTML();
VerticalPanel dialogVPanel = new VerticalPanel();
dialogVPanel.addStyleName("dialogVPanel");
dialogVPanel.add(new HTML("<b>Sending name to the server:</b>"));
dialogVPanel.add(textToServerLabel);
dialogVPanel.add(new HTML("<br><b>Server replies:</b>"));
dialogVPanel.add(serverResponseLabel);
dialogVPanel.setHorizontalAlignment(VerticalPanel.ALIGN_RIGHT);
dialogVPanel.add(closeButton);
dialogBox.setWidget(dialogVPanel);
// Add a handler to close the DialogBox
closeButton.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
dialogBox.hide();
sendButton.setEnabled(true);
sendButton.setFocus(true);
}
});
// Create a handler for the sendButton and nameField
class MyHandler implements ClickHandler, KeyUpHandler {
/**
* Fired when the user clicks on the sendButton.
*/
public void onClick(ClickEvent event) {
sendNameToServer();
}
/**
* Fired when the user types in the nameField.
*/
public void onKeyUp(KeyUpEvent event) {
if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
sendNameToServer();
}
}
/**
* Send the name from the nameField to the server and wait for a response.
*/
private void sendNameToServer() {
// First, we validate the input.
errorLabel.setText("");
String textToServer = nameField.getText();
if (!FieldVerifier.isValidName(textToServer)) {
errorLabel.setText("Please enter at least four characters");
return;
}
// Then, we send the input to the server.
sendButton.setEnabled(false);
textToServerLabel.setText(textToServer);
serverResponseLabel.setText("");
greetingService.greetServer(textToServer,
new AsyncCallback<String>() {
public void onFailure(Throwable caught) {
// Show the RPC error message to the user
dialogBox
.setText("Remote Procedure Call - Failure");
serverResponseLabel
.addStyleName("error");
serverResponseLabel.setHTML(SERVER_ERROR);
dialogBox.center();
closeButton.setFocus(true);
}
public void onSuccess(String result) {
dialogBox.setText("Remote Procedure Call");
serverResponseLabel
.removeStyleName("error");
serverResponseLabel.setHTML(result);
dialogBox.center();
closeButton.setFocus(true);
}
});
}
}
// Add a handler to send the name to the server
MyHandler handler = new MyHandler();
sendButton.addClickHandler(handler);
nameField.addKeyUpHandler(handler);
}
|
diff --git a/src/edu/sc/seis/sod/NetworkArm.java b/src/edu/sc/seis/sod/NetworkArm.java
index 0a0d392b4..65ce6dee6 100644
--- a/src/edu/sc/seis/sod/NetworkArm.java
+++ b/src/edu/sc/seis/sod/NetworkArm.java
@@ -1,818 +1,820 @@
package edu.sc.seis.sod;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import org.apache.log4j.Logger;
import org.hibernate.LockMode;
import org.hibernate.NonUniqueObjectException;
import org.omg.CORBA.BAD_PARAM;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import edu.iris.Fissures.IfNetwork.Channel;
import edu.iris.Fissures.IfNetwork.NetworkAccess;
import edu.iris.Fissures.IfNetwork.NetworkAttr;
import edu.iris.Fissures.IfNetwork.NetworkDCOperations;
import edu.iris.Fissures.IfNetwork.NetworkId;
import edu.iris.Fissures.IfNetwork.NetworkNotFound;
import edu.iris.Fissures.IfNetwork.Station;
import edu.iris.Fissures.IfNetwork.VirtualNetworkHelper;
import edu.iris.Fissures.model.MicroSecondDate;
import edu.iris.Fissures.model.TimeInterval;
import edu.iris.Fissures.network.ChannelIdUtil;
import edu.iris.Fissures.network.ChannelImpl;
import edu.iris.Fissures.network.NetworkAttrImpl;
import edu.iris.Fissures.network.NetworkIdUtil;
import edu.iris.Fissures.network.StationIdUtil;
import edu.iris.Fissures.network.StationImpl;
import edu.sc.seis.fissuresUtil.cache.CacheNetworkAccess;
import edu.sc.seis.fissuresUtil.cache.DBCacheNetworkAccess;
import edu.sc.seis.fissuresUtil.cache.ProxyNetworkDC;
import edu.sc.seis.fissuresUtil.cache.WorkerThreadPool;
import edu.sc.seis.fissuresUtil.chooser.ClockUtil;
import edu.sc.seis.fissuresUtil.database.NotFound;
import edu.sc.seis.fissuresUtil.display.MicroSecondTimeRange;
import edu.sc.seis.fissuresUtil.exceptionHandler.GlobalExceptionHandler;
import edu.sc.seis.fissuresUtil.hibernate.ChannelGroup;
import edu.sc.seis.fissuresUtil.hibernate.NetworkDB;
import edu.sc.seis.sod.hibernate.SodDB;
import edu.sc.seis.sod.source.event.EventSource;
import edu.sc.seis.sod.source.network.NetworkFinder;
import edu.sc.seis.sod.status.StringTree;
import edu.sc.seis.sod.status.networkArm.NetworkMonitor;
import edu.sc.seis.sod.subsetter.channel.ChannelEffectiveTimeOverlap;
import edu.sc.seis.sod.subsetter.channel.ChannelSubsetter;
import edu.sc.seis.sod.subsetter.channel.PassChannel;
import edu.sc.seis.sod.subsetter.network.NetworkCode;
import edu.sc.seis.sod.subsetter.network.NetworkEffectiveTimeOverlap;
import edu.sc.seis.sod.subsetter.network.NetworkOR;
import edu.sc.seis.sod.subsetter.network.NetworkSubsetter;
import edu.sc.seis.sod.subsetter.network.PassNetwork;
import edu.sc.seis.sod.subsetter.station.PassStation;
import edu.sc.seis.sod.subsetter.station.StationEffectiveTimeOverlap;
import edu.sc.seis.sod.subsetter.station.StationSubsetter;
public class NetworkArm implements Arm {
public NetworkArm(Element config) throws SQLException,
ConfigurationException {
processConfig(config);
}
public void run() {
try {
getSuccessfulNetworks();
} catch(Throwable e) {
Start.armFailure(this, e);
armFinished = true;
}
}
public boolean isActive() {
return !armFinished;
}
public String getName() {
return "NetworkArm";
}
public CacheNetworkAccess getNetwork(NetworkId network_id)
throws NetworkNotFound {
CacheNetworkAccess[] netDbs = getSuccessfulNetworks();
MicroSecondDate beginTime = new MicroSecondDate(network_id.begin_time);
String netCode = network_id.network_code;
for(int i = 0; i < netDbs.length; i++) {
NetworkAttr attr = netDbs[i].get_attributes();
if(netCode.equals(attr.get_code())
&& new MicroSecondTimeRange(attr.getEffectiveTime()).contains(beginTime)) {
return netDbs[i];
}
}
throw new NetworkNotFound("No network for id: "
+ NetworkIdUtil.toString(network_id));
}
private void processConfig(Element config) throws ConfigurationException {
NodeList children = config.getChildNodes();
for(int i = 0; i < children.getLength(); i++) {
Node node = children.item(i);
if(node instanceof Element) {
loadConfigElement(SodUtil.load((Element)node, PACKAGES));
} // end of if (node instanceof Element)
} // end of for (int i=0; i<children.getSize(); i++)
configureEffectiveTimeCheckers();
}
private void configureEffectiveTimeCheckers() {
EventArm arm = Start.getEventArm();
if(arm != null && !Start.getRunProps().allowDeadNets()) {
EventSource[] sources = arm.getSources();
MicroSecondTimeRange fullTime = sources[0].getEventTimeRange();
for(int i = 1; i < sources.length; i++) {
fullTime = new MicroSecondTimeRange(fullTime,
sources[i].getEventTimeRange());
}
edu.iris.Fissures.TimeRange eventQueryTimes = fullTime.getFissuresTimeRange();
netEffectiveSubsetter = new NetworkEffectiveTimeOverlap(eventQueryTimes);
staEffectiveSubsetter = new StationEffectiveTimeOverlap(eventQueryTimes);
chanEffectiveSubsetter = new ChannelEffectiveTimeOverlap(eventQueryTimes);
} else {
logger.debug("No implicit effective time constraint");
}
}
public static final String[] PACKAGES = {"networkArm",
"channel",
"site",
"station",
"network"};
private void loadConfigElement(Object sodElement)
throws ConfigurationException {
if(sodElement instanceof NetworkFinder) {
finder = (NetworkFinder)sodElement;
} else if(sodElement instanceof NetworkSubsetter) {
attrSubsetter = (NetworkSubsetter)sodElement;
} else if(sodElement instanceof StationSubsetter) {
stationSubsetter = (StationSubsetter)sodElement;
} else if(sodElement instanceof ChannelSubsetter) {
chanSubsetters.add(sodElement);
} else {
throw new ConfigurationException("Unknown configuration object: "
+ sodElement);
}
}
public void add(NetworkMonitor monitor) {
synchronized(statusMonitors) {
statusMonitors.add(monitor);
}
}
public ProxyNetworkDC getNetworkDC() {
return finder.getNetworkDC();
}
public TimeInterval getRefreshInterval() {
return finder.getRefreshInterval();
}
/**
* returns an array of SuccessfulNetworks. if the refreshInterval is valid
* it gets the networks from the database(may be embedded or external). if
* not it gets the networks again from the network server specified in the
* networkFinder. After obtaining the Networks if processes them using the
* NetworkSubsetter and returns the successful networks as an array of
* NetworkDbObjects.
*
* @throws NetworkNotFound
*/
public CacheNetworkAccess[] getSuccessfulNetworks() throws NetworkNotFound {
synchronized(netGetSync) {
SodDB sodDb = SodDB.getSingleton();
if(lastQueryTime == null) {
// try from db
lastQueryTime = sodDb.getQueryTime(finder.getName(),
finder.getDNS());
}
if(lastQueryTime == null) {
// still null, must be first time
lastQueryTime = new QueryTime(finder.getName(),
finder.getDNS(),
ClockUtil.now().getTimestamp());
sodDb.putQueryTime(lastQueryTime);
} else if(!lastQueryTime.needsRefresh(finder.getRefreshInterval())) {
if(cacheNets == null) {
cacheNets = getNetworkDB().getAllNets(getNetworkDC());
for(int i = 0; i < cacheNets.length; i++) {
// this is for the side effect of creating
// networkInfoTemplate stuff
// avoids a null ptr later
change(cacheNets[i],
Status.get(Stage.NETWORK_SUBSETTER,
Standing.SUCCESS));
}
}
return cacheNets;
}
statusChanged("Getting networks");
logger.info("Getting networks");
ArrayList successes = new ArrayList();
CacheNetworkAccess[] allNets;
NetworkDCOperations netDC = finder.getNetworkDC();
synchronized(netDC) {
String[] constrainingCodes = getConstrainingNetworkCodes(attrSubsetter);
if(constrainingCodes.length > 0) {
edu.iris.Fissures.IfNetwork.NetworkFinder netFinder = netDC.a_finder();
List<CacheNetworkAccess> constrainedNets = new ArrayList<CacheNetworkAccess>(constrainingCodes.length);
for(int i = 0; i < constrainingCodes.length; i++) {
CacheNetworkAccess[] found;
// this is a bit of a hack as names could be one or two
// characters, but works with _US-TA style
// virtual networks at the DMC
if(constrainingCodes[i].length() > 2) {
found = (CacheNetworkAccess[])netFinder.retrieve_by_name(constrainingCodes[i]);
} else {
found = (CacheNetworkAccess[])netFinder.retrieve_by_code(constrainingCodes[i]);
}
for(int j = 0; j < found.length; j++) {
constrainedNets.add(found[j]);
}
}
allNets = (CacheNetworkAccess[])constrainedNets.toArray(new CacheNetworkAccess[0]);
} else {
NetworkAccess[] tmpNets = netDC.a_finder().retrieve_all();
ArrayList goodNets = new ArrayList();
for(int i = 0; i < tmpNets.length; i++) {
try {
VirtualNetworkHelper.narrow(tmpNets[i]);
// Ignore any virtual nets returned here
logger.debug("ignoring virtual network "
+ tmpNets[i].get_attributes().get_code());
continue;
} catch(BAD_PARAM bp) {
// Must be a concrete, keep it
goodNets.add(tmpNets[i]);
}
}
allNets = (CacheNetworkAccess[])goodNets.toArray(new CacheNetworkAccess[0]);
}
}
logger.info("Found " + allNets.length + " networks");
NetworkPusher lastPusher = null;
for(int i = 0; i < allNets.length; i++) {
allNets[i] = new DBCacheNetworkAccess(allNets[i]);
+ NetworkAttrImpl attr = null;
try {
- NetworkAttrImpl attr = (NetworkAttrImpl)allNets[i].get_attributes();
+ attr = (NetworkAttrImpl)allNets[i].get_attributes();
if(netEffectiveSubsetter.accept(attr).isSuccess()) {
if(attrSubsetter.accept(attr).isSuccess()) {
NetworkDB ndb = getNetworkDB();
int dbid = ndb.put(attr);
NetworkDB.commit();
logger.info("store network: " + attr.getDbid()
+ " " + dbid);
successes.add(allNets[i]);
change(allNets[i],
Status.get(Stage.NETWORK_SUBSETTER,
Standing.SUCCESS));
if(Start.getWaveformArm() == null
&& (! stationSubsetter.getClass().equals(PassStation.class)
|| chanSubsetters.size() != 0 )) {
// only do netpushers if there are more subsetters downstream
// and the waveform arm does not exist, otherwise there is no point
// or we can let the waveform processors handle via EventNetworkPair
if (lastPusher == null) {
lastPusher = new NetworkPusher(allNets[i].get_attributes());
netPopulators.invokeLater(lastPusher);
} else {
lastPusher.addNetwork(allNets[i].get_attributes());
}
logger.debug("running network");
//lastPusher.runNetwork(allNets[i].get_attributes());
}
} else {
change(allNets[i],
Status.get(Stage.NETWORK_SUBSETTER,
Standing.REJECT));
failLogger.info(NetworkIdUtil.toString(allNets[i].get_attributes()
.get_id())
+ " was rejected.");
}
} else {
change(allNets[i], Status.get(Stage.NETWORK_SUBSETTER,
Standing.REJECT));
failLogger.info(NetworkIdUtil.toString(allNets[i].get_attributes()
.get_id())
+ " was rejected because it wasn't active during the time range of requested events");
}
} catch(Throwable th) {
GlobalExceptionHandler.handle("Got an exception while trying getSuccessfulNetworks for the "
+ i
- + "th networkAccess",
+ + "th networkAccess ("
+ +(attr==null?"null":NetworkIdUtil.toStringNoDates(((NetworkAttrImpl)allNets[i].get_attributes()))),
th);
}
}
if(lastPusher != null) {
lastPusher.setLastPusher();
} else {
// no pushers
if(allNets.length == 0) {
logger.warn("Found no networks. Make sure the network codes you entered are valid");
}
finish();
}
// Set the time of the last check to now
lastQueryTime.setTime(ClockUtil.now().getTimestamp());
cacheNets = new CacheNetworkAccess[successes.size()];
successes.toArray(cacheNets);
logger.info(cacheNets.length + " networks passed");
statusChanged("Waiting for a request");
return cacheNets;
}
}
/**
* Given a network subsetter, return a string array consisting of all the
* network codes this subsetter accepts. If it doesn't constrain network
* codes, an empty array is returned.
*/
public static String[] getConstrainingNetworkCodes(NetworkSubsetter ns) {
if(ns == null) {
return new String[0];
} else if(ns instanceof NetworkOR) {
NetworkSubsetter[] kids = ((NetworkOR)ns).getSubsetters();
String[] codes = new String[kids.length];
for(int i = 0; i < kids.length; i++) {
if(kids[i] instanceof NetworkCode) {
codes[i] = ((NetworkCode)kids[i]).getCode();
} else {
return new String[0];
}
}
return codes;
} else if(ns instanceof NetworkCode) {
return new String[] {((NetworkCode)ns).getCode()};
} else {
return new String[0];
}
}
/**
* retrieves all the stations, sites and channels for a network to populate
* the db and cache
*/
private class NetworkPusher implements Runnable {
public NetworkPusher(NetworkAttrImpl net) {
netList.add(net);
}
public void run() {
logger.debug("Start NetworkPusher");
NetworkAttrImpl n = netList.poll();
while ( ! lastPusher || n != null) {
if (n != null) {
runNetwork(n);
} else {
try {
Thread.sleep(100);
} catch(InterruptedException e) {}
}
n = netList.poll();
}
logger.debug("Finish NetworkPusher");
synchronized(this) {
pusherFinished = true;
finishArm();
}
}
void addNetwork(NetworkAttrImpl net) {
logger.debug("Add to NetworkPusher "+net.get_code());
netList.offer(net);
}
protected void runNetwork(NetworkAttrImpl net) {
if(!Start.isArmFailure()) {
logger.info("NetworkPusher Starting work on " + net.get_code());
// new thread, so need to attach net attr instance
NetworkDB ndb = getNetworkDB();
try {
NetworkDB.getSession().lock(net,
LockMode.NONE);
} catch(NonUniqueObjectException e) {
logger.error("Try to lock net="
+ NetworkIdUtil.toString(net)
+ " dbid="
+ ((NetworkAttrImpl)net).getDbid(),
e);
throw e;
}
StationImpl[] staDbs = getSuccessfulStations(net);
if(!(Start.getWaveformArm() == null && chanSubsetters.size() == 0)) {
// only get channels if there are subsetters or a
// waveform arm
for(int j = 0; j < staDbs.length; j++) {
// commit for each station
synchronized(NetworkArm.this) {
NetworkDB.getSession().lock(net,
LockMode.NONE);
List<ChannelImpl> chans = getSuccessfulChannels(staDbs[j]);
}
}
} else {
logger.info("Not getting channels as no subsetters or waveform arm");
}
// make sure everything is cleaned up in hibernate session
NetworkDB.commit();
}
}
private void finishArm() {
if(lastPusher && pusherFinished) {
finish();
}
}
public synchronized void setLastPusher() {
lastPusher = true;
finishArm();
}
private boolean lastPusher = false, pusherFinished = false;
private Queue<NetworkAttrImpl> netList = new LinkedList<NetworkAttrImpl>();
}
private void finish() {
armFinished = true;
logger.info("Network arm finished.");
for(Iterator iter = armListeners.iterator(); iter.hasNext();) {
ArmListener listener = (ArmListener)iter.next();
listener.finished(this);
}
}
public void add(ArmListener listener) {
armListeners.add(listener);
if(armFinished == true) {
listener.finished(this);
}
}
/**
* @return stations for the given network object that pass this arm's
* station subsetter
*/
public StationImpl[] getSuccessfulStations(CacheNetworkAccess net) {
return getSuccessfulStations(net.get_attributes());
}
public StationImpl[] getSuccessfulStations(NetworkAttrImpl net) {
String netCode = net.get_code();
logger.debug("getSuccessfulStations");
if(allStationFailureNets.contains(NetworkIdUtil.toStringNoDates(net))) {
return new StationImpl[0];
}
synchronized(this) {
// try db
List<StationImpl> sta = getNetworkDB().getStationForNet((NetworkAttrImpl)net);
if(sta.size() != 0) {
logger.debug("getSuccessfulStations " + netCode + " - from db "
+ sta.size());
return sta.toArray(new StationImpl[0]);
}
// really no dice, go to server
statusChanged("Getting stations for "
+ net.getName());
ArrayList<Station> arrayList = new ArrayList<Station>();
try {
CacheNetworkAccess netAccess = CacheNetworkAccess.create((NetworkAttrImpl)net,
CommonAccess.getNameService());
Station[] stations = netAccess.retrieve_stations();
for(int i = 0; i < stations.length; i++) {
logger.debug("Station in NetworkArm: "
+ StationIdUtil.toString(stations[i]));
}
for(int i = 0; i < stations.length; i++) {
// hibernate gets angry if the network isn't the same object
// as the one already in the thread's session
stations[i].setNetworkAttr(net);
StringTree effResult = staEffectiveSubsetter.accept(stations[i],
netAccess);
if(effResult.isSuccess()) {
StringTree staResult = stationSubsetter.accept(stations[i],
netAccess);
if(staResult.isSuccess()) {
int dbid = getNetworkDB().put((StationImpl)stations[i]);
logger.info("Store " + stations[i].get_code()
+ " as " + dbid + " in " + getNetworkDB());
arrayList.add(stations[i]);
change(stations[i],
Status.get(Stage.NETWORK_SUBSETTER,
Standing.SUCCESS));
} else {
change(stations[i],
Status.get(Stage.NETWORK_SUBSETTER,
Standing.REJECT));
failLogger.info(StationIdUtil.toString(stations[i].get_id())
+ " was rejected: " + staResult);
}
} else {
change(stations[i], Status.get(Stage.NETWORK_SUBSETTER,
Standing.REJECT));
failLogger.info(StationIdUtil.toString(stations[i].get_id())
+ " was rejected based on its effective time not matching the range of requested events: "
+ effResult);
}
}
NetworkDB.commit();
} catch(Exception e) {
GlobalExceptionHandler.handle("Problem in method getSuccessfulStations for net "
+ NetworkIdUtil.toString(net.get_id()),
e);
}
StationImpl[] rtnValues = new StationImpl[arrayList.size()];
rtnValues = (StationImpl[])arrayList.toArray(rtnValues);
statusChanged("Waiting for a request");
logger.debug("getSuccessfulStations " + netCode + " - from server "
+ rtnValues.length);
if(rtnValues.length == 0) {
allStationFailureNets.add(NetworkIdUtil.toStringNoDates(net));
}
return rtnValues;
}
}
/**
* Obtains the Channels corresponding to the station, processes them using
* the ChannelSubsetter and returns an array of those that pass
*
* @throws NetworkNotFound
*/
public List<ChannelImpl> getSuccessfulChannels(StationImpl station) {
if(allChannelFailureStations.contains(StationIdUtil.toStringNoDates(station))) {
return new ArrayList<ChannelImpl>(0);
}
synchronized(this) {
// no dice, try db
List<ChannelImpl> sta = getNetworkDB().getChannelsForStation(station);
if(sta.size() != 0) {
logger.debug("successfulChannels " + station.get_code()
+ " - from db " + sta.size());
return sta;
}
// really no dice, go to server
statusChanged("Getting channels for " + station);
List<ChannelImpl> successes = new ArrayList<ChannelImpl>();
try {
CacheNetworkAccess networkAccess = CacheNetworkAccess.create((NetworkAttrImpl)station.getNetworkAttr(),
CommonAccess.getNameService());
Channel[] tmpChannels = networkAccess.retrieve_for_station(station.get_id());
MicroSecondDate stationBegin = new MicroSecondDate(station.getBeginTime());
// dmc network server ignores date in station id in
// retrieve_for_station, so all channels for station code are
// returned. This checks to make sure the station is the same.
// ProxyNetworkAccess already interns stations in channels
// so as long as station begin times are the same, they are
// equal...we hope
ArrayList<ChannelImpl> chansAtStation = new ArrayList<ChannelImpl>();
for(int i = 0; i < tmpChannels.length; i++) {
if(new MicroSecondDate(tmpChannels[i].getSite().getStation().getBeginTime()).equals(stationBegin)) {
chansAtStation.add((ChannelImpl)tmpChannels[i]);
} else {
logger.info("Channel "
+ ChannelIdUtil.toString(tmpChannels[i].get_id())
+ " has a station that is not the same as the requested station: req="
+ StationIdUtil.toString(station.get_id())
+ " chan sta="
+ StationIdUtil.toString(tmpChannels[i].getSite()
.getStation())+" "+tmpChannels[i].getSite().getStation().getBeginTime().date_time+" != "+station.getBeginTime().date_time);
}
}
ChannelImpl[] channels = (ChannelImpl[])chansAtStation.toArray(new ChannelImpl[0]);
Status inProg = Status.get(Stage.NETWORK_SUBSETTER,
Standing.IN_PROG);
boolean needCommit = false;
for(int i = 0; i < channels.length; i++) {
ChannelImpl chan = channels[i];
change(chan, inProg);
StringTree effectiveTimeResult = chanEffectiveSubsetter.accept(chan,
networkAccess);
if(effectiveTimeResult.isSuccess()) {
boolean accepted = true;
synchronized(chanSubsetters) {
Iterator it = chanSubsetters.iterator();
while(it.hasNext()) {
ChannelSubsetter cur = (ChannelSubsetter)it.next();
StringTree result = cur.accept(chan,
networkAccess);
if(!result.isSuccess()) {
change(chan,
Status.get(Stage.NETWORK_SUBSETTER,
Standing.REJECT));
failLogger.info("Rejected "
+ ChannelIdUtil.toString(chan.get_id())
+ ": " + result);
accepted = false;
break;
}
}
}
if(accepted) {
Integer dbidInt = new Integer(getNetworkDB().put(chan));
needCommit = true;
channelMap.put(dbidInt, chan);
channelToSiteMap.put(dbidInt, station);
successes.add(chan);
change(chan, Status.get(Stage.NETWORK_SUBSETTER,
Standing.SUCCESS));
}
} else {
change(chan, Status.get(Stage.NETWORK_SUBSETTER,
Standing.REJECT));
failLogger.info("Reject based on effective time not matching the range of requested events: "
+ ChannelIdUtil.toString(chan.get_id())
+ effectiveTimeResult);
}
}
if(needCommit) {
NetworkDB.commit();
}
} catch(Throwable e) {
GlobalExceptionHandler.handle("Problem in method getSuccessfulChannels for "
+ StationIdUtil.toString(station.get_id()),
e);
NetworkDB.rollback();
}
statusChanged("Waiting for a request");
if(successes.size() == 0) {
allChannelFailureStations.add(StationIdUtil.toStringNoDates(station));
}
return successes;
}
}
public List<ChannelGroup> getSuccessfulChannelGroups(StationImpl station) {
if(allChannelFailureStations.contains(StationIdUtil.toStringNoDates(station))) {
return new ArrayList<ChannelGroup>(0);
}
synchronized(this) {
// no dice, try db
List<ChannelGroup> sta = getNetworkDB().getChannelGroupsForStation(station);
if(sta.size() != 0) {
logger.debug("successfulChannelGroups " + station.get_code()
+ " - from db " + sta.size());
return sta;
}
// really no dice, go to server
List<ChannelImpl> failures = new ArrayList<ChannelImpl>();
List<ChannelGroup> chanGroups = channelGrouper.group(getSuccessfulChannels(station),
failures);
for(ChannelGroup cg : chanGroups) {
getNetworkDB().put(cg);
}
if (chanGroups.size() != 0) {
getNetworkDB().commit();
}
Iterator it = failures.iterator();
Status chanReject = Status.get(Stage.NETWORK_SUBSETTER,
Standing.REJECT);
while(it.hasNext()) {
Channel failchan = (Channel)it.next();
failLogger.info(ChannelIdUtil.toString(failchan.get_id())
+ " Channel not grouped.");
}
return chanGroups;
}
}
// This is a HACK. Since we're already storing the channels whole hog, it
// isn't much of a stretch to cache them by dbid, and this allows
// JDBCEventChannelStatus to quickly pull them out instead of going to the
// Net database
public Channel getChannel(int chanId) throws NotFound, SQLException {
ChannelImpl chan = (ChannelImpl)channelMap.get(new Integer(chanId));
if(chan != null) {
return chan;
}
chan = getNetworkDB().getChannel(chanId);
channelMap.put(new Integer(chanId), chan);
return chan;
}
private QueryTime lastQueryTime = null;
private Map channelMap = Collections.synchronizedMap(new HashMap());
private Map channelToSiteMap = Collections.synchronizedMap(new HashMap());
private void statusChanged(String newStatus) {
synchronized(statusMonitors) {
Iterator it = statusMonitors.iterator();
while(it.hasNext()) {
try {
((NetworkMonitor)it.next()).setArmStatus(newStatus);
} catch(Throwable e) {
// caught for one, but should continue with rest after
// logging
// it
GlobalExceptionHandler.handle("Problem changing status in NetworkArm",
e);
}
}
}
}
private void change(Channel chan, Status newStatus) {
synchronized(statusMonitors) {
Iterator it = statusMonitors.iterator();
while(it.hasNext()) {
try {
((NetworkMonitor)it.next()).change(chan, newStatus);
} catch(Throwable e) {
// caught for one, but should continue with rest after
// logging
// it
GlobalExceptionHandler.handle("Problem changing channel status in NetworkArm",
e);
}
}
}
}
private void change(Station sta, Status newStatus) {
synchronized(statusMonitors) {
Iterator it = statusMonitors.iterator();
while(it.hasNext()) {
try {
((NetworkMonitor)it.next()).change(sta, newStatus);
} catch(Throwable e) {
// caught for one, but should continue with rest after
// logging
// it
GlobalExceptionHandler.handle("Problem changing station status in NetworkArm",
e);
}
}
}
}
private void change(NetworkAccess na, Status newStatus) {
synchronized(statusMonitors) {
Iterator it = statusMonitors.iterator();
while(it.hasNext()) {
try {
((NetworkMonitor)it.next()).change(na, newStatus);
} catch(Throwable e) {
// caught for one, but should continue with rest after
// logging
// it
GlobalExceptionHandler.handle("Problem changing network status in NetworkArm",
e);
}
}
}
}
// Since we synchronize around the NetDC, only 1 thread can get stuff from
// the network server at the same time. The pool is here in the off chance
// the IRIS Network Server is fixed and we can run multiple threads to fill
// up the db. If so, remove SynchronizedNetworkAccess from
// BulletproofVestFactory, increase the number of threads here, and chuckle
// as the stations stream in.
private WorkerThreadPool netPopulators = new WorkerThreadPool("NetPopulator",
1);
private NetworkFinder finder = null;
private NetworkSubsetter attrSubsetter = new PassNetwork();
private NetworkSubsetter netEffectiveSubsetter = new PassNetwork();
private StationSubsetter stationSubsetter = new PassStation();
private StationSubsetter staEffectiveSubsetter = new PassStation();
private List chanSubsetters = new ArrayList();
private ChannelSubsetter chanEffectiveSubsetter = new PassChannel();
private ChannelGrouper channelGrouper = new ChannelGrouper();
protected NetworkDB getNetworkDB() {
return NetworkDB.getSingleton();
}
private CacheNetworkAccess[] cacheNets;
private HashSet<String> allStationFailureNets = new HashSet<String>();
private HashSet<String> allChannelFailureStations = new HashSet<String>();
private List statusMonitors = new ArrayList();
private List armListeners = new ArrayList();
private static Logger logger = Logger.getLogger(NetworkArm.class);
private static final org.apache.log4j.Logger failLogger = org.apache.log4j.Logger.getLogger("Fail.NetworkArm");
private boolean armFinished = false;
private final Object netGetSync = new Object();
private final Object staGetSync = new Object();
private final Object chanGetSync = new Object();
}// NetworkArm
| false | true | public CacheNetworkAccess[] getSuccessfulNetworks() throws NetworkNotFound {
synchronized(netGetSync) {
SodDB sodDb = SodDB.getSingleton();
if(lastQueryTime == null) {
// try from db
lastQueryTime = sodDb.getQueryTime(finder.getName(),
finder.getDNS());
}
if(lastQueryTime == null) {
// still null, must be first time
lastQueryTime = new QueryTime(finder.getName(),
finder.getDNS(),
ClockUtil.now().getTimestamp());
sodDb.putQueryTime(lastQueryTime);
} else if(!lastQueryTime.needsRefresh(finder.getRefreshInterval())) {
if(cacheNets == null) {
cacheNets = getNetworkDB().getAllNets(getNetworkDC());
for(int i = 0; i < cacheNets.length; i++) {
// this is for the side effect of creating
// networkInfoTemplate stuff
// avoids a null ptr later
change(cacheNets[i],
Status.get(Stage.NETWORK_SUBSETTER,
Standing.SUCCESS));
}
}
return cacheNets;
}
statusChanged("Getting networks");
logger.info("Getting networks");
ArrayList successes = new ArrayList();
CacheNetworkAccess[] allNets;
NetworkDCOperations netDC = finder.getNetworkDC();
synchronized(netDC) {
String[] constrainingCodes = getConstrainingNetworkCodes(attrSubsetter);
if(constrainingCodes.length > 0) {
edu.iris.Fissures.IfNetwork.NetworkFinder netFinder = netDC.a_finder();
List<CacheNetworkAccess> constrainedNets = new ArrayList<CacheNetworkAccess>(constrainingCodes.length);
for(int i = 0; i < constrainingCodes.length; i++) {
CacheNetworkAccess[] found;
// this is a bit of a hack as names could be one or two
// characters, but works with _US-TA style
// virtual networks at the DMC
if(constrainingCodes[i].length() > 2) {
found = (CacheNetworkAccess[])netFinder.retrieve_by_name(constrainingCodes[i]);
} else {
found = (CacheNetworkAccess[])netFinder.retrieve_by_code(constrainingCodes[i]);
}
for(int j = 0; j < found.length; j++) {
constrainedNets.add(found[j]);
}
}
allNets = (CacheNetworkAccess[])constrainedNets.toArray(new CacheNetworkAccess[0]);
} else {
NetworkAccess[] tmpNets = netDC.a_finder().retrieve_all();
ArrayList goodNets = new ArrayList();
for(int i = 0; i < tmpNets.length; i++) {
try {
VirtualNetworkHelper.narrow(tmpNets[i]);
// Ignore any virtual nets returned here
logger.debug("ignoring virtual network "
+ tmpNets[i].get_attributes().get_code());
continue;
} catch(BAD_PARAM bp) {
// Must be a concrete, keep it
goodNets.add(tmpNets[i]);
}
}
allNets = (CacheNetworkAccess[])goodNets.toArray(new CacheNetworkAccess[0]);
}
}
logger.info("Found " + allNets.length + " networks");
NetworkPusher lastPusher = null;
for(int i = 0; i < allNets.length; i++) {
allNets[i] = new DBCacheNetworkAccess(allNets[i]);
try {
NetworkAttrImpl attr = (NetworkAttrImpl)allNets[i].get_attributes();
if(netEffectiveSubsetter.accept(attr).isSuccess()) {
if(attrSubsetter.accept(attr).isSuccess()) {
NetworkDB ndb = getNetworkDB();
int dbid = ndb.put(attr);
NetworkDB.commit();
logger.info("store network: " + attr.getDbid()
+ " " + dbid);
successes.add(allNets[i]);
change(allNets[i],
Status.get(Stage.NETWORK_SUBSETTER,
Standing.SUCCESS));
if(Start.getWaveformArm() == null
&& (! stationSubsetter.getClass().equals(PassStation.class)
|| chanSubsetters.size() != 0 )) {
// only do netpushers if there are more subsetters downstream
// and the waveform arm does not exist, otherwise there is no point
// or we can let the waveform processors handle via EventNetworkPair
if (lastPusher == null) {
lastPusher = new NetworkPusher(allNets[i].get_attributes());
netPopulators.invokeLater(lastPusher);
} else {
lastPusher.addNetwork(allNets[i].get_attributes());
}
logger.debug("running network");
//lastPusher.runNetwork(allNets[i].get_attributes());
}
} else {
change(allNets[i],
Status.get(Stage.NETWORK_SUBSETTER,
Standing.REJECT));
failLogger.info(NetworkIdUtil.toString(allNets[i].get_attributes()
.get_id())
+ " was rejected.");
}
} else {
change(allNets[i], Status.get(Stage.NETWORK_SUBSETTER,
Standing.REJECT));
failLogger.info(NetworkIdUtil.toString(allNets[i].get_attributes()
.get_id())
+ " was rejected because it wasn't active during the time range of requested events");
}
} catch(Throwable th) {
GlobalExceptionHandler.handle("Got an exception while trying getSuccessfulNetworks for the "
+ i
+ "th networkAccess",
th);
}
}
if(lastPusher != null) {
lastPusher.setLastPusher();
} else {
// no pushers
if(allNets.length == 0) {
logger.warn("Found no networks. Make sure the network codes you entered are valid");
}
finish();
}
// Set the time of the last check to now
lastQueryTime.setTime(ClockUtil.now().getTimestamp());
cacheNets = new CacheNetworkAccess[successes.size()];
successes.toArray(cacheNets);
logger.info(cacheNets.length + " networks passed");
statusChanged("Waiting for a request");
return cacheNets;
}
}
| public CacheNetworkAccess[] getSuccessfulNetworks() throws NetworkNotFound {
synchronized(netGetSync) {
SodDB sodDb = SodDB.getSingleton();
if(lastQueryTime == null) {
// try from db
lastQueryTime = sodDb.getQueryTime(finder.getName(),
finder.getDNS());
}
if(lastQueryTime == null) {
// still null, must be first time
lastQueryTime = new QueryTime(finder.getName(),
finder.getDNS(),
ClockUtil.now().getTimestamp());
sodDb.putQueryTime(lastQueryTime);
} else if(!lastQueryTime.needsRefresh(finder.getRefreshInterval())) {
if(cacheNets == null) {
cacheNets = getNetworkDB().getAllNets(getNetworkDC());
for(int i = 0; i < cacheNets.length; i++) {
// this is for the side effect of creating
// networkInfoTemplate stuff
// avoids a null ptr later
change(cacheNets[i],
Status.get(Stage.NETWORK_SUBSETTER,
Standing.SUCCESS));
}
}
return cacheNets;
}
statusChanged("Getting networks");
logger.info("Getting networks");
ArrayList successes = new ArrayList();
CacheNetworkAccess[] allNets;
NetworkDCOperations netDC = finder.getNetworkDC();
synchronized(netDC) {
String[] constrainingCodes = getConstrainingNetworkCodes(attrSubsetter);
if(constrainingCodes.length > 0) {
edu.iris.Fissures.IfNetwork.NetworkFinder netFinder = netDC.a_finder();
List<CacheNetworkAccess> constrainedNets = new ArrayList<CacheNetworkAccess>(constrainingCodes.length);
for(int i = 0; i < constrainingCodes.length; i++) {
CacheNetworkAccess[] found;
// this is a bit of a hack as names could be one or two
// characters, but works with _US-TA style
// virtual networks at the DMC
if(constrainingCodes[i].length() > 2) {
found = (CacheNetworkAccess[])netFinder.retrieve_by_name(constrainingCodes[i]);
} else {
found = (CacheNetworkAccess[])netFinder.retrieve_by_code(constrainingCodes[i]);
}
for(int j = 0; j < found.length; j++) {
constrainedNets.add(found[j]);
}
}
allNets = (CacheNetworkAccess[])constrainedNets.toArray(new CacheNetworkAccess[0]);
} else {
NetworkAccess[] tmpNets = netDC.a_finder().retrieve_all();
ArrayList goodNets = new ArrayList();
for(int i = 0; i < tmpNets.length; i++) {
try {
VirtualNetworkHelper.narrow(tmpNets[i]);
// Ignore any virtual nets returned here
logger.debug("ignoring virtual network "
+ tmpNets[i].get_attributes().get_code());
continue;
} catch(BAD_PARAM bp) {
// Must be a concrete, keep it
goodNets.add(tmpNets[i]);
}
}
allNets = (CacheNetworkAccess[])goodNets.toArray(new CacheNetworkAccess[0]);
}
}
logger.info("Found " + allNets.length + " networks");
NetworkPusher lastPusher = null;
for(int i = 0; i < allNets.length; i++) {
allNets[i] = new DBCacheNetworkAccess(allNets[i]);
NetworkAttrImpl attr = null;
try {
attr = (NetworkAttrImpl)allNets[i].get_attributes();
if(netEffectiveSubsetter.accept(attr).isSuccess()) {
if(attrSubsetter.accept(attr).isSuccess()) {
NetworkDB ndb = getNetworkDB();
int dbid = ndb.put(attr);
NetworkDB.commit();
logger.info("store network: " + attr.getDbid()
+ " " + dbid);
successes.add(allNets[i]);
change(allNets[i],
Status.get(Stage.NETWORK_SUBSETTER,
Standing.SUCCESS));
if(Start.getWaveformArm() == null
&& (! stationSubsetter.getClass().equals(PassStation.class)
|| chanSubsetters.size() != 0 )) {
// only do netpushers if there are more subsetters downstream
// and the waveform arm does not exist, otherwise there is no point
// or we can let the waveform processors handle via EventNetworkPair
if (lastPusher == null) {
lastPusher = new NetworkPusher(allNets[i].get_attributes());
netPopulators.invokeLater(lastPusher);
} else {
lastPusher.addNetwork(allNets[i].get_attributes());
}
logger.debug("running network");
//lastPusher.runNetwork(allNets[i].get_attributes());
}
} else {
change(allNets[i],
Status.get(Stage.NETWORK_SUBSETTER,
Standing.REJECT));
failLogger.info(NetworkIdUtil.toString(allNets[i].get_attributes()
.get_id())
+ " was rejected.");
}
} else {
change(allNets[i], Status.get(Stage.NETWORK_SUBSETTER,
Standing.REJECT));
failLogger.info(NetworkIdUtil.toString(allNets[i].get_attributes()
.get_id())
+ " was rejected because it wasn't active during the time range of requested events");
}
} catch(Throwable th) {
GlobalExceptionHandler.handle("Got an exception while trying getSuccessfulNetworks for the "
+ i
+ "th networkAccess ("
+(attr==null?"null":NetworkIdUtil.toStringNoDates(((NetworkAttrImpl)allNets[i].get_attributes()))),
th);
}
}
if(lastPusher != null) {
lastPusher.setLastPusher();
} else {
// no pushers
if(allNets.length == 0) {
logger.warn("Found no networks. Make sure the network codes you entered are valid");
}
finish();
}
// Set the time of the last check to now
lastQueryTime.setTime(ClockUtil.now().getTimestamp());
cacheNets = new CacheNetworkAccess[successes.size()];
successes.toArray(cacheNets);
logger.info(cacheNets.length + " networks passed");
statusChanged("Waiting for a request");
return cacheNets;
}
}
|
diff --git a/src/main/java/org/cchmc/bmi/snpomics/OutputField.java b/src/main/java/org/cchmc/bmi/snpomics/OutputField.java
index ce879a4..059802a 100644
--- a/src/main/java/org/cchmc/bmi/snpomics/OutputField.java
+++ b/src/main/java/org/cchmc/bmi/snpomics/OutputField.java
@@ -1,57 +1,58 @@
package org.cchmc.bmi.snpomics;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;
import org.cchmc.bmi.snpomics.annotation.interactive.InteractiveAnnotation;
import org.cchmc.bmi.snpomics.annotation.interactive.MetaAnnotation;
import org.cchmc.bmi.snpomics.annotation.reference.ReferenceAnnotation;
import org.cchmc.bmi.snpomics.exception.SnpomicsException;
public class OutputField {
public OutputField(Method source) {
method = source;
annotation = method.getAnnotation(MetaAnnotation.class);
- throw new SnpomicsException("Method '"+method.getClass().getCanonicalName()+"."+method.getName()+
- "' is an OutputField with no MetaAnnotation");
+ if (annotation == null)
+ throw new SnpomicsException("Method '"+method.getDeclaringClass().getCanonicalName()+"."+method.getName()+
+ "' is an OutputField with no MetaAnnotation");
}
public String getName() {
return annotation.name();
}
public String getDescription() {
return annotation.description();
}
public List<String> getGroups() {
return Arrays.asList(annotation.groups());
}
public List<Class<? extends ReferenceAnnotation>> getReferences() {
return Arrays.asList(annotation.ref());
}
@SuppressWarnings("unchecked")
public Class<? extends InteractiveAnnotation> getDeclaringClass() {
return (Class<? extends InteractiveAnnotation>) method.getDeclaringClass();
}
public String getOutput(InteractiveAnnotation annot) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {
return method.invoke(annot).toString();
}
public String getInternalName() {
return method.getName();
}
public static boolean isOutputField(Method toCheck) {
return toCheck.isAnnotationPresent(MetaAnnotation.class);
}
private Method method;
private MetaAnnotation annotation;
}
| true | true | public OutputField(Method source) {
method = source;
annotation = method.getAnnotation(MetaAnnotation.class);
throw new SnpomicsException("Method '"+method.getClass().getCanonicalName()+"."+method.getName()+
"' is an OutputField with no MetaAnnotation");
}
| public OutputField(Method source) {
method = source;
annotation = method.getAnnotation(MetaAnnotation.class);
if (annotation == null)
throw new SnpomicsException("Method '"+method.getDeclaringClass().getCanonicalName()+"."+method.getName()+
"' is an OutputField with no MetaAnnotation");
}
|
diff --git a/Ingest/src/org/sleuthkit/autopsy/ingest/IngestMessageMainPanel.java b/Ingest/src/org/sleuthkit/autopsy/ingest/IngestMessageMainPanel.java
index 8b757d406..88a34a498 100644
--- a/Ingest/src/org/sleuthkit/autopsy/ingest/IngestMessageMainPanel.java
+++ b/Ingest/src/org/sleuthkit/autopsy/ingest/IngestMessageMainPanel.java
@@ -1,133 +1,135 @@
/*
* Autopsy Forensic Browser
*
* Copyright 2011 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.ingest;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.BoxLayout;
import javax.swing.JLayeredPane;
/**
* the main layered pane container for messages table (IngestMessagePanel)
* and details view (IngestMessageDetailsPanel)
*/
public class IngestMessageMainPanel extends JLayeredPane {
private IngestMessagePanel messagePanel;
private IngestMessageDetailsPanel detailsPanel;
private Logger logger = Logger.getLogger(IngestMessageMainPanel.class.getName());
//private JLayeredPane layeredPane;
/** Creates new form IngestMessageMainPanel */
public IngestMessageMainPanel() {
initComponents();
customizeComponents();
}
private void customizeComponents() {
messagePanel = new IngestMessagePanel(this);
detailsPanel = new IngestMessageDetailsPanel(this);
//we need to handle resizing ourselves due to absence of layout manager
//in layered layout
this.addComponentListener(new ComponentListener() {
@Override
public void componentHidden(ComponentEvent e) {
}
@Override
public void componentMoved(ComponentEvent e) {
}
@Override
public void componentShown(ComponentEvent e) {
}
@Override
public void componentResized(ComponentEvent e) {
//we need to handle resizing ourselves due to absence of layout manager
//in layered layout
Dimension dim = getSize();
messagePanel.setPreferredSize(dim);
detailsPanel.setPreferredSize(dim);
messagePanel.setBounds(0, 0, dim.width, dim.height);
detailsPanel.setBounds(0, 0, dim.width, dim.height);
revalidate();
}
});
+ messagePanel.setOpaque(true);
+ detailsPanel.setOpaque(true);
add(messagePanel, JLayeredPane.PALETTE_LAYER);
add(detailsPanel, JLayeredPane.DEFAULT_LAYER);
this.setOpaque(true);
}
IngestMessagePanel getMessagePanel() {
return messagePanel;
}
IngestMessageDetailsPanel getDetailsPanel() {
return detailsPanel;
}
void showMessages() {
setLayer(detailsPanel, JLayeredPane.DEFAULT_LAYER);
setLayer(messagePanel, JLayeredPane.PALETTE_LAYER);
}
void showDetails(int rowNumber) {
detailsPanel.showDetails(rowNumber);
setLayer(detailsPanel, JLayeredPane.PALETTE_LAYER);
setLayer(messagePanel, JLayeredPane.DEFAULT_LAYER);
}
public void addMessage(IngestMessage ingestMessage) {
messagePanel.addMessage(ingestMessage);
}
public void clearMessages() {
messagePanel.clearMessages();
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGap(0, 454, Short.MAX_VALUE));
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGap(0, 309, Short.MAX_VALUE));
}// </editor-fold>
// Variables declaration - do not modify
// End of variables declaration
}
| true | true | private void customizeComponents() {
messagePanel = new IngestMessagePanel(this);
detailsPanel = new IngestMessageDetailsPanel(this);
//we need to handle resizing ourselves due to absence of layout manager
//in layered layout
this.addComponentListener(new ComponentListener() {
@Override
public void componentHidden(ComponentEvent e) {
}
@Override
public void componentMoved(ComponentEvent e) {
}
@Override
public void componentShown(ComponentEvent e) {
}
@Override
public void componentResized(ComponentEvent e) {
//we need to handle resizing ourselves due to absence of layout manager
//in layered layout
Dimension dim = getSize();
messagePanel.setPreferredSize(dim);
detailsPanel.setPreferredSize(dim);
messagePanel.setBounds(0, 0, dim.width, dim.height);
detailsPanel.setBounds(0, 0, dim.width, dim.height);
revalidate();
}
});
add(messagePanel, JLayeredPane.PALETTE_LAYER);
add(detailsPanel, JLayeredPane.DEFAULT_LAYER);
this.setOpaque(true);
}
| private void customizeComponents() {
messagePanel = new IngestMessagePanel(this);
detailsPanel = new IngestMessageDetailsPanel(this);
//we need to handle resizing ourselves due to absence of layout manager
//in layered layout
this.addComponentListener(new ComponentListener() {
@Override
public void componentHidden(ComponentEvent e) {
}
@Override
public void componentMoved(ComponentEvent e) {
}
@Override
public void componentShown(ComponentEvent e) {
}
@Override
public void componentResized(ComponentEvent e) {
//we need to handle resizing ourselves due to absence of layout manager
//in layered layout
Dimension dim = getSize();
messagePanel.setPreferredSize(dim);
detailsPanel.setPreferredSize(dim);
messagePanel.setBounds(0, 0, dim.width, dim.height);
detailsPanel.setBounds(0, 0, dim.width, dim.height);
revalidate();
}
});
messagePanel.setOpaque(true);
detailsPanel.setOpaque(true);
add(messagePanel, JLayeredPane.PALETTE_LAYER);
add(detailsPanel, JLayeredPane.DEFAULT_LAYER);
this.setOpaque(true);
}
|
diff --git a/sinciput/src/com/technosophos/sinciput/commands/admin/RemoveUser.java b/sinciput/src/com/technosophos/sinciput/commands/admin/RemoveUser.java
index 866c903..b946d87 100644
--- a/sinciput/src/com/technosophos/sinciput/commands/admin/RemoveUser.java
+++ b/sinciput/src/com/technosophos/sinciput/commands/admin/RemoveUser.java
@@ -1,171 +1,156 @@
package com.technosophos.sinciput.commands.admin;
import java.util.List;
import java.util.Map;
import com.technosophos.rhizome.command.AbstractCommand;
import com.technosophos.rhizome.controller.CommandResult;
import com.technosophos.rhizome.controller.ReRouteRequest;
import com.technosophos.sinciput.types.admin.UserEnum;
import com.technosophos.rhizome.repository.RepositoryAccessException;
import com.technosophos.rhizome.repository.RepositorySearcher;
import com.technosophos.rhizome.repository.DocumentRepository;
import com.technosophos.rhizome.repository.RhizomeInitializationException;
import com.technosophos.rhizome.document.Metadatum;
import static com.technosophos.sinciput.servlet.ServletConstants.SETTINGS_REPO;
public class RemoveUser extends AbstractCommand {
/**
* Remove a user.
* <p>There are two supposedly unique identifiers for a user. The Doc ID, which is truly
* unique, and the username, which ought to be unique within the repository. This
* will first check for a UID (aka doc ID), and if none is found, it will check for a username.</p>
* <p>Once it has found a UID or username, it will attempt to delete the record.</p>
* <p>If both a UUID and username are supplied, the command will only try to delete
* the UUID.</p>
*/
public void doCommand(Map<String, Object> params,
List<CommandResult> results) throws ReRouteRequest {
RepositorySearcher search = null;
try {
search = this.repoman.getSearcher(SETTINGS_REPO);
} catch (RhizomeInitializationException e) {
String errMsg = "RepositorySearcher could not be retrieved.";
String friendlyErrMsg = "This server has had a woeful tragedy attempting to answer your request. Please try again when I stop whimpering.";
results.add(this.createErrorCommandResult(errMsg, friendlyErrMsg, e));
return;
}
// CASE 1: We get a document ID to delete.
if(this.hasParam(params, "id")){
/*
* Get a document, verify it is right, and delete it.
*/
String docID = this.getParam(params, "id").toString();
try {
// #1: Make sure doc exists.
DocumentRepository repo = this.repoman.getRepository(SETTINGS_REPO);
if( repo.hasDocument(docID)) {
// #2 Make sure the document is the correct type.
Metadatum m = search.getMetadatumByDocID(UserEnum.TYPE.getKey(), docID);
- List<String> vals = m.getValues();
- if(vals == null) {
- String errMsg = String.format("DocID %s is not a user account: No type.", docID);
- String friendlyErrMsg = String.format("There is no user record with the ID %s. Nothing deleted.", docID);
- results.add(this.createErrorCommandResult(errMsg, friendlyErrMsg));
- return;
- }
- boolean isUserDoc = false;
- // #2b: loop through and see if any value matches the "user" def. value
- for(String v: vals) {
- if(UserEnum.TYPE.getFieldDescription().getDefaultValue().equalsIgnoreCase(v)) {
- isUserDoc = true;
- break;
- }
- }
- if(!isUserDoc) {
+ if(!m.hasValue(UserEnum.TYPE.getFieldDescription().getDefaultValue())) {
String errMsg = String.format("DocID %s is not a user account: Wrong type.", docID);
String friendlyErrMsg = String.format("There is no user record with the ID %s. Nothing deleted.", docID);
results.add(this.createErrorCommandResult(errMsg, friendlyErrMsg));
return;
}
// #3: Try to delete from index.
try {
this.repoman.getIndexer(SETTINGS_REPO).deleteFromIndex(docID);
} catch (RhizomeInitializationException e) {
String errMsg = String.format("Error deleting from indexer: %.", e.getMessage());
String friendlyErrMsg = String.format("The system could not access the record for %s. Nothing deleted.", docID);
results.add(this.createErrorCommandResult(errMsg, friendlyErrMsg, e));
return;
}
// #4: Remove record from repository.
repo.removeDocument(docID);
} else {
String errMsg = String.format("DocID %s not found.", docID);
String friendlyErrMsg = String.format("There is no user record with the ID %s. Nothing deleted.", docID);
results.add(this.createErrorCommandResult(errMsg, friendlyErrMsg));
return;
}
} catch (RhizomeInitializationException e) {
String errMsg = "DocumentRepository could not be created.";
String friendlyErrMsg = String.format("The system could not access the record for %s. Nothing deleted.", docID);
results.add(this.createErrorCommandResult(errMsg, friendlyErrMsg, e));
return;
} catch (RepositoryAccessException e) {
String errMsg = String.format("User %s could not be deleted from the document repository.", docID);
String friendlyErrMsg = String.format("The system could not remove the record for %s. Nothing deleted.", docID);
results.add(this.createErrorCommandResult(errMsg, friendlyErrMsg, e));
return;
}
results.add(this.createCommandResult(String.format("User %s removed.")));
return;
// CASE #2: Delete by user name
} else if(this.hasParam(params, UserEnum.USERNAME.getKey())) {
// Step #1: Get the user record with the given username
String username_field = UserEnum.USERNAME.getKey();
String username = this.getParam(params, username_field).toString();
try {
String [] docids = search.getDocIDsByMetadataValue(username_field, username); // RepositoryAccessException
if(docids == null) {
// Shouldn't happen
String errMsg = String.format("WARNING: Unexpected null looking for user %s.", username);
String friendlyErrMsg = String.format("There is no user named %s. Nothing deleted.", username);
results.add(this.createErrorCommandResult(errMsg, friendlyErrMsg));
return;
} else if( docids.length == 0 ) {
// No docs
String errMsg = String.format("User %s not found.", username);
String friendlyErrMsg = String.format("There is no user named %s. Nothing deleted.", username);
results.add(this.createErrorCommandResult(errMsg, friendlyErrMsg));
return;
} else if (docids.length == 1 ) {
// Step #2: BINGO! Now delete document
try {
this.repoman.removeDocument(SETTINGS_REPO, docids[0]);
/*} catch (RhizomeInitializationException e) {
String errMsg = "DocumentRepository could not be created.";
String friendlyErrMsg = String.format("The system could not access the record for %s. Nothing deleted.", username);
results.add(this.createErrorCommandResult(errMsg, friendlyErrMsg, e));
return;*/
} catch (RepositoryAccessException e) {
String errMsg = String.format("User %s could not be deleted from the document repository.", username);
String friendlyErrMsg = String.format("The system could not remove the record for %s. Nothing deleted.", username);
results.add(this.createErrorCommandResult(errMsg, friendlyErrMsg, e));
return;
} catch (com.technosophos.rhizome.RhizomeException e) {
String errMsg = String.format("User %s could not be deleted from the document repository.", username);
String friendlyErrMsg = String.format("The system could not remove the record for %s. Nothing deleted.", username);
results.add(this.createErrorCommandResult(errMsg, friendlyErrMsg, e));
return;
}
results.add(this.createCommandResult(String.format("User %s removed.")));
return;
} else {
// Oops! How did we get multiple users? Better delete by docID instead!
String errMsg = String.format("WARNING: More than one user named %s!.", username);
String friendlyErrMsg = String.format("There are multiple users named %s. This is bad. Contact your system administrator. Nothing deleted.", username);
results.add(this.createErrorCommandResult(errMsg, friendlyErrMsg));
return;
}
} catch (RepositoryAccessException e) {
String errMsg = "RepositorySearcher could not be created.";
String friendlyErrMsg = String.format("Due to an error on our part, we could not find the record for %s. Nothing deleted.", username);
results.add(this.createErrorCommandResult(errMsg, friendlyErrMsg, e));
return;
}
// CASE #3: No user at all!
} else {
String errMsg = "No user or UUID provided.";
String friendlyErrMsg = "You must specify a user to delete.";
results.add(this.createErrorCommandResult(errMsg, friendlyErrMsg));
return;
}
}
}
| true | true | public void doCommand(Map<String, Object> params,
List<CommandResult> results) throws ReRouteRequest {
RepositorySearcher search = null;
try {
search = this.repoman.getSearcher(SETTINGS_REPO);
} catch (RhizomeInitializationException e) {
String errMsg = "RepositorySearcher could not be retrieved.";
String friendlyErrMsg = "This server has had a woeful tragedy attempting to answer your request. Please try again when I stop whimpering.";
results.add(this.createErrorCommandResult(errMsg, friendlyErrMsg, e));
return;
}
// CASE 1: We get a document ID to delete.
if(this.hasParam(params, "id")){
/*
* Get a document, verify it is right, and delete it.
*/
String docID = this.getParam(params, "id").toString();
try {
// #1: Make sure doc exists.
DocumentRepository repo = this.repoman.getRepository(SETTINGS_REPO);
if( repo.hasDocument(docID)) {
// #2 Make sure the document is the correct type.
Metadatum m = search.getMetadatumByDocID(UserEnum.TYPE.getKey(), docID);
List<String> vals = m.getValues();
if(vals == null) {
String errMsg = String.format("DocID %s is not a user account: No type.", docID);
String friendlyErrMsg = String.format("There is no user record with the ID %s. Nothing deleted.", docID);
results.add(this.createErrorCommandResult(errMsg, friendlyErrMsg));
return;
}
boolean isUserDoc = false;
// #2b: loop through and see if any value matches the "user" def. value
for(String v: vals) {
if(UserEnum.TYPE.getFieldDescription().getDefaultValue().equalsIgnoreCase(v)) {
isUserDoc = true;
break;
}
}
if(!isUserDoc) {
String errMsg = String.format("DocID %s is not a user account: Wrong type.", docID);
String friendlyErrMsg = String.format("There is no user record with the ID %s. Nothing deleted.", docID);
results.add(this.createErrorCommandResult(errMsg, friendlyErrMsg));
return;
}
// #3: Try to delete from index.
try {
this.repoman.getIndexer(SETTINGS_REPO).deleteFromIndex(docID);
} catch (RhizomeInitializationException e) {
String errMsg = String.format("Error deleting from indexer: %.", e.getMessage());
String friendlyErrMsg = String.format("The system could not access the record for %s. Nothing deleted.", docID);
results.add(this.createErrorCommandResult(errMsg, friendlyErrMsg, e));
return;
}
// #4: Remove record from repository.
repo.removeDocument(docID);
} else {
String errMsg = String.format("DocID %s not found.", docID);
String friendlyErrMsg = String.format("There is no user record with the ID %s. Nothing deleted.", docID);
results.add(this.createErrorCommandResult(errMsg, friendlyErrMsg));
return;
}
} catch (RhizomeInitializationException e) {
String errMsg = "DocumentRepository could not be created.";
String friendlyErrMsg = String.format("The system could not access the record for %s. Nothing deleted.", docID);
results.add(this.createErrorCommandResult(errMsg, friendlyErrMsg, e));
return;
} catch (RepositoryAccessException e) {
String errMsg = String.format("User %s could not be deleted from the document repository.", docID);
String friendlyErrMsg = String.format("The system could not remove the record for %s. Nothing deleted.", docID);
results.add(this.createErrorCommandResult(errMsg, friendlyErrMsg, e));
return;
}
results.add(this.createCommandResult(String.format("User %s removed.")));
return;
// CASE #2: Delete by user name
} else if(this.hasParam(params, UserEnum.USERNAME.getKey())) {
// Step #1: Get the user record with the given username
String username_field = UserEnum.USERNAME.getKey();
String username = this.getParam(params, username_field).toString();
try {
String [] docids = search.getDocIDsByMetadataValue(username_field, username); // RepositoryAccessException
if(docids == null) {
// Shouldn't happen
String errMsg = String.format("WARNING: Unexpected null looking for user %s.", username);
String friendlyErrMsg = String.format("There is no user named %s. Nothing deleted.", username);
results.add(this.createErrorCommandResult(errMsg, friendlyErrMsg));
return;
} else if( docids.length == 0 ) {
// No docs
String errMsg = String.format("User %s not found.", username);
String friendlyErrMsg = String.format("There is no user named %s. Nothing deleted.", username);
results.add(this.createErrorCommandResult(errMsg, friendlyErrMsg));
return;
} else if (docids.length == 1 ) {
// Step #2: BINGO! Now delete document
try {
this.repoman.removeDocument(SETTINGS_REPO, docids[0]);
/*} catch (RhizomeInitializationException e) {
String errMsg = "DocumentRepository could not be created.";
String friendlyErrMsg = String.format("The system could not access the record for %s. Nothing deleted.", username);
results.add(this.createErrorCommandResult(errMsg, friendlyErrMsg, e));
return;*/
} catch (RepositoryAccessException e) {
String errMsg = String.format("User %s could not be deleted from the document repository.", username);
String friendlyErrMsg = String.format("The system could not remove the record for %s. Nothing deleted.", username);
results.add(this.createErrorCommandResult(errMsg, friendlyErrMsg, e));
return;
} catch (com.technosophos.rhizome.RhizomeException e) {
String errMsg = String.format("User %s could not be deleted from the document repository.", username);
String friendlyErrMsg = String.format("The system could not remove the record for %s. Nothing deleted.", username);
results.add(this.createErrorCommandResult(errMsg, friendlyErrMsg, e));
return;
}
results.add(this.createCommandResult(String.format("User %s removed.")));
return;
} else {
// Oops! How did we get multiple users? Better delete by docID instead!
String errMsg = String.format("WARNING: More than one user named %s!.", username);
String friendlyErrMsg = String.format("There are multiple users named %s. This is bad. Contact your system administrator. Nothing deleted.", username);
results.add(this.createErrorCommandResult(errMsg, friendlyErrMsg));
return;
}
} catch (RepositoryAccessException e) {
String errMsg = "RepositorySearcher could not be created.";
String friendlyErrMsg = String.format("Due to an error on our part, we could not find the record for %s. Nothing deleted.", username);
results.add(this.createErrorCommandResult(errMsg, friendlyErrMsg, e));
return;
}
// CASE #3: No user at all!
} else {
String errMsg = "No user or UUID provided.";
String friendlyErrMsg = "You must specify a user to delete.";
results.add(this.createErrorCommandResult(errMsg, friendlyErrMsg));
return;
}
}
| public void doCommand(Map<String, Object> params,
List<CommandResult> results) throws ReRouteRequest {
RepositorySearcher search = null;
try {
search = this.repoman.getSearcher(SETTINGS_REPO);
} catch (RhizomeInitializationException e) {
String errMsg = "RepositorySearcher could not be retrieved.";
String friendlyErrMsg = "This server has had a woeful tragedy attempting to answer your request. Please try again when I stop whimpering.";
results.add(this.createErrorCommandResult(errMsg, friendlyErrMsg, e));
return;
}
// CASE 1: We get a document ID to delete.
if(this.hasParam(params, "id")){
/*
* Get a document, verify it is right, and delete it.
*/
String docID = this.getParam(params, "id").toString();
try {
// #1: Make sure doc exists.
DocumentRepository repo = this.repoman.getRepository(SETTINGS_REPO);
if( repo.hasDocument(docID)) {
// #2 Make sure the document is the correct type.
Metadatum m = search.getMetadatumByDocID(UserEnum.TYPE.getKey(), docID);
if(!m.hasValue(UserEnum.TYPE.getFieldDescription().getDefaultValue())) {
String errMsg = String.format("DocID %s is not a user account: Wrong type.", docID);
String friendlyErrMsg = String.format("There is no user record with the ID %s. Nothing deleted.", docID);
results.add(this.createErrorCommandResult(errMsg, friendlyErrMsg));
return;
}
// #3: Try to delete from index.
try {
this.repoman.getIndexer(SETTINGS_REPO).deleteFromIndex(docID);
} catch (RhizomeInitializationException e) {
String errMsg = String.format("Error deleting from indexer: %.", e.getMessage());
String friendlyErrMsg = String.format("The system could not access the record for %s. Nothing deleted.", docID);
results.add(this.createErrorCommandResult(errMsg, friendlyErrMsg, e));
return;
}
// #4: Remove record from repository.
repo.removeDocument(docID);
} else {
String errMsg = String.format("DocID %s not found.", docID);
String friendlyErrMsg = String.format("There is no user record with the ID %s. Nothing deleted.", docID);
results.add(this.createErrorCommandResult(errMsg, friendlyErrMsg));
return;
}
} catch (RhizomeInitializationException e) {
String errMsg = "DocumentRepository could not be created.";
String friendlyErrMsg = String.format("The system could not access the record for %s. Nothing deleted.", docID);
results.add(this.createErrorCommandResult(errMsg, friendlyErrMsg, e));
return;
} catch (RepositoryAccessException e) {
String errMsg = String.format("User %s could not be deleted from the document repository.", docID);
String friendlyErrMsg = String.format("The system could not remove the record for %s. Nothing deleted.", docID);
results.add(this.createErrorCommandResult(errMsg, friendlyErrMsg, e));
return;
}
results.add(this.createCommandResult(String.format("User %s removed.")));
return;
// CASE #2: Delete by user name
} else if(this.hasParam(params, UserEnum.USERNAME.getKey())) {
// Step #1: Get the user record with the given username
String username_field = UserEnum.USERNAME.getKey();
String username = this.getParam(params, username_field).toString();
try {
String [] docids = search.getDocIDsByMetadataValue(username_field, username); // RepositoryAccessException
if(docids == null) {
// Shouldn't happen
String errMsg = String.format("WARNING: Unexpected null looking for user %s.", username);
String friendlyErrMsg = String.format("There is no user named %s. Nothing deleted.", username);
results.add(this.createErrorCommandResult(errMsg, friendlyErrMsg));
return;
} else if( docids.length == 0 ) {
// No docs
String errMsg = String.format("User %s not found.", username);
String friendlyErrMsg = String.format("There is no user named %s. Nothing deleted.", username);
results.add(this.createErrorCommandResult(errMsg, friendlyErrMsg));
return;
} else if (docids.length == 1 ) {
// Step #2: BINGO! Now delete document
try {
this.repoman.removeDocument(SETTINGS_REPO, docids[0]);
/*} catch (RhizomeInitializationException e) {
String errMsg = "DocumentRepository could not be created.";
String friendlyErrMsg = String.format("The system could not access the record for %s. Nothing deleted.", username);
results.add(this.createErrorCommandResult(errMsg, friendlyErrMsg, e));
return;*/
} catch (RepositoryAccessException e) {
String errMsg = String.format("User %s could not be deleted from the document repository.", username);
String friendlyErrMsg = String.format("The system could not remove the record for %s. Nothing deleted.", username);
results.add(this.createErrorCommandResult(errMsg, friendlyErrMsg, e));
return;
} catch (com.technosophos.rhizome.RhizomeException e) {
String errMsg = String.format("User %s could not be deleted from the document repository.", username);
String friendlyErrMsg = String.format("The system could not remove the record for %s. Nothing deleted.", username);
results.add(this.createErrorCommandResult(errMsg, friendlyErrMsg, e));
return;
}
results.add(this.createCommandResult(String.format("User %s removed.")));
return;
} else {
// Oops! How did we get multiple users? Better delete by docID instead!
String errMsg = String.format("WARNING: More than one user named %s!.", username);
String friendlyErrMsg = String.format("There are multiple users named %s. This is bad. Contact your system administrator. Nothing deleted.", username);
results.add(this.createErrorCommandResult(errMsg, friendlyErrMsg));
return;
}
} catch (RepositoryAccessException e) {
String errMsg = "RepositorySearcher could not be created.";
String friendlyErrMsg = String.format("Due to an error on our part, we could not find the record for %s. Nothing deleted.", username);
results.add(this.createErrorCommandResult(errMsg, friendlyErrMsg, e));
return;
}
// CASE #3: No user at all!
} else {
String errMsg = "No user or UUID provided.";
String friendlyErrMsg = "You must specify a user to delete.";
results.add(this.createErrorCommandResult(errMsg, friendlyErrMsg));
return;
}
}
|
diff --git a/Android/src/pt/traincompany/account/CardAdapter.java b/Android/src/pt/traincompany/account/CardAdapter.java
index bb0e631..f71a6c0 100644
--- a/Android/src/pt/traincompany/account/CardAdapter.java
+++ b/Android/src/pt/traincompany/account/CardAdapter.java
@@ -1,57 +1,58 @@
package pt.traincompany.account;
import pt.traincompany.main.R;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class CardAdapter extends ArrayAdapter<Card> {
Context context;
int layoutResourceId;
int icon;
Card data[] = null;
public CardAdapter(Context context, int layoutResourceId, int icon,
Card[] data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.icon = icon;
this.data = data;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
CardHolder holder = null;
if (row == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new CardHolder();
holder.imgIcon = (ImageView) row.findViewById(R.id.removeCard);
holder.txtNumber = (TextView) row.findViewById(R.id.creditCardNumber);
row.setTag(holder);
} else {
+ holder = (CardHolder) row.getTag();
}
Card weather = data[position];
holder.txtNumber.setText(weather.number);
holder.imgIcon.setImageResource(this.icon);
return row;
}
static class CardHolder {
ImageView imgIcon;
TextView txtNumber;
}
}
| true | true | public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
CardHolder holder = null;
if (row == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new CardHolder();
holder.imgIcon = (ImageView) row.findViewById(R.id.removeCard);
holder.txtNumber = (TextView) row.findViewById(R.id.creditCardNumber);
row.setTag(holder);
} else {
}
Card weather = data[position];
holder.txtNumber.setText(weather.number);
holder.imgIcon.setImageResource(this.icon);
return row;
}
| public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
CardHolder holder = null;
if (row == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new CardHolder();
holder.imgIcon = (ImageView) row.findViewById(R.id.removeCard);
holder.txtNumber = (TextView) row.findViewById(R.id.creditCardNumber);
row.setTag(holder);
} else {
holder = (CardHolder) row.getTag();
}
Card weather = data[position];
holder.txtNumber.setText(weather.number);
holder.imgIcon.setImageResource(this.icon);
return row;
}
|
diff --git a/tool/src/java/org/sakaiproject/profile2/tool/entityprovider/ProfileEntityProvider.java b/tool/src/java/org/sakaiproject/profile2/tool/entityprovider/ProfileEntityProvider.java
index 0e9417fb..b0e0998e 100644
--- a/tool/src/java/org/sakaiproject/profile2/tool/entityprovider/ProfileEntityProvider.java
+++ b/tool/src/java/org/sakaiproject/profile2/tool/entityprovider/ProfileEntityProvider.java
@@ -1,688 +1,687 @@
/**
* Copyright (c) 2008-2010 The Sakai Foundation
*
* 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.osedu.org/licenses/ECL-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.sakaiproject.profile2.tool.entityprovider;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.sakaiproject.entitybroker.EntityReference;
import org.sakaiproject.entitybroker.EntityView;
import org.sakaiproject.entitybroker.entityprovider.CoreEntityProvider;
import org.sakaiproject.entitybroker.entityprovider.annotations.EntityCustomAction;
import org.sakaiproject.entitybroker.entityprovider.annotations.EntityURLRedirect;
import org.sakaiproject.entitybroker.entityprovider.capabilities.AutoRegisterEntityProvider;
import org.sakaiproject.entitybroker.entityprovider.capabilities.RESTful;
import org.sakaiproject.entitybroker.entityprovider.capabilities.RequestAware;
import org.sakaiproject.entitybroker.entityprovider.extension.ActionReturn;
import org.sakaiproject.entitybroker.entityprovider.extension.Formats;
import org.sakaiproject.entitybroker.entityprovider.extension.RequestGetter;
import org.sakaiproject.entitybroker.entityprovider.search.Search;
import org.sakaiproject.entitybroker.exception.EntityException;
import org.sakaiproject.entitybroker.exception.EntityNotFoundException;
import org.sakaiproject.entitybroker.util.AbstractEntityProvider;
import org.sakaiproject.entitybroker.util.TemplateParseUtil;
import org.sakaiproject.profile2.logic.ProfileConnectionsLogic;
import org.sakaiproject.profile2.logic.ProfileImageLogic;
import org.sakaiproject.profile2.logic.ProfileLogic;
import org.sakaiproject.profile2.logic.SakaiProxy;
import org.sakaiproject.profile2.model.BasicConnection;
import org.sakaiproject.profile2.model.ProfileImage;
import org.sakaiproject.profile2.model.UserProfile;
import org.sakaiproject.profile2.util.Messages;
import org.sakaiproject.profile2.util.ProfileConstants;
import org.sakaiproject.profile2.util.ProfileUtils;
import org.apache.commons.lang.StringEscapeUtils;
/**
* This is the entity provider for a user's profile.
*
* @author Steve Swinsburg ([email protected])
*
*/
public class ProfileEntityProvider extends AbstractEntityProvider implements CoreEntityProvider, AutoRegisterEntityProvider, RESTful, RequestAware {
public final static String ENTITY_PREFIX = "profile";
public String getEntityPrefix() {
return ENTITY_PREFIX;
}
public boolean entityExists(String eid) {
return true;
}
public Object getSampleEntity() {
return new UserProfile();
}
public Object getEntity(EntityReference ref) {
//convert input to uuid
String uuid = sakaiProxy.ensureUuid(ref.getId());
if(StringUtils.isBlank(uuid)) {
throw new EntityNotFoundException("Invalid user.", ref.getId());
}
//get the full profile for the user, takes care of privacy checks against the current user
UserProfile userProfile = profileLogic.getUserProfile(uuid);
if(userProfile == null) {
throw new EntityNotFoundException("Profile could not be retrieved for " + ref.getId(), ref.getReference());
}
return userProfile;
}
@EntityCustomAction(action="image",viewKey=EntityView.VIEW_SHOW)
public Object getProfileImage(OutputStream out, EntityView view, Map<String,Object> params, EntityReference ref) {
//convert input to uuid
String uuid = sakaiProxy.ensureUuid(ref.getId());
if(StringUtils.isBlank(uuid)) {
throw new EntityNotFoundException("Invalid user.", ref.getId());
}
ProfileImage image = new ProfileImage();
boolean wantsThumbnail = "thumb".equals(view.getPathSegment(3)) ? true : false;
//optional siteid
String siteId = (String)params.get("siteId");
if(StringUtils.isNotBlank(siteId) && !sakaiProxy.checkForSite(siteId)){
throw new EntityNotFoundException("Invalid siteId: " + siteId, ref.getReference());
}
//get thumb if requested - will fallback by default
if(wantsThumbnail) {
image = imageLogic.getProfileImage(uuid, null, null, ProfileConstants.PROFILE_IMAGE_THUMBNAIL, siteId);
} else {
image = imageLogic.getProfileImage(uuid, null, null, ProfileConstants.PROFILE_IMAGE_MAIN, siteId);
}
if(image == null) {
throw new EntityNotFoundException("No profile image for " + ref.getId(), ref.getReference());
}
//check for binary
final byte[] bytes = image.getBinary();
if(bytes != null && bytes.length > 0) {
try {
out.write(bytes);
ActionReturn actionReturn = new ActionReturn("BASE64", image.getMimeType(), out);
return actionReturn;
} catch (IOException e) {
throw new EntityException("Error retrieving profile image for " + ref.getId() + " : " + e.getMessage(), ref.getReference());
}
}
String url = image.getUrl();
if(StringUtils.isNotBlank(url)) {
try {
requestGetter.getResponse().sendRedirect(url);
} catch (IOException e) {
throw new EntityException("Error redirecting to external image for " + ref.getId() + " : " + e.getMessage(), ref.getReference());
}
}
return null;
}
@EntityCustomAction(action="connections",viewKey=EntityView.VIEW_SHOW)
public Object getConnections(EntityView view, EntityReference ref) {
if(!sakaiProxy.isLoggedIn()) {
throw new SecurityException("You must be logged in to get a connection list.");
}
//convert input to uuid
String uuid = sakaiProxy.ensureUuid(ref.getId());
if(StringUtils.isBlank(uuid)) {
throw new EntityNotFoundException("Invalid user.", ref.getId());
}
//get list of connections
List<BasicConnection> connections = connectionsLogic.getBasicConnectionsForUser(uuid);
if(connections == null) {
throw new EntityException("Error retrieving connections for " + ref.getId(), ref.getReference());
}
ActionReturn actionReturn = new ActionReturn(connections);
return actionReturn;
}
@EntityCustomAction(action="friendStatus",viewKey=EntityView.VIEW_SHOW)
public Object getConnectionStatus(EntityReference ref, Map<String, Object> parameters) {
if(!sakaiProxy.isLoggedIn()) {
throw new SecurityException("You must be logged in to get a friend status record.");
}
//convert input to uuid (user making query)
String uuid = sakaiProxy.ensureUuid(ref.getId());
if(StringUtils.isBlank(uuid)) {
throw new EntityNotFoundException("Invalid user.", ref.getId());
}
if (false == parameters.containsKey("friendId")) {
throw new EntityNotFoundException("Parameter must be specified: friendId", ref.getId());
}
return connectionsLogic.getConnectionStatus(uuid, parameters.get("friendId").toString());
}
@EntityCustomAction(action="formatted",viewKey=EntityView.VIEW_SHOW)
public Object getFormattedProfile(EntityReference ref) {
//this allows a normal full profile to be returned formatted in HTML
//get the full profile
UserProfile userProfile = (UserProfile) getEntity(ref);
//convert UserProfile to HTML object
String formattedProfile = getUserProfileAsHTML(userProfile);
//ActionReturn actionReturn = new ActionReturn("UTF-8", "text/html", entity);
ActionReturn actionReturn = new ActionReturn(Formats.UTF_8, Formats.HTML_MIME_TYPE, formattedProfile);
return actionReturn;
}
@EntityCustomAction(action="requestFriend",viewKey=EntityView.VIEW_SHOW)
public Object requestFriend(EntityReference ref,Map<String,Object> params) {
if(!sakaiProxy.isLoggedIn()) {
throw new SecurityException("You must be logged in to make a connection request.");
}
//convert input to uuid
String uuid = sakaiProxy.ensureUuid(ref.getId());
if(StringUtils.isBlank(uuid)) {
throw new EntityNotFoundException("Invalid user.", ref.getId());
}
String friendId = (String) params.get("friendId");
//get list of connections
if(!connectionsLogic.requestFriend(uuid, friendId)) {
throw new EntityException("Error requesting friend connection for " + ref.getId(), ref.getReference());
}
else
return Messages.getString("Label.friend.requested");
}
@EntityCustomAction(action="removeFriend",viewKey=EntityView.VIEW_SHOW)
public Object removeFriend(EntityReference ref,Map<String,Object> params) {
if(!sakaiProxy.isLoggedIn()) {
throw new SecurityException("You must be logged in to remove a connection.");
}
//convert input to uuid
String uuid = sakaiProxy.ensureUuid(ref.getId());
if(StringUtils.isBlank(uuid)) {
throw new EntityNotFoundException("Invalid user.", ref.getId());
}
String friendId = (String) params.get("friendId");
//get list of connections
if(!connectionsLogic.removeFriend(uuid, friendId)) {
throw new EntityException("Error removing friend connection for " + ref.getId(), ref.getReference());
}
else
return Messages.getString("Label.friend.add");
}
@EntityCustomAction(action="confirmFriendRequest",viewKey=EntityView.VIEW_SHOW)
public Object confirmFriendRequest(EntityReference ref,Map<String,Object> params) {
if(!sakaiProxy.isLoggedIn()) {
throw new SecurityException("You must be logged in to confirm a connection request.");
}
//convert input to uuid
String uuid = sakaiProxy.ensureUuid(ref.getId());
if(StringUtils.isBlank(uuid)) {
throw new EntityNotFoundException("Invalid user.", ref.getId());
}
String friendId = (String) params.get("friendId");
//get list of connections
if(!connectionsLogic.confirmFriendRequest(friendId, uuid)) {
//if(!connectionsLogic.confirmFriendRequest(uuid, friendId)) {
throw new EntityException("Error confirming friend connection for " + ref.getId(), ref.getReference());
}
else
return Messages.getString("Label.friend.remove");
}
@EntityCustomAction(action="ignoreFriendRequest",viewKey=EntityView.VIEW_SHOW)
public Object ignoreFriendRequest(EntityReference ref,Map<String,Object> params) {
if(!sakaiProxy.isLoggedIn()) {
throw new SecurityException("You must be logged in to ignore a connection request.");
}
//convert input to uuid
String uuid = sakaiProxy.ensureUuid(ref.getId());
if(StringUtils.isBlank(uuid)) {
throw new EntityNotFoundException("Invalid user.", ref.getId());
}
String friendId = (String) params.get("friendId");
//we're ignoring a request FROM the friendId TO the uuid
if(!connectionsLogic.ignoreFriendRequest(friendId, uuid)) {
throw new EntityException("Error ignoring friend connection for " + ref.getId(), ref.getReference());
}
else
return Messages.getString("Label.friend.add");
}
@EntityURLRedirect("/{prefix}/{id}/account")
public String redirectUserAccount(Map<String,String> vars) {
return "user/" + vars.get("id") + vars.get(TemplateParseUtil.DOT_EXTENSION);
}
public void updateEntity(EntityReference ref, Object entity, Map<String, Object> params) {
String userId = ref.getId();
if (StringUtils.isBlank(userId)) {
throw new IllegalArgumentException("Cannot update, No userId in provided reference: " + ref);
}
if (entity.getClass().isAssignableFrom(UserProfile.class)) {
UserProfile userProfile = (UserProfile) entity;
profileLogic.saveUserProfile(userProfile);
} else {
throw new IllegalArgumentException("Invalid entity for update, must be UserProfile object");
}
}
public String createEntity(EntityReference ref, Object entity, Map<String, Object> params) {
//reference will be the userUuid, which comes from the UserProfile
String userUuid = null;
if (entity.getClass().isAssignableFrom(UserProfile.class)) {
UserProfile userProfile = (UserProfile) entity;
if(profileLogic.saveUserProfile(userProfile)) {
userUuid = userProfile.getUserUuid();
}
if(userUuid == null) {
throw new EntityException("Could not create entity", ref.getReference());
}
} else {
throw new IllegalArgumentException("Invalid entity for create, must be UserProfile object");
}
return userUuid;
}
/**
* {@inheritDoc}
*/
private String getUserProfileAsHTML(UserProfile userProfile) {
//note there is no birthday in this field. we need a good way to get the birthday without the year.
//maybe it needs to be stored in a separate field and treated differently. Or returned as a localised string.
StringBuilder sb = new StringBuilder();
sb.append("<script type=\"text/javascript\" src=\"/profile2-tool/javascript/profile2-eb.js\"></script>");
sb.append("<div class=\"profile2-profile\">");
sb.append("<div class=\"profile2-profile-image\">");
sb.append("<img src=\"");
sb.append(userProfile.getImageUrl());
sb.append("\" />");
sb.append("</div>");
sb.append("<div class=\"profile2-profile-content\">");
if(StringUtils.isNotBlank(userProfile.getUserUuid())) {
sb.append("<div class=\"profile2-profile-userUuid\">");
sb.append("<span class=\"profile2-profile-label\">");
sb.append(Messages.getString("Label.userUuid"));
sb.append("</span>");
sb.append(userProfile.getUserUuid());
sb.append("</div>");
}
String displayName = userProfile.getDisplayName();
if(StringUtils.isNotBlank(displayName)) {
sb.append("<div class=\"profile2-profile-displayName\">");
- sb.append(userProfile.getDisplayName());
sb.append(StringEscapeUtils.escapeHtml(displayName));
sb.append("</div>");
}
if(!sakaiProxy.getCurrentUserId().equals(userProfile.getUserUuid())) {
int connectionStatus = connectionsLogic.getConnectionStatus(sakaiProxy.getCurrentUserId(), userProfile.getUserUuid());
if(connectionStatus == ProfileConstants.CONNECTION_CONFIRMED) {
sb.append("<div id=\"profile_friend_" + userProfile.getUserUuid() + "\" class=\"icon connection-confirmed\"><a href=\"javascript:;\" onClick=\"return removeFriend('" + sakaiProxy.getCurrentUserId() + "','" + userProfile.getUserUuid() + "');\">" + Messages.getString("Label.friend.remove") + "</a></div>");
}
else if(connectionStatus == ProfileConstants.CONNECTION_REQUESTED) {
sb.append("<div id=\"profile_friend_" + userProfile.getUserUuid() + "\" class=\"icon connection-request\">" + Messages.getString("Label.friend.requested") + "</div>");
}
else if(connectionStatus == ProfileConstants.CONNECTION_INCOMING) {
sb.append("<div id=\"profile_friend_" + userProfile.getUserUuid() + "\" class=\"icon connection-request\">" + Messages.getString("Label.friend.requested") + "<a href=\"javascript:;\" title=\"" + Messages.getString("Label.friend.confirm") + "\" onClick=\"return confirmFriendRequest('" + sakaiProxy.getCurrentUserId() + "','" + userProfile.getUserUuid() + "');\"><img src=\"/library/image/silk/accept.png\"></a><a href=\"javascript:;\" title=\"" + Messages.getString("Label.friend.ignore") + "\" onClick=\"return ignoreFriendRequest('" + sakaiProxy.getCurrentUserId() + "','" + userProfile.getUserUuid() + "');\"><img src=\"/library/image/silk/cancel.png\"></a></div>");
}
else {
sb.append("<div id=\"profile_friend_" + userProfile.getUserUuid() + "\" class=\"icon connection-add\"><a href=\"javascript:;\" onClick=\"return requestFriend('" + sakaiProxy.getCurrentUserId() + "','" + userProfile.getUserUuid() + "');\">" + Messages.getString("Label.friend.add") + "</a></div>");
}
sb.append("<br />");
}
//status
if(userProfile.getStatus() != null) {
String message = userProfile.getStatus().getMessage();
if(StringUtils.isNotBlank(message)) {
sb.append("<div class=\"profile2-profile-statusMessage\">");
sb.append(StringEscapeUtils.escapeHtml(message));
sb.append("</div>");
}
if(StringUtils.isNotBlank(userProfile.getStatus().getDateFormatted())) {
sb.append("<div class=\"profile2-profile-statusDate\">");
sb.append(userProfile.getStatus().getDateFormatted());
sb.append("</div>");
}
}
//basic info
String nickname = userProfile.getNickname();
if(StringUtils.isNotBlank(nickname)) {
sb.append("<div class=\"profile2-profile-nickname\">");
sb.append("<span class=\"profile2-profile-label\">");
sb.append(Messages.getString("Label.nickname"));
sb.append("</span>");
sb.append(StringEscapeUtils.escapeHtml(nickname).toString());
sb.append("</div>");
}
if(StringUtils.isNotBlank(userProfile.getPersonalSummary())) {
sb.append("<div class=\"profile2-profile-personalSummary\">");
sb.append("<span class=\"profile2-profile-label\">");
sb.append(Messages.getString("Label.personalSummary"));
sb.append("</span>");
//PRFL-389 abbreviate long personal summary
int maxLength = Integer.parseInt(sakaiProxy.getServerConfigurationParameter("profile2.formatted.profile.summary.max", ProfileConstants.FORMATTED_PROFILE_SUMMARY_MAX_LENGTH));
sb.append(ProfileUtils.truncateAndAbbreviate(ProfileUtils.processHtml(userProfile.getPersonalSummary()), maxLength, true));
sb.append("</div>");
}
//contact info
if(StringUtils.isNotBlank(userProfile.getEmail())) {
sb.append("<div class=\"profile2-profile-email\">");
sb.append("<span class=\"profile2-profile-label\">");
sb.append(Messages.getString("Label.email"));
sb.append("</span>");
sb.append(userProfile.getEmail());
sb.append("</div>");
}
if(StringUtils.isNotBlank(userProfile.getHomepage())) {
sb.append("<div class=\"profile2-profile-homepage\">");
sb.append("<span class=\"profile2-profile-label\">");
sb.append(Messages.getString("Label.homepage"));
sb.append("</span>");
sb.append(userProfile.getHomepage());
sb.append("</div>");
}
if(StringUtils.isNotBlank(userProfile.getHomephone())) {
sb.append("<div class=\"profile2-profile-homephone\">");
sb.append("<span class=\"profile2-profile-label\">");
sb.append(Messages.getString("Label.homephone"));
sb.append("</span>");
sb.append(userProfile.getHomephone());
sb.append("</div>");
}
if(StringUtils.isNotBlank(userProfile.getWorkphone())) {
sb.append("<div class=\"profile2-profile-workphone\">");
sb.append("<span class=\"profile2-profile-label\">");
sb.append(Messages.getString("Label.workphone"));
sb.append("</span>");
sb.append(userProfile.getWorkphone());
sb.append("</div>");
}
if(StringUtils.isNotBlank(userProfile.getMobilephone())) {
sb.append("<div class=\"profile2-profile-mobilephone\">");
sb.append("<span class=\"profile2-profile-label\">");
sb.append(Messages.getString("Label.mobilephone"));
sb.append("</span>");
sb.append(userProfile.getMobilephone());
sb.append("</div>");
}
if(StringUtils.isNotBlank(userProfile.getFacsimile())) {
sb.append("<div class=\"profile2-profile-facsimile\">");
sb.append("<span class=\"profile2-profile-label\">");
sb.append(Messages.getString("Label.facsimile"));
sb.append("</span>");
sb.append(userProfile.getFacsimile());
sb.append("</div>");
}
//academic info
String position = userProfile.getPosition();
if(StringUtils.isNotBlank(position)) {
sb.append("<div class=\"profile2-profile-position\">");
sb.append("<span class=\"profile2-profile-label\">");
sb.append(Messages.getString("Label.position"));
sb.append("</span>");
sb.append(StringEscapeUtils.escapeHtml(position));
sb.append("</div>");
}
String department = userProfile.getDepartment();
if(StringUtils.isNotBlank(department)) {
sb.append("<div class=\"profile2-profile-department\">");
sb.append("<span class=\"profile2-profile-label\">");
sb.append(Messages.getString("Label.department"));
sb.append("</span>");
sb.append(StringEscapeUtils.escapeHtml(department));
sb.append("</div>");
}
String school = userProfile.getSchool();
if(StringUtils.isNotBlank(school)) {
sb.append("<div class=\"profile2-profile-school\">");
sb.append("<span class=\"profile2-profile-label\">");
sb.append(Messages.getString("Label.school"));
sb.append("</span>");
sb.append(StringEscapeUtils.escapeHtml(school));
sb.append("</div>");
}
String room = userProfile.getRoom();
if(StringUtils.isNotBlank(room)) {
sb.append("<div class=\"profile2-profile-room\">");
sb.append("<span class=\"profile2-profile-label\">");
sb.append(Messages.getString("Label.room"));
sb.append("</span>");
sb.append(StringEscapeUtils.escapeHtml(room));
sb.append("</div>");
}
String course = userProfile.getCourse();
if(StringUtils.isNotBlank(course)) {
sb.append("<div class=\"profile2-profile-course\">");
sb.append("<span class=\"profile2-profile-label\">");
sb.append(Messages.getString("Label.course"));
sb.append("</span>");
sb.append(StringEscapeUtils.escapeHtml(course));
sb.append("</div>");
}
String subjects = userProfile.getSubjects();
if(StringUtils.isNotBlank(subjects)) {
sb.append("<div class=\"profile2-profile-subjects\">");
sb.append("<span class=\"profile2-profile-label\">");
sb.append(Messages.getString("Label.subjects"));
sb.append("</span>");
sb.append(StringEscapeUtils.escapeHtml(subjects));
sb.append("</div>");
}
//personal info
String favouriteBooks = userProfile.getFavouriteBooks();
if(StringUtils.isNotBlank(favouriteBooks)) {
sb.append("<div class=\"profile2-profile-favouriteBooks\">");
sb.append("<span class=\"profile2-profile-label\">");
sb.append(Messages.getString("Label.favouriteBooks"));
sb.append("</span>");
sb.append(StringEscapeUtils.escapeHtml(favouriteBooks));
sb.append("</div>");
}
String favouriteTvShows = userProfile.getFavouriteTvShows();
if(StringUtils.isNotBlank(favouriteTvShows)) {
sb.append("<div class=\"profile2-profile-favouriteTvShows\">");
sb.append("<span class=\"profile2-profile-label\">");
sb.append(Messages.getString("Label.favouriteTvShows"));
sb.append("</span>");
sb.append(StringEscapeUtils.escapeHtml(favouriteTvShows));
sb.append("</div>");
}
String favouriteMovies = userProfile.getFavouriteMovies();
if(StringUtils.isNotBlank(favouriteMovies)) {
sb.append("<div class=\"profile2-profile-favouriteMovies\">");
sb.append("<span class=\"profile2-profile-label\">");
sb.append(Messages.getString("Label.favouriteMovies"));
sb.append("</span>");
sb.append(StringEscapeUtils.escapeHtml(favouriteMovies));
sb.append("</div>");
}
String favouriteQuotes = userProfile.getFavouriteQuotes();
if(StringUtils.isNotBlank(favouriteQuotes)) {
sb.append("<div class=\"profile2-profile-favouriteQuotes\">");
sb.append("<span class=\"profile2-profile-label\">");
sb.append(Messages.getString("Label.favouriteQuotes"));
sb.append("</span>");
sb.append(StringEscapeUtils.escapeHtml(favouriteQuotes));
sb.append("</div>");
}
sb.append("</div>");
sb.append("</div>");
//add the stylesheet
sb.append("<link href=\"");
sb.append(ProfileConstants.ENTITY_CSS_PROFILE);
sb.append("\" type=\"text/css\" rel=\"stylesheet\" media=\"all\" />");
return sb.toString();
}
public void deleteEntity(EntityReference ref, Map<String, Object> params) {
// TODO Auto-generated method stub
}
public List<?> getEntities(EntityReference ref, Search search) {
// TODO Auto-generated method stub
return null;
}
private RequestGetter requestGetter;
public void setRequestGetter(RequestGetter requestGetter) {
this.requestGetter = requestGetter;
}
public String[] getHandledOutputFormats() {
return new String[] {Formats.HTML, Formats.XML, Formats.JSON};
}
public String[] getHandledInputFormats() {
return new String[] {Formats.XML, Formats.JSON, Formats.HTML};
}
private SakaiProxy sakaiProxy;
public void setSakaiProxy(SakaiProxy sakaiProxy) {
this.sakaiProxy = sakaiProxy;
}
private ProfileLogic profileLogic;
public void setProfileLogic(ProfileLogic profileLogic) {
this.profileLogic = profileLogic;
}
private ProfileConnectionsLogic connectionsLogic;
public void setConnectionsLogic(ProfileConnectionsLogic connectionsLogic) {
this.connectionsLogic = connectionsLogic;
}
private ProfileImageLogic imageLogic;
public void setImageLogic(ProfileImageLogic imageLogic) {
this.imageLogic = imageLogic;
}
}
| true | true | private String getUserProfileAsHTML(UserProfile userProfile) {
//note there is no birthday in this field. we need a good way to get the birthday without the year.
//maybe it needs to be stored in a separate field and treated differently. Or returned as a localised string.
StringBuilder sb = new StringBuilder();
sb.append("<script type=\"text/javascript\" src=\"/profile2-tool/javascript/profile2-eb.js\"></script>");
sb.append("<div class=\"profile2-profile\">");
sb.append("<div class=\"profile2-profile-image\">");
sb.append("<img src=\"");
sb.append(userProfile.getImageUrl());
sb.append("\" />");
sb.append("</div>");
sb.append("<div class=\"profile2-profile-content\">");
if(StringUtils.isNotBlank(userProfile.getUserUuid())) {
sb.append("<div class=\"profile2-profile-userUuid\">");
sb.append("<span class=\"profile2-profile-label\">");
sb.append(Messages.getString("Label.userUuid"));
sb.append("</span>");
sb.append(userProfile.getUserUuid());
sb.append("</div>");
}
String displayName = userProfile.getDisplayName();
if(StringUtils.isNotBlank(displayName)) {
sb.append("<div class=\"profile2-profile-displayName\">");
sb.append(userProfile.getDisplayName());
sb.append(StringEscapeUtils.escapeHtml(displayName));
sb.append("</div>");
}
if(!sakaiProxy.getCurrentUserId().equals(userProfile.getUserUuid())) {
int connectionStatus = connectionsLogic.getConnectionStatus(sakaiProxy.getCurrentUserId(), userProfile.getUserUuid());
if(connectionStatus == ProfileConstants.CONNECTION_CONFIRMED) {
sb.append("<div id=\"profile_friend_" + userProfile.getUserUuid() + "\" class=\"icon connection-confirmed\"><a href=\"javascript:;\" onClick=\"return removeFriend('" + sakaiProxy.getCurrentUserId() + "','" + userProfile.getUserUuid() + "');\">" + Messages.getString("Label.friend.remove") + "</a></div>");
}
else if(connectionStatus == ProfileConstants.CONNECTION_REQUESTED) {
sb.append("<div id=\"profile_friend_" + userProfile.getUserUuid() + "\" class=\"icon connection-request\">" + Messages.getString("Label.friend.requested") + "</div>");
}
else if(connectionStatus == ProfileConstants.CONNECTION_INCOMING) {
sb.append("<div id=\"profile_friend_" + userProfile.getUserUuid() + "\" class=\"icon connection-request\">" + Messages.getString("Label.friend.requested") + "<a href=\"javascript:;\" title=\"" + Messages.getString("Label.friend.confirm") + "\" onClick=\"return confirmFriendRequest('" + sakaiProxy.getCurrentUserId() + "','" + userProfile.getUserUuid() + "');\"><img src=\"/library/image/silk/accept.png\"></a><a href=\"javascript:;\" title=\"" + Messages.getString("Label.friend.ignore") + "\" onClick=\"return ignoreFriendRequest('" + sakaiProxy.getCurrentUserId() + "','" + userProfile.getUserUuid() + "');\"><img src=\"/library/image/silk/cancel.png\"></a></div>");
}
else {
sb.append("<div id=\"profile_friend_" + userProfile.getUserUuid() + "\" class=\"icon connection-add\"><a href=\"javascript:;\" onClick=\"return requestFriend('" + sakaiProxy.getCurrentUserId() + "','" + userProfile.getUserUuid() + "');\">" + Messages.getString("Label.friend.add") + "</a></div>");
}
sb.append("<br />");
}
//status
if(userProfile.getStatus() != null) {
String message = userProfile.getStatus().getMessage();
if(StringUtils.isNotBlank(message)) {
sb.append("<div class=\"profile2-profile-statusMessage\">");
sb.append(StringEscapeUtils.escapeHtml(message));
sb.append("</div>");
}
if(StringUtils.isNotBlank(userProfile.getStatus().getDateFormatted())) {
sb.append("<div class=\"profile2-profile-statusDate\">");
sb.append(userProfile.getStatus().getDateFormatted());
sb.append("</div>");
}
}
//basic info
String nickname = userProfile.getNickname();
if(StringUtils.isNotBlank(nickname)) {
sb.append("<div class=\"profile2-profile-nickname\">");
sb.append("<span class=\"profile2-profile-label\">");
sb.append(Messages.getString("Label.nickname"));
sb.append("</span>");
sb.append(StringEscapeUtils.escapeHtml(nickname).toString());
sb.append("</div>");
}
if(StringUtils.isNotBlank(userProfile.getPersonalSummary())) {
sb.append("<div class=\"profile2-profile-personalSummary\">");
sb.append("<span class=\"profile2-profile-label\">");
sb.append(Messages.getString("Label.personalSummary"));
sb.append("</span>");
//PRFL-389 abbreviate long personal summary
int maxLength = Integer.parseInt(sakaiProxy.getServerConfigurationParameter("profile2.formatted.profile.summary.max", ProfileConstants.FORMATTED_PROFILE_SUMMARY_MAX_LENGTH));
sb.append(ProfileUtils.truncateAndAbbreviate(ProfileUtils.processHtml(userProfile.getPersonalSummary()), maxLength, true));
sb.append("</div>");
}
//contact info
if(StringUtils.isNotBlank(userProfile.getEmail())) {
sb.append("<div class=\"profile2-profile-email\">");
sb.append("<span class=\"profile2-profile-label\">");
sb.append(Messages.getString("Label.email"));
sb.append("</span>");
sb.append(userProfile.getEmail());
sb.append("</div>");
}
if(StringUtils.isNotBlank(userProfile.getHomepage())) {
sb.append("<div class=\"profile2-profile-homepage\">");
sb.append("<span class=\"profile2-profile-label\">");
sb.append(Messages.getString("Label.homepage"));
sb.append("</span>");
sb.append(userProfile.getHomepage());
sb.append("</div>");
}
if(StringUtils.isNotBlank(userProfile.getHomephone())) {
sb.append("<div class=\"profile2-profile-homephone\">");
sb.append("<span class=\"profile2-profile-label\">");
sb.append(Messages.getString("Label.homephone"));
sb.append("</span>");
sb.append(userProfile.getHomephone());
sb.append("</div>");
}
if(StringUtils.isNotBlank(userProfile.getWorkphone())) {
sb.append("<div class=\"profile2-profile-workphone\">");
sb.append("<span class=\"profile2-profile-label\">");
sb.append(Messages.getString("Label.workphone"));
sb.append("</span>");
sb.append(userProfile.getWorkphone());
sb.append("</div>");
}
if(StringUtils.isNotBlank(userProfile.getMobilephone())) {
sb.append("<div class=\"profile2-profile-mobilephone\">");
sb.append("<span class=\"profile2-profile-label\">");
sb.append(Messages.getString("Label.mobilephone"));
sb.append("</span>");
sb.append(userProfile.getMobilephone());
sb.append("</div>");
}
if(StringUtils.isNotBlank(userProfile.getFacsimile())) {
sb.append("<div class=\"profile2-profile-facsimile\">");
sb.append("<span class=\"profile2-profile-label\">");
sb.append(Messages.getString("Label.facsimile"));
sb.append("</span>");
sb.append(userProfile.getFacsimile());
sb.append("</div>");
}
//academic info
String position = userProfile.getPosition();
if(StringUtils.isNotBlank(position)) {
sb.append("<div class=\"profile2-profile-position\">");
sb.append("<span class=\"profile2-profile-label\">");
sb.append(Messages.getString("Label.position"));
sb.append("</span>");
sb.append(StringEscapeUtils.escapeHtml(position));
sb.append("</div>");
}
String department = userProfile.getDepartment();
if(StringUtils.isNotBlank(department)) {
sb.append("<div class=\"profile2-profile-department\">");
sb.append("<span class=\"profile2-profile-label\">");
sb.append(Messages.getString("Label.department"));
sb.append("</span>");
sb.append(StringEscapeUtils.escapeHtml(department));
sb.append("</div>");
}
String school = userProfile.getSchool();
if(StringUtils.isNotBlank(school)) {
sb.append("<div class=\"profile2-profile-school\">");
sb.append("<span class=\"profile2-profile-label\">");
sb.append(Messages.getString("Label.school"));
sb.append("</span>");
sb.append(StringEscapeUtils.escapeHtml(school));
sb.append("</div>");
}
String room = userProfile.getRoom();
if(StringUtils.isNotBlank(room)) {
sb.append("<div class=\"profile2-profile-room\">");
sb.append("<span class=\"profile2-profile-label\">");
sb.append(Messages.getString("Label.room"));
sb.append("</span>");
sb.append(StringEscapeUtils.escapeHtml(room));
sb.append("</div>");
}
String course = userProfile.getCourse();
if(StringUtils.isNotBlank(course)) {
sb.append("<div class=\"profile2-profile-course\">");
sb.append("<span class=\"profile2-profile-label\">");
sb.append(Messages.getString("Label.course"));
sb.append("</span>");
sb.append(StringEscapeUtils.escapeHtml(course));
sb.append("</div>");
}
String subjects = userProfile.getSubjects();
if(StringUtils.isNotBlank(subjects)) {
sb.append("<div class=\"profile2-profile-subjects\">");
sb.append("<span class=\"profile2-profile-label\">");
sb.append(Messages.getString("Label.subjects"));
sb.append("</span>");
sb.append(StringEscapeUtils.escapeHtml(subjects));
sb.append("</div>");
}
//personal info
String favouriteBooks = userProfile.getFavouriteBooks();
if(StringUtils.isNotBlank(favouriteBooks)) {
sb.append("<div class=\"profile2-profile-favouriteBooks\">");
sb.append("<span class=\"profile2-profile-label\">");
sb.append(Messages.getString("Label.favouriteBooks"));
sb.append("</span>");
sb.append(StringEscapeUtils.escapeHtml(favouriteBooks));
sb.append("</div>");
}
String favouriteTvShows = userProfile.getFavouriteTvShows();
if(StringUtils.isNotBlank(favouriteTvShows)) {
sb.append("<div class=\"profile2-profile-favouriteTvShows\">");
sb.append("<span class=\"profile2-profile-label\">");
sb.append(Messages.getString("Label.favouriteTvShows"));
sb.append("</span>");
sb.append(StringEscapeUtils.escapeHtml(favouriteTvShows));
sb.append("</div>");
}
String favouriteMovies = userProfile.getFavouriteMovies();
if(StringUtils.isNotBlank(favouriteMovies)) {
sb.append("<div class=\"profile2-profile-favouriteMovies\">");
sb.append("<span class=\"profile2-profile-label\">");
sb.append(Messages.getString("Label.favouriteMovies"));
sb.append("</span>");
sb.append(StringEscapeUtils.escapeHtml(favouriteMovies));
sb.append("</div>");
}
String favouriteQuotes = userProfile.getFavouriteQuotes();
if(StringUtils.isNotBlank(favouriteQuotes)) {
sb.append("<div class=\"profile2-profile-favouriteQuotes\">");
sb.append("<span class=\"profile2-profile-label\">");
sb.append(Messages.getString("Label.favouriteQuotes"));
sb.append("</span>");
sb.append(StringEscapeUtils.escapeHtml(favouriteQuotes));
sb.append("</div>");
}
sb.append("</div>");
sb.append("</div>");
//add the stylesheet
sb.append("<link href=\"");
sb.append(ProfileConstants.ENTITY_CSS_PROFILE);
sb.append("\" type=\"text/css\" rel=\"stylesheet\" media=\"all\" />");
return sb.toString();
}
| private String getUserProfileAsHTML(UserProfile userProfile) {
//note there is no birthday in this field. we need a good way to get the birthday without the year.
//maybe it needs to be stored in a separate field and treated differently. Or returned as a localised string.
StringBuilder sb = new StringBuilder();
sb.append("<script type=\"text/javascript\" src=\"/profile2-tool/javascript/profile2-eb.js\"></script>");
sb.append("<div class=\"profile2-profile\">");
sb.append("<div class=\"profile2-profile-image\">");
sb.append("<img src=\"");
sb.append(userProfile.getImageUrl());
sb.append("\" />");
sb.append("</div>");
sb.append("<div class=\"profile2-profile-content\">");
if(StringUtils.isNotBlank(userProfile.getUserUuid())) {
sb.append("<div class=\"profile2-profile-userUuid\">");
sb.append("<span class=\"profile2-profile-label\">");
sb.append(Messages.getString("Label.userUuid"));
sb.append("</span>");
sb.append(userProfile.getUserUuid());
sb.append("</div>");
}
String displayName = userProfile.getDisplayName();
if(StringUtils.isNotBlank(displayName)) {
sb.append("<div class=\"profile2-profile-displayName\">");
sb.append(StringEscapeUtils.escapeHtml(displayName));
sb.append("</div>");
}
if(!sakaiProxy.getCurrentUserId().equals(userProfile.getUserUuid())) {
int connectionStatus = connectionsLogic.getConnectionStatus(sakaiProxy.getCurrentUserId(), userProfile.getUserUuid());
if(connectionStatus == ProfileConstants.CONNECTION_CONFIRMED) {
sb.append("<div id=\"profile_friend_" + userProfile.getUserUuid() + "\" class=\"icon connection-confirmed\"><a href=\"javascript:;\" onClick=\"return removeFriend('" + sakaiProxy.getCurrentUserId() + "','" + userProfile.getUserUuid() + "');\">" + Messages.getString("Label.friend.remove") + "</a></div>");
}
else if(connectionStatus == ProfileConstants.CONNECTION_REQUESTED) {
sb.append("<div id=\"profile_friend_" + userProfile.getUserUuid() + "\" class=\"icon connection-request\">" + Messages.getString("Label.friend.requested") + "</div>");
}
else if(connectionStatus == ProfileConstants.CONNECTION_INCOMING) {
sb.append("<div id=\"profile_friend_" + userProfile.getUserUuid() + "\" class=\"icon connection-request\">" + Messages.getString("Label.friend.requested") + "<a href=\"javascript:;\" title=\"" + Messages.getString("Label.friend.confirm") + "\" onClick=\"return confirmFriendRequest('" + sakaiProxy.getCurrentUserId() + "','" + userProfile.getUserUuid() + "');\"><img src=\"/library/image/silk/accept.png\"></a><a href=\"javascript:;\" title=\"" + Messages.getString("Label.friend.ignore") + "\" onClick=\"return ignoreFriendRequest('" + sakaiProxy.getCurrentUserId() + "','" + userProfile.getUserUuid() + "');\"><img src=\"/library/image/silk/cancel.png\"></a></div>");
}
else {
sb.append("<div id=\"profile_friend_" + userProfile.getUserUuid() + "\" class=\"icon connection-add\"><a href=\"javascript:;\" onClick=\"return requestFriend('" + sakaiProxy.getCurrentUserId() + "','" + userProfile.getUserUuid() + "');\">" + Messages.getString("Label.friend.add") + "</a></div>");
}
sb.append("<br />");
}
//status
if(userProfile.getStatus() != null) {
String message = userProfile.getStatus().getMessage();
if(StringUtils.isNotBlank(message)) {
sb.append("<div class=\"profile2-profile-statusMessage\">");
sb.append(StringEscapeUtils.escapeHtml(message));
sb.append("</div>");
}
if(StringUtils.isNotBlank(userProfile.getStatus().getDateFormatted())) {
sb.append("<div class=\"profile2-profile-statusDate\">");
sb.append(userProfile.getStatus().getDateFormatted());
sb.append("</div>");
}
}
//basic info
String nickname = userProfile.getNickname();
if(StringUtils.isNotBlank(nickname)) {
sb.append("<div class=\"profile2-profile-nickname\">");
sb.append("<span class=\"profile2-profile-label\">");
sb.append(Messages.getString("Label.nickname"));
sb.append("</span>");
sb.append(StringEscapeUtils.escapeHtml(nickname).toString());
sb.append("</div>");
}
if(StringUtils.isNotBlank(userProfile.getPersonalSummary())) {
sb.append("<div class=\"profile2-profile-personalSummary\">");
sb.append("<span class=\"profile2-profile-label\">");
sb.append(Messages.getString("Label.personalSummary"));
sb.append("</span>");
//PRFL-389 abbreviate long personal summary
int maxLength = Integer.parseInt(sakaiProxy.getServerConfigurationParameter("profile2.formatted.profile.summary.max", ProfileConstants.FORMATTED_PROFILE_SUMMARY_MAX_LENGTH));
sb.append(ProfileUtils.truncateAndAbbreviate(ProfileUtils.processHtml(userProfile.getPersonalSummary()), maxLength, true));
sb.append("</div>");
}
//contact info
if(StringUtils.isNotBlank(userProfile.getEmail())) {
sb.append("<div class=\"profile2-profile-email\">");
sb.append("<span class=\"profile2-profile-label\">");
sb.append(Messages.getString("Label.email"));
sb.append("</span>");
sb.append(userProfile.getEmail());
sb.append("</div>");
}
if(StringUtils.isNotBlank(userProfile.getHomepage())) {
sb.append("<div class=\"profile2-profile-homepage\">");
sb.append("<span class=\"profile2-profile-label\">");
sb.append(Messages.getString("Label.homepage"));
sb.append("</span>");
sb.append(userProfile.getHomepage());
sb.append("</div>");
}
if(StringUtils.isNotBlank(userProfile.getHomephone())) {
sb.append("<div class=\"profile2-profile-homephone\">");
sb.append("<span class=\"profile2-profile-label\">");
sb.append(Messages.getString("Label.homephone"));
sb.append("</span>");
sb.append(userProfile.getHomephone());
sb.append("</div>");
}
if(StringUtils.isNotBlank(userProfile.getWorkphone())) {
sb.append("<div class=\"profile2-profile-workphone\">");
sb.append("<span class=\"profile2-profile-label\">");
sb.append(Messages.getString("Label.workphone"));
sb.append("</span>");
sb.append(userProfile.getWorkphone());
sb.append("</div>");
}
if(StringUtils.isNotBlank(userProfile.getMobilephone())) {
sb.append("<div class=\"profile2-profile-mobilephone\">");
sb.append("<span class=\"profile2-profile-label\">");
sb.append(Messages.getString("Label.mobilephone"));
sb.append("</span>");
sb.append(userProfile.getMobilephone());
sb.append("</div>");
}
if(StringUtils.isNotBlank(userProfile.getFacsimile())) {
sb.append("<div class=\"profile2-profile-facsimile\">");
sb.append("<span class=\"profile2-profile-label\">");
sb.append(Messages.getString("Label.facsimile"));
sb.append("</span>");
sb.append(userProfile.getFacsimile());
sb.append("</div>");
}
//academic info
String position = userProfile.getPosition();
if(StringUtils.isNotBlank(position)) {
sb.append("<div class=\"profile2-profile-position\">");
sb.append("<span class=\"profile2-profile-label\">");
sb.append(Messages.getString("Label.position"));
sb.append("</span>");
sb.append(StringEscapeUtils.escapeHtml(position));
sb.append("</div>");
}
String department = userProfile.getDepartment();
if(StringUtils.isNotBlank(department)) {
sb.append("<div class=\"profile2-profile-department\">");
sb.append("<span class=\"profile2-profile-label\">");
sb.append(Messages.getString("Label.department"));
sb.append("</span>");
sb.append(StringEscapeUtils.escapeHtml(department));
sb.append("</div>");
}
String school = userProfile.getSchool();
if(StringUtils.isNotBlank(school)) {
sb.append("<div class=\"profile2-profile-school\">");
sb.append("<span class=\"profile2-profile-label\">");
sb.append(Messages.getString("Label.school"));
sb.append("</span>");
sb.append(StringEscapeUtils.escapeHtml(school));
sb.append("</div>");
}
String room = userProfile.getRoom();
if(StringUtils.isNotBlank(room)) {
sb.append("<div class=\"profile2-profile-room\">");
sb.append("<span class=\"profile2-profile-label\">");
sb.append(Messages.getString("Label.room"));
sb.append("</span>");
sb.append(StringEscapeUtils.escapeHtml(room));
sb.append("</div>");
}
String course = userProfile.getCourse();
if(StringUtils.isNotBlank(course)) {
sb.append("<div class=\"profile2-profile-course\">");
sb.append("<span class=\"profile2-profile-label\">");
sb.append(Messages.getString("Label.course"));
sb.append("</span>");
sb.append(StringEscapeUtils.escapeHtml(course));
sb.append("</div>");
}
String subjects = userProfile.getSubjects();
if(StringUtils.isNotBlank(subjects)) {
sb.append("<div class=\"profile2-profile-subjects\">");
sb.append("<span class=\"profile2-profile-label\">");
sb.append(Messages.getString("Label.subjects"));
sb.append("</span>");
sb.append(StringEscapeUtils.escapeHtml(subjects));
sb.append("</div>");
}
//personal info
String favouriteBooks = userProfile.getFavouriteBooks();
if(StringUtils.isNotBlank(favouriteBooks)) {
sb.append("<div class=\"profile2-profile-favouriteBooks\">");
sb.append("<span class=\"profile2-profile-label\">");
sb.append(Messages.getString("Label.favouriteBooks"));
sb.append("</span>");
sb.append(StringEscapeUtils.escapeHtml(favouriteBooks));
sb.append("</div>");
}
String favouriteTvShows = userProfile.getFavouriteTvShows();
if(StringUtils.isNotBlank(favouriteTvShows)) {
sb.append("<div class=\"profile2-profile-favouriteTvShows\">");
sb.append("<span class=\"profile2-profile-label\">");
sb.append(Messages.getString("Label.favouriteTvShows"));
sb.append("</span>");
sb.append(StringEscapeUtils.escapeHtml(favouriteTvShows));
sb.append("</div>");
}
String favouriteMovies = userProfile.getFavouriteMovies();
if(StringUtils.isNotBlank(favouriteMovies)) {
sb.append("<div class=\"profile2-profile-favouriteMovies\">");
sb.append("<span class=\"profile2-profile-label\">");
sb.append(Messages.getString("Label.favouriteMovies"));
sb.append("</span>");
sb.append(StringEscapeUtils.escapeHtml(favouriteMovies));
sb.append("</div>");
}
String favouriteQuotes = userProfile.getFavouriteQuotes();
if(StringUtils.isNotBlank(favouriteQuotes)) {
sb.append("<div class=\"profile2-profile-favouriteQuotes\">");
sb.append("<span class=\"profile2-profile-label\">");
sb.append(Messages.getString("Label.favouriteQuotes"));
sb.append("</span>");
sb.append(StringEscapeUtils.escapeHtml(favouriteQuotes));
sb.append("</div>");
}
sb.append("</div>");
sb.append("</div>");
//add the stylesheet
sb.append("<link href=\"");
sb.append(ProfileConstants.ENTITY_CSS_PROFILE);
sb.append("\" type=\"text/css\" rel=\"stylesheet\" media=\"all\" />");
return sb.toString();
}
|
diff --git a/insight/insight-camel/src/main/java/org/fusesource/insight/camel/breadcrumb/Breadcrumbs.java b/insight/insight-camel/src/main/java/org/fusesource/insight/camel/breadcrumb/Breadcrumbs.java
index b72822ad9..744190aa1 100644
--- a/insight/insight-camel/src/main/java/org/fusesource/insight/camel/breadcrumb/Breadcrumbs.java
+++ b/insight/insight-camel/src/main/java/org/fusesource/insight/camel/breadcrumb/Breadcrumbs.java
@@ -1,106 +1,107 @@
/**
* Copyright (C) FuseSource, Inc.
* http://fusesource.com
*
* 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.fusesource.insight.camel.breadcrumb;
import org.apache.camel.CamelContext;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.api.management.ManagedResource;
import org.apache.camel.model.ProcessorDefinition;
import org.apache.camel.spi.ProcessorFactory;
import org.apache.camel.spi.RouteContext;
import org.fusesource.insight.camel.base.SwitchableContainerStrategy;
import java.util.HashSet;
import java.util.Set;
/**
*
*/
@ManagedResource(description = "Breadcrumbs")
public class Breadcrumbs extends SwitchableContainerStrategy implements BreadcrumbsMBean {
public static final String BREADCRUMB = "ExtendedBreadcrumb";
public Breadcrumbs() {
enable();
}
@Override
public void manage(CamelContext context) throws Exception {
final ProcessorFactory delegate = context.getProcessorFactory();
context.setProcessorFactory(new ProcessorFactory() {
@Override
public Processor createChildProcessor(RouteContext routeContext, ProcessorDefinition<?> definition, boolean mandatory) throws Exception {
Processor proc = delegate != null ? delegate.createChildProcessor(routeContext, definition, mandatory)
: definition.createOutputsProcessor(routeContext);
return wrap(routeContext, definition, proc);
}
@Override
public Processor createProcessor(RouteContext routeContext, ProcessorDefinition<?> definition) throws Exception {
Processor proc = delegate != null ? delegate.createProcessor(routeContext, definition)
: definition.createProcessor(routeContext);
return wrap(routeContext, definition, proc);
}
});
}
public Processor wrap(RouteContext routeContext, ProcessorDefinition<?> definition, Processor processor) {
if (processor == null) {
return null;
}
return new BreadcrumbsProcessor(this, processor);
}
public static Set<String> getBreadcrumbs(Exchange exchange) {
Object val = exchange.getIn().getHeader(BREADCRUMB);
Set<String> breadcrumbs;
if (val instanceof BreadcrumbSet) {
return (BreadcrumbSet) val;
}
breadcrumbs = new BreadcrumbSet();
+ exchange.getIn().setHeader(BREADCRUMB, breadcrumbs);
if (val instanceof Iterable) {
for (Object o : ((Iterable) val)) {
if (o != null) {
breadcrumbs.add(o.toString());
}
}
} else if (val != null) {
breadcrumbs.add(val.toString());
}
return breadcrumbs;
}
public static Set<String> getBreadcrumbs(Exchange... exchanges) {
Set<String> breadcrumbs = new BreadcrumbSet();
for (Exchange exchange : exchanges) {
if (exchange != null) {
breadcrumbs.addAll(getBreadcrumbs(exchange));
}
}
return breadcrumbs;
}
public static void setBreadcrumbs(Exchange exchange, Set<String> breadcrumbs) {
exchange.getIn().setHeader(BREADCRUMB, breadcrumbs);
}
private static class BreadcrumbSet extends HashSet<String> {
}
}
| true | true | public static Set<String> getBreadcrumbs(Exchange exchange) {
Object val = exchange.getIn().getHeader(BREADCRUMB);
Set<String> breadcrumbs;
if (val instanceof BreadcrumbSet) {
return (BreadcrumbSet) val;
}
breadcrumbs = new BreadcrumbSet();
if (val instanceof Iterable) {
for (Object o : ((Iterable) val)) {
if (o != null) {
breadcrumbs.add(o.toString());
}
}
} else if (val != null) {
breadcrumbs.add(val.toString());
}
return breadcrumbs;
}
| public static Set<String> getBreadcrumbs(Exchange exchange) {
Object val = exchange.getIn().getHeader(BREADCRUMB);
Set<String> breadcrumbs;
if (val instanceof BreadcrumbSet) {
return (BreadcrumbSet) val;
}
breadcrumbs = new BreadcrumbSet();
exchange.getIn().setHeader(BREADCRUMB, breadcrumbs);
if (val instanceof Iterable) {
for (Object o : ((Iterable) val)) {
if (o != null) {
breadcrumbs.add(o.toString());
}
}
} else if (val != null) {
breadcrumbs.add(val.toString());
}
return breadcrumbs;
}
|
diff --git a/izpack-src/trunk/src/lib/com/izforge/izpack/installer/Unpacker.java b/izpack-src/trunk/src/lib/com/izforge/izpack/installer/Unpacker.java
index 32fde411..ca071d6c 100644
--- a/izpack-src/trunk/src/lib/com/izforge/izpack/installer/Unpacker.java
+++ b/izpack-src/trunk/src/lib/com/izforge/izpack/installer/Unpacker.java
@@ -1,601 +1,606 @@
/*
* $Id$
* IzPack - Copyright 2001-2008 Julien Ponge, All Rights Reserved.
*
* http://izpack.org/
* http://izpack.codehaus.org/
*
* Copyright 2001 Johannes Lehtinen
*
* 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.izforge.izpack.installer;
import com.izforge.izpack.*;
import com.izforge.izpack.event.InstallerListener;
import com.izforge.izpack.util.*;
import java.io.*;
import java.lang.reflect.Constructor;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.jar.Pack200;
/**
* Unpacker class.
*
* @author Julien Ponge
* @author Johannes Lehtinen
*/
public class Unpacker extends UnpackerBase
{
private static final String tempSubPath = "/IzpackWebTemp";
private Pack200.Unpacker unpacker;
/**
* The constructor.
*
* @param idata The installation data.
* @param handler The installation progress handler.
*/
public Unpacker(AutomatedInstallData idata, AbstractUIProgressHandler handler)
{
super(idata, handler);
}
/* (non-Javadoc)
* @see com.izforge.izpack.installer.IUnpacker#run()
*/
public void run()
{
addToInstances();
try
{
//
// Initialisations
FileOutputStream out = null;
ArrayList<ParsableFile> parsables = new ArrayList<ParsableFile>();
ArrayList<ExecutableFile> executables = new ArrayList<ExecutableFile>();
ArrayList<UpdateCheck> updatechecks = new ArrayList<UpdateCheck>();
List packs = idata.selectedPacks;
int npacks = packs.size();
handler.startAction("Unpacking", npacks);
udata = UninstallData.getInstance();
// Custom action listener stuff --- load listeners ----
List[] customActions = getCustomActions();
// Custom action listener stuff --- beforePacks ----
informListeners(customActions, InstallerListener.BEFORE_PACKS, idata, npacks, handler);
packs = idata.selectedPacks;
npacks = packs.size();
// We unpack the selected packs
for (int i = 0; i < npacks; i++)
{
// We get the pack stream
//int n = idata.allPacks.indexOf(packs.get(i));
Pack p = (Pack) packs.get(i);
// evaluate condition
if (p.hasCondition())
{
if (rules != null)
{
if (!rules.isConditionTrue(p.getCondition()))
{
// skip pack, condition is not fullfilled.
continue;
}
}
else
{
// TODO: skip pack, because condition can not be checked
}
}
// Custom action listener stuff --- beforePack ----
informListeners(customActions, InstallerListener.BEFORE_PACK, packs.get(i),
npacks, handler);
ObjectInputStream objIn = new ObjectInputStream(getPackAsStream(p.id, p.uninstall));
// We unpack the files
int nfiles = objIn.readInt();
// We get the internationalized name of the pack
final Pack pack = ((Pack) packs.get(i));
String stepname = pack.name;// the message to be passed to the
// installpanel
if (langpack != null && !(pack.id == null || "".equals(pack.id)))
{
final String name = langpack.getString(pack.id);
if (name != null && !"".equals(name))
{
stepname = name;
}
}
handler.nextStep(stepname, i + 1, nfiles);
for (int j = 0; j < nfiles; j++)
{
// We read the header
PackFile pf = (PackFile) objIn.readObject();
// TODO: reaction if condition can not be checked
if (pf.hasCondition() && (rules != null))
{
if (!rules.isConditionTrue(pf.getCondition()))
{
if (!pf.isBackReference()){
// skip, condition is not fulfilled
objIn.skip(pf.length());
}
continue;
}
}
if (OsConstraint.oneMatchesCurrentSystem(pf.osConstraints()))
{
// We translate & build the path
String path = IoHelper.translatePath(pf.getTargetPath(), vs);
File pathFile = new File(path);
File dest = pathFile;
if (!pf.isDirectory())
{
dest = pathFile.getParentFile();
}
if (!dest.exists())
{
// If there are custom actions which would be called
// at
// creating a directory, create it recursively.
List fileListeners = customActions[customActions.length - 1];
if (fileListeners != null && fileListeners.size() > 0)
{
mkDirsWithEnhancement(dest, pf, customActions);
}
else
// Create it in on step.
{
if (!dest.mkdirs())
{
handler.emitError("Error creating directories",
"Could not create directory\n" + dest.getPath());
handler.stopAction();
this.result = false;
return;
}
}
}
if (pf.isDirectory())
{
continue;
}
// Custom action listener stuff --- beforeFile ----
informListeners(customActions, InstallerListener.BEFORE_FILE, pathFile, pf,
null);
// We add the path to the log,
udata.addFile(path, pack.uninstall);
handler.progress(j, path);
// if this file exists and should not be overwritten,
// check
// what to do
if ((pathFile.exists()) && (pf.override() != PackFile.OVERRIDE_TRUE))
{
boolean overwritefile = false;
// don't overwrite file if the user said so
if (pf.override() != PackFile.OVERRIDE_FALSE)
{
if (pf.override() == PackFile.OVERRIDE_TRUE)
{
overwritefile = true;
}
else if (pf.override() == PackFile.OVERRIDE_UPDATE)
{
// check mtime of involved files
// (this is not 100% perfect, because the
// already existing file might
// still be modified but the new installed
// is just a bit newer; we would
// need the creation time of the existing
// file or record with which mtime
// it was installed...)
overwritefile = (pathFile.lastModified() < pf.lastModified());
}
else
{
int def_choice = -1;
if (pf.override() == PackFile.OVERRIDE_ASK_FALSE)
{
def_choice = AbstractUIHandler.ANSWER_NO;
}
if (pf.override() == PackFile.OVERRIDE_ASK_TRUE)
{
def_choice = AbstractUIHandler.ANSWER_YES;
}
int answer = handler.askQuestion(idata.langpack
.getString("InstallPanel.overwrite.title")
+ " - " + pathFile.getName(), idata.langpack
.getString("InstallPanel.overwrite.question")
+ pathFile.getAbsolutePath(),
AbstractUIHandler.CHOICES_YES_NO, def_choice);
overwritefile = (answer == AbstractUIHandler.ANSWER_YES);
}
}
if (!overwritefile)
{
if (!pf.isBackReference() && !((Pack) packs.get(i)).loose)
{
objIn.skip(pf.length());
}
continue;
}
}
// We copy the file
InputStream pis = objIn;
if (pf.isBackReference())
{
InputStream is = getPackAsStream(pf.previousPackId, pack.uninstall);
pis = new ObjectInputStream(is);
// must wrap for blockdata use by objectstream
// (otherwise strange result)
// skip on underlaying stream (for some reason not
// possible on ObjectStream)
is.skip(pf.offsetInPreviousPack - 4);
// but the stream header is now already read (== 4
// bytes)
}
else if (((Pack) packs.get(i)).loose)
{
/* Old way of doing the job by using the (absolute) sourcepath.
* Since this is very likely to fail and does not confirm to the documentation,
* prefer using relative path's
pis = new FileInputStream(pf.sourcePath);
*/
File resolvedFile = new File(getAbsolutInstallSource(), pf
.getRelativeSourcePath());
if (!resolvedFile.exists())
{
//try alternative destination - the current working directory
//user.dir is likely (depends on launcher type) the current directory of the executable or jar-file...
final File userDir = new File(System.getProperty("user.dir"));
resolvedFile = new File(userDir, pf.getRelativeSourcePath());
}
if (resolvedFile.exists())
{
pis = new FileInputStream(resolvedFile);
//may have a different length & last modified than we had at compiletime, therefore we have to build a new PackFile for the copy process...
pf = new PackFile(resolvedFile.getParentFile(), resolvedFile, pf.getTargetPath(), pf.osConstraints(), pf.override(), pf.getAdditionals());
}
else
{
//file not found
//issue a warning (logging api pending)
//since this file was loosely bundled, we continue with the installation.
System.out.println("Could not find loosely bundled file: " + pf.getRelativeSourcePath());
out.close();
continue;
}
}
if (pf.isPack200Jar())
{
int key = objIn.readInt();
InputStream pack200Input = Unpacker.class.getResourceAsStream("/packs/pack200-" + key);
Pack200.Unpacker unpacker = getPack200Unpacker();
java.util.jar.JarOutputStream jarOut = new java.util.jar.JarOutputStream(new FileOutputStream(pathFile));
unpacker.unpack(pack200Input, jarOut);
jarOut.close();
}
else
{
out = new FileOutputStream(pathFile);
byte[] buffer = new byte[5120];
long bytesCopied = 0;
while (bytesCopied < pf.length())
{
if (performInterrupted())
{ // Interrupt was initiated; perform it.
out.close();
if (pis != objIn)
{
pis.close();
}
return;
}
int maxBytes = (int) Math.min(pf.length() - bytesCopied, buffer.length);
int bytesInBuffer = pis.read(buffer, 0, maxBytes);
if (bytesInBuffer == -1)
{
throw new IOException("Unexpected end of stream (installer corrupted?)");
}
out.write(buffer, 0, bytesInBuffer);
bytesCopied += bytesInBuffer;
}
out.close();
}
if (pis != objIn)
{
pis.close();
}
// Set file modification time if specified
if (pf.lastModified() >= 0)
{
pathFile.setLastModified(pf.lastModified());
}
// Custom action listener stuff --- afterFile ----
informListeners(customActions, InstallerListener.AFTER_FILE, pathFile, pf,
null);
}
else
{
if (!pf.isBackReference())
{
objIn.skip(pf.length());
}
}
}
// Load information about parsable files
int numParsables = objIn.readInt();
for (int k = 0; k < numParsables; k++)
{
ParsableFile pf = (ParsableFile) objIn.readObject();
if (pf.hasCondition() && (rules != null))
{
if (!rules.isConditionTrue(pf.getCondition()))
{
// skip, condition is not fulfilled
continue;
}
}
pf.path = IoHelper.translatePath(pf.path, vs);
parsables.add(pf);
}
// Load information about executable files
int numExecutables = objIn.readInt();
for (int k = 0; k < numExecutables; k++)
{
ExecutableFile ef = (ExecutableFile) objIn.readObject();
if (ef.hasCondition() && (rules != null))
{
if (!rules.isConditionTrue(ef.getCondition()))
{
// skip, condition is false
continue;
}
}
ef.path = IoHelper.translatePath(ef.path, vs);
if (null != ef.argList && !ef.argList.isEmpty())
{
String arg = null;
for (int j = 0; j < ef.argList.size(); j++)
{
arg = ef.argList.get(j);
arg = IoHelper.translatePath(arg, vs);
ef.argList.set(j, arg);
}
}
executables.add(ef);
if (ef.executionStage == ExecutableFile.UNINSTALL)
{
udata.addExecutable(ef);
}
}
// Custom action listener stuff --- uninstall data ----
handleAdditionalUninstallData(udata, customActions);
// Load information about updatechecks
int numUpdateChecks = objIn.readInt();
for (int k = 0; k < numUpdateChecks; k++)
{
UpdateCheck uc = (UpdateCheck) objIn.readObject();
updatechecks.add(uc);
}
objIn.close();
if (performInterrupted())
{ // Interrupt was initiated; perform it.
return;
}
// Custom action listener stuff --- afterPack ----
informListeners(customActions, InstallerListener.AFTER_PACK, packs.get(i),
i, handler);
}
// We use the scripts parser
ScriptParser parser = new ScriptParser(parsables, vs);
parser.parseFiles();
if (performInterrupted())
{ // Interrupt was initiated; perform it.
return;
}
// We use the file executor
FileExecutor executor = new FileExecutor(executables);
if (executor.executeFiles(ExecutableFile.POSTINSTALL, handler) != 0)
{
handler.emitError("File execution failed", "The installation was not completed");
this.result = false;
}
if (performInterrupted())
{ // Interrupt was initiated; perform it.
return;
}
// We put the uninstaller (it's not yet complete...)
putUninstaller();
// update checks _after_ uninstaller was put, so we don't delete it
performUpdateChecks(updatechecks);
if (performInterrupted())
{ // Interrupt was initiated; perform it.
return;
}
// Custom action listener stuff --- afterPacks ----
informListeners(customActions, InstallerListener.AFTER_PACKS, idata, handler, null);
if (performInterrupted())
{ // Interrupt was initiated; perform it.
return;
}
// write installation information
writeInstallationInformation();
// The end :-)
handler.stopAction();
}
catch (Exception err)
{
// TODO: finer grained error handling with useful error messages
handler.stopAction();
- if ("Installation cancelled".equals(err.getMessage()))
+ String message = err.getMessage();
+ if ("Installation cancelled".equals(message))
{
handler.emitNotification("Installation cancelled");
}
else
{
- handler.emitError("An error occured", err.getMessage());
+ if (message == null || message.isEmpty())
+ {
+ message = "Internal error occured : " + err.toString();
+ }
+ handler.emitError("An error occured", message);
err.printStackTrace();
}
this.result = false;
Housekeeper.getInstance().shutDown(4);
}
finally
{
removeFromInstances();
}
}
private Pack200.Unpacker getPack200Unpacker()
{
if (unpacker == null)
{
unpacker = Pack200.newUnpacker();
}
return unpacker;
}
/**
* Returns a stream to a pack, location depending on if it's web based.
*
* @param uninstall true if pack must be uninstalled
* @return The stream or null if it could not be found.
* @throws Exception Description of the Exception
*/
private InputStream getPackAsStream(String packid, boolean uninstall) throws Exception
{
InputStream in = null;
String webDirURL = idata.info.getWebDirURL();
packid = "-" + packid;
if (webDirURL == null) // local
{
in = Unpacker.class.getResourceAsStream("/packs/pack" + packid);
}
else
// web based
{
// TODO: Look first in same directory as primary jar
// This may include prompting for changing of media
// TODO: download and cache them all before starting copy process
// See compiler.Packager#getJarOutputStream for the counterpart
String baseName = idata.info.getInstallerBase();
String packURL = webDirURL + "/" + baseName + ".pack" + packid + ".jar";
String tf = IoHelper.translatePath(idata.info.getUninstallerPath()+ Unpacker.tempSubPath, vs);
String tempfile;
try
{
tempfile = WebRepositoryAccessor.getCachedUrl(packURL, tf);
udata.addFile(tempfile, uninstall);
}
catch (Exception e)
{
if ("Cancelled".equals(e.getMessage()))
{
throw new InstallerException("Installation cancelled", e);
}
else
{
throw new InstallerException("Installation failed", e);
}
}
URL url = new URL("jar:" + tempfile + "!/packs/pack" + packid);
//URL url = new URL("jar:" + packURL + "!/packs/pack" + packid);
// JarURLConnection jarConnection = (JarURLConnection)
// url.openConnection();
// TODO: what happens when using an automated installer?
in = new WebAccessor(null).openInputStream(url);
// TODO: Fails miserably when pack jars are not found, so this is
// temporary
if (in == null)
{
throw new InstallerException(url.toString() + " not available", new FileNotFoundException(url.toString()));
}
}
if (in != null && idata.info.getPackDecoderClassName() != null)
{
Class<Object> decoder = (Class<Object>) Class.forName(idata.info.getPackDecoderClassName());
Class[] paramsClasses = new Class[1];
paramsClasses[0] = Class.forName("java.io.InputStream");
Constructor<Object> constructor = decoder.getDeclaredConstructor(paramsClasses);
// Our first used decoder input stream (bzip2) reads byte for byte from
// the source. Therefore we put a buffering stream between it and the
// source.
InputStream buffer = new BufferedInputStream(in);
Object[] params = {buffer};
Object instance = null;
instance = constructor.newInstance(params);
if (!InputStream.class.isInstance(instance))
{
throw new InstallerException("'" + idata.info.getPackDecoderClassName()
+ "' must be derived from "
+ InputStream.class.toString());
}
in = (InputStream) instance;
}
return in;
}
}
| false | true | public void run()
{
addToInstances();
try
{
//
// Initialisations
FileOutputStream out = null;
ArrayList<ParsableFile> parsables = new ArrayList<ParsableFile>();
ArrayList<ExecutableFile> executables = new ArrayList<ExecutableFile>();
ArrayList<UpdateCheck> updatechecks = new ArrayList<UpdateCheck>();
List packs = idata.selectedPacks;
int npacks = packs.size();
handler.startAction("Unpacking", npacks);
udata = UninstallData.getInstance();
// Custom action listener stuff --- load listeners ----
List[] customActions = getCustomActions();
// Custom action listener stuff --- beforePacks ----
informListeners(customActions, InstallerListener.BEFORE_PACKS, idata, npacks, handler);
packs = idata.selectedPacks;
npacks = packs.size();
// We unpack the selected packs
for (int i = 0; i < npacks; i++)
{
// We get the pack stream
//int n = idata.allPacks.indexOf(packs.get(i));
Pack p = (Pack) packs.get(i);
// evaluate condition
if (p.hasCondition())
{
if (rules != null)
{
if (!rules.isConditionTrue(p.getCondition()))
{
// skip pack, condition is not fullfilled.
continue;
}
}
else
{
// TODO: skip pack, because condition can not be checked
}
}
// Custom action listener stuff --- beforePack ----
informListeners(customActions, InstallerListener.BEFORE_PACK, packs.get(i),
npacks, handler);
ObjectInputStream objIn = new ObjectInputStream(getPackAsStream(p.id, p.uninstall));
// We unpack the files
int nfiles = objIn.readInt();
// We get the internationalized name of the pack
final Pack pack = ((Pack) packs.get(i));
String stepname = pack.name;// the message to be passed to the
// installpanel
if (langpack != null && !(pack.id == null || "".equals(pack.id)))
{
final String name = langpack.getString(pack.id);
if (name != null && !"".equals(name))
{
stepname = name;
}
}
handler.nextStep(stepname, i + 1, nfiles);
for (int j = 0; j < nfiles; j++)
{
// We read the header
PackFile pf = (PackFile) objIn.readObject();
// TODO: reaction if condition can not be checked
if (pf.hasCondition() && (rules != null))
{
if (!rules.isConditionTrue(pf.getCondition()))
{
if (!pf.isBackReference()){
// skip, condition is not fulfilled
objIn.skip(pf.length());
}
continue;
}
}
if (OsConstraint.oneMatchesCurrentSystem(pf.osConstraints()))
{
// We translate & build the path
String path = IoHelper.translatePath(pf.getTargetPath(), vs);
File pathFile = new File(path);
File dest = pathFile;
if (!pf.isDirectory())
{
dest = pathFile.getParentFile();
}
if (!dest.exists())
{
// If there are custom actions which would be called
// at
// creating a directory, create it recursively.
List fileListeners = customActions[customActions.length - 1];
if (fileListeners != null && fileListeners.size() > 0)
{
mkDirsWithEnhancement(dest, pf, customActions);
}
else
// Create it in on step.
{
if (!dest.mkdirs())
{
handler.emitError("Error creating directories",
"Could not create directory\n" + dest.getPath());
handler.stopAction();
this.result = false;
return;
}
}
}
if (pf.isDirectory())
{
continue;
}
// Custom action listener stuff --- beforeFile ----
informListeners(customActions, InstallerListener.BEFORE_FILE, pathFile, pf,
null);
// We add the path to the log,
udata.addFile(path, pack.uninstall);
handler.progress(j, path);
// if this file exists and should not be overwritten,
// check
// what to do
if ((pathFile.exists()) && (pf.override() != PackFile.OVERRIDE_TRUE))
{
boolean overwritefile = false;
// don't overwrite file if the user said so
if (pf.override() != PackFile.OVERRIDE_FALSE)
{
if (pf.override() == PackFile.OVERRIDE_TRUE)
{
overwritefile = true;
}
else if (pf.override() == PackFile.OVERRIDE_UPDATE)
{
// check mtime of involved files
// (this is not 100% perfect, because the
// already existing file might
// still be modified but the new installed
// is just a bit newer; we would
// need the creation time of the existing
// file or record with which mtime
// it was installed...)
overwritefile = (pathFile.lastModified() < pf.lastModified());
}
else
{
int def_choice = -1;
if (pf.override() == PackFile.OVERRIDE_ASK_FALSE)
{
def_choice = AbstractUIHandler.ANSWER_NO;
}
if (pf.override() == PackFile.OVERRIDE_ASK_TRUE)
{
def_choice = AbstractUIHandler.ANSWER_YES;
}
int answer = handler.askQuestion(idata.langpack
.getString("InstallPanel.overwrite.title")
+ " - " + pathFile.getName(), idata.langpack
.getString("InstallPanel.overwrite.question")
+ pathFile.getAbsolutePath(),
AbstractUIHandler.CHOICES_YES_NO, def_choice);
overwritefile = (answer == AbstractUIHandler.ANSWER_YES);
}
}
if (!overwritefile)
{
if (!pf.isBackReference() && !((Pack) packs.get(i)).loose)
{
objIn.skip(pf.length());
}
continue;
}
}
// We copy the file
InputStream pis = objIn;
if (pf.isBackReference())
{
InputStream is = getPackAsStream(pf.previousPackId, pack.uninstall);
pis = new ObjectInputStream(is);
// must wrap for blockdata use by objectstream
// (otherwise strange result)
// skip on underlaying stream (for some reason not
// possible on ObjectStream)
is.skip(pf.offsetInPreviousPack - 4);
// but the stream header is now already read (== 4
// bytes)
}
else if (((Pack) packs.get(i)).loose)
{
/* Old way of doing the job by using the (absolute) sourcepath.
* Since this is very likely to fail and does not confirm to the documentation,
* prefer using relative path's
pis = new FileInputStream(pf.sourcePath);
*/
File resolvedFile = new File(getAbsolutInstallSource(), pf
.getRelativeSourcePath());
if (!resolvedFile.exists())
{
//try alternative destination - the current working directory
//user.dir is likely (depends on launcher type) the current directory of the executable or jar-file...
final File userDir = new File(System.getProperty("user.dir"));
resolvedFile = new File(userDir, pf.getRelativeSourcePath());
}
if (resolvedFile.exists())
{
pis = new FileInputStream(resolvedFile);
//may have a different length & last modified than we had at compiletime, therefore we have to build a new PackFile for the copy process...
pf = new PackFile(resolvedFile.getParentFile(), resolvedFile, pf.getTargetPath(), pf.osConstraints(), pf.override(), pf.getAdditionals());
}
else
{
//file not found
//issue a warning (logging api pending)
//since this file was loosely bundled, we continue with the installation.
System.out.println("Could not find loosely bundled file: " + pf.getRelativeSourcePath());
out.close();
continue;
}
}
if (pf.isPack200Jar())
{
int key = objIn.readInt();
InputStream pack200Input = Unpacker.class.getResourceAsStream("/packs/pack200-" + key);
Pack200.Unpacker unpacker = getPack200Unpacker();
java.util.jar.JarOutputStream jarOut = new java.util.jar.JarOutputStream(new FileOutputStream(pathFile));
unpacker.unpack(pack200Input, jarOut);
jarOut.close();
}
else
{
out = new FileOutputStream(pathFile);
byte[] buffer = new byte[5120];
long bytesCopied = 0;
while (bytesCopied < pf.length())
{
if (performInterrupted())
{ // Interrupt was initiated; perform it.
out.close();
if (pis != objIn)
{
pis.close();
}
return;
}
int maxBytes = (int) Math.min(pf.length() - bytesCopied, buffer.length);
int bytesInBuffer = pis.read(buffer, 0, maxBytes);
if (bytesInBuffer == -1)
{
throw new IOException("Unexpected end of stream (installer corrupted?)");
}
out.write(buffer, 0, bytesInBuffer);
bytesCopied += bytesInBuffer;
}
out.close();
}
if (pis != objIn)
{
pis.close();
}
// Set file modification time if specified
if (pf.lastModified() >= 0)
{
pathFile.setLastModified(pf.lastModified());
}
// Custom action listener stuff --- afterFile ----
informListeners(customActions, InstallerListener.AFTER_FILE, pathFile, pf,
null);
}
else
{
if (!pf.isBackReference())
{
objIn.skip(pf.length());
}
}
}
// Load information about parsable files
int numParsables = objIn.readInt();
for (int k = 0; k < numParsables; k++)
{
ParsableFile pf = (ParsableFile) objIn.readObject();
if (pf.hasCondition() && (rules != null))
{
if (!rules.isConditionTrue(pf.getCondition()))
{
// skip, condition is not fulfilled
continue;
}
}
pf.path = IoHelper.translatePath(pf.path, vs);
parsables.add(pf);
}
// Load information about executable files
int numExecutables = objIn.readInt();
for (int k = 0; k < numExecutables; k++)
{
ExecutableFile ef = (ExecutableFile) objIn.readObject();
if (ef.hasCondition() && (rules != null))
{
if (!rules.isConditionTrue(ef.getCondition()))
{
// skip, condition is false
continue;
}
}
ef.path = IoHelper.translatePath(ef.path, vs);
if (null != ef.argList && !ef.argList.isEmpty())
{
String arg = null;
for (int j = 0; j < ef.argList.size(); j++)
{
arg = ef.argList.get(j);
arg = IoHelper.translatePath(arg, vs);
ef.argList.set(j, arg);
}
}
executables.add(ef);
if (ef.executionStage == ExecutableFile.UNINSTALL)
{
udata.addExecutable(ef);
}
}
// Custom action listener stuff --- uninstall data ----
handleAdditionalUninstallData(udata, customActions);
// Load information about updatechecks
int numUpdateChecks = objIn.readInt();
for (int k = 0; k < numUpdateChecks; k++)
{
UpdateCheck uc = (UpdateCheck) objIn.readObject();
updatechecks.add(uc);
}
objIn.close();
if (performInterrupted())
{ // Interrupt was initiated; perform it.
return;
}
// Custom action listener stuff --- afterPack ----
informListeners(customActions, InstallerListener.AFTER_PACK, packs.get(i),
i, handler);
}
// We use the scripts parser
ScriptParser parser = new ScriptParser(parsables, vs);
parser.parseFiles();
if (performInterrupted())
{ // Interrupt was initiated; perform it.
return;
}
// We use the file executor
FileExecutor executor = new FileExecutor(executables);
if (executor.executeFiles(ExecutableFile.POSTINSTALL, handler) != 0)
{
handler.emitError("File execution failed", "The installation was not completed");
this.result = false;
}
if (performInterrupted())
{ // Interrupt was initiated; perform it.
return;
}
// We put the uninstaller (it's not yet complete...)
putUninstaller();
// update checks _after_ uninstaller was put, so we don't delete it
performUpdateChecks(updatechecks);
if (performInterrupted())
{ // Interrupt was initiated; perform it.
return;
}
// Custom action listener stuff --- afterPacks ----
informListeners(customActions, InstallerListener.AFTER_PACKS, idata, handler, null);
if (performInterrupted())
{ // Interrupt was initiated; perform it.
return;
}
// write installation information
writeInstallationInformation();
// The end :-)
handler.stopAction();
}
catch (Exception err)
{
// TODO: finer grained error handling with useful error messages
handler.stopAction();
if ("Installation cancelled".equals(err.getMessage()))
{
handler.emitNotification("Installation cancelled");
}
else
{
handler.emitError("An error occured", err.getMessage());
err.printStackTrace();
}
this.result = false;
Housekeeper.getInstance().shutDown(4);
}
finally
{
removeFromInstances();
}
}
| public void run()
{
addToInstances();
try
{
//
// Initialisations
FileOutputStream out = null;
ArrayList<ParsableFile> parsables = new ArrayList<ParsableFile>();
ArrayList<ExecutableFile> executables = new ArrayList<ExecutableFile>();
ArrayList<UpdateCheck> updatechecks = new ArrayList<UpdateCheck>();
List packs = idata.selectedPacks;
int npacks = packs.size();
handler.startAction("Unpacking", npacks);
udata = UninstallData.getInstance();
// Custom action listener stuff --- load listeners ----
List[] customActions = getCustomActions();
// Custom action listener stuff --- beforePacks ----
informListeners(customActions, InstallerListener.BEFORE_PACKS, idata, npacks, handler);
packs = idata.selectedPacks;
npacks = packs.size();
// We unpack the selected packs
for (int i = 0; i < npacks; i++)
{
// We get the pack stream
//int n = idata.allPacks.indexOf(packs.get(i));
Pack p = (Pack) packs.get(i);
// evaluate condition
if (p.hasCondition())
{
if (rules != null)
{
if (!rules.isConditionTrue(p.getCondition()))
{
// skip pack, condition is not fullfilled.
continue;
}
}
else
{
// TODO: skip pack, because condition can not be checked
}
}
// Custom action listener stuff --- beforePack ----
informListeners(customActions, InstallerListener.BEFORE_PACK, packs.get(i),
npacks, handler);
ObjectInputStream objIn = new ObjectInputStream(getPackAsStream(p.id, p.uninstall));
// We unpack the files
int nfiles = objIn.readInt();
// We get the internationalized name of the pack
final Pack pack = ((Pack) packs.get(i));
String stepname = pack.name;// the message to be passed to the
// installpanel
if (langpack != null && !(pack.id == null || "".equals(pack.id)))
{
final String name = langpack.getString(pack.id);
if (name != null && !"".equals(name))
{
stepname = name;
}
}
handler.nextStep(stepname, i + 1, nfiles);
for (int j = 0; j < nfiles; j++)
{
// We read the header
PackFile pf = (PackFile) objIn.readObject();
// TODO: reaction if condition can not be checked
if (pf.hasCondition() && (rules != null))
{
if (!rules.isConditionTrue(pf.getCondition()))
{
if (!pf.isBackReference()){
// skip, condition is not fulfilled
objIn.skip(pf.length());
}
continue;
}
}
if (OsConstraint.oneMatchesCurrentSystem(pf.osConstraints()))
{
// We translate & build the path
String path = IoHelper.translatePath(pf.getTargetPath(), vs);
File pathFile = new File(path);
File dest = pathFile;
if (!pf.isDirectory())
{
dest = pathFile.getParentFile();
}
if (!dest.exists())
{
// If there are custom actions which would be called
// at
// creating a directory, create it recursively.
List fileListeners = customActions[customActions.length - 1];
if (fileListeners != null && fileListeners.size() > 0)
{
mkDirsWithEnhancement(dest, pf, customActions);
}
else
// Create it in on step.
{
if (!dest.mkdirs())
{
handler.emitError("Error creating directories",
"Could not create directory\n" + dest.getPath());
handler.stopAction();
this.result = false;
return;
}
}
}
if (pf.isDirectory())
{
continue;
}
// Custom action listener stuff --- beforeFile ----
informListeners(customActions, InstallerListener.BEFORE_FILE, pathFile, pf,
null);
// We add the path to the log,
udata.addFile(path, pack.uninstall);
handler.progress(j, path);
// if this file exists and should not be overwritten,
// check
// what to do
if ((pathFile.exists()) && (pf.override() != PackFile.OVERRIDE_TRUE))
{
boolean overwritefile = false;
// don't overwrite file if the user said so
if (pf.override() != PackFile.OVERRIDE_FALSE)
{
if (pf.override() == PackFile.OVERRIDE_TRUE)
{
overwritefile = true;
}
else if (pf.override() == PackFile.OVERRIDE_UPDATE)
{
// check mtime of involved files
// (this is not 100% perfect, because the
// already existing file might
// still be modified but the new installed
// is just a bit newer; we would
// need the creation time of the existing
// file or record with which mtime
// it was installed...)
overwritefile = (pathFile.lastModified() < pf.lastModified());
}
else
{
int def_choice = -1;
if (pf.override() == PackFile.OVERRIDE_ASK_FALSE)
{
def_choice = AbstractUIHandler.ANSWER_NO;
}
if (pf.override() == PackFile.OVERRIDE_ASK_TRUE)
{
def_choice = AbstractUIHandler.ANSWER_YES;
}
int answer = handler.askQuestion(idata.langpack
.getString("InstallPanel.overwrite.title")
+ " - " + pathFile.getName(), idata.langpack
.getString("InstallPanel.overwrite.question")
+ pathFile.getAbsolutePath(),
AbstractUIHandler.CHOICES_YES_NO, def_choice);
overwritefile = (answer == AbstractUIHandler.ANSWER_YES);
}
}
if (!overwritefile)
{
if (!pf.isBackReference() && !((Pack) packs.get(i)).loose)
{
objIn.skip(pf.length());
}
continue;
}
}
// We copy the file
InputStream pis = objIn;
if (pf.isBackReference())
{
InputStream is = getPackAsStream(pf.previousPackId, pack.uninstall);
pis = new ObjectInputStream(is);
// must wrap for blockdata use by objectstream
// (otherwise strange result)
// skip on underlaying stream (for some reason not
// possible on ObjectStream)
is.skip(pf.offsetInPreviousPack - 4);
// but the stream header is now already read (== 4
// bytes)
}
else if (((Pack) packs.get(i)).loose)
{
/* Old way of doing the job by using the (absolute) sourcepath.
* Since this is very likely to fail and does not confirm to the documentation,
* prefer using relative path's
pis = new FileInputStream(pf.sourcePath);
*/
File resolvedFile = new File(getAbsolutInstallSource(), pf
.getRelativeSourcePath());
if (!resolvedFile.exists())
{
//try alternative destination - the current working directory
//user.dir is likely (depends on launcher type) the current directory of the executable or jar-file...
final File userDir = new File(System.getProperty("user.dir"));
resolvedFile = new File(userDir, pf.getRelativeSourcePath());
}
if (resolvedFile.exists())
{
pis = new FileInputStream(resolvedFile);
//may have a different length & last modified than we had at compiletime, therefore we have to build a new PackFile for the copy process...
pf = new PackFile(resolvedFile.getParentFile(), resolvedFile, pf.getTargetPath(), pf.osConstraints(), pf.override(), pf.getAdditionals());
}
else
{
//file not found
//issue a warning (logging api pending)
//since this file was loosely bundled, we continue with the installation.
System.out.println("Could not find loosely bundled file: " + pf.getRelativeSourcePath());
out.close();
continue;
}
}
if (pf.isPack200Jar())
{
int key = objIn.readInt();
InputStream pack200Input = Unpacker.class.getResourceAsStream("/packs/pack200-" + key);
Pack200.Unpacker unpacker = getPack200Unpacker();
java.util.jar.JarOutputStream jarOut = new java.util.jar.JarOutputStream(new FileOutputStream(pathFile));
unpacker.unpack(pack200Input, jarOut);
jarOut.close();
}
else
{
out = new FileOutputStream(pathFile);
byte[] buffer = new byte[5120];
long bytesCopied = 0;
while (bytesCopied < pf.length())
{
if (performInterrupted())
{ // Interrupt was initiated; perform it.
out.close();
if (pis != objIn)
{
pis.close();
}
return;
}
int maxBytes = (int) Math.min(pf.length() - bytesCopied, buffer.length);
int bytesInBuffer = pis.read(buffer, 0, maxBytes);
if (bytesInBuffer == -1)
{
throw new IOException("Unexpected end of stream (installer corrupted?)");
}
out.write(buffer, 0, bytesInBuffer);
bytesCopied += bytesInBuffer;
}
out.close();
}
if (pis != objIn)
{
pis.close();
}
// Set file modification time if specified
if (pf.lastModified() >= 0)
{
pathFile.setLastModified(pf.lastModified());
}
// Custom action listener stuff --- afterFile ----
informListeners(customActions, InstallerListener.AFTER_FILE, pathFile, pf,
null);
}
else
{
if (!pf.isBackReference())
{
objIn.skip(pf.length());
}
}
}
// Load information about parsable files
int numParsables = objIn.readInt();
for (int k = 0; k < numParsables; k++)
{
ParsableFile pf = (ParsableFile) objIn.readObject();
if (pf.hasCondition() && (rules != null))
{
if (!rules.isConditionTrue(pf.getCondition()))
{
// skip, condition is not fulfilled
continue;
}
}
pf.path = IoHelper.translatePath(pf.path, vs);
parsables.add(pf);
}
// Load information about executable files
int numExecutables = objIn.readInt();
for (int k = 0; k < numExecutables; k++)
{
ExecutableFile ef = (ExecutableFile) objIn.readObject();
if (ef.hasCondition() && (rules != null))
{
if (!rules.isConditionTrue(ef.getCondition()))
{
// skip, condition is false
continue;
}
}
ef.path = IoHelper.translatePath(ef.path, vs);
if (null != ef.argList && !ef.argList.isEmpty())
{
String arg = null;
for (int j = 0; j < ef.argList.size(); j++)
{
arg = ef.argList.get(j);
arg = IoHelper.translatePath(arg, vs);
ef.argList.set(j, arg);
}
}
executables.add(ef);
if (ef.executionStage == ExecutableFile.UNINSTALL)
{
udata.addExecutable(ef);
}
}
// Custom action listener stuff --- uninstall data ----
handleAdditionalUninstallData(udata, customActions);
// Load information about updatechecks
int numUpdateChecks = objIn.readInt();
for (int k = 0; k < numUpdateChecks; k++)
{
UpdateCheck uc = (UpdateCheck) objIn.readObject();
updatechecks.add(uc);
}
objIn.close();
if (performInterrupted())
{ // Interrupt was initiated; perform it.
return;
}
// Custom action listener stuff --- afterPack ----
informListeners(customActions, InstallerListener.AFTER_PACK, packs.get(i),
i, handler);
}
// We use the scripts parser
ScriptParser parser = new ScriptParser(parsables, vs);
parser.parseFiles();
if (performInterrupted())
{ // Interrupt was initiated; perform it.
return;
}
// We use the file executor
FileExecutor executor = new FileExecutor(executables);
if (executor.executeFiles(ExecutableFile.POSTINSTALL, handler) != 0)
{
handler.emitError("File execution failed", "The installation was not completed");
this.result = false;
}
if (performInterrupted())
{ // Interrupt was initiated; perform it.
return;
}
// We put the uninstaller (it's not yet complete...)
putUninstaller();
// update checks _after_ uninstaller was put, so we don't delete it
performUpdateChecks(updatechecks);
if (performInterrupted())
{ // Interrupt was initiated; perform it.
return;
}
// Custom action listener stuff --- afterPacks ----
informListeners(customActions, InstallerListener.AFTER_PACKS, idata, handler, null);
if (performInterrupted())
{ // Interrupt was initiated; perform it.
return;
}
// write installation information
writeInstallationInformation();
// The end :-)
handler.stopAction();
}
catch (Exception err)
{
// TODO: finer grained error handling with useful error messages
handler.stopAction();
String message = err.getMessage();
if ("Installation cancelled".equals(message))
{
handler.emitNotification("Installation cancelled");
}
else
{
if (message == null || message.isEmpty())
{
message = "Internal error occured : " + err.toString();
}
handler.emitError("An error occured", message);
err.printStackTrace();
}
this.result = false;
Housekeeper.getInstance().shutDown(4);
}
finally
{
removeFromInstances();
}
}
|
diff --git a/src/simple/home/jtbuaa/simpleHome.java b/src/simple/home/jtbuaa/simpleHome.java
index 4795ca8..7cd7503 100755
--- a/src/simple/home/jtbuaa/simpleHome.java
+++ b/src/simple/home/jtbuaa/simpleHome.java
@@ -1,1415 +1,1415 @@
package simple.home.jtbuaa;
import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Random;
import base.lib.HanziToPinyin;
import base.lib.util;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.WallpaperManager;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.pm.ApplicationInfo;
import android.content.pm.IPackageStatsObserver;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageStats;
import android.content.pm.ResolveInfo;
import android.content.res.Configuration;
import android.database.ContentObserver;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Parcelable;
import android.os.RemoteException;
import android.preference.PreferenceManager;
import android.provider.CallLog.Calls;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.telephony.TelephonyManager;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class simpleHome extends Activity implements SensorEventListener, sizedRelativeLayout.OnResizeChangeListener {
int homeTab = 1;
AlertDialog restartDialog = null;
AlertDialog hintDialog = null;
//wall paper related
String downloadPath;
SensorManager sensorMgr;
Sensor mSensor;
float last_x, last_y, last_z;
long lastUpdate, lastSet;
ArrayList<String> picList, picList_selected;
boolean shakeWallpaper = false;
boolean busy;
SharedPreferences perferences;
String wallpaperFile = "";
AppAlphaList sysAlphaList, userAlphaList;
//alpha list related
TextView radioText;
RadioGroup radioGroup;
//app list related
private List<View> mListViews;
GridView favoAppList;
ListView sysAppList, userAppList, shortAppList;
ImageView homeBar, shortBar;
String version, myPackageName;
ViewPager mainlayout;
MyPagerAdapter myPagerAdapter;
RelativeLayout home;
ResolveInfo appDetail;
List<ResolveInfo> mAllApps, mFavoApps, mSysApps, mUserApps, mShortApps;
PackageManager pm;
favoAppAdapter favoAdapter;
shortAppAdapter shortAdapter;
ResolveInfo ri_phone, ri_sms, ri_contact;
CallObserver callObserver;
SmsChangeObserver smsObserver;
ImageView shortcut_phone, shortcut_sms, shortcut_contact;
sizedRelativeLayout base;
RelativeLayout apps;
appHandler mAppHandler = new appHandler();
final static int UPDATE_RI_PHONE = 0, UPDATE_RI_SMS = 1, UPDATE_RI_CONTACT = 2, UPDATE_USER = 3, UPDATE_SPLASH = 4;
ContextMenu mMenu;
ricase selected_case;
boolean canRoot;
DisplayMetrics dm;
IBinder token;
//package size related
HashMap<String, Object> packagesSize;
Method getPackageSizeInfo;
IPackageStatsObserver sizeObserver;
static int sizeM = 1024*1024;
static public com.android.internal.telephony.ITelephony getITelephony(TelephonyManager telMgr) throws Exception {
Method getITelephonyMethod = telMgr.getClass().getDeclaredMethod("getITelephony");
getITelephonyMethod.setAccessible(true);//even private function can use this
return (com.android.internal.telephony.ITelephony)getITelephonyMethod.invoke(telMgr);
}
WallpaperManager mWallpaperManager;
class MyPagerAdapter extends PagerAdapter{
@Override
public void destroyItem(View collection, int arg1, Object view) {
((ViewPager) collection).removeView((View) view);
}
@Override
public void finishUpdate(View arg0) {
}
@Override
public int getCount() {
return mListViews.size();
}
@Override
public Object instantiateItem(View arg0, int arg1) {
((ViewPager) arg0).addView(mListViews.get(arg1), 0);
return mListViews.get(arg1);
}
@Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0==(arg1);
}
@Override
public void restoreState(Parcelable arg0, ClassLoader arg1) {
}
@Override
public Parcelable saveState() {
return null;
}
@Override
public void startUpdate(View arg0) {
}
@Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
}
@Override
protected void onResume() {
if (sysAlphaList.appToDel != null) {
String apkToDel = sysAlphaList.appToDel.activityInfo.applicationInfo.sourceDir;
String res = ShellInterface.doExec(new String[] {"ls /data/data/" + sysAlphaList.appToDel.activityInfo.packageName}, true);
if (res.contains("No such file or directory")) {//uninstalled
String[] cmds = {
"rm " + apkToDel + ".bak",
"rm " + apkToDel.replace(".apk", ".odex")};
//ShellInterface.doExec(cmds);// not really delete.
}
else ShellInterface.doExec(new String[] {"mv " + apkToDel + ".bak " + apkToDel});
sysAlphaList.appToDel = null;
}
shakeWallpaper = perferences.getBoolean("shake", false);
if (shakeWallpaper) {
sensorMgr.registerListener(this, mSensor, SensorManager.SENSOR_DELAY_UI);
busy = false;
}
else {
sensorMgr.unregisterListener(this);
}
super.onResume();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
menu.add(0, 0, 0, R.string.wallpaper).setIcon(android.R.drawable.ic_menu_gallery).setAlphabeticShortcut('W');
menu.add(0, 1, 0, R.string.settings).setIcon(android.R.drawable.ic_menu_preferences)
.setIntent(new Intent(android.provider.Settings.ACTION_SETTINGS));
menu.add(0, 2, 0, R.string.help).setIcon(android.R.drawable.ic_menu_help).setAlphabeticShortcut('H');
return true;
}
public boolean onOptionsItemSelected(MenuItem item){
switch (item.getItemId()) {
case 0://wallpaper
final Intent pickWallpaper = new Intent(Intent.ACTION_SET_WALLPAPER);
util.startActivity(Intent.createChooser(pickWallpaper, getString(R.string.wallpaper)), true, getBaseContext());
break;
case 1://settings
return super.onOptionsItemSelected(item);
case 2://help dialog
Intent intent = new Intent("about");
intent.setClassName(getPackageName(), About.class.getName());
intent.putExtra("version", version);
intent.putExtra("filename", wallpaperFile);
util.startActivity(intent, false, getBaseContext());
break;
}
return true;
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
selected_case = (ricase) v.getTag();
switch (selected_case.mCase) {
case 0://on home
menu.add(0, 0, 0, getString(R.string.removeFromFavo));
break;
case 1://on shortcut
menu.add(0, 1, 0, getString(R.string.removeFromShort));
break;
case 2://on app list
if (mainlayout.getCurrentItem() == 0) {
if (sysAlphaList.mIsGrid)
menu.add(0, 8, 0, getString(R.string.list_view));
else
menu.add(0, 8, 0, getString(R.string.grid_view));
}
else if (mainlayout.getCurrentItem() == 2) {
if (userAlphaList.mIsGrid)
menu.add(0, 8, 0, getString(R.string.list_view));
else
menu.add(0, 8, 0, getString(R.string.grid_view));
}
menu.add(0, 7, 0, getString(R.string.hideapp));
menu.add(0, 4, 0, getString(R.string.appdetail));
menu.add(0, 5, 0, getString(R.string.addtoFavo));
menu.add(0, 6, 0, getString(R.string.addtoShort));
mMenu = menu;
break;
}
}
void writeFile(String name) {
try {
FileOutputStream fo = this.openFileOutput(name, 0);
ObjectOutputStream oos = new ObjectOutputStream(fo);
if (name.equals("short")) {
for (int i = 0; i < mShortApps.size(); i++)
oos.writeObject(((ResolveInfo)mShortApps.get(i)).activityInfo.name);
}
else if (name.equals("favo")) {
for (int i = 0; i < mFavoApps.size(); i++)
oos.writeObject(((ResolveInfo)mFavoApps.get(i)).activityInfo.name);
}
oos.flush();
oos.close();
fo.close();
} catch (Exception e) {}
}
boolean backup(String sourceDir) {//copy file to sdcard
String apk = sourceDir.split("/")[sourceDir.split("/").length-1];
FileOutputStream fos;
FileInputStream fis;
String filename = downloadPath + "apk/" + apk;
try {
File target = new File(filename);
fos = new FileOutputStream(target, false);
fis = new FileInputStream(sourceDir);
byte buf[] = new byte[10240];
int readLength = 0;
while((readLength = fis.read(buf))>0){
fos.write(buf, 0, readLength);
}
fos.close();
fis.close();
} catch (Exception e) {
hintDialog.setMessage(e.toString());
hintDialog.show();
return false;
}
return true;
}
public boolean onContextItemSelected(MenuItem item){
super.onContextItemSelected(item);
ResolveInfo info = null;
if (item.getItemId() < 8) info = (ResolveInfo) selected_case.mRi;
switch (item.getItemId()) {
case 0://remove from home
favoAdapter.remove(info);
writeFile("favo");
break;
case 1://remove from shortcut
shortAdapter.remove(info);
writeFile("short"); //save shortcut to file
break;
case 4://get app detail info
showDetail(info.activityInfo.applicationInfo.sourceDir, info.activityInfo.packageName, info.loadLabel(pm), info.loadIcon(pm));
break;
case 5://add to home
if (favoAdapter.getPosition(info) < 0) {
favoAdapter.add(info);
writeFile("favo");
}
break;
case 6://add to shortcut
if (shortAdapter.getPosition(info) < 0) {
shortAdapter.insert(info, 0);
writeFile("short"); //save shortcut to file
}
break;
case 7://hide the ri
if (mainlayout.getCurrentItem() == 0) {
sysAlphaList.remove(info.activityInfo.packageName);
}
else {
userAlphaList.remove(info.activityInfo.packageName);
}
refreshRadioButton();
break;
case 8://switch view
restartDialog.show();
return true;//break can't finish on some device?
case 9://get package detail info
PackageInfo pi = (PackageInfo) selected_case.mRi;
showDetail(pi.applicationInfo.sourceDir, pi.packageName, pi.applicationInfo.loadLabel(pm), pi.applicationInfo.loadIcon(pm));
break;
}
return false;
}
void showDetail(final String sourceDir, final String packageName, final CharSequence label, Drawable icon) {
AlertDialog detailDlg = new AlertDialog.Builder(this).
setTitle(label).
setIcon(icon).
setMessage(packageName + "\n\n" + sourceDir).
setPositiveButton(R.string.share, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_SUBJECT, R.string.share);
String text = label + getString(R.string.app_share_text)
+ "http://bpc.borqs.com/market.html?id=" + packageName;
intent.putExtra(Intent.EXTRA_TEXT, text);
util.startActivity(Intent.createChooser(intent, getString(R.string.sharemode)), true, getBaseContext());
}
}).setNeutralButton(R.string.backapp, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String apk = sourceDir.split("/")[sourceDir.split("/").length-1];
if (backup(sourceDir)) {
String odex = sourceDir.replace(".apk", ".odex");
File target = new File(odex);
boolean backupOdex = true;
if (target.exists())
if (!backup(odex)) backupOdex = false;//backup odex if any
if (backupOdex) {
hintDialog.setMessage(getString(R.string.backapp) + " " +
label + " to " +
downloadPath + "apk/" + apk);
hintDialog.show();
}
}
}
}).
setNegativeButton(R.string.more, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
Intent intent;
if (appDetail != null) {
intent = new Intent(Intent.ACTION_VIEW);
intent.setClassName(appDetail.activityInfo.packageName, appDetail.activityInfo.name);
intent.putExtra("pkg", packageName);
intent.putExtra("com.android.settings.ApplicationPkgName", packageName);
}
else {//2.6 tahiti change the action.
intent = new Intent("android.settings.APPLICATION_DETAILS_SETTINGS", Uri.fromParts("package", packageName, null));
}
util.startActivity(intent, true, getBaseContext());
}
}).create();
boolean canBackup = !downloadPath.startsWith(getFilesDir().getPath());
detailDlg.show();
detailDlg.getButton(DialogInterface.BUTTON_NEUTRAL).setEnabled(canBackup);//not backup if no SDcard.
}
@SuppressWarnings("unchecked")
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
myPackageName = this.getPackageName();
pm = getPackageManager();
version = util.getVersion(this);
try {
getPackageSizeInfo = PackageManager.class.getMethod(
"getPackageSizeInfo", new Class[] {String.class, IPackageStatsObserver.class});
} catch (Exception e) {
e.printStackTrace();
}
sizeObserver = new IPackageStatsObserver.Stub() {
@Override
public void onGetStatsCompleted(PackageStats pStats,
boolean succeeded) throws RemoteException {
long size = pStats.codeSize;
String ssize = new String();
if (size > 10 * sizeM) ssize = size / sizeM + "M";
else if (size > 10 * 1024) ssize = size / 1024 + "K";
else if (size > 0) ssize = size + "B";
else ssize = "";
packagesSize.put(pStats.packageName, ssize);
}
};
packagesSize = new HashMap<String, Object>();
sensorMgr = (SensorManager) getSystemService(SENSOR_SERVICE);
mSensor = sensorMgr.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
perferences = PreferenceManager.getDefaultSharedPreferences(this);
dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
//1,2,3,4 are integer value of small, normal, large and XLARGE screen respectively.
//int screen_size = getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK;
//if (screen_size < Configuration.SCREENLAYOUT_SIZE_LARGE)//disable auto rotate screen for small and normal screen.
//setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
requestWindowFeature(Window.FEATURE_NO_TITLE); //hide titlebar of application, must be before setting the layout
setContentView(R.layout.ads);
home = (RelativeLayout) getLayoutInflater().inflate(R.layout.home, null);
//favorite app tab
favoAppList = (GridView) home.findViewById(R.id.favos);
favoAppList.setVerticalScrollBarEnabled(false);
favoAppList.inflate(this, R.layout.app_list, null);
favoAppList.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View arg0, MotionEvent arg1) {
shortAppList.setVisibility(View.INVISIBLE);
return false;
}
});
shortAppList = (ListView) home.findViewById(R.id.business);
shortAppList.bringToFront();
shortAppList.setVisibility(View.INVISIBLE);
boolean isGrid = perferences.getBoolean("system", true);
sysAlphaList = new AppAlphaList(this, pm, packagesSize, isGrid, dm.widthPixels > 480);
isGrid = perferences.getBoolean("user", false);
userAlphaList = new AppAlphaList(this, pm, packagesSize, isGrid, dm.widthPixels > 480);
mListViews = new ArrayList<View>();
mListViews.add(sysAlphaList.view);
mListViews.add(home);
mListViews.add(userAlphaList.view);
radioText = (TextView) findViewById(R.id.radio_text);
radioGroup = (RadioGroup) findViewById(R.id.radio_hint);
radioGroup.removeViewAt(0);
mWallpaperManager = WallpaperManager.getInstance(this);
mainlayout = (ViewPager)findViewById(R.id.mainFrame);
mainlayout.setLongClickable(true);
myPagerAdapter = new MyPagerAdapter();
mainlayout.setAdapter(myPagerAdapter);
mainlayout.setOnPageChangeListener(new OnPageChangeListener() {
@Override
public void onPageScrollStateChanged(int state) {
if (state == ViewPager.SCROLL_STATE_SETTLING) {
refreshRadioButton();
}
}
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
if (!shakeWallpaper) {//don't move wallpaper if change wallpaper by shake
if (token == null) token = mainlayout.getWindowToken();//any token from a component is ok
mWallpaperManager.setWallpaperOffsets(token,
//when slide from home to systems or from systems to home, the "position" is 0,
//when slide from home to users or from users to home, it is 1.
//positionOffset is from 0 to 1. sometime it will jump from 1 to 0, we just omit it if it is 0.
//so we can unify it to (0, 1) by (positionOffset+position)/2
(positionOffset+position)/(mListViews.size()-1), 0);
}
}
@Override
public void onPageSelected(int arg0) {
}
});
mainlayout.setCurrentItem(homeTab);
mSysApps = new ArrayList<ResolveInfo>();
mUserApps = new ArrayList<ResolveInfo>();
mFavoApps = new ArrayList<ResolveInfo>();
mShortApps = new ArrayList<ResolveInfo>();
favoAdapter = new favoAppAdapter(getBaseContext(), mFavoApps);
favoAppList.setAdapter(favoAdapter);
base = (sizedRelativeLayout) home.findViewById(R.id.base);
base.setResizeListener(this);
homeBar = (ImageView) home.findViewById(R.id.home_bar);
homeBar.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
Intent intent = new Intent(Intent.ACTION_MAIN);
- intent.setClassName("harley.browsers", "harley.lib.HarleyBrowser");
+ intent.setPackage("harley.browsers");
if (!util.startActivity(intent, false, getBaseContext())) {
- intent.setClassName("easy.browser", "easy.lib.SimpleBrowser");
+ intent.setPackage("easy.browser");
if (!util.startActivity(intent, false, getBaseContext())) {
//intent = new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=harley.browsers"));
- intent.setClassName(myPackageName, "easy.lib.SimpleBrowser");// runtime error. VFY: unable to resolve static field
+ intent.setPackage(myPackageName);// runtime error. VFY: unable to resolve static field
util.startActivity(intent, true, getBaseContext());
}
}
}
});
shortBar = (ImageView) home.findViewById(R.id.business_bar);
shortBar.setOnClickListener(new OnClickListener() {//by click this bar to show/hide mainlayout
@Override
public void onClick(View arg0) {
if ((shortAppList.getVisibility() == View.INVISIBLE) && !mShortApps.isEmpty())
shortAppList.setVisibility(View.VISIBLE);
else shortAppList.setVisibility(View.INVISIBLE);
}
});
shortcut_phone = (ImageView) home.findViewById(R.id.shortcut_phone);
shortcut_sms = (ImageView) home.findViewById(R.id.shortcut_sms);
//shortcut_contact = (ImageView) findViewById(R.id.shortcut_contact);
//for package add/remove
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_PACKAGE_ADDED);
filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
filter.addDataScheme("package");
registerReceiver(packageReceiver, filter);
//for wall paper changed
filter = new IntentFilter(Intent.ACTION_WALLPAPER_CHANGED);
registerReceiver(wallpaperReceiver, filter);
filter = new IntentFilter("simpleHome.action.HOME_CHANGED");
registerReceiver(homeChangeReceiver, filter);
filter = new IntentFilter("simpleHome.action.PIC_ADDED");
registerReceiver(picAddReceiver, filter);
filter = new IntentFilter("simpleHome.action.SHARE_DESKTOP");
registerReceiver(deskShareReceiver, filter);
filter = new IntentFilter(Intent.ACTION_MEDIA_MOUNTED);
filter.addAction(Intent.ACTION_MEDIA_SCANNER_STARTED);
filter.addAction(Intent.ACTION_MEDIA_SCANNER_FINISHED);
filter.addAction(Intent.ACTION_MEDIA_REMOVED);
filter.addAction(Intent.ACTION_MEDIA_UNMOUNTED);
filter.addAction(Intent.ACTION_MEDIA_BAD_REMOVAL);
filter.addDataScheme("file");
registerReceiver(sdcardListener, filter);
apps = (RelativeLayout) findViewById(R.id.apps);
//mWallpaperManager.setWallpaperOffsets(apps.getWindowToken(), 0.5f, 0);//move wallpaper to center, but null pointer?
//TelephonyManager tm = (TelephonyManager) getSystemService(Service.TELEPHONY_SERVICE);
//getITelephony(tm).getActivePhoneType();
ContentResolver cr = getContentResolver();
callObserver = new CallObserver(cr, mAppHandler);
smsObserver = new SmsChangeObserver(cr, mAppHandler);
getContentResolver().registerContentObserver(Calls.CONTENT_URI, true, callObserver);
cr.registerContentObserver(Uri.parse("content://mms-sms/"), true, smsObserver);
//task for init, such as load webview, load package list
InitTask initTask = new InitTask();
initTask.execute("");
restartDialog = new AlertDialog.Builder(this).
setTitle(R.string.app_name).
setIcon(R.drawable.icon).
setMessage(R.string.restart).
setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//save the layout
SharedPreferences.Editor editor = perferences.edit();
if (mainlayout.getCurrentItem() == 0)
editor.putBoolean("system", !sysAlphaList.mIsGrid);
else if (mainlayout.getCurrentItem() == 2)
editor.putBoolean("user", !userAlphaList.mIsGrid);
editor.commit();
//restart the activity. note if set singleinstance or singletask of activity, below will not work on some device.
Intent intent = getIntent();
overridePendingTransition(0, 0);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION | Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
finish();
overridePendingTransition(0, 0);
startActivity(intent);
}
}).
setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
}).create();
hintDialog = new AlertDialog.Builder(this).
setNegativeButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
}).create();
}
@Override
protected void onDestroy() {
unregisterReceiver(packageReceiver);
unregisterReceiver(wallpaperReceiver);
unregisterReceiver(picAddReceiver);
unregisterReceiver(deskShareReceiver);
unregisterReceiver(homeChangeReceiver);
unregisterReceiver(sdcardListener);
super.onDestroy();
}
BroadcastReceiver sdcardListener = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(Intent.ACTION_MEDIA_MOUNTED.equals(action)
|| Intent.ACTION_MEDIA_SCANNER_STARTED.equals(action)
|| Intent.ACTION_MEDIA_SCANNER_FINISHED.equals(action)
){// mount sd card success
if (downloadPath != null)
downloadPath = Environment.getExternalStorageDirectory() + "/simpleHome/";
if (mMenu != null) mMenu.getItem(3).setEnabled(true);
} else if(Intent.ACTION_MEDIA_REMOVED.equals(action)
|| Intent.ACTION_MEDIA_UNMOUNTED.equals(action)
|| Intent.ACTION_MEDIA_BAD_REMOVAL.equals(action)
){// fail to mount sd card
if (downloadPath != null)
downloadPath = getFilesDir().getPath() + "/";
if (mMenu != null) mMenu.getItem(3).setEnabled(false);
}
}
};
BroadcastReceiver wallpaperReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context arg0, Intent arg1) {
apps.setBackgroundColor(0);//set back ground to transparent to show wallpaper
wallpaperFile = "";
}
};
BroadcastReceiver picAddReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
final String picName = intent.getStringExtra("picFile");
picList.add(picName);//add to picture list
SharedPreferences.Editor editor = perferences.edit();
editor.putBoolean("shake_enabled", true);
editor.commit();
}
};
BroadcastReceiver deskShareReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String snap = downloadPath + "snap/snap.png";
FileOutputStream fos;
try {//prepare for share desktop
fos = new FileOutputStream(snap);
apps.setDrawingCacheEnabled(true);
Bitmap bmp = apps.getDrawingCache();
bmp.compress(Bitmap.CompressFormat.PNG, 90, fos);
fos.close();
apps.destroyDrawingCache();
} catch (Exception e) {
}
Intent intentSend = new Intent(Intent.ACTION_SEND);
intentSend.setType("image/*");
intentSend.putExtra(Intent.EXTRA_SUBJECT, R.string.share);
intentSend.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File(downloadPath + "snap/snap.png")));
util.startActivity(Intent.createChooser(intentSend, getString(R.string.sharemode)), true, getBaseContext());
}
};
BroadcastReceiver homeChangeReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
final String homeName = intent.getStringExtra("old_home");
if(homeName.equals(myPackageName)) finish();
}
};
void refreshRadioButton() {
int current = mainlayout.getCurrentItem();
radioGroup.clearCheck();
if (current < radioGroup.getChildCount()) ((RadioButton) radioGroup.getChildAt(current)).setChecked(true);// crash once for C lassCastException.
if (current == 0)
radioText.setText(getString(R.string.systemapps) + "(" + sysAlphaList.getCount() + ")");
else if (current == 2)
radioText.setText(getString(R.string.userapps) + "(" + userAlphaList.getCount() + ")");
else radioText.setText("Home");
}
BroadcastReceiver packageReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
String packageName = intent.getDataString().split(":")[1];//it always in the format of package:x.y.z
if (action.equals(Intent.ACTION_PACKAGE_REMOVED)) {
ResolveInfo info = userAlphaList.remove(packageName);
if (info == null) info = sysAlphaList.remove(packageName);
refreshRadioButton();
if (!intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {//not remove shortcut if it is just replace
for (int i = 0; i < favoAdapter.getCount(); i++) {
info = favoAdapter.getItem(i);
if (info.activityInfo.packageName.equals(packageName)) {
favoAdapter.remove(info);
writeFile("favo");
break;
}
}
for (int i = 0; i < shortAdapter.getCount(); i++) {
info = shortAdapter.getItem(i);
if (info.activityInfo.packageName.equals(packageName)) {
shortAdapter.remove(info);
writeFile("short");
break;
}
}
}
}
else if (action.equals(Intent.ACTION_PACKAGE_ADDED)) {
try {//get size of new installed package
getPackageSizeInfo.invoke(pm, packageName, sizeObserver);
} catch (Exception e) {
e.printStackTrace();
}
Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
mainIntent.setPackage(packageName);
List<ResolveInfo> targetApps = pm.queryIntentActivities(mainIntent, 0);
for (int i = 0; i < targetApps.size(); i++) {
if (targetApps.get(i).activityInfo.packageName.equals(packageName) ) {//the new package may not support Launcher category, we will omit it.
ResolveInfo ri = targetApps.get(i);
CharSequence sa = ri.loadLabel(pm);
if (sa == null) sa = ri.activityInfo.name;
ri.activityInfo.applicationInfo.dataDir = getToken(sa);//we borrow dataDir to store the Pinyin of the label.
String tmp = ri.activityInfo.applicationInfo.dataDir.substring(0, 1);
if ((ri.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == ApplicationInfo.FLAG_SYSTEM) {
sysAlphaList.add(ri);
break;
}
else {
userAlphaList.add(ri);
break;
}
}
}
refreshRadioButton();
}
}
};
private class favoAppAdapter extends ArrayAdapter<ResolveInfo> {
ArrayList<ResolveInfo> localApplist;
public favoAppAdapter(Context context, List<ResolveInfo> apps) {
super(context, 0, apps);
localApplist = (ArrayList<ResolveInfo>) apps;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
final ResolveInfo info = (ResolveInfo) localApplist.get(position);
if (convertView == null) {
final LayoutInflater inflater = getLayoutInflater();
convertView = inflater.inflate(R.layout.favo_list, parent, false);
}
convertView.setBackgroundColor(0);
final ImageView btnIcon = (ImageView) convertView.findViewById(R.id.favoappicon);
btnIcon.setImageDrawable(info.loadIcon(pm));
btnIcon.setOnClickListener(new OnClickListener() {//start app
@Override
public void onClick(View arg0) {
util.startApp(info, getBaseContext());
}
});
btnIcon.setTag(new ricase(info, 0));
registerForContextMenu(btnIcon);
return convertView;
}
}
private class shortAppAdapter extends ArrayAdapter<ResolveInfo> {
ArrayList<ResolveInfo> localApplist;
public shortAppAdapter(Context context, List<ResolveInfo> apps) {
super(context, 0, apps);
localApplist = (ArrayList<ResolveInfo>) apps;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
final ResolveInfo info = (ResolveInfo) localApplist.get(position);
if (convertView == null) {
final LayoutInflater inflater = getLayoutInflater();
convertView = inflater.inflate(R.layout.favo_list, parent, false);
}
final ImageView btnIcon = (ImageView) convertView.findViewById(R.id.favoappicon);
btnIcon.setImageDrawable(info.loadIcon(pm));
TextView appname = (TextView) convertView.findViewById(R.id.favoappname);
appname.setText(info.loadLabel(pm));
convertView.setOnClickListener(new OnClickListener() {//launch app
@Override
public void onClick(View arg0) {
util.startApp(info, getBaseContext());
shortAppList.setVisibility(View.INVISIBLE);
}
});
convertView.setTag(new ricase(info, 1));
registerForContextMenu(convertView);
return convertView;
}
}
void readFile(String name)
{
FileInputStream fi = null;
ObjectInputStream ois = null;
try {//read favorite or shortcut data
fi = openFileInput(name);
ois = new ObjectInputStream(fi);
String activityName;
while ((activityName = (String) ois.readObject()) != null) {
for (int i = 0; i < mAllApps.size(); i++)
if (mAllApps.get(i).activityInfo.name.equals(activityName)) {
if (name.equals("favo")) mFavoApps.add(mAllApps.get(i));
else if (name.equals("short")) mShortApps.add(mAllApps.get(i));
break;
}
}
} catch (EOFException e) {//only when read eof need send out msg.
try {
ois.close();
fi.close();
} catch (IOException e1) {
e1.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
}
public String getToken(CharSequence sa) {
String sa1 = sa.toString().trim();
String sa2 = sa1;
if (sa1.length() > 0) {
try {//this is to fix a bug report by market
sa2 = HanziToPinyin.getInstance().getToken(sa1.charAt(0)).target.trim();
if (sa2.length() > 1) sa2 = sa2.substring(0, 1);
} catch(Exception e) {
e.printStackTrace();
}
}
sa2 = sa2.toUpperCase();
if ((sa2.compareTo("A") < 0) || (sa2.compareTo("Z") > 0)) sa2 = "#";//for space or number, we change to #
return sa2;
}
class InitTask extends AsyncTask<String, Integer, String> {
@Override
protected String doInBackground(String... params) {//do all time consuming work here
canRoot = false;
String res = ShellInterface.doExec(new String[] {"id"}, true);
if (res.contains("root")) {
res = ShellInterface.doExec(new String[] {"mount -o rw,remount -t yaffs2 /dev/block/mtdblock3 /system"}, true);
if (res.contains("Error")) canRoot = false;
else canRoot = true;
}
Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
mAllApps = pm.queryIntentActivities(mainIntent, 0);
readFile("favo");
readFile("short");
boolean shortEmpty = mShortApps.isEmpty();
//read all resolveinfo
String label_sms = "簡訊 Messaging Messages メッセージ 信息 消息 短信 메시지 Mensajes Messaggi Berichten SMS a MMS SMS/MMS"; //use label name to get short cut
String label_phone = "電話 Phone 电话 电话和联系人 拨号键盘 키패드 Telefon Teléfono Téléphone Telefono Telefoon Телефон 휴대전화 Dialer";
String label_contact = "聯絡人 联系人 Contacts People 連絡先 通讯录 전화번호부 Kontakty Kontakte Contactos Contatti Contacten Контакты 주소록";
int match = 0;
for (int i = 0; i < mAllApps.size(); i++) {
ResolveInfo ri = mAllApps.get(i);
CharSequence sa = ri.loadLabel(pm);
if (sa == null) sa = ri.activityInfo.name;
ri.activityInfo.applicationInfo.dataDir = getToken(sa);//we borrow dataDir to store the Pinyin of the label.
if ((ri.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == ApplicationInfo.FLAG_SYSTEM) {
sysAlphaList.add(ri, false, false);
if (match < 3) {//only find 3 match: sms, phone, contact
String name = sa.toString() ;
//Log.d("===============", name);
if (label_phone.contains(name)) {
if (ri_phone == null) {
ri_phone = ri;
Message msgphone = mAppHandler.obtainMessage();
msgphone.what = UPDATE_RI_PHONE;
mAppHandler.sendMessage(msgphone);//inform UI thread to update UI.
match += 1;
}
}
else if (label_sms.contains(name)) {
if ((ri_sms == null) && (!name.equals("MM"))) {
ri_sms = ri;
Message msgsms = mAppHandler.obtainMessage();
msgsms.what = UPDATE_RI_SMS;
mAppHandler.sendMessage(msgsms);//inform UI thread to update UI.
match += 1;
}
}
else if ((shortEmpty) && label_contact.contains(name)) {//only add contact to shortcut if shortcut is empty.
if (ri_contact == null) {
mShortApps.add(ri);
/*ri_contact = ri;
Message msgcontact = mAppHandler.obtainMessage();
msgcontact.what = UPDATE_RI_CONTACT;
mAppHandler.sendMessage(msgcontact);//inform UI thread to update UI.*/
match += 1;
}
}
}
}
else userAlphaList.add(ri, false, false);
try {
getPackageSizeInfo.invoke(pm, ri.activityInfo.packageName, sizeObserver);
} catch (Exception e) {
e.printStackTrace();
}
}
sysAlphaList.sortAlpha();
userAlphaList.sortAlpha();
Message msguser = mAppHandler.obtainMessage();
msguser.what = UPDATE_USER;
mAppHandler.sendMessage(msguser);//inform UI thread to update UI.
downloadPath = util.preparePath(getBaseContext());
picList = new ArrayList();
picList_selected = new ArrayList();
new File(downloadPath).list(new OnlyPic());
if (picList.size() > 0) {
SharedPreferences.Editor editor = perferences.edit();
editor.putBoolean("shake_enabled", true);
editor.commit();
}
mainIntent = new Intent(Intent.ACTION_VIEW, null);
mainIntent.addCategory(Intent.CATEGORY_DEFAULT);
List<ResolveInfo> viewApps = pm.queryIntentActivities(mainIntent, 0);
appDetail = null;
for (int i = 0; i < viewApps.size(); i++) {
if (viewApps.get(i).activityInfo.name.contains("InstalledAppDetails")) {
appDetail = viewApps.get(i);//get the activity for app detail setting
break;
}
}
return null;
}
}
class OnlyPic implements FilenameFilter {
public boolean accept(File dir, String s) {
String name = s.toLowerCase();
if (s.endsWith(".png") || s.endsWith(".jpg")) {
picList.add(s);
return true;
}
else return false;
}
}
class appHandler extends Handler {
public void handleMessage(Message msg) {
switch (msg.what) {
case UPDATE_USER:
sysAlphaList.setAdapter();
userAlphaList.setAdapter();
refreshRadioButton();//this will update the radio button with correct app number. only for very slow phone
shortAdapter = new shortAppAdapter(getBaseContext(), mShortApps);
shortAppList.setAdapter(shortAdapter);
break;
case UPDATE_RI_PHONE:
int missCallCount = callObserver.countUnread();
if (missCallCount > 0) {
Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.phone);
shortcut_phone.setImageBitmap(util.generatorCountIcon(bm, missCallCount, 1, 1, getBaseContext()));
}
else shortcut_phone.setImageResource(R.drawable.phone);
shortcut_phone.setOnClickListener(new OnClickListener() {//start app
@Override
public void onClick(View arg0) {
util.startApp(ri_phone, getBaseContext());
}
});
break;
case UPDATE_RI_SMS:
int unreadCount = smsObserver.countUnread();
if (unreadCount > 0) {
Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.sms);
shortcut_sms.setImageBitmap(util.generatorCountIcon(bm, unreadCount, 1, 1, getBaseContext()));
}
else shortcut_sms.setImageResource(R.drawable.sms);
shortcut_sms.setOnClickListener(new OnClickListener() {//start app
@Override
public void onClick(View arg0) {
util.startApp(ri_sms, getBaseContext());
}
});
break;
case UPDATE_RI_CONTACT:
shortcut_contact.setImageDrawable(ri_contact.loadIcon(pm));
shortcut_contact.setOnClickListener(new OnClickListener() {//start app
@Override
public void onClick(View arg0) {
util.startApp(ri_contact, getBaseContext());
}
});
break;
}
}
};
@Override
protected void onNewIntent(Intent intent) {//go back to home if press Home key.
if ((intent.getAction().equals(Intent.ACTION_MAIN)) && (intent.hasCategory(Intent.CATEGORY_HOME))) {
if (mainlayout.getCurrentItem() != homeTab) mainlayout.setCurrentItem(homeTab);
else if (shortAppList.getVisibility() == View.VISIBLE) shortBar.performClick();
}
super.onNewIntent(intent);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (event.getRepeatCount() == 0) {
if (keyCode == KeyEvent.KEYCODE_BACK) {//press Back key in webview will go backword.
if (mainlayout.getCurrentItem() != homeTab) mainlayout.setCurrentItem(homeTab);
else if (shortAppList.getVisibility() == View.VISIBLE) shortBar.performClick();
else this.openOptionsMenu();
return true;
}
}
return false;
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig); //not restart activity each time screen orientation changes
getWindowManager().getDefaultDisplay().getMetrics(dm);
if (newConfig.hardKeyboardHidden == Configuration.HARDKEYBOARDHIDDEN_NO)
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
}
@Override
public void onAccuracyChanged(Sensor arg0, int arg1) {
}
@Override
public void onSensorChanged(SensorEvent arg0) {
if (arg0.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
long curTime = System.currentTimeMillis();
// detect every 100ms
if ((curTime - lastUpdate) > 100) {
long timeInterval = (curTime - lastUpdate);
lastUpdate = curTime;
float x = arg0.values[SensorManager.DATA_X];
float y = arg0.values[SensorManager.DATA_Y];
float z = arg0.values[SensorManager.DATA_Z];
float deltaX = x - last_x;
float deltaY = y - last_y;
float deltaZ = z - last_z;
double speed = Math.sqrt(deltaX*deltaX + deltaY*deltaY + deltaZ*deltaZ)/timeInterval * 100;
//condition to change wallpaper: speed is enough; frequency is not too high; picList is not empty.
if ((!busy) && (speed > 8) && (curTime - lastSet > 500) && (picList != null) && (picList.size() > 0)) {
busy = true;
Random random = new Random();
int id = random.nextInt(picList.size());
try {
wallpaperFile = downloadPath + picList.get(id);
BitmapDrawable bd = (BitmapDrawable) BitmapDrawable.createFromPath(wallpaperFile);
double factor = 1.0 * bd.getIntrinsicWidth() / bd.getIntrinsicHeight();
if (factor >= 1.2) {//if too wide, we want use setWallpaperOffsets to move it, so we need set it to wallpaper
int tmpWidth = (int) (dm.heightPixels * factor);
mWallpaperManager.setBitmap(Bitmap.createScaledBitmap(bd.getBitmap(), tmpWidth, dm.heightPixels, false));
mWallpaperManager.suggestDesiredDimensions(tmpWidth, dm.heightPixels);
sensorMgr.unregisterListener(this);
SharedPreferences.Editor editor = perferences.edit();
shakeWallpaper = false;
editor.putBoolean("shake", false);
editor.commit();
}
else {//otherwise just change the background is ok.
ClippedDrawable cd = new ClippedDrawable(bd, apps.getWidth(), apps.getHeight());
apps.setBackgroundDrawable(cd);
}
picList_selected.add(picList.get(id));
picList.remove(id);//prevent it be selected again before a full cycle
lastSet = System.currentTimeMillis();
} catch (Exception e) {
e.printStackTrace();
picList.remove(id);
wallpaperFile = "";
}
if (picList.isEmpty()) {
if (picList_selected.isEmpty()) {
sensorMgr.unregisterListener(this);
SharedPreferences.Editor editor = perferences.edit();
editor.putBoolean("shake_enabled", false);
shakeWallpaper = false;
editor.putBoolean("shake", false);
editor.commit();
}
else {
picList = (ArrayList<String>) picList_selected.clone();
picList_selected.clear();
}
}
busy = false;
}
last_x = x;
last_y = y;
last_z = z;
}
}
}
@Override
public void onSizeChanged(int w, int h, int oldW, int oldH) {
//setLayout(oldW);
}
}
/** from Android Home sample
* When a drawable is attached to a View, the View gives the Drawable its dimensions
* by calling Drawable.setBounds(). In this application, the View that draws the
* wallpaper has the same size as the screen. However, the wallpaper might be larger
* that the screen which means it will be automatically stretched. Because stretching
* a bitmap while drawing it is very expensive, we use a ClippedDrawable instead.
* This drawable simply draws another wallpaper but makes sure it is not stretched
* by always giving it its intrinsic dimensions. If the wallpaper is larger than the
* screen, it will simply get clipped but it won't impact performance.
*/
class ClippedDrawable extends Drawable {
private final Drawable mWallpaper;
int screenWidth, screenHeight;
boolean tooWide = false;
public ClippedDrawable(Drawable wallpaper, int sw, int sh) {
mWallpaper = wallpaper;
screenWidth = sw;
screenHeight = sh;
}
@Override
public void setBounds(int left, int top, int right, int bottom) {
super.setBounds(left, top, right, bottom);
// Ensure the wallpaper is as large as it really is, to avoid stretching it at drawing time
int tmpHeight = mWallpaper.getIntrinsicHeight() * screenWidth / mWallpaper.getIntrinsicWidth();
int tmpWidth = mWallpaper.getIntrinsicWidth() * screenHeight / mWallpaper.getIntrinsicHeight();
if (tmpHeight >= screenHeight) {
top -= (tmpHeight - screenHeight)/2;
mWallpaper.setBounds(left, top, left + screenWidth, top + tmpHeight);
}
else {//if the pic width is wider than screen width, then we need show part of the pic.
tooWide = true;
left -= (tmpWidth - screenWidth)/2;
mWallpaper.setBounds(left, top, left + tmpWidth, top + screenHeight);
}
}
public void draw(Canvas canvas) {
mWallpaper.draw(canvas);
}
public void setAlpha(int alpha) {
mWallpaper.setAlpha(alpha);
}
public void setColorFilter(ColorFilter cf) {
mWallpaper.setColorFilter(cf);
}
public int getOpacity() {
return mWallpaper.getOpacity();
}
}
class sizedRelativeLayout extends RelativeLayout {
public sizedRelativeLayout(Context context) {
super(context);
}
public sizedRelativeLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
private OnResizeChangeListener mOnResizeChangeListener;
protected void onSizeChanged(int w, int h, int oldW, int oldH) {
if(mOnResizeChangeListener!=null){
mOnResizeChangeListener.onSizeChanged(w,h,oldW,oldH);
}
super.onSizeChanged(w,h,oldW,oldH);
}
public void setResizeListener(OnResizeChangeListener l) {
mOnResizeChangeListener = l;
}
public interface OnResizeChangeListener{
void onSizeChanged(int w,int h,int oldW,int oldH);
}
}
class SmsChangeObserver extends ContentObserver {
ContentResolver mCR;
Handler mHandler;
public SmsChangeObserver(ContentResolver cr, Handler handler) {
super(handler);
mCR = cr;
mHandler = handler;
}
public int countUnread() {
//get sms unread count
int ret = 0;
Cursor csr = mCR.query(Uri.parse("content://sms"),
new String[] {"thread_id"},
"read=0",
null,
null);
if (csr != null) ret = csr.getCount();
//get mms unread count
csr = mCR.query(Uri.parse("content://mms"),
new String[] {"thread_id"},
"read=0",
null,
null);
if (csr != null) ret += csr.getCount();
return ret;
}
@Override
public void onChange(boolean selfChange) {
super.onChange(selfChange);
Message msgsms = mHandler.obtainMessage();
msgsms.what = 1;//UPDATE_RI_SMS;
mHandler.sendMessage(msgsms);//inform UI thread to update UI.
}
}
class CallObserver extends ContentObserver {
ContentResolver mCR;
Handler mHandler;
public CallObserver(ContentResolver cr, Handler handler) {
super(handler);
mHandler = handler;
mCR = cr;
}
public int countUnread() {
//get missed call number
Cursor csr = mCR.query(Calls.CONTENT_URI,
new String[] {Calls.NUMBER, Calls.TYPE, Calls.NEW},
Calls.TYPE + "=" + Calls.MISSED_TYPE + " AND " + Calls.NEW + "=1",
null, Calls.DEFAULT_SORT_ORDER);
if (csr != null) return csr.getCount();
else return 0;
}
@Override
public void onChange(boolean selfChange) {
super.onChange(selfChange);
Message msgphone = mHandler.obtainMessage();
msgphone.what = 0;//UPDATE_RI_PHONE;
mHandler.sendMessage(msgphone);//inform UI thread to update UI.
}
}
| false | true | public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
myPackageName = this.getPackageName();
pm = getPackageManager();
version = util.getVersion(this);
try {
getPackageSizeInfo = PackageManager.class.getMethod(
"getPackageSizeInfo", new Class[] {String.class, IPackageStatsObserver.class});
} catch (Exception e) {
e.printStackTrace();
}
sizeObserver = new IPackageStatsObserver.Stub() {
@Override
public void onGetStatsCompleted(PackageStats pStats,
boolean succeeded) throws RemoteException {
long size = pStats.codeSize;
String ssize = new String();
if (size > 10 * sizeM) ssize = size / sizeM + "M";
else if (size > 10 * 1024) ssize = size / 1024 + "K";
else if (size > 0) ssize = size + "B";
else ssize = "";
packagesSize.put(pStats.packageName, ssize);
}
};
packagesSize = new HashMap<String, Object>();
sensorMgr = (SensorManager) getSystemService(SENSOR_SERVICE);
mSensor = sensorMgr.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
perferences = PreferenceManager.getDefaultSharedPreferences(this);
dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
//1,2,3,4 are integer value of small, normal, large and XLARGE screen respectively.
//int screen_size = getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK;
//if (screen_size < Configuration.SCREENLAYOUT_SIZE_LARGE)//disable auto rotate screen for small and normal screen.
//setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
requestWindowFeature(Window.FEATURE_NO_TITLE); //hide titlebar of application, must be before setting the layout
setContentView(R.layout.ads);
home = (RelativeLayout) getLayoutInflater().inflate(R.layout.home, null);
//favorite app tab
favoAppList = (GridView) home.findViewById(R.id.favos);
favoAppList.setVerticalScrollBarEnabled(false);
favoAppList.inflate(this, R.layout.app_list, null);
favoAppList.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View arg0, MotionEvent arg1) {
shortAppList.setVisibility(View.INVISIBLE);
return false;
}
});
shortAppList = (ListView) home.findViewById(R.id.business);
shortAppList.bringToFront();
shortAppList.setVisibility(View.INVISIBLE);
boolean isGrid = perferences.getBoolean("system", true);
sysAlphaList = new AppAlphaList(this, pm, packagesSize, isGrid, dm.widthPixels > 480);
isGrid = perferences.getBoolean("user", false);
userAlphaList = new AppAlphaList(this, pm, packagesSize, isGrid, dm.widthPixels > 480);
mListViews = new ArrayList<View>();
mListViews.add(sysAlphaList.view);
mListViews.add(home);
mListViews.add(userAlphaList.view);
radioText = (TextView) findViewById(R.id.radio_text);
radioGroup = (RadioGroup) findViewById(R.id.radio_hint);
radioGroup.removeViewAt(0);
mWallpaperManager = WallpaperManager.getInstance(this);
mainlayout = (ViewPager)findViewById(R.id.mainFrame);
mainlayout.setLongClickable(true);
myPagerAdapter = new MyPagerAdapter();
mainlayout.setAdapter(myPagerAdapter);
mainlayout.setOnPageChangeListener(new OnPageChangeListener() {
@Override
public void onPageScrollStateChanged(int state) {
if (state == ViewPager.SCROLL_STATE_SETTLING) {
refreshRadioButton();
}
}
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
if (!shakeWallpaper) {//don't move wallpaper if change wallpaper by shake
if (token == null) token = mainlayout.getWindowToken();//any token from a component is ok
mWallpaperManager.setWallpaperOffsets(token,
//when slide from home to systems or from systems to home, the "position" is 0,
//when slide from home to users or from users to home, it is 1.
//positionOffset is from 0 to 1. sometime it will jump from 1 to 0, we just omit it if it is 0.
//so we can unify it to (0, 1) by (positionOffset+position)/2
(positionOffset+position)/(mListViews.size()-1), 0);
}
}
@Override
public void onPageSelected(int arg0) {
}
});
mainlayout.setCurrentItem(homeTab);
mSysApps = new ArrayList<ResolveInfo>();
mUserApps = new ArrayList<ResolveInfo>();
mFavoApps = new ArrayList<ResolveInfo>();
mShortApps = new ArrayList<ResolveInfo>();
favoAdapter = new favoAppAdapter(getBaseContext(), mFavoApps);
favoAppList.setAdapter(favoAdapter);
base = (sizedRelativeLayout) home.findViewById(R.id.base);
base.setResizeListener(this);
homeBar = (ImageView) home.findViewById(R.id.home_bar);
homeBar.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.setClassName("harley.browsers", "harley.lib.HarleyBrowser");
if (!util.startActivity(intent, false, getBaseContext())) {
intent.setClassName("easy.browser", "easy.lib.SimpleBrowser");
if (!util.startActivity(intent, false, getBaseContext())) {
//intent = new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=harley.browsers"));
intent.setClassName(myPackageName, "easy.lib.SimpleBrowser");// runtime error. VFY: unable to resolve static field
util.startActivity(intent, true, getBaseContext());
}
}
}
});
shortBar = (ImageView) home.findViewById(R.id.business_bar);
shortBar.setOnClickListener(new OnClickListener() {//by click this bar to show/hide mainlayout
@Override
public void onClick(View arg0) {
if ((shortAppList.getVisibility() == View.INVISIBLE) && !mShortApps.isEmpty())
shortAppList.setVisibility(View.VISIBLE);
else shortAppList.setVisibility(View.INVISIBLE);
}
});
shortcut_phone = (ImageView) home.findViewById(R.id.shortcut_phone);
shortcut_sms = (ImageView) home.findViewById(R.id.shortcut_sms);
//shortcut_contact = (ImageView) findViewById(R.id.shortcut_contact);
//for package add/remove
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_PACKAGE_ADDED);
filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
filter.addDataScheme("package");
registerReceiver(packageReceiver, filter);
//for wall paper changed
filter = new IntentFilter(Intent.ACTION_WALLPAPER_CHANGED);
registerReceiver(wallpaperReceiver, filter);
filter = new IntentFilter("simpleHome.action.HOME_CHANGED");
registerReceiver(homeChangeReceiver, filter);
filter = new IntentFilter("simpleHome.action.PIC_ADDED");
registerReceiver(picAddReceiver, filter);
filter = new IntentFilter("simpleHome.action.SHARE_DESKTOP");
registerReceiver(deskShareReceiver, filter);
filter = new IntentFilter(Intent.ACTION_MEDIA_MOUNTED);
filter.addAction(Intent.ACTION_MEDIA_SCANNER_STARTED);
filter.addAction(Intent.ACTION_MEDIA_SCANNER_FINISHED);
filter.addAction(Intent.ACTION_MEDIA_REMOVED);
filter.addAction(Intent.ACTION_MEDIA_UNMOUNTED);
filter.addAction(Intent.ACTION_MEDIA_BAD_REMOVAL);
filter.addDataScheme("file");
registerReceiver(sdcardListener, filter);
apps = (RelativeLayout) findViewById(R.id.apps);
//mWallpaperManager.setWallpaperOffsets(apps.getWindowToken(), 0.5f, 0);//move wallpaper to center, but null pointer?
//TelephonyManager tm = (TelephonyManager) getSystemService(Service.TELEPHONY_SERVICE);
//getITelephony(tm).getActivePhoneType();
ContentResolver cr = getContentResolver();
callObserver = new CallObserver(cr, mAppHandler);
smsObserver = new SmsChangeObserver(cr, mAppHandler);
getContentResolver().registerContentObserver(Calls.CONTENT_URI, true, callObserver);
cr.registerContentObserver(Uri.parse("content://mms-sms/"), true, smsObserver);
//task for init, such as load webview, load package list
InitTask initTask = new InitTask();
initTask.execute("");
restartDialog = new AlertDialog.Builder(this).
setTitle(R.string.app_name).
setIcon(R.drawable.icon).
setMessage(R.string.restart).
setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//save the layout
SharedPreferences.Editor editor = perferences.edit();
if (mainlayout.getCurrentItem() == 0)
editor.putBoolean("system", !sysAlphaList.mIsGrid);
else if (mainlayout.getCurrentItem() == 2)
editor.putBoolean("user", !userAlphaList.mIsGrid);
editor.commit();
//restart the activity. note if set singleinstance or singletask of activity, below will not work on some device.
Intent intent = getIntent();
overridePendingTransition(0, 0);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION | Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
finish();
overridePendingTransition(0, 0);
startActivity(intent);
}
}).
setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
}).create();
hintDialog = new AlertDialog.Builder(this).
setNegativeButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
}).create();
}
| public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
myPackageName = this.getPackageName();
pm = getPackageManager();
version = util.getVersion(this);
try {
getPackageSizeInfo = PackageManager.class.getMethod(
"getPackageSizeInfo", new Class[] {String.class, IPackageStatsObserver.class});
} catch (Exception e) {
e.printStackTrace();
}
sizeObserver = new IPackageStatsObserver.Stub() {
@Override
public void onGetStatsCompleted(PackageStats pStats,
boolean succeeded) throws RemoteException {
long size = pStats.codeSize;
String ssize = new String();
if (size > 10 * sizeM) ssize = size / sizeM + "M";
else if (size > 10 * 1024) ssize = size / 1024 + "K";
else if (size > 0) ssize = size + "B";
else ssize = "";
packagesSize.put(pStats.packageName, ssize);
}
};
packagesSize = new HashMap<String, Object>();
sensorMgr = (SensorManager) getSystemService(SENSOR_SERVICE);
mSensor = sensorMgr.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
perferences = PreferenceManager.getDefaultSharedPreferences(this);
dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
//1,2,3,4 are integer value of small, normal, large and XLARGE screen respectively.
//int screen_size = getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK;
//if (screen_size < Configuration.SCREENLAYOUT_SIZE_LARGE)//disable auto rotate screen for small and normal screen.
//setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
requestWindowFeature(Window.FEATURE_NO_TITLE); //hide titlebar of application, must be before setting the layout
setContentView(R.layout.ads);
home = (RelativeLayout) getLayoutInflater().inflate(R.layout.home, null);
//favorite app tab
favoAppList = (GridView) home.findViewById(R.id.favos);
favoAppList.setVerticalScrollBarEnabled(false);
favoAppList.inflate(this, R.layout.app_list, null);
favoAppList.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View arg0, MotionEvent arg1) {
shortAppList.setVisibility(View.INVISIBLE);
return false;
}
});
shortAppList = (ListView) home.findViewById(R.id.business);
shortAppList.bringToFront();
shortAppList.setVisibility(View.INVISIBLE);
boolean isGrid = perferences.getBoolean("system", true);
sysAlphaList = new AppAlphaList(this, pm, packagesSize, isGrid, dm.widthPixels > 480);
isGrid = perferences.getBoolean("user", false);
userAlphaList = new AppAlphaList(this, pm, packagesSize, isGrid, dm.widthPixels > 480);
mListViews = new ArrayList<View>();
mListViews.add(sysAlphaList.view);
mListViews.add(home);
mListViews.add(userAlphaList.view);
radioText = (TextView) findViewById(R.id.radio_text);
radioGroup = (RadioGroup) findViewById(R.id.radio_hint);
radioGroup.removeViewAt(0);
mWallpaperManager = WallpaperManager.getInstance(this);
mainlayout = (ViewPager)findViewById(R.id.mainFrame);
mainlayout.setLongClickable(true);
myPagerAdapter = new MyPagerAdapter();
mainlayout.setAdapter(myPagerAdapter);
mainlayout.setOnPageChangeListener(new OnPageChangeListener() {
@Override
public void onPageScrollStateChanged(int state) {
if (state == ViewPager.SCROLL_STATE_SETTLING) {
refreshRadioButton();
}
}
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
if (!shakeWallpaper) {//don't move wallpaper if change wallpaper by shake
if (token == null) token = mainlayout.getWindowToken();//any token from a component is ok
mWallpaperManager.setWallpaperOffsets(token,
//when slide from home to systems or from systems to home, the "position" is 0,
//when slide from home to users or from users to home, it is 1.
//positionOffset is from 0 to 1. sometime it will jump from 1 to 0, we just omit it if it is 0.
//so we can unify it to (0, 1) by (positionOffset+position)/2
(positionOffset+position)/(mListViews.size()-1), 0);
}
}
@Override
public void onPageSelected(int arg0) {
}
});
mainlayout.setCurrentItem(homeTab);
mSysApps = new ArrayList<ResolveInfo>();
mUserApps = new ArrayList<ResolveInfo>();
mFavoApps = new ArrayList<ResolveInfo>();
mShortApps = new ArrayList<ResolveInfo>();
favoAdapter = new favoAppAdapter(getBaseContext(), mFavoApps);
favoAppList.setAdapter(favoAdapter);
base = (sizedRelativeLayout) home.findViewById(R.id.base);
base.setResizeListener(this);
homeBar = (ImageView) home.findViewById(R.id.home_bar);
homeBar.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.setPackage("harley.browsers");
if (!util.startActivity(intent, false, getBaseContext())) {
intent.setPackage("easy.browser");
if (!util.startActivity(intent, false, getBaseContext())) {
//intent = new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=harley.browsers"));
intent.setPackage(myPackageName);// runtime error. VFY: unable to resolve static field
util.startActivity(intent, true, getBaseContext());
}
}
}
});
shortBar = (ImageView) home.findViewById(R.id.business_bar);
shortBar.setOnClickListener(new OnClickListener() {//by click this bar to show/hide mainlayout
@Override
public void onClick(View arg0) {
if ((shortAppList.getVisibility() == View.INVISIBLE) && !mShortApps.isEmpty())
shortAppList.setVisibility(View.VISIBLE);
else shortAppList.setVisibility(View.INVISIBLE);
}
});
shortcut_phone = (ImageView) home.findViewById(R.id.shortcut_phone);
shortcut_sms = (ImageView) home.findViewById(R.id.shortcut_sms);
//shortcut_contact = (ImageView) findViewById(R.id.shortcut_contact);
//for package add/remove
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_PACKAGE_ADDED);
filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
filter.addDataScheme("package");
registerReceiver(packageReceiver, filter);
//for wall paper changed
filter = new IntentFilter(Intent.ACTION_WALLPAPER_CHANGED);
registerReceiver(wallpaperReceiver, filter);
filter = new IntentFilter("simpleHome.action.HOME_CHANGED");
registerReceiver(homeChangeReceiver, filter);
filter = new IntentFilter("simpleHome.action.PIC_ADDED");
registerReceiver(picAddReceiver, filter);
filter = new IntentFilter("simpleHome.action.SHARE_DESKTOP");
registerReceiver(deskShareReceiver, filter);
filter = new IntentFilter(Intent.ACTION_MEDIA_MOUNTED);
filter.addAction(Intent.ACTION_MEDIA_SCANNER_STARTED);
filter.addAction(Intent.ACTION_MEDIA_SCANNER_FINISHED);
filter.addAction(Intent.ACTION_MEDIA_REMOVED);
filter.addAction(Intent.ACTION_MEDIA_UNMOUNTED);
filter.addAction(Intent.ACTION_MEDIA_BAD_REMOVAL);
filter.addDataScheme("file");
registerReceiver(sdcardListener, filter);
apps = (RelativeLayout) findViewById(R.id.apps);
//mWallpaperManager.setWallpaperOffsets(apps.getWindowToken(), 0.5f, 0);//move wallpaper to center, but null pointer?
//TelephonyManager tm = (TelephonyManager) getSystemService(Service.TELEPHONY_SERVICE);
//getITelephony(tm).getActivePhoneType();
ContentResolver cr = getContentResolver();
callObserver = new CallObserver(cr, mAppHandler);
smsObserver = new SmsChangeObserver(cr, mAppHandler);
getContentResolver().registerContentObserver(Calls.CONTENT_URI, true, callObserver);
cr.registerContentObserver(Uri.parse("content://mms-sms/"), true, smsObserver);
//task for init, such as load webview, load package list
InitTask initTask = new InitTask();
initTask.execute("");
restartDialog = new AlertDialog.Builder(this).
setTitle(R.string.app_name).
setIcon(R.drawable.icon).
setMessage(R.string.restart).
setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//save the layout
SharedPreferences.Editor editor = perferences.edit();
if (mainlayout.getCurrentItem() == 0)
editor.putBoolean("system", !sysAlphaList.mIsGrid);
else if (mainlayout.getCurrentItem() == 2)
editor.putBoolean("user", !userAlphaList.mIsGrid);
editor.commit();
//restart the activity. note if set singleinstance or singletask of activity, below will not work on some device.
Intent intent = getIntent();
overridePendingTransition(0, 0);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION | Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
finish();
overridePendingTransition(0, 0);
startActivity(intent);
}
}).
setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
}).create();
hintDialog = new AlertDialog.Builder(this).
setNegativeButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
}).create();
}
|
diff --git a/se/sics/mspsim/core/MSP430Core.java b/se/sics/mspsim/core/MSP430Core.java
index a6c7c3d..5ed2a40 100644
--- a/se/sics/mspsim/core/MSP430Core.java
+++ b/se/sics/mspsim/core/MSP430Core.java
@@ -1,1210 +1,1211 @@
/**
* Copyright (c) 2007, Swedish Institute of Computer Science.
* 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 the Institute 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 INSTITUTE 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 INSTITUTE 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.
*
* This file is part of MSPSim.
*
* $Id$
*
* -----------------------------------------------------------------
*
* MSP430Core
*
* Author : Joakim Eriksson
* Created : Sun Oct 21 22:00:00 2007
* Updated : $Date$
* $Revision$
*/
package se.sics.mspsim.core;
import se.sics.mspsim.util.Utils;
/**
* The CPU of the MSP430
*/
public class MSP430Core extends Chip implements MSP430Constants {
public static final boolean DEBUG = false;
public static final boolean debugInterrupts = true; //false;
// Try it out with 64 k memory
public static final int MAX_MEM = 64*1024;
public static final int MAX_MEM_IO = 0x200;
public static final int INTERNAL_IO_SIZE = 3;
public static final int PORTS = 6;
// 16 registers of which some are "special" - PC, SP, etc.
public int[] reg = new int[16];
public CPUMonitor[] regWriteMonitors = new CPUMonitor[16];
public CPUMonitor[] regReadMonitors = new CPUMonitor[16];
// For breakpoints, etc... how should memory monitors be implemented?
// Maybe monitors should have a "next" pointer...? or just have a [][]?
public CPUMonitor[] breakPoints = new CPUMonitor[MAX_MEM];
// true => breakpoints can occur!
boolean breakpointActive = true;
public int memory[] = new int[MAX_MEM];
public long cycles = 0;
public long cpuCycles = 0;
// Most HW needs only notify write and clocking, others need also read...
// For notify write...
public IOUnit[] memOut = new IOUnit[MAX_MEM_IO];
// For notify read... -> which will happen before actual read!
public IOUnit[] memIn = new IOUnit[MAX_MEM_IO];
private IOUnit[] ioUnits;
private IOUnit[] passiveIOUnits;
private SFR sfr;
private long[] ioCycles;
private long nextIOTickCycles;
private int nextIOTickIndex;
private int lastIOUnitPos = INTERNAL_IO_SIZE;
// From the possible interrupt sources - to be able to indicate is serviced.
private IOUnit interruptSource[] = new IOUnit[16];
private int interruptMax = -1;
// Op/instruction represents the last executed OP / instruction
private int op;
int instruction;
int servicedInterrupt = -1;
IOUnit servicedInterruptUnit = null;
private boolean interruptsEnabled = false;
private boolean cpuOff = false;
// Not private since they are needed (for fast access...)
private int dcoFrq = 2500000;
int aclkFrq = 32768;
int smclkFrq = dcoFrq;
long lastCyclesTime = 0;
long lastVTime = 0;
long currentTime = 0;
double currentDCOFactor = 1.0;
// Clk A can be "captured" by timers - needs to be handled close to CPU...?
private int clkACaptureMode = CLKCAPTURE_NONE;
// Other clocks too...
private long nextEventCycles;
private EventQueue vTimeEventQueue = new EventQueue();
private long nextVTimeEventCycles;
private EventQueue cycleEventQueue = new EventQueue();
private long nextCycleEventCycles;
public MSP430Core(int type) {
// Ignore type for now...
setModeNames(MODE_NAMES);
// Internal Active IOUnits
int passIO = 0;
int actIO = 0;
ioUnits = new IOUnit[INTERNAL_IO_SIZE + 10];
ioCycles = new long[INTERNAL_IO_SIZE + 10];
// Passive IOUnits (no tick) - do we need to remember them???
// Maybe for debugging purposes...
passiveIOUnits = new IOUnit[PORTS + 2];
Timer ta = new Timer(this, Timer.TIMER_Ax149, memory, 0x160);
Timer tb = new Timer(this, Timer.TIMER_Bx149, memory, 0x180);
for (int i = 0, n = 0x20; i < n; i++) {
memOut[0x160 + i] = ta;
memOut[0x180 + i] = tb;
memIn[0x160 + i] = ta;
memIn[0x180 + i] = tb;
}
Watchdog wdt = new Watchdog(this);
memOut[0x120] = wdt;
memIn[0x120] = wdt;
sfr = new SFR(this, memory);
for (int i = 0, n = 0x10; i < n; i++) {
memOut[i] = sfr;
memIn[i] = sfr;
}
memIn[Timer.TAIV] = ta;
memIn[Timer.TBIV] = tb;
BasicClockModule bcs = new BasicClockModule(this, memory, 0);
for (int i = 0x56, n = 0x59; i < n; i++) {
memOut[i] = bcs;
}
Multiplier mp = new Multiplier(this, memory, 0);
// Only cares of writes!
for (int i = 0x130, n = 0x13f; i < n; i++) {
memOut[i] = mp;
memIn[i] = mp;
}
// ioUnits[0] = ta;
// ioUnits[1] = tb;
ioUnits[actIO++] = bcs;
USART usart0 = new USART(this, memory, 0x70);
USART usart1 = new USART(this, memory, 0x78);
ioUnits[actIO++] = usart0;
ioUnits[actIO++] = usart1;
for (int i = 0, n = 8; i < n; i++) {
memOut[0x70 + i] = usart0;
memIn[0x70 + i] = usart0;
memOut[0x78 + i] = usart1;
memIn[0x78 + i] = usart1;
}
ADC12 adc12 = new ADC12(this);
ioUnits[actIO++] = adc12;
for (int i = 0, n = 16; i < n; i++) {
memOut[0x80 + i] = adc12;
memIn[0x80 + i] = adc12;
memOut[0x140 + i] = adc12;
memIn[0x140 + i] = adc12;
memOut[0x150 + i] = adc12;
memIn[0x150 + i] = adc12;
}
for (int i = 0, n = 8; i < n; i++) {
memOut[0x1A0 + i] = adc12;
memIn[0x1A0 + i] = adc12;
}
// Add port 1,2 with interrupt capability!
passiveIOUnits[0] = new IOPort(this, "1", 4, memory, 0x20);
passiveIOUnits[1] = new IOPort(this, "2", 1, memory, 0x28);
for (int i = 0, n = 8; i < n; i++) {
memOut[0x20 + i] = passiveIOUnits[0];
memOut[0x28 + i] = passiveIOUnits[1];
}
// Add port 3,4 & 5,6
for (int i = 0, n = 2; i < n; i++) {
passiveIOUnits[i + 2] = new IOPort(this, "" + (3 + i), 0,
memory, 0x18 + i * 4);
memOut[0x18 + i * 4] = passiveIOUnits[i + 2];
memOut[0x19 + i * 4] = passiveIOUnits[i + 2];
memOut[0x1a + i * 4] = passiveIOUnits[i + 2];
memOut[0x1b + i * 4] = passiveIOUnits[i + 2];
passiveIOUnits[i + 4] = new IOPort(this, "" + (5 + i), 0,
memory, 0x30 + i * 4);
memOut[0x30 + i * 4] = passiveIOUnits[i + 4];
memOut[0x31 + i * 4] = passiveIOUnits[i + 4];
memOut[0x32 + i * 4] = passiveIOUnits[i + 4];
memOut[0x33 + i * 4] = passiveIOUnits[i + 4];
}
passIO = 6;
// Add the timers
passiveIOUnits[passIO++] = ta;
passiveIOUnits[passIO++] = tb;
initIOUnit();
}
public SFR getSFR() {
return sfr;
}
public void addIOUnit(int loReadMem, int hiReadMem,
int loWriteMem, int hiWriteMem,
IOUnit unit, boolean active) {
// Not implemented yet... IS it needed?
// if (loReadMem != -1) {
// for (int i = lo, n = hiMem; i < n; i++) {
// }
// }
if (active) {
ioUnits[lastIOUnitPos++] = unit;
}
}
public void setBreakPoint(int address, CPUMonitor mon) {
breakPoints[address] = mon;
}
public boolean hasBreakPoint(int address) {
return breakPoints[address] != null;
}
public void clearBreakPoint(int address) {
breakPoints[address] = null;
}
public void setRegisterWriteMonitor(int r, CPUMonitor mon) {
regWriteMonitors[r] = mon;
}
public void setRegisterReadMonitor(int r, CPUMonitor mon) {
regReadMonitors[r] = mon;
}
public int[] getMemory() {
return memory;
}
public void writeRegister(int r, int value) {
// Before the write!
if (regWriteMonitors[r] != null) {
regWriteMonitors[r].cpuAction(CPUMonitor.REGISTER_WRITE, r, value);
}
reg[r] = value;
if (r == SR) {
boolean oldCpuOff = cpuOff;
interruptsEnabled = ((value & GIE) == GIE);
cpuOff = ((value & CPUOFF) == CPUOFF);
if (cpuOff != oldCpuOff) {
// System.out.println("LPM CPUOff: " + cpuOff + " cycles: " + cycles);
}
if (cpuOff) {
boolean scg0 = (value & SCG0) == SCG0;
boolean scg1 = (value & SCG1) == SCG1;
boolean oscoff = (value & OSCOFF) == OSCOFF;
if (oscoff && scg1 && scg0) {
setMode(MODE_LPM4);
} else if (scg1 && scg0){
setMode(MODE_LPM3);
} else if (scg1) {
setMode(MODE_LPM2);
} else if (scg0) {
setMode(MODE_LPM1);
} else {
setMode(MODE_LPM0);
}
} else {
setMode(MODE_ACTIVE);
}
}
}
public int readRegister(int r) {
if (regReadMonitors[r] != null) {
regReadMonitors[r].cpuAction(CPUMonitor.REGISTER_READ, r, reg[r]);
}
return reg[r];
}
public int readRegisterCG(int r, int m) {
// CG1 + m == 0 => SR!
if ((r == CG1 && m != 0) || r == CG2) {
// No monitoring here... just return the CG values
return CREG_VALUES[r - 2][m];
}
if (regReadMonitors[r] != null) {
regReadMonitors[r].cpuAction(CPUMonitor.REGISTER_READ, r, reg[r]);
}
return reg[r];
}
public int incRegister(int r, int value) {
if (regReadMonitors[r] != null) {
regReadMonitors[r].cpuAction(CPUMonitor.REGISTER_READ, r, reg[r]);
}
if (regWriteMonitors[r] != null) {
regWriteMonitors[r].cpuAction(CPUMonitor.REGISTER_WRITE, r,
reg[r] + value);
}
reg[r] += value;
return reg[r];
}
public void setACLKFrq(int frequency) {
aclkFrq = frequency;
}
public void setDCOFrq(int frequency, int smclkFrq) {
dcoFrq = frequency;
this.smclkFrq = smclkFrq;
// update last virtual time before updating DCOfactor
lastCyclesTime = cycles;
lastVTime = getTime();
currentDCOFactor = 1.0 * BasicClockModule.MAX_DCO_FRQ / frequency;
if (DEBUG)
System.out.println("Set smclkFrq: " + smclkFrq);
}
// returns global time counted in max speed of DCOs (~5Mhz)
public long getTime() {
long diff = cycles - lastCyclesTime;
return lastVTime + (long) (diff * currentDCOFactor);
}
// Converts a virtual time to a cycles time according to the current
// cycle speed
private long convertVTime(long vTime) {
long tmpTime = lastCyclesTime + (long) ((vTime - lastVTime) / currentDCOFactor);
// System.out.println("ConvertVTime: vTime=" + vTime + " => " + tmpTime);
return tmpTime;
}
// get elapsed time in seconds
public double getTimeMillis() {
return 1000.0 * getTime() / BasicClockModule.MAX_DCO_FRQ;
}
private void executeEvents() {
if (cycles >= nextVTimeEventCycles) {
if (vTimeEventQueue.eventCount == 0) {
nextVTimeEventCycles = cycles + 10000;
} else {
TimeEvent te = vTimeEventQueue.popFirst();
long now = getTime();
te.execute(now);
if (vTimeEventQueue.eventCount > 0) {
nextVTimeEventCycles = convertVTime(vTimeEventQueue.nextTime);
} else {
nextVTimeEventCycles = cycles + 10000;
}
}
}
if (cycles >= nextCycleEventCycles) {
if (cycleEventQueue.eventCount == 0) {
nextCycleEventCycles = cycles + 10000;
} else {
TimeEvent te = cycleEventQueue.popFirst();
te.execute(cycles);
if (cycleEventQueue.eventCount > 0) {
nextCycleEventCycles = cycleEventQueue.nextTime;
} else {
nextCycleEventCycles = cycles + 10000;
}
}
}
// Pick the one with shortest time in the future.
nextEventCycles = nextCycleEventCycles < nextVTimeEventCycles ?
nextCycleEventCycles : nextVTimeEventCycles;
}
/**
* Schedules a new Time event using the cycles counter
* @param event
* @param time
*/
public void scheduleCycleEvent(TimeEvent event, long cycles) {
long currentNext = cycleEventQueue.nextTime;
cycleEventQueue.addEvent(event, cycles);
if (currentNext != cycleEventQueue.nextTime) {
nextCycleEventCycles = cycleEventQueue.nextTime;
if (nextEventCycles > nextCycleEventCycles) {
nextEventCycles = nextCycleEventCycles;
}
}
}
/**
* Schedules a new Time event using the virtual time clock
* @param event
* @param time
*/
public void scheduleTimeEvent(TimeEvent event, long time) {
long currentNext = vTimeEventQueue.nextTime;
vTimeEventQueue.addEvent(event, time);
if (currentNext != vTimeEventQueue.nextTime) {
// This is only valid when not having a cycle event queue also...
// if we have it needs to be checked also!
nextVTimeEventCycles = convertVTime(vTimeEventQueue.nextTime);
if (nextEventCycles > nextVTimeEventCycles) {
nextEventCycles = nextVTimeEventCycles;
}
}
}
/**
* Schedules a new Time event msec milliseconds in the future
* @param event
* @param time
*/
public long scheduleTimeEventMillis(TimeEvent event, double msec) {
long time = (long) (getTime() + msec / 1000 * BasicClockModule.MAX_DCO_FRQ);
// System.out.println("Scheduling at: " + time + " (" + msec + ") getTime: " + getTime());
scheduleTimeEvent(event, time);
return time;
}
// Should also return active units...
public IOUnit getIOUnit(String name) {
for (int i = 0, n = passiveIOUnits.length; i < n; i++) {
if (name.equals(passiveIOUnits[i].getName())) {
return passiveIOUnits[i];
}
}
for (int i = 0, n = ioUnits.length; i < n; i++) {
if (name.equals(ioUnits[i].getName())) {
return ioUnits[i];
}
}
return null;
}
private void initIOUnit() {
long smallestCyc = 10000000l;
for (int i = 0, n = lastIOUnitPos; i < n; i++) {
if ((ioCycles[i] = ioUnits[i].ioTick(0)) < smallestCyc) {
smallestCyc = ioCycles[i];
nextIOTickIndex = i;
}
}
}
private void resetIOUnits() {
for (int i = 0, n = lastIOUnitPos; i < n; i++) {
ioUnits[i].reset(RESET_POR);
}
for (int i = 0, n = passiveIOUnits.length; i < n; i++) {
passiveIOUnits[i].reset(RESET_POR);
}
}
private void internalReset() {
resetIOUnits();
for (int i = 0, n = 16; i < n; i++) {
interruptSource[i] = null;
}
servicedInterruptUnit = null;
servicedInterrupt = -1;
interruptMax = -1;
writeRegister(SR, 0);
cycleEventQueue.removeAll();
vTimeEventQueue.removeAll();
}
public void reset() {
// reg[PC] = memory[0xfffe] + (memory[0xffff] << 8);
// System.out.println("Reset the CPU: " + reg[PC]);
flagInterrupt(15, null, true);
}
// Indicate that we have an interrupt now!
// We should only get same IOUnit for same interrupt level
public void flagInterrupt(int interrupt, IOUnit source, boolean triggerIR) {
if (triggerIR) {
interruptSource[interrupt] = source;
if (debugInterrupts) {
if (source != null) {
System.out.println("### Interrupt flagged ON by " + source.getName());
} else {
System.out.println("### Interrupt flagged ON by <null>");
}
}
// MAX priority is executed first - update max if this is higher!
if (interrupt > interruptMax) {
interruptMax = interrupt;
if (interruptMax == 15) {
// This can not be masked at all!
interruptsEnabled = true;
}
}
} else {
if (interruptSource[interrupt] == source) {
if (debugInterrupts) {
System.out.println("### Interrupt flagged OFF by " + source.getName());
}
interruptSource[interrupt] = null;
}
}
}
// returns the currently serviced interrupt (vector ID)
public int getServicedInterrupt() {
return servicedInterrupt;
}
// This will be called after an interrupt have been handled
// In the main-CPU loop
public void handlePendingInterrupts() {
// By default no int. left to process...
interruptMax = -1;
// Find next pending interrupt
for (int i = 0, n = 16; i < n; i++) {
if (interruptSource[i] != null)
interruptMax = i;
}
servicedInterrupt = -1;
servicedInterruptUnit = null;
}
private void handleIO() {
// Call the IO unit!
// System.out.println("Calling: " + ioUnits[nextIOTickIndex].getName());
ioCycles[nextIOTickIndex] = ioUnits[nextIOTickIndex].ioTick(cycles);
// Find the next unit to call...
long smallestCyc = cycles + 1000000l;
int index = 0;
for (int i = 0, n = lastIOUnitPos; i < n; i++) {
if (ioCycles[i] < smallestCyc) {
smallestCyc = ioCycles[i];
index = i;
}
}
nextIOTickCycles = smallestCyc;
nextIOTickIndex = index;
// System.out.println("Smallest IO cycles: " + smallestCyc + " => " +
// ioUnits[index].getName());
}
// Read method that handles read from IO units!
public int read(int address, boolean word) {
int val = 0;
// Only word reads at 0x1fe which is highest address...
if (address < 0x1ff && memIn[address] != null) {
val = memIn[address].read(address, word, cycles);
} else {
address &= 0xffff;
val = memory[address] & 0xff;
if (word) {
val |= (memory[(address + 1) & 0xffff] << 8);
}
}
if (breakPoints[address] != null) {
breakPoints[address].cpuAction(CPUMonitor.MEMORY_READ, address, val);
}
return val;
}
public void write(int dstAddress, int dst, boolean word) {
if (breakPoints[dstAddress] != null) {
breakPoints[dstAddress].cpuAction(CPUMonitor.MEMORY_WRITE, dstAddress, dst);
}
// Only word writes at 0x1fe which is highest address...
if (dstAddress < 0x1ff && memOut[dstAddress] != null) {
if (!word) dst &= 0xff;
memOut[dstAddress].write(dstAddress, dst, word, cycles);
} else {
// TODO: add check for Flash / RAM!
memory[dstAddress] = dst & 0xff;
if (word) {
memory[dstAddress + 1] = (dst >> 8) & 0xff;
}
}
}
private int serviceInterrupt(int pc) {
int pcBefore = pc;
int spBefore = readRegister(SP);
int sp = spBefore;
int sr = readRegister(SR);
// Only store stuff on irq except reset... - not sure if this is correct...
// TODO: Check what to do if reset is called!
if (interruptMax < 15) {
// Push PC and SR to stack
// store on stack - always move 2 steps (W) even if B.
writeRegister(SP, sp = spBefore - 2);
// Put lo & hi on stack!
memory[sp] = pc & 0xff;
memory[sp + 1] = (pc >> 8) & 0xff;
writeRegister(SP, sp = sp - 2);
// Put lo & hi on stack!
memory[sp] = sr & 0xff;
memory[sp + 1] = (sr >> 8) & 0xff;
}
// Clear SR - except ...
// Jump to the address specified in the interrupt vector
writeRegister(PC, pc =
memory[0xffe0 + interruptMax * 2] +
(memory[0xffe0 + interruptMax * 2 + 1] << 8));
writeRegister(SR, sr & ~CPUOFF & ~SCG1 & ~OSCOFF);
servicedInterrupt = interruptMax;
servicedInterruptUnit = interruptSource[servicedInterrupt];
// Flag off this interrupt - for now - as soon as RETI is
// executed things might change!
interruptMax = -1;
if (servicedInterrupt == 15) {
// System.out.println("**** Servicing RESET! => " + Utils.hex16(pc));
internalReset();
}
// Interrupts take 6 cycles!
cycles += 6;
if (debugInterrupts) {
System.out.println("### Executing interrupt: " +
servicedInterrupt + " at "
+ pcBefore + " to " + pc +
" SP before: " + spBefore);
}
// And call the serviced routine (which can cause another interrupt)
if (servicedInterruptUnit != null) {
if (debugInterrupts) {
System.out.println("### Calling serviced interrupt on: " +
servicedInterruptUnit.getName());
}
servicedInterruptUnit.interruptServiced(servicedInterrupt);
}
return pc;
}
/* returns true if any instruction was emulated - false if CpuOff */
public boolean emulateOP() {
//System.out.println("CYCLES BEFORE: " + cycles);
int pc = readRegister(PC);
long startCycles = cycles;
// -------------------------------------------------------------------
// Event processing
// -------------------------------------------------------------------
if (cycles >= nextEventCycles) {
executeEvents();
}
// -------------------------------------------------------------------
// (old) I/O processing
// -------------------------------------------------------------------
if (cycles >= nextIOTickCycles) {
handleIO();
}
// -------------------------------------------------------------------
// Interrupt processing [after the last instruction was executed]
// -------------------------------------------------------------------
if (interruptsEnabled && servicedInterrupt == -1 && interruptMax >= 0) {
pc = serviceInterrupt(pc);
}
/* Did not execute any instructions */
if (cpuOff) {
// System.out.println("Jumping: " + (nextIOTickCycles - cycles));
cycles = nextIOTickCycles;
return false;
}
// This is quite costly... should probably be made more
// efficiently
if (breakPoints[pc] != null) {
if (breakpointActive) {
breakPoints[pc].cpuAction(CPUMonitor.BREAK, pc, 0);
breakpointActive = false;
return false;
} else {
// Execute this instruction - this is second call...
breakpointActive = true;
}
}
instruction = memory[pc] + (memory[pc + 1] << 8);
op = instruction >> 12;
int sp = 0;
int sr = 0;
boolean word = (instruction & 0x40) == 0;
// Destination vars
int dstRegister = 0;
int dstAddress = -1;
boolean dstRegMode = false;
int dst = 0;
boolean write = false;
boolean updateStatus = true;
// When is PC increased probably immediately (e.g. here)?
pc += 2;
writeRegister(PC, pc);
switch (op) {
case 1:
// -------------------------------------------------------------------
// Single operand instructions
// -------------------------------------------------------------------
{
// Register
dstRegister = instruction & 0xf;
// Adress mode of destination...
int ad = (instruction >> 4) & 3;
int nxtCarry = 0;
op = instruction & 0xff80;
if (op == PUSH) {
// The PUSH operation increase the SP before address resolution!
// store on stack - always move 2 steps (W) even if B./
sp = readRegister(SP) - 2;
writeRegister(SP, sp);
}
if ((dstRegister == CG1 && ad != AM_INDEX) || dstRegister == CG2) {
dstRegMode = true;
cycles++;
} else {
switch(ad) {
// Operand in register!
case AM_REG:
dstRegMode = true;
cycles++;
break;
case AM_INDEX:
dstAddress = readRegisterCG(dstRegister, ad) +
memory[pc] + (memory[pc + 1] << 8);
// When is PC incremented - assuming immediately after "read"?
pc += 2;
writeRegister(PC, pc);
cycles += 4;
break;
// Indirect register
case AM_IND_REG:
dstAddress = readRegister(dstRegister);
cycles += 3;
break;
// Bugfix suggested by Matt Thompson
case AM_IND_AUTOINC:
if(dstRegister == PC) {
dstAddress = readRegister(PC);
pc += 2;
writeRegister(PC, pc);
cycles += 5;
} else {
dstAddress = readRegister(dstRegister);
writeRegister(dstRegister, dstAddress + (word ? 2 : 1));
cycles += 3;
}
break;
}
// case AM_IND_AUTOINC:
// dstAddress = readRegister(dstRegister);
// writeRegister(dstRegister, dstAddress + (word ? 2 : 1));
// cycles += 3;
// break;
// }
}
// Perform the read
if (dstRegMode) {
dst = readRegisterCG(dstRegister, ad);
if (!word) {
dst &= 0xff;
}
} else {
dst = read(dstAddress, word);
}
switch(op) {
case RRC:
nxtCarry = (dst & 1) > 0 ? CARRY : 0;
dst = dst >> 1;
if (word) {
dst |= (readRegister(SR) & CARRY) > 0 ? 0x8000 : 0;
} else {
dst |= (readRegister(SR) & CARRY) > 0 ? 0x80 : 0;
}
// Indicate write to memory!!
write = true;
// Set the next carry!
writeRegister(SR, (readRegister(SR) & ~CARRY) | nxtCarry);
break;
case SWPB:
int tmp = dst;
dst = ((tmp >> 8) & 0xff) + ((tmp << 8) & 0xff00);
write = true;
break;
case RRA:
nxtCarry = (dst & 1) > 0 ? CARRY : 0;
if (word) {
dst = (dst & 0x8000) | (dst >> 1);
} else {
dst = (dst & 0x80) | (dst >> 1);
}
write = true;
writeRegister(SR, (readRegister(SR) & ~CARRY) | nxtCarry);
break;
case SXT:
// Extend Sign (bit 8-15 => same as bit 7)
dst = (dst & 0x80) > 0 ? dst | 0xff00 : dst & 0x7f;
write = true;
break;
case PUSH:
if (word) {
// Put lo & hi on stack!
memory[sp] = dst & 0xff;
memory[sp + 1] = dst >> 8;
} else {
// Byte => only lo byte
memory[sp] = dst & 0xff;
memory[sp + 1] = 0;
}
write = false;
updateStatus = false;
break;
case CALL:
// store current PC on stack... (current PC points to next instr.)
sp = readRegister(SP) - 2;
writeRegister(SP, sp);
pc = readRegister(PC);
memory[sp] = pc & 0xff;
memory[sp + 1] = pc >> 8;
writeRegister(PC, dst);
write = false;
updateStatus = false;
break;
case RETI:
// Put Top of stack to Status DstRegister (TOS -> SR)
sp = readRegister(SP);
writeRegister(SR, memory[sp++] + (memory[sp++] << 8));
// TOS -> PC
writeRegister(PC, memory[sp++] + (memory[sp++] << 8));
writeRegister(SP, sp);
write = false;
updateStatus = false;
if (debugInterrupts) {
System.out.println("### RETI at " + pc + " => " + reg[PC] +
" SP after: " + reg[SP]);
}
// This assumes that all interrupts will get back using RETI!
handlePendingInterrupts();
break;
default:
System.out.println("Error: Not implemented instruction:" +
instruction);
}
}
break;
// Jump instructions
case 2:
case 3:
// 10 bits for address for these => 0x00fc => remove 2 bits
int jmpOffset = instruction & 0x3ff;
jmpOffset = (jmpOffset & 0x200) == 0 ?
2 * jmpOffset : -(2 * (0x200 - (jmpOffset & 0x1ff)));
boolean jump = false;
// All jump takes two cycles
cycles += 2;
sr = readRegister(SR);
switch(instruction & 0xfc00) {
case JNE:
jump = (sr & ZERO) == 0;
break;
case JEQ:
jump = (sr & ZERO) > 0;
break;
case JNC:
jump = (sr & CARRY) == 0;
break;
case JC:
jump = (sr & CARRY) > 0;
break;
case JN:
jump = (sr & NEGATIVE) > 0;
break;
case JGE:
jump = (sr & NEGATIVE) > 0 == (sr & OVERFLOW) > 0;
break;
case JL:
jump = (sr & NEGATIVE) > 0 != (sr & OVERFLOW) > 0;
break;
case JMP:
jump = true;
break;
default:
System.out.println("Not implemented instruction: " +
Utils.binary16(instruction));
}
// Perform the Jump
if (jump) {
writeRegister(PC, pc + jmpOffset);
}
break;
default:
// ---------------------------------------------------------------
// Double operand instructions!
// ---------------------------------------------------------------
dstRegister = instruction & 0xf;
int srcRegister = (instruction >> 8) & 0xf;
int as = (instruction >> 4) & 3;
// AD: 0 => register direct, 1 => register index, e.g. X(Rn)
dstRegMode = ((instruction >> 7) & 1) == 0;
dstAddress = -1;
int srcAddress = -1;
int src = 0;
// Some CGs should be handled as registry reads only...
if ((srcRegister == CG1 && as != AM_INDEX) || srcRegister == CG2) {
src = CREG_VALUES[srcRegister - 2][as];
if (!word) {
src &= 0xff;
}
cycles += dstRegMode ? 1 : 4;
} else {
switch(as) {
// Operand in register!
case AM_REG:
// CG handled above!
src = readRegister(srcRegister);
if (!word) {
src &= 0xff;
}
cycles += dstRegMode ? 1 : 4;
break;
case AM_INDEX:
// Indexed if reg != PC & CG1/CG2 - will PC be incremented?
srcAddress = readRegisterCG(srcRegister, as) +
memory[pc] + (memory[pc + 1] << 8);
// When is PC incremented - assuming immediately after "read"?
incRegister(PC, 2);
cycles += dstRegMode ? 3 : 6;
break;
// Indirect register
case AM_IND_REG:
srcAddress = readRegister(srcRegister);
cycles += dstRegMode ? 2 : 5;
break;
case AM_IND_AUTOINC:
if (srcRegister == PC) {
srcAddress = readRegister(PC);
pc += 2;
incRegister(PC, 2);
cycles += 3;
} else {
srcAddress = readRegister(srcRegister);
incRegister(srcRegister, word ? 2 : 1);
cycles += dstRegMode ? 2 : 5;
}
break;
}
}
// Perform the read of destination!
if (dstRegMode) {
dst = readRegister(dstRegister);
if (!word) {
dst &= 0xff;
}
} else {
// PC Could have changed above!
pc = readRegister(PC);
if (dstRegister == 2) {
dstAddress = memory[pc] + (memory[pc + 1] << 8);
} else {
// CG here???
dstAddress = readRegister(dstRegister)
+ memory[pc] + (memory[pc + 1] << 8);
}
dst = read(dstAddress, word);
pc += 2;
incRegister(PC, 2);
}
// **** Perform the read...
if (srcAddress != -1) {
// Got very high address - check that?!!
srcAddress = srcAddress & 0xffff;
src = read(srcAddress, word);
// if (debug) {
// System.out.println("Reading from " + Utils.hex16(srcAddress) +
// " => " + src);
// }
}
int tmp = 0;
int tmpAdd = 0;
switch (op) {
case MOV: // MOV
dst = src;
write = true;
break;
// FIX THIS!!! - make SUB a separate operation so that
// it is clear that overflow flag is corretct...
case SUB:
// Carry always 1 with SUB
tmpAdd = 1;
case SUBC:
// Both sub and subc does one complement (not) + 1 (or carry)
src = (src ^ 0xffff) & 0xffff;
case ADDC: // ADDC
if (op == ADDC || op == SUBC)
tmpAdd = ((readRegister(SR) & CARRY) > 0) ? 1 : 0;
case ADD: // ADD
// Tmp gives zero if same sign! if sign is different after -> overf.
sr = readRegister(SR);
sr &= ~(OVERFLOW | CARRY);
tmp = (src ^ dst) & (word ? 0x8000 : 0x80);
// Includes carry if carry should be added...
dst = dst + src + tmpAdd;
if (dst > (word ? 0xffff : 0xff)) {
sr |= CARRY;
}
// If tmp == 0 and currenly not the same sign for src & dst
if (tmp == 0 && ((src ^ dst) & (word ? 0x8000 : 0x80)) != 0) {
sr |= OVERFLOW;
// System.out.println("OVERFLOW - ADD/SUB " + Utils.hex16(src)
// + " + " + Utils.hex16(tmpDst));
}
// System.out.println(Utils.hex16(dst) + " [SR=" +
// Utils.hex16(reg[SR]) + "]");
writeRegister(SR, sr);
write = true;
break;
case CMP: // CMP
// Set CARRY if A >= B, and it's clear if A < B
int b = word ? 0x8000 : 0x80;
sr = readRegister(SR);
sr = (sr & ~(CARRY | OVERFLOW)) | (dst >= src ? CARRY : 0);
tmp = dst - src;
if (((src ^ tmp) & b) == 0 && (((src ^ dst) & b) != 0)) {
sr |= OVERFLOW;
}
writeRegister(SR, sr);
// Must set dst to the result to set the rest of the status register
dst = tmp;
break;
case DADD: // DADD
if (DEBUG)
System.out.println("DADD: Decimal add executed - result error!!!");
// Decimal add... this is wrong... each nibble is 0-9...
// So this has to be reimplemented...
dst = dst + src + ((readRegister(SR) & CARRY) > 0 ? 1 : 0);
write = true;
break;
case BIT: // BIT
dst = src & dst;
sr = readRegister(SR);
// Clear overflow and carry!
sr = sr & ~(CARRY | OVERFLOW);
// Set carry if result is non-zero!
if (dst != 0) {
sr |= CARRY;
}
writeRegister(SR, sr);
break;
case BIC: // BIC
// No status reg change
// System.out.println("BIC: =>" + Utils.hex16(dstAddress) + " => "
// + Utils.hex16(dst) + " AS: " + as +
// " sReg: " + srcRegister + " => " + src +
// " dReg: " + dstRegister + " => " + dst);
dst = (~src) & dst;
write = true;
updateStatus = false;
break;
case BIS: // BIS
dst = src | dst;
write = true;
updateStatus = false;
break;
case XOR: // XOR
dst = src ^ dst;
write = true;
break;
case AND: // AND
dst = src & dst;
write = true;
break;
default:
System.out.println("DoubleOperand not implemented: " + op +
" at " + pc);
}
}
dst &= 0xffff;
if (write) {
if (dstRegMode) {
+ if (!word) dst &= 0xff;
writeRegister(dstRegister, dst);
} else {
dstAddress &= 0xffff;
write(dstAddress, dst, word);
}
}
if (updateStatus) {
// Update the Zero and Negative status!
// Carry and overflow must be set separately!
sr = readRegister(SR);
sr = (sr & ~(ZERO | NEGATIVE)) |
((dst == 0) ? ZERO : 0) |
(word ? ((dst & 0x8000) > 0 ? NEGATIVE : 0) :
((dst & 0x80) > 0 ? NEGATIVE : 0));
writeRegister(SR, sr);
}
//System.out.println("CYCLES AFTER: " + cycles);
cpuCycles += cycles - startCycles;
return true;
}
public String getName() {
return "MSP430 Core";
}
public int getModeMax() {
return MODE_MAX;
}
}
| true | true | public boolean emulateOP() {
//System.out.println("CYCLES BEFORE: " + cycles);
int pc = readRegister(PC);
long startCycles = cycles;
// -------------------------------------------------------------------
// Event processing
// -------------------------------------------------------------------
if (cycles >= nextEventCycles) {
executeEvents();
}
// -------------------------------------------------------------------
// (old) I/O processing
// -------------------------------------------------------------------
if (cycles >= nextIOTickCycles) {
handleIO();
}
// -------------------------------------------------------------------
// Interrupt processing [after the last instruction was executed]
// -------------------------------------------------------------------
if (interruptsEnabled && servicedInterrupt == -1 && interruptMax >= 0) {
pc = serviceInterrupt(pc);
}
/* Did not execute any instructions */
if (cpuOff) {
// System.out.println("Jumping: " + (nextIOTickCycles - cycles));
cycles = nextIOTickCycles;
return false;
}
// This is quite costly... should probably be made more
// efficiently
if (breakPoints[pc] != null) {
if (breakpointActive) {
breakPoints[pc].cpuAction(CPUMonitor.BREAK, pc, 0);
breakpointActive = false;
return false;
} else {
// Execute this instruction - this is second call...
breakpointActive = true;
}
}
instruction = memory[pc] + (memory[pc + 1] << 8);
op = instruction >> 12;
int sp = 0;
int sr = 0;
boolean word = (instruction & 0x40) == 0;
// Destination vars
int dstRegister = 0;
int dstAddress = -1;
boolean dstRegMode = false;
int dst = 0;
boolean write = false;
boolean updateStatus = true;
// When is PC increased probably immediately (e.g. here)?
pc += 2;
writeRegister(PC, pc);
switch (op) {
case 1:
// -------------------------------------------------------------------
// Single operand instructions
// -------------------------------------------------------------------
{
// Register
dstRegister = instruction & 0xf;
// Adress mode of destination...
int ad = (instruction >> 4) & 3;
int nxtCarry = 0;
op = instruction & 0xff80;
if (op == PUSH) {
// The PUSH operation increase the SP before address resolution!
// store on stack - always move 2 steps (W) even if B./
sp = readRegister(SP) - 2;
writeRegister(SP, sp);
}
if ((dstRegister == CG1 && ad != AM_INDEX) || dstRegister == CG2) {
dstRegMode = true;
cycles++;
} else {
switch(ad) {
// Operand in register!
case AM_REG:
dstRegMode = true;
cycles++;
break;
case AM_INDEX:
dstAddress = readRegisterCG(dstRegister, ad) +
memory[pc] + (memory[pc + 1] << 8);
// When is PC incremented - assuming immediately after "read"?
pc += 2;
writeRegister(PC, pc);
cycles += 4;
break;
// Indirect register
case AM_IND_REG:
dstAddress = readRegister(dstRegister);
cycles += 3;
break;
// Bugfix suggested by Matt Thompson
case AM_IND_AUTOINC:
if(dstRegister == PC) {
dstAddress = readRegister(PC);
pc += 2;
writeRegister(PC, pc);
cycles += 5;
} else {
dstAddress = readRegister(dstRegister);
writeRegister(dstRegister, dstAddress + (word ? 2 : 1));
cycles += 3;
}
break;
}
// case AM_IND_AUTOINC:
// dstAddress = readRegister(dstRegister);
// writeRegister(dstRegister, dstAddress + (word ? 2 : 1));
// cycles += 3;
// break;
// }
}
// Perform the read
if (dstRegMode) {
dst = readRegisterCG(dstRegister, ad);
if (!word) {
dst &= 0xff;
}
} else {
dst = read(dstAddress, word);
}
switch(op) {
case RRC:
nxtCarry = (dst & 1) > 0 ? CARRY : 0;
dst = dst >> 1;
if (word) {
dst |= (readRegister(SR) & CARRY) > 0 ? 0x8000 : 0;
} else {
dst |= (readRegister(SR) & CARRY) > 0 ? 0x80 : 0;
}
// Indicate write to memory!!
write = true;
// Set the next carry!
writeRegister(SR, (readRegister(SR) & ~CARRY) | nxtCarry);
break;
case SWPB:
int tmp = dst;
dst = ((tmp >> 8) & 0xff) + ((tmp << 8) & 0xff00);
write = true;
break;
case RRA:
nxtCarry = (dst & 1) > 0 ? CARRY : 0;
if (word) {
dst = (dst & 0x8000) | (dst >> 1);
} else {
dst = (dst & 0x80) | (dst >> 1);
}
write = true;
writeRegister(SR, (readRegister(SR) & ~CARRY) | nxtCarry);
break;
case SXT:
// Extend Sign (bit 8-15 => same as bit 7)
dst = (dst & 0x80) > 0 ? dst | 0xff00 : dst & 0x7f;
write = true;
break;
case PUSH:
if (word) {
// Put lo & hi on stack!
memory[sp] = dst & 0xff;
memory[sp + 1] = dst >> 8;
} else {
// Byte => only lo byte
memory[sp] = dst & 0xff;
memory[sp + 1] = 0;
}
write = false;
updateStatus = false;
break;
case CALL:
// store current PC on stack... (current PC points to next instr.)
sp = readRegister(SP) - 2;
writeRegister(SP, sp);
pc = readRegister(PC);
memory[sp] = pc & 0xff;
memory[sp + 1] = pc >> 8;
writeRegister(PC, dst);
write = false;
updateStatus = false;
break;
case RETI:
// Put Top of stack to Status DstRegister (TOS -> SR)
sp = readRegister(SP);
writeRegister(SR, memory[sp++] + (memory[sp++] << 8));
// TOS -> PC
writeRegister(PC, memory[sp++] + (memory[sp++] << 8));
writeRegister(SP, sp);
write = false;
updateStatus = false;
if (debugInterrupts) {
System.out.println("### RETI at " + pc + " => " + reg[PC] +
" SP after: " + reg[SP]);
}
// This assumes that all interrupts will get back using RETI!
handlePendingInterrupts();
break;
default:
System.out.println("Error: Not implemented instruction:" +
instruction);
}
}
break;
// Jump instructions
case 2:
case 3:
// 10 bits for address for these => 0x00fc => remove 2 bits
int jmpOffset = instruction & 0x3ff;
jmpOffset = (jmpOffset & 0x200) == 0 ?
2 * jmpOffset : -(2 * (0x200 - (jmpOffset & 0x1ff)));
boolean jump = false;
// All jump takes two cycles
cycles += 2;
sr = readRegister(SR);
switch(instruction & 0xfc00) {
case JNE:
jump = (sr & ZERO) == 0;
break;
case JEQ:
jump = (sr & ZERO) > 0;
break;
case JNC:
jump = (sr & CARRY) == 0;
break;
case JC:
jump = (sr & CARRY) > 0;
break;
case JN:
jump = (sr & NEGATIVE) > 0;
break;
case JGE:
jump = (sr & NEGATIVE) > 0 == (sr & OVERFLOW) > 0;
break;
case JL:
jump = (sr & NEGATIVE) > 0 != (sr & OVERFLOW) > 0;
break;
case JMP:
jump = true;
break;
default:
System.out.println("Not implemented instruction: " +
Utils.binary16(instruction));
}
// Perform the Jump
if (jump) {
writeRegister(PC, pc + jmpOffset);
}
break;
default:
// ---------------------------------------------------------------
// Double operand instructions!
// ---------------------------------------------------------------
dstRegister = instruction & 0xf;
int srcRegister = (instruction >> 8) & 0xf;
int as = (instruction >> 4) & 3;
// AD: 0 => register direct, 1 => register index, e.g. X(Rn)
dstRegMode = ((instruction >> 7) & 1) == 0;
dstAddress = -1;
int srcAddress = -1;
int src = 0;
// Some CGs should be handled as registry reads only...
if ((srcRegister == CG1 && as != AM_INDEX) || srcRegister == CG2) {
src = CREG_VALUES[srcRegister - 2][as];
if (!word) {
src &= 0xff;
}
cycles += dstRegMode ? 1 : 4;
} else {
switch(as) {
// Operand in register!
case AM_REG:
// CG handled above!
src = readRegister(srcRegister);
if (!word) {
src &= 0xff;
}
cycles += dstRegMode ? 1 : 4;
break;
case AM_INDEX:
// Indexed if reg != PC & CG1/CG2 - will PC be incremented?
srcAddress = readRegisterCG(srcRegister, as) +
memory[pc] + (memory[pc + 1] << 8);
// When is PC incremented - assuming immediately after "read"?
incRegister(PC, 2);
cycles += dstRegMode ? 3 : 6;
break;
// Indirect register
case AM_IND_REG:
srcAddress = readRegister(srcRegister);
cycles += dstRegMode ? 2 : 5;
break;
case AM_IND_AUTOINC:
if (srcRegister == PC) {
srcAddress = readRegister(PC);
pc += 2;
incRegister(PC, 2);
cycles += 3;
} else {
srcAddress = readRegister(srcRegister);
incRegister(srcRegister, word ? 2 : 1);
cycles += dstRegMode ? 2 : 5;
}
break;
}
}
// Perform the read of destination!
if (dstRegMode) {
dst = readRegister(dstRegister);
if (!word) {
dst &= 0xff;
}
} else {
// PC Could have changed above!
pc = readRegister(PC);
if (dstRegister == 2) {
dstAddress = memory[pc] + (memory[pc + 1] << 8);
} else {
// CG here???
dstAddress = readRegister(dstRegister)
+ memory[pc] + (memory[pc + 1] << 8);
}
dst = read(dstAddress, word);
pc += 2;
incRegister(PC, 2);
}
// **** Perform the read...
if (srcAddress != -1) {
// Got very high address - check that?!!
srcAddress = srcAddress & 0xffff;
src = read(srcAddress, word);
// if (debug) {
// System.out.println("Reading from " + Utils.hex16(srcAddress) +
// " => " + src);
// }
}
int tmp = 0;
int tmpAdd = 0;
switch (op) {
case MOV: // MOV
dst = src;
write = true;
break;
// FIX THIS!!! - make SUB a separate operation so that
// it is clear that overflow flag is corretct...
case SUB:
// Carry always 1 with SUB
tmpAdd = 1;
case SUBC:
// Both sub and subc does one complement (not) + 1 (or carry)
src = (src ^ 0xffff) & 0xffff;
case ADDC: // ADDC
if (op == ADDC || op == SUBC)
tmpAdd = ((readRegister(SR) & CARRY) > 0) ? 1 : 0;
case ADD: // ADD
// Tmp gives zero if same sign! if sign is different after -> overf.
sr = readRegister(SR);
sr &= ~(OVERFLOW | CARRY);
tmp = (src ^ dst) & (word ? 0x8000 : 0x80);
// Includes carry if carry should be added...
dst = dst + src + tmpAdd;
if (dst > (word ? 0xffff : 0xff)) {
sr |= CARRY;
}
// If tmp == 0 and currenly not the same sign for src & dst
if (tmp == 0 && ((src ^ dst) & (word ? 0x8000 : 0x80)) != 0) {
sr |= OVERFLOW;
// System.out.println("OVERFLOW - ADD/SUB " + Utils.hex16(src)
// + " + " + Utils.hex16(tmpDst));
}
// System.out.println(Utils.hex16(dst) + " [SR=" +
// Utils.hex16(reg[SR]) + "]");
writeRegister(SR, sr);
write = true;
break;
case CMP: // CMP
// Set CARRY if A >= B, and it's clear if A < B
int b = word ? 0x8000 : 0x80;
sr = readRegister(SR);
sr = (sr & ~(CARRY | OVERFLOW)) | (dst >= src ? CARRY : 0);
tmp = dst - src;
if (((src ^ tmp) & b) == 0 && (((src ^ dst) & b) != 0)) {
sr |= OVERFLOW;
}
writeRegister(SR, sr);
// Must set dst to the result to set the rest of the status register
dst = tmp;
break;
case DADD: // DADD
if (DEBUG)
System.out.println("DADD: Decimal add executed - result error!!!");
// Decimal add... this is wrong... each nibble is 0-9...
// So this has to be reimplemented...
dst = dst + src + ((readRegister(SR) & CARRY) > 0 ? 1 : 0);
write = true;
break;
case BIT: // BIT
dst = src & dst;
sr = readRegister(SR);
// Clear overflow and carry!
sr = sr & ~(CARRY | OVERFLOW);
// Set carry if result is non-zero!
if (dst != 0) {
sr |= CARRY;
}
writeRegister(SR, sr);
break;
case BIC: // BIC
// No status reg change
// System.out.println("BIC: =>" + Utils.hex16(dstAddress) + " => "
// + Utils.hex16(dst) + " AS: " + as +
// " sReg: " + srcRegister + " => " + src +
// " dReg: " + dstRegister + " => " + dst);
dst = (~src) & dst;
write = true;
updateStatus = false;
break;
case BIS: // BIS
dst = src | dst;
write = true;
updateStatus = false;
break;
case XOR: // XOR
dst = src ^ dst;
write = true;
break;
case AND: // AND
dst = src & dst;
write = true;
break;
default:
System.out.println("DoubleOperand not implemented: " + op +
" at " + pc);
}
}
dst &= 0xffff;
if (write) {
if (dstRegMode) {
writeRegister(dstRegister, dst);
} else {
dstAddress &= 0xffff;
write(dstAddress, dst, word);
}
}
if (updateStatus) {
// Update the Zero and Negative status!
// Carry and overflow must be set separately!
sr = readRegister(SR);
sr = (sr & ~(ZERO | NEGATIVE)) |
((dst == 0) ? ZERO : 0) |
(word ? ((dst & 0x8000) > 0 ? NEGATIVE : 0) :
((dst & 0x80) > 0 ? NEGATIVE : 0));
writeRegister(SR, sr);
}
//System.out.println("CYCLES AFTER: " + cycles);
cpuCycles += cycles - startCycles;
return true;
}
| public boolean emulateOP() {
//System.out.println("CYCLES BEFORE: " + cycles);
int pc = readRegister(PC);
long startCycles = cycles;
// -------------------------------------------------------------------
// Event processing
// -------------------------------------------------------------------
if (cycles >= nextEventCycles) {
executeEvents();
}
// -------------------------------------------------------------------
// (old) I/O processing
// -------------------------------------------------------------------
if (cycles >= nextIOTickCycles) {
handleIO();
}
// -------------------------------------------------------------------
// Interrupt processing [after the last instruction was executed]
// -------------------------------------------------------------------
if (interruptsEnabled && servicedInterrupt == -1 && interruptMax >= 0) {
pc = serviceInterrupt(pc);
}
/* Did not execute any instructions */
if (cpuOff) {
// System.out.println("Jumping: " + (nextIOTickCycles - cycles));
cycles = nextIOTickCycles;
return false;
}
// This is quite costly... should probably be made more
// efficiently
if (breakPoints[pc] != null) {
if (breakpointActive) {
breakPoints[pc].cpuAction(CPUMonitor.BREAK, pc, 0);
breakpointActive = false;
return false;
} else {
// Execute this instruction - this is second call...
breakpointActive = true;
}
}
instruction = memory[pc] + (memory[pc + 1] << 8);
op = instruction >> 12;
int sp = 0;
int sr = 0;
boolean word = (instruction & 0x40) == 0;
// Destination vars
int dstRegister = 0;
int dstAddress = -1;
boolean dstRegMode = false;
int dst = 0;
boolean write = false;
boolean updateStatus = true;
// When is PC increased probably immediately (e.g. here)?
pc += 2;
writeRegister(PC, pc);
switch (op) {
case 1:
// -------------------------------------------------------------------
// Single operand instructions
// -------------------------------------------------------------------
{
// Register
dstRegister = instruction & 0xf;
// Adress mode of destination...
int ad = (instruction >> 4) & 3;
int nxtCarry = 0;
op = instruction & 0xff80;
if (op == PUSH) {
// The PUSH operation increase the SP before address resolution!
// store on stack - always move 2 steps (W) even if B./
sp = readRegister(SP) - 2;
writeRegister(SP, sp);
}
if ((dstRegister == CG1 && ad != AM_INDEX) || dstRegister == CG2) {
dstRegMode = true;
cycles++;
} else {
switch(ad) {
// Operand in register!
case AM_REG:
dstRegMode = true;
cycles++;
break;
case AM_INDEX:
dstAddress = readRegisterCG(dstRegister, ad) +
memory[pc] + (memory[pc + 1] << 8);
// When is PC incremented - assuming immediately after "read"?
pc += 2;
writeRegister(PC, pc);
cycles += 4;
break;
// Indirect register
case AM_IND_REG:
dstAddress = readRegister(dstRegister);
cycles += 3;
break;
// Bugfix suggested by Matt Thompson
case AM_IND_AUTOINC:
if(dstRegister == PC) {
dstAddress = readRegister(PC);
pc += 2;
writeRegister(PC, pc);
cycles += 5;
} else {
dstAddress = readRegister(dstRegister);
writeRegister(dstRegister, dstAddress + (word ? 2 : 1));
cycles += 3;
}
break;
}
// case AM_IND_AUTOINC:
// dstAddress = readRegister(dstRegister);
// writeRegister(dstRegister, dstAddress + (word ? 2 : 1));
// cycles += 3;
// break;
// }
}
// Perform the read
if (dstRegMode) {
dst = readRegisterCG(dstRegister, ad);
if (!word) {
dst &= 0xff;
}
} else {
dst = read(dstAddress, word);
}
switch(op) {
case RRC:
nxtCarry = (dst & 1) > 0 ? CARRY : 0;
dst = dst >> 1;
if (word) {
dst |= (readRegister(SR) & CARRY) > 0 ? 0x8000 : 0;
} else {
dst |= (readRegister(SR) & CARRY) > 0 ? 0x80 : 0;
}
// Indicate write to memory!!
write = true;
// Set the next carry!
writeRegister(SR, (readRegister(SR) & ~CARRY) | nxtCarry);
break;
case SWPB:
int tmp = dst;
dst = ((tmp >> 8) & 0xff) + ((tmp << 8) & 0xff00);
write = true;
break;
case RRA:
nxtCarry = (dst & 1) > 0 ? CARRY : 0;
if (word) {
dst = (dst & 0x8000) | (dst >> 1);
} else {
dst = (dst & 0x80) | (dst >> 1);
}
write = true;
writeRegister(SR, (readRegister(SR) & ~CARRY) | nxtCarry);
break;
case SXT:
// Extend Sign (bit 8-15 => same as bit 7)
dst = (dst & 0x80) > 0 ? dst | 0xff00 : dst & 0x7f;
write = true;
break;
case PUSH:
if (word) {
// Put lo & hi on stack!
memory[sp] = dst & 0xff;
memory[sp + 1] = dst >> 8;
} else {
// Byte => only lo byte
memory[sp] = dst & 0xff;
memory[sp + 1] = 0;
}
write = false;
updateStatus = false;
break;
case CALL:
// store current PC on stack... (current PC points to next instr.)
sp = readRegister(SP) - 2;
writeRegister(SP, sp);
pc = readRegister(PC);
memory[sp] = pc & 0xff;
memory[sp + 1] = pc >> 8;
writeRegister(PC, dst);
write = false;
updateStatus = false;
break;
case RETI:
// Put Top of stack to Status DstRegister (TOS -> SR)
sp = readRegister(SP);
writeRegister(SR, memory[sp++] + (memory[sp++] << 8));
// TOS -> PC
writeRegister(PC, memory[sp++] + (memory[sp++] << 8));
writeRegister(SP, sp);
write = false;
updateStatus = false;
if (debugInterrupts) {
System.out.println("### RETI at " + pc + " => " + reg[PC] +
" SP after: " + reg[SP]);
}
// This assumes that all interrupts will get back using RETI!
handlePendingInterrupts();
break;
default:
System.out.println("Error: Not implemented instruction:" +
instruction);
}
}
break;
// Jump instructions
case 2:
case 3:
// 10 bits for address for these => 0x00fc => remove 2 bits
int jmpOffset = instruction & 0x3ff;
jmpOffset = (jmpOffset & 0x200) == 0 ?
2 * jmpOffset : -(2 * (0x200 - (jmpOffset & 0x1ff)));
boolean jump = false;
// All jump takes two cycles
cycles += 2;
sr = readRegister(SR);
switch(instruction & 0xfc00) {
case JNE:
jump = (sr & ZERO) == 0;
break;
case JEQ:
jump = (sr & ZERO) > 0;
break;
case JNC:
jump = (sr & CARRY) == 0;
break;
case JC:
jump = (sr & CARRY) > 0;
break;
case JN:
jump = (sr & NEGATIVE) > 0;
break;
case JGE:
jump = (sr & NEGATIVE) > 0 == (sr & OVERFLOW) > 0;
break;
case JL:
jump = (sr & NEGATIVE) > 0 != (sr & OVERFLOW) > 0;
break;
case JMP:
jump = true;
break;
default:
System.out.println("Not implemented instruction: " +
Utils.binary16(instruction));
}
// Perform the Jump
if (jump) {
writeRegister(PC, pc + jmpOffset);
}
break;
default:
// ---------------------------------------------------------------
// Double operand instructions!
// ---------------------------------------------------------------
dstRegister = instruction & 0xf;
int srcRegister = (instruction >> 8) & 0xf;
int as = (instruction >> 4) & 3;
// AD: 0 => register direct, 1 => register index, e.g. X(Rn)
dstRegMode = ((instruction >> 7) & 1) == 0;
dstAddress = -1;
int srcAddress = -1;
int src = 0;
// Some CGs should be handled as registry reads only...
if ((srcRegister == CG1 && as != AM_INDEX) || srcRegister == CG2) {
src = CREG_VALUES[srcRegister - 2][as];
if (!word) {
src &= 0xff;
}
cycles += dstRegMode ? 1 : 4;
} else {
switch(as) {
// Operand in register!
case AM_REG:
// CG handled above!
src = readRegister(srcRegister);
if (!word) {
src &= 0xff;
}
cycles += dstRegMode ? 1 : 4;
break;
case AM_INDEX:
// Indexed if reg != PC & CG1/CG2 - will PC be incremented?
srcAddress = readRegisterCG(srcRegister, as) +
memory[pc] + (memory[pc + 1] << 8);
// When is PC incremented - assuming immediately after "read"?
incRegister(PC, 2);
cycles += dstRegMode ? 3 : 6;
break;
// Indirect register
case AM_IND_REG:
srcAddress = readRegister(srcRegister);
cycles += dstRegMode ? 2 : 5;
break;
case AM_IND_AUTOINC:
if (srcRegister == PC) {
srcAddress = readRegister(PC);
pc += 2;
incRegister(PC, 2);
cycles += 3;
} else {
srcAddress = readRegister(srcRegister);
incRegister(srcRegister, word ? 2 : 1);
cycles += dstRegMode ? 2 : 5;
}
break;
}
}
// Perform the read of destination!
if (dstRegMode) {
dst = readRegister(dstRegister);
if (!word) {
dst &= 0xff;
}
} else {
// PC Could have changed above!
pc = readRegister(PC);
if (dstRegister == 2) {
dstAddress = memory[pc] + (memory[pc + 1] << 8);
} else {
// CG here???
dstAddress = readRegister(dstRegister)
+ memory[pc] + (memory[pc + 1] << 8);
}
dst = read(dstAddress, word);
pc += 2;
incRegister(PC, 2);
}
// **** Perform the read...
if (srcAddress != -1) {
// Got very high address - check that?!!
srcAddress = srcAddress & 0xffff;
src = read(srcAddress, word);
// if (debug) {
// System.out.println("Reading from " + Utils.hex16(srcAddress) +
// " => " + src);
// }
}
int tmp = 0;
int tmpAdd = 0;
switch (op) {
case MOV: // MOV
dst = src;
write = true;
break;
// FIX THIS!!! - make SUB a separate operation so that
// it is clear that overflow flag is corretct...
case SUB:
// Carry always 1 with SUB
tmpAdd = 1;
case SUBC:
// Both sub and subc does one complement (not) + 1 (or carry)
src = (src ^ 0xffff) & 0xffff;
case ADDC: // ADDC
if (op == ADDC || op == SUBC)
tmpAdd = ((readRegister(SR) & CARRY) > 0) ? 1 : 0;
case ADD: // ADD
// Tmp gives zero if same sign! if sign is different after -> overf.
sr = readRegister(SR);
sr &= ~(OVERFLOW | CARRY);
tmp = (src ^ dst) & (word ? 0x8000 : 0x80);
// Includes carry if carry should be added...
dst = dst + src + tmpAdd;
if (dst > (word ? 0xffff : 0xff)) {
sr |= CARRY;
}
// If tmp == 0 and currenly not the same sign for src & dst
if (tmp == 0 && ((src ^ dst) & (word ? 0x8000 : 0x80)) != 0) {
sr |= OVERFLOW;
// System.out.println("OVERFLOW - ADD/SUB " + Utils.hex16(src)
// + " + " + Utils.hex16(tmpDst));
}
// System.out.println(Utils.hex16(dst) + " [SR=" +
// Utils.hex16(reg[SR]) + "]");
writeRegister(SR, sr);
write = true;
break;
case CMP: // CMP
// Set CARRY if A >= B, and it's clear if A < B
int b = word ? 0x8000 : 0x80;
sr = readRegister(SR);
sr = (sr & ~(CARRY | OVERFLOW)) | (dst >= src ? CARRY : 0);
tmp = dst - src;
if (((src ^ tmp) & b) == 0 && (((src ^ dst) & b) != 0)) {
sr |= OVERFLOW;
}
writeRegister(SR, sr);
// Must set dst to the result to set the rest of the status register
dst = tmp;
break;
case DADD: // DADD
if (DEBUG)
System.out.println("DADD: Decimal add executed - result error!!!");
// Decimal add... this is wrong... each nibble is 0-9...
// So this has to be reimplemented...
dst = dst + src + ((readRegister(SR) & CARRY) > 0 ? 1 : 0);
write = true;
break;
case BIT: // BIT
dst = src & dst;
sr = readRegister(SR);
// Clear overflow and carry!
sr = sr & ~(CARRY | OVERFLOW);
// Set carry if result is non-zero!
if (dst != 0) {
sr |= CARRY;
}
writeRegister(SR, sr);
break;
case BIC: // BIC
// No status reg change
// System.out.println("BIC: =>" + Utils.hex16(dstAddress) + " => "
// + Utils.hex16(dst) + " AS: " + as +
// " sReg: " + srcRegister + " => " + src +
// " dReg: " + dstRegister + " => " + dst);
dst = (~src) & dst;
write = true;
updateStatus = false;
break;
case BIS: // BIS
dst = src | dst;
write = true;
updateStatus = false;
break;
case XOR: // XOR
dst = src ^ dst;
write = true;
break;
case AND: // AND
dst = src & dst;
write = true;
break;
default:
System.out.println("DoubleOperand not implemented: " + op +
" at " + pc);
}
}
dst &= 0xffff;
if (write) {
if (dstRegMode) {
if (!word) dst &= 0xff;
writeRegister(dstRegister, dst);
} else {
dstAddress &= 0xffff;
write(dstAddress, dst, word);
}
}
if (updateStatus) {
// Update the Zero and Negative status!
// Carry and overflow must be set separately!
sr = readRegister(SR);
sr = (sr & ~(ZERO | NEGATIVE)) |
((dst == 0) ? ZERO : 0) |
(word ? ((dst & 0x8000) > 0 ? NEGATIVE : 0) :
((dst & 0x80) > 0 ? NEGATIVE : 0));
writeRegister(SR, sr);
}
//System.out.println("CYCLES AFTER: " + cycles);
cpuCycles += cycles - startCycles;
return true;
}
|
diff --git a/src/java/org/grails/plugin/config/AbstractConfigHelper.java b/src/java/org/grails/plugin/config/AbstractConfigHelper.java
index 37bd017..730033b 100644
--- a/src/java/org/grails/plugin/config/AbstractConfigHelper.java
+++ b/src/java/org/grails/plugin/config/AbstractConfigHelper.java
@@ -1,371 +1,372 @@
/*
* Copyright 2011 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.grails.plugin.config;
import grails.util.Environment;
import grails.util.Metadata;
import groovy.lang.Closure;
import groovy.lang.GroovyClassLoader;
import groovy.lang.GroovyObject;
import groovy.util.ConfigObject;
import groovy.util.ConfigSlurper;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.codehaus.groovy.grails.commons.GrailsApplication;
import org.codehaus.groovy.grails.commons.GrailsClassUtils;
import org.codehaus.groovy.grails.commons.cfg.ConfigurationHelper;
import org.codehaus.groovy.grails.plugins.GrailsPlugin;
import org.codehaus.groovy.grails.plugins.GrailsPluginManager;
import org.springframework.context.ApplicationContext;
import org.springframework.util.Assert;
/**
* @author Daniel Henrique Alves Lima
*/
public abstract class AbstractConfigHelper {
private static final String GRAILS_PLUGIN_SUFFIX = "GrailsPlugin";
private static final String DEFAULT_CONFIG_SUFFIX = "DefaultConfig";
protected final Log log = LogFactory.getLog(getClass());
private GrailsPluginManager defaultPluginManager;
public void setDefaultPluginManager(GrailsPluginManager defaultPluginManager) {
if (log.isDebugEnabled()) {
log.debug("setPluginManager(): " + defaultPluginManager);
}
this.defaultPluginManager = defaultPluginManager;
}
public abstract void enhanceClasses();
public abstract void notifyConfigChange();
protected ConfigObject buildMergedConfig(GrailsPluginManager pluginManager,
GrailsApplication grailsApplication) {
if (log.isDebugEnabled()) {
log.debug("getMergedConfigImpl()");
}
Assert.notNull(pluginManager);
Assert.notNull(grailsApplication);
Metadata applicationMetaData = grailsApplication.getMetadata();
String applicationName = applicationMetaData.getApplicationName();
List<Class<?>> defaultConfigClasses = new ArrayList<Class<?>>();
/*
* Search for all the default configurations using the plugin manager
* processing order.
*/
List<Closure> afterConfigMergeClosures = new ArrayList<Closure>();
boolean classesLoaded = false;
if (grailsApplication.isInitialised()) {
Class<?>[] classes = grailsApplication.getAllClasses();
if (classes != null && classes.length > 0) {
classesLoaded = true;
}
}
- for (GrailsPlugin plugin : pluginManager.getAllPlugins()) {
+ GrailsPlugin[] allPlugins = pluginManager.getAllPlugins();
+ for (GrailsPlugin plugin : allPlugins) {
if (plugin.isEnabled()) {
Class<?> defaultConfigClass = null;
Class<?> pluginClass = plugin.getPluginClass();
org.codehaus.groovy.grails.plugins.metadata.GrailsPlugin pluginClassMetadata = null;
org.codehaus.groovy.grails.plugins.metadata.GrailsPlugin defaultConfigClassMetadata = null;
String configName = pluginClass.getSimpleName();
if (configName.endsWith(GRAILS_PLUGIN_SUFFIX)) {
configName = configName.replace(GRAILS_PLUGIN_SUFFIX, DEFAULT_CONFIG_SUFFIX);
} else {
configName = configName + DEFAULT_CONFIG_SUFFIX;
}
if (log.isDebugEnabled()) {
log.debug("getMergedConfigImpl(): configName " + configName);
}
if (classesLoaded) {
defaultConfigClass = grailsApplication.getClassForName(configName);
} else {
/*
* When called from doWithWebDescriptor, classes aren't loaded yet.
*/
try {
defaultConfigClass = grailsApplication.getClassLoader().loadClass(configName);
// defaultConfigClass = null;
} catch (ClassNotFoundException e) {
}
}
if (defaultConfigClass != null) {
/* The class is inside one grails-app subdirectory. */
pluginClassMetadata = pluginClass.getAnnotation(
org.codehaus.groovy.grails.plugins.metadata.GrailsPlugin.class);
defaultConfigClassMetadata = defaultConfigClass.getAnnotation(
org.codehaus.groovy.grails.plugins.metadata.GrailsPlugin.class);
if (log.isDebugEnabled()) {
log.debug("getMergedConfigImpl(): pluginClassMetadata " + pluginClassMetadata);
log.debug("getMergedConfigImpl(): defaultConfigClassMetadata " + defaultConfigClassMetadata);
}
if (pluginClassMetadata == null &&
defaultConfigClassMetadata == null ||
pluginClassMetadata != null &&
defaultConfigClassMetadata != null &&
pluginClassMetadata.name().equals(defaultConfigClassMetadata.name()) ||
/* Workaround when building this as a Grails 2.0.0 plugin. */ applicationName != null &&
applicationName.equals(plugin.getFileSystemShortName())) {
/* The default config belongs to this plugin. */
log.debug("getMergedConfigImpl(): default config found");
} else {
if (log.isWarnEnabled()) {
log.warn("getMergedConfigImpl(): " + defaultConfigClass + " doesn't belong to " + plugin.getName());
}
defaultConfigClass = null;
}
}
if (defaultConfigClass != null) {
defaultConfigClasses.add(defaultConfigClass);
}
GroovyObject pluginInstance = plugin.getInstance();
Object o = GrailsClassUtils.getPropertyOrStaticPropertyOrFieldValue(pluginInstance, "afterConfigMerge");
if (o != null) {
Closure c = null;
if (o instanceof Closure) {
c = (Closure) o;
if (c.getMaximumNumberOfParameters() > 0) {
afterConfigMergeClosures.add(c);
//c.setDelegate(plugin);
} else {
c = null;
}
}
if (c == null) {
if (log.isWarnEnabled()) {
log.warn("getMergedConfigImpl(): Invalid afterConfigMerge closure " + o);
}
}
}
}
}
if (log.isDebugEnabled()) {
log.debug("getMergedConfigImpl(): defaultConfigClasses " + defaultConfigClasses);
}
GroovyClassLoader classLoader = null;
ClassLoader parentClassLoader = grailsApplication.getClassLoader();
if (parentClassLoader == null) {
parentClassLoader = Thread.currentThread().getContextClassLoader();
if (parentClassLoader == null) {
parentClassLoader = getClass().getClassLoader();
}
}
if (parentClassLoader instanceof GroovyClassLoader) {
classLoader = (GroovyClassLoader) parentClassLoader;
} else {
classLoader = new GroovyClassLoader(parentClassLoader);
}
ConfigObject config = new ConfigObject();
mergeInDefaultConfigs(config, defaultConfigClasses, classLoader);
ConfigurationHelper.initConfig(config, null, classLoader);
config.merge(grailsApplication.getConfig());
if (log.isDebugEnabled()) {
log.debug("getMergedConfigImpl(): config " + config);
}
/*
* Executed the collected closures. It's the last chance of influencing
* the merged config.
*/
Map<String, Object> ctx = new LinkedHashMap<String, Object>();
ctx.put("appConfig", grailsApplication.getConfig());
ctx = Collections.unmodifiableMap(ctx);
Object arg = config;
Object[] args = new Object[]{config, ctx};
for (Closure closure : afterConfigMergeClosures) {
try {
if (closure.getMaximumNumberOfParameters() == 1) {
closure.call(arg);
} else {
closure.call(args);
}
} catch (RuntimeException e) {
log.error("getMergedConfigImpl(): error executing afterConfigClosure", e);
}
}
return config;
}
protected void mergeInDefaultConfigs(ConfigObject config, List<Class<?>> defaultConfigClasses, GroovyClassLoader classLoader) {
ConfigSlurper configSlurper = new ConfigSlurper(Environment
.getCurrent().getName());
configSlurper.setClassLoader(classLoader);
for (Class<?> defaultConfigClass : defaultConfigClasses) {
try {
configSlurper.setBinding(config);
ConfigObject newConfig = configSlurper.parse(defaultConfigClass);
if (log.isDebugEnabled()) {
log.debug("mergeInDefaultConfigs(): newConfig " + newConfig);
}
config.merge(newConfig);
} catch (RuntimeException e) {
log.error("mergeInDefaultConfigs(): Error merging "
+ defaultConfigClass, e);
}
}
if (log.isDebugEnabled()) {
log.debug("mergeInDefaultConfigs(): config " + config);
}
}
protected GrailsPluginManager getPluginManager(
GrailsApplication grailsApplication) {
GrailsPluginManager pluginManager = null;
{
ApplicationContext mainContext = grailsApplication.getMainContext();
if (mainContext != null) {
pluginManager = (GrailsPluginManager) mainContext
.getBean("pluginManager");
}
}
if (pluginManager == null) {
ApplicationContext mainContext = grailsApplication
.getParentContext();
if (mainContext != null) {
try {
pluginManager = (GrailsPluginManager) mainContext
.getBean("pluginManager");
} catch (org.springframework.beans.factory.NoSuchBeanDefinitionException e) {
/* Workaround for Grails 2.0.0. */
log.warn("getPluginManager()", e);
}
}
}
if (pluginManager == null) {
pluginManager = defaultPluginManager;
}
Assert.notNull(pluginManager);
return pluginManager;
}
protected static class ConfigObjectProxy implements InvocationHandler {
private static final Log LOG = LogFactory
.getLog(ConfigObjectProxy.class);
private boolean isCheckedMap;
private Map<Object, Object> config;
public static Object newInstance(Map<Object, Object> config,
boolean isCheckedMap) {
ClassLoader cl = config.getClass().getClassLoader();
Class<?>[] configInterfaces = config.getClass().getInterfaces();
Set<Class<?>> interfaces = new LinkedHashSet<Class<?>>(
Arrays.asList(configInterfaces));
interfaces.add(Map.class);
Assert.notNull(interfaces.remove(GroovyObject.class));
@SuppressWarnings("unchecked")
Map<Object, Object> result = (Map<Object, Object>) java.lang.reflect.Proxy
.newProxyInstance(
cl,
interfaces.toArray(new Class<?>[interfaces.size()]),
new ConfigObjectProxy(config, isCheckedMap));
return result;
}
private ConfigObjectProxy(Map<Object, Object> config,
boolean isCheckedMap) {
this.config = config;
this.isCheckedMap = isCheckedMap;
}
@SuppressWarnings({"unchecked"})
public Object invoke(Object proxy, Method m, Object[] args) throws Throwable {
Object result = null;
try {
if (LOG.isDebugEnabled()) {
LOG.debug("before method " + m.getName());
}
if (m.getDeclaringClass().equals(Map.class) && m.getName().equals("get")) {
boolean containsKey = config.containsKey(args[0]);
if (!containsKey) {
result = null;
if (isCheckedMap) {
throw new IllegalArgumentException("Inexistent key " + args[0]);
}
}
}
if (result == null) {
result = m.invoke(config, args);
}
if (result != null && result instanceof ConfigObject) {
result = newInstance((Map<Object, Object>) result, isCheckedMap);
}
/*
* } catch (Exception e) { throw new
* RuntimeException("unexpected invocation exception: " +
* e.getMessage());
*/
} finally {
if (LOG.isDebugEnabled()) {
LOG.debug("after method " + m.getName());
}
}
return result;
}
}
}
| true | true | protected ConfigObject buildMergedConfig(GrailsPluginManager pluginManager,
GrailsApplication grailsApplication) {
if (log.isDebugEnabled()) {
log.debug("getMergedConfigImpl()");
}
Assert.notNull(pluginManager);
Assert.notNull(grailsApplication);
Metadata applicationMetaData = grailsApplication.getMetadata();
String applicationName = applicationMetaData.getApplicationName();
List<Class<?>> defaultConfigClasses = new ArrayList<Class<?>>();
/*
* Search for all the default configurations using the plugin manager
* processing order.
*/
List<Closure> afterConfigMergeClosures = new ArrayList<Closure>();
boolean classesLoaded = false;
if (grailsApplication.isInitialised()) {
Class<?>[] classes = grailsApplication.getAllClasses();
if (classes != null && classes.length > 0) {
classesLoaded = true;
}
}
for (GrailsPlugin plugin : pluginManager.getAllPlugins()) {
if (plugin.isEnabled()) {
Class<?> defaultConfigClass = null;
Class<?> pluginClass = plugin.getPluginClass();
org.codehaus.groovy.grails.plugins.metadata.GrailsPlugin pluginClassMetadata = null;
org.codehaus.groovy.grails.plugins.metadata.GrailsPlugin defaultConfigClassMetadata = null;
String configName = pluginClass.getSimpleName();
if (configName.endsWith(GRAILS_PLUGIN_SUFFIX)) {
configName = configName.replace(GRAILS_PLUGIN_SUFFIX, DEFAULT_CONFIG_SUFFIX);
} else {
configName = configName + DEFAULT_CONFIG_SUFFIX;
}
if (log.isDebugEnabled()) {
log.debug("getMergedConfigImpl(): configName " + configName);
}
if (classesLoaded) {
defaultConfigClass = grailsApplication.getClassForName(configName);
} else {
/*
* When called from doWithWebDescriptor, classes aren't loaded yet.
*/
try {
defaultConfigClass = grailsApplication.getClassLoader().loadClass(configName);
// defaultConfigClass = null;
} catch (ClassNotFoundException e) {
}
}
if (defaultConfigClass != null) {
/* The class is inside one grails-app subdirectory. */
pluginClassMetadata = pluginClass.getAnnotation(
org.codehaus.groovy.grails.plugins.metadata.GrailsPlugin.class);
defaultConfigClassMetadata = defaultConfigClass.getAnnotation(
org.codehaus.groovy.grails.plugins.metadata.GrailsPlugin.class);
if (log.isDebugEnabled()) {
log.debug("getMergedConfigImpl(): pluginClassMetadata " + pluginClassMetadata);
log.debug("getMergedConfigImpl(): defaultConfigClassMetadata " + defaultConfigClassMetadata);
}
if (pluginClassMetadata == null &&
defaultConfigClassMetadata == null ||
pluginClassMetadata != null &&
defaultConfigClassMetadata != null &&
pluginClassMetadata.name().equals(defaultConfigClassMetadata.name()) ||
/* Workaround when building this as a Grails 2.0.0 plugin. */ applicationName != null &&
applicationName.equals(plugin.getFileSystemShortName())) {
/* The default config belongs to this plugin. */
log.debug("getMergedConfigImpl(): default config found");
} else {
if (log.isWarnEnabled()) {
log.warn("getMergedConfigImpl(): " + defaultConfigClass + " doesn't belong to " + plugin.getName());
}
defaultConfigClass = null;
}
}
if (defaultConfigClass != null) {
defaultConfigClasses.add(defaultConfigClass);
}
GroovyObject pluginInstance = plugin.getInstance();
Object o = GrailsClassUtils.getPropertyOrStaticPropertyOrFieldValue(pluginInstance, "afterConfigMerge");
if (o != null) {
Closure c = null;
if (o instanceof Closure) {
c = (Closure) o;
if (c.getMaximumNumberOfParameters() > 0) {
afterConfigMergeClosures.add(c);
//c.setDelegate(plugin);
} else {
c = null;
}
}
if (c == null) {
if (log.isWarnEnabled()) {
log.warn("getMergedConfigImpl(): Invalid afterConfigMerge closure " + o);
}
}
}
}
}
if (log.isDebugEnabled()) {
log.debug("getMergedConfigImpl(): defaultConfigClasses " + defaultConfigClasses);
}
GroovyClassLoader classLoader = null;
ClassLoader parentClassLoader = grailsApplication.getClassLoader();
if (parentClassLoader == null) {
parentClassLoader = Thread.currentThread().getContextClassLoader();
if (parentClassLoader == null) {
parentClassLoader = getClass().getClassLoader();
}
}
if (parentClassLoader instanceof GroovyClassLoader) {
classLoader = (GroovyClassLoader) parentClassLoader;
} else {
classLoader = new GroovyClassLoader(parentClassLoader);
}
ConfigObject config = new ConfigObject();
mergeInDefaultConfigs(config, defaultConfigClasses, classLoader);
ConfigurationHelper.initConfig(config, null, classLoader);
config.merge(grailsApplication.getConfig());
if (log.isDebugEnabled()) {
log.debug("getMergedConfigImpl(): config " + config);
}
/*
* Executed the collected closures. It's the last chance of influencing
* the merged config.
*/
Map<String, Object> ctx = new LinkedHashMap<String, Object>();
ctx.put("appConfig", grailsApplication.getConfig());
ctx = Collections.unmodifiableMap(ctx);
Object arg = config;
Object[] args = new Object[]{config, ctx};
for (Closure closure : afterConfigMergeClosures) {
try {
if (closure.getMaximumNumberOfParameters() == 1) {
closure.call(arg);
} else {
closure.call(args);
}
} catch (RuntimeException e) {
log.error("getMergedConfigImpl(): error executing afterConfigClosure", e);
}
}
return config;
}
| protected ConfigObject buildMergedConfig(GrailsPluginManager pluginManager,
GrailsApplication grailsApplication) {
if (log.isDebugEnabled()) {
log.debug("getMergedConfigImpl()");
}
Assert.notNull(pluginManager);
Assert.notNull(grailsApplication);
Metadata applicationMetaData = grailsApplication.getMetadata();
String applicationName = applicationMetaData.getApplicationName();
List<Class<?>> defaultConfigClasses = new ArrayList<Class<?>>();
/*
* Search for all the default configurations using the plugin manager
* processing order.
*/
List<Closure> afterConfigMergeClosures = new ArrayList<Closure>();
boolean classesLoaded = false;
if (grailsApplication.isInitialised()) {
Class<?>[] classes = grailsApplication.getAllClasses();
if (classes != null && classes.length > 0) {
classesLoaded = true;
}
}
GrailsPlugin[] allPlugins = pluginManager.getAllPlugins();
for (GrailsPlugin plugin : allPlugins) {
if (plugin.isEnabled()) {
Class<?> defaultConfigClass = null;
Class<?> pluginClass = plugin.getPluginClass();
org.codehaus.groovy.grails.plugins.metadata.GrailsPlugin pluginClassMetadata = null;
org.codehaus.groovy.grails.plugins.metadata.GrailsPlugin defaultConfigClassMetadata = null;
String configName = pluginClass.getSimpleName();
if (configName.endsWith(GRAILS_PLUGIN_SUFFIX)) {
configName = configName.replace(GRAILS_PLUGIN_SUFFIX, DEFAULT_CONFIG_SUFFIX);
} else {
configName = configName + DEFAULT_CONFIG_SUFFIX;
}
if (log.isDebugEnabled()) {
log.debug("getMergedConfigImpl(): configName " + configName);
}
if (classesLoaded) {
defaultConfigClass = grailsApplication.getClassForName(configName);
} else {
/*
* When called from doWithWebDescriptor, classes aren't loaded yet.
*/
try {
defaultConfigClass = grailsApplication.getClassLoader().loadClass(configName);
// defaultConfigClass = null;
} catch (ClassNotFoundException e) {
}
}
if (defaultConfigClass != null) {
/* The class is inside one grails-app subdirectory. */
pluginClassMetadata = pluginClass.getAnnotation(
org.codehaus.groovy.grails.plugins.metadata.GrailsPlugin.class);
defaultConfigClassMetadata = defaultConfigClass.getAnnotation(
org.codehaus.groovy.grails.plugins.metadata.GrailsPlugin.class);
if (log.isDebugEnabled()) {
log.debug("getMergedConfigImpl(): pluginClassMetadata " + pluginClassMetadata);
log.debug("getMergedConfigImpl(): defaultConfigClassMetadata " + defaultConfigClassMetadata);
}
if (pluginClassMetadata == null &&
defaultConfigClassMetadata == null ||
pluginClassMetadata != null &&
defaultConfigClassMetadata != null &&
pluginClassMetadata.name().equals(defaultConfigClassMetadata.name()) ||
/* Workaround when building this as a Grails 2.0.0 plugin. */ applicationName != null &&
applicationName.equals(plugin.getFileSystemShortName())) {
/* The default config belongs to this plugin. */
log.debug("getMergedConfigImpl(): default config found");
} else {
if (log.isWarnEnabled()) {
log.warn("getMergedConfigImpl(): " + defaultConfigClass + " doesn't belong to " + plugin.getName());
}
defaultConfigClass = null;
}
}
if (defaultConfigClass != null) {
defaultConfigClasses.add(defaultConfigClass);
}
GroovyObject pluginInstance = plugin.getInstance();
Object o = GrailsClassUtils.getPropertyOrStaticPropertyOrFieldValue(pluginInstance, "afterConfigMerge");
if (o != null) {
Closure c = null;
if (o instanceof Closure) {
c = (Closure) o;
if (c.getMaximumNumberOfParameters() > 0) {
afterConfigMergeClosures.add(c);
//c.setDelegate(plugin);
} else {
c = null;
}
}
if (c == null) {
if (log.isWarnEnabled()) {
log.warn("getMergedConfigImpl(): Invalid afterConfigMerge closure " + o);
}
}
}
}
}
if (log.isDebugEnabled()) {
log.debug("getMergedConfigImpl(): defaultConfigClasses " + defaultConfigClasses);
}
GroovyClassLoader classLoader = null;
ClassLoader parentClassLoader = grailsApplication.getClassLoader();
if (parentClassLoader == null) {
parentClassLoader = Thread.currentThread().getContextClassLoader();
if (parentClassLoader == null) {
parentClassLoader = getClass().getClassLoader();
}
}
if (parentClassLoader instanceof GroovyClassLoader) {
classLoader = (GroovyClassLoader) parentClassLoader;
} else {
classLoader = new GroovyClassLoader(parentClassLoader);
}
ConfigObject config = new ConfigObject();
mergeInDefaultConfigs(config, defaultConfigClasses, classLoader);
ConfigurationHelper.initConfig(config, null, classLoader);
config.merge(grailsApplication.getConfig());
if (log.isDebugEnabled()) {
log.debug("getMergedConfigImpl(): config " + config);
}
/*
* Executed the collected closures. It's the last chance of influencing
* the merged config.
*/
Map<String, Object> ctx = new LinkedHashMap<String, Object>();
ctx.put("appConfig", grailsApplication.getConfig());
ctx = Collections.unmodifiableMap(ctx);
Object arg = config;
Object[] args = new Object[]{config, ctx};
for (Closure closure : afterConfigMergeClosures) {
try {
if (closure.getMaximumNumberOfParameters() == 1) {
closure.call(arg);
} else {
closure.call(args);
}
} catch (RuntimeException e) {
log.error("getMergedConfigImpl(): error executing afterConfigClosure", e);
}
}
return config;
}
|
diff --git a/src/checkstyle/com/puppycrawl/tools/checkstyle/ConfigurationLoader.java b/src/checkstyle/com/puppycrawl/tools/checkstyle/ConfigurationLoader.java
index 11e99b9c..2eec1a9d 100644
--- a/src/checkstyle/com/puppycrawl/tools/checkstyle/ConfigurationLoader.java
+++ b/src/checkstyle/com/puppycrawl/tools/checkstyle/ConfigurationLoader.java
@@ -1,172 +1,174 @@
////////////////////////////////////////////////////////////////////////////////
// checkstyle: Checks Java source code for adherence to a set of rules.
// Copyright (C) 2001-2002 Oliver Burn
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
////////////////////////////////////////////////////////////////////////////////
package com.puppycrawl.tools.checkstyle;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Properties;
import java.util.Stack;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParserFactory;
import com.puppycrawl.tools.checkstyle.api.Configuration;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import com.puppycrawl.tools.checkstyle.api.CheckstyleException;
// TODO: Fix the loader so it doesn't validate the document
/**
* Describe class <code>ConfigurationLoader</code> here.
*
* @author <a href="mailto:[email protected]">Oliver Burn</a>
* @version 1.0
*/
class ConfigurationLoader
extends DefaultHandler
{
/** overriding properties **/
private Properties mOverrideProps = new Properties();
/** parser to read XML files **/
private final XMLReader mParser;
/** the loaded configuration **/
private Stack mConfigStack = new Stack();
/** the Configuration that is beeing built */
private Configuration mConfiguration = null;
/**
* Creates a new <code>ConfigurationLoader</code> instance.
* @throws ParserConfigurationException if an error occurs
* @throws SAXException if an error occurs
*/
private ConfigurationLoader()
throws ParserConfigurationException, SAXException
{
mParser = SAXParserFactory.newInstance().newSAXParser().getXMLReader();
mParser.setContentHandler(this);
}
/**
* Parses the specified file loading the configuration information.
* @param aFilename the file to parse
* @throws FileNotFoundException if an error occurs
* @throws IOException if an error occurs
* @throws SAXException if an error occurs
*/
void parseFile(String aFilename)
throws FileNotFoundException, IOException, SAXException
{
mParser.parse(new InputSource(new FileReader(aFilename)));
}
///////////////////////////////////////////////////////////////////////////
// Document handler methods
///////////////////////////////////////////////////////////////////////////
/** @see org.xml.sax.helpers.DefaultHandler **/
public void startElement(String aNamespaceURI,
String aLocalName,
String aQName,
Attributes aAtts)
throws SAXException
{
// TODO: debug logging for support puposes
DefaultConfiguration conf = new DefaultConfiguration(aQName);
final int attCount = aAtts.getLength();
for (int i = 0; i < attCount; i++) {
String name = aAtts.getQName(i);
String value = aAtts.getValue(i);
// expand properties
if (value.startsWith("${") && value.endsWith("}")) {
String propName = value.substring(2, value.length() - 1);
value = mOverrideProps.getProperty(propName);
if (value == null) {
- throw new SAXException("missing external property " + propName);
+ throw new SAXException(
+ "missing external property " + propName);
}
}
conf.addAttribute(name, value);
}
if (mConfiguration == null) {
mConfiguration = conf;
}
if (!mConfigStack.isEmpty()) {
- DefaultConfiguration top = (DefaultConfiguration) mConfigStack.peek();
+ DefaultConfiguration top =
+ (DefaultConfiguration) mConfigStack.peek();
top.addChild(conf);
}
mConfigStack.push(conf);
}
/** @see org.xml.sax.helpers.DefaultHandler **/
public void endElement(String aNamespaceURI,
String aLocalName,
String aQName)
{
mConfigStack.pop();
}
/**
* Returns the check configurations in a specified file.
* @param aConfigFname name of config file
* @param aOverrideProps overriding properties
* @return the check configurations
* @throws CheckstyleException if an error occurs
*/
public static Configuration loadConfiguration(String aConfigFname,
Properties aOverrideProps)
throws CheckstyleException
{
try {
final ConfigurationLoader loader = new ConfigurationLoader();
loader.mOverrideProps = aOverrideProps;
loader.parseFile(aConfigFname);
return loader.getConfiguration();
}
catch (FileNotFoundException e) {
throw new CheckstyleException("unable to find " + aConfigFname);
}
catch (ParserConfigurationException e) {
throw new CheckstyleException("unable to parse " + aConfigFname);
}
catch (SAXException e) {
throw new CheckstyleException("unable to parse "
+ aConfigFname + " - " + e.getMessage());
}
catch (IOException e) {
throw new CheckstyleException("unable to read " + aConfigFname);
}
}
/**
* Returns the configuration in the last file parsed.
* @return Configuration object
*/
private Configuration getConfiguration()
{
return mConfiguration;
}
}
| false | true | public void startElement(String aNamespaceURI,
String aLocalName,
String aQName,
Attributes aAtts)
throws SAXException
{
// TODO: debug logging for support puposes
DefaultConfiguration conf = new DefaultConfiguration(aQName);
final int attCount = aAtts.getLength();
for (int i = 0; i < attCount; i++) {
String name = aAtts.getQName(i);
String value = aAtts.getValue(i);
// expand properties
if (value.startsWith("${") && value.endsWith("}")) {
String propName = value.substring(2, value.length() - 1);
value = mOverrideProps.getProperty(propName);
if (value == null) {
throw new SAXException("missing external property " + propName);
}
}
conf.addAttribute(name, value);
}
if (mConfiguration == null) {
mConfiguration = conf;
}
if (!mConfigStack.isEmpty()) {
DefaultConfiguration top = (DefaultConfiguration) mConfigStack.peek();
top.addChild(conf);
}
mConfigStack.push(conf);
}
| public void startElement(String aNamespaceURI,
String aLocalName,
String aQName,
Attributes aAtts)
throws SAXException
{
// TODO: debug logging for support puposes
DefaultConfiguration conf = new DefaultConfiguration(aQName);
final int attCount = aAtts.getLength();
for (int i = 0; i < attCount; i++) {
String name = aAtts.getQName(i);
String value = aAtts.getValue(i);
// expand properties
if (value.startsWith("${") && value.endsWith("}")) {
String propName = value.substring(2, value.length() - 1);
value = mOverrideProps.getProperty(propName);
if (value == null) {
throw new SAXException(
"missing external property " + propName);
}
}
conf.addAttribute(name, value);
}
if (mConfiguration == null) {
mConfiguration = conf;
}
if (!mConfigStack.isEmpty()) {
DefaultConfiguration top =
(DefaultConfiguration) mConfigStack.peek();
top.addChild(conf);
}
mConfigStack.push(conf);
}
|
diff --git a/test/edu/msu/cme/rdp/kmer/cli/KmerCoverageTest.java b/test/edu/msu/cme/rdp/kmer/cli/KmerCoverageTest.java
index d0deaa6..7cbf19d 100644
--- a/test/edu/msu/cme/rdp/kmer/cli/KmerCoverageTest.java
+++ b/test/edu/msu/cme/rdp/kmer/cli/KmerCoverageTest.java
@@ -1,112 +1,112 @@
/*
* Copyright (C) 2014 wangqion
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package edu.msu.cme.rdp.kmer.cli;
import edu.msu.cme.rdp.kmer.cli.KmerCoverage.Contig;
import edu.msu.cme.rdp.readseq.readers.SequenceReader;
import edu.msu.cme.rdp.readseq.readers.core.SeqReaderCore;
import edu.msu.cme.rdp.readseq.utils.SeqUtils;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.concurrent.ConcurrentHashMap;
import org.junit.Test;
import static org.junit.Assert.*;
/**
*
* @author wangqion
*/
public class KmerCoverageTest {
public KmerCoverageTest() {
}
/**
* Test of printCovereage method, of class KmerCoverage.
*/
@Test
public void testGetContigMap() throws Exception {
System.out.println("getContigMap");
int kmer_size = 30;
String contigs = ">contig1\n" +
"ccccacgagcaggcgaccaagcaaggcccgaagatcatggaattccggctcacggttga\n" +
">contig2\n" +
"caggcgaccaagcaaggcccgaagatcatggaattccggctcacggttgaggagaagcgaattgtcatcgacgacatgg\n" +
">contig3\n" +
"caggcgaccaagcaaggcccgaagatcatggaattccggctcacggttgagN\n";
String reads = ">r1\n" +
"ccccacgagcaggcgaccaagcaaggcccgaagatcatggaattccggctcacggttgaggagaagcgaattgtcatcgacgacatgg\n" +
">r2 reverse of r1 \n" +
"CCATGTCGTCGATGACAATTCGCTTCTCCTCAACCGTGAGCCGGAATTCCATGATCTTCGGGCCTTGCTTGGTCGCCTGCTCGTGGGG\n" +
">r3 one mismatch\n" +
"ccccacgagcaggcgaccaagcaaggcccgNagatcatggaattccggctcacggttgaggC";
SeqReaderCore readsReader = SeqUtils.getSeqReaderCore(new BufferedInputStream(new ByteArrayInputStream(reads.getBytes())));
SequenceReader contigReader = new SequenceReader(new BufferedInputStream(new ByteArrayInputStream(contigs.getBytes())));
ByteArrayOutputStream coverage_out = new ByteArrayOutputStream();
ByteArrayOutputStream abundance_out = new ByteArrayOutputStream();
KmerCoverage instance = new KmerCoverage(kmer_size, contigReader, readsReader, null);
ConcurrentHashMap<Integer, Contig> contigMap = instance.getContigMap();
// contig 1 should have full coverage
Contig contig1 = contigMap.get(0);
assertEquals(contig1.name, "contig1");
// offset from 1,
assertEquals(contig1.coverage[0], 3, 0.005);
assertEquals(contig1.coverage[8], 2, 0.005);
assertEquals(contig1.coverage[9], 0.6666, 0.005);
assertEquals(contig1.coverage[29], 0.6666, 0.005);
//contig2 is the reverse complement of contig1, should have the same coverage
Contig contig2 = contigMap.get(1);
assertEquals(contig2.name, "contig2");
// offset from 1,
assertEquals(contig2.coverage[0], 0.6666, 0.005);
assertEquals(contig2.coverage[20], 0.6666, 0.005);
assertEquals(contig2.coverage[21], 1, 0.005);
assertEquals(contig2.coverage[22], 3, 0.005);
assertEquals(contig2.coverage[23], 2, 0.005);
assertEquals(contig2.coverage[49], 2, 0.005);
//contig3 has a few mismatches
Contig contig3 = contigMap.get(2);
assertEquals(contig3.name, "contig3");
//offset from 1,
assertEquals(contig3.coverage[0], 0.6666, 0.005);
assertEquals(contig3.coverage[21], 1, 0.005);
assertEquals(contig3.coverage[22], 0, 0.005);
// check summary
instance.printCovereage(coverage_out, abundance_out);
String[] summary = coverage_out.toString().split("\n");
- assertEquals("contig1\t0.667\t1.100\t30\t30\t1.000", summary[1]);
- assertEquals("contig3\t0.667\t0.652\t23\t22\t0.957", summary[2]);
- assertEquals("contig2\t2.000\t1.440\t50\t50\t1.000", summary[3]);
+ assertEquals("contig1\t1.100\t0.667\t30\t30\t1.000", summary[3]);
+ assertEquals("contig3\t0.652\t0.667\t23\t22\t0.957", summary[4]);
+ assertEquals("contig2\t1.440\t2.000\t50\t50\t1.000", summary[5]);
}
}
| true | true | public void testGetContigMap() throws Exception {
System.out.println("getContigMap");
int kmer_size = 30;
String contigs = ">contig1\n" +
"ccccacgagcaggcgaccaagcaaggcccgaagatcatggaattccggctcacggttga\n" +
">contig2\n" +
"caggcgaccaagcaaggcccgaagatcatggaattccggctcacggttgaggagaagcgaattgtcatcgacgacatgg\n" +
">contig3\n" +
"caggcgaccaagcaaggcccgaagatcatggaattccggctcacggttgagN\n";
String reads = ">r1\n" +
"ccccacgagcaggcgaccaagcaaggcccgaagatcatggaattccggctcacggttgaggagaagcgaattgtcatcgacgacatgg\n" +
">r2 reverse of r1 \n" +
"CCATGTCGTCGATGACAATTCGCTTCTCCTCAACCGTGAGCCGGAATTCCATGATCTTCGGGCCTTGCTTGGTCGCCTGCTCGTGGGG\n" +
">r3 one mismatch\n" +
"ccccacgagcaggcgaccaagcaaggcccgNagatcatggaattccggctcacggttgaggC";
SeqReaderCore readsReader = SeqUtils.getSeqReaderCore(new BufferedInputStream(new ByteArrayInputStream(reads.getBytes())));
SequenceReader contigReader = new SequenceReader(new BufferedInputStream(new ByteArrayInputStream(contigs.getBytes())));
ByteArrayOutputStream coverage_out = new ByteArrayOutputStream();
ByteArrayOutputStream abundance_out = new ByteArrayOutputStream();
KmerCoverage instance = new KmerCoverage(kmer_size, contigReader, readsReader, null);
ConcurrentHashMap<Integer, Contig> contigMap = instance.getContigMap();
// contig 1 should have full coverage
Contig contig1 = contigMap.get(0);
assertEquals(contig1.name, "contig1");
// offset from 1,
assertEquals(contig1.coverage[0], 3, 0.005);
assertEquals(contig1.coverage[8], 2, 0.005);
assertEquals(contig1.coverage[9], 0.6666, 0.005);
assertEquals(contig1.coverage[29], 0.6666, 0.005);
//contig2 is the reverse complement of contig1, should have the same coverage
Contig contig2 = contigMap.get(1);
assertEquals(contig2.name, "contig2");
// offset from 1,
assertEquals(contig2.coverage[0], 0.6666, 0.005);
assertEquals(contig2.coverage[20], 0.6666, 0.005);
assertEquals(contig2.coverage[21], 1, 0.005);
assertEquals(contig2.coverage[22], 3, 0.005);
assertEquals(contig2.coverage[23], 2, 0.005);
assertEquals(contig2.coverage[49], 2, 0.005);
//contig3 has a few mismatches
Contig contig3 = contigMap.get(2);
assertEquals(contig3.name, "contig3");
//offset from 1,
assertEquals(contig3.coverage[0], 0.6666, 0.005);
assertEquals(contig3.coverage[21], 1, 0.005);
assertEquals(contig3.coverage[22], 0, 0.005);
// check summary
instance.printCovereage(coverage_out, abundance_out);
String[] summary = coverage_out.toString().split("\n");
assertEquals("contig1\t0.667\t1.100\t30\t30\t1.000", summary[1]);
assertEquals("contig3\t0.667\t0.652\t23\t22\t0.957", summary[2]);
assertEquals("contig2\t2.000\t1.440\t50\t50\t1.000", summary[3]);
}
| public void testGetContigMap() throws Exception {
System.out.println("getContigMap");
int kmer_size = 30;
String contigs = ">contig1\n" +
"ccccacgagcaggcgaccaagcaaggcccgaagatcatggaattccggctcacggttga\n" +
">contig2\n" +
"caggcgaccaagcaaggcccgaagatcatggaattccggctcacggttgaggagaagcgaattgtcatcgacgacatgg\n" +
">contig3\n" +
"caggcgaccaagcaaggcccgaagatcatggaattccggctcacggttgagN\n";
String reads = ">r1\n" +
"ccccacgagcaggcgaccaagcaaggcccgaagatcatggaattccggctcacggttgaggagaagcgaattgtcatcgacgacatgg\n" +
">r2 reverse of r1 \n" +
"CCATGTCGTCGATGACAATTCGCTTCTCCTCAACCGTGAGCCGGAATTCCATGATCTTCGGGCCTTGCTTGGTCGCCTGCTCGTGGGG\n" +
">r3 one mismatch\n" +
"ccccacgagcaggcgaccaagcaaggcccgNagatcatggaattccggctcacggttgaggC";
SeqReaderCore readsReader = SeqUtils.getSeqReaderCore(new BufferedInputStream(new ByteArrayInputStream(reads.getBytes())));
SequenceReader contigReader = new SequenceReader(new BufferedInputStream(new ByteArrayInputStream(contigs.getBytes())));
ByteArrayOutputStream coverage_out = new ByteArrayOutputStream();
ByteArrayOutputStream abundance_out = new ByteArrayOutputStream();
KmerCoverage instance = new KmerCoverage(kmer_size, contigReader, readsReader, null);
ConcurrentHashMap<Integer, Contig> contigMap = instance.getContigMap();
// contig 1 should have full coverage
Contig contig1 = contigMap.get(0);
assertEquals(contig1.name, "contig1");
// offset from 1,
assertEquals(contig1.coverage[0], 3, 0.005);
assertEquals(contig1.coverage[8], 2, 0.005);
assertEquals(contig1.coverage[9], 0.6666, 0.005);
assertEquals(contig1.coverage[29], 0.6666, 0.005);
//contig2 is the reverse complement of contig1, should have the same coverage
Contig contig2 = contigMap.get(1);
assertEquals(contig2.name, "contig2");
// offset from 1,
assertEquals(contig2.coverage[0], 0.6666, 0.005);
assertEquals(contig2.coverage[20], 0.6666, 0.005);
assertEquals(contig2.coverage[21], 1, 0.005);
assertEquals(contig2.coverage[22], 3, 0.005);
assertEquals(contig2.coverage[23], 2, 0.005);
assertEquals(contig2.coverage[49], 2, 0.005);
//contig3 has a few mismatches
Contig contig3 = contigMap.get(2);
assertEquals(contig3.name, "contig3");
//offset from 1,
assertEquals(contig3.coverage[0], 0.6666, 0.005);
assertEquals(contig3.coverage[21], 1, 0.005);
assertEquals(contig3.coverage[22], 0, 0.005);
// check summary
instance.printCovereage(coverage_out, abundance_out);
String[] summary = coverage_out.toString().split("\n");
assertEquals("contig1\t1.100\t0.667\t30\t30\t1.000", summary[3]);
assertEquals("contig3\t0.652\t0.667\t23\t22\t0.957", summary[4]);
assertEquals("contig2\t1.440\t2.000\t50\t50\t1.000", summary[5]);
}
|
diff --git a/logic/src/de/zib/gndms/logic/model/gorfx/AbstractTransferORQCalculator.java b/logic/src/de/zib/gndms/logic/model/gorfx/AbstractTransferORQCalculator.java
index ce5fcbbc..ff3f2a3f 100644
--- a/logic/src/de/zib/gndms/logic/model/gorfx/AbstractTransferORQCalculator.java
+++ b/logic/src/de/zib/gndms/logic/model/gorfx/AbstractTransferORQCalculator.java
@@ -1,159 +1,159 @@
package de.zib.gndms.logic.model.gorfx;
/*
* Copyright 2008-2011 Zuse Institute Berlin (ZIB)
*
* 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.
*/
import de.zib.gndms.kit.network.GNDMSFileTransfer;
import de.zib.gndms.kit.network.NetworkAuxiliariesProvider;
import de.zib.gndms.model.common.types.FutureTime;
import de.zib.gndms.model.common.types.TransientContract;
import de.zib.gndms.model.gorfx.types.FileTransferORQ;
import org.apache.axis.types.URI;
import org.globus.ftp.GridFTPClient;
import org.globus.ftp.exception.ClientException;
import org.globus.ftp.exception.ServerException;
import org.joda.time.Duration;
import java.util.concurrent.TimeoutException;
import java.io.IOException;
/**
* @author try ma ik jo rr a zib
* @version $Id$
* <p/>
* User: mjorra, Date: 30.09.2008, Time: 10:51:38
*/
public abstract class AbstractTransferORQCalculator<M extends FileTransferORQ, C extends AbstractORQCalculator<M, C>>
extends AbstractORQCalculator<M,C> {
private Long estimatedTransferSize; // estimatedTransferSize
private Float estimatedBandWidth;
protected AbstractTransferORQCalculator( Class<M> cls ) {
super();
super.setORQModelClass( cls );
}
@Override
public TransientContract createOffer() throws ServerException, IOException, ClientException {
estimateTransferSize();
estimateBandWidth();
return calculateOffer( );
}
@SuppressWarnings({ "FeatureEnvy" })
protected Long estimateTransferSize( ) throws ServerException, IOException, ClientException {
GridFTPClient clnt = null;
try {
URI suri = new URI( getORQArguments().getSourceURI() );
clnt = NetworkAuxiliariesProvider.getGridFTPClientFactory().createClient( suri, getCredentialProvider() );
GNDMSFileTransfer ft = NetworkAuxiliariesProvider.newGNDMSFileTransfer();
ft.setSourceClient( clnt );
ft.setSourcePath( suri.getPath( ) );
ft.setFiles( getORQArguments().getFileMap() );
estimatedTransferSize = ft.estimateTransferSize( );
- } catch( TimeoutException e ) {
- throw new RuntimeException( e );
+ } catch( TimeoutException e ) {
+ throw new RuntimeException( e );
} finally {
if ( clnt != null )
clnt.close( true ); // none blocking close op
}
return estimatedTransferSize;
}
/**
* PRECONDITION estimateTransferSize must have been called before.
* @return The estimated transfer size or NULL if it wasn't estimated yet.
*/
public Long getEstimatedTransferSize( ) throws ServerException, IOException, ClientException {
return estimatedTransferSize;
}
/**
* Estimates the bandwidth
*/
protected Float estimateBandWidth( ) throws IOException {
estimatedBandWidth = NetworkAuxiliariesProvider.getBandWidthEstimater().estimateBandWidthFromTo(
getORQArguments( ).getSourceURI(), getORQArguments( ).getTargetURI() );
if( estimatedBandWidth == null )
throw new IOException( "Couldn't estimate bandwidth." );
return estimatedBandWidth;
}
/**
* PRECONDITION estimateBandWidth must have been called before.
* @return The band width NULL if it wasn't estimated yet.
*/
public Float getEstimatedBandWidth( ) {
return estimatedBandWidth;
}
/**
* PRECONDITION estimateTransferSize and estimateBandWidth or their associated setters
* must have been called before.
* @return The band width NULL if it wasn't estimated yet.
*/
protected TransientContract calculateOffer( ) {
// may at least take 10 s to cover comunication overhead.
long ms = NetworkAuxiliariesProvider.calculateTransferTime( estimatedTransferSize, estimatedBandWidth, 10000 );
TransientContract ct = new TransientContract( );
ct.setDeadline( FutureTime.atOffset( new Duration( ms ) ) );
// none means forever
// ct.setResultValidity( FutureTime.atTime(dat.plusHours( ContractConstants.FILE_TRANSFER_RESULT_VALIDITY )) );
return ct;
}
/**
* Use this method to set the download size manually.
*
* This is the alternativ to calling estimateTransferSize.
*
* @param estimatedTransferSize -- what the name implies.
*/
protected void setEstimatedTransferSize( long estimatedTransferSize ) {
this.estimatedTransferSize = estimatedTransferSize;
}
/**
* Use this method to set the available band-width manually.
*
* This is the alternativ to calling estimateBandWidth.
*
* @param estimatedBandWidth -- Guess what.
*/
protected void setEstimatedBandWidth( float estimatedBandWidth ) {
this.estimatedBandWidth = estimatedBandWidth;
}
}
| true | true | protected Long estimateTransferSize( ) throws ServerException, IOException, ClientException {
GridFTPClient clnt = null;
try {
URI suri = new URI( getORQArguments().getSourceURI() );
clnt = NetworkAuxiliariesProvider.getGridFTPClientFactory().createClient( suri, getCredentialProvider() );
GNDMSFileTransfer ft = NetworkAuxiliariesProvider.newGNDMSFileTransfer();
ft.setSourceClient( clnt );
ft.setSourcePath( suri.getPath( ) );
ft.setFiles( getORQArguments().getFileMap() );
estimatedTransferSize = ft.estimateTransferSize( );
} catch( TimeoutException e ) {
throw new RuntimeException( e );
} finally {
if ( clnt != null )
clnt.close( true ); // none blocking close op
}
return estimatedTransferSize;
}
| protected Long estimateTransferSize( ) throws ServerException, IOException, ClientException {
GridFTPClient clnt = null;
try {
URI suri = new URI( getORQArguments().getSourceURI() );
clnt = NetworkAuxiliariesProvider.getGridFTPClientFactory().createClient( suri, getCredentialProvider() );
GNDMSFileTransfer ft = NetworkAuxiliariesProvider.newGNDMSFileTransfer();
ft.setSourceClient( clnt );
ft.setSourcePath( suri.getPath( ) );
ft.setFiles( getORQArguments().getFileMap() );
estimatedTransferSize = ft.estimateTransferSize( );
} catch( TimeoutException e ) {
throw new RuntimeException( e );
} finally {
if ( clnt != null )
clnt.close( true ); // none blocking close op
}
return estimatedTransferSize;
}
|
diff --git a/src/java/com/eviware/soapui/impl/wsdl/submit/filters/HttpRequestFilter.java b/src/java/com/eviware/soapui/impl/wsdl/submit/filters/HttpRequestFilter.java
index 0a00e6a52..b309fe599 100644
--- a/src/java/com/eviware/soapui/impl/wsdl/submit/filters/HttpRequestFilter.java
+++ b/src/java/com/eviware/soapui/impl/wsdl/submit/filters/HttpRequestFilter.java
@@ -1,458 +1,458 @@
/*
* soapUI, copyright (C) 2004-2011 eviware.com
*
* soapUI is free software; you can redistribute it and/or modify it under the
* terms of version 2.1 of the GNU Lesser General Public License as published by
* the Free Software Foundation.
*
* soapUI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details at gnu.org.
*/
package com.eviware.soapui.impl.wsdl.submit.filters;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.PreencodedMimeBodyPart;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.utils.URIUtils;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.entity.StringEntity;
import org.apache.xmlbeans.XmlBoolean;
import com.eviware.soapui.SoapUI;
import com.eviware.soapui.impl.rest.RestRequest;
import com.eviware.soapui.impl.rest.support.RestParamProperty;
import com.eviware.soapui.impl.rest.support.RestParamsPropertyHolder;
import com.eviware.soapui.impl.rest.support.RestParamsPropertyHolder.ParameterStyle;
import com.eviware.soapui.impl.rest.support.RestUtils;
import com.eviware.soapui.impl.support.http.HttpRequestInterface;
import com.eviware.soapui.impl.wsdl.submit.transports.http.BaseHttpRequestTransport;
import com.eviware.soapui.impl.wsdl.submit.transports.http.support.attachments.AttachmentDataSource;
import com.eviware.soapui.impl.wsdl.submit.transports.http.support.attachments.AttachmentUtils;
import com.eviware.soapui.impl.wsdl.submit.transports.http.support.attachments.RestRequestDataSource;
import com.eviware.soapui.impl.wsdl.submit.transports.http.support.attachments.RestRequestMimeMessageRequestEntity;
import com.eviware.soapui.impl.wsdl.support.FileAttachment;
import com.eviware.soapui.impl.wsdl.support.PathUtils;
import com.eviware.soapui.impl.wsdl.teststeps.HttpTestRequest;
import com.eviware.soapui.model.iface.Attachment;
import com.eviware.soapui.model.iface.SubmitContext;
import com.eviware.soapui.model.propertyexpansion.PropertyExpander;
import com.eviware.soapui.settings.HttpSettings;
import com.eviware.soapui.support.StringUtils;
import com.eviware.soapui.support.editor.inspectors.attachments.ContentTypeHandler;
import com.eviware.soapui.support.types.StringToStringMap;
import com.eviware.soapui.support.uri.URI;
/**
* RequestFilter that adds SOAP specific headers
*
* @author Ole.Matzura
*/
public class HttpRequestFilter extends AbstractRequestFilter
{
@SuppressWarnings( "deprecation" )
@Override
public void filterHttpRequest( SubmitContext context, HttpRequestInterface<?> request )
{
HttpRequestBase httpMethod = ( HttpRequestBase )context.getProperty( BaseHttpRequestTransport.HTTP_METHOD );
String path = PropertyExpander.expandProperties( context, request.getPath() );
StringBuffer query = new StringBuffer();
StringToStringMap responseProperties = ( StringToStringMap )context
.getProperty( BaseHttpRequestTransport.RESPONSE_PROPERTIES );
MimeMultipart formMp = "multipart/form-data".equals( request.getMediaType() )
&& httpMethod instanceof HttpEntityEnclosingRequestBase ? new MimeMultipart() : null;
RestParamsPropertyHolder params = request.getParams();
for( int c = 0; c < params.getPropertyCount(); c++ )
{
RestParamProperty param = params.getPropertyAt( c );
String value = PropertyExpander.expandProperties( context, param.getValue() );
responseProperties.put( param.getName(), value );
List<String> valueParts = sendEmptyParameters( request )
|| ( !StringUtils.hasContent( value ) && param.getRequired() ) ? RestUtils
.splitMultipleParametersEmptyIncluded( value, request.getMultiValueDelimiter() ) : RestUtils
.splitMultipleParameters( value, request.getMultiValueDelimiter() );
// skip HEADER and TEMPLATE parameter encoding (TEMPLATE is encoded by
// the URI handling further down)
if( value != null && param.getStyle() != ParameterStyle.HEADER && param.getStyle() != ParameterStyle.TEMPLATE
&& !param.isDisableUrlEncoding() )
{
try
{
String encoding = System.getProperty( "soapui.request.encoding", request.getEncoding() );
if( StringUtils.hasContent( encoding ) )
{
value = URLEncoder.encode( value, encoding );
for( int i = 0; i < valueParts.size(); i++ )
valueParts.set( i, URLEncoder.encode( valueParts.get( i ), encoding ) );
}
else
{
value = URLEncoder.encode( value );
for( int i = 0; i < valueParts.size(); i++ )
valueParts.set( i, URLEncoder.encode( valueParts.get( i ) ) );
}
}
catch( UnsupportedEncodingException e1 )
{
SoapUI.logError( e1 );
value = URLEncoder.encode( value );
for( int i = 0; i < valueParts.size(); i++ )
valueParts.set( i, URLEncoder.encode( valueParts.get( i ) ) );
}
// URLEncoder replaces space with "+", but we want "%20".
value = value.replaceAll( "\\+", "%20" );
for( int i = 0; i < valueParts.size(); i++ )
valueParts.set( i, valueParts.get( i ).replaceAll( "\\+", "%20" ) );
}
if( param.getStyle() == ParameterStyle.QUERY && !sendEmptyParameters( request ) )
{
if( !StringUtils.hasContent( value ) && !param.getRequired() )
continue;
}
switch( param.getStyle() )
{
case HEADER :
for( String valuePart : valueParts )
httpMethod.addHeader( param.getName(), valuePart );
break;
case QUERY :
if( formMp == null || !request.isPostQueryString() )
{
for( String valuePart : valueParts )
{
if( query.length() > 0 )
query.append( '&' );
query.append( URLEncoder.encode( param.getName() ) );
query.append( '=' );
if( StringUtils.hasContent( valuePart ) )
query.append( valuePart );
}
}
else
{
try
{
addFormMultipart( request, formMp, param.getName(), responseProperties.get( param.getName() ) );
}
catch( MessagingException e )
{
SoapUI.logError( e );
}
}
break;
case TEMPLATE :
path = path.replaceAll( "\\{" + param.getName() + "\\}", value == null ? "" : value );
break;
case MATRIX :
if( param.getType().equals( XmlBoolean.type.getName() ) )
{
if( value.toUpperCase().equals( "TRUE" ) || value.equals( "1" ) )
{
path += ";" + param.getName();
}
}
else
{
path += ";" + param.getName();
if( StringUtils.hasContent( value ) )
{
path += "=" + value;
}
}
case PLAIN :
break;
}
}
if( request.getSettings().getBoolean( HttpSettings.FORWARD_SLASHES ) )
path = PathUtils.fixForwardSlashesInPath( path );
if( PathUtils.isHttpPath( path ) )
{
try
{
// URI(String) automatically URLencodes the input, so we need to
// decode it first...
- URI uri = new URI( path, false );
+ URI uri = new URI( path, request.getSettings().getBoolean( HttpSettings.ENCODED_URLS ) );
context.setProperty( BaseHttpRequestTransport.REQUEST_URI, uri );
httpMethod.setURI( new java.net.URI( uri.toString() ) );
}
catch( Exception e )
{
SoapUI.logError( e );
}
}
else if( StringUtils.hasContent( path ) )
{
try
{
java.net.URI oldUri = httpMethod.getURI();
httpMethod.setURI( URIUtils.createURI( oldUri.getScheme(), oldUri.getHost(), oldUri.getPort(), path,
oldUri.getQuery(), oldUri.getFragment() ) );
}
catch( Exception e )
{
SoapUI.logError( e );
}
}
if( query.length() > 0 && !request.isPostQueryString() )
{
java.net.URI oldUri = httpMethod.getURI();
try
{
java.net.URI tempUri = URIUtils.createURI( oldUri.getScheme(), oldUri.getHost(), oldUri.getPort(),
oldUri.getPath(), query.toString(), null );
httpMethod.setURI( tempUri );
}
catch( Exception e )
{
SoapUI.logError( e );
}
}
if( request instanceof RestRequest )
{
String acceptEncoding = ( ( RestRequest )request ).getAccept();
if( StringUtils.hasContent( acceptEncoding ) )
{
httpMethod.setHeader( "Accept", acceptEncoding );
}
}
String encoding = System.getProperty( "soapui.request.encoding", StringUtils.unquote( request.getEncoding() ) );
if( formMp != null )
{
// create request message
try
{
if( request.hasRequestBody() && httpMethod instanceof HttpEntityEnclosingRequest )
{
String requestContent = PropertyExpander.expandProperties( context, request.getRequestContent(),
request.isEntitizeProperties() );
if( StringUtils.hasContent( requestContent ) )
{
initRootPart( request, requestContent, formMp );
}
}
for( Attachment attachment : request.getAttachments() )
{
MimeBodyPart part = new PreencodedMimeBodyPart( "binary" );
if( attachment instanceof FileAttachment<?> )
{
String name = attachment.getName();
if( StringUtils.hasContent( attachment.getContentID() ) && !name.equals( attachment.getContentID() ) )
name = attachment.getContentID();
part.setDisposition( "form-data; name=\"" + name + "\"; filename=\"" + attachment.getName() + "\"" );
}
else
part.setDisposition( "form-data; name=\"" + attachment.getName() + "\"" );
part.setDataHandler( new DataHandler( new AttachmentDataSource( attachment ) ) );
formMp.addBodyPart( part );
}
MimeMessage message = new MimeMessage( AttachmentUtils.JAVAMAIL_SESSION );
message.setContent( formMp );
message.saveChanges();
RestRequestMimeMessageRequestEntity mimeMessageRequestEntity = new RestRequestMimeMessageRequestEntity(
message, request );
( ( HttpEntityEnclosingRequest )httpMethod ).setEntity( mimeMessageRequestEntity );
httpMethod.setHeader( "Content-Type", mimeMessageRequestEntity.getContentType().getValue() );
httpMethod.setHeader( "MIME-Version", "1.0" );
}
catch( Throwable e )
{
SoapUI.logError( e );
}
}
else if( request.hasRequestBody() && httpMethod instanceof HttpEntityEnclosingRequest )
{
if( StringUtils.hasContent( request.getMediaType() ) )
httpMethod.setHeader( "Content-Type", getContentTypeHeader( request.getMediaType(), encoding ) );
if( request.isPostQueryString() )
{
try
{
( ( HttpEntityEnclosingRequest )httpMethod ).setEntity( new StringEntity( query.toString() ) );
}
catch( UnsupportedEncodingException e )
{
SoapUI.logError( e );
}
}
else
{
String requestContent = PropertyExpander.expandProperties( context, request.getRequestContent(),
request.isEntitizeProperties() );
List<Attachment> attachments = new ArrayList<Attachment>();
for( Attachment attachment : request.getAttachments() )
{
if( attachment.getContentType().equals( request.getMediaType() ) )
{
attachments.add( attachment );
}
}
if( StringUtils.hasContent( requestContent ) && attachments.isEmpty() )
{
try
{
byte[] content = encoding == null ? requestContent.getBytes() : requestContent.getBytes( encoding );
( ( HttpEntityEnclosingRequest )httpMethod ).setEntity( new ByteArrayEntity( content ) );
}
catch( UnsupportedEncodingException e )
{
( ( HttpEntityEnclosingRequest )httpMethod ).setEntity( new ByteArrayEntity( requestContent
.getBytes() ) );
}
}
else if( attachments.size() > 0 )
{
try
{
MimeMultipart mp = null;
if( StringUtils.hasContent( requestContent ) )
{
mp = new MimeMultipart();
initRootPart( request, requestContent, mp );
}
else if( attachments.size() == 1 )
{
( ( HttpEntityEnclosingRequest )httpMethod ).setEntity( new InputStreamEntity( attachments.get( 0 )
.getInputStream(), -1 ) );
httpMethod.setHeader( "Content-Type", getContentTypeHeader( request.getMediaType(), encoding ) );
}
if( ( ( HttpEntityEnclosingRequest )httpMethod ).getEntity() == null )
{
if( mp == null )
mp = new MimeMultipart();
// init mimeparts
AttachmentUtils.addMimeParts( request, attachments, mp, new StringToStringMap() );
// create request message
MimeMessage message = new MimeMessage( AttachmentUtils.JAVAMAIL_SESSION );
message.setContent( mp );
message.saveChanges();
RestRequestMimeMessageRequestEntity mimeMessageRequestEntity = new RestRequestMimeMessageRequestEntity(
message, request );
( ( HttpEntityEnclosingRequest )httpMethod ).setEntity( mimeMessageRequestEntity );
httpMethod.setHeader( "Content-Type",
getContentTypeHeader( mimeMessageRequestEntity.getContentType().getValue(), encoding ) );
httpMethod.setHeader( "MIME-Version", "1.0" );
}
}
catch( Exception e )
{
SoapUI.logError( e );
}
}
}
}
}
private boolean sendEmptyParameters( HttpRequestInterface<?> request )
{
return request instanceof HttpTestRequest && ( ( HttpTestRequest )request ).isSendEmptyParameters();
}
private String getContentTypeHeader( String contentType, String encoding )
{
return ( encoding == null || encoding.trim().length() == 0 ) ? contentType : contentType + ";charset=" + encoding;
}
private void addFormMultipart( HttpRequestInterface<?> request, MimeMultipart formMp, String name, String value )
throws MessagingException
{
MimeBodyPart part = new MimeBodyPart();
if( value.startsWith( "file:" ) )
{
String fileName = value.substring( 5 );
File file = new File( fileName );
part.setDisposition( "form-data; name=\"" + name + "\"; filename=\"" + file.getName() + "\"" );
if( file.exists() )
{
part.setDataHandler( new DataHandler( new FileDataSource( file ) ) );
}
else
{
for( Attachment attachment : request.getAttachments() )
{
if( attachment.getName().equals( fileName ) )
{
part.setDataHandler( new DataHandler( new AttachmentDataSource( attachment ) ) );
break;
}
}
}
part.setHeader( "Content-Type", ContentTypeHandler.getContentTypeFromFilename( file.getName() ) );
part.setHeader( "Content-Transfer-Encoding", "binary" );
}
else
{
part.setDisposition( "form-data; name=\"" + name + "\"" );
part.setText( value, System.getProperty( "soapui.request.encoding", request.getEncoding() ) );
}
if( part != null )
{
formMp.addBodyPart( part );
}
}
protected void initRootPart( HttpRequestInterface<?> wsdlRequest, String requestContent, MimeMultipart mp )
throws MessagingException
{
MimeBodyPart rootPart = new PreencodedMimeBodyPart( "8bit" );
// rootPart.setContentID( AttachmentUtils.ROOTPART_SOAPUI_ORG );
mp.addBodyPart( rootPart, 0 );
DataHandler dataHandler = new DataHandler( new RestRequestDataSource( wsdlRequest, requestContent ) );
rootPart.setDataHandler( dataHandler );
}
}
| true | true | public void filterHttpRequest( SubmitContext context, HttpRequestInterface<?> request )
{
HttpRequestBase httpMethod = ( HttpRequestBase )context.getProperty( BaseHttpRequestTransport.HTTP_METHOD );
String path = PropertyExpander.expandProperties( context, request.getPath() );
StringBuffer query = new StringBuffer();
StringToStringMap responseProperties = ( StringToStringMap )context
.getProperty( BaseHttpRequestTransport.RESPONSE_PROPERTIES );
MimeMultipart formMp = "multipart/form-data".equals( request.getMediaType() )
&& httpMethod instanceof HttpEntityEnclosingRequestBase ? new MimeMultipart() : null;
RestParamsPropertyHolder params = request.getParams();
for( int c = 0; c < params.getPropertyCount(); c++ )
{
RestParamProperty param = params.getPropertyAt( c );
String value = PropertyExpander.expandProperties( context, param.getValue() );
responseProperties.put( param.getName(), value );
List<String> valueParts = sendEmptyParameters( request )
|| ( !StringUtils.hasContent( value ) && param.getRequired() ) ? RestUtils
.splitMultipleParametersEmptyIncluded( value, request.getMultiValueDelimiter() ) : RestUtils
.splitMultipleParameters( value, request.getMultiValueDelimiter() );
// skip HEADER and TEMPLATE parameter encoding (TEMPLATE is encoded by
// the URI handling further down)
if( value != null && param.getStyle() != ParameterStyle.HEADER && param.getStyle() != ParameterStyle.TEMPLATE
&& !param.isDisableUrlEncoding() )
{
try
{
String encoding = System.getProperty( "soapui.request.encoding", request.getEncoding() );
if( StringUtils.hasContent( encoding ) )
{
value = URLEncoder.encode( value, encoding );
for( int i = 0; i < valueParts.size(); i++ )
valueParts.set( i, URLEncoder.encode( valueParts.get( i ), encoding ) );
}
else
{
value = URLEncoder.encode( value );
for( int i = 0; i < valueParts.size(); i++ )
valueParts.set( i, URLEncoder.encode( valueParts.get( i ) ) );
}
}
catch( UnsupportedEncodingException e1 )
{
SoapUI.logError( e1 );
value = URLEncoder.encode( value );
for( int i = 0; i < valueParts.size(); i++ )
valueParts.set( i, URLEncoder.encode( valueParts.get( i ) ) );
}
// URLEncoder replaces space with "+", but we want "%20".
value = value.replaceAll( "\\+", "%20" );
for( int i = 0; i < valueParts.size(); i++ )
valueParts.set( i, valueParts.get( i ).replaceAll( "\\+", "%20" ) );
}
if( param.getStyle() == ParameterStyle.QUERY && !sendEmptyParameters( request ) )
{
if( !StringUtils.hasContent( value ) && !param.getRequired() )
continue;
}
switch( param.getStyle() )
{
case HEADER :
for( String valuePart : valueParts )
httpMethod.addHeader( param.getName(), valuePart );
break;
case QUERY :
if( formMp == null || !request.isPostQueryString() )
{
for( String valuePart : valueParts )
{
if( query.length() > 0 )
query.append( '&' );
query.append( URLEncoder.encode( param.getName() ) );
query.append( '=' );
if( StringUtils.hasContent( valuePart ) )
query.append( valuePart );
}
}
else
{
try
{
addFormMultipart( request, formMp, param.getName(), responseProperties.get( param.getName() ) );
}
catch( MessagingException e )
{
SoapUI.logError( e );
}
}
break;
case TEMPLATE :
path = path.replaceAll( "\\{" + param.getName() + "\\}", value == null ? "" : value );
break;
case MATRIX :
if( param.getType().equals( XmlBoolean.type.getName() ) )
{
if( value.toUpperCase().equals( "TRUE" ) || value.equals( "1" ) )
{
path += ";" + param.getName();
}
}
else
{
path += ";" + param.getName();
if( StringUtils.hasContent( value ) )
{
path += "=" + value;
}
}
case PLAIN :
break;
}
}
if( request.getSettings().getBoolean( HttpSettings.FORWARD_SLASHES ) )
path = PathUtils.fixForwardSlashesInPath( path );
if( PathUtils.isHttpPath( path ) )
{
try
{
// URI(String) automatically URLencodes the input, so we need to
// decode it first...
URI uri = new URI( path, false );
context.setProperty( BaseHttpRequestTransport.REQUEST_URI, uri );
httpMethod.setURI( new java.net.URI( uri.toString() ) );
}
catch( Exception e )
{
SoapUI.logError( e );
}
}
else if( StringUtils.hasContent( path ) )
{
try
{
java.net.URI oldUri = httpMethod.getURI();
httpMethod.setURI( URIUtils.createURI( oldUri.getScheme(), oldUri.getHost(), oldUri.getPort(), path,
oldUri.getQuery(), oldUri.getFragment() ) );
}
catch( Exception e )
{
SoapUI.logError( e );
}
}
if( query.length() > 0 && !request.isPostQueryString() )
{
java.net.URI oldUri = httpMethod.getURI();
try
{
java.net.URI tempUri = URIUtils.createURI( oldUri.getScheme(), oldUri.getHost(), oldUri.getPort(),
oldUri.getPath(), query.toString(), null );
httpMethod.setURI( tempUri );
}
catch( Exception e )
{
SoapUI.logError( e );
}
}
if( request instanceof RestRequest )
{
String acceptEncoding = ( ( RestRequest )request ).getAccept();
if( StringUtils.hasContent( acceptEncoding ) )
{
httpMethod.setHeader( "Accept", acceptEncoding );
}
}
String encoding = System.getProperty( "soapui.request.encoding", StringUtils.unquote( request.getEncoding() ) );
if( formMp != null )
{
// create request message
try
{
if( request.hasRequestBody() && httpMethod instanceof HttpEntityEnclosingRequest )
{
String requestContent = PropertyExpander.expandProperties( context, request.getRequestContent(),
request.isEntitizeProperties() );
if( StringUtils.hasContent( requestContent ) )
{
initRootPart( request, requestContent, formMp );
}
}
for( Attachment attachment : request.getAttachments() )
{
MimeBodyPart part = new PreencodedMimeBodyPart( "binary" );
if( attachment instanceof FileAttachment<?> )
{
String name = attachment.getName();
if( StringUtils.hasContent( attachment.getContentID() ) && !name.equals( attachment.getContentID() ) )
name = attachment.getContentID();
part.setDisposition( "form-data; name=\"" + name + "\"; filename=\"" + attachment.getName() + "\"" );
}
else
part.setDisposition( "form-data; name=\"" + attachment.getName() + "\"" );
part.setDataHandler( new DataHandler( new AttachmentDataSource( attachment ) ) );
formMp.addBodyPart( part );
}
MimeMessage message = new MimeMessage( AttachmentUtils.JAVAMAIL_SESSION );
message.setContent( formMp );
message.saveChanges();
RestRequestMimeMessageRequestEntity mimeMessageRequestEntity = new RestRequestMimeMessageRequestEntity(
message, request );
( ( HttpEntityEnclosingRequest )httpMethod ).setEntity( mimeMessageRequestEntity );
httpMethod.setHeader( "Content-Type", mimeMessageRequestEntity.getContentType().getValue() );
httpMethod.setHeader( "MIME-Version", "1.0" );
}
catch( Throwable e )
{
SoapUI.logError( e );
}
}
else if( request.hasRequestBody() && httpMethod instanceof HttpEntityEnclosingRequest )
{
if( StringUtils.hasContent( request.getMediaType() ) )
httpMethod.setHeader( "Content-Type", getContentTypeHeader( request.getMediaType(), encoding ) );
if( request.isPostQueryString() )
{
try
{
( ( HttpEntityEnclosingRequest )httpMethod ).setEntity( new StringEntity( query.toString() ) );
}
catch( UnsupportedEncodingException e )
{
SoapUI.logError( e );
}
}
else
{
String requestContent = PropertyExpander.expandProperties( context, request.getRequestContent(),
request.isEntitizeProperties() );
List<Attachment> attachments = new ArrayList<Attachment>();
for( Attachment attachment : request.getAttachments() )
{
if( attachment.getContentType().equals( request.getMediaType() ) )
{
attachments.add( attachment );
}
}
if( StringUtils.hasContent( requestContent ) && attachments.isEmpty() )
{
try
{
byte[] content = encoding == null ? requestContent.getBytes() : requestContent.getBytes( encoding );
( ( HttpEntityEnclosingRequest )httpMethod ).setEntity( new ByteArrayEntity( content ) );
}
catch( UnsupportedEncodingException e )
{
( ( HttpEntityEnclosingRequest )httpMethod ).setEntity( new ByteArrayEntity( requestContent
.getBytes() ) );
}
}
else if( attachments.size() > 0 )
{
try
{
MimeMultipart mp = null;
if( StringUtils.hasContent( requestContent ) )
{
mp = new MimeMultipart();
initRootPart( request, requestContent, mp );
}
else if( attachments.size() == 1 )
{
( ( HttpEntityEnclosingRequest )httpMethod ).setEntity( new InputStreamEntity( attachments.get( 0 )
.getInputStream(), -1 ) );
httpMethod.setHeader( "Content-Type", getContentTypeHeader( request.getMediaType(), encoding ) );
}
if( ( ( HttpEntityEnclosingRequest )httpMethod ).getEntity() == null )
{
if( mp == null )
mp = new MimeMultipart();
// init mimeparts
AttachmentUtils.addMimeParts( request, attachments, mp, new StringToStringMap() );
// create request message
MimeMessage message = new MimeMessage( AttachmentUtils.JAVAMAIL_SESSION );
message.setContent( mp );
message.saveChanges();
RestRequestMimeMessageRequestEntity mimeMessageRequestEntity = new RestRequestMimeMessageRequestEntity(
message, request );
( ( HttpEntityEnclosingRequest )httpMethod ).setEntity( mimeMessageRequestEntity );
httpMethod.setHeader( "Content-Type",
getContentTypeHeader( mimeMessageRequestEntity.getContentType().getValue(), encoding ) );
httpMethod.setHeader( "MIME-Version", "1.0" );
}
}
catch( Exception e )
{
SoapUI.logError( e );
}
}
}
}
}
| public void filterHttpRequest( SubmitContext context, HttpRequestInterface<?> request )
{
HttpRequestBase httpMethod = ( HttpRequestBase )context.getProperty( BaseHttpRequestTransport.HTTP_METHOD );
String path = PropertyExpander.expandProperties( context, request.getPath() );
StringBuffer query = new StringBuffer();
StringToStringMap responseProperties = ( StringToStringMap )context
.getProperty( BaseHttpRequestTransport.RESPONSE_PROPERTIES );
MimeMultipart formMp = "multipart/form-data".equals( request.getMediaType() )
&& httpMethod instanceof HttpEntityEnclosingRequestBase ? new MimeMultipart() : null;
RestParamsPropertyHolder params = request.getParams();
for( int c = 0; c < params.getPropertyCount(); c++ )
{
RestParamProperty param = params.getPropertyAt( c );
String value = PropertyExpander.expandProperties( context, param.getValue() );
responseProperties.put( param.getName(), value );
List<String> valueParts = sendEmptyParameters( request )
|| ( !StringUtils.hasContent( value ) && param.getRequired() ) ? RestUtils
.splitMultipleParametersEmptyIncluded( value, request.getMultiValueDelimiter() ) : RestUtils
.splitMultipleParameters( value, request.getMultiValueDelimiter() );
// skip HEADER and TEMPLATE parameter encoding (TEMPLATE is encoded by
// the URI handling further down)
if( value != null && param.getStyle() != ParameterStyle.HEADER && param.getStyle() != ParameterStyle.TEMPLATE
&& !param.isDisableUrlEncoding() )
{
try
{
String encoding = System.getProperty( "soapui.request.encoding", request.getEncoding() );
if( StringUtils.hasContent( encoding ) )
{
value = URLEncoder.encode( value, encoding );
for( int i = 0; i < valueParts.size(); i++ )
valueParts.set( i, URLEncoder.encode( valueParts.get( i ), encoding ) );
}
else
{
value = URLEncoder.encode( value );
for( int i = 0; i < valueParts.size(); i++ )
valueParts.set( i, URLEncoder.encode( valueParts.get( i ) ) );
}
}
catch( UnsupportedEncodingException e1 )
{
SoapUI.logError( e1 );
value = URLEncoder.encode( value );
for( int i = 0; i < valueParts.size(); i++ )
valueParts.set( i, URLEncoder.encode( valueParts.get( i ) ) );
}
// URLEncoder replaces space with "+", but we want "%20".
value = value.replaceAll( "\\+", "%20" );
for( int i = 0; i < valueParts.size(); i++ )
valueParts.set( i, valueParts.get( i ).replaceAll( "\\+", "%20" ) );
}
if( param.getStyle() == ParameterStyle.QUERY && !sendEmptyParameters( request ) )
{
if( !StringUtils.hasContent( value ) && !param.getRequired() )
continue;
}
switch( param.getStyle() )
{
case HEADER :
for( String valuePart : valueParts )
httpMethod.addHeader( param.getName(), valuePart );
break;
case QUERY :
if( formMp == null || !request.isPostQueryString() )
{
for( String valuePart : valueParts )
{
if( query.length() > 0 )
query.append( '&' );
query.append( URLEncoder.encode( param.getName() ) );
query.append( '=' );
if( StringUtils.hasContent( valuePart ) )
query.append( valuePart );
}
}
else
{
try
{
addFormMultipart( request, formMp, param.getName(), responseProperties.get( param.getName() ) );
}
catch( MessagingException e )
{
SoapUI.logError( e );
}
}
break;
case TEMPLATE :
path = path.replaceAll( "\\{" + param.getName() + "\\}", value == null ? "" : value );
break;
case MATRIX :
if( param.getType().equals( XmlBoolean.type.getName() ) )
{
if( value.toUpperCase().equals( "TRUE" ) || value.equals( "1" ) )
{
path += ";" + param.getName();
}
}
else
{
path += ";" + param.getName();
if( StringUtils.hasContent( value ) )
{
path += "=" + value;
}
}
case PLAIN :
break;
}
}
if( request.getSettings().getBoolean( HttpSettings.FORWARD_SLASHES ) )
path = PathUtils.fixForwardSlashesInPath( path );
if( PathUtils.isHttpPath( path ) )
{
try
{
// URI(String) automatically URLencodes the input, so we need to
// decode it first...
URI uri = new URI( path, request.getSettings().getBoolean( HttpSettings.ENCODED_URLS ) );
context.setProperty( BaseHttpRequestTransport.REQUEST_URI, uri );
httpMethod.setURI( new java.net.URI( uri.toString() ) );
}
catch( Exception e )
{
SoapUI.logError( e );
}
}
else if( StringUtils.hasContent( path ) )
{
try
{
java.net.URI oldUri = httpMethod.getURI();
httpMethod.setURI( URIUtils.createURI( oldUri.getScheme(), oldUri.getHost(), oldUri.getPort(), path,
oldUri.getQuery(), oldUri.getFragment() ) );
}
catch( Exception e )
{
SoapUI.logError( e );
}
}
if( query.length() > 0 && !request.isPostQueryString() )
{
java.net.URI oldUri = httpMethod.getURI();
try
{
java.net.URI tempUri = URIUtils.createURI( oldUri.getScheme(), oldUri.getHost(), oldUri.getPort(),
oldUri.getPath(), query.toString(), null );
httpMethod.setURI( tempUri );
}
catch( Exception e )
{
SoapUI.logError( e );
}
}
if( request instanceof RestRequest )
{
String acceptEncoding = ( ( RestRequest )request ).getAccept();
if( StringUtils.hasContent( acceptEncoding ) )
{
httpMethod.setHeader( "Accept", acceptEncoding );
}
}
String encoding = System.getProperty( "soapui.request.encoding", StringUtils.unquote( request.getEncoding() ) );
if( formMp != null )
{
// create request message
try
{
if( request.hasRequestBody() && httpMethod instanceof HttpEntityEnclosingRequest )
{
String requestContent = PropertyExpander.expandProperties( context, request.getRequestContent(),
request.isEntitizeProperties() );
if( StringUtils.hasContent( requestContent ) )
{
initRootPart( request, requestContent, formMp );
}
}
for( Attachment attachment : request.getAttachments() )
{
MimeBodyPart part = new PreencodedMimeBodyPart( "binary" );
if( attachment instanceof FileAttachment<?> )
{
String name = attachment.getName();
if( StringUtils.hasContent( attachment.getContentID() ) && !name.equals( attachment.getContentID() ) )
name = attachment.getContentID();
part.setDisposition( "form-data; name=\"" + name + "\"; filename=\"" + attachment.getName() + "\"" );
}
else
part.setDisposition( "form-data; name=\"" + attachment.getName() + "\"" );
part.setDataHandler( new DataHandler( new AttachmentDataSource( attachment ) ) );
formMp.addBodyPart( part );
}
MimeMessage message = new MimeMessage( AttachmentUtils.JAVAMAIL_SESSION );
message.setContent( formMp );
message.saveChanges();
RestRequestMimeMessageRequestEntity mimeMessageRequestEntity = new RestRequestMimeMessageRequestEntity(
message, request );
( ( HttpEntityEnclosingRequest )httpMethod ).setEntity( mimeMessageRequestEntity );
httpMethod.setHeader( "Content-Type", mimeMessageRequestEntity.getContentType().getValue() );
httpMethod.setHeader( "MIME-Version", "1.0" );
}
catch( Throwable e )
{
SoapUI.logError( e );
}
}
else if( request.hasRequestBody() && httpMethod instanceof HttpEntityEnclosingRequest )
{
if( StringUtils.hasContent( request.getMediaType() ) )
httpMethod.setHeader( "Content-Type", getContentTypeHeader( request.getMediaType(), encoding ) );
if( request.isPostQueryString() )
{
try
{
( ( HttpEntityEnclosingRequest )httpMethod ).setEntity( new StringEntity( query.toString() ) );
}
catch( UnsupportedEncodingException e )
{
SoapUI.logError( e );
}
}
else
{
String requestContent = PropertyExpander.expandProperties( context, request.getRequestContent(),
request.isEntitizeProperties() );
List<Attachment> attachments = new ArrayList<Attachment>();
for( Attachment attachment : request.getAttachments() )
{
if( attachment.getContentType().equals( request.getMediaType() ) )
{
attachments.add( attachment );
}
}
if( StringUtils.hasContent( requestContent ) && attachments.isEmpty() )
{
try
{
byte[] content = encoding == null ? requestContent.getBytes() : requestContent.getBytes( encoding );
( ( HttpEntityEnclosingRequest )httpMethod ).setEntity( new ByteArrayEntity( content ) );
}
catch( UnsupportedEncodingException e )
{
( ( HttpEntityEnclosingRequest )httpMethod ).setEntity( new ByteArrayEntity( requestContent
.getBytes() ) );
}
}
else if( attachments.size() > 0 )
{
try
{
MimeMultipart mp = null;
if( StringUtils.hasContent( requestContent ) )
{
mp = new MimeMultipart();
initRootPart( request, requestContent, mp );
}
else if( attachments.size() == 1 )
{
( ( HttpEntityEnclosingRequest )httpMethod ).setEntity( new InputStreamEntity( attachments.get( 0 )
.getInputStream(), -1 ) );
httpMethod.setHeader( "Content-Type", getContentTypeHeader( request.getMediaType(), encoding ) );
}
if( ( ( HttpEntityEnclosingRequest )httpMethod ).getEntity() == null )
{
if( mp == null )
mp = new MimeMultipart();
// init mimeparts
AttachmentUtils.addMimeParts( request, attachments, mp, new StringToStringMap() );
// create request message
MimeMessage message = new MimeMessage( AttachmentUtils.JAVAMAIL_SESSION );
message.setContent( mp );
message.saveChanges();
RestRequestMimeMessageRequestEntity mimeMessageRequestEntity = new RestRequestMimeMessageRequestEntity(
message, request );
( ( HttpEntityEnclosingRequest )httpMethod ).setEntity( mimeMessageRequestEntity );
httpMethod.setHeader( "Content-Type",
getContentTypeHeader( mimeMessageRequestEntity.getContentType().getValue(), encoding ) );
httpMethod.setHeader( "MIME-Version", "1.0" );
}
}
catch( Exception e )
{
SoapUI.logError( e );
}
}
}
}
}
|
diff --git a/flexmojos-testing/flexmojos-test-harness/src/test/java/org/sonatype/flexmojos/tests/concept/ArchetypesTest.java b/flexmojos-testing/flexmojos-test-harness/src/test/java/org/sonatype/flexmojos/tests/concept/ArchetypesTest.java
index a4f91bf42..49fc3bdd7 100644
--- a/flexmojos-testing/flexmojos-test-harness/src/test/java/org/sonatype/flexmojos/tests/concept/ArchetypesTest.java
+++ b/flexmojos-testing/flexmojos-test-harness/src/test/java/org/sonatype/flexmojos/tests/concept/ArchetypesTest.java
@@ -1,74 +1,74 @@
/**
* Flexmojos is a set of maven goals to allow maven users to compile, optimize and test Flex SWF, Flex SWC, Air SWF and Air SWC.
* Copyright (C) 2008-2012 Marvin Froeder <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.sonatype.flexmojos.tests.concept;
import java.io.File;
import java.io.IOException;
import org.apache.maven.it.VerificationException;
import org.sonatype.flexmojos.tests.AbstractFlexMojosTests;
import org.testng.annotations.Test;
public class ArchetypesTest
extends AbstractFlexMojosTests
{
private static File baseTestDir;
@Test
public void testApplication()
throws Exception
{
testArchetype( "application" );
}
@Test
public void testLibrary()
throws Exception
{
testArchetype( "library" );
}
@Test
public void testModular()
throws Exception
{
testArchetype( "modular-webapp" );
}
private void testArchetype( String kind )
throws IOException, VerificationException
{
if ( baseTestDir == null )
{
baseTestDir = getProject( "/concept/archetype" );
}
String artifactId = "artifact-it-" + kind;
String[] args =
new String[] { "-DarchetypeGroupId=org.sonatype.flexmojos",
"-DarchetypeArtifactId=flexmojos-archetypes-" + kind, "-DarchetypeVersion=" + getFlexmojosVersion(),
"-DgroupId=org.sonatype.flexmojos.it", "-DartifactId=" + artifactId, "-Dversion=1.0-SNAPSHOT" };
- test( baseTestDir, "org.apache.maven.plugins:maven-archetype-plugin:2.0-alpha-4:create", args );
+ test( baseTestDir, "org.apache.maven.plugins:maven-archetype-plugin:2.0-alpha-5:create", args );
File testDir2 = new File( baseTestDir, artifactId );
test( testDir2, "install" );
}
}
| true | true | private void testArchetype( String kind )
throws IOException, VerificationException
{
if ( baseTestDir == null )
{
baseTestDir = getProject( "/concept/archetype" );
}
String artifactId = "artifact-it-" + kind;
String[] args =
new String[] { "-DarchetypeGroupId=org.sonatype.flexmojos",
"-DarchetypeArtifactId=flexmojos-archetypes-" + kind, "-DarchetypeVersion=" + getFlexmojosVersion(),
"-DgroupId=org.sonatype.flexmojos.it", "-DartifactId=" + artifactId, "-Dversion=1.0-SNAPSHOT" };
test( baseTestDir, "org.apache.maven.plugins:maven-archetype-plugin:2.0-alpha-4:create", args );
File testDir2 = new File( baseTestDir, artifactId );
test( testDir2, "install" );
}
| private void testArchetype( String kind )
throws IOException, VerificationException
{
if ( baseTestDir == null )
{
baseTestDir = getProject( "/concept/archetype" );
}
String artifactId = "artifact-it-" + kind;
String[] args =
new String[] { "-DarchetypeGroupId=org.sonatype.flexmojos",
"-DarchetypeArtifactId=flexmojos-archetypes-" + kind, "-DarchetypeVersion=" + getFlexmojosVersion(),
"-DgroupId=org.sonatype.flexmojos.it", "-DartifactId=" + artifactId, "-Dversion=1.0-SNAPSHOT" };
test( baseTestDir, "org.apache.maven.plugins:maven-archetype-plugin:2.0-alpha-5:create", args );
File testDir2 = new File( baseTestDir, artifactId );
test( testDir2, "install" );
}
|
diff --git a/src/de/bwv_aachen/dijkstra/gui/Mainwindow.java b/src/de/bwv_aachen/dijkstra/gui/Mainwindow.java
index 5394aa1..8ba619d 100644
--- a/src/de/bwv_aachen/dijkstra/gui/Mainwindow.java
+++ b/src/de/bwv_aachen/dijkstra/gui/Mainwindow.java
@@ -1,228 +1,228 @@
/**
* Mainwindow
* <p>
* The main window
*
* @author Serjoscha Bassauer
*/
package de.bwv_aachen.dijkstra.gui;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowFocusListener;
import java.awt.event.WindowListener;
import java.awt.event.WindowStateListener;
import java.io.File;
import java.util.Vector;
import java.util.regex.Pattern;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import de.bwv_aachen.dijkstra.controller.Controller;
import de.bwv_aachen.dijkstra.helpers.JSONFileChooser;
import de.bwv_aachen.dijkstra.model.Airport;
import de.bwv_aachen.dijkstra.model.ListDataModel;
@SuppressWarnings("serial")
public class Mainwindow extends View implements ActionListener {
private JComboBox<Object> leftList;
private JComboBox<Object> rightList;
boolean file_changed;
private File connectionFile;
private final JSONFileChooser chooser = new JSONFileChooser();
public Mainwindow(Controller c) {
super(c);
connectionFile = controller.getDefaultConnectionFile();
file_changed = true;
//Every time when the Mainwindow gains the focus, redraw it
this.addWindowFocusListener(new WindowFocusListener() {
@Override
public void windowGainedFocus(WindowEvent e) {
draw();
}
@Override
public void windowLostFocus(WindowEvent e) {
}
});
}
@Override
public void draw() {
super.getContentPane().removeAll(); // making this function being able
// to repaint the mainwindow
super.setTitle("Dijkstra");
super.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
super.setResizable(false);
super.setLayout(new GridLayout(3, 2, 2, 2));
((JComponent) getContentPane()).setBorder(BorderFactory
.createMatteBorder(4, 4, 4, 4, Color.LIGHT_GRAY));
if (file_changed) {
try {
Controller.INSTANCE.readFile(connectionFile);
}
catch (Exception e) {
JOptionPane.showMessageDialog(this,
- "Die Datei konnte nicht ge�ffnet werden", "Fehler",
+ "Die Datei konnte nicht geöffnet werden", "Fehler",
JOptionPane.ERROR_MESSAGE);
}
file_changed = false;
}
ListDataModel model = controller.getModel();
Object[] locations = model.getAirportList().values().toArray();
// Create the lists
leftList = new JComboBox<>(locations);
rightList = new JComboBox<>(locations);
rightList.setSelectedIndex(1); // just for a more professional
// impression of the program -> mark
// the second element in the second
// list as active
// Create a button for being able to submit the action
JButton startAction = new JButton("Berechnen");
startAction.setActionCommand("calc");
startAction.addActionListener(this);
// Add elements to the frame
super.add(new JLabel("Start"));
super.add(leftList);
super.add(new JLabel("Ziel"));
super.add(rightList);
super.add(startAction);
super.add(new JLabel());
// Create a menu for various actions
JMenuBar menuBar = new JMenuBar();
super.setJMenuBar(menuBar);
// Define Menu Cats
JMenu fileMenu = new JMenu("Datei");
menuBar.add(fileMenu);
JMenu infoMenu = new JMenu("Info");
menuBar.add(infoMenu);
// Define Menu Items within the cats
- JMenuItem openFile = new JMenuItem("�ffnen...");
+ JMenuItem openFile = new JMenuItem("Öffnen...");
openFile.addActionListener(this);
openFile.setActionCommand("loadFile");
fileMenu.add(openFile);
JMenuItem editFile = new JMenuItem("Bearbeiten...");
editFile.addActionListener(this);
editFile.setActionCommand("editFile");
fileMenu.add(editFile);
JMenuItem saveFile = new JMenuItem("Speichern unter...");
saveFile.addActionListener(this);
saveFile.setActionCommand("saveFile");
fileMenu.add(saveFile);
// Info menu
JMenuItem fileInfo = new JMenuItem(connectionFile.getAbsolutePath()
.toString());
fileInfo.setEnabled(false);
JMenuItem textLabelFileInfo = new JMenuItem(
"Momentan ge�ffnete Datei:");
textLabelFileInfo.setEnabled(false);
infoMenu.add(textLabelFileInfo);
infoMenu.add(fileInfo);
// Do the rest for displaying the window
super.pack();
super.setLocationRelativeTo(null); // center the frame
// Show the window
super.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
switch (e.getActionCommand()) {
case "calc": {
Airport from = (Airport) leftList.getSelectedItem();
Airport to = (Airport) rightList.getSelectedItem();
Vector<Vector<Object>> test = Controller.INSTANCE.getModel()
.getRoute(from, to);
new ConnectionTableWindow(test).draw();
break;
}
case "loadFile": {
chooser.setDialogType(JFileChooser.OPEN_DIALOG);
if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
connectionFile = new File(chooser.getSelectedFile()
.getAbsolutePath()); // set the new file to parse before
// redrawing the gui with new
// data
file_changed = true;
// draw(); // repaint the gui!
}
break;
}
case "editFile": {
EditorWindow ew = new EditorWindow(controller);
ew.draw();
break;
}
case "saveFile": {
File oldFile = connectionFile;
chooser.setDialogType(JFileChooser.SAVE_DIALOG);
if (chooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
String path = chooser.getSelectedFile().getAbsolutePath();
// Add file ending if missing
if (!Pattern.matches(".*\\.json", path)) {
path = path.concat(".json");
}
connectionFile = new File(path);
try {
Controller.INSTANCE.writeFile(connectionFile);
file_changed = true;
}
catch (Exception ex) {
// TODO Show an error message depending on the thrown
// exception
connectionFile = oldFile;
JOptionPane.showMessageDialog(this,
"Die Datei konnte nicht gespeichert werden",
"Fehler", JOptionPane.ERROR_MESSAGE);
}
}
break;
}
}
}
}
| false | true | public void draw() {
super.getContentPane().removeAll(); // making this function being able
// to repaint the mainwindow
super.setTitle("Dijkstra");
super.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
super.setResizable(false);
super.setLayout(new GridLayout(3, 2, 2, 2));
((JComponent) getContentPane()).setBorder(BorderFactory
.createMatteBorder(4, 4, 4, 4, Color.LIGHT_GRAY));
if (file_changed) {
try {
Controller.INSTANCE.readFile(connectionFile);
}
catch (Exception e) {
JOptionPane.showMessageDialog(this,
"Die Datei konnte nicht ge�ffnet werden", "Fehler",
JOptionPane.ERROR_MESSAGE);
}
file_changed = false;
}
ListDataModel model = controller.getModel();
Object[] locations = model.getAirportList().values().toArray();
// Create the lists
leftList = new JComboBox<>(locations);
rightList = new JComboBox<>(locations);
rightList.setSelectedIndex(1); // just for a more professional
// impression of the program -> mark
// the second element in the second
// list as active
// Create a button for being able to submit the action
JButton startAction = new JButton("Berechnen");
startAction.setActionCommand("calc");
startAction.addActionListener(this);
// Add elements to the frame
super.add(new JLabel("Start"));
super.add(leftList);
super.add(new JLabel("Ziel"));
super.add(rightList);
super.add(startAction);
super.add(new JLabel());
// Create a menu for various actions
JMenuBar menuBar = new JMenuBar();
super.setJMenuBar(menuBar);
// Define Menu Cats
JMenu fileMenu = new JMenu("Datei");
menuBar.add(fileMenu);
JMenu infoMenu = new JMenu("Info");
menuBar.add(infoMenu);
// Define Menu Items within the cats
JMenuItem openFile = new JMenuItem("�ffnen...");
openFile.addActionListener(this);
openFile.setActionCommand("loadFile");
fileMenu.add(openFile);
JMenuItem editFile = new JMenuItem("Bearbeiten...");
editFile.addActionListener(this);
editFile.setActionCommand("editFile");
fileMenu.add(editFile);
JMenuItem saveFile = new JMenuItem("Speichern unter...");
saveFile.addActionListener(this);
saveFile.setActionCommand("saveFile");
fileMenu.add(saveFile);
// Info menu
JMenuItem fileInfo = new JMenuItem(connectionFile.getAbsolutePath()
.toString());
fileInfo.setEnabled(false);
JMenuItem textLabelFileInfo = new JMenuItem(
"Momentan ge�ffnete Datei:");
textLabelFileInfo.setEnabled(false);
infoMenu.add(textLabelFileInfo);
infoMenu.add(fileInfo);
// Do the rest for displaying the window
super.pack();
super.setLocationRelativeTo(null); // center the frame
// Show the window
super.setVisible(true);
}
| public void draw() {
super.getContentPane().removeAll(); // making this function being able
// to repaint the mainwindow
super.setTitle("Dijkstra");
super.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
super.setResizable(false);
super.setLayout(new GridLayout(3, 2, 2, 2));
((JComponent) getContentPane()).setBorder(BorderFactory
.createMatteBorder(4, 4, 4, 4, Color.LIGHT_GRAY));
if (file_changed) {
try {
Controller.INSTANCE.readFile(connectionFile);
}
catch (Exception e) {
JOptionPane.showMessageDialog(this,
"Die Datei konnte nicht geöffnet werden", "Fehler",
JOptionPane.ERROR_MESSAGE);
}
file_changed = false;
}
ListDataModel model = controller.getModel();
Object[] locations = model.getAirportList().values().toArray();
// Create the lists
leftList = new JComboBox<>(locations);
rightList = new JComboBox<>(locations);
rightList.setSelectedIndex(1); // just for a more professional
// impression of the program -> mark
// the second element in the second
// list as active
// Create a button for being able to submit the action
JButton startAction = new JButton("Berechnen");
startAction.setActionCommand("calc");
startAction.addActionListener(this);
// Add elements to the frame
super.add(new JLabel("Start"));
super.add(leftList);
super.add(new JLabel("Ziel"));
super.add(rightList);
super.add(startAction);
super.add(new JLabel());
// Create a menu for various actions
JMenuBar menuBar = new JMenuBar();
super.setJMenuBar(menuBar);
// Define Menu Cats
JMenu fileMenu = new JMenu("Datei");
menuBar.add(fileMenu);
JMenu infoMenu = new JMenu("Info");
menuBar.add(infoMenu);
// Define Menu Items within the cats
JMenuItem openFile = new JMenuItem("Öffnen...");
openFile.addActionListener(this);
openFile.setActionCommand("loadFile");
fileMenu.add(openFile);
JMenuItem editFile = new JMenuItem("Bearbeiten...");
editFile.addActionListener(this);
editFile.setActionCommand("editFile");
fileMenu.add(editFile);
JMenuItem saveFile = new JMenuItem("Speichern unter...");
saveFile.addActionListener(this);
saveFile.setActionCommand("saveFile");
fileMenu.add(saveFile);
// Info menu
JMenuItem fileInfo = new JMenuItem(connectionFile.getAbsolutePath()
.toString());
fileInfo.setEnabled(false);
JMenuItem textLabelFileInfo = new JMenuItem(
"Momentan ge�ffnete Datei:");
textLabelFileInfo.setEnabled(false);
infoMenu.add(textLabelFileInfo);
infoMenu.add(fileInfo);
// Do the rest for displaying the window
super.pack();
super.setLocationRelativeTo(null); // center the frame
// Show the window
super.setVisible(true);
}
|
diff --git a/chips/src/com/android/ex/chips/SingleAddressAdapter.java b/chips/src/com/android/ex/chips/SingleAddressAdapter.java
index 97ad21e..8131fc3 100644
--- a/chips/src/com/android/ex/chips/SingleAddressAdapter.java
+++ b/chips/src/com/android/ex/chips/SingleAddressAdapter.java
@@ -1,63 +1,63 @@
/*
* Copyright (C) 2011 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.android.ex.chips;
import android.content.Context;
import android.text.util.Rfc822Tokenizer;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
class SingleRecipientArrayAdapter extends ArrayAdapter<RecipientEntry> {
private int mLayoutId;
private final LayoutInflater mLayoutInflater;
public SingleRecipientArrayAdapter(Context context, int resourceId, RecipientEntry entry) {
super(context, resourceId, new RecipientEntry[] {
entry
});
mLayoutInflater = LayoutInflater.from(context);
mLayoutId = resourceId;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = newView();
}
bindView(convertView, convertView.getContext(), getItem(position));
return convertView;
}
private View newView() {
return mLayoutInflater.inflate(mLayoutId, null);
}
private void bindView(View view, Context context, RecipientEntry entry) {
- TextView display = (TextView) view.findViewById(android.R.id.text1);
+ TextView display = (TextView) view.findViewById(android.R.id.title);
ImageView imageView = (ImageView) view.findViewById(android.R.id.icon);
display.setText(entry.getDisplayName());
display.setVisibility(View.VISIBLE);
imageView.setVisibility(View.VISIBLE);
- TextView destination = (TextView) view.findViewById(android.R.id.text2);
+ TextView destination = (TextView) view.findViewById(android.R.id.text1);
destination.setText(Rfc822Tokenizer.tokenize(entry.getDestination())[0].getAddress());
}
}
| false | true | private void bindView(View view, Context context, RecipientEntry entry) {
TextView display = (TextView) view.findViewById(android.R.id.text1);
ImageView imageView = (ImageView) view.findViewById(android.R.id.icon);
display.setText(entry.getDisplayName());
display.setVisibility(View.VISIBLE);
imageView.setVisibility(View.VISIBLE);
TextView destination = (TextView) view.findViewById(android.R.id.text2);
destination.setText(Rfc822Tokenizer.tokenize(entry.getDestination())[0].getAddress());
}
| private void bindView(View view, Context context, RecipientEntry entry) {
TextView display = (TextView) view.findViewById(android.R.id.title);
ImageView imageView = (ImageView) view.findViewById(android.R.id.icon);
display.setText(entry.getDisplayName());
display.setVisibility(View.VISIBLE);
imageView.setVisibility(View.VISIBLE);
TextView destination = (TextView) view.findViewById(android.R.id.text1);
destination.setText(Rfc822Tokenizer.tokenize(entry.getDestination())[0].getAddress());
}
|
diff --git a/util/plugins/eu.esdihumboldt.util/src/eu/esdihumboldt/util/StructuredEquals.java b/util/plugins/eu.esdihumboldt.util/src/eu/esdihumboldt/util/StructuredEquals.java
index 3ea38784a..2c1b99806 100644
--- a/util/plugins/eu.esdihumboldt.util/src/eu/esdihumboldt/util/StructuredEquals.java
+++ b/util/plugins/eu.esdihumboldt.util/src/eu/esdihumboldt/util/StructuredEquals.java
@@ -1,122 +1,122 @@
/*
* HUMBOLDT: A Framework for Data Harmonisation and Service Integration.
* EU Integrated Project #030962 01.10.2006 - 30.09.2010
*
* For more information on the project, please refer to the this web site:
* http://www.esdi-humboldt.eu
*
* LICENSE: For information on the license under which this program is
* available, please refer to http:/www.esdi-humboldt.eu/license.html#core
* (c) the HUMBOLDT Consortium, 2007 to 2011.
*/
package eu.esdihumboldt.util;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.NoSuchElementException;
import com.google.common.base.Objects;
import com.google.common.collect.Iterables;
/**
* StructuredEquals provides methods for equals and hashCode implementations
* for complex structures.
*
* @author Simon Templer
*/
public class StructuredEquals {
/**
* Determines if the given objects are equal, in turn descending into
* {@link Iterable}s and arrays and checking if the elements are equal
* (in order).
* @param o1 the first object
* @param o2 the second object
* @return if both objects are equal
* @see #deepIterableHashCode(Object)
*/
public boolean deepIterableEquals(Object o1, Object o2) {
if (o1 == o2) {
return true;
}
Iterable<?> iterable1 = asIterable(o1);
- Iterable<?> iterable2 = asIterable(o1);
+ Iterable<?> iterable2 = asIterable(o2);
if (iterable1 != null && iterable2 != null) {
if (Iterables.size(iterable1) == Iterables.size(iterable2)) { // size check
Iterator<?> it1 = iterable1.iterator();
Iterator<?> it2 = iterable2.iterator();
while (it1.hasNext() || it2.hasNext()) {
try {
if (!deepIterableEquals(it1.next(), it2.next())) {
return false;
}
} catch (NoSuchElementException e) {
return false;
}
}
return true;
}
return false;
}
else {
return Objects.equal(o1, o2);
}
}
/**
* Get the hash code for all contained objects, descending into
* {@link Iterable}s and arrays.
* @param object the object to determine the hash code from
* @return the hash code
* @see #deepIterableEquals(Object, Object)
*/
public int deepIterableHashCode(Object object) {
return Arrays.hashCode(collectObjects(object).toArray());
}
/**
* Collect all objects contained in an {@link Iterable} or array and in
* their elements.
* @param object the object to collect objects on
* @return the collected objects
*/
public Collection<?> collectObjects(Object object) {
Iterable<?> iterable = asIterable(object);
if (iterable == null) {
return Collections.singleton(object);
}
else {
Collection<Object> result = new ArrayList<Object>();
for (Object child : iterable) {
result.addAll(collectObjects(child));
}
return result;
}
}
/**
* Returns an iterable for the given objects contents, or null
* if it does not contain anything that needs to be compared.
*
* @param object the object in question
* @return an iterable for the given object
*/
protected Iterable<?> asIterable(Object object) {
if (object == null)
return null;
if (object instanceof Iterable<?>) {
return (Iterable<?>) object;
}
if (object.getClass().isArray()) {
return Arrays.asList((Object[]) object);
}
return null;
}
}
| true | true | public boolean deepIterableEquals(Object o1, Object o2) {
if (o1 == o2) {
return true;
}
Iterable<?> iterable1 = asIterable(o1);
Iterable<?> iterable2 = asIterable(o1);
if (iterable1 != null && iterable2 != null) {
if (Iterables.size(iterable1) == Iterables.size(iterable2)) { // size check
Iterator<?> it1 = iterable1.iterator();
Iterator<?> it2 = iterable2.iterator();
while (it1.hasNext() || it2.hasNext()) {
try {
if (!deepIterableEquals(it1.next(), it2.next())) {
return false;
}
} catch (NoSuchElementException e) {
return false;
}
}
return true;
}
return false;
}
else {
return Objects.equal(o1, o2);
}
}
| public boolean deepIterableEquals(Object o1, Object o2) {
if (o1 == o2) {
return true;
}
Iterable<?> iterable1 = asIterable(o1);
Iterable<?> iterable2 = asIterable(o2);
if (iterable1 != null && iterable2 != null) {
if (Iterables.size(iterable1) == Iterables.size(iterable2)) { // size check
Iterator<?> it1 = iterable1.iterator();
Iterator<?> it2 = iterable2.iterator();
while (it1.hasNext() || it2.hasNext()) {
try {
if (!deepIterableEquals(it1.next(), it2.next())) {
return false;
}
} catch (NoSuchElementException e) {
return false;
}
}
return true;
}
return false;
}
else {
return Objects.equal(o1, o2);
}
}
|
diff --git a/src/impl/java/org/wyona/yarep/impl/repo/xmldb/XMLDBStorage.java b/src/impl/java/org/wyona/yarep/impl/repo/xmldb/XMLDBStorage.java
index a83da06..b119749 100644
--- a/src/impl/java/org/wyona/yarep/impl/repo/xmldb/XMLDBStorage.java
+++ b/src/impl/java/org/wyona/yarep/impl/repo/xmldb/XMLDBStorage.java
@@ -1,354 +1,354 @@
package org.wyona.yarep.impl.repo.xmldb;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.io.Writer;
import org.wyona.yarep.core.Path;
import org.wyona.yarep.core.RepositoryException;
import org.wyona.yarep.core.Storage;
import org.wyona.yarep.core.UID;
import org.wyona.commons.io.FileUtil;
import org.apache.avalon.framework.configuration.Configuration;
import org.apache.avalon.framework.configuration.DefaultConfigurationBuilder;
import org.apache.log4j.Category;
import org.xmldb.api.DatabaseManager;
import org.xmldb.api.base.Collection;
import org.xmldb.api.base.Database;
import org.xmldb.api.base.Service;
import org.xmldb.api.base.XMLDBException;
import org.xmldb.api.modules.CollectionManagementService;
/**
* @author Andreas Wuest
*/
public class XMLDBStorage implements Storage {
private static Category mLog = Category.getInstance(XMLDBStorage.class);
private Credentials mCredentials;
private String mDatabaseURIPrefix;
/**
* XMLDBStorage constructor.
*/
public XMLDBStorage() {}
/**
* XMLDBStorage constructor.
*
* @param aID the repository ID
* @param aRepoConfigFile the repsitory configuration file
*/
public XMLDBStorage(String aID, File aRepoConfigFile) throws RepositoryException {
Configuration storageConfig;
try {
storageConfig = (new DefaultConfigurationBuilder()).buildFromFile(aRepoConfigFile).getChild("storage", false);
} catch (Exception exception) {
mLog.error(exception);
throw new RepositoryException(exception.getMessage(), exception);
}
readConfig(storageConfig, aRepoConfigFile);
}
/**
* Reads the repository configuration and initialises the database.
*
* @param aStorageConfig the storage configuration
* @param aRepoConfigFile the storage configuration as a raw file
*/
public void readConfig(Configuration aStorageConfig, File aRepoConfigFile) throws RepositoryException {
- Boolean createPrefix;
+ boolean createPrefix;
Configuration repositoryConfig;
Configuration credentialsConfig;
Database database;
File databaseHomeDir;
Service collectionService;
String driverName;
String databaseHome;
String rootCollection;
String pathPrefix;
String databaseAddress;
String databaseName;
String databaseURIPrefix;
/* TODO: replace most mLog.error() invocations by mLog.debug().
* Unfortunately, mLog.debug() produces no output, even if activated
* in the log4.properties. */
// check if we received a storage configuration and a repo config file
if (aStorageConfig == null || aRepoConfigFile == null)
throw new RepositoryException("No storage/repository configuration available.");
try {
// retrieve the database driver name (e.g. "org.apache.xindice.client.xmldb.DatabaseImpl") [mandatory]
driverName = aStorageConfig.getChild("driver").getValue("");
mLog.error("Specified driver name = \"" + driverName + "\".");
// retrieve the database home (e.g. "../data") [optional]
databaseHome = aStorageConfig.getChild("db-home").getValue(null);
mLog.error("Specified database home = \"" + databaseHome + "\".");
// retrieve the root collection name (e.g. "db") [mandatory]
rootCollection = aStorageConfig.getChild("root").getValue("");
mLog.error("Specified root collection = \"" + rootCollection + "\".");
// retrieve the path prefix (e.g. "some/sample/collection") [optional]
pathPrefix = aStorageConfig.getChild("prefix").getValue("");
createPrefix = aStorageConfig.getChild("prefix").getAttributeAsBoolean("createIfNotExists", false);
mLog.error("Specified collection prefix = \"" + pathPrefix + "\" (create if not exists: \"" + createPrefix + "\").");
// retrieve the name of the database host (e.g. "myhost.domain.com:8080") [optional]
databaseAddress = aStorageConfig.getChild("address").getValue("");
mLog.error("Specified database address = \"" + databaseAddress + "\".");
// retrieve credentials [optional]
credentialsConfig = aStorageConfig.getChild("credentials", false);
if (credentialsConfig != null) {
mCredentials = new Credentials(credentialsConfig.getChild("username").getValue(""),
credentialsConfig.getChild("password").getValue(""));
mLog.error("Specified credentials read.");
}
} catch (Exception exception) {
mLog.error(exception);
throw new RepositoryException(exception.getMessage(), exception);
}
// check if the driver name was specified
if (driverName.equals(""))
throw new RepositoryException("Database driver not specified.");
// check if the root collection was specified
if (rootCollection.equals(""))
throw new RepositoryException("Database root collection not specified.");
// register the database with the database manager
try {
database = (Database) Class.forName(driverName).newInstance();
// determine the database location
if (databaseHome != null) {
// resolve the database home relative to the repo config file directory
databaseHomeDir = new File(databaseHome);
if (!databaseHomeDir.isAbsolute()) {
databaseHomeDir = FileUtil.file(aRepoConfigFile.getParent(), databaseHomeDir.toString());
}
mLog.error("Resolved database home directory = \"" + databaseHomeDir + "\"");
database.setProperty("db-home", databaseHomeDir.toString());
}
// set the database location
DatabaseManager.registerDatabase(database);
databaseName = database.getName();
} catch (Exception exception) {
mLog.error(exception);
throw new RepositoryException(exception.getMessage(), exception);
}
// construct the database URI prefix up to (and inluding) the root collection
databaseURIPrefix = "xmldb:" + databaseName + "://" + databaseAddress + "/" + rootCollection + "/";
// construct the complete database URI prefix including a potential path prefix
if (pathPrefix.equals("")) {
mDatabaseURIPrefix = databaseURIPrefix;
} else {
mDatabaseURIPrefix = databaseURIPrefix + "/" + pathPrefix + "/";
}
mLog.error("Collection base path = \"" + databaseURIPrefix + "\".");
mLog.error("Complete collection base path = \"" + mDatabaseURIPrefix + "\".");
// test drive our new database instance
try {
database.acceptsURI(mDatabaseURIPrefix);
} catch (XMLDBException exception) {
mLog.error(exception);
if (exception.errorCode == org.xmldb.api.base.ErrorCodes.INVALID_URI) {
throw new RepositoryException("The database does not accept the URI prefix \"" + mDatabaseURIPrefix + "\" as valid. Please make sure that the database host address (\"" + databaseAddress + "\") is correct. Original message: " + exception.getMessage(), exception);
} else {
throw new RepositoryException(exception.getMessage(), exception);
}
} catch (Exception exception) {
mLog.error(exception);
throw new RepositoryException(exception.getMessage(), exception);
}
try {
// check if the specified root collection exists
if (getCollection(databaseURIPrefix) == null)
throw new RepositoryException("Specified root collection (\"" + rootCollection + "\") does not exist.");
// check if the complete collection prefix exists
if (getCollectionRelative(null) == null) {
if (createPrefix) {
// create the prefix collection
try {
collectionService = getCollection(databaseURIPrefix).getService("CollectionManagementService", "1.0");
((CollectionManagementService) collectionService).createCollection(pathPrefix);
// re-check if complete collection prefix exists now, we don't want to take any chances here
if (getCollectionRelative(null) == null)
throw new RepositoryException("Specified collection prefix (\"" + pathPrefix + "\") does not exist.");
} catch (Exception exception) {
mLog.error(exception);
throw new RepositoryException("Failed to create prefix collection (\"" + pathPrefix + "\"). Original message: " + exception.getMessage(), exception);
}
mLog.error("Created new collection \"" + pathPrefix + "\".");
} else {
// the prefix collection does not exist
throw new RepositoryException("Specified collection prefix (\"" + pathPrefix + "\") does not exist.");
}
}
} catch (Exception exception) {
// something went wrong after registering the database, we have to deregister it now
try {
DatabaseManager.deregisterDatabase(database);
} catch (Exception databaseException) {
mLog.error(databaseException);
throw new RepositoryException(databaseException.getMessage(), databaseException);
}
/* Rethrow exception. We have to construct a new exception here, because the type system
* doesn't know that only RepositoryExceptions can get to this point (we catch all other
* exceptions above already), and would therefore complain. */
throw new RepositoryException(exception.getMessage(), exception);
}
}
/**
*@deprecated
*/
public Writer getWriter(UID aUID, Path aPath) {
mLog.warn("Not implemented yet!");
return null;
}
/**
*
*/
public OutputStream getOutputStream(UID aUID, Path aPath) throws RepositoryException {
mLog.warn("Not implemented yet!");
return null;
}
/**
*@deprecated
*/
public Reader getReader(UID aUID, Path aPath) {
mLog.warn("Not implemented yet!");
return null;
}
/**
*
*/
public InputStream getInputStream(UID aUID, Path aPath) throws RepositoryException {
mLog.warn("Not implemented yet!");
return null;
}
/**
*
*/
public long getLastModified(UID aUID, Path aPath) throws RepositoryException {
mLog.warn("Not implemented yet!");
return 0;
}
/**
*
*/
public long getSize(UID aUID, Path aPath) throws RepositoryException {
mLog.warn("Not implemented yet!");
return 0;
}
/**
*
*/
public boolean delete(UID aUID, Path aPath) throws RepositoryException {
mLog.error("TODO: Not implemented yet!");
return false;
}
/**
*
*/
public String[] getRevisions(UID aUID, Path aPath) throws RepositoryException {
mLog.warn("Versioning not implemented yet");
return null;
}
/**
* Retrieves the collection for the specified collection URI, relative to
* the global collection prefix path.
*
* @param aCollectionURI the relative URI of the collection to retrieve, or null to
* retrieve the global prefix collection
* @return a collection instance for the requested collection or
* null if the collection could not be found
* @throws RepositoryException if an error occurred retrieving the collection (e.g.
* permission was denied)
*/
private Collection getCollectionRelative(String aCollectionURI) throws RepositoryException {
return getCollection(constructCollectionURI(aCollectionURI));
}
/**
* Retrieves the collection for the specified collection URI.
*
* @param aCollectionURI the xmldb URI of the collection to retrieve
* @return a collection instance for the requested collection or
* null if the collection could not be found
* @throws RepositoryException if an error occurred retrieving the collection (e.g.
* permission was denied)
*/
private Collection getCollection(String aCollectionURI) throws RepositoryException {
try {
if (mCredentials != null) {
return DatabaseManager.getCollection(aCollectionURI, mCredentials.getUsername(), mCredentials.getPassword());
} else {
return DatabaseManager.getCollection(aCollectionURI);
}
} catch (Exception exception) {
mLog.error(exception);
throw new RepositoryException(exception.getMessage(), exception);
}
}
private String constructCollectionURI(String aCollectionURI) {
return mDatabaseURIPrefix + "/" + (aCollectionURI != null ? aCollectionURI : "");
}
private class Credentials {
private final String mUsername;
private final String mPassword;
public Credentials(String aUsername, String aPassword) {
mUsername = aUsername;
mPassword = aPassword;
}
public String getUsername() {
return mUsername;
}
public String getPassword() {
return mPassword;
}
}
}
| true | true | public void readConfig(Configuration aStorageConfig, File aRepoConfigFile) throws RepositoryException {
Boolean createPrefix;
Configuration repositoryConfig;
Configuration credentialsConfig;
Database database;
File databaseHomeDir;
Service collectionService;
String driverName;
String databaseHome;
String rootCollection;
String pathPrefix;
String databaseAddress;
String databaseName;
String databaseURIPrefix;
/* TODO: replace most mLog.error() invocations by mLog.debug().
* Unfortunately, mLog.debug() produces no output, even if activated
* in the log4.properties. */
// check if we received a storage configuration and a repo config file
if (aStorageConfig == null || aRepoConfigFile == null)
throw new RepositoryException("No storage/repository configuration available.");
try {
// retrieve the database driver name (e.g. "org.apache.xindice.client.xmldb.DatabaseImpl") [mandatory]
driverName = aStorageConfig.getChild("driver").getValue("");
mLog.error("Specified driver name = \"" + driverName + "\".");
// retrieve the database home (e.g. "../data") [optional]
databaseHome = aStorageConfig.getChild("db-home").getValue(null);
mLog.error("Specified database home = \"" + databaseHome + "\".");
// retrieve the root collection name (e.g. "db") [mandatory]
rootCollection = aStorageConfig.getChild("root").getValue("");
mLog.error("Specified root collection = \"" + rootCollection + "\".");
// retrieve the path prefix (e.g. "some/sample/collection") [optional]
pathPrefix = aStorageConfig.getChild("prefix").getValue("");
createPrefix = aStorageConfig.getChild("prefix").getAttributeAsBoolean("createIfNotExists", false);
mLog.error("Specified collection prefix = \"" + pathPrefix + "\" (create if not exists: \"" + createPrefix + "\").");
// retrieve the name of the database host (e.g. "myhost.domain.com:8080") [optional]
databaseAddress = aStorageConfig.getChild("address").getValue("");
mLog.error("Specified database address = \"" + databaseAddress + "\".");
// retrieve credentials [optional]
credentialsConfig = aStorageConfig.getChild("credentials", false);
if (credentialsConfig != null) {
mCredentials = new Credentials(credentialsConfig.getChild("username").getValue(""),
credentialsConfig.getChild("password").getValue(""));
mLog.error("Specified credentials read.");
}
} catch (Exception exception) {
mLog.error(exception);
throw new RepositoryException(exception.getMessage(), exception);
}
// check if the driver name was specified
if (driverName.equals(""))
throw new RepositoryException("Database driver not specified.");
// check if the root collection was specified
if (rootCollection.equals(""))
throw new RepositoryException("Database root collection not specified.");
// register the database with the database manager
try {
database = (Database) Class.forName(driverName).newInstance();
// determine the database location
if (databaseHome != null) {
// resolve the database home relative to the repo config file directory
databaseHomeDir = new File(databaseHome);
if (!databaseHomeDir.isAbsolute()) {
databaseHomeDir = FileUtil.file(aRepoConfigFile.getParent(), databaseHomeDir.toString());
}
mLog.error("Resolved database home directory = \"" + databaseHomeDir + "\"");
database.setProperty("db-home", databaseHomeDir.toString());
}
// set the database location
DatabaseManager.registerDatabase(database);
databaseName = database.getName();
} catch (Exception exception) {
mLog.error(exception);
throw new RepositoryException(exception.getMessage(), exception);
}
// construct the database URI prefix up to (and inluding) the root collection
databaseURIPrefix = "xmldb:" + databaseName + "://" + databaseAddress + "/" + rootCollection + "/";
// construct the complete database URI prefix including a potential path prefix
if (pathPrefix.equals("")) {
mDatabaseURIPrefix = databaseURIPrefix;
} else {
mDatabaseURIPrefix = databaseURIPrefix + "/" + pathPrefix + "/";
}
mLog.error("Collection base path = \"" + databaseURIPrefix + "\".");
mLog.error("Complete collection base path = \"" + mDatabaseURIPrefix + "\".");
// test drive our new database instance
try {
database.acceptsURI(mDatabaseURIPrefix);
} catch (XMLDBException exception) {
mLog.error(exception);
if (exception.errorCode == org.xmldb.api.base.ErrorCodes.INVALID_URI) {
throw new RepositoryException("The database does not accept the URI prefix \"" + mDatabaseURIPrefix + "\" as valid. Please make sure that the database host address (\"" + databaseAddress + "\") is correct. Original message: " + exception.getMessage(), exception);
} else {
throw new RepositoryException(exception.getMessage(), exception);
}
} catch (Exception exception) {
mLog.error(exception);
throw new RepositoryException(exception.getMessage(), exception);
}
try {
// check if the specified root collection exists
if (getCollection(databaseURIPrefix) == null)
throw new RepositoryException("Specified root collection (\"" + rootCollection + "\") does not exist.");
// check if the complete collection prefix exists
if (getCollectionRelative(null) == null) {
if (createPrefix) {
// create the prefix collection
try {
collectionService = getCollection(databaseURIPrefix).getService("CollectionManagementService", "1.0");
((CollectionManagementService) collectionService).createCollection(pathPrefix);
// re-check if complete collection prefix exists now, we don't want to take any chances here
if (getCollectionRelative(null) == null)
throw new RepositoryException("Specified collection prefix (\"" + pathPrefix + "\") does not exist.");
} catch (Exception exception) {
mLog.error(exception);
throw new RepositoryException("Failed to create prefix collection (\"" + pathPrefix + "\"). Original message: " + exception.getMessage(), exception);
}
mLog.error("Created new collection \"" + pathPrefix + "\".");
} else {
// the prefix collection does not exist
throw new RepositoryException("Specified collection prefix (\"" + pathPrefix + "\") does not exist.");
}
}
} catch (Exception exception) {
// something went wrong after registering the database, we have to deregister it now
try {
DatabaseManager.deregisterDatabase(database);
} catch (Exception databaseException) {
mLog.error(databaseException);
throw new RepositoryException(databaseException.getMessage(), databaseException);
}
/* Rethrow exception. We have to construct a new exception here, because the type system
* doesn't know that only RepositoryExceptions can get to this point (we catch all other
* exceptions above already), and would therefore complain. */
throw new RepositoryException(exception.getMessage(), exception);
}
}
| public void readConfig(Configuration aStorageConfig, File aRepoConfigFile) throws RepositoryException {
boolean createPrefix;
Configuration repositoryConfig;
Configuration credentialsConfig;
Database database;
File databaseHomeDir;
Service collectionService;
String driverName;
String databaseHome;
String rootCollection;
String pathPrefix;
String databaseAddress;
String databaseName;
String databaseURIPrefix;
/* TODO: replace most mLog.error() invocations by mLog.debug().
* Unfortunately, mLog.debug() produces no output, even if activated
* in the log4.properties. */
// check if we received a storage configuration and a repo config file
if (aStorageConfig == null || aRepoConfigFile == null)
throw new RepositoryException("No storage/repository configuration available.");
try {
// retrieve the database driver name (e.g. "org.apache.xindice.client.xmldb.DatabaseImpl") [mandatory]
driverName = aStorageConfig.getChild("driver").getValue("");
mLog.error("Specified driver name = \"" + driverName + "\".");
// retrieve the database home (e.g. "../data") [optional]
databaseHome = aStorageConfig.getChild("db-home").getValue(null);
mLog.error("Specified database home = \"" + databaseHome + "\".");
// retrieve the root collection name (e.g. "db") [mandatory]
rootCollection = aStorageConfig.getChild("root").getValue("");
mLog.error("Specified root collection = \"" + rootCollection + "\".");
// retrieve the path prefix (e.g. "some/sample/collection") [optional]
pathPrefix = aStorageConfig.getChild("prefix").getValue("");
createPrefix = aStorageConfig.getChild("prefix").getAttributeAsBoolean("createIfNotExists", false);
mLog.error("Specified collection prefix = \"" + pathPrefix + "\" (create if not exists: \"" + createPrefix + "\").");
// retrieve the name of the database host (e.g. "myhost.domain.com:8080") [optional]
databaseAddress = aStorageConfig.getChild("address").getValue("");
mLog.error("Specified database address = \"" + databaseAddress + "\".");
// retrieve credentials [optional]
credentialsConfig = aStorageConfig.getChild("credentials", false);
if (credentialsConfig != null) {
mCredentials = new Credentials(credentialsConfig.getChild("username").getValue(""),
credentialsConfig.getChild("password").getValue(""));
mLog.error("Specified credentials read.");
}
} catch (Exception exception) {
mLog.error(exception);
throw new RepositoryException(exception.getMessage(), exception);
}
// check if the driver name was specified
if (driverName.equals(""))
throw new RepositoryException("Database driver not specified.");
// check if the root collection was specified
if (rootCollection.equals(""))
throw new RepositoryException("Database root collection not specified.");
// register the database with the database manager
try {
database = (Database) Class.forName(driverName).newInstance();
// determine the database location
if (databaseHome != null) {
// resolve the database home relative to the repo config file directory
databaseHomeDir = new File(databaseHome);
if (!databaseHomeDir.isAbsolute()) {
databaseHomeDir = FileUtil.file(aRepoConfigFile.getParent(), databaseHomeDir.toString());
}
mLog.error("Resolved database home directory = \"" + databaseHomeDir + "\"");
database.setProperty("db-home", databaseHomeDir.toString());
}
// set the database location
DatabaseManager.registerDatabase(database);
databaseName = database.getName();
} catch (Exception exception) {
mLog.error(exception);
throw new RepositoryException(exception.getMessage(), exception);
}
// construct the database URI prefix up to (and inluding) the root collection
databaseURIPrefix = "xmldb:" + databaseName + "://" + databaseAddress + "/" + rootCollection + "/";
// construct the complete database URI prefix including a potential path prefix
if (pathPrefix.equals("")) {
mDatabaseURIPrefix = databaseURIPrefix;
} else {
mDatabaseURIPrefix = databaseURIPrefix + "/" + pathPrefix + "/";
}
mLog.error("Collection base path = \"" + databaseURIPrefix + "\".");
mLog.error("Complete collection base path = \"" + mDatabaseURIPrefix + "\".");
// test drive our new database instance
try {
database.acceptsURI(mDatabaseURIPrefix);
} catch (XMLDBException exception) {
mLog.error(exception);
if (exception.errorCode == org.xmldb.api.base.ErrorCodes.INVALID_URI) {
throw new RepositoryException("The database does not accept the URI prefix \"" + mDatabaseURIPrefix + "\" as valid. Please make sure that the database host address (\"" + databaseAddress + "\") is correct. Original message: " + exception.getMessage(), exception);
} else {
throw new RepositoryException(exception.getMessage(), exception);
}
} catch (Exception exception) {
mLog.error(exception);
throw new RepositoryException(exception.getMessage(), exception);
}
try {
// check if the specified root collection exists
if (getCollection(databaseURIPrefix) == null)
throw new RepositoryException("Specified root collection (\"" + rootCollection + "\") does not exist.");
// check if the complete collection prefix exists
if (getCollectionRelative(null) == null) {
if (createPrefix) {
// create the prefix collection
try {
collectionService = getCollection(databaseURIPrefix).getService("CollectionManagementService", "1.0");
((CollectionManagementService) collectionService).createCollection(pathPrefix);
// re-check if complete collection prefix exists now, we don't want to take any chances here
if (getCollectionRelative(null) == null)
throw new RepositoryException("Specified collection prefix (\"" + pathPrefix + "\") does not exist.");
} catch (Exception exception) {
mLog.error(exception);
throw new RepositoryException("Failed to create prefix collection (\"" + pathPrefix + "\"). Original message: " + exception.getMessage(), exception);
}
mLog.error("Created new collection \"" + pathPrefix + "\".");
} else {
// the prefix collection does not exist
throw new RepositoryException("Specified collection prefix (\"" + pathPrefix + "\") does not exist.");
}
}
} catch (Exception exception) {
// something went wrong after registering the database, we have to deregister it now
try {
DatabaseManager.deregisterDatabase(database);
} catch (Exception databaseException) {
mLog.error(databaseException);
throw new RepositoryException(databaseException.getMessage(), databaseException);
}
/* Rethrow exception. We have to construct a new exception here, because the type system
* doesn't know that only RepositoryExceptions can get to this point (we catch all other
* exceptions above already), and would therefore complain. */
throw new RepositoryException(exception.getMessage(), exception);
}
}
|
diff --git a/mes-plugins/mes-plugins-time-norms-for-operations/src/test/java/com/qcadoo/mes/timeNormsForOperations/hooks/TechnologyOperationComponentDetailsHooksTest.java b/mes-plugins/mes-plugins-time-norms-for-operations/src/test/java/com/qcadoo/mes/timeNormsForOperations/hooks/TechnologyOperationComponentDetailsHooksTest.java
index 07c06bbe3e..579d4573eb 100644
--- a/mes-plugins/mes-plugins-time-norms-for-operations/src/test/java/com/qcadoo/mes/timeNormsForOperations/hooks/TechnologyOperationComponentDetailsHooksTest.java
+++ b/mes-plugins/mes-plugins-time-norms-for-operations/src/test/java/com/qcadoo/mes/timeNormsForOperations/hooks/TechnologyOperationComponentDetailsHooksTest.java
@@ -1,142 +1,142 @@
package com.qcadoo.mes.timeNormsForOperations.hooks;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.verify;
import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.Locale;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.test.util.ReflectionTestUtils;
import com.qcadoo.localization.api.TranslationService;
import com.qcadoo.mes.technologies.TechnologyService;
import com.qcadoo.model.api.DataDefinition;
import com.qcadoo.model.api.Entity;
import com.qcadoo.model.api.NumberService;
import com.qcadoo.view.api.ComponentState;
import com.qcadoo.view.api.ComponentState.MessageType;
import com.qcadoo.view.api.ViewDefinitionState;
import com.qcadoo.view.api.components.FormComponent;
public class TechnologyOperationComponentDetailsHooksTest {
private TechnologyOperationComponentDetailsHooks technologyOperationComponentDetailsHooks;
@Mock
private ViewDefinitionState view;
@Mock
private TechnologyService technologyService;
@Mock
private TranslationService translationService;
@Mock
private NumberService numberService;
@Mock
private Entity opComp1, prodComp1, product1;
@Mock
private FormComponent form;
@Mock
private DataDefinition dd;
@Mock
private ComponentState productionInOneCycle;
private DecimalFormat decimalFormat;
private Locale locale;
@Before
public void init() {
MockitoAnnotations.initMocks(this);
technologyOperationComponentDetailsHooks = new TechnologyOperationComponentDetailsHooks();
ReflectionTestUtils.setField(technologyOperationComponentDetailsHooks, "technologyService", technologyService);
ReflectionTestUtils.setField(technologyOperationComponentDetailsHooks, "translationService", translationService);
ReflectionTestUtils.setField(technologyOperationComponentDetailsHooks, "numberService", numberService);
given(numberService.getMathContext()).willReturn(MathContext.DECIMAL64);
locale = LocaleContextHolder.getLocale();
decimalFormat = (DecimalFormat) DecimalFormat.getInstance(locale);
decimalFormat.setMaximumFractionDigits(3);
decimalFormat.setMinimumFractionDigits(3);
decimalFormat.setRoundingMode(RoundingMode.HALF_EVEN);
given(numberService.format(Mockito.any(BigDecimal.class))).willAnswer(new Answer<String>() {
@Override
public String answer(InvocationOnMock invocation) throws Throwable {
Object[] args = invocation.getArguments();
BigDecimal number = (BigDecimal) args[0];
return decimalFormat.format(number);
}
});
given(view.getComponentByReference("form")).willReturn(form);
given(form.getEntity()).willReturn(opComp1);
given(opComp1.getDataDefinition()).willReturn(dd);
- given(dd.get(0l)).willReturn(opComp1);
+ given(dd.get(0L)).willReturn(opComp1);
given(technologyService.getMainOutputProductComponent(opComp1)).willReturn(prodComp1);
given(prodComp1.getDecimalField("quantity")).willReturn(new BigDecimal(1.1f));
given(opComp1.getDecimalField("productionInOneCycle")).willReturn(new BigDecimal(1.2f));
given(view.getComponentByReference("productionInOneCycle")).willReturn(productionInOneCycle);
given(prodComp1.getBelongsToField("product")).willReturn(product1);
given(product1.getStringField("unit")).willReturn("unit");
}
@Test
public void shouldNotFreakOutWhenTheOutputProductComponentCannotBeFound() {
given(technologyService.getMainOutputProductComponent(opComp1)).willThrow(new IllegalStateException());
// when
technologyOperationComponentDetailsHooks.checkOperationOutputQuantities(view);
}
@Test
public void shouldAttachCorrectErrorToTheRightComponentIfQuantitiesAreDifferent() {
// given
given(translationService.translate("technologies.technologyOperationComponent.validate.error.invalidQuantity1", locale))
.willReturn("message1");
given(translationService.translate("technologies.technologyOperationComponent.validate.error.invalidQuantity2", locale))
.willReturn("message2");
String number = decimalFormat.format(prodComp1.getDecimalField("quantity"));
// when
technologyOperationComponentDetailsHooks.checkOperationOutputQuantities(view);
// then
verify(productionInOneCycle).addMessage("message1 " + number + " unit message2", MessageType.FAILURE);
}
@Test
public void shouldNotGiveAnyErrorIfQuantitiesAreTheSame() {
// given
given(prodComp1.getDecimalField("quantity")).willReturn(new BigDecimal(1.1f));
given(opComp1.getDecimalField("productionInOneCycle")).willReturn(new BigDecimal(1.1f));
// when
technologyOperationComponentDetailsHooks.checkOperationOutputQuantities(view);
// then
verify(productionInOneCycle, Mockito.never()).addMessage(Mockito.anyString(), Mockito.eq(MessageType.FAILURE));
}
}
| true | true | public void init() {
MockitoAnnotations.initMocks(this);
technologyOperationComponentDetailsHooks = new TechnologyOperationComponentDetailsHooks();
ReflectionTestUtils.setField(technologyOperationComponentDetailsHooks, "technologyService", technologyService);
ReflectionTestUtils.setField(technologyOperationComponentDetailsHooks, "translationService", translationService);
ReflectionTestUtils.setField(technologyOperationComponentDetailsHooks, "numberService", numberService);
given(numberService.getMathContext()).willReturn(MathContext.DECIMAL64);
locale = LocaleContextHolder.getLocale();
decimalFormat = (DecimalFormat) DecimalFormat.getInstance(locale);
decimalFormat.setMaximumFractionDigits(3);
decimalFormat.setMinimumFractionDigits(3);
decimalFormat.setRoundingMode(RoundingMode.HALF_EVEN);
given(numberService.format(Mockito.any(BigDecimal.class))).willAnswer(new Answer<String>() {
@Override
public String answer(InvocationOnMock invocation) throws Throwable {
Object[] args = invocation.getArguments();
BigDecimal number = (BigDecimal) args[0];
return decimalFormat.format(number);
}
});
given(view.getComponentByReference("form")).willReturn(form);
given(form.getEntity()).willReturn(opComp1);
given(opComp1.getDataDefinition()).willReturn(dd);
given(dd.get(0l)).willReturn(opComp1);
given(technologyService.getMainOutputProductComponent(opComp1)).willReturn(prodComp1);
given(prodComp1.getDecimalField("quantity")).willReturn(new BigDecimal(1.1f));
given(opComp1.getDecimalField("productionInOneCycle")).willReturn(new BigDecimal(1.2f));
given(view.getComponentByReference("productionInOneCycle")).willReturn(productionInOneCycle);
given(prodComp1.getBelongsToField("product")).willReturn(product1);
given(product1.getStringField("unit")).willReturn("unit");
}
| public void init() {
MockitoAnnotations.initMocks(this);
technologyOperationComponentDetailsHooks = new TechnologyOperationComponentDetailsHooks();
ReflectionTestUtils.setField(technologyOperationComponentDetailsHooks, "technologyService", technologyService);
ReflectionTestUtils.setField(technologyOperationComponentDetailsHooks, "translationService", translationService);
ReflectionTestUtils.setField(technologyOperationComponentDetailsHooks, "numberService", numberService);
given(numberService.getMathContext()).willReturn(MathContext.DECIMAL64);
locale = LocaleContextHolder.getLocale();
decimalFormat = (DecimalFormat) DecimalFormat.getInstance(locale);
decimalFormat.setMaximumFractionDigits(3);
decimalFormat.setMinimumFractionDigits(3);
decimalFormat.setRoundingMode(RoundingMode.HALF_EVEN);
given(numberService.format(Mockito.any(BigDecimal.class))).willAnswer(new Answer<String>() {
@Override
public String answer(InvocationOnMock invocation) throws Throwable {
Object[] args = invocation.getArguments();
BigDecimal number = (BigDecimal) args[0];
return decimalFormat.format(number);
}
});
given(view.getComponentByReference("form")).willReturn(form);
given(form.getEntity()).willReturn(opComp1);
given(opComp1.getDataDefinition()).willReturn(dd);
given(dd.get(0L)).willReturn(opComp1);
given(technologyService.getMainOutputProductComponent(opComp1)).willReturn(prodComp1);
given(prodComp1.getDecimalField("quantity")).willReturn(new BigDecimal(1.1f));
given(opComp1.getDecimalField("productionInOneCycle")).willReturn(new BigDecimal(1.2f));
given(view.getComponentByReference("productionInOneCycle")).willReturn(productionInOneCycle);
given(prodComp1.getBelongsToField("product")).willReturn(product1);
given(product1.getStringField("unit")).willReturn("unit");
}
|
diff --git a/com.mountainminds.eclemma.ui/src/com/mountainminds/eclemma/internal/ui/launching/InplaceInstrumentationWarning.java b/com.mountainminds.eclemma.ui/src/com/mountainminds/eclemma/internal/ui/launching/InplaceInstrumentationWarning.java
index f590ea2..8089c89 100644
--- a/com.mountainminds.eclemma.ui/src/com/mountainminds/eclemma/internal/ui/launching/InplaceInstrumentationWarning.java
+++ b/com.mountainminds.eclemma.ui/src/com/mountainminds/eclemma/internal/ui/launching/InplaceInstrumentationWarning.java
@@ -1,56 +1,56 @@
/*
* $Id$
*/
package com.mountainminds.eclemma.internal.ui.launching;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.debug.core.ILaunchConfiguration;
import org.eclipse.debug.core.IStatusHandler;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.MessageDialogWithToggle;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.osgi.util.NLS;
import org.eclipse.swt.widgets.Shell;
import com.mountainminds.eclemma.internal.ui.EclEmmaUIPlugin;
import com.mountainminds.eclemma.internal.ui.UIMessages;
import com.mountainminds.eclemma.internal.ui.UIPreferences;
/**
* Status handler that issues a warning for in place instrumentation.
*
* @author Marc R. Hoffmann
* @version $Revision$
*/
public class InplaceInstrumentationWarning implements IStatusHandler {
public Object handleStatus(IStatus status, Object source)
throws CoreException {
ILaunchConfiguration config = (ILaunchConfiguration) source;
Shell parent = EclEmmaUIPlugin.getInstance().getShell();
String title = UIMessages.InstrumentationWarning_title;
String message = NLS.bind(UIMessages.InstrumentationWarning_message, config
.getName());
IPreferenceStore store = EclEmmaUIPlugin.getInstance().getPreferenceStore();
if (MessageDialogWithToggle.ALWAYS.equals(store
.getString(UIPreferences.PREF_ALLOW_INPLACE_INSTRUMENTATION))) {
return Boolean.TRUE;
}
MessageDialogWithToggle dialog = new MessageDialogWithToggle(parent, title,
null, message, MessageDialog.WARNING, new String[] {
IDialogConstants.OK_LABEL, IDialogConstants.CANCEL_LABEL }, 0,
null, false);
dialog.setPrefKey(UIPreferences.PREF_ALLOW_INPLACE_INSTRUMENTATION);
dialog.setPrefStore(store);
dialog.open();
- return new Boolean(dialog.getReturnCode() == IDialogConstants.OK_ID);
+ return Boolean.valueOf(dialog.getReturnCode() == IDialogConstants.OK_ID);
}
}
| true | true | public Object handleStatus(IStatus status, Object source)
throws CoreException {
ILaunchConfiguration config = (ILaunchConfiguration) source;
Shell parent = EclEmmaUIPlugin.getInstance().getShell();
String title = UIMessages.InstrumentationWarning_title;
String message = NLS.bind(UIMessages.InstrumentationWarning_message, config
.getName());
IPreferenceStore store = EclEmmaUIPlugin.getInstance().getPreferenceStore();
if (MessageDialogWithToggle.ALWAYS.equals(store
.getString(UIPreferences.PREF_ALLOW_INPLACE_INSTRUMENTATION))) {
return Boolean.TRUE;
}
MessageDialogWithToggle dialog = new MessageDialogWithToggle(parent, title,
null, message, MessageDialog.WARNING, new String[] {
IDialogConstants.OK_LABEL, IDialogConstants.CANCEL_LABEL }, 0,
null, false);
dialog.setPrefKey(UIPreferences.PREF_ALLOW_INPLACE_INSTRUMENTATION);
dialog.setPrefStore(store);
dialog.open();
return new Boolean(dialog.getReturnCode() == IDialogConstants.OK_ID);
}
| public Object handleStatus(IStatus status, Object source)
throws CoreException {
ILaunchConfiguration config = (ILaunchConfiguration) source;
Shell parent = EclEmmaUIPlugin.getInstance().getShell();
String title = UIMessages.InstrumentationWarning_title;
String message = NLS.bind(UIMessages.InstrumentationWarning_message, config
.getName());
IPreferenceStore store = EclEmmaUIPlugin.getInstance().getPreferenceStore();
if (MessageDialogWithToggle.ALWAYS.equals(store
.getString(UIPreferences.PREF_ALLOW_INPLACE_INSTRUMENTATION))) {
return Boolean.TRUE;
}
MessageDialogWithToggle dialog = new MessageDialogWithToggle(parent, title,
null, message, MessageDialog.WARNING, new String[] {
IDialogConstants.OK_LABEL, IDialogConstants.CANCEL_LABEL }, 0,
null, false);
dialog.setPrefKey(UIPreferences.PREF_ALLOW_INPLACE_INSTRUMENTATION);
dialog.setPrefStore(store);
dialog.open();
return Boolean.valueOf(dialog.getReturnCode() == IDialogConstants.OK_ID);
}
|
diff --git a/src/node/src/main/java/vdi/node/rest/InitializeContext.java b/src/node/src/main/java/vdi/node/rest/InitializeContext.java
index 07525aa..b5fb864 100644
--- a/src/node/src/main/java/vdi/node/rest/InitializeContext.java
+++ b/src/node/src/main/java/vdi/node/rest/InitializeContext.java
@@ -1,57 +1,57 @@
package vdi.node.rest;
import java.io.IOException;
import java.io.InputStream;
import java.util.Timer;
import java.util.logging.Logger;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import vdi.commons.common.Configuration;
import vdi.node.management.Registration;
import vdi.node.management.VirtualMachine;
/**
* Initialization.
*/
public class InitializeContext implements ServletContextListener {
private static final Logger LOGGER = Logger.getLogger(InitializeContext.class.getName());
@Override
public void contextInitialized(ServletContextEvent contextEvent) {
// Load configuration
InputStream is = contextEvent.getServletContext().getResourceAsStream("/WEB-INF/configuration.properties");
if (is != null) {
Configuration.loadProperties(is);
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
} else {
throw new Error("Missing configuration file '/WEB-INF/configuration.properties'");
}
- // start registration in 10s
+ // Start registration after delay
int seconds = Integer.parseInt(Configuration.getProperty("node.registration_delay"));
LOGGER.info("starting registration to '" + Configuration.getProperty("managementserver.uri") + "' in "
+ seconds + " seconds.");
Timer registration = new Timer();
registration.schedule(new Registration(), seconds * 1000);
}
@Override
public void contextDestroyed(ServletContextEvent contextEvent) {
// Clean up VirtualBox
try {
VirtualMachine.cleanup();
} catch (ExceptionInInitializerError e) {
}
// unregister this NodeController at ManagementServer
Registration.unregister();
}
}
| true | true | public void contextInitialized(ServletContextEvent contextEvent) {
// Load configuration
InputStream is = contextEvent.getServletContext().getResourceAsStream("/WEB-INF/configuration.properties");
if (is != null) {
Configuration.loadProperties(is);
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
} else {
throw new Error("Missing configuration file '/WEB-INF/configuration.properties'");
}
// start registration in 10s
int seconds = Integer.parseInt(Configuration.getProperty("node.registration_delay"));
LOGGER.info("starting registration to '" + Configuration.getProperty("managementserver.uri") + "' in "
+ seconds + " seconds.");
Timer registration = new Timer();
registration.schedule(new Registration(), seconds * 1000);
}
| public void contextInitialized(ServletContextEvent contextEvent) {
// Load configuration
InputStream is = contextEvent.getServletContext().getResourceAsStream("/WEB-INF/configuration.properties");
if (is != null) {
Configuration.loadProperties(is);
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
} else {
throw new Error("Missing configuration file '/WEB-INF/configuration.properties'");
}
// Start registration after delay
int seconds = Integer.parseInt(Configuration.getProperty("node.registration_delay"));
LOGGER.info("starting registration to '" + Configuration.getProperty("managementserver.uri") + "' in "
+ seconds + " seconds.");
Timer registration = new Timer();
registration.schedule(new Registration(), seconds * 1000);
}
|
diff --git a/src/main/java/com/p000ison/dev/copybooks/commands/DownloadCommand.java b/src/main/java/com/p000ison/dev/copybooks/commands/DownloadCommand.java
index 43f5dec..81f6d28 100644
--- a/src/main/java/com/p000ison/dev/copybooks/commands/DownloadCommand.java
+++ b/src/main/java/com/p000ison/dev/copybooks/commands/DownloadCommand.java
@@ -1,62 +1,62 @@
package com.p000ison.dev.copybooks.commands;
import com.p000ison.dev.copybooks.CopyBooks;
import com.p000ison.dev.copybooks.api.InvalidBookException;
import com.p000ison.dev.copybooks.api.WrittenBook;
import com.p000ison.dev.copybooks.objects.GenericCommand;
import com.p000ison.dev.copybooks.util.Helper;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.io.IOException;
/**
* Represents a AcceptCommand
*/
public class DownloadCommand extends GenericCommand {
public DownloadCommand(CopyBooks plugin, String name)
{
super(plugin, name);
setArgumentRange(2, 3);
setIdentifiers("download");
setUsages("/cb download <url> <title> [author]- Downloads a url from this page.");
}
@Override
public void execute(CommandSender sender, String label, String[] args)
{
if (sender instanceof Player) {
Player player = (Player) sender;
String author = player.getName();
if (args.length == 3) {
author = args[2];
}
WrittenBook book;
try {
- book = Helper.createBookFromURL(author, Helper.formatURL(args[0]), args[1]);
+ book = Helper.createBookFromURL(Helper.formatURL(args[0]), args[1], author);
} catch (IOException e) {
player.sendMessage("Invalid URL! [" + e.getMessage() + "]");
return;
} catch (InvalidBookException e) {
player.sendMessage("Failed to create book!");
return;
}
try {
player.getInventory().addItem(book.toItemStack(1));
} catch (InvalidBookException e) {
player.sendMessage("Failed to create book!");
return;
}
player.sendMessage("Book downloaded!");
} else {
}
}
}
| true | true | public void execute(CommandSender sender, String label, String[] args)
{
if (sender instanceof Player) {
Player player = (Player) sender;
String author = player.getName();
if (args.length == 3) {
author = args[2];
}
WrittenBook book;
try {
book = Helper.createBookFromURL(author, Helper.formatURL(args[0]), args[1]);
} catch (IOException e) {
player.sendMessage("Invalid URL! [" + e.getMessage() + "]");
return;
} catch (InvalidBookException e) {
player.sendMessage("Failed to create book!");
return;
}
try {
player.getInventory().addItem(book.toItemStack(1));
} catch (InvalidBookException e) {
player.sendMessage("Failed to create book!");
return;
}
player.sendMessage("Book downloaded!");
} else {
}
}
| public void execute(CommandSender sender, String label, String[] args)
{
if (sender instanceof Player) {
Player player = (Player) sender;
String author = player.getName();
if (args.length == 3) {
author = args[2];
}
WrittenBook book;
try {
book = Helper.createBookFromURL(Helper.formatURL(args[0]), args[1], author);
} catch (IOException e) {
player.sendMessage("Invalid URL! [" + e.getMessage() + "]");
return;
} catch (InvalidBookException e) {
player.sendMessage("Failed to create book!");
return;
}
try {
player.getInventory().addItem(book.toItemStack(1));
} catch (InvalidBookException e) {
player.sendMessage("Failed to create book!");
return;
}
player.sendMessage("Book downloaded!");
} else {
}
}
|
diff --git a/src/com/cyanogenmod/filemanager/ui/dialogs/InitialDirectoryDialog.java b/src/com/cyanogenmod/filemanager/ui/dialogs/InitialDirectoryDialog.java
index 9e5e0e2..2761531 100644
--- a/src/com/cyanogenmod/filemanager/ui/dialogs/InitialDirectoryDialog.java
+++ b/src/com/cyanogenmod/filemanager/ui/dialogs/InitialDirectoryDialog.java
@@ -1,185 +1,185 @@
/*
* Copyright (C) 2012 The CyanogenMod 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.cyanogenmod.filemanager.ui.dialogs;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.Toast;
import com.cyanogenmod.filemanager.R;
import com.cyanogenmod.filemanager.preferences.FileManagerSettings;
import com.cyanogenmod.filemanager.preferences.Preferences;
import com.cyanogenmod.filemanager.ui.widgets.DirectoryInlineAutocompleteTextView;
import com.cyanogenmod.filemanager.util.DialogHelper;
import java.io.File;
/**
* A class that wraps a dialog for showing list of consoles for choosing one.
* This class lets the user to set the default console.
*/
public class InitialDirectoryDialog implements DialogInterface.OnClickListener {
/**
* An interface to communicate events for value changing.
*/
public interface OnValueChangedListener {
/**
* Method invoked when the value of the initial directory was changed.
*
* @param newInitialDir The new initial directory
*/
void onValueChanged(String newInitialDir);
}
private static final String TAG = "InitialDirectoryDialog"; //$NON-NLS-1$
private final Context mContext;
/**
* @hide
*/
final AlertDialog mDialog;
private final DirectoryInlineAutocompleteTextView mAutocomplete;
private OnValueChangedListener mOnValueChangedListener;
/**
* Constructor of <code>InitialDirectoryDialog</code>.
*
* @param context The current context
*/
public InitialDirectoryDialog(Context context) {
super();
//Save the context
this.mContext = context;
//Extract current value
String value = Preferences.getSharedPreferences().getString(
FileManagerSettings.SETTINGS_INITIAL_DIR.getId(),
(String)FileManagerSettings.SETTINGS_INITIAL_DIR.getDefaultValue());
//Create the layout
LayoutInflater li =
(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
LinearLayout layout = (LinearLayout)li.inflate(R.layout.initial_directory, null);
final View msgView = layout.findViewById(R.id.initial_directory_info_msg);
this.mAutocomplete =
(DirectoryInlineAutocompleteTextView)layout.findViewById(
R.id.initial_directory_edittext);
this.mAutocomplete.setOnValidationListener(
new DirectoryInlineAutocompleteTextView.OnValidationListener() {
@Override
public void onVoidValue() {
msgView.setVisibility(View.GONE);
//The first invocation is valid. Can be ignore safely
if (InitialDirectoryDialog.this.mDialog != null) {
InitialDirectoryDialog.this.mDialog.getButton(
DialogInterface.BUTTON_POSITIVE).setEnabled(false);
}
}
@Override
public void onValidValue() {
msgView.setVisibility(View.GONE);
//The first invocation is valid. Can be ignore safely
if (InitialDirectoryDialog.this.mDialog != null) {
InitialDirectoryDialog.this.mDialog.getButton(
DialogInterface.BUTTON_POSITIVE).setEnabled(true);
}
}
@Override
public void onInvalidValue() {
msgView.setVisibility(View.VISIBLE);
//The first invocation is valid. Can be ignore safely
if (InitialDirectoryDialog.this.mDialog != null) {
InitialDirectoryDialog.this.mDialog.getButton(
DialogInterface.BUTTON_POSITIVE).setEnabled(false);
}
}
});
this.mAutocomplete.setText(value);
//Create the dialog
this.mDialog = DialogHelper.createDialog(
context,
- R.drawable.ic_holo_light_home,
+ 0,
R.string.initial_directory_dialog_title,
layout);
this.mDialog.setButton(
DialogInterface.BUTTON_POSITIVE, context.getString(android.R.string.ok), this);
this.mDialog.setButton(
DialogInterface.BUTTON_NEGATIVE, context.getString(android.R.string.cancel), this);
}
/**
* Method that set the listener for retrieve value changed events.
*
* @param onValueChangedListener The listener for retrieve value changed events
*/
public void setOnValueChangedListener(OnValueChangedListener onValueChangedListener) {
this.mOnValueChangedListener = onValueChangedListener;
}
/**
* Method that shows the dialog.
*/
public void show() {
this.mDialog.show();
}
/**
* {@inheritDoc}
*/
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case DialogInterface.BUTTON_POSITIVE:
done();
break;
default:
break;
}
}
/**
* Method invoked when the user press ok, or Enter key
*/
private void done() {
//Check that the directory is a valid directory
String newInitialDir = this.mAutocomplete.getText().toString();
try {
if (!newInitialDir.endsWith(File.separator)) {
newInitialDir += File.separator;
}
Preferences.savePreference(
FileManagerSettings.SETTINGS_INITIAL_DIR, newInitialDir, true);
if (this.mOnValueChangedListener != null) {
this.mOnValueChangedListener.onValueChanged(newInitialDir);
}
} catch (Throwable ex) {
Log.e(TAG, "The save initial directory setting operation fails", ex); //$NON-NLS-1$
DialogHelper.showToast(
this.mContext,
R.string.initial_directory_error_msg,
Toast.LENGTH_LONG);
}
}
}
| true | true | public InitialDirectoryDialog(Context context) {
super();
//Save the context
this.mContext = context;
//Extract current value
String value = Preferences.getSharedPreferences().getString(
FileManagerSettings.SETTINGS_INITIAL_DIR.getId(),
(String)FileManagerSettings.SETTINGS_INITIAL_DIR.getDefaultValue());
//Create the layout
LayoutInflater li =
(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
LinearLayout layout = (LinearLayout)li.inflate(R.layout.initial_directory, null);
final View msgView = layout.findViewById(R.id.initial_directory_info_msg);
this.mAutocomplete =
(DirectoryInlineAutocompleteTextView)layout.findViewById(
R.id.initial_directory_edittext);
this.mAutocomplete.setOnValidationListener(
new DirectoryInlineAutocompleteTextView.OnValidationListener() {
@Override
public void onVoidValue() {
msgView.setVisibility(View.GONE);
//The first invocation is valid. Can be ignore safely
if (InitialDirectoryDialog.this.mDialog != null) {
InitialDirectoryDialog.this.mDialog.getButton(
DialogInterface.BUTTON_POSITIVE).setEnabled(false);
}
}
@Override
public void onValidValue() {
msgView.setVisibility(View.GONE);
//The first invocation is valid. Can be ignore safely
if (InitialDirectoryDialog.this.mDialog != null) {
InitialDirectoryDialog.this.mDialog.getButton(
DialogInterface.BUTTON_POSITIVE).setEnabled(true);
}
}
@Override
public void onInvalidValue() {
msgView.setVisibility(View.VISIBLE);
//The first invocation is valid. Can be ignore safely
if (InitialDirectoryDialog.this.mDialog != null) {
InitialDirectoryDialog.this.mDialog.getButton(
DialogInterface.BUTTON_POSITIVE).setEnabled(false);
}
}
});
this.mAutocomplete.setText(value);
//Create the dialog
this.mDialog = DialogHelper.createDialog(
context,
R.drawable.ic_holo_light_home,
R.string.initial_directory_dialog_title,
layout);
this.mDialog.setButton(
DialogInterface.BUTTON_POSITIVE, context.getString(android.R.string.ok), this);
this.mDialog.setButton(
DialogInterface.BUTTON_NEGATIVE, context.getString(android.R.string.cancel), this);
}
| public InitialDirectoryDialog(Context context) {
super();
//Save the context
this.mContext = context;
//Extract current value
String value = Preferences.getSharedPreferences().getString(
FileManagerSettings.SETTINGS_INITIAL_DIR.getId(),
(String)FileManagerSettings.SETTINGS_INITIAL_DIR.getDefaultValue());
//Create the layout
LayoutInflater li =
(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
LinearLayout layout = (LinearLayout)li.inflate(R.layout.initial_directory, null);
final View msgView = layout.findViewById(R.id.initial_directory_info_msg);
this.mAutocomplete =
(DirectoryInlineAutocompleteTextView)layout.findViewById(
R.id.initial_directory_edittext);
this.mAutocomplete.setOnValidationListener(
new DirectoryInlineAutocompleteTextView.OnValidationListener() {
@Override
public void onVoidValue() {
msgView.setVisibility(View.GONE);
//The first invocation is valid. Can be ignore safely
if (InitialDirectoryDialog.this.mDialog != null) {
InitialDirectoryDialog.this.mDialog.getButton(
DialogInterface.BUTTON_POSITIVE).setEnabled(false);
}
}
@Override
public void onValidValue() {
msgView.setVisibility(View.GONE);
//The first invocation is valid. Can be ignore safely
if (InitialDirectoryDialog.this.mDialog != null) {
InitialDirectoryDialog.this.mDialog.getButton(
DialogInterface.BUTTON_POSITIVE).setEnabled(true);
}
}
@Override
public void onInvalidValue() {
msgView.setVisibility(View.VISIBLE);
//The first invocation is valid. Can be ignore safely
if (InitialDirectoryDialog.this.mDialog != null) {
InitialDirectoryDialog.this.mDialog.getButton(
DialogInterface.BUTTON_POSITIVE).setEnabled(false);
}
}
});
this.mAutocomplete.setText(value);
//Create the dialog
this.mDialog = DialogHelper.createDialog(
context,
0,
R.string.initial_directory_dialog_title,
layout);
this.mDialog.setButton(
DialogInterface.BUTTON_POSITIVE, context.getString(android.R.string.ok), this);
this.mDialog.setButton(
DialogInterface.BUTTON_NEGATIVE, context.getString(android.R.string.cancel), this);
}
|
diff --git a/Edge3.java b/Edge3.java
index 60bc2e67..c0d116f9 100644
--- a/Edge3.java
+++ b/Edge3.java
@@ -1,253 +1,253 @@
package cs.threephase;
import java.util.*;
import java.io.*;
import static cs.threephase.Util.*;
import static cs.threephase.Moves.*;
final class Edge3 implements Runnable {
int[] edge = new int[12];
int[] temp;
static int[] prun;
final static int[][] edgex = { { 3, 0, 1, 2, 4, 5, 6, 7, 8, 9,10,11},
{ 2, 3, 0, 1, 4, 5, 6, 7, 8, 9,10,11},
{ 1, 2, 3, 0, 4, 5, 6, 7, 8, 9,10,11},
{ 0, 1, 2, 7, 4, 5, 6, 3, 8, 9,11,10},
{ 8, 1, 2, 3, 4, 5,11, 7, 6, 9,10, 0},
{ 6, 1, 2, 3, 4, 5, 0, 7,11, 9,10, 8},
{11, 1, 2, 3, 4, 5, 8, 7, 0, 9,10, 6},
{ 0, 1, 2, 3, 7, 4, 5, 6, 8, 9,10,11},
{ 0, 1, 2, 3, 6, 7, 4, 5, 8, 9,10,11},
{ 0, 1, 2, 3, 5, 6, 7, 4, 8, 9,10,11},
{ 0, 5, 2, 3, 4, 1, 6, 7, 9, 8,10,11},
{ 0, 1,10, 3, 9, 5, 6, 7, 8, 2, 4,11},
{ 0, 1, 4, 3, 2, 5, 6, 7, 8,10, 9,11},
{ 0, 1, 9, 3,10, 5, 6, 7, 8, 4, 2,11},
{ 2, 3, 0, 1, 4, 5, 6, 7, 8,11,10, 9},
{ 0, 1, 6, 7, 4, 5, 2, 3, 8, 9,11,10},
{ 6, 1, 2, 5, 4, 3, 0, 7,11, 9,10, 8},
{ 0, 1, 2, 3, 6, 7, 4, 5,10, 9, 8,11},
{ 4, 5, 2, 3, 0, 1, 6, 7, 9, 8,10,11},
{ 0, 7, 4, 3, 2, 5, 6, 1, 8,10, 9,11}};
final static int[][] edgeox = { { 1, 2, 3, 0, 4, 5, 6, 7, 8, 9,10,11},
{ 2, 3, 0, 1, 4, 5, 6, 7, 8, 9,10,11},
{ 3, 0, 1, 2, 4, 5, 6, 7, 8, 9,10,11},
{ 0, 1, 2, 7, 4, 5, 6, 3, 8, 9,11,10},
{11, 1, 2, 3, 4, 5, 8, 7, 0, 9,10, 6},
{ 6, 1, 2, 3, 4, 5, 0, 7,11, 9,10, 8},
{ 8, 1, 2, 3, 4, 5,11, 7, 6, 9,10, 0},
{ 0, 1, 2, 3, 5, 6, 7, 4, 8, 9,10,11},
{ 0, 1, 2, 3, 6, 7, 4, 5, 8, 9,10,11},
{ 0, 1, 2, 3, 7, 4, 5, 6, 8, 9,10,11},
{ 0, 5, 2, 3, 4, 1, 6, 7, 9, 8,10,11},
{ 0, 1, 9, 3,10, 5, 6, 7, 8, 4, 2,11},
{ 0, 1, 4, 3, 2, 5, 6, 7, 8,10, 9,11},
{ 0, 1,10, 3, 9, 5, 6, 7, 8, 2, 4,11},
{ 2, 3, 0, 1, 4, 5, 6, 7,10, 9, 8,11},
{ 4, 1, 2, 7, 0, 5, 6, 3, 8, 9,11,10},
{ 6, 7, 2, 3, 4, 5, 0, 1,11, 9,10, 8},
{ 0, 1, 2, 3, 6, 7, 4, 5, 8,11,10, 9},
{ 0, 5, 6, 3, 4, 1, 2, 7, 9, 8,10,11},
{ 0, 1, 4, 5, 2, 3, 6, 7, 8,10, 9,11}};
private static int[] fact = {19958400, 1814400, 181440, 20160, 2520, 360, 60, 12, 3, 1};
static int[] factX = {1, 1, 2/2, 6/2, 24/2, 120/2, 720/2, 5040/2, 40320/2, 362880/2, 3628800/2, 39916800/2, 479001600/2};
int idx = 0;
final static int MOD = 12;
static int doneMod = 1;
static byte[] modedTable = new byte[12*11*10*9*8*7*6*5*4*3/MOD/2];
final static int SPLIT = 4;
static int done = 0;
static int depth = 0;
static int depm3;// = depth % 3;
static int depp3;// = 3 ^ ((depth+1) % 3);
static boolean inv;// = depth > 10;
static int check;// = inv ? 3 : depm3;
static int found;// = inv ? depm3 : 3;
public void run() {
int offset = 239500800 / SPLIT * idx;
int[] mvarr = new int[17];
for (int i=0; i<239500800 / SPLIT;) {
int cx=prun[(i + offset)>>4];
if (cx == -1 && !inv) {
i+=16;
continue;
}
for (int j=i+16; i<j; i++, cx>>=2) {
if ((cx & 3) == check) {
this.set(i + offset);
for (int m=0; m<17; m++) {
mvarr[m] = getmv(this.edge, m);
}
synchronized (prun) {
for (int m=0; m<17; m++) {
getAndSet(mvarr[m], depp3);
}
}
}
}
}
}
static void getAndSet(int index, int value) {
int shift = (index & 0x0f) << 1, idx = index >> 4;
if (((prun[idx] >> shift) & 3) == 3) {
prun[idx] ^= value << shift;
++done;
if (getPruning(modedTable, index/MOD) == 0xb) {
setPruning(modedTable, index/MOD, depth+1);
++doneMod;
}
if ((done & 0x3ffff) == 0) {
System.out.print(String.format("%5.2f%%\t%d\r", done / 897632.96, doneMod));
}
}
}
static void createPrun() {
System.out.println("Create Phase3 Edge Pruning Table...");
prun = new int[12*11*10*9*8*7*6*5*4*3/16];
- Arrays.fill(prun, (int)-1);
+ Arrays.fill(prun, -1);
Arrays.fill(modedTable, (byte)0xbb);
setPruning(modedTable, 0, 0);
prun[0] = 0xfffffffc;
for (depth=0; depth<10; depth++) {
depm3 = depth % 3;
depp3 = 3 ^ ((depth+1) % 3);
inv = depth > 10;
check = inv ? 3 : depm3;
found = inv ? depm3 : 3;
Edge3[] ts = new Edge3[SPLIT];
for (int i=0; i<SPLIT; i++) {
ts[i] = new Edge3();
ts[i].idx = i;
}
Thread[] r = new Thread[SPLIT];
for (int i=0; i<SPLIT; i++) {
r[i] = new Thread(ts[i]);
r[i].start();
}
for (int i=0; i<SPLIT; i++) {
try {
r[i].join();
} catch (Exception ea) {
ea.printStackTrace();
}
}
System.out.println(String.format("%2d%10d%10d", depth+1, done, doneMod));
}
prun = null;
System.gc();
}
static void setPruning(byte[] table, int index, int value) {
table[index >> 1] ^= (0x0b ^ value) << ((index & 1) << 2);
}
static int getPruning(byte[] table, int index) {
return (table[index >> 1] >> ((index & 1) << 2)) & 0x0f;
}
static int getprunmod(int edge) {
return getPruning(modedTable, edge/MOD);
}
int set(EdgeCube c) {
if (temp == null) {
temp = new int[12];
}
for (int i=0; i<12; i++) {
temp[i] = i;
edge[i] = c.ep[i+12]%12;
}
int parity = 0;
for (int i=0; i<12; i++) {
while (edge[i] != i) {
int t = edge[i];
edge[i] = edge[t];
edge[t] = t;
int s = temp[i];
temp[i] = temp[t];
temp[t] = s;
parity ^= 1;
}
}
for (int i=0; i<12; i++) {
edge[i] = temp[c.ep[i]%12];
}
return parity;
}
static int getmv(int[] ep, int mv) {
int[] movo = edgeox[mv];
int[] mov = edgex[mv];
int idx = 0;
long val = 0xba9876543210L;
for (int i=0; i<10; i++) {
int v = movo[ep[mov[i]]] << 2;
idx *= 12-i;
idx += (val >> v) & 0xf;
val -= 0x111111111110L << v;
}
return idx;
}
static int[] movX = { 6,11, 0, 8, 2,10, 4, 9, 7, 3, 1, 5};
static int[] movoX ={ 2,10, 4, 9, 6,11, 0, 8, 3, 7, 5, 1};
int getmv_x() {
int idx = 0;
long val = 0xba9876543210L;
for (int i=0; i<10; i++) {
int v = movoX[edge[movX[i]]] << 2;
idx *= 12-i;
idx += (val >> v) & 0xf;
val -= 0x111111111110L << v;
}
return idx;
}
int get() {
int idx = 0;
long val = 0xba9876543210L;
for (int i=0; i<10; i++) {
int v = edge[i] << 2;
idx *= 12-i;
idx += (val >> v) & 0xf;
val -= 0x111111111110L << v;
}
return idx;
}
void set(int idx) {
long val = 0xba9876543210L;
int parity = 0;
for (int i=0; i<11; i++) {
int p = factX[11-i];
int v = idx / p;
idx -= v*p;
parity ^= v;
v <<= 2;
edge[i] = (int) ((val >> v) & 0xf);
long m = (1L << v) - 1;
val = (val & m) + ((val >> 4) & ~m);
}
if ((parity & 1) == 0) {
edge[11] = (int)val;
} else {
edge[11] = edge[10];
edge[10] = (int)val;
}
}
}
| true | true | static void createPrun() {
System.out.println("Create Phase3 Edge Pruning Table...");
prun = new int[12*11*10*9*8*7*6*5*4*3/16];
Arrays.fill(prun, (int)-1);
Arrays.fill(modedTable, (byte)0xbb);
setPruning(modedTable, 0, 0);
prun[0] = 0xfffffffc;
for (depth=0; depth<10; depth++) {
depm3 = depth % 3;
depp3 = 3 ^ ((depth+1) % 3);
inv = depth > 10;
check = inv ? 3 : depm3;
found = inv ? depm3 : 3;
Edge3[] ts = new Edge3[SPLIT];
for (int i=0; i<SPLIT; i++) {
ts[i] = new Edge3();
ts[i].idx = i;
}
Thread[] r = new Thread[SPLIT];
for (int i=0; i<SPLIT; i++) {
r[i] = new Thread(ts[i]);
r[i].start();
}
for (int i=0; i<SPLIT; i++) {
try {
r[i].join();
} catch (Exception ea) {
ea.printStackTrace();
}
}
System.out.println(String.format("%2d%10d%10d", depth+1, done, doneMod));
}
prun = null;
System.gc();
}
| static void createPrun() {
System.out.println("Create Phase3 Edge Pruning Table...");
prun = new int[12*11*10*9*8*7*6*5*4*3/16];
Arrays.fill(prun, -1);
Arrays.fill(modedTable, (byte)0xbb);
setPruning(modedTable, 0, 0);
prun[0] = 0xfffffffc;
for (depth=0; depth<10; depth++) {
depm3 = depth % 3;
depp3 = 3 ^ ((depth+1) % 3);
inv = depth > 10;
check = inv ? 3 : depm3;
found = inv ? depm3 : 3;
Edge3[] ts = new Edge3[SPLIT];
for (int i=0; i<SPLIT; i++) {
ts[i] = new Edge3();
ts[i].idx = i;
}
Thread[] r = new Thread[SPLIT];
for (int i=0; i<SPLIT; i++) {
r[i] = new Thread(ts[i]);
r[i].start();
}
for (int i=0; i<SPLIT; i++) {
try {
r[i].join();
} catch (Exception ea) {
ea.printStackTrace();
}
}
System.out.println(String.format("%2d%10d%10d", depth+1, done, doneMod));
}
prun = null;
System.gc();
}
|
diff --git a/TestNetworkTable/src/NetworkTablesDesktopClient.java b/TestNetworkTable/src/NetworkTablesDesktopClient.java
index 4f7a4f9..1349a18 100644
--- a/TestNetworkTable/src/NetworkTablesDesktopClient.java
+++ b/TestNetworkTable/src/NetworkTablesDesktopClient.java
@@ -1,42 +1,42 @@
import edu.wpi.first.smartdashboard.robot.Robot;
import edu.wpi.first.wpilibj.networktables.NetworkTable;
import edu.wpi.first.wpilibj.networktables2.*;
public class NetworkTablesDesktopClient {
/**
* @param args
*/
public static void main(String[] args) {
new NetworkTablesDesktopClient();
NetworkTablesDesktopClient.run();
}
static void run() {
- NetworkTable.setTeam(2557); //sets our team number
- NetworkTable table = (NetworkTable) Robot.getTable();
+ NetworkTable.setIPAddress("10.25.57.2"); //sets our team number
+ NetworkTable table = NetworkTable.getTable("SmartDashboard");
while (true) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
table.putNumber("Q", 11); //puts the number "11" into a key called "Q"
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(table.getNumber("Q")); //Gets the value "Q" that we put in earlier
}
}
}
| true | true | static void run() {
NetworkTable.setTeam(2557); //sets our team number
NetworkTable table = (NetworkTable) Robot.getTable();
while (true) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
table.putNumber("Q", 11); //puts the number "11" into a key called "Q"
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(table.getNumber("Q")); //Gets the value "Q" that we put in earlier
}
}
| static void run() {
NetworkTable.setIPAddress("10.25.57.2"); //sets our team number
NetworkTable table = NetworkTable.getTable("SmartDashboard");
while (true) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
table.putNumber("Q", 11); //puts the number "11" into a key called "Q"
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(table.getNumber("Q")); //Gets the value "Q" that we put in earlier
}
}
|
diff --git a/src/graphview/LineShape.java b/src/graphview/LineShape.java
index eb188ee..9a86f8b 100644
--- a/src/graphview/LineShape.java
+++ b/src/graphview/LineShape.java
@@ -1,200 +1,200 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package graphview;
import geometry.Intersect;
import geometry.Rect;
import geometry.Vec2;
import graphevents.ShapeMouseEvent;
import java.awt.Color;
import java.awt.Graphics2D;
import java.util.ArrayList;
/**
*
* @author Kirill
*/
public class LineShape extends BaseShape {
protected BaseShape portNodeA=null;
protected BaseShape portNodeB=null;
protected ArrayList<BaseShape> points=new ArrayList<BaseShape>();
public LineShape(BaseShape portA, BaseShape portB)
{
portNodeA=portA;
portNodeB=portB;
bMoveable=false;
bUnbodied=true;
};
@Override
public void draw(Graphics2D g) {
g.setColor(color);
if(bSelected) g.setColor(Color.red);
Vec2 point=null;
Vec2 point1=null;
for(int i=0;i<getNumPointsWithPort()-1;i++)
{
point=getPointWithPort(i);
point1=getPointWithPort(i+1);
g.drawLine((int)point.x, (int)point.y, (int)point1.x, (int)point1.y);
if(i==0)
{
g.fillOval((int)point.x-3, (int)point.y-3, 6, 6);
}
- else if(i==getNumPointsWithPort()-2)
+ if(i==getNumPointsWithPort()-2)
{
g.fillOval((int)point1.x-3, (int)point1.y-3, 6, 6);
};
};
super.draw(g);
return;
}
public void insertPoint(BaseShape shape, int index)
{
for(int i=0;i<points.size();i++)
{
if(points.get(i)==shape) return;
};
points.add(index, shape);
addChild(shape);
};
public Vec2 getPoint(int index){
return points.get(index).getGlobalPosition();
}
public void setPoint(Vec2 pt, int index){
points.get(index).setGlobalPosition(pt);
update();
};
public int getNumPoints()
{
return points.size();
};
public Vec2 getPointWithPort(int index){
int offset=0;
if(portNodeA!=null) offset=1;
if(index==0)
{
if(portNodeA!=null) return getPortPointA();
};
if(index==(getNumPointsWithPort()-1))
{
if(portNodeB!=null) return getPortPointB();
};
return points.get(index-offset).getGlobalPlacement().getCenter();
}
public int getNumPointsWithPort()
{
int count=points.size();
if(portNodeA!=null) count++;
if(portNodeB!=null) count++;
return count;
};
public void setPortA(BaseShape shape){
portNodeA=shape;
update();
}
public void setPortB(BaseShape shape){
portNodeB=shape;
update();
}
public Vec2 getPortPointA(){
Vec2 point;
Vec2 portA;
if(getNumPoints()==0)
{
if(portNodeB!=null)
point=portNodeB.getGlobalPlacement().getCenter();
else
return new Vec2();
}
else
point=points.get(0).getGlobalPlacement().getCenter();
if(portNodeA!=null)
portA=portNodeA.getPortPoint(point);
else
portA=point;
return portA;
}
public Vec2 getPortPointB(){
Vec2 point;
Vec2 portB;
if(getNumPoints()==0)
{
if(portNodeA!=null)
point=portNodeA.getGlobalPlacement().getCenter();
else
return new Vec2();
}
else
point=points.get(points.size()-1).getGlobalPlacement().getCenter();
if(portNodeB!=null)
portB=portNodeB.getPortPoint(point);
else
portB=point;
return portB;
}
@Override
public boolean onMouseClick(ShapeMouseEvent evt){
if(evt.getButton()==1 &&
evt.getIntersectedChild()==-1 &&
isIntersects(evt.getPosition()))
{
boolean bSel=bSelected;
clearSelection();
setSelected(!bSel);
return true;
}
return false;
}
@Override
public boolean isIntersects(Vec2 pt) {
if(testChildIntersect(pt)!=-1) return true;
Vec2 point=null;
Vec2 point1=null;
for(int i=0;i<getNumPointsWithPort()-1;i++)
{
point=getPointWithPort(i);
point1=getPointWithPort(i+1);
if(Intersect.lineseg_point(point, point1, 5,pt)==Intersect.INCLUSION) return true;
};
return false;
}
@Override
public boolean isIntersects(Rect r) {
return false;
}
@Override
public Vec2 getPortPoint(Vec2 from) {
return null;
}
}
| true | true | public void draw(Graphics2D g) {
g.setColor(color);
if(bSelected) g.setColor(Color.red);
Vec2 point=null;
Vec2 point1=null;
for(int i=0;i<getNumPointsWithPort()-1;i++)
{
point=getPointWithPort(i);
point1=getPointWithPort(i+1);
g.drawLine((int)point.x, (int)point.y, (int)point1.x, (int)point1.y);
if(i==0)
{
g.fillOval((int)point.x-3, (int)point.y-3, 6, 6);
}
else if(i==getNumPointsWithPort()-2)
{
g.fillOval((int)point1.x-3, (int)point1.y-3, 6, 6);
};
};
super.draw(g);
return;
}
| public void draw(Graphics2D g) {
g.setColor(color);
if(bSelected) g.setColor(Color.red);
Vec2 point=null;
Vec2 point1=null;
for(int i=0;i<getNumPointsWithPort()-1;i++)
{
point=getPointWithPort(i);
point1=getPointWithPort(i+1);
g.drawLine((int)point.x, (int)point.y, (int)point1.x, (int)point1.y);
if(i==0)
{
g.fillOval((int)point.x-3, (int)point.y-3, 6, 6);
}
if(i==getNumPointsWithPort()-2)
{
g.fillOval((int)point1.x-3, (int)point1.y-3, 6, 6);
};
};
super.draw(g);
return;
}
|
diff --git a/src/main/java/com/laurinka/skga/server/data/SearchProducer.java b/src/main/java/com/laurinka/skga/server/data/SearchProducer.java
index 8e5b652..e21a9f7 100644
--- a/src/main/java/com/laurinka/skga/server/data/SearchProducer.java
+++ b/src/main/java/com/laurinka/skga/server/data/SearchProducer.java
@@ -1,152 +1,150 @@
package com.laurinka.skga.server.data;
import com.laurinka.skga.server.model.Result;
import com.laurinka.skga.server.model.Snapshot;
import com.laurinka.skga.server.rest.CgfMemberResourceRESTService;
import com.laurinka.skga.server.rest.SearchCgfResourceRESTService;
import com.laurinka.skga.server.rest.SearchMemberResourceRESTService;
import com.laurinka.skga.server.rest.SkgaMemberResourceRESTService;
import com.laurinka.skga.server.rest.model.Hcp;
import com.laurinka.skga.server.rest.model.NameNumberXml;
import com.laurinka.skga.server.scratch.CgfGolferNumber;
import com.laurinka.skga.server.scratch.SkgaGolferNumber;
import com.laurinka.skga.server.services.WebsiteService;
import javax.annotation.PostConstruct;
import javax.enterprise.context.RequestScoped;
import javax.enterprise.inject.Produces;
import javax.inject.Inject;
import javax.inject.Named;
import javax.persistence.EntityManager;
import javax.ws.rs.WebApplicationException;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.logging.Logger;
import java.util.regex.Pattern;
@RequestScoped
@Named("search")
public class SearchProducer {
static Pattern number = Pattern.compile("\\d{1,7}");
@Inject
private EntityManager em;
@Inject
private WebsiteService service;
@Inject
Logger log;
@Inject
SkgaMemberResourceRESTService skga;
@Inject
CgfMemberResourceRESTService cgf;
private List<Snapshot> results;
private String q;
@Inject
SearchCgfResourceRESTService cgfSearch;
@Inject
SearchMemberResourceRESTService skSearch;
@Produces
@Named
public List<Snapshot> getResults() {
return results;
}
@PostConstruct
public void retrieveLastSnapshotsOrderedByName() {
if (null == q || q.isEmpty()) {
log.info("search string is empty!");
results = Collections.emptyList();
return;
}
if (number.matcher(q).matches()) {
log.info("User entered number on page:" + q);
//search by number
Result detailSk = service.findDetail(new SkgaGolferNumber(q));
Result detailCz = service.findDetail(new CgfGolferNumber(q));
if (null == detailCz && null == detailSk) {
log.info("Nothing found.");
results = Collections.emptyList();
return;
}
results = new LinkedList<Snapshot>();
if (detailSk != null) {
log.info("Found sk:" + detailSk.toString());
Snapshot sk = new Snapshot();
sk.setResult(detailSk);
results.add(sk);
}
if (detailCz != null) {
log.info("Found cz: " + detailCz.toString());
Snapshot cz = new Snapshot();
cz.setResult(detailCz);
results.add(cz);
}
return;
} else {
results = new LinkedList<Snapshot>();
List<NameNumberXml> czs = cgfSearch.lookupMemberByName(q);
for (NameNumberXml n : czs) {
log.info("Query cgf: " + n.getNumber());
Hcp hcp = null;
try {
hcp = cgf.lookupMemberById(n.getNumber());
} catch (WebApplicationException e) {
log.warning(e.getLocalizedMessage());
continue;
}
Snapshot s = new Snapshot();
Result result = Result.newCgf();
result.setClub(hcp.getClub());
result.setHcp(hcp.getHandicap());
result.setName(hcp.getName());
result.setSkgaNr(hcp.getNumber());
s.setResult(result);
results.add(s);
}
List<NameNumberXml> sks = skSearch.lookupMemberByName(q);
for (NameNumberXml n : sks) {
log.info("Query skga: " + n.getNumber());
Hcp hcp = null;
try {
hcp = cgf.lookupMemberById(n.getNumber());
} catch (WebApplicationException e) {
log.warning(e.getLocalizedMessage());
continue;
}
Snapshot s = new Snapshot();
Result result = Result.newSkga();
result.setClub(hcp.getClub());
result.setHcp(hcp.getHandicap());
result.setName(hcp.getName());
result.setSkgaNr(hcp.getNumber());
s.setResult(result);
results.add(s);
}
- // search by name
- results = Collections.emptyList();
- }
+ }
}
public String getQ() {
return q;
}
public void setQ(String q) {
this.q = q;
}
public void setService(WebsiteService service) {
this.service = service;
}
}
| true | true | public void retrieveLastSnapshotsOrderedByName() {
if (null == q || q.isEmpty()) {
log.info("search string is empty!");
results = Collections.emptyList();
return;
}
if (number.matcher(q).matches()) {
log.info("User entered number on page:" + q);
//search by number
Result detailSk = service.findDetail(new SkgaGolferNumber(q));
Result detailCz = service.findDetail(new CgfGolferNumber(q));
if (null == detailCz && null == detailSk) {
log.info("Nothing found.");
results = Collections.emptyList();
return;
}
results = new LinkedList<Snapshot>();
if (detailSk != null) {
log.info("Found sk:" + detailSk.toString());
Snapshot sk = new Snapshot();
sk.setResult(detailSk);
results.add(sk);
}
if (detailCz != null) {
log.info("Found cz: " + detailCz.toString());
Snapshot cz = new Snapshot();
cz.setResult(detailCz);
results.add(cz);
}
return;
} else {
results = new LinkedList<Snapshot>();
List<NameNumberXml> czs = cgfSearch.lookupMemberByName(q);
for (NameNumberXml n : czs) {
log.info("Query cgf: " + n.getNumber());
Hcp hcp = null;
try {
hcp = cgf.lookupMemberById(n.getNumber());
} catch (WebApplicationException e) {
log.warning(e.getLocalizedMessage());
continue;
}
Snapshot s = new Snapshot();
Result result = Result.newCgf();
result.setClub(hcp.getClub());
result.setHcp(hcp.getHandicap());
result.setName(hcp.getName());
result.setSkgaNr(hcp.getNumber());
s.setResult(result);
results.add(s);
}
List<NameNumberXml> sks = skSearch.lookupMemberByName(q);
for (NameNumberXml n : sks) {
log.info("Query skga: " + n.getNumber());
Hcp hcp = null;
try {
hcp = cgf.lookupMemberById(n.getNumber());
} catch (WebApplicationException e) {
log.warning(e.getLocalizedMessage());
continue;
}
Snapshot s = new Snapshot();
Result result = Result.newSkga();
result.setClub(hcp.getClub());
result.setHcp(hcp.getHandicap());
result.setName(hcp.getName());
result.setSkgaNr(hcp.getNumber());
s.setResult(result);
results.add(s);
}
// search by name
results = Collections.emptyList();
}
}
| public void retrieveLastSnapshotsOrderedByName() {
if (null == q || q.isEmpty()) {
log.info("search string is empty!");
results = Collections.emptyList();
return;
}
if (number.matcher(q).matches()) {
log.info("User entered number on page:" + q);
//search by number
Result detailSk = service.findDetail(new SkgaGolferNumber(q));
Result detailCz = service.findDetail(new CgfGolferNumber(q));
if (null == detailCz && null == detailSk) {
log.info("Nothing found.");
results = Collections.emptyList();
return;
}
results = new LinkedList<Snapshot>();
if (detailSk != null) {
log.info("Found sk:" + detailSk.toString());
Snapshot sk = new Snapshot();
sk.setResult(detailSk);
results.add(sk);
}
if (detailCz != null) {
log.info("Found cz: " + detailCz.toString());
Snapshot cz = new Snapshot();
cz.setResult(detailCz);
results.add(cz);
}
return;
} else {
results = new LinkedList<Snapshot>();
List<NameNumberXml> czs = cgfSearch.lookupMemberByName(q);
for (NameNumberXml n : czs) {
log.info("Query cgf: " + n.getNumber());
Hcp hcp = null;
try {
hcp = cgf.lookupMemberById(n.getNumber());
} catch (WebApplicationException e) {
log.warning(e.getLocalizedMessage());
continue;
}
Snapshot s = new Snapshot();
Result result = Result.newCgf();
result.setClub(hcp.getClub());
result.setHcp(hcp.getHandicap());
result.setName(hcp.getName());
result.setSkgaNr(hcp.getNumber());
s.setResult(result);
results.add(s);
}
List<NameNumberXml> sks = skSearch.lookupMemberByName(q);
for (NameNumberXml n : sks) {
log.info("Query skga: " + n.getNumber());
Hcp hcp = null;
try {
hcp = cgf.lookupMemberById(n.getNumber());
} catch (WebApplicationException e) {
log.warning(e.getLocalizedMessage());
continue;
}
Snapshot s = new Snapshot();
Result result = Result.newSkga();
result.setClub(hcp.getClub());
result.setHcp(hcp.getHandicap());
result.setName(hcp.getName());
result.setSkgaNr(hcp.getNumber());
s.setResult(result);
results.add(s);
}
}
}
|
diff --git a/src/com/android/camera/PhotoModule.java b/src/com/android/camera/PhotoModule.java
index 0ab6bd596..53fb46058 100644
--- a/src/com/android/camera/PhotoModule.java
+++ b/src/com/android/camera/PhotoModule.java
@@ -1,2291 +1,2283 @@
/*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.camera;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentProviderClient;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences.Editor;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.SurfaceTexture;
import android.hardware.Camera.CameraInfo;
import android.hardware.Camera.Parameters;
import android.hardware.Camera.PictureCallback;
import android.hardware.Camera.Size;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.location.Location;
import android.media.CameraProfile;
import android.net.Uri;
import android.os.Bundle;
import android.os.ConditionVariable;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.MessageQueue;
import android.os.SystemClock;
import android.provider.MediaStore;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.OrientationEventListener;
import android.view.SurfaceHolder;
import android.view.View;
import android.view.WindowManager;
import com.android.camera.CameraManager.CameraProxy;
import com.android.camera.ui.CountDownView.OnCountDownFinishedListener;
import com.android.camera.ui.PopupManager;
import com.android.camera.ui.RotateTextToast;
import com.android.gallery3d.R;
import com.android.gallery3d.common.ApiHelper;
import com.android.gallery3d.exif.ExifInterface;
import com.android.gallery3d.exif.ExifTag;
import com.android.gallery3d.exif.Rational;
import com.android.gallery3d.filtershow.FilterShowActivity;
import com.android.gallery3d.filtershow.crop.CropExtras;
import com.android.gallery3d.util.UsageStatistics;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Formatter;
import java.util.List;
import java.util.TimeZone;
public class PhotoModule
implements CameraModule,
PhotoController,
FocusOverlayManager.Listener,
CameraPreference.OnPreferenceChangedListener,
ShutterButton.OnShutterButtonListener,
MediaSaveService.Listener,
OnCountDownFinishedListener,
SensorEventListener {
private static final String TAG = "CAM_PhotoModule";
private boolean mRestartPreview = false;
private boolean mAspectRatioChanged = false;
// We number the request code from 1000 to avoid collision with Gallery.
private static final int REQUEST_CROP = 1000;
private static final int SETUP_PREVIEW = 1;
private static final int FIRST_TIME_INIT = 2;
private static final int CLEAR_SCREEN_DELAY = 3;
private static final int SET_CAMERA_PARAMETERS_WHEN_IDLE = 4;
private static final int CHECK_DISPLAY_ROTATION = 5;
private static final int SHOW_TAP_TO_FOCUS_TOAST = 6;
private static final int SWITCH_CAMERA = 7;
private static final int SWITCH_CAMERA_START_ANIMATION = 8;
private static final int CAMERA_OPEN_DONE = 9;
private static final int START_PREVIEW_DONE = 10;
private static final int OPEN_CAMERA_FAIL = 11;
private static final int CAMERA_DISABLED = 12;
private static final int CAPTURE_ANIMATION_DONE = 13;
private static final int SET_PHOTO_UI_PARAMS = 15;
// The subset of parameters we need to update in setCameraParameters().
private static final int UPDATE_PARAM_INITIALIZE = 1;
private static final int UPDATE_PARAM_ZOOM = 2;
private static final int UPDATE_PARAM_PREFERENCE = 4;
private static final int UPDATE_PARAM_ALL = -1;
// This is the timeout to keep the camera in onPause for the first time
// after screen on if the activity is started from secure lock screen.
private static final int KEEP_CAMERA_TIMEOUT = 1000; // ms
// copied from Camera hierarchy
private CameraActivity mActivity;
private CameraProxy mCameraDevice;
private int mCameraId;
private Parameters mParameters;
private boolean mPaused;
private PhotoUI mUI;
// these are only used by Camera
// The activity is going to switch to the specified camera id. This is
// needed because texture copy is done in GL thread. -1 means camera is not
// switching.
protected int mPendingSwitchCameraId = -1;
private boolean mOpenCameraFail;
private boolean mCameraDisabled;
// When setCameraParametersWhenIdle() is called, we accumulate the subsets
// needed to be updated in mUpdateSet.
private int mUpdateSet;
private static final int SCREEN_DELAY = 2 * 60 * 1000;
private int mZoomValue; // The current zoom value.
private Parameters mInitialParams;
private boolean mFocusAreaSupported;
private boolean mMeteringAreaSupported;
private boolean mAeLockSupported;
private boolean mAwbLockSupported;
private boolean mContinousFocusSupported;
// The degrees of the device rotated clockwise from its natural orientation.
private int mOrientation = OrientationEventListener.ORIENTATION_UNKNOWN;
private ComboPreferences mPreferences;
private static final String sTempCropFilename = "crop-temp";
private ContentProviderClient mMediaProviderClient;
private ShutterButton mShutterButton;
private boolean mFaceDetectionStarted = false;
// mCropValue and mSaveUri are used only if isImageCaptureIntent() is true.
private String mCropValue;
private Uri mSaveUri;
// We use a queue to generated names of the images to be used later
// when the image is ready to be saved.
private NamedImages mNamedImages;
private Runnable mDoSnapRunnable = new Runnable() {
@Override
public void run() {
onShutterButtonClick();
}
};
private Runnable mFlashRunnable = new Runnable() {
@Override
public void run() {
animateFlash();
}
};
private final StringBuilder mBuilder = new StringBuilder();
private final Formatter mFormatter = new Formatter(mBuilder);
private final Object[] mFormatterArgs = new Object[1];
/**
* An unpublished intent flag requesting to return as soon as capturing
* is completed.
*
* TODO: consider publishing by moving into MediaStore.
*/
private static final String EXTRA_QUICK_CAPTURE =
"android.intent.extra.quickCapture";
// The display rotation in degrees. This is only valid when mCameraState is
// not PREVIEW_STOPPED.
private int mDisplayRotation;
// The value for android.hardware.Camera.setDisplayOrientation.
private int mCameraDisplayOrientation;
// The value for UI components like indicators.
private int mDisplayOrientation;
// The value for android.hardware.Camera.Parameters.setRotation.
private int mJpegRotation;
private boolean mFirstTimeInitialized;
private boolean mIsImageCaptureIntent;
private int mCameraState = PREVIEW_STOPPED;
private boolean mSnapshotOnIdle = false;
private ContentResolver mContentResolver;
private LocationManager mLocationManager;
private final PostViewPictureCallback mPostViewPictureCallback =
new PostViewPictureCallback();
private final RawPictureCallback mRawPictureCallback =
new RawPictureCallback();
private final AutoFocusCallback mAutoFocusCallback =
new AutoFocusCallback();
private final Object mAutoFocusMoveCallback =
ApiHelper.HAS_AUTO_FOCUS_MOVE_CALLBACK
? new AutoFocusMoveCallback()
: null;
private final CameraErrorCallback mErrorCallback = new CameraErrorCallback();
private long mFocusStartTime;
private long mShutterCallbackTime;
private long mPostViewPictureCallbackTime;
private long mRawPictureCallbackTime;
private long mJpegPictureCallbackTime;
private long mOnResumeTime;
private byte[] mJpegImageData;
// These latency time are for the CameraLatency test.
public long mAutoFocusTime;
public long mShutterLag;
public long mShutterToPictureDisplayedTime;
public long mPictureDisplayedToJpegCallbackTime;
public long mJpegCallbackFinishTime;
public long mCaptureStartTime;
// This handles everything about focus.
private FocusOverlayManager mFocusManager;
private String mSceneMode;
private final Handler mHandler = new MainHandler();
private PreferenceGroup mPreferenceGroup;
private boolean mQuickCapture;
CameraStartUpThread mCameraStartUpThread;
ConditionVariable mStartPreviewPrerequisiteReady = new ConditionVariable();
private SensorManager mSensorManager;
private float[] mGData = new float[3];
private float[] mMData = new float[3];
private float[] mR = new float[16];
private int mHeading = -1;
private MediaSaveService.OnMediaSavedListener mOnMediaSavedListener =
new MediaSaveService.OnMediaSavedListener() {
@Override
public void onMediaSaved(Uri uri) {
if (uri != null) {
mActivity.addSecureAlbumItemIfNeeded(false, uri);
Util.broadcastNewPicture(mActivity, uri);
}
}
};
// The purpose is not to block the main thread in onCreate and onResume.
private class CameraStartUpThread extends Thread {
private volatile boolean mCancelled;
public void cancel() {
mCancelled = true;
interrupt();
}
public boolean isCanceled() {
return mCancelled;
}
@Override
public void run() {
try {
// We need to check whether the activity is paused before long
// operations to ensure that onPause() can be done ASAP.
if (mCancelled) return;
mCameraDevice = Util.openCamera(mActivity, mCameraId);
mParameters = mCameraDevice.getParameters();
// Wait until all the initialization needed by startPreview are
// done.
mStartPreviewPrerequisiteReady.block();
initializeCapabilities();
if (mFocusManager == null) initializeFocusManager();
if (mCancelled) return;
setCameraParameters(UPDATE_PARAM_ALL);
mHandler.sendEmptyMessage(CAMERA_OPEN_DONE);
if (mCancelled) return;
startPreview();
mHandler.sendEmptyMessage(START_PREVIEW_DONE);
mOnResumeTime = SystemClock.uptimeMillis();
mHandler.sendEmptyMessage(CHECK_DISPLAY_ROTATION);
} catch (CameraHardwareException e) {
mHandler.sendEmptyMessage(OPEN_CAMERA_FAIL);
} catch (CameraDisabledException e) {
mHandler.sendEmptyMessage(CAMERA_DISABLED);
}
}
}
/**
* This Handler is used to post message back onto the main thread of the
* application
*/
private class MainHandler extends Handler {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case SETUP_PREVIEW: {
setupPreview();
break;
}
case CLEAR_SCREEN_DELAY: {
mActivity.getWindow().clearFlags(
WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
break;
}
case FIRST_TIME_INIT: {
initializeFirstTime();
break;
}
case SET_CAMERA_PARAMETERS_WHEN_IDLE: {
setCameraParametersWhenIdle(0);
break;
}
case CHECK_DISPLAY_ROTATION: {
// Set the display orientation if display rotation has changed.
// Sometimes this happens when the device is held upside
// down and camera app is opened. Rotation animation will
// take some time and the rotation value we have got may be
// wrong. Framework does not have a callback for this now.
if (Util.getDisplayRotation(mActivity) != mDisplayRotation) {
setDisplayOrientation();
}
if (SystemClock.uptimeMillis() - mOnResumeTime < 5000) {
mHandler.sendEmptyMessageDelayed(CHECK_DISPLAY_ROTATION, 100);
}
break;
}
case SHOW_TAP_TO_FOCUS_TOAST: {
showTapToFocusToast();
break;
}
case SWITCH_CAMERA: {
switchCamera();
break;
}
case SWITCH_CAMERA_START_ANIMATION: {
((CameraScreenNail) mActivity.mCameraScreenNail).animateSwitchCamera();
break;
}
case CAMERA_OPEN_DONE: {
onCameraOpened();
break;
}
case START_PREVIEW_DONE: {
onPreviewStarted();
break;
}
case OPEN_CAMERA_FAIL: {
mCameraStartUpThread = null;
mOpenCameraFail = true;
Util.showErrorAndFinish(mActivity,
R.string.cannot_connect_camera);
break;
}
case CAMERA_DISABLED: {
mCameraStartUpThread = null;
mCameraDisabled = true;
Util.showErrorAndFinish(mActivity,
R.string.camera_disabled);
break;
}
case CAPTURE_ANIMATION_DONE: {
mUI.enablePreviewThumb(false);
break;
}
case SET_PHOTO_UI_PARAMS: {
setCameraParametersWhenIdle(UPDATE_PARAM_PREFERENCE);
resizeForPreviewAspectRatio();
mUI.updateOnScreenIndicators(mParameters, mPreferenceGroup,
mPreferences);
break;
}
}
}
}
@Override
public void init(CameraActivity activity, View parent, boolean reuseNail) {
mActivity = activity;
mUI = new PhotoUI(activity, this, parent);
mPreferences = new ComboPreferences(mActivity);
CameraSettings.upgradeGlobalPreferences(mPreferences.getGlobal());
mCameraId = getPreferredCameraId(mPreferences);
mContentResolver = mActivity.getContentResolver();
// To reduce startup time, open the camera and start the preview in
// another thread.
mCameraStartUpThread = new CameraStartUpThread();
mCameraStartUpThread.start();
// Surface texture is from camera screen nail and startPreview needs it.
// This must be done before startPreview.
mIsImageCaptureIntent = isImageCaptureIntent();
if (reuseNail) {
mActivity.reuseCameraScreenNail(!mIsImageCaptureIntent);
} else {
mActivity.createCameraScreenNail(!mIsImageCaptureIntent);
}
mPreferences.setLocalId(mActivity, mCameraId);
CameraSettings.upgradeLocalPreferences(mPreferences.getLocal());
mActivity.setStoragePath(mPreferences);
// we need to reset exposure for the preview
resetExposureCompensation();
// Starting the preview needs preferences, camera screen nail, and
// focus area indicator.
mStartPreviewPrerequisiteReady.open();
initializeControlByIntent();
mQuickCapture = mActivity.getIntent().getBooleanExtra(EXTRA_QUICK_CAPTURE, false);
mLocationManager = new LocationManager(mActivity, mUI);
mSensorManager = (SensorManager)(mActivity.getSystemService(Context.SENSOR_SERVICE));
}
private void initializeControlByIntent() {
mUI.initializeControlByIntent();
if (mIsImageCaptureIntent) {
setupCaptureParams();
}
}
private void onPreviewStarted() {
mCameraStartUpThread = null;
setCameraState(IDLE);
if (!ApiHelper.HAS_SURFACE_TEXTURE) {
// This may happen if surfaceCreated has arrived.
mCameraDevice.setPreviewDisplayAsync(mUI.getSurfaceHolder());
}
startFaceDetection();
locationFirstRun();
}
// Prompt the user to pick to record location for the very first run of
// camera only
private void locationFirstRun() {
if (RecordLocationPreference.isSet(mPreferences)) {
return;
}
if (mActivity.isSecureCamera()) return;
// Check if the back camera exists
int backCameraId = CameraHolder.instance().getBackCameraId();
if (backCameraId == -1) {
// If there is no back camera, do not show the prompt.
return;
}
new AlertDialog.Builder(mActivity)
.setTitle(R.string.remember_location_title)
.setMessage(R.string.remember_location_prompt)
.setPositiveButton(R.string.remember_location_yes, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int arg1) {
setLocationPreference(RecordLocationPreference.VALUE_ON);
}
})
.setNegativeButton(R.string.remember_location_no, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int arg1) {
dialog.cancel();
}
})
.setOnCancelListener(new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
setLocationPreference(RecordLocationPreference.VALUE_OFF);
}
})
.show();
}
private void setLocationPreference(String value) {
mPreferences.edit()
.putString(CameraSettings.KEY_RECORD_LOCATION, value)
.apply();
// TODO: Fix this to use the actual onSharedPreferencesChanged listener
// instead of invoking manually
onSharedPreferenceChanged();
}
private void onCameraOpened() {
View root = mUI.getRootView();
// These depend on camera parameters.
int width = mUI.mPreviewFrameLayout.getWidth();
int height = mUI.mPreviewFrameLayout.getHeight();
openCameraCommon();
resizeForPreviewAspectRatio();
mFocusManager.setPreviewSize(width, height);
// Full-screen screennail
if (Util.getDisplayRotation(mActivity) % 180 == 0) {
((CameraScreenNail) mActivity.mCameraScreenNail).setPreviewFrameLayoutSize(width, height);
} else {
((CameraScreenNail) mActivity.mCameraScreenNail).setPreviewFrameLayoutSize(height, width);
}
// Set touch focus listener.
mActivity.setSingleTapUpListener(root);
onFullScreenChanged(mActivity.isInCameraApp());
}
private void switchCamera() {
if (mPaused) return;
Log.v(TAG, "Start to switch camera. id=" + mPendingSwitchCameraId);
mCameraId = mPendingSwitchCameraId;
mPendingSwitchCameraId = -1;
setCameraId(mCameraId);
// from onPause
closeCamera();
mUI.collapseCameraControls();
mUI.clearFaces();
if (mFocusManager != null) mFocusManager.removeMessages();
// Restart the camera and initialize the UI. From onCreate.
mPreferences.setLocalId(mActivity, mCameraId);
CameraSettings.upgradeLocalPreferences(mPreferences.getLocal());
try {
mCameraDevice = Util.openCamera(mActivity, mCameraId);
mParameters = mCameraDevice.getParameters();
} catch (CameraHardwareException e) {
Util.showErrorAndFinish(mActivity, R.string.cannot_connect_camera);
return;
} catch (CameraDisabledException e) {
Util.showErrorAndFinish(mActivity, R.string.camera_disabled);
return;
}
initializeCapabilities();
CameraInfo info = CameraHolder.instance().getCameraInfo()[mCameraId];
boolean mirror = (info.facing == CameraInfo.CAMERA_FACING_FRONT);
mFocusManager.setMirror(mirror);
mFocusManager.setParameters(mInitialParams);
setupPreview();
resizeForPreviewAspectRatio();
openCameraCommon();
if (ApiHelper.HAS_SURFACE_TEXTURE) {
// Start switch camera animation. Post a message because
// onFrameAvailable from the old camera may already exist.
mHandler.sendEmptyMessage(SWITCH_CAMERA_START_ANIMATION);
}
}
protected void setCameraId(int cameraId) {
ListPreference pref = mPreferenceGroup.findPreference(CameraSettings.KEY_CAMERA_ID);
pref.setValue("" + cameraId);
}
// either open a new camera or switch cameras
private void openCameraCommon() {
loadCameraPreferences();
mUI.onCameraOpened(mPreferenceGroup, mPreferences, mParameters, this);
updateSceneMode();
showTapToFocusToastIfNeeded();
}
public void onScreenSizeChanged(int width, int height, int previewWidth, int previewHeight) {
Log.d(TAG, "Preview size changed.");
if (mFocusManager != null) mFocusManager.setPreviewSize(width, height);
((CameraScreenNail) mActivity.mCameraScreenNail).setPreviewFrameLayoutSize(
previewWidth, previewHeight);
mActivity.notifyScreenNailChanged();
}
private void resetExposureCompensation() {
String value = mPreferences.getString(CameraSettings.KEY_EXPOSURE,
CameraSettings.EXPOSURE_DEFAULT_VALUE);
if (!CameraSettings.EXPOSURE_DEFAULT_VALUE.equals(value)) {
Editor editor = mPreferences.edit();
editor.putString(CameraSettings.KEY_EXPOSURE, "0");
editor.apply();
}
}
private void keepMediaProviderInstance() {
// We want to keep a reference to MediaProvider in camera's lifecycle.
// TODO: Utilize mMediaProviderClient instance to replace
// ContentResolver calls.
if (mMediaProviderClient == null) {
mMediaProviderClient = mContentResolver
.acquireContentProviderClient(MediaStore.AUTHORITY);
}
}
// Snapshots can only be taken after this is called. It should be called
// once only. We could have done these things in onCreate() but we want to
// make preview screen appear as soon as possible.
private void initializeFirstTime() {
if (mFirstTimeInitialized) return;
// Initialize location service.
boolean recordLocation = RecordLocationPreference.get(
mPreferences, mContentResolver);
mLocationManager.recordLocation(recordLocation);
keepMediaProviderInstance();
mShutterButton = mActivity.getShutterButton();
mUI.initializeFirstTime();
MediaSaveService s = mActivity.getMediaSaveService();
// We set the listener only when both service and shutterbutton
// are initialized.
if (s != null) {
s.setListener(this);
}
mNamedImages = new NamedImages();
mFirstTimeInitialized = true;
addIdleHandler();
mActivity.updateStorageSpaceAndHint();
}
// If the activity is paused and resumed, this method will be called in
// onResume.
private void initializeSecondTime() {
// Start location update if needed.
boolean recordLocation = RecordLocationPreference.get(
mPreferences, mContentResolver);
mLocationManager.recordLocation(recordLocation);
MediaSaveService s = mActivity.getMediaSaveService();
if (s != null) {
s.setListener(this);
}
mNamedImages = new NamedImages();
mUI.initializeSecondTime(mParameters);
keepMediaProviderInstance();
}
@Override
public void onSurfaceCreated(SurfaceHolder holder) {
// Do not access the camera if camera start up thread is not finished.
if (mCameraDevice == null || mCameraStartUpThread != null)
return;
mCameraDevice.setPreviewDisplayAsync(holder);
// This happens when onConfigurationChanged arrives, surface has been
// destroyed, and there is no onFullScreenChanged.
if (mCameraState == PREVIEW_STOPPED) {
setupPreview();
}
}
private void showTapToFocusToastIfNeeded() {
// Show the tap to focus toast if this is the first start.
if (mFocusAreaSupported &&
mPreferences.getBoolean(CameraSettings.KEY_CAMERA_FIRST_USE_HINT_SHOWN, true)) {
// Delay the toast for one second to wait for orientation.
mHandler.sendEmptyMessageDelayed(SHOW_TAP_TO_FOCUS_TOAST, 1000);
}
}
private void addIdleHandler() {
MessageQueue queue = Looper.myQueue();
queue.addIdleHandler(new MessageQueue.IdleHandler() {
@Override
public boolean queueIdle() {
Storage.getInstance().ensureOSXCompatible();
return false;
}
});
}
@TargetApi(ApiHelper.VERSION_CODES.ICE_CREAM_SANDWICH)
@Override
public void startFaceDetection() {
if (!ApiHelper.HAS_FACE_DETECTION) return;
CameraInfo info = CameraHolder.instance().getCameraInfo()[mCameraId];
// Workaround for a buggy camera library
if (Util.noFaceDetectOnFrontCamera() && info.facing == CameraInfo.CAMERA_FACING_FRONT) {
return;
}
if (mFaceDetectionStarted || mCameraState != IDLE) return;
if (mParameters.getMaxNumDetectedFaces() > 0) {
mFaceDetectionStarted = true;
mUI.onStartFaceDetection(mDisplayOrientation,
(info.facing == CameraInfo.CAMERA_FACING_FRONT));
mCameraDevice.setFaceDetectionListener(mUI);
mCameraDevice.startFaceDetection();
}
}
@TargetApi(ApiHelper.VERSION_CODES.ICE_CREAM_SANDWICH)
@Override
public void stopFaceDetection() {
if (!ApiHelper.HAS_FACE_DETECTION) return;
if (!mFaceDetectionStarted) return;
if (mParameters.getMaxNumDetectedFaces() > 0) {
mFaceDetectionStarted = false;
mCameraDevice.setFaceDetectionListener(null);
mCameraDevice.stopFaceDetection();
mUI.clearFaces();
}
}
@Override
public boolean dispatchTouchEvent(MotionEvent m) {
if (mCameraState == SWITCHING_CAMERA) return true;
return mUI.dispatchTouchEvent(m);
}
private final class ShutterCallback
implements android.hardware.Camera.ShutterCallback {
private boolean mAnimateFlash;
public ShutterCallback(boolean animateFlash) {
mAnimateFlash = animateFlash;
}
@Override
public void onShutter() {
mShutterCallbackTime = System.currentTimeMillis();
mShutterLag = mShutterCallbackTime - mCaptureStartTime;
Log.v(TAG, "mShutterLag = " + mShutterLag + "ms");
if (mAnimateFlash) {
mActivity.runOnUiThread(mFlashRunnable);
}
}
}
private final class PostViewPictureCallback implements PictureCallback {
@Override
public void onPictureTaken(
byte [] data, android.hardware.Camera camera) {
mPostViewPictureCallbackTime = System.currentTimeMillis();
Log.v(TAG, "mShutterToPostViewCallbackTime = "
+ (mPostViewPictureCallbackTime - mShutterCallbackTime)
+ "ms");
}
}
private final class RawPictureCallback implements PictureCallback {
@Override
public void onPictureTaken(
byte [] rawData, android.hardware.Camera camera) {
mRawPictureCallbackTime = System.currentTimeMillis();
Log.v(TAG, "mShutterToRawCallbackTime = "
+ (mRawPictureCallbackTime - mShutterCallbackTime) + "ms");
}
}
private final class JpegPictureCallback implements PictureCallback {
Location mLocation;
public JpegPictureCallback(Location loc) {
mLocation = loc;
}
@Override
public void onPictureTaken(
final byte [] jpegData, final android.hardware.Camera camera) {
if (mPaused) {
return;
}
if (mSceneMode == Util.SCENE_MODE_HDR) {
mActivity.showSwitcher();
mActivity.setSwipingEnabled(true);
}
mJpegPictureCallbackTime = System.currentTimeMillis();
// If postview callback has arrived, the captured image is displayed
// in postview callback. If not, the captured image is displayed in
// raw picture callback.
if (mPostViewPictureCallbackTime != 0) {
mShutterToPictureDisplayedTime =
mPostViewPictureCallbackTime - mShutterCallbackTime;
mPictureDisplayedToJpegCallbackTime =
mJpegPictureCallbackTime - mPostViewPictureCallbackTime;
} else {
mShutterToPictureDisplayedTime =
mRawPictureCallbackTime - mShutterCallbackTime;
mPictureDisplayedToJpegCallbackTime =
mJpegPictureCallbackTime - mRawPictureCallbackTime;
}
Log.v(TAG, "mPictureDisplayedToJpegCallbackTime = "
+ mPictureDisplayedToJpegCallbackTime + "ms");
// Only animate when in full screen capture mode
// i.e. If monkey/a user swipes to the gallery during picture taking,
// don't show animation
if (ApiHelper.HAS_SURFACE_TEXTURE && !mIsImageCaptureIntent
&& mActivity.mShowCameraAppView) {
// Finish capture animation
mHandler.removeMessages(CAPTURE_ANIMATION_DONE);
((CameraScreenNail) mActivity.mCameraScreenNail).animateSlide();
mHandler.sendEmptyMessageDelayed(CAPTURE_ANIMATION_DONE,
CaptureAnimManager.getAnimationDuration());
}
mFocusManager.updateFocusUI(); // Ensure focus indicator is hidden.
boolean isSamsungHDR =
(mSceneMode == Util.SCENE_MODE_HDR && Util.needSamsungHDRFormat());
if (!mIsImageCaptureIntent && (!Util.isZSLEnabled() || isSamsungHDR)) {
if (ApiHelper.CAN_START_PREVIEW_IN_JPEG_CALLBACK) {
setupPreview();
} else {
// Camera HAL of some devices have a bug. Starting preview
// immediately after taking a picture will fail. Wait some
// time before starting the preview.
mHandler.sendEmptyMessageDelayed(SETUP_PREVIEW, 300);
}
- } else if (Util.isZSLEnabled() && !isSamsungHDR) {
- // In ZSL mode, the preview is not stopped, due to which the
- // review mode (ImageCapture) doesn't show the captured frame.
- // Hence stop the preview if ZSL mode is active so that the
- // preview can be restarted using the onReviewRetakeClicked().
- if (mIsImageCaptureIntent) {
- stopPreview();
- } else {
- mFocusManager.resetTouchFocus();
- setCameraState(IDLE);
- }
+ } else {
+ mFocusManager.resetTouchFocus();
+ setCameraState(IDLE);
}
if (!mIsImageCaptureIntent) {
// Calculate the width and the height of the jpeg.
Size s = mParameters.getPictureSize();
final ExifInterface exif = Exif.getExif(jpegData);
final int orientation = Exif.getOrientation(exif);
final int width, height;
if ((mJpegRotation + orientation) % 180 == 0 || isSamsungHDR) {
width = s.width;
height = s.height;
} else {
width = s.height;
height = s.width;
}
final String title = mNamedImages.getTitle();
long date = mNamedImages.getDate();
if (title == null) {
Log.e(TAG, "Unbalanced name/data pair");
} else {
if (date == -1) date = mCaptureStartTime;
if (mHeading >= 0) {
// heading direction has been updated by the sensor.
ExifTag directionRefTag = exif.buildTag(
ExifInterface.TAG_GPS_IMG_DIRECTION_REF,
ExifInterface.GpsTrackRef.MAGNETIC_DIRECTION);
ExifTag directionTag = exif.buildTag(
ExifInterface.TAG_GPS_IMG_DIRECTION,
new Rational(mHeading, 1));
exif.setTag(directionRefTag);
exif.setTag(directionTag);
}
if (mLocation != null) {
exif.addGpsTags(mLocation.getLatitude(), mLocation.getLongitude());
exif.addGpsDateTimeStampTag(date);
exif.setTag(exif.buildTag(ExifInterface.TAG_GPS_PROCESSING_METHOD,
mLocation.getProvider()));
}
exif.addDateTimeStampTag(ExifInterface.TAG_DATE_TIME,
date, TimeZone.getDefault());
if (isSamsungHDR) {
final long finalDate = date;
new Thread(new Runnable() {
public void run() {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Bitmap bm = Util.decodeYUV422P(jpegData, width, height);
if (mJpegRotation != 0) {
Matrix matrix = new Matrix();
matrix.postRotate(mJpegRotation);
bm = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, true);
}
bm.compress(Bitmap.CompressFormat.JPEG,
CameraSettings.getJpegQualityIntValue(mPreferences),
baos);
boolean rotated = (mJpegRotation % 180) != 0;
mActivity.getMediaSaveService().addImage(
baos.toByteArray(), title, finalDate, mLocation,
rotated ? height : width, rotated ? width : height,
orientation, exif, mOnMediaSavedListener, mContentResolver);
}
}).start();
} else {
mActivity.getMediaSaveService().addImage(
jpegData, title, date, mLocation, width, height,
orientation, exif, mOnMediaSavedListener, mContentResolver);
}
}
} else {
mJpegImageData = jpegData;
if (!mQuickCapture) {
mUI.showPostCaptureAlert();
} else {
onCaptureDone();
}
}
// Check this in advance of each shot so we don't add to shutter
// latency. It's true that someone else could write to the SD card in
// the mean time and fill it, but that could have happened between the
// shutter press and saving the JPEG too.
mActivity.updateStorageSpaceAndHint();
long now = System.currentTimeMillis();
mJpegCallbackFinishTime = now - mJpegPictureCallbackTime;
Log.v(TAG, "mJpegCallbackFinishTime = "
+ mJpegCallbackFinishTime + "ms");
mJpegPictureCallbackTime = 0;
}
}
private final class AutoFocusCallback
implements android.hardware.Camera.AutoFocusCallback {
@Override
public void onAutoFocus(
boolean focused, android.hardware.Camera camera) {
if (mPaused) return;
mAutoFocusTime = System.currentTimeMillis() - mFocusStartTime;
Log.v(TAG, "mAutoFocusTime = " + mAutoFocusTime + "ms");
setCameraState(IDLE);
mFocusManager.onAutoFocus(focused, mUI.isShutterPressed());
}
}
@TargetApi(ApiHelper.VERSION_CODES.JELLY_BEAN)
private final class AutoFocusMoveCallback
implements android.hardware.Camera.AutoFocusMoveCallback {
@Override
public void onAutoFocusMoving(
boolean moving, android.hardware.Camera camera) {
mFocusManager.onAutoFocusMoving(moving);
}
}
private static class NamedImages {
private ArrayList<NamedEntity> mQueue;
private boolean mStop;
private NamedEntity mNamedEntity;
public NamedImages() {
mQueue = new ArrayList<NamedEntity>();
}
public void nameNewImage(ContentResolver resolver, long date) {
NamedEntity r = new NamedEntity();
r.title = Util.createJpegName(date);
r.date = date;
mQueue.add(r);
}
public String getTitle() {
if (mQueue.isEmpty()) {
mNamedEntity = null;
return null;
}
mNamedEntity = mQueue.get(0);
mQueue.remove(0);
return mNamedEntity.title;
}
// Must be called after getTitle().
public long getDate() {
if (mNamedEntity == null) return -1;
return mNamedEntity.date;
}
private static class NamedEntity {
String title;
long date;
}
}
private void setCameraState(int state) {
mCameraState = state;
switch (state) {
case PhotoController.PREVIEW_STOPPED:
case PhotoController.SNAPSHOT_IN_PROGRESS:
case PhotoController.FOCUSING:
case PhotoController.SWITCHING_CAMERA:
mUI.enableGestures(false);
break;
case PhotoController.IDLE:
if (mActivity.isInCameraApp()) {
mUI.enableGestures(true);
}
break;
}
}
private void animateFlash() {
// Only animate when in full screen capture mode
// i.e. If monkey/a user swipes to the gallery during picture taking,
// don't show animation
if (ApiHelper.HAS_SURFACE_TEXTURE && !mIsImageCaptureIntent
&& mActivity.mShowCameraAppView) {
// Start capture animation.
((CameraScreenNail) mActivity.mCameraScreenNail).animateFlash(mDisplayRotation);
mUI.enablePreviewThumb(true);
mHandler.sendEmptyMessageDelayed(CAPTURE_ANIMATION_DONE,
CaptureAnimManager.getAnimationDuration());
}
}
@Override
public boolean capture() {
// If we are already in the middle of taking a snapshot or the image save request
// is full then ignore.
if (mCameraDevice == null || mCameraState == SNAPSHOT_IN_PROGRESS
|| mCameraState == SWITCHING_CAMERA
|| mActivity.getMediaSaveService().isQueueFull()) {
return false;
}
mCaptureStartTime = System.currentTimeMillis();
mPostViewPictureCallbackTime = 0;
mJpegImageData = null;
final boolean animateBefore = (mSceneMode == Util.SCENE_MODE_HDR);
if (animateBefore) {
animateFlash();
}
// Set rotation and gps data.
int orientation;
// We need to be consistent with the framework orientation (i.e. the
// orientation of the UI.) when the auto-rotate screen setting is on.
if (mActivity.isAutoRotateScreen()) {
orientation = (360 - mDisplayRotation) % 360;
} else {
orientation = mOrientation;
}
mJpegRotation = Util.getJpegRotation(mCameraId, orientation);
mParameters.setRotation(mJpegRotation);
Location loc = mLocationManager.getCurrentLocation();
Util.setGpsParameters(mParameters, loc);
mCameraDevice.setParameters(mParameters);
mCameraDevice.takePicture2(new ShutterCallback(!animateBefore),
mRawPictureCallback, mPostViewPictureCallback,
new JpegPictureCallback(loc), mCameraState,
mFocusManager.getFocusState());
mNamedImages.nameNewImage(mContentResolver, mCaptureStartTime);
if (Util.isZSLEnabled() &&
(mSceneMode != Util.SCENE_MODE_HDR || !Util.needSamsungHDRFormat())) {
mRestartPreview = false;
}
mFaceDetectionStarted = false;
setCameraState(SNAPSHOT_IN_PROGRESS);
UsageStatistics.onEvent(UsageStatistics.COMPONENT_CAMERA,
UsageStatistics.ACTION_CAPTURE_DONE, "Photo");
return true;
}
@Override
public void setFocusParameters() {
setCameraParameters(UPDATE_PARAM_PREFERENCE);
}
private int getPreferredCameraId(ComboPreferences preferences) {
int intentCameraId = Util.getCameraFacingIntentExtras(mActivity);
if (intentCameraId != -1) {
// Testing purpose. Launch a specific camera through the intent
// extras.
return intentCameraId;
} else {
return CameraSettings.readPreferredCameraId(preferences);
}
}
@Override
public void onFullScreenChanged(boolean full) {
mUI.onFullScreenChanged(full);
if (ApiHelper.HAS_SURFACE_TEXTURE) {
if (mActivity.mCameraScreenNail != null) {
((CameraScreenNail) mActivity.mCameraScreenNail).setFullScreen(full);
}
return;
}
}
private void updateSceneMode() {
// If scene mode is set, we cannot set flash mode, white balance, and
// focus mode, instead, we read it from driver
if (!Parameters.SCENE_MODE_AUTO.equals(mSceneMode)) {
overrideCameraSettings(mParameters.getFlashMode(),
mParameters.getWhiteBalance(), mParameters.getFocusMode());
} else {
overrideCameraSettings(null, null, null);
}
}
private void overrideCameraSettings(final String flashMode,
final String whiteBalance, final String focusMode) {
mUI.overrideSettings(
CameraSettings.KEY_FLASH_MODE, flashMode,
CameraSettings.KEY_WHITE_BALANCE, whiteBalance,
CameraSettings.KEY_FOCUS_MODE, focusMode);
if (Util.needSamsungHDRFormat()){
if (mSceneMode == Util.SCENE_MODE_HDR) {
mUI.overrideSettings(CameraSettings.KEY_EXPOSURE,
String.valueOf(mParameters.getMaxExposureCompensation()));
mParameters.setExposureCompensation(mParameters.getMaxExposureCompensation());
} else {
mUI.overrideSettings(CameraSettings.KEY_EXPOSURE, null);
mParameters.setExposureCompensation(CameraSettings.readExposure(mPreferences));
}
mCameraDevice.setParameters(mParameters);
}
}
private void loadCameraPreferences() {
CameraSettings settings = new CameraSettings(mActivity, mInitialParams,
mCameraId, CameraHolder.instance().getCameraInfo());
mPreferenceGroup = settings.getPreferenceGroup(R.xml.camera_preferences);
}
@Override
public void onOrientationChanged(int orientation) {
// We keep the last known orientation. So if the user first orient
// the camera then point the camera to floor or sky, we still have
// the correct orientation.
if (orientation == OrientationEventListener.ORIENTATION_UNKNOWN) return;
mOrientation = Util.roundOrientation(orientation, mOrientation);
// Show the toast after getting the first orientation changed.
if (mHandler.hasMessages(SHOW_TAP_TO_FOCUS_TOAST)) {
mHandler.removeMessages(SHOW_TAP_TO_FOCUS_TOAST);
showTapToFocusToast();
}
}
@Override
public void onStop() {
if (mMediaProviderClient != null) {
mMediaProviderClient.release();
mMediaProviderClient = null;
}
}
@Override
public void onCaptureCancelled() {
mActivity.setResultEx(Activity.RESULT_CANCELED, new Intent());
mActivity.finish();
}
@Override
public void onCaptureRetake() {
if (mPaused)
return;
mUI.hidePostCaptureAlert();
setupPreview();
}
@Override
public void onCaptureDone() {
if (mPaused) {
return;
}
byte[] data = mJpegImageData;
if (mCropValue == null) {
// First handle the no crop case -- just return the value. If the
// caller specifies a "save uri" then write the data to its
// stream. Otherwise, pass back a scaled down version of the bitmap
// directly in the extras.
if (mSaveUri != null) {
OutputStream outputStream = null;
try {
outputStream = mContentResolver.openOutputStream(mSaveUri);
outputStream.write(data);
outputStream.close();
mActivity.setResultEx(Activity.RESULT_OK);
mActivity.finish();
} catch (IOException ex) {
// ignore exception
} finally {
Util.closeSilently(outputStream);
}
} else {
ExifInterface exif = Exif.getExif(data);
int orientation = Exif.getOrientation(exif);
Bitmap bitmap = Util.makeBitmap(data, 50 * 1024);
bitmap = Util.rotate(bitmap, orientation);
mActivity.setResultEx(Activity.RESULT_OK,
new Intent("inline-data").putExtra("data", bitmap));
mActivity.finish();
}
} else {
// Save the image to a temp file and invoke the cropper
Uri tempUri = null;
FileOutputStream tempStream = null;
try {
File path = mActivity.getFileStreamPath(sTempCropFilename);
path.delete();
tempStream = mActivity.openFileOutput(sTempCropFilename, 0);
tempStream.write(data);
tempStream.close();
tempUri = Uri.fromFile(path);
} catch (FileNotFoundException ex) {
mActivity.setResultEx(Activity.RESULT_CANCELED);
mActivity.finish();
return;
} catch (IOException ex) {
mActivity.setResultEx(Activity.RESULT_CANCELED);
mActivity.finish();
return;
} finally {
Util.closeSilently(tempStream);
}
Bundle newExtras = new Bundle();
if (mCropValue.equals("circle")) {
newExtras.putString("circleCrop", "true");
}
if (mSaveUri != null) {
newExtras.putParcelable(MediaStore.EXTRA_OUTPUT, mSaveUri);
} else {
newExtras.putBoolean(CropExtras.KEY_RETURN_DATA, true);
}
if (mActivity.isSecureCamera()) {
newExtras.putBoolean(CropExtras.KEY_SHOW_WHEN_LOCKED, true);
}
Intent cropIntent = new Intent(FilterShowActivity.CROP_ACTION);
cropIntent.setData(tempUri);
cropIntent.putExtras(newExtras);
mActivity.startActivityForResult(cropIntent, REQUEST_CROP);
}
}
@Override
public void onShutterButtonFocus(boolean pressed) {
if (mPaused || mUI.collapseCameraControls()
|| (mCameraState == SNAPSHOT_IN_PROGRESS)
|| (mCameraState == PREVIEW_STOPPED)) return;
// Do not do focus if there is not enough storage.
if (pressed && !canTakePicture()) return;
if (pressed) {
mFocusManager.onShutterDown();
} else {
// for countdown mode, we need to postpone the shutter release
// i.e. lock the focus during countdown.
if (!mUI.isCountingDown()) {
mFocusManager.onShutterUp();
}
}
}
@Override
public void onShutterButtonClick() {
if (mPaused || mUI.collapseCameraControls()
|| (mCameraState == SWITCHING_CAMERA)
|| (mCameraState == PREVIEW_STOPPED)) return;
// Do not take the picture if there is not enough storage.
if (mActivity.getStorageSpace() <= Storage.LOW_STORAGE_THRESHOLD) {
Log.i(TAG, "Not enough space or storage not ready. remaining="
+ mActivity.getStorageSpace());
return;
}
Log.v(TAG, "onShutterButtonClick: mCameraState=" + mCameraState);
if (mSceneMode == Util.SCENE_MODE_HDR) {
mActivity.hideSwitcher();
mActivity.setSwipingEnabled(false);
}
// If the user wants to do a snapshot while the previous one is still
// in progress, remember the fact and do it after we finish the previous
// one and re-start the preview. Snapshot in progress also includes the
// state that autofocus is focusing and a picture will be taken when
// focus callback arrives.
if ((mFocusManager.isFocusingSnapOnFinish() || mCameraState == SNAPSHOT_IN_PROGRESS)
&& !mIsImageCaptureIntent) {
mSnapshotOnIdle = true;
return;
}
String timer = mPreferences.getString(
CameraSettings.KEY_TIMER,
mActivity.getString(R.string.pref_camera_timer_default));
boolean playSound = mPreferences.getString(CameraSettings.KEY_TIMER_SOUND_EFFECTS,
mActivity.getString(R.string.pref_camera_timer_sound_default))
.equals(mActivity.getString(R.string.setting_on_value));
int seconds = Integer.parseInt(timer);
// When shutter button is pressed, check whether the previous countdown is
// finished. If not, cancel the previous countdown and start a new one.
if (mUI.isCountingDown()) {
mUI.cancelCountDown();
}
if (seconds > 0) {
mUI.startCountDown(seconds, playSound);
} else {
mSnapshotOnIdle = false;
mFocusManager.doSnap();
}
}
void setPreviewFrameLayoutCameraOrientation(){
CameraInfo info = CameraHolder.instance().getCameraInfo()[mCameraId];
//if camera mount angle is 0 or 180, we want to resize preview
if(info.orientation % 180 == 0){
mUI.mPreviewFrameLayout.setRenderer(mUI.mPieRenderer);
mUI.mPreviewFrameLayout.cameraOrientationPreviewResize(true);
} else{
mUI.mPreviewFrameLayout.cameraOrientationPreviewResize(false);
}
}
private void resizeForPreviewAspectRatio() {
if ( mCameraDevice == null || mParameters == null) {
Log.e(TAG, "Camera not yet initialized");
return;
}
setPreviewFrameLayoutCameraOrientation();
Size size = mParameters.getPictureSize();
Log.e(TAG,"Width = "+ size.width+ "Height = "+size.height);
mUI.setAspectRatio((double) size.width / size.height);
}
@Override
public void installIntentFilter() {
}
@Override
public boolean updateStorageHintOnResume() {
return mFirstTimeInitialized;
}
@Override
public void updateCameraAppView() {
}
@Override
public void onResumeBeforeSuper() {
mPaused = false;
}
@Override
public void onResumeAfterSuper() {
if (mOpenCameraFail || mCameraDisabled) return;
mJpegPictureCallbackTime = 0;
mZoomValue = 0;
// Start the preview if it is not started.
if (mCameraState == PREVIEW_STOPPED && mCameraStartUpThread == null) {
resetExposureCompensation();
mCameraStartUpThread = new CameraStartUpThread();
mCameraStartUpThread.start();
}
// If first time initialization is not finished, put it in the
// message queue.
if (!mFirstTimeInitialized) {
mHandler.sendEmptyMessage(FIRST_TIME_INIT);
} else {
initializeSecondTime();
}
keepScreenOnAwhile();
// Dismiss open menu if exists.
PopupManager.getInstance(mActivity).notifyShowPopup(null);
UsageStatistics.onContentViewChanged(
UsageStatistics.COMPONENT_CAMERA, "PhotoModule");
Sensor gsensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
if (gsensor != null) {
mSensorManager.registerListener(this, gsensor, SensorManager.SENSOR_DELAY_NORMAL);
}
Sensor msensor = mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
if (msensor != null) {
mSensorManager.registerListener(this, msensor, SensorManager.SENSOR_DELAY_NORMAL);
}
}
void waitCameraStartUpThread() {
try {
if (mCameraStartUpThread != null) {
mCameraStartUpThread.cancel();
mCameraStartUpThread.join();
mCameraStartUpThread = null;
setCameraState(IDLE);
}
} catch (InterruptedException e) {
// ignore
}
}
@Override
public void onPauseBeforeSuper() {
mPaused = true;
Sensor gsensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
if (gsensor != null) {
mSensorManager.unregisterListener(this, gsensor);
}
Sensor msensor = mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
if (msensor != null) {
mSensorManager.unregisterListener(this, msensor);
}
}
@Override
public void onPauseAfterSuper() {
// Wait the camera start up thread to finish.
waitCameraStartUpThread();
// When camera is started from secure lock screen for the first time
// after screen on, the activity gets onCreate->onResume->onPause->onResume.
// To reduce the latency, keep the camera for a short time so it does
// not need to be opened again.
if (mCameraDevice != null && mActivity.isSecureCamera()
&& ActivityBase.isFirstStartAfterScreenOn()) {
ActivityBase.resetFirstStartAfterScreenOn();
CameraHolder.instance().keep(KEEP_CAMERA_TIMEOUT);
}
// Reset the focus first. Camera CTS does not guarantee that
// cancelAutoFocus is allowed after preview stops.
if (mCameraDevice != null && mCameraState != PREVIEW_STOPPED) {
mCameraDevice.cancelAutoFocus();
}
stopPreview();
// Release surface texture.
mActivity.getCameraScreenNail().releaseSurfaceTexture();
resetScreenOn();
mNamedImages = null;
if (mLocationManager != null) mLocationManager.recordLocation(false);
// If we are in an image capture intent and has taken
// a picture, we just clear it in onPause.
mJpegImageData = null;
// Remove the messages in the event queue.
mHandler.removeMessages(SETUP_PREVIEW);
mHandler.removeMessages(FIRST_TIME_INIT);
mHandler.removeMessages(CHECK_DISPLAY_ROTATION);
mHandler.removeMessages(SWITCH_CAMERA);
mHandler.removeMessages(SWITCH_CAMERA_START_ANIMATION);
mHandler.removeMessages(CAMERA_OPEN_DONE);
mHandler.removeMessages(START_PREVIEW_DONE);
mHandler.removeMessages(OPEN_CAMERA_FAIL);
mHandler.removeMessages(CAMERA_DISABLED);
closeCamera();
resetScreenOn();
mUI.onPause();
mPendingSwitchCameraId = -1;
if (mFocusManager != null) mFocusManager.removeMessages();
MediaSaveService s = mActivity.getMediaSaveService();
if (s != null) {
s.setListener(null);
}
}
/**
* The focus manager is the first UI related element to get initialized,
* and it requires the RenderOverlay, so initialize it here
*/
private void initializeFocusManager() {
// Create FocusManager object. startPreview needs it.
// if mFocusManager not null, reuse it
// otherwise create a new instance
if (mFocusManager != null) {
mFocusManager.removeMessages();
} else {
CameraInfo info = CameraHolder.instance().getCameraInfo()[mCameraId];
boolean mirror = (info.facing == CameraInfo.CAMERA_FACING_FRONT);
String[] defaultFocusModes = mActivity.getResources().getStringArray(
R.array.pref_camera_focusmode_default_array);
mFocusManager = new FocusOverlayManager(mPreferences, defaultFocusModes,
mInitialParams, this, mirror,
mActivity.getMainLooper(), mUI);
}
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
Log.v(TAG, "onConfigurationChanged");
// Ignore until the hardware is started
if (mCameraStartUpThread != null) {
return;
}
setDisplayOrientation();
resizeForPreviewAspectRatio();
}
@Override
public void onActivityResult(
int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQUEST_CROP: {
Intent intent = new Intent();
if (data != null) {
Bundle extras = data.getExtras();
if (extras != null) {
intent.putExtras(extras);
}
}
mActivity.setResultEx(resultCode, intent);
mActivity.finish();
File path = mActivity.getFileStreamPath(sTempCropFilename);
path.delete();
break;
}
}
}
private boolean canTakePicture() {
return isCameraIdle() && (mActivity.getStorageSpace() > Storage.LOW_STORAGE_THRESHOLD);
}
@Override
public void autoFocus() {
mFocusStartTime = System.currentTimeMillis();
mCameraDevice.autoFocus(mAutoFocusCallback);
setCameraState(FOCUSING);
}
@Override
public void cancelAutoFocus() {
mCameraDevice.cancelAutoFocus();
setCameraState(IDLE);
setCameraParameters(UPDATE_PARAM_PREFERENCE);
}
// Preview area is touched. Handle touch focus.
@Override
public void onSingleTapUp(View view, int x, int y) {
if (mPaused || mCameraDevice == null || !mFirstTimeInitialized
|| mCameraState == SNAPSHOT_IN_PROGRESS
|| mCameraState == SWITCHING_CAMERA
|| mCameraState == PREVIEW_STOPPED) {
return;
}
// Do not trigger touch focus if popup window is opened.
if (mUI.removeTopLevelPopup()) return;
// Check if metering area or focus area is supported.
if (!mFocusAreaSupported && !mMeteringAreaSupported) return;
mFocusManager.onSingleTapUp(x, y);
}
@Override
public boolean onBackPressed() {
return mUI.onBackPressed();
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_VOLUME_UP:
if (mActivity.isInCameraApp() && mFirstTimeInitialized
&& (mUI.mMenuInitialized)) {
mUI.onScaleStepResize(true);
}
return true;
case KeyEvent.KEYCODE_VOLUME_DOWN:
if (mActivity.isInCameraApp() && mFirstTimeInitialized
&& (mUI.mMenuInitialized)) {
mUI.onScaleStepResize(false);
}
return true;
case KeyEvent.KEYCODE_FOCUS:
if (mActivity.isInCameraApp() && mFirstTimeInitialized &&
mShutterButton.getVisibility() == View.VISIBLE) {
if (event.getRepeatCount() == 0) {
onShutterButtonFocus(true);
}
return true;
}
return false;
case KeyEvent.KEYCODE_CAMERA:
if (mFirstTimeInitialized && event.getRepeatCount() == 0) {
// Only capture when in full screen capture mode
if (mActivity.isInCameraApp() && mShutterButton.getVisibility() == View.VISIBLE)
onShutterButtonClick();
}
return true;
case KeyEvent.KEYCODE_DPAD_CENTER:
// If we get a dpad center event without any focused view, move
// the focus to the shutter button and press it.
if (mFirstTimeInitialized && event.getRepeatCount() == 0) {
// Start auto-focus immediately to reduce shutter lag. After
// the shutter button gets the focus, onShutterButtonFocus()
// will be called again but it is fine.
if (mUI.removeTopLevelPopup()) return true;
onShutterButtonFocus(true);
mUI.pressShutterButton();
}
return true;
}
return false;
}
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_VOLUME_UP:
case KeyEvent.KEYCODE_VOLUME_DOWN:
return true;
case KeyEvent.KEYCODE_FOCUS:
if (mFirstTimeInitialized) {
onShutterButtonFocus(false);
}
return true;
}
return false;
}
@TargetApi(ApiHelper.VERSION_CODES.ICE_CREAM_SANDWICH)
private void closeCamera() {
if (mCameraDevice != null) {
mCameraDevice.setZoomChangeListener(null);
if(ApiHelper.HAS_FACE_DETECTION) {
mCameraDevice.setFaceDetectionListener(null);
}
mCameraDevice.setErrorCallback(null);
CameraHolder.instance().release();
mFaceDetectionStarted = false;
mCameraDevice = null;
setCameraState(PREVIEW_STOPPED);
mFocusManager.onCameraReleased();
}
}
private void setDisplayOrientation() {
mDisplayRotation = Util.getDisplayRotation(mActivity);
mDisplayOrientation = Util.getDisplayOrientation(mDisplayRotation, mCameraId);
mCameraDisplayOrientation = Util.getDisplayOrientation(0, mCameraId);
mUI.setDisplayOrientation(mDisplayOrientation);
if (mFocusManager != null) {
mFocusManager.setDisplayOrientation(mDisplayOrientation);
}
// GLRoot also uses the DisplayRotation, and needs to be told to layout to update
mActivity.getGLRoot().requestLayoutContentPane();
}
// Only called by UI thread.
private void setupPreview() {
mFocusManager.resetTouchFocus();
startPreview();
setCameraState(IDLE);
startFaceDetection();
}
// This can be called by UI Thread or CameraStartUpThread. So this should
// not modify the views.
private void startPreview() {
mCameraDevice.setErrorCallback(mErrorCallback);
// ICS camera frameworks has a bug. Face detection state is not cleared
// after taking a picture. Stop the preview to work around it. The bug
// was fixed in JB.
if (mCameraState != PREVIEW_STOPPED &&
(!mActivity.getResources().getBoolean(R.bool.previewStopsDuringSnapshot) ||
mCameraState != SNAPSHOT_IN_PROGRESS)) {
stopPreview();
}
setDisplayOrientation();
if (!mSnapshotOnIdle && !mAspectRatioChanged) {
// If the focus mode is continuous autofocus, call cancelAutoFocus to
// resume it because it may have been paused by autoFocus call.
if (Util.FOCUS_MODE_CONTINUOUS_PICTURE.equals(mFocusManager.getFocusMode())
&& mCameraState != PREVIEW_STOPPED) {
mCameraDevice.cancelAutoFocus();
}
mFocusManager.setAeAwbLock(false); // Unlock AE and AWB.
}
setCameraParameters(UPDATE_PARAM_ALL);
if (ApiHelper.HAS_SURFACE_TEXTURE) {
if (mUI.getSurfaceTexture() == null) {
if (mCameraStartUpThread != null && mCameraStartUpThread.isCanceled()) {
return; // Exiting, so no need to get the surface texture.
}
}
SurfaceTexture texture = mActivity.getScreenNailTextureForPreviewSize(
mCameraId, mCameraDisplayOrientation, mParameters);
mUI.setSurfaceTexture(texture);
mCameraDevice.setDisplayOrientation(mCameraDisplayOrientation);
if (texture == null) {
if (mCameraStartUpThread != null && mCameraStartUpThread.isCanceled()) {
return; // Exiting, so no need to get the surface texture.
}
} else {
mCameraDevice.setPreviewTextureAsync(texture);
}
} else {
mCameraDevice.setDisplayOrientation(mDisplayOrientation);
mCameraDevice.setPreviewDisplayAsync(mUI.getSurfaceHolder());
}
Log.v(TAG, "startPreview");
mCameraDevice.startPreviewAsync();
mFocusManager.onPreviewStarted();
// Set camera mode
CameraSettings.setVideoMode(mParameters, false);
mCameraDevice.setParameters(mParameters);
if (mSnapshotOnIdle) {
mHandler.post(mDoSnapRunnable);
}
}
@Override
public void stopPreview() {
if (mCameraDevice != null && mCameraState != PREVIEW_STOPPED) {
Log.v(TAG, "stopPreview");
mCameraDevice.stopPreview();
//mFaceDetectionStarted = false;
}
setCameraState(PREVIEW_STOPPED);
if (mFocusManager != null) mFocusManager.onPreviewStopped();
}
@SuppressWarnings("deprecation")
private void updateCameraParametersInitialize() {
// Reset preview frame rate to the maximum because it may be lowered by
// video camera application.
List<Integer> frameRates = mParameters.getSupportedPreviewFrameRates();
if (frameRates != null) {
Integer max = Collections.max(frameRates);
mParameters.setPreviewFrameRate(max);
}
CameraSettings.setReducePurple(mParameters, true);
mParameters.set(Util.RECORDING_HINT, Util.FALSE);
// Disable video stabilization. Convenience methods not available in API
// level <= 14
String vstabSupported = mParameters.get("video-stabilization-supported");
if ("true".equals(vstabSupported)) {
mParameters.set("video-stabilization", "false");
}
// Enable face detection if needed
List<String> faceSupported = mParameters.getSupportedFaceDetectionModes();
if (faceSupported != null && faceSupported.contains("on")) {
mParameters.setFaceDetectionMode("on");
}
}
private void updateCameraParametersZoom() {
// Set zoom.
if (mParameters.isZoomSupported()) {
mParameters.setZoom(mZoomValue);
}
}
@TargetApi(ApiHelper.VERSION_CODES.JELLY_BEAN)
private void setAutoExposureLockIfSupported() {
if (mAeLockSupported) {
mParameters.setAutoExposureLock(mFocusManager.getAeAwbLock());
}
}
@TargetApi(ApiHelper.VERSION_CODES.JELLY_BEAN)
private void setAutoWhiteBalanceLockIfSupported() {
if (mAwbLockSupported) {
mParameters.setAutoWhiteBalanceLock(mFocusManager.getAeAwbLock());
}
}
@TargetApi(ApiHelper.VERSION_CODES.ICE_CREAM_SANDWICH)
private void setFocusAreasIfSupported() {
if (mFocusAreaSupported) {
mParameters.setFocusAreas(mFocusManager.getFocusAreas());
}
}
@TargetApi(ApiHelper.VERSION_CODES.ICE_CREAM_SANDWICH)
private void setMeteringAreasIfSupported() {
if (mMeteringAreaSupported) {
// Use the same area for focus and metering.
mParameters.setMeteringAreas(mFocusManager.getMeteringAreas());
}
}
private void updateCameraParametersPreference() {
setAutoExposureLockIfSupported();
setAutoWhiteBalanceLockIfSupported();
setFocusAreasIfSupported();
setMeteringAreasIfSupported();
// Set picture size.
String pictureSize = mPreferences.getString(
CameraSettings.KEY_PICTURE_SIZE, null);
if (pictureSize == null) {
CameraSettings.initialCameraPictureSize(mActivity, mParameters);
} else {
Size oldSize = mParameters.getPictureSize();
List<Size> supported = mParameters.getSupportedPictureSizes();
CameraSettings.setCameraPictureSize(
pictureSize, supported, mParameters);
Size size = mParameters.getPictureSize();
if (oldSize != null && size != null) {
if (!size.equals(oldSize) && mCameraState != PREVIEW_STOPPED) {
Log.d(TAG, "Picture size changed. Restart preview");
mAspectRatioChanged = true;
stopPreview();
}
}
}
Size size = mParameters.getPictureSize();
// Set a preview size that is closest to the viewfinder height and has
// the right aspect ratio.
List<Size> sizes = mParameters.getSupportedPreviewSizes();
Size optimalSize = Util.getOptimalPreviewSize(mActivity, sizes,
(double) size.width / size.height);
Size original = mParameters.getPreviewSize();
if (!original.equals(optimalSize)) {
mParameters.setPreviewSize(optimalSize.width, optimalSize.height);
// Zoom related settings will be changed for different preview
// sizes, so set and read the parameters to get latest values
if (mHandler.getLooper() == Looper.myLooper()) {
// On UI thread only, not when camera starts up
setupPreview();
} else {
mCameraDevice.setParameters(mParameters);
}
mParameters = mCameraDevice.getParameters();
}
Log.v(TAG, "Preview size is " + optimalSize.width + "x" + optimalSize.height);
// Since changing scene mode may change supported values, set scene mode
// first. HDR is a scene mode. To promote it in UI, it is stored in a
// separate preference.
String hdr = mPreferences.getString(CameraSettings.KEY_CAMERA_HDR,
mActivity.getString(R.string.pref_camera_hdr_default));
if (mActivity.getString(R.string.setting_on_value).equals(hdr)) {
mSceneMode = Util.SCENE_MODE_HDR;
} else {
mSceneMode = mPreferences.getString(
CameraSettings.KEY_SCENE_MODE,
mActivity.getString(R.string.pref_camera_scenemode_default));
}
if (Util.isSupported(mSceneMode, mParameters.getSupportedSceneModes())) {
if (!mParameters.getSceneMode().equals(mSceneMode)) {
mParameters.setSceneMode(mSceneMode);
// Setting scene mode will change the settings of flash mode,
// white balance, and focus mode. Here we read back the
// parameters, so we can know those settings.
mCameraDevice.setParameters(mParameters);
mParameters = mCameraDevice.getParameters();
}
} else {
mSceneMode = mParameters.getSceneMode();
if (mSceneMode == null) {
mSceneMode = Parameters.SCENE_MODE_AUTO;
}
}
if (Util.isZSLEnabled()) {
if (Util.sendMagicSamsungZSLCommand()) {
mCameraDevice.sendMagicSamsungZSLCommand();
}
// Switch on ZSL mode
mParameters.set("zsl", "on");
mParameters.set("camera-mode", "1");
}
// Set JPEG quality.
int jpegQuality = CameraProfile.getJpegEncodingQualityParameter(mCameraId,
CameraProfile.QUALITY_HIGH);
mParameters.setJpegQuality(jpegQuality);
// For the following settings, we need to check if the settings are
// still supported by latest driver, if not, ignore the settings.
// Set exposure compensation
int value = CameraSettings.readExposure(mPreferences);
int max = mParameters.getMaxExposureCompensation();
int min = mParameters.getMinExposureCompensation();
if (value >= min && value <= max) {
if (mSceneMode != Util.SCENE_MODE_HDR || !Util.needSamsungHDRFormat()) {
mParameters.setExposureCompensation(value);
}
} else {
Log.w(TAG, "invalid exposure range: " + value);
}
if (Parameters.SCENE_MODE_AUTO.equals(mSceneMode)) {
// Set flash mode.
String flashMode = mPreferences.getString(
CameraSettings.KEY_FLASH_MODE,
mActivity.getString(R.string.pref_camera_flashmode_default));
List<String> supportedFlash = mParameters.getSupportedFlashModes();
if (Util.isSupported(flashMode, supportedFlash)) {
mParameters.setFlashMode(flashMode);
} else {
flashMode = mParameters.getFlashMode();
if (flashMode == null) {
flashMode = mActivity.getString(
R.string.pref_camera_flashmode_no_flash);
}
}
// Set white balance parameter.
String whiteBalance = mPreferences.getString(
CameraSettings.KEY_WHITE_BALANCE,
mActivity.getString(R.string.pref_camera_whitebalance_default));
if (Util.isSupported(whiteBalance,
mParameters.getSupportedWhiteBalance())) {
mParameters.setWhiteBalance(whiteBalance);
} else {
whiteBalance = mParameters.getWhiteBalance();
if (whiteBalance == null) {
whiteBalance = Parameters.WHITE_BALANCE_AUTO;
}
}
// Set focus mode.
mFocusManager.overrideFocusMode(null);
mParameters.setFocusMode(mFocusManager.getFocusMode());
} else {
mFocusManager.overrideFocusMode(mParameters.getFocusMode());
}
if (mContinousFocusSupported && ApiHelper.HAS_AUTO_FOCUS_MOVE_CALLBACK) {
updateAutoFocusMoveCallback();
}
}
@TargetApi(ApiHelper.VERSION_CODES.JELLY_BEAN)
private void updateAutoFocusMoveCallback() {
if (mParameters.getFocusMode().equals(Util.FOCUS_MODE_CONTINUOUS_PICTURE)) {
mCameraDevice.setAutoFocusMoveCallback(
(AutoFocusMoveCallback) mAutoFocusMoveCallback);
} else {
mCameraDevice.setAutoFocusMoveCallback(null);
}
}
// We separate the parameters into several subsets, so we can update only
// the subsets actually need updating. The PREFERENCE set needs extra
// locking because the preference can be changed from GLThread as well.
private void setCameraParameters(int updateSet) {
if ((updateSet & UPDATE_PARAM_INITIALIZE) != 0) {
updateCameraParametersInitialize();
// Set camera mode
CameraSettings.setVideoMode(mParameters, false);
}
if ((updateSet & UPDATE_PARAM_ZOOM) != 0) {
updateCameraParametersZoom();
}
if ((updateSet & UPDATE_PARAM_PREFERENCE) != 0) {
updateCameraParametersPreference();
}
Util.dumpParameters(mParameters);
mCameraDevice.setParameters(mParameters);
}
// If the Camera is idle, update the parameters immediately, otherwise
// accumulate them in mUpdateSet and update later.
private void setCameraParametersWhenIdle(int additionalUpdateSet) {
mUpdateSet |= additionalUpdateSet;
if (mCameraDevice == null) {
// We will update all the parameters when we open the device, so
// we don't need to do anything now.
mUpdateSet = 0;
return;
} else if (isCameraIdle()) {
if (mRestartPreview) {
Log.d(TAG, "Restarting preview");
resizeForPreviewAspectRatio();
startPreview();
mRestartPreview = false;
}
setCameraParameters(mUpdateSet);
updateSceneMode();
mUpdateSet = 0;
} else {
if (!mHandler.hasMessages(SET_CAMERA_PARAMETERS_WHEN_IDLE)) {
mHandler.sendEmptyMessageDelayed(
SET_CAMERA_PARAMETERS_WHEN_IDLE, 1000);
}
}
if (mAspectRatioChanged || mRestartPreview) {
Log.e(TAG, "Aspect ratio changed, restarting preview");
startPreview();
mAspectRatioChanged = false;
mRestartPreview = false;
mHandler.sendEmptyMessage(START_PREVIEW_DONE);
}
}
public boolean isCameraIdle() {
return (mCameraState == IDLE) ||
(mCameraState == PREVIEW_STOPPED) ||
((mFocusManager != null) && mFocusManager.isFocusCompleted()
&& (mCameraState != SWITCHING_CAMERA));
}
public boolean isImageCaptureIntent() {
String action = mActivity.getIntent().getAction();
return (MediaStore.ACTION_IMAGE_CAPTURE.equals(action)
|| ActivityBase.ACTION_IMAGE_CAPTURE_SECURE.equals(action));
}
private void setupCaptureParams() {
Bundle myExtras = mActivity.getIntent().getExtras();
if (myExtras != null) {
mSaveUri = (Uri) myExtras.getParcelable(MediaStore.EXTRA_OUTPUT);
mCropValue = myExtras.getString("crop");
}
}
@Override
public void onSharedPreferenceChanged() {
// ignore the events after "onPause()"
if (mPaused) return;
boolean recordLocation = RecordLocationPreference.get(
mPreferences, mContentResolver);
mLocationManager.recordLocation(recordLocation);
if (mActivity.setStoragePath(mPreferences)) {
mActivity.updateStorageSpaceAndHint();
mActivity.reuseCameraScreenNail(!mIsImageCaptureIntent);
}
/* Check if the PhotoUI Menu is initialized or not. This
* should be initialized during onCameraOpen() which should
* have been called by now. But for some reason that is not
* executed till now, then schedule these functionality for
* later by posting a message to the handler */
if (mUI.mMenuInitialized) {
setCameraParametersWhenIdle(UPDATE_PARAM_PREFERENCE);
resizeForPreviewAspectRatio();
mUI.updateOnScreenIndicators(mParameters, mPreferenceGroup,
mPreferences);
} else {
mHandler.sendEmptyMessage(SET_PHOTO_UI_PARAMS);
}
}
@Override
public void onCameraPickerClicked(int cameraId) {
if (mPaused || mPendingSwitchCameraId != -1) return;
mPendingSwitchCameraId = cameraId;
if (ApiHelper.HAS_SURFACE_TEXTURE) {
Log.v(TAG, "Start to copy texture. cameraId=" + cameraId);
// We need to keep a preview frame for the animation before
// releasing the camera. This will trigger onPreviewTextureCopied.
((CameraScreenNail) mActivity.mCameraScreenNail).copyTexture();
// Disable all camera controls.
setCameraState(SWITCHING_CAMERA);
} else {
switchCamera();
}
}
@Override
public void onCameraPickerSuperClicked() {
}
// Preview texture has been copied. Now camera can be released and the
// animation can be started.
@Override
public void onPreviewTextureCopied() {
mHandler.sendEmptyMessage(SWITCH_CAMERA);
}
@Override
public void onCaptureTextureCopied() {
}
@Override
public void onUserInteraction() {
if (!mActivity.isFinishing()) keepScreenOnAwhile();
}
private void resetScreenOn() {
mHandler.removeMessages(CLEAR_SCREEN_DELAY);
mActivity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
private void keepScreenOnAwhile() {
mHandler.removeMessages(CLEAR_SCREEN_DELAY);
mActivity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
mHandler.sendEmptyMessageDelayed(CLEAR_SCREEN_DELAY, SCREEN_DELAY);
}
// TODO: Delete this function after old camera code is removed
@Override
public void onRestorePreferencesClicked() {
}
@Override
public void onOverriddenPreferencesClicked() {
if (mPaused) return;
mUI.showPreferencesToast();
}
private void showTapToFocusToast() {
// TODO: Use a toast?
new RotateTextToast(mActivity, R.string.tap_to_focus, 0).show();
// Clear the preference.
Editor editor = mPreferences.edit();
editor.putBoolean(CameraSettings.KEY_CAMERA_FIRST_USE_HINT_SHOWN, false);
editor.apply();
}
private void initializeCapabilities() {
mInitialParams = mCameraDevice.getParameters();
mFocusAreaSupported = Util.isFocusAreaSupported(mInitialParams);
mMeteringAreaSupported = Util.isMeteringAreaSupported(mInitialParams);
mAeLockSupported = Util.isAutoExposureLockSupported(mInitialParams);
mAwbLockSupported = Util.isAutoWhiteBalanceLockSupported(mInitialParams);
mContinousFocusSupported = mInitialParams.getSupportedFocusModes().contains(
Util.FOCUS_MODE_CONTINUOUS_PICTURE);
}
@Override
public void onCountDownFinished() {
mSnapshotOnIdle = false;
mFocusManager.doSnap();
mFocusManager.onShutterUp();
}
@Override
public boolean needsSwitcher() {
return !mIsImageCaptureIntent;
}
@Override
public boolean needsPieMenu() {
return true;
}
@Override
public void onShowSwitcherPopup() {
mUI.onShowSwitcherPopup();
}
@Override
public int onZoomChanged(int index) {
// Not useful to change zoom value when the activity is paused.
if (mPaused) return index;
mZoomValue = index;
if (mParameters == null || mCameraDevice == null) return index;
// Set zoom parameters asynchronously
mParameters.setZoom(mZoomValue);
mCameraDevice.setParameters(mParameters);
Parameters p = mCameraDevice.getParameters();
if (p != null) return p.getZoom();
return index;
}
@Override
public int getCameraState() {
return mCameraState;
}
@Override
public void onQueueStatus(boolean full) {
mUI.enableShutter(!full);
}
@Override
public void onMediaSaveServiceConnected(MediaSaveService s) {
// We set the listener only when both service and shutterbutton
// are initialized.
if (mFirstTimeInitialized) {
s.setListener(this);
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
@Override
public void onSensorChanged(SensorEvent event) {
int type = event.sensor.getType();
float[] data;
if (type == Sensor.TYPE_ACCELEROMETER) {
data = mGData;
} else if (type == Sensor.TYPE_MAGNETIC_FIELD) {
data = mMData;
} else {
// we should not be here.
return;
}
for (int i = 0; i < 3 ; i++) {
data[i] = event.values[i];
}
float[] orientation = new float[3];
SensorManager.getRotationMatrix(mR, null, mGData, mMData);
SensorManager.getOrientation(mR, orientation);
mHeading = (int) (orientation[0] * 180f / Math.PI) % 360;
if (mHeading < 0) {
mHeading += 360;
}
}
}
| true | true | public void onPictureTaken(
final byte [] jpegData, final android.hardware.Camera camera) {
if (mPaused) {
return;
}
if (mSceneMode == Util.SCENE_MODE_HDR) {
mActivity.showSwitcher();
mActivity.setSwipingEnabled(true);
}
mJpegPictureCallbackTime = System.currentTimeMillis();
// If postview callback has arrived, the captured image is displayed
// in postview callback. If not, the captured image is displayed in
// raw picture callback.
if (mPostViewPictureCallbackTime != 0) {
mShutterToPictureDisplayedTime =
mPostViewPictureCallbackTime - mShutterCallbackTime;
mPictureDisplayedToJpegCallbackTime =
mJpegPictureCallbackTime - mPostViewPictureCallbackTime;
} else {
mShutterToPictureDisplayedTime =
mRawPictureCallbackTime - mShutterCallbackTime;
mPictureDisplayedToJpegCallbackTime =
mJpegPictureCallbackTime - mRawPictureCallbackTime;
}
Log.v(TAG, "mPictureDisplayedToJpegCallbackTime = "
+ mPictureDisplayedToJpegCallbackTime + "ms");
// Only animate when in full screen capture mode
// i.e. If monkey/a user swipes to the gallery during picture taking,
// don't show animation
if (ApiHelper.HAS_SURFACE_TEXTURE && !mIsImageCaptureIntent
&& mActivity.mShowCameraAppView) {
// Finish capture animation
mHandler.removeMessages(CAPTURE_ANIMATION_DONE);
((CameraScreenNail) mActivity.mCameraScreenNail).animateSlide();
mHandler.sendEmptyMessageDelayed(CAPTURE_ANIMATION_DONE,
CaptureAnimManager.getAnimationDuration());
}
mFocusManager.updateFocusUI(); // Ensure focus indicator is hidden.
boolean isSamsungHDR =
(mSceneMode == Util.SCENE_MODE_HDR && Util.needSamsungHDRFormat());
if (!mIsImageCaptureIntent && (!Util.isZSLEnabled() || isSamsungHDR)) {
if (ApiHelper.CAN_START_PREVIEW_IN_JPEG_CALLBACK) {
setupPreview();
} else {
// Camera HAL of some devices have a bug. Starting preview
// immediately after taking a picture will fail. Wait some
// time before starting the preview.
mHandler.sendEmptyMessageDelayed(SETUP_PREVIEW, 300);
}
} else if (Util.isZSLEnabled() && !isSamsungHDR) {
// In ZSL mode, the preview is not stopped, due to which the
// review mode (ImageCapture) doesn't show the captured frame.
// Hence stop the preview if ZSL mode is active so that the
// preview can be restarted using the onReviewRetakeClicked().
if (mIsImageCaptureIntent) {
stopPreview();
} else {
mFocusManager.resetTouchFocus();
setCameraState(IDLE);
}
}
if (!mIsImageCaptureIntent) {
// Calculate the width and the height of the jpeg.
Size s = mParameters.getPictureSize();
final ExifInterface exif = Exif.getExif(jpegData);
final int orientation = Exif.getOrientation(exif);
final int width, height;
if ((mJpegRotation + orientation) % 180 == 0 || isSamsungHDR) {
width = s.width;
height = s.height;
} else {
width = s.height;
height = s.width;
}
final String title = mNamedImages.getTitle();
long date = mNamedImages.getDate();
if (title == null) {
Log.e(TAG, "Unbalanced name/data pair");
} else {
if (date == -1) date = mCaptureStartTime;
if (mHeading >= 0) {
// heading direction has been updated by the sensor.
ExifTag directionRefTag = exif.buildTag(
ExifInterface.TAG_GPS_IMG_DIRECTION_REF,
ExifInterface.GpsTrackRef.MAGNETIC_DIRECTION);
ExifTag directionTag = exif.buildTag(
ExifInterface.TAG_GPS_IMG_DIRECTION,
new Rational(mHeading, 1));
exif.setTag(directionRefTag);
exif.setTag(directionTag);
}
if (mLocation != null) {
exif.addGpsTags(mLocation.getLatitude(), mLocation.getLongitude());
exif.addGpsDateTimeStampTag(date);
exif.setTag(exif.buildTag(ExifInterface.TAG_GPS_PROCESSING_METHOD,
mLocation.getProvider()));
}
exif.addDateTimeStampTag(ExifInterface.TAG_DATE_TIME,
date, TimeZone.getDefault());
if (isSamsungHDR) {
final long finalDate = date;
new Thread(new Runnable() {
public void run() {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Bitmap bm = Util.decodeYUV422P(jpegData, width, height);
if (mJpegRotation != 0) {
Matrix matrix = new Matrix();
matrix.postRotate(mJpegRotation);
bm = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, true);
}
bm.compress(Bitmap.CompressFormat.JPEG,
CameraSettings.getJpegQualityIntValue(mPreferences),
baos);
boolean rotated = (mJpegRotation % 180) != 0;
mActivity.getMediaSaveService().addImage(
baos.toByteArray(), title, finalDate, mLocation,
rotated ? height : width, rotated ? width : height,
orientation, exif, mOnMediaSavedListener, mContentResolver);
}
}).start();
} else {
mActivity.getMediaSaveService().addImage(
jpegData, title, date, mLocation, width, height,
orientation, exif, mOnMediaSavedListener, mContentResolver);
}
}
} else {
mJpegImageData = jpegData;
if (!mQuickCapture) {
mUI.showPostCaptureAlert();
} else {
onCaptureDone();
}
}
// Check this in advance of each shot so we don't add to shutter
// latency. It's true that someone else could write to the SD card in
// the mean time and fill it, but that could have happened between the
// shutter press and saving the JPEG too.
mActivity.updateStorageSpaceAndHint();
long now = System.currentTimeMillis();
mJpegCallbackFinishTime = now - mJpegPictureCallbackTime;
Log.v(TAG, "mJpegCallbackFinishTime = "
+ mJpegCallbackFinishTime + "ms");
mJpegPictureCallbackTime = 0;
}
| public void onPictureTaken(
final byte [] jpegData, final android.hardware.Camera camera) {
if (mPaused) {
return;
}
if (mSceneMode == Util.SCENE_MODE_HDR) {
mActivity.showSwitcher();
mActivity.setSwipingEnabled(true);
}
mJpegPictureCallbackTime = System.currentTimeMillis();
// If postview callback has arrived, the captured image is displayed
// in postview callback. If not, the captured image is displayed in
// raw picture callback.
if (mPostViewPictureCallbackTime != 0) {
mShutterToPictureDisplayedTime =
mPostViewPictureCallbackTime - mShutterCallbackTime;
mPictureDisplayedToJpegCallbackTime =
mJpegPictureCallbackTime - mPostViewPictureCallbackTime;
} else {
mShutterToPictureDisplayedTime =
mRawPictureCallbackTime - mShutterCallbackTime;
mPictureDisplayedToJpegCallbackTime =
mJpegPictureCallbackTime - mRawPictureCallbackTime;
}
Log.v(TAG, "mPictureDisplayedToJpegCallbackTime = "
+ mPictureDisplayedToJpegCallbackTime + "ms");
// Only animate when in full screen capture mode
// i.e. If monkey/a user swipes to the gallery during picture taking,
// don't show animation
if (ApiHelper.HAS_SURFACE_TEXTURE && !mIsImageCaptureIntent
&& mActivity.mShowCameraAppView) {
// Finish capture animation
mHandler.removeMessages(CAPTURE_ANIMATION_DONE);
((CameraScreenNail) mActivity.mCameraScreenNail).animateSlide();
mHandler.sendEmptyMessageDelayed(CAPTURE_ANIMATION_DONE,
CaptureAnimManager.getAnimationDuration());
}
mFocusManager.updateFocusUI(); // Ensure focus indicator is hidden.
boolean isSamsungHDR =
(mSceneMode == Util.SCENE_MODE_HDR && Util.needSamsungHDRFormat());
if (!mIsImageCaptureIntent && (!Util.isZSLEnabled() || isSamsungHDR)) {
if (ApiHelper.CAN_START_PREVIEW_IN_JPEG_CALLBACK) {
setupPreview();
} else {
// Camera HAL of some devices have a bug. Starting preview
// immediately after taking a picture will fail. Wait some
// time before starting the preview.
mHandler.sendEmptyMessageDelayed(SETUP_PREVIEW, 300);
}
} else {
mFocusManager.resetTouchFocus();
setCameraState(IDLE);
}
if (!mIsImageCaptureIntent) {
// Calculate the width and the height of the jpeg.
Size s = mParameters.getPictureSize();
final ExifInterface exif = Exif.getExif(jpegData);
final int orientation = Exif.getOrientation(exif);
final int width, height;
if ((mJpegRotation + orientation) % 180 == 0 || isSamsungHDR) {
width = s.width;
height = s.height;
} else {
width = s.height;
height = s.width;
}
final String title = mNamedImages.getTitle();
long date = mNamedImages.getDate();
if (title == null) {
Log.e(TAG, "Unbalanced name/data pair");
} else {
if (date == -1) date = mCaptureStartTime;
if (mHeading >= 0) {
// heading direction has been updated by the sensor.
ExifTag directionRefTag = exif.buildTag(
ExifInterface.TAG_GPS_IMG_DIRECTION_REF,
ExifInterface.GpsTrackRef.MAGNETIC_DIRECTION);
ExifTag directionTag = exif.buildTag(
ExifInterface.TAG_GPS_IMG_DIRECTION,
new Rational(mHeading, 1));
exif.setTag(directionRefTag);
exif.setTag(directionTag);
}
if (mLocation != null) {
exif.addGpsTags(mLocation.getLatitude(), mLocation.getLongitude());
exif.addGpsDateTimeStampTag(date);
exif.setTag(exif.buildTag(ExifInterface.TAG_GPS_PROCESSING_METHOD,
mLocation.getProvider()));
}
exif.addDateTimeStampTag(ExifInterface.TAG_DATE_TIME,
date, TimeZone.getDefault());
if (isSamsungHDR) {
final long finalDate = date;
new Thread(new Runnable() {
public void run() {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Bitmap bm = Util.decodeYUV422P(jpegData, width, height);
if (mJpegRotation != 0) {
Matrix matrix = new Matrix();
matrix.postRotate(mJpegRotation);
bm = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, true);
}
bm.compress(Bitmap.CompressFormat.JPEG,
CameraSettings.getJpegQualityIntValue(mPreferences),
baos);
boolean rotated = (mJpegRotation % 180) != 0;
mActivity.getMediaSaveService().addImage(
baos.toByteArray(), title, finalDate, mLocation,
rotated ? height : width, rotated ? width : height,
orientation, exif, mOnMediaSavedListener, mContentResolver);
}
}).start();
} else {
mActivity.getMediaSaveService().addImage(
jpegData, title, date, mLocation, width, height,
orientation, exif, mOnMediaSavedListener, mContentResolver);
}
}
} else {
mJpegImageData = jpegData;
if (!mQuickCapture) {
mUI.showPostCaptureAlert();
} else {
onCaptureDone();
}
}
// Check this in advance of each shot so we don't add to shutter
// latency. It's true that someone else could write to the SD card in
// the mean time and fill it, but that could have happened between the
// shutter press and saving the JPEG too.
mActivity.updateStorageSpaceAndHint();
long now = System.currentTimeMillis();
mJpegCallbackFinishTime = now - mJpegPictureCallbackTime;
Log.v(TAG, "mJpegCallbackFinishTime = "
+ mJpegCallbackFinishTime + "ms");
mJpegPictureCallbackTime = 0;
}
|
diff --git a/src/net/mcft/copy/betterstorage/block/BlockReinforcedChest.java b/src/net/mcft/copy/betterstorage/block/BlockReinforcedChest.java
index a1524ca..d33f300 100644
--- a/src/net/mcft/copy/betterstorage/block/BlockReinforcedChest.java
+++ b/src/net/mcft/copy/betterstorage/block/BlockReinforcedChest.java
@@ -1,180 +1,181 @@
package net.mcft.copy.betterstorage.block;
import java.util.List;
import java.util.Random;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.mcft.copy.betterstorage.api.BetterStorageEnchantment;
import net.mcft.copy.betterstorage.api.IKey;
import net.mcft.copy.betterstorage.api.ILock;
import net.mcft.copy.betterstorage.proxy.ClientProxy;
import net.mcft.copy.betterstorage.utils.DirectionUtils;
import net.mcft.copy.betterstorage.utils.StackUtils;
import net.mcft.copy.betterstorage.utils.WorldUtils;
import net.minecraft.block.Block;
import net.minecraft.block.BlockContainer;
import net.minecraft.block.material.Material;
import net.minecraft.client.renderer.texture.IconRegister;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLiving;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import net.minecraftforge.common.ForgeDirection;
import net.minecraftforge.common.MinecraftForge;
public class BlockReinforcedChest extends BlockContainer {
public BlockReinforcedChest(int id) {
super(id, Material.wood);
setHardness(8.0f);
setResistance(20.0f);
setStepSound(Block.soundWoodFootstep);
setBlockBounds(0.0625F, 0.0F, 0.0625F, 0.9375F, 0.875F, 0.9375F);
MinecraftForge.setBlockHarvestLevel(this, "axe", 2);
}
@Override
@SideOnly(Side.CLIENT)
public void registerIcons(IconRegister iconRegister) {
blockIcon = iconRegister.registerIcon("tree_side");
}
@Override
public boolean isOpaqueCube() { return false; }
@Override
public boolean renderAsNormalBlock() { return false; }
@Override
@SideOnly(Side.CLIENT)
public int getRenderType() { return ClientProxy.reinforcedChestRenderId; }
@Override
public int damageDropped(int metadata) { return metadata; }
@Override
public void getSubBlocks(int id, CreativeTabs tab, List list) {
for (ChestMaterial material : ChestMaterial.materials)
list.add(new ItemStack(id, 1, material.id));
}
@Override
public float getBlockHardness(World world, int x, int y, int z) {
TileEntityReinforcedChest chest = WorldUtils.get(world, x, y, z, TileEntityReinforcedChest.class);
float hardness = blockHardness;
if (chest != null && chest.getLock() != null) {
hardness *= 15.0F;
int persistance = BetterStorageEnchantment.getLevel(chest.getLock(), "persistance");
if (persistance > 0) hardness *= persistance + 2;
}
return hardness;
}
@Override
public float getExplosionResistance(Entity entity, World world, int x, int y, int z, double explosionX, double explosionY, double explosionZ) {
float modifier = 1.0F;
TileEntityReinforcedChest chest = WorldUtils.get(world, x, y, z, TileEntityReinforcedChest.class);
if (chest != null) {
int persistance = BetterStorageEnchantment.getLevel(chest.getLock(), "persistance");
if (persistance > 0) modifier += Math.pow(2, persistance);
}
return super.getExplosionResistance(entity) * modifier;
}
@Override
public void setBlockBoundsBasedOnState(IBlockAccess world, int x, int y, int z) {
TileEntityReinforcedChest chest = WorldUtils.get(world, x, y, z, TileEntityReinforcedChest.class);
if (chest.isConnected()) {
if (chest.connected == ForgeDirection.NORTH)
setBlockBounds(0.0625F, 0.0F, 0.0F, 0.9375F, 0.875F, 0.9375F);
else if (chest.connected == ForgeDirection.SOUTH)
setBlockBounds(0.0625F, 0.0F, 0.0625F, 0.9375F, 0.875F, 1.0F);
else if (chest.connected == ForgeDirection.WEST)
setBlockBounds(0.0F, 0.0F, 0.0625F, 0.9375F, 0.875F, 0.9375F);
else if (chest.connected == ForgeDirection.EAST)
setBlockBounds(0.0625F, 0.0F, 0.0625F, 1.0F, 0.875F, 0.9375F);
} else setBlockBounds(0.0625F, 0.0F, 0.0625F, 0.9375F, 0.875F, 0.9375F);
}
@Override
public void onBlockPlacedBy(World world, int x, int y, int z, EntityLiving player, ItemStack stack) {
TileEntityReinforcedChest chest = WorldUtils.get(world, x, y, z, TileEntityReinforcedChest.class);
chest.orientation = DirectionUtils.getOrientation(player).getOpposite();
chest.checkForConnections();
}
@Override
public void breakBlock(World world, int x, int y, int z, int id, int meta) {
TileEntityReinforcedChest chest = WorldUtils.get(world, x, y, z, TileEntityReinforcedChest.class);
super.breakBlock(world, x, y, z, id, meta);
if (chest != null) {
chest.dropContents();
chest.disconnect();
}
}
@Override
public TileEntity createNewTileEntity(World world) {
return new TileEntityReinforcedChest();
}
@Override
public boolean onBlockActivated(World world, int x, int y, int z, EntityPlayer player, int par6, float par7, float par8, float par9) {
if (world.isRemote) return true;
TileEntityReinforcedChest chest = WorldUtils.get(world, x, y, z, TileEntityReinforcedChest.class);
ItemStack holding = player.getHeldItem();
ItemStack lock = chest.getLock();
ItemStack key = (StackUtils.isKey(holding) ? holding : null);
ILock lockType = ((lock != null) ? (ILock)lock.getItem() : null);
IKey keyType = ((key != null) ? (IKey)key.getItem() : null);
// If the chest isn't locked and item held is
// a lock, use it instead of opening the chest.
if (lock == null && StackUtils.isLock(holding))
return false;
boolean success = (lock == null || chest.canUse(player) ||
(key != null && keyType.unlock(key, lock, true)));
- lockType.onUnlock(lock, key, chest, player, success);
+ if (lockType != null)
+ lockType.onUnlock(lock, key, chest, player, success);
if (success) chest.openGui(player);
return true;
}
@Override
public void onBlockClicked(World world, int x, int y, int z, EntityPlayer player) {
if (world.isRemote) return;
TileEntityReinforcedChest chest = WorldUtils.get(world, x, y, z, TileEntityReinforcedChest.class);
ItemStack lock = chest.getLock();
if (lock == null) return;
ILock lockType = (ILock)lock.getItem();
lockType.applyEffects(lock, chest, player, 3);
}
// Trigger enchantment related
@Override
public boolean canProvidePower() { return true; }
@Override
public int isProvidingWeakPower(IBlockAccess world, int x, int y, int z, int side) {
return (WorldUtils.get(world, x, y, z, TileEntityReinforcedChest.class).isPowered() ? 15 : 0);
}
@Override
public int isProvidingStrongPower(IBlockAccess world, int x, int y, int z, int side) {
return isProvidingWeakPower(world, x, y, z, side);
}
@Override
public void updateTick(World world, int x, int y, int z, Random random) {
WorldUtils.get(world, x, y, z, TileEntityReinforcedChest.class).setPowered(false);
}
}
| true | true | public boolean onBlockActivated(World world, int x, int y, int z, EntityPlayer player, int par6, float par7, float par8, float par9) {
if (world.isRemote) return true;
TileEntityReinforcedChest chest = WorldUtils.get(world, x, y, z, TileEntityReinforcedChest.class);
ItemStack holding = player.getHeldItem();
ItemStack lock = chest.getLock();
ItemStack key = (StackUtils.isKey(holding) ? holding : null);
ILock lockType = ((lock != null) ? (ILock)lock.getItem() : null);
IKey keyType = ((key != null) ? (IKey)key.getItem() : null);
// If the chest isn't locked and item held is
// a lock, use it instead of opening the chest.
if (lock == null && StackUtils.isLock(holding))
return false;
boolean success = (lock == null || chest.canUse(player) ||
(key != null && keyType.unlock(key, lock, true)));
lockType.onUnlock(lock, key, chest, player, success);
if (success) chest.openGui(player);
return true;
}
| public boolean onBlockActivated(World world, int x, int y, int z, EntityPlayer player, int par6, float par7, float par8, float par9) {
if (world.isRemote) return true;
TileEntityReinforcedChest chest = WorldUtils.get(world, x, y, z, TileEntityReinforcedChest.class);
ItemStack holding = player.getHeldItem();
ItemStack lock = chest.getLock();
ItemStack key = (StackUtils.isKey(holding) ? holding : null);
ILock lockType = ((lock != null) ? (ILock)lock.getItem() : null);
IKey keyType = ((key != null) ? (IKey)key.getItem() : null);
// If the chest isn't locked and item held is
// a lock, use it instead of opening the chest.
if (lock == null && StackUtils.isLock(holding))
return false;
boolean success = (lock == null || chest.canUse(player) ||
(key != null && keyType.unlock(key, lock, true)));
if (lockType != null)
lockType.onUnlock(lock, key, chest, player, success);
if (success) chest.openGui(player);
return true;
}
|
diff --git a/core/java/src/net/i2p/client/naming/SingleFileNamingService.java b/core/java/src/net/i2p/client/naming/SingleFileNamingService.java
index f00102c46..30722a04f 100644
--- a/core/java/src/net/i2p/client/naming/SingleFileNamingService.java
+++ b/core/java/src/net/i2p/client/naming/SingleFileNamingService.java
@@ -1,453 +1,454 @@
/*
* free (adj.): unencumbered; not under the control of others
* Written by mihi in 2004 and released into the public domain
* with no warranty of any kind, either expressed or implied.
* It probably won't make your computer catch on fire, or eat
* your children, but it might. Use at your own risk.
*/
package net.i2p.client.naming;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import net.i2p.I2PAppContext;
import net.i2p.data.DataFormatException;
import net.i2p.data.DataHelper;
import net.i2p.data.Destination;
import net.i2p.util.FileUtil;
import net.i2p.util.Log;
import net.i2p.util.SecureFile;
import net.i2p.util.SecureFileOutputStream;
/**
* A naming service based on a single file using the "hosts.txt" format.
* Supports adds, removes, and listeners.
*
* All methods here are case-sensitive.
* Conversion to lower case is done in HostsTxtNamingService.
*
* This does NOT provide .b32.i2p or {b64} resolution.
* It also does not do any caching.
* Use from HostsTxtNamingService or chain with another NamingService
* via MetaNamingService if you need those features.
*
* @since 0.8.5
*/
public class SingleFileNamingService extends NamingService {
private final static Log _log = new Log(SingleFileNamingService.class);
private final File _file;
private final ReentrantReadWriteLock _fileLock;
/** cached number of entries */
private int _size;
/** last write time */
private long _lastWrite;
public SingleFileNamingService(I2PAppContext context, String filename) {
super(context);
File file = new File(filename);
if (!file.isAbsolute())
file = new File(context.getRouterDir(), filename);
_file = file;
_fileLock = new ReentrantReadWriteLock(true);
}
/**
* @return the base file name
*/
@Override
public String getName() {
return _file.getAbsolutePath();
}
/**
* @param hostname case-sensitive; caller should convert to lower case
* @param lookupOptions ignored
* @param storedOptions ignored
*/
@Override
public Destination lookup(String hostname, Properties lookupOptions, Properties storedOptions) {
try {
String key = getKey(hostname);
if (key != null)
return lookupBase64(key);
} catch (Exception ioe) {
if (_file.exists())
_log.error("Error loading hosts file " + _file, ioe);
else if (_log.shouldLog(Log.WARN))
_log.warn("Error loading hosts file " + _file, ioe);
}
return null;
}
/**
* @param options ignored
*/
@Override
public String reverseLookup(Destination dest, Properties options) {
String destkey = dest.toBase64();
BufferedReader in = null;
getReadLock();
try {
in = new BufferedReader(new InputStreamReader(new FileInputStream(_file), "UTF-8"), 16*1024);
String line = null;
while ( (line = in.readLine()) != null) {
if (line.startsWith("#"))
continue;
if (line.indexOf('#') > 0) // trim off any end of line comment
line = line.substring(0, line.indexOf('#')).trim();
int split = line.indexOf('=');
if (split <= 0)
continue;
if (destkey.equals(line.substring(split + 1)))
return line.substring(0, split);
}
return null;
} catch (Exception ioe) {
if (_file.exists())
_log.error("Error loading hosts file " + _file, ioe);
else if (_log.shouldLog(Log.WARN))
_log.warn("Error loading hosts file " + _file, ioe);
return null;
} finally {
releaseReadLock();
}
}
/**
* Better than DataHelper.loadProps(), doesn't load the whole file into memory,
* and stops when it finds a match.
*
* @param host case-sensitive; caller should convert to lower case
*/
private String getKey(String host) throws IOException {
BufferedReader in = null;
getReadLock();
try {
in = new BufferedReader(new InputStreamReader(new FileInputStream(_file), "UTF-8"), 16*1024);
String line = null;
String search = host + '=';
while ( (line = in.readLine()) != null) {
if (!line.startsWith(search))
continue;
if (line.indexOf('#') > 0) // trim off any end of line comment
line = line.substring(0, line.indexOf('#')).trim();
int split = line.indexOf('=');
return line.substring(split+1); //.trim() ??????????????
}
} finally {
if (in != null) try { in.close(); } catch (IOException ioe) {}
releaseReadLock();
}
return null;
}
/**
* @param hostname case-sensitive; caller should convert to lower case
* @param options ignored
*/
@Override
public boolean put(String hostname, Destination d, Properties options) {
// try easy way first, most adds are not replaces
if (putIfAbsent(hostname, d, options))
return true;
if (!getWriteLock())
return false;
BufferedReader in = null;
BufferedWriter out = null;
try {
File tmp = SecureFile.createTempFile("temp-", ".tmp", _file.getAbsoluteFile().getParentFile());
out = new BufferedWriter(new OutputStreamWriter(new SecureFileOutputStream(tmp), "UTF-8"));
if (_file.exists()) {
in = new BufferedReader(new InputStreamReader(new FileInputStream(_file), "UTF-8"), 16*1024);
String line = null;
String search = hostname + '=';
while ( (line = in.readLine()) != null) {
if (line.startsWith(search))
continue;
out.write(line);
out.newLine();
}
in.close();
}
out.write(hostname);
out.write('=');
out.write(d.toBase64());
out.newLine();
out.close();
boolean success = rename(tmp, _file);
if (success) {
for (NamingServiceListener nsl : _listeners) {
nsl.entryChanged(this, hostname, d, options);
}
}
return success;
} catch (IOException ioe) {
if (in != null) try { in.close(); } catch (IOException e) {}
if (out != null) try { out.close(); } catch (IOException e) {}
_log.error("Error adding " + hostname, ioe);
return false;
} finally { releaseWriteLock(); }
}
/**
* @param hostname case-sensitive; caller should convert to lower case
* @param options ignored
*/
@Override
public boolean putIfAbsent(String hostname, Destination d, Properties options) {
if (!getWriteLock())
return false;
OutputStream out = null;
try {
// simply check if present, and if not, append
try {
if (getKey(hostname) != null)
return false;
} catch (IOException ioe) {
if (_file.exists()) {
_log.error("Error adding " + hostname, ioe);
return false;
}
// else new file
}
out = new SecureFileOutputStream(_file, true);
// FIXME fails if previous last line didn't have a trailing \n
out.write(hostname.getBytes("UTF-8"));
out.write('=');
out.write(d.toBase64().getBytes());
out.write('\n');
out.close();
for (NamingServiceListener nsl : _listeners) {
nsl.entryAdded(this, hostname, d, options);
}
return true;
} catch (IOException ioe) {
if (out != null) try { out.close(); } catch (IOException e) {}
_log.error("Error adding " + hostname, ioe);
return false;
} finally { releaseWriteLock(); }
}
/**
* @param hostname case-sensitive; caller should convert to lower case
* @param options ignored
*/
@Override
public boolean remove(String hostname, Properties options) {
if (!getWriteLock())
return false;
if (!_file.exists())
return false;
BufferedReader in = null;
BufferedWriter out = null;
try {
in = new BufferedReader(new InputStreamReader(new FileInputStream(_file), "UTF-8"), 16*1024);
File tmp = SecureFile.createTempFile("temp-", ".tmp", _file.getAbsoluteFile().getParentFile());
out = new BufferedWriter(new OutputStreamWriter(new SecureFileOutputStream(tmp), "UTF-8"));
String line = null;
String search = hostname + '=';
boolean success = false;
while ( (line = in.readLine()) != null) {
if (line.startsWith(search)) {
success = true;
continue;
}
out.write(line);
out.newLine();
}
in.close();
out.close();
if (!success) {
tmp.delete();
return false;
}
success = rename(tmp, _file);
if (success) {
for (NamingServiceListener nsl : _listeners) {
nsl.entryRemoved(this, hostname);
}
}
return success;
} catch (IOException ioe) {
if (in != null) try { in.close(); } catch (IOException e) {}
if (out != null) try { out.close(); } catch (IOException e) {}
_log.error("Error removing " + hostname, ioe);
return false;
} finally {
releaseWriteLock();
}
}
/**
* @param options As follows:
* Key "search": return only those matching substring
* Key "startsWith": return only those starting with
* ("[0-9]" allowed)
*/
@Override
public Map<String, Destination> getEntries(Properties options) {
if (!_file.exists())
return Collections.EMPTY_MAP;
String searchOpt = null;
String startsWith = null;
if (options != null) {
searchOpt = options.getProperty("search");
startsWith = options.getProperty("startsWith");
}
+ if (_log.shouldLog(Log.DEBUG))
+ _log.debug("Searching " + " starting with " + startsWith + " search string " + searchOpt);
BufferedReader in = null;
getReadLock();
try {
in = new BufferedReader(new InputStreamReader(new FileInputStream(_file), "UTF-8"), 16*1024);
String line = null;
- String search = startsWith == null ? null : startsWith + '=';
Map<String, Destination> rv = new HashMap();
while ( (line = in.readLine()) != null) {
if (line.length() <= 0)
continue;
- if (search != null) {
+ if (startsWith != null) {
if (startsWith.equals("[0-9]")) {
if (line.charAt(0) < '0' || line.charAt(0) > '9')
continue;
- } else if (!line.startsWith(search)) {
+ } else if (!line.startsWith(startsWith)) {
continue;
}
}
if (line.startsWith("#"))
continue;
if (line.indexOf('#') > 0) // trim off any end of line comment
line = line.substring(0, line.indexOf('#')).trim();
int split = line.indexOf('=');
if (split <= 0)
continue;
String key = line.substring(0, split);
if (searchOpt != null && key.indexOf(searchOpt) < 0)
continue;
String b64 = line.substring(split+1); //.trim() ??????????????
try {
Destination dest = new Destination(b64);
rv.put(key, dest);
} catch (DataFormatException dfe) {}
}
if (searchOpt == null && startsWith == null) {
_lastWrite = _file.lastModified();
_size = rv.size();
}
return rv;
} catch (IOException ioe) {
_log.error("getEntries error", ioe);
return Collections.EMPTY_MAP;
} finally {
if (in != null) try { in.close(); } catch (IOException ioe) {}
releaseReadLock();
}
}
/**
* @param options ignored
*/
@Override
public int size(Properties options) {
if (!_file.exists())
return 0;
BufferedReader in = null;
getReadLock();
try {
if (_file.lastModified() <= _lastWrite)
return _size;
in = new BufferedReader(new InputStreamReader(new FileInputStream(_file), "UTF-8"), 16*1024);
String line = null;
int rv = 0;
while ( (line = in.readLine()) != null) {
if (line.startsWith("#") || line.length() <= 0)
continue;
rv++;
}
_lastWrite = _file.lastModified();
_size = rv;
return rv;
} catch (IOException ioe) {
_log.error("size() error", ioe);
return -1;
} finally {
if (in != null) try { in.close(); } catch (IOException ioe) {}
releaseReadLock();
}
}
private static boolean rename(File from, File to) {
boolean success = false;
boolean isWindows = System.getProperty("os.name").startsWith("Win");
// overwrite fails on windows
if (!isWindows)
success = from.renameTo(to);
if (!success) {
to.delete();
success = from.renameTo(to);
if (!success) {
// hard way
success = FileUtil.copy(from.getAbsolutePath(), to.getAbsolutePath(), true, true);
from.delete();
}
}
return success;
}
private void getReadLock() {
_fileLock.readLock().lock();
}
private void releaseReadLock() {
_fileLock.readLock().unlock();
}
/** @return true if the lock was acquired */
private boolean getWriteLock() {
try {
boolean rv = _fileLock.writeLock().tryLock(10000, TimeUnit.MILLISECONDS);
if ((!rv) && _log.shouldLog(Log.WARN))
_log.warn("no lock, size is: " + _fileLock.getQueueLength(), new Exception("rats"));
return rv;
} catch (InterruptedException ie) {}
return false;
}
private void releaseWriteLock() {
_fileLock.writeLock().unlock();
}
public static void main(String[] args) {
NamingService ns = new SingleFileNamingService(I2PAppContext.getGlobalContext(), "hosts.txt");
Destination d = new Destination();
try {
d.readBytes(new byte[387], 0);
} catch (DataFormatException dfe) {}
boolean b = ns.put("aaaaa", d);
System.out.println("Test 1 pass? " + b);
b = ns.put("bbbbb", d);
System.out.println("Test 2 pass? " + b);
b = ns.remove("aaaaa");
System.out.println("Test 3 pass? " + b);
b = ns.lookup("aaaaa") == null;
System.out.println("Test 4 pass? " + b);
b = ns.lookup("bbbbb") != null;
System.out.println("Test 5 pass? " + b);
b = !ns.putIfAbsent("bbbbb", d);
System.out.println("Test 6 pass? " + b);
}
}
| false | true | public Map<String, Destination> getEntries(Properties options) {
if (!_file.exists())
return Collections.EMPTY_MAP;
String searchOpt = null;
String startsWith = null;
if (options != null) {
searchOpt = options.getProperty("search");
startsWith = options.getProperty("startsWith");
}
BufferedReader in = null;
getReadLock();
try {
in = new BufferedReader(new InputStreamReader(new FileInputStream(_file), "UTF-8"), 16*1024);
String line = null;
String search = startsWith == null ? null : startsWith + '=';
Map<String, Destination> rv = new HashMap();
while ( (line = in.readLine()) != null) {
if (line.length() <= 0)
continue;
if (search != null) {
if (startsWith.equals("[0-9]")) {
if (line.charAt(0) < '0' || line.charAt(0) > '9')
continue;
} else if (!line.startsWith(search)) {
continue;
}
}
if (line.startsWith("#"))
continue;
if (line.indexOf('#') > 0) // trim off any end of line comment
line = line.substring(0, line.indexOf('#')).trim();
int split = line.indexOf('=');
if (split <= 0)
continue;
String key = line.substring(0, split);
if (searchOpt != null && key.indexOf(searchOpt) < 0)
continue;
String b64 = line.substring(split+1); //.trim() ??????????????
try {
Destination dest = new Destination(b64);
rv.put(key, dest);
} catch (DataFormatException dfe) {}
}
if (searchOpt == null && startsWith == null) {
_lastWrite = _file.lastModified();
_size = rv.size();
}
return rv;
} catch (IOException ioe) {
_log.error("getEntries error", ioe);
return Collections.EMPTY_MAP;
} finally {
if (in != null) try { in.close(); } catch (IOException ioe) {}
releaseReadLock();
}
}
| public Map<String, Destination> getEntries(Properties options) {
if (!_file.exists())
return Collections.EMPTY_MAP;
String searchOpt = null;
String startsWith = null;
if (options != null) {
searchOpt = options.getProperty("search");
startsWith = options.getProperty("startsWith");
}
if (_log.shouldLog(Log.DEBUG))
_log.debug("Searching " + " starting with " + startsWith + " search string " + searchOpt);
BufferedReader in = null;
getReadLock();
try {
in = new BufferedReader(new InputStreamReader(new FileInputStream(_file), "UTF-8"), 16*1024);
String line = null;
Map<String, Destination> rv = new HashMap();
while ( (line = in.readLine()) != null) {
if (line.length() <= 0)
continue;
if (startsWith != null) {
if (startsWith.equals("[0-9]")) {
if (line.charAt(0) < '0' || line.charAt(0) > '9')
continue;
} else if (!line.startsWith(startsWith)) {
continue;
}
}
if (line.startsWith("#"))
continue;
if (line.indexOf('#') > 0) // trim off any end of line comment
line = line.substring(0, line.indexOf('#')).trim();
int split = line.indexOf('=');
if (split <= 0)
continue;
String key = line.substring(0, split);
if (searchOpt != null && key.indexOf(searchOpt) < 0)
continue;
String b64 = line.substring(split+1); //.trim() ??????????????
try {
Destination dest = new Destination(b64);
rv.put(key, dest);
} catch (DataFormatException dfe) {}
}
if (searchOpt == null && startsWith == null) {
_lastWrite = _file.lastModified();
_size = rv.size();
}
return rv;
} catch (IOException ioe) {
_log.error("getEntries error", ioe);
return Collections.EMPTY_MAP;
} finally {
if (in != null) try { in.close(); } catch (IOException ioe) {}
releaseReadLock();
}
}
|
diff --git a/OpTalk/OpTalk/src/be/infogroep/optalk/ItemShare.java b/OpTalk/OpTalk/src/be/infogroep/optalk/ItemShare.java
index 5669fbc..938df38 100644
--- a/OpTalk/OpTalk/src/be/infogroep/optalk/ItemShare.java
+++ b/OpTalk/OpTalk/src/be/infogroep/optalk/ItemShare.java
@@ -1,129 +1,131 @@
package be.infogroep.optalk;
//import java.util.Map;
import java.util.*;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.command.CommandSender;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.*;
import org.bukkit.inventory.*;
import org.bukkit.inventory.meta.*;
import org.bukkit.potion.*;
public class ItemShare {
private int header = 5;
private boolean potion = false;
private Player receiver_ = null;
private Player sender_;
private ItemStack item_;
private ItemMeta meta_;
private String itemName_;
ItemShare(CommandSender sender, String[] msg) {
Bukkit.getLogger().info("ItemShare");
if (msg.length > 0) {
String name = msg[0];
receiver_ = Bukkit.getServer().getPlayer(name);
}
sender_ = (Player) sender;
item_ = sender_.getItemInHand();
meta_ = item_.getItemMeta();
if (meta_ != null) {
if (meta_.hasDisplayName())
itemName_ = meta_.getDisplayName();
else
itemName_ = item_.getType().name();
} else
itemName_ = // item_.getType().name();
item_.getData().getClass().getName();
Map<Enchantment, Integer> enchants = /* item_.getEnchantments(); */
item_.getEnchantments();
Collection<PotionEffect> effects = null;
Material material_ = item_.getType();
if (material_.getId() == 387) {// special case book
BookMeta BM = (BookMeta) meta_;
itemName_ = BM.getTitle() + " - " + BM.getAuthor();
}
if (material_.getId() == 403) {// special case enchanted book
EnchantmentStorageMeta ESM = (EnchantmentStorageMeta) meta_;
enchants = ESM.getStoredEnchants();
}
if (material_.getId() == 373) {// special case potions
potion = true;
PotionMeta PM = (PotionMeta) meta_;
if (PM.hasDisplayName())
itemName_ = PM.getDisplayName();
effects = PM.getCustomEffects();
}
// Recipe R = ShapedRecipe(item_);
int EnchantsSize = enchants.size();
int EnchantsHeaderSize = 1;
if (EnchantsSize > 0)
EnchantsHeaderSize = EnchantsSize;
else if (effects != null) {
if (effects.size() != 0)
EnchantsHeaderSize = effects.size();
}
String[] message = new String[header + EnchantsHeaderSize];
message[0] = "§5" + sender.getName() + ": §6shared an item";
message[1] = "§aItem name: §b" + itemName_;
message[2] = "§aType: §b"
+ material_.name().replace("_", " ").toLowerCase();
if (potion)
message[3] = "§aEffect: ";
else
message[3] = "§aEnchanments: ";
int index = 4;
if (EnchantsSize > 0) {
for (Map.Entry<Enchantment, Integer> current : enchants.entrySet()) {
message[index] = current.getKey().getName() + " Level: "
+ current.getValue();
index = index + 1;
}
- } else if (!effects.isEmpty()) {
- for (PotionEffect P : effects) {
- message[index] = P.getType().getName() + ": " + P.getDuration();
+ } else if (effects != null)
+ if (!effects.isEmpty()) {
+ for (PotionEffect P : effects) {
+ message[index] = P.getType().getName() + ": "
+ + P.getDuration();
+ }
+ } else {
+ message[index] = "None";
+ index = index + 1;
}
- } else {
- message[index] = "None";
- index = index + 1;
- }
message[index] = "§a-------------------";
if (null == receiver_) {
if (msg.length == 0) {
Bukkit.getServer().broadcastMessage("§a§nPublicly shared item");
for (String s : message) {
Bukkit.getServer().broadcastMessage(s);
}
} else {
sender.sendMessage("§ccould not find player: " + msg[0]);
}
} else {
receiver_.sendMessage(message);
sender.sendMessage("§asuccesfully shared your item with " + msg[0]);
}
}
}
| false | true | ItemShare(CommandSender sender, String[] msg) {
Bukkit.getLogger().info("ItemShare");
if (msg.length > 0) {
String name = msg[0];
receiver_ = Bukkit.getServer().getPlayer(name);
}
sender_ = (Player) sender;
item_ = sender_.getItemInHand();
meta_ = item_.getItemMeta();
if (meta_ != null) {
if (meta_.hasDisplayName())
itemName_ = meta_.getDisplayName();
else
itemName_ = item_.getType().name();
} else
itemName_ = // item_.getType().name();
item_.getData().getClass().getName();
Map<Enchantment, Integer> enchants = /* item_.getEnchantments(); */
item_.getEnchantments();
Collection<PotionEffect> effects = null;
Material material_ = item_.getType();
if (material_.getId() == 387) {// special case book
BookMeta BM = (BookMeta) meta_;
itemName_ = BM.getTitle() + " - " + BM.getAuthor();
}
if (material_.getId() == 403) {// special case enchanted book
EnchantmentStorageMeta ESM = (EnchantmentStorageMeta) meta_;
enchants = ESM.getStoredEnchants();
}
if (material_.getId() == 373) {// special case potions
potion = true;
PotionMeta PM = (PotionMeta) meta_;
if (PM.hasDisplayName())
itemName_ = PM.getDisplayName();
effects = PM.getCustomEffects();
}
// Recipe R = ShapedRecipe(item_);
int EnchantsSize = enchants.size();
int EnchantsHeaderSize = 1;
if (EnchantsSize > 0)
EnchantsHeaderSize = EnchantsSize;
else if (effects != null) {
if (effects.size() != 0)
EnchantsHeaderSize = effects.size();
}
String[] message = new String[header + EnchantsHeaderSize];
message[0] = "§5" + sender.getName() + ": §6shared an item";
message[1] = "§aItem name: §b" + itemName_;
message[2] = "§aType: §b"
+ material_.name().replace("_", " ").toLowerCase();
if (potion)
message[3] = "§aEffect: ";
else
message[3] = "§aEnchanments: ";
int index = 4;
if (EnchantsSize > 0) {
for (Map.Entry<Enchantment, Integer> current : enchants.entrySet()) {
message[index] = current.getKey().getName() + " Level: "
+ current.getValue();
index = index + 1;
}
} else if (!effects.isEmpty()) {
for (PotionEffect P : effects) {
message[index] = P.getType().getName() + ": " + P.getDuration();
}
} else {
message[index] = "None";
index = index + 1;
}
message[index] = "§a-------------------";
if (null == receiver_) {
if (msg.length == 0) {
Bukkit.getServer().broadcastMessage("§a§nPublicly shared item");
for (String s : message) {
Bukkit.getServer().broadcastMessage(s);
}
} else {
sender.sendMessage("§ccould not find player: " + msg[0]);
}
} else {
receiver_.sendMessage(message);
sender.sendMessage("§asuccesfully shared your item with " + msg[0]);
}
}
| ItemShare(CommandSender sender, String[] msg) {
Bukkit.getLogger().info("ItemShare");
if (msg.length > 0) {
String name = msg[0];
receiver_ = Bukkit.getServer().getPlayer(name);
}
sender_ = (Player) sender;
item_ = sender_.getItemInHand();
meta_ = item_.getItemMeta();
if (meta_ != null) {
if (meta_.hasDisplayName())
itemName_ = meta_.getDisplayName();
else
itemName_ = item_.getType().name();
} else
itemName_ = // item_.getType().name();
item_.getData().getClass().getName();
Map<Enchantment, Integer> enchants = /* item_.getEnchantments(); */
item_.getEnchantments();
Collection<PotionEffect> effects = null;
Material material_ = item_.getType();
if (material_.getId() == 387) {// special case book
BookMeta BM = (BookMeta) meta_;
itemName_ = BM.getTitle() + " - " + BM.getAuthor();
}
if (material_.getId() == 403) {// special case enchanted book
EnchantmentStorageMeta ESM = (EnchantmentStorageMeta) meta_;
enchants = ESM.getStoredEnchants();
}
if (material_.getId() == 373) {// special case potions
potion = true;
PotionMeta PM = (PotionMeta) meta_;
if (PM.hasDisplayName())
itemName_ = PM.getDisplayName();
effects = PM.getCustomEffects();
}
// Recipe R = ShapedRecipe(item_);
int EnchantsSize = enchants.size();
int EnchantsHeaderSize = 1;
if (EnchantsSize > 0)
EnchantsHeaderSize = EnchantsSize;
else if (effects != null) {
if (effects.size() != 0)
EnchantsHeaderSize = effects.size();
}
String[] message = new String[header + EnchantsHeaderSize];
message[0] = "§5" + sender.getName() + ": §6shared an item";
message[1] = "§aItem name: §b" + itemName_;
message[2] = "§aType: §b"
+ material_.name().replace("_", " ").toLowerCase();
if (potion)
message[3] = "§aEffect: ";
else
message[3] = "§aEnchanments: ";
int index = 4;
if (EnchantsSize > 0) {
for (Map.Entry<Enchantment, Integer> current : enchants.entrySet()) {
message[index] = current.getKey().getName() + " Level: "
+ current.getValue();
index = index + 1;
}
} else if (effects != null)
if (!effects.isEmpty()) {
for (PotionEffect P : effects) {
message[index] = P.getType().getName() + ": "
+ P.getDuration();
}
} else {
message[index] = "None";
index = index + 1;
}
message[index] = "§a-------------------";
if (null == receiver_) {
if (msg.length == 0) {
Bukkit.getServer().broadcastMessage("§a§nPublicly shared item");
for (String s : message) {
Bukkit.getServer().broadcastMessage(s);
}
} else {
sender.sendMessage("§ccould not find player: " + msg[0]);
}
} else {
receiver_.sendMessage(message);
sender.sendMessage("§asuccesfully shared your item with " + msg[0]);
}
}
|
diff --git a/plugins/org.bigraph.model/src/org/bigraph/model/SignatureDescriptorHandler.java b/plugins/org.bigraph.model/src/org/bigraph/model/SignatureDescriptorHandler.java
index 1bc57f15..c1eaa54c 100644
--- a/plugins/org.bigraph.model/src/org/bigraph/model/SignatureDescriptorHandler.java
+++ b/plugins/org.bigraph.model/src/org/bigraph/model/SignatureDescriptorHandler.java
@@ -1,99 +1,99 @@
package org.bigraph.model;
import org.bigraph.model.Signature.ChangeAddControlDescriptor;
import org.bigraph.model.Signature.ChangeAddSignatureDescriptor;
import org.bigraph.model.Signature.ChangeRemoveControlDescriptor;
import org.bigraph.model.Signature.ChangeRemoveSignatureDescriptor;
import org.bigraph.model.assistants.PropertyScratchpad;
import org.bigraph.model.assistants.IObjectIdentifier.Resolver;
import org.bigraph.model.changes.descriptors.ChangeCreationException;
import org.bigraph.model.changes.descriptors.IChangeDescriptor;
final class SignatureDescriptorHandler
extends HandlerUtilities.DescriptorHandlerImpl {
@Override
public boolean tryValidateChange(Process context, IChangeDescriptor change)
throws ChangeCreationException {
final PropertyScratchpad scratch = context.getScratch();
final Resolver resolver = context.getResolver();
if (change instanceof ChangeAddControlDescriptor) {
ChangeAddControlDescriptor cd = (ChangeAddControlDescriptor)change;
Signature s = tryLookup(cd,
cd.getTarget(), scratch, resolver, Signature.class);
NamedModelObjectDescriptorHandler.checkName(scratch, cd,
cd.getControl(), s.getNamespace(),
cd.getControl().getName());
} else if (change instanceof ChangeRemoveControlDescriptor) {
ChangeRemoveControlDescriptor cd =
(ChangeRemoveControlDescriptor)change;
tryLookup(cd, cd.getTarget(), scratch, resolver, Signature.class);
Control c = tryLookup(
cd, cd.getControl(), scratch, resolver, Control.class);
if (c.getPorts(scratch).size() != 0)
throw new ChangeCreationException(cd,
"" + cd.getControl() + " still has ports " +
"that must be removed first");
- if (c.getExtendedDataMap().size() != 0)
+ if (c.getExtendedDataMap(scratch).size() != 0)
throw new ChangeCreationException(cd,
"" + cd.getControl() + " still has extended data " +
"that must be removed first");
} else if (change instanceof ChangeAddSignatureDescriptor) {
ChangeAddSignatureDescriptor cd =
(ChangeAddSignatureDescriptor)change;
Signature s = tryLookup(cd,
cd.getTarget(), scratch, resolver, Signature.class);
Signature ch = cd.getSignature();
if (ch == null)
throw new ChangeCreationException(cd,
"Can't insert a null signature");
HandlerUtilities.checkAddBounds(cd,
s.getSignatures(scratch), cd.getPosition());
} else if (change instanceof ChangeRemoveSignatureDescriptor) {
ChangeRemoveSignatureDescriptor cd =
(ChangeRemoveSignatureDescriptor)change;
Signature s = tryLookup(cd,
cd.getTarget(), scratch, resolver, Signature.class);
HandlerUtilities.checkRemove(cd,
s.getSignatures(scratch),
cd.getSignature(), cd.getPosition());
} else return false;
return true;
}
@Override
public boolean executeChange(Resolver resolver, IChangeDescriptor change) {
if (change instanceof ChangeAddControlDescriptor) {
ChangeAddControlDescriptor cd = (ChangeAddControlDescriptor)change;
Signature s = cd.getTarget().lookup(null, resolver);
Control c = new Control();
c.setName(s.getNamespace().put(cd.getControl().getName(), c));
s.addControl(c);
} else if (change instanceof ChangeRemoveControlDescriptor) {
ChangeRemoveControlDescriptor cd =
(ChangeRemoveControlDescriptor)change;
Signature s = cd.getTarget().lookup(null, resolver);
Control c = cd.getControl().lookup(null, resolver);
s.removeControl(c);
s.getNamespace().remove(c.getName());
} else if (change instanceof ChangeAddSignatureDescriptor) {
ChangeAddSignatureDescriptor cd =
(ChangeAddSignatureDescriptor)change;
cd.getTarget().lookup(null, resolver).addSignature(
cd.getPosition(), cd.getSignature());
} else if (change instanceof ChangeRemoveSignatureDescriptor) {
ChangeRemoveSignatureDescriptor cd =
(ChangeRemoveSignatureDescriptor)change;
cd.getTarget().lookup(null, resolver).removeSignature(
cd.getSignature());
} else return false;
return true;
}
}
| true | true | public boolean tryValidateChange(Process context, IChangeDescriptor change)
throws ChangeCreationException {
final PropertyScratchpad scratch = context.getScratch();
final Resolver resolver = context.getResolver();
if (change instanceof ChangeAddControlDescriptor) {
ChangeAddControlDescriptor cd = (ChangeAddControlDescriptor)change;
Signature s = tryLookup(cd,
cd.getTarget(), scratch, resolver, Signature.class);
NamedModelObjectDescriptorHandler.checkName(scratch, cd,
cd.getControl(), s.getNamespace(),
cd.getControl().getName());
} else if (change instanceof ChangeRemoveControlDescriptor) {
ChangeRemoveControlDescriptor cd =
(ChangeRemoveControlDescriptor)change;
tryLookup(cd, cd.getTarget(), scratch, resolver, Signature.class);
Control c = tryLookup(
cd, cd.getControl(), scratch, resolver, Control.class);
if (c.getPorts(scratch).size() != 0)
throw new ChangeCreationException(cd,
"" + cd.getControl() + " still has ports " +
"that must be removed first");
if (c.getExtendedDataMap().size() != 0)
throw new ChangeCreationException(cd,
"" + cd.getControl() + " still has extended data " +
"that must be removed first");
} else if (change instanceof ChangeAddSignatureDescriptor) {
ChangeAddSignatureDescriptor cd =
(ChangeAddSignatureDescriptor)change;
Signature s = tryLookup(cd,
cd.getTarget(), scratch, resolver, Signature.class);
Signature ch = cd.getSignature();
if (ch == null)
throw new ChangeCreationException(cd,
"Can't insert a null signature");
HandlerUtilities.checkAddBounds(cd,
s.getSignatures(scratch), cd.getPosition());
} else if (change instanceof ChangeRemoveSignatureDescriptor) {
ChangeRemoveSignatureDescriptor cd =
(ChangeRemoveSignatureDescriptor)change;
Signature s = tryLookup(cd,
cd.getTarget(), scratch, resolver, Signature.class);
HandlerUtilities.checkRemove(cd,
s.getSignatures(scratch),
cd.getSignature(), cd.getPosition());
} else return false;
return true;
}
| public boolean tryValidateChange(Process context, IChangeDescriptor change)
throws ChangeCreationException {
final PropertyScratchpad scratch = context.getScratch();
final Resolver resolver = context.getResolver();
if (change instanceof ChangeAddControlDescriptor) {
ChangeAddControlDescriptor cd = (ChangeAddControlDescriptor)change;
Signature s = tryLookup(cd,
cd.getTarget(), scratch, resolver, Signature.class);
NamedModelObjectDescriptorHandler.checkName(scratch, cd,
cd.getControl(), s.getNamespace(),
cd.getControl().getName());
} else if (change instanceof ChangeRemoveControlDescriptor) {
ChangeRemoveControlDescriptor cd =
(ChangeRemoveControlDescriptor)change;
tryLookup(cd, cd.getTarget(), scratch, resolver, Signature.class);
Control c = tryLookup(
cd, cd.getControl(), scratch, resolver, Control.class);
if (c.getPorts(scratch).size() != 0)
throw new ChangeCreationException(cd,
"" + cd.getControl() + " still has ports " +
"that must be removed first");
if (c.getExtendedDataMap(scratch).size() != 0)
throw new ChangeCreationException(cd,
"" + cd.getControl() + " still has extended data " +
"that must be removed first");
} else if (change instanceof ChangeAddSignatureDescriptor) {
ChangeAddSignatureDescriptor cd =
(ChangeAddSignatureDescriptor)change;
Signature s = tryLookup(cd,
cd.getTarget(), scratch, resolver, Signature.class);
Signature ch = cd.getSignature();
if (ch == null)
throw new ChangeCreationException(cd,
"Can't insert a null signature");
HandlerUtilities.checkAddBounds(cd,
s.getSignatures(scratch), cd.getPosition());
} else if (change instanceof ChangeRemoveSignatureDescriptor) {
ChangeRemoveSignatureDescriptor cd =
(ChangeRemoveSignatureDescriptor)change;
Signature s = tryLookup(cd,
cd.getTarget(), scratch, resolver, Signature.class);
HandlerUtilities.checkRemove(cd,
s.getSignatures(scratch),
cd.getSignature(), cd.getPosition());
} else return false;
return true;
}
|
diff --git a/src/main/java/org/jsonman/NodeUpdater.java b/src/main/java/org/jsonman/NodeUpdater.java
index e465c39..37c64aa 100644
--- a/src/main/java/org/jsonman/NodeUpdater.java
+++ b/src/main/java/org/jsonman/NodeUpdater.java
@@ -1,113 +1,113 @@
/*
* Copyright 2013 Takao Nakaguchi.
*
* 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.jsonman;
import java.text.ParseException;
import java.util.Iterator;
import org.jsonman.finder.Reference;
import org.jsonman.finder.ReferenceParser;
import org.jsonman.node.ArrayNode;
import org.jsonman.node.MapNode;
public class NodeUpdater {
public NodeUpdater(Node target){
this.target = target;
}
public Node getTarget() {
return target;
}
public void update(String referencePath, Node node) throws ParseException{
update(ReferenceParser.parse(referencePath), node);
}
public void update(Iterable<Reference> path, Node node){
final Iterator<Reference> it = path.iterator();
Node t = target;
while(true){
Reference r = it.next();
if(t.isArray() && r.isArray()){
ArrayNode an = t.cast();
Integer index = r.getId();
t = an.getChild(index);
if(t != null){
if(!it.hasNext()){
if(t.isMap() && node.isMap()){
((MapNode)t).mergeValue((MapNode)node);
} else{
t.setValue(node.getValue());
}
break;
}
continue;
} else{
an.setChild(index, createNode(it, node));
break;
}
} else if(t.isMap() && r.isMap()){
MapNode mn = t.cast();
String name = r.getId();
t = mn.getChild(name);
if(t != null){
if(!it.hasNext()){
if(t.isMap() && node.isMap()){
((MapNode)t).mergeValue((MapNode)node);
} else{
- t.setValue(node.getValue());
+ mn.setChild(name, node);
}
break;
}
continue;
} else{
mn.setChild(name, createNode(it, node));
break;
}
} else{
throw new RuntimeException(String.format(
"type of node(%s) and reference(%s) not match.",
t.getClass().getName(),
r.getClass().getName()
));
}
}
}
static Node createNode(Iterator<Reference> it, Node leaf){
Reference ref = it.next();
Node child = null;
if(it.hasNext()){
child = createNode(it, leaf);
} else{
child = leaf;
}
Node n = null;
if(ref.isMap()){
MapNode mn = new MapNode();
mn.appendChild((String)ref.getId(), child);
n = mn;
} else if(ref.isArray()){
ArrayNode an = new ArrayNode();
an.setChild((Integer)ref.getId(), child);
n = an;
} else{
return null;
}
return n;
}
private Node target;
}
| true | true | public void update(Iterable<Reference> path, Node node){
final Iterator<Reference> it = path.iterator();
Node t = target;
while(true){
Reference r = it.next();
if(t.isArray() && r.isArray()){
ArrayNode an = t.cast();
Integer index = r.getId();
t = an.getChild(index);
if(t != null){
if(!it.hasNext()){
if(t.isMap() && node.isMap()){
((MapNode)t).mergeValue((MapNode)node);
} else{
t.setValue(node.getValue());
}
break;
}
continue;
} else{
an.setChild(index, createNode(it, node));
break;
}
} else if(t.isMap() && r.isMap()){
MapNode mn = t.cast();
String name = r.getId();
t = mn.getChild(name);
if(t != null){
if(!it.hasNext()){
if(t.isMap() && node.isMap()){
((MapNode)t).mergeValue((MapNode)node);
} else{
t.setValue(node.getValue());
}
break;
}
continue;
} else{
mn.setChild(name, createNode(it, node));
break;
}
} else{
throw new RuntimeException(String.format(
"type of node(%s) and reference(%s) not match.",
t.getClass().getName(),
r.getClass().getName()
));
}
}
}
| public void update(Iterable<Reference> path, Node node){
final Iterator<Reference> it = path.iterator();
Node t = target;
while(true){
Reference r = it.next();
if(t.isArray() && r.isArray()){
ArrayNode an = t.cast();
Integer index = r.getId();
t = an.getChild(index);
if(t != null){
if(!it.hasNext()){
if(t.isMap() && node.isMap()){
((MapNode)t).mergeValue((MapNode)node);
} else{
t.setValue(node.getValue());
}
break;
}
continue;
} else{
an.setChild(index, createNode(it, node));
break;
}
} else if(t.isMap() && r.isMap()){
MapNode mn = t.cast();
String name = r.getId();
t = mn.getChild(name);
if(t != null){
if(!it.hasNext()){
if(t.isMap() && node.isMap()){
((MapNode)t).mergeValue((MapNode)node);
} else{
mn.setChild(name, node);
}
break;
}
continue;
} else{
mn.setChild(name, createNode(it, node));
break;
}
} else{
throw new RuntimeException(String.format(
"type of node(%s) and reference(%s) not match.",
t.getClass().getName(),
r.getClass().getName()
));
}
}
}
|
diff --git a/core/src/java/org/apache/ftpserver/command/MKD.java b/core/src/java/org/apache/ftpserver/command/MKD.java
index d2e9af5a..bccabf36 100644
--- a/core/src/java/org/apache/ftpserver/command/MKD.java
+++ b/core/src/java/org/apache/ftpserver/command/MKD.java
@@ -1,144 +1,144 @@
/*
* 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.ftpserver.command;
import java.io.File;
import java.io.IOException;
import org.apache.ftpserver.FtpSessionImpl;
import org.apache.ftpserver.ftplet.FileObject;
import org.apache.ftpserver.ftplet.FtpException;
import org.apache.ftpserver.ftplet.FtpReply;
import org.apache.ftpserver.ftplet.FtpReplyOutput;
import org.apache.ftpserver.ftplet.FtpRequest;
import org.apache.ftpserver.ftplet.Ftplet;
import org.apache.ftpserver.ftplet.FtpletEnum;
import org.apache.ftpserver.interfaces.FtpServerContext;
import org.apache.ftpserver.interfaces.ServerFtpStatistics;
import org.apache.ftpserver.listener.Connection;
import org.apache.ftpserver.util.FtpReplyUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* <code>MKD <SP> <pathname> <CRLF></code><br>
*
* This command causes the directory specified in the pathname
* to be created as a directory (if the pathname is absolute)
* or as a subdirectory of the current working directory (if
* the pathname is relative).
*/
public
class MKD extends AbstractCommand {
private final Logger LOG = LoggerFactory.getLogger(MKD.class);
/**
* Execute command.
*/
public void execute(Connection connection,
FtpRequest request,
FtpSessionImpl session,
FtpReplyOutput out) throws IOException, FtpException {
// reset state
session.resetState();
FtpServerContext serverContext = connection.getServerContext();
// argument check
String fileName = request.getArgument();
if(fileName == null || fileName.indexOf(File.pathSeparatorChar) > -1) {
out.write(FtpReplyUtil.translate(session, FtpReply.REPLY_501_SYNTAX_ERROR_IN_PARAMETERS_OR_ARGUMENTS, "MKD", null));
return;
}
// call Ftplet.onMkdirStart() method
Ftplet ftpletContainer = serverContext.getFtpletContainer();
FtpletEnum ftpletRet;
try{
ftpletRet = ftpletContainer.onMkdirStart(session, request, out);
} catch(Exception e) {
LOG.debug("Ftplet container threw exception", e);
ftpletRet = FtpletEnum.RET_DISCONNECT;
}
if(ftpletRet == FtpletEnum.RET_SKIP) {
return;
}
else if(ftpletRet == FtpletEnum.RET_DISCONNECT) {
serverContext.getConnectionManager().closeConnection(connection);
return;
}
// get file object
FileObject file = null;
try {
file = session.getFileSystemView().getFileObject(fileName);
}
catch(Exception ex) {
LOG.debug("Exception getting file object", ex);
}
if(file == null) {
out.write(FtpReplyUtil.translate(session, FtpReply.REPLY_550_REQUESTED_ACTION_NOT_TAKEN, "MKD.invalid", fileName));
return;
}
// check permission
fileName = file.getFullName();
if( !file.hasWritePermission() ) {
out.write(FtpReplyUtil.translate(session, FtpReply.REPLY_550_REQUESTED_ACTION_NOT_TAKEN, "MKD.permission", fileName));
return;
}
// check file existance
if(file.doesExist()) {
out.write(FtpReplyUtil.translate(session, FtpReply.REPLY_550_REQUESTED_ACTION_NOT_TAKEN, "MKD.exists", fileName));
return;
}
// now create directory
if(file.mkdir()) {
- out.write(FtpReplyUtil.translate(session, FtpReply.REPLY_250_REQUESTED_FILE_ACTION_OKAY, "MKD", fileName));
+ out.write(FtpReplyUtil.translate(session, FtpReply.REPLY_257_PATHNAME_CREATED, "MKD", fileName));
// write log message
String userName = session.getUser().getName();
LOG.info("Directory create : " + userName + " - " + fileName);
// notify statistics object
ServerFtpStatistics ftpStat = (ServerFtpStatistics)connection.getServerContext().getFtpStatistics();
ftpStat.setMkdir(connection, file);
// call Ftplet.onMkdirEnd() method
try{
ftpletRet = ftpletContainer.onMkdirEnd(session, request, out);
} catch(Exception e) {
LOG.debug("Ftplet container threw exception", e);
ftpletRet = FtpletEnum.RET_DISCONNECT;
}
if(ftpletRet == FtpletEnum.RET_DISCONNECT) {
serverContext.getConnectionManager().closeConnection(connection);
return;
}
}
else {
out.write(FtpReplyUtil.translate(session, FtpReply.REPLY_550_REQUESTED_ACTION_NOT_TAKEN, "MKD", fileName));
}
}
}
| true | true | public void execute(Connection connection,
FtpRequest request,
FtpSessionImpl session,
FtpReplyOutput out) throws IOException, FtpException {
// reset state
session.resetState();
FtpServerContext serverContext = connection.getServerContext();
// argument check
String fileName = request.getArgument();
if(fileName == null || fileName.indexOf(File.pathSeparatorChar) > -1) {
out.write(FtpReplyUtil.translate(session, FtpReply.REPLY_501_SYNTAX_ERROR_IN_PARAMETERS_OR_ARGUMENTS, "MKD", null));
return;
}
// call Ftplet.onMkdirStart() method
Ftplet ftpletContainer = serverContext.getFtpletContainer();
FtpletEnum ftpletRet;
try{
ftpletRet = ftpletContainer.onMkdirStart(session, request, out);
} catch(Exception e) {
LOG.debug("Ftplet container threw exception", e);
ftpletRet = FtpletEnum.RET_DISCONNECT;
}
if(ftpletRet == FtpletEnum.RET_SKIP) {
return;
}
else if(ftpletRet == FtpletEnum.RET_DISCONNECT) {
serverContext.getConnectionManager().closeConnection(connection);
return;
}
// get file object
FileObject file = null;
try {
file = session.getFileSystemView().getFileObject(fileName);
}
catch(Exception ex) {
LOG.debug("Exception getting file object", ex);
}
if(file == null) {
out.write(FtpReplyUtil.translate(session, FtpReply.REPLY_550_REQUESTED_ACTION_NOT_TAKEN, "MKD.invalid", fileName));
return;
}
// check permission
fileName = file.getFullName();
if( !file.hasWritePermission() ) {
out.write(FtpReplyUtil.translate(session, FtpReply.REPLY_550_REQUESTED_ACTION_NOT_TAKEN, "MKD.permission", fileName));
return;
}
// check file existance
if(file.doesExist()) {
out.write(FtpReplyUtil.translate(session, FtpReply.REPLY_550_REQUESTED_ACTION_NOT_TAKEN, "MKD.exists", fileName));
return;
}
// now create directory
if(file.mkdir()) {
out.write(FtpReplyUtil.translate(session, FtpReply.REPLY_250_REQUESTED_FILE_ACTION_OKAY, "MKD", fileName));
// write log message
String userName = session.getUser().getName();
LOG.info("Directory create : " + userName + " - " + fileName);
// notify statistics object
ServerFtpStatistics ftpStat = (ServerFtpStatistics)connection.getServerContext().getFtpStatistics();
ftpStat.setMkdir(connection, file);
// call Ftplet.onMkdirEnd() method
try{
ftpletRet = ftpletContainer.onMkdirEnd(session, request, out);
} catch(Exception e) {
LOG.debug("Ftplet container threw exception", e);
ftpletRet = FtpletEnum.RET_DISCONNECT;
}
if(ftpletRet == FtpletEnum.RET_DISCONNECT) {
serverContext.getConnectionManager().closeConnection(connection);
return;
}
}
else {
out.write(FtpReplyUtil.translate(session, FtpReply.REPLY_550_REQUESTED_ACTION_NOT_TAKEN, "MKD", fileName));
}
}
| public void execute(Connection connection,
FtpRequest request,
FtpSessionImpl session,
FtpReplyOutput out) throws IOException, FtpException {
// reset state
session.resetState();
FtpServerContext serverContext = connection.getServerContext();
// argument check
String fileName = request.getArgument();
if(fileName == null || fileName.indexOf(File.pathSeparatorChar) > -1) {
out.write(FtpReplyUtil.translate(session, FtpReply.REPLY_501_SYNTAX_ERROR_IN_PARAMETERS_OR_ARGUMENTS, "MKD", null));
return;
}
// call Ftplet.onMkdirStart() method
Ftplet ftpletContainer = serverContext.getFtpletContainer();
FtpletEnum ftpletRet;
try{
ftpletRet = ftpletContainer.onMkdirStart(session, request, out);
} catch(Exception e) {
LOG.debug("Ftplet container threw exception", e);
ftpletRet = FtpletEnum.RET_DISCONNECT;
}
if(ftpletRet == FtpletEnum.RET_SKIP) {
return;
}
else if(ftpletRet == FtpletEnum.RET_DISCONNECT) {
serverContext.getConnectionManager().closeConnection(connection);
return;
}
// get file object
FileObject file = null;
try {
file = session.getFileSystemView().getFileObject(fileName);
}
catch(Exception ex) {
LOG.debug("Exception getting file object", ex);
}
if(file == null) {
out.write(FtpReplyUtil.translate(session, FtpReply.REPLY_550_REQUESTED_ACTION_NOT_TAKEN, "MKD.invalid", fileName));
return;
}
// check permission
fileName = file.getFullName();
if( !file.hasWritePermission() ) {
out.write(FtpReplyUtil.translate(session, FtpReply.REPLY_550_REQUESTED_ACTION_NOT_TAKEN, "MKD.permission", fileName));
return;
}
// check file existance
if(file.doesExist()) {
out.write(FtpReplyUtil.translate(session, FtpReply.REPLY_550_REQUESTED_ACTION_NOT_TAKEN, "MKD.exists", fileName));
return;
}
// now create directory
if(file.mkdir()) {
out.write(FtpReplyUtil.translate(session, FtpReply.REPLY_257_PATHNAME_CREATED, "MKD", fileName));
// write log message
String userName = session.getUser().getName();
LOG.info("Directory create : " + userName + " - " + fileName);
// notify statistics object
ServerFtpStatistics ftpStat = (ServerFtpStatistics)connection.getServerContext().getFtpStatistics();
ftpStat.setMkdir(connection, file);
// call Ftplet.onMkdirEnd() method
try{
ftpletRet = ftpletContainer.onMkdirEnd(session, request, out);
} catch(Exception e) {
LOG.debug("Ftplet container threw exception", e);
ftpletRet = FtpletEnum.RET_DISCONNECT;
}
if(ftpletRet == FtpletEnum.RET_DISCONNECT) {
serverContext.getConnectionManager().closeConnection(connection);
return;
}
}
else {
out.write(FtpReplyUtil.translate(session, FtpReply.REPLY_550_REQUESTED_ACTION_NOT_TAKEN, "MKD", fileName));
}
}
|
diff --git a/search-util/src/test/org/sakaiproject/search/util/test/HTMLParserTest.java b/search-util/src/test/org/sakaiproject/search/util/test/HTMLParserTest.java
index 9e8d9a58..c1fbbb9b 100644
--- a/search-util/src/test/org/sakaiproject/search/util/test/HTMLParserTest.java
+++ b/search-util/src/test/org/sakaiproject/search/util/test/HTMLParserTest.java
@@ -1,105 +1,105 @@
/**********************************************************************************
* $URL$
* $Id$
***********************************************************************************
*
* Copyright (c) 2003, 2004, 2005, 2006, 2007 The Sakai Foundation.
*
* Licensed under the Educational Community License, Version 1.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ecl1.php
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
**********************************************************************************/
package org.sakaiproject.search.util.test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Iterator;
import java.util.Properties;
import junit.framework.TestCase;
import org.sakaiproject.search.api.SearchUtils;
import org.sakaiproject.search.util.HTMLParser;
/**
* @author ieb
*
*/
public class HTMLParserTest extends TestCase
{
/**
* @param arg0
*/
public HTMLParserTest(String arg0)
{
super(arg0);
}
/* (non-Javadoc)
* @see junit.framework.TestCase#setUp()
*/
protected void setUp() throws Exception
{
super.setUp();
}
/* (non-Javadoc)
* @see junit.framework.TestCase#tearDown()
*/
protected void tearDown() throws Exception
{
super.tearDown();
}
public void testParser() throws Exception {
Properties p = new Properties();
InputStream inStream = getClass().getResourceAsStream("parsertest.config");
p.load(inStream);
inStream.close();
for ( Iterator tests = p.keySet().iterator(); tests.hasNext(); ) {
String tname = (String)tests.next();
StringBuilder sb = new StringBuilder();
for ( Iterator<String> i = new HTMLParser(loadFile(p.getProperty(tname))); i.hasNext();) {
String n = i.next();
SearchUtils.appendCleanString(n, sb);
}
String result = sb.toString();
- System.err.println("Result is "+result);
+// System.err.println("Result is "+result);
if ( p.containsKey(tname+".result") ) {
assertEquals("Tokens dont match ", loadFile(p.getProperty(tname+".result")), sb.toString());
}
}
}
/**
* @param property
* @return
* @throws IOException
*/
private String loadFile(String property) throws IOException
{
System.err.println("Loading :"+property+":");
BufferedReader br = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream(property),"UTF-8"));
StringBuffer sb = new StringBuffer();
for ( String s = br.readLine(); s != null; s = br.readLine()) {
sb.append(s).append("\n");
}
br.close();
return sb.toString();
}
}
| true | true | public void testParser() throws Exception {
Properties p = new Properties();
InputStream inStream = getClass().getResourceAsStream("parsertest.config");
p.load(inStream);
inStream.close();
for ( Iterator tests = p.keySet().iterator(); tests.hasNext(); ) {
String tname = (String)tests.next();
StringBuilder sb = new StringBuilder();
for ( Iterator<String> i = new HTMLParser(loadFile(p.getProperty(tname))); i.hasNext();) {
String n = i.next();
SearchUtils.appendCleanString(n, sb);
}
String result = sb.toString();
System.err.println("Result is "+result);
if ( p.containsKey(tname+".result") ) {
assertEquals("Tokens dont match ", loadFile(p.getProperty(tname+".result")), sb.toString());
}
}
}
| public void testParser() throws Exception {
Properties p = new Properties();
InputStream inStream = getClass().getResourceAsStream("parsertest.config");
p.load(inStream);
inStream.close();
for ( Iterator tests = p.keySet().iterator(); tests.hasNext(); ) {
String tname = (String)tests.next();
StringBuilder sb = new StringBuilder();
for ( Iterator<String> i = new HTMLParser(loadFile(p.getProperty(tname))); i.hasNext();) {
String n = i.next();
SearchUtils.appendCleanString(n, sb);
}
String result = sb.toString();
// System.err.println("Result is "+result);
if ( p.containsKey(tname+".result") ) {
assertEquals("Tokens dont match ", loadFile(p.getProperty(tname+".result")), sb.toString());
}
}
}
|
diff --git a/patientview-parent/radar/src/test/java/org/patientview/radar/test/service/PatientLinkManagerTest.java b/patientview-parent/radar/src/test/java/org/patientview/radar/test/service/PatientLinkManagerTest.java
index 1ff3f482..68b2f0a2 100644
--- a/patientview-parent/radar/src/test/java/org/patientview/radar/test/service/PatientLinkManagerTest.java
+++ b/patientview-parent/radar/src/test/java/org/patientview/radar/test/service/PatientLinkManagerTest.java
@@ -1,100 +1,100 @@
package org.patientview.radar.test.service;
import org.apache.commons.collections.CollectionUtils;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.patientview.model.Patient;
import org.patientview.model.generic.DiseaseGroup;
import org.patientview.radar.dao.DemographicsDao;
import org.patientview.radar.dao.UtilityDao;
import org.patientview.radar.model.PatientLink;
import org.patientview.radar.service.PatientLinkManager;
import org.patientview.radar.test.TestPvDbSchema;
import org.springframework.test.context.ContextConfiguration;
import javax.inject.Inject;
import java.util.Date;
import java.util.List;
/**
* User: [email protected]
* Date: 15/11/13
* Time: 14:32
*/
@RunWith(org.springframework.test.context.junit4.SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:test-context.xml"})
public class PatientLinkManagerTest extends TestPvDbSchema {
private final static String testDiseaseUnit = "Allports";
private final static String testRenalUnit = "RENALA";
@Inject
private PatientLinkManager patientLinkManager;
@Inject
private DemographicsDao demographicsDao;
@Inject
private UtilityDao utilityDao;
/**
* A unit admin is created by the superadmin in PV.
* <p/>
* Create a basic PV user structure - User - Role as unit admin etc
*/
@Before
public void setup() {
// Setup a Renal Unit and Disease Group
try {
utilityDao.createUnit(testRenalUnit);
utilityDao.createUnit(testDiseaseUnit);
} catch (Exception e) {
}
}
/**
* Test to create a link record and then query to find is that record is linked.
*
*/
@Test
- public void testLinkingPatientRecord() {
+ public void testLinkingPatientRecord() throws Exception {
Patient patient = new Patient();
patient.setUnitcode(testRenalUnit);
patient.setSurname("Test");
patient.setForename("Test");
patient.setDob(new Date());
patient.setNhsno("234235242");
DiseaseGroup diseaseGroup = new DiseaseGroup();
diseaseGroup.setId(testDiseaseUnit);
patient.setDiseaseGroup(diseaseGroup);
// Save the patient record before linking because the record should already exist
demographicsDao.saveDemographics(patient);
patientLinkManager.linkPatientRecord(patient);
List<PatientLink> patientLink = patientLinkManager.getPatientLink(patient.getNhsno(), testRenalUnit);
Assert.assertTrue("The list return should not be empty." , CollectionUtils.isNotEmpty(patientLink));
Assert.assertTrue("The should only be one link recreated", patientLink.size() == 1);
}
@After
public void tearDown(){
try {
this.clearData();
} catch (Exception e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
}
| true | true | public void testLinkingPatientRecord() {
Patient patient = new Patient();
patient.setUnitcode(testRenalUnit);
patient.setSurname("Test");
patient.setForename("Test");
patient.setDob(new Date());
patient.setNhsno("234235242");
DiseaseGroup diseaseGroup = new DiseaseGroup();
diseaseGroup.setId(testDiseaseUnit);
patient.setDiseaseGroup(diseaseGroup);
// Save the patient record before linking because the record should already exist
demographicsDao.saveDemographics(patient);
patientLinkManager.linkPatientRecord(patient);
List<PatientLink> patientLink = patientLinkManager.getPatientLink(patient.getNhsno(), testRenalUnit);
Assert.assertTrue("The list return should not be empty." , CollectionUtils.isNotEmpty(patientLink));
Assert.assertTrue("The should only be one link recreated", patientLink.size() == 1);
}
| public void testLinkingPatientRecord() throws Exception {
Patient patient = new Patient();
patient.setUnitcode(testRenalUnit);
patient.setSurname("Test");
patient.setForename("Test");
patient.setDob(new Date());
patient.setNhsno("234235242");
DiseaseGroup diseaseGroup = new DiseaseGroup();
diseaseGroup.setId(testDiseaseUnit);
patient.setDiseaseGroup(diseaseGroup);
// Save the patient record before linking because the record should already exist
demographicsDao.saveDemographics(patient);
patientLinkManager.linkPatientRecord(patient);
List<PatientLink> patientLink = patientLinkManager.getPatientLink(patient.getNhsno(), testRenalUnit);
Assert.assertTrue("The list return should not be empty." , CollectionUtils.isNotEmpty(patientLink));
Assert.assertTrue("The should only be one link recreated", patientLink.size() == 1);
}
|
diff --git a/src/ch/amana/android/cputuner/view/fragments/ProfilesListFragment.java b/src/ch/amana/android/cputuner/view/fragments/ProfilesListFragment.java
index 51cac8c9..e1f62d2d 100644
--- a/src/ch/amana/android/cputuner/view/fragments/ProfilesListFragment.java
+++ b/src/ch/amana/android/cputuner/view/fragments/ProfilesListFragment.java
@@ -1,400 +1,400 @@
package ch.amana.android.cputuner.view.fragments;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.ContentUris;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationSet;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.SimpleCursorAdapter.ViewBinder;
import android.widget.TextView;
import ch.amana.android.cputuner.R;
import ch.amana.android.cputuner.helper.GeneralMenuHelper;
import ch.amana.android.cputuner.helper.Logger;
import ch.amana.android.cputuner.helper.SettingsStorage;
import ch.amana.android.cputuner.hw.HardwareHandler;
import ch.amana.android.cputuner.hw.PowerProfiles;
import ch.amana.android.cputuner.model.ModelAccess;
import ch.amana.android.cputuner.model.ProfileModel;
import ch.amana.android.cputuner.model.VirtualGovernorModel;
import ch.amana.android.cputuner.provider.CpuTunerProvider;
import ch.amana.android.cputuner.provider.db.DB;
import ch.amana.android.cputuner.provider.db.DB.CpuProfile;
import ch.amana.android.cputuner.provider.db.DB.VirtualGovernor;
import ch.amana.android.cputuner.view.activity.CpuTunerViewpagerActivity;
import ch.amana.android.cputuner.view.activity.CpuTunerViewpagerActivity.StateChangeListener;
import ch.amana.android.cputuner.view.activity.HelpActivity;
import ch.amana.android.cputuner.view.adapter.PagerAdapter;
import com.markupartist.android.widget.ActionBar;
import com.markupartist.android.widget.ActionBar.Action;
public class ProfilesListFragment extends PagerListFragment implements StateChangeListener {
private static final int ALPHA_ON = 200;
private static final int ALPHA_OFF = 40;
private static final int ALPHA_LEAVE = 100;
private SimpleCursorAdapter adapter;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Activity act = getActivity();
Cursor c = act.managedQuery(DB.CpuProfile.CONTENT_URI, DB.CpuProfile.PROJECTION_DEFAULT, null, null, DB.CpuProfile.SORTORDER_DEFAULT);
adapter = new SimpleCursorAdapter(act, R.layout.profile_item, c,
new String[] { DB.CpuProfile.NAME_PROFILE_NAME, DB.CpuProfile.NAME_GOVERNOR,
DB.CpuProfile.NAME_FREQUENCY_MIN, DB.CpuProfile.NAME_FREQUENCY_MAX, DB.CpuProfile.NAME_WIFI_STATE, DB.CpuProfile.NAME_GPS_STATE,
DB.CpuProfile.NAME_BLUETOOTH_STATE, DB.CpuProfile.NAME_MOBILEDATA_3G_STATE, DB.CpuProfile.NAME_BACKGROUND_SYNC_STATE,
DB.CpuProfile.NAME_MOBILEDATA_CONNECTION_STATE, DB.CpuProfile.NAME_AIRPLANEMODE_STATE },
new int[] { R.id.tvName, R.id.tvGov, R.id.tvFreqMin, R.id.tvFreqMax, R.id.ivServiceWifi, R.id.ivServiceGPS, R.id.ivServiceBluetooth,
R.id.ivServiceMD3g, R.id.ivServiceSync, R.id.ivServiceMDCon, R.id.ivServiceAirplane });
adapter.setViewBinder(new ViewBinder() {
@Override
public boolean setViewValue(View view, Cursor cursor, int
columnIndex) {
if (cursor == null) {
return false;
}
if (columnIndex == DB.CpuProfile.INDEX_PROFILE_NAME) {
- ProfileModel currentProfile = PowerProfiles.getInstance().getCurrentProfile();
+ ProfileModel currentProfile = PowerProfiles.getInstance(getActivity()).getCurrentProfile();
int color = Color.LTGRAY;
if (currentProfile != null && currentProfile.getDbId() == cursor.getLong(DB.INDEX_ID) && SettingsStorage.getInstance().isEnableProfiles()) {
color = getResources().getColor(R.color.cputuner_green);
}
((TextView) view).setTextColor(color);
} else if (columnIndex == DB.CpuProfile.INDEX_GOVERNOR) {
if (SettingsStorage.getInstance().isUseVirtualGovernors()) {
int virtGovId = cursor.getInt(CpuProfile.INDEX_VIRTUAL_GOVERNOR);
if (virtGovId > -1) {
Cursor virtGovCursor = getActivity().managedQuery(VirtualGovernor.CONTENT_URI, VirtualGovernor.PROJECTION_DEFAULT, DB.SELECTION_BY_ID,
new String[] { virtGovId + "" }, VirtualGovernor.SORTORDER_DEFAULT);
if (virtGovCursor.moveToFirst()) {
VirtualGovernorModel vgm = new VirtualGovernorModel(virtGovCursor);
((TextView) view).setText(vgm.getVirtualGovernorName());
((TextView) ((View) view.getParent()).findViewById(R.id.labelGovernor)).setText(R.string.labelVirtualGovernor);
return true;
}
}
}
StringBuilder sb = new StringBuilder();
sb.append(cursor.getString(DB.CpuProfile.INDEX_GOVERNOR));
int up = cursor.getInt(DB.CpuProfile.INDEX_GOVERNOR_THRESHOLD_UP);
if (up > 0) {
sb.append(" (");
int down = cursor.getInt(DB.CpuProfile.INDEX_GOVERNOR_THRESHOLD_DOWN);
if (down > 0) {
sb.append(down).append("% - ");
}
sb.append(up).append("%)");
}
((TextView) view).setText(sb.toString());
return true;
} else if (columnIndex == DB.CpuProfile.INDEX_FREQUENCY_MIN
|| columnIndex == DB.CpuProfile.INDEX_FREQUENCY_MAX) {
int freq = cursor.getInt(columnIndex);
if (freq == HardwareHandler.NO_VALUE_INT) {
((TextView) view).setText(R.string.notAvailable);
} else {
((TextView) view).setText(ProfileModel.convertFreq2GHz(freq));
}
return true;
} else if (columnIndex == DB.CpuProfile.INDEX_GPS_STATE) {
if (SettingsStorage.getInstance().isEnableSwitchGps()) {
view.setVisibility(View.VISIBLE);
setServiceStateIcon((ImageView) view, cursor.getInt(columnIndex));
} else {
view.setVisibility(View.GONE);
}
return true;
} else if (columnIndex == DB.CpuProfile.INDEX_WIFI_STATE) {
if (SettingsStorage.getInstance().isEnableSwitchWifi()) {
view.setVisibility(View.VISIBLE);
setServiceStateIcon((ImageView) view, cursor.getInt(columnIndex));
} else {
view.setVisibility(View.GONE);
}
return true;
} else if (columnIndex == DB.CpuProfile.INDEX_BLUETOOTH_STATE) {
if (SettingsStorage.getInstance().isEnableSwitchBluetooth()) {
view.setVisibility(View.VISIBLE);
setServiceStateIcon((ImageView) view, cursor.getInt(columnIndex));
} else {
view.setVisibility(View.GONE);
}
return true;
} else if (columnIndex == DB.CpuProfile.INDEX_BACKGROUND_SYNC_STATE) {
if (SettingsStorage.getInstance().isEnableSwitchBackgroundSync()) {
view.setVisibility(View.VISIBLE);
setServiceStateIcon((ImageView) view, cursor.getInt(columnIndex));
} else {
view.setVisibility(View.GONE);
}
return true;
} else if (columnIndex == DB.CpuProfile.INDEX_MOBILEDATA_3G_STATE) {
if (!SettingsStorage.getInstance().isEnableSwitchMobiledata3G()) {
view.setVisibility(View.GONE);
return true;
}
view.setVisibility(View.VISIBLE);
ImageView icon = (ImageView) view;
icon.clearAnimation();
int state = cursor.getInt(columnIndex);
if (state == PowerProfiles.SERVICE_STATE_2G) {
icon.setImageResource(R.drawable.serviceicon_md_2g);
} else if (state == PowerProfiles.SERVICE_STATE_2G_3G) {
icon.setImageResource(R.drawable.serviceicon_md_2g3g);
} else if (state == PowerProfiles.SERVICE_STATE_3G) {
icon.setImageResource(R.drawable.serviceicon_md_3g);
} else if (state == PowerProfiles.SERVICE_STATE_PREV) {
icon.setImageResource(R.drawable.serviceicon_md_2g3g);
setAnimation(icon, R.anim.back);
}
if (state == PowerProfiles.SERVICE_STATE_LEAVE) {
icon.setAlpha(ALPHA_LEAVE);
} else {
icon.setAlpha(ALPHA_ON);
}
return true;
} else if (columnIndex == DB.CpuProfile.INDEX_MOBILEDATA_CONNECTION_STATE) {
if (SettingsStorage.getInstance().isEnableSwitchMobiledataConnection()) {
view.setVisibility(View.VISIBLE);
setServiceStateIcon((ImageView) view, cursor.getInt(columnIndex));
} else {
view.setVisibility(View.GONE);
}
return true;
} else if (columnIndex == DB.CpuProfile.INDEX_AIRPLANEMODE_STATE) {
if (SettingsStorage.getInstance().isEnableAirplaneMode()) {
view.setVisibility(View.VISIBLE);
setServiceStateIcon((ImageView) view, cursor.getInt(columnIndex));
} else {
view.setVisibility(View.GONE);
}
return true;
}
return false;
}
private void setServiceStateIcon(ImageView icon, int state) {
icon.clearAnimation();
if (state == PowerProfiles.SERVICE_STATE_LEAVE) {
icon.setAlpha(ALPHA_LEAVE);
} else if (state == PowerProfiles.SERVICE_STATE_OFF) {
icon.setAlpha(ALPHA_OFF);
} else if (state == PowerProfiles.SERVICE_STATE_PREV) {
setAnimation(icon, R.anim.back);
} else if (state == PowerProfiles.SERVICE_STATE_PULSE) {
setAnimation(icon, R.anim.pluse);
} else {
icon.setAlpha(ALPHA_ON);
}
}
});
setListAdapter(adapter);
getListView().setOnCreateContextMenuListener(this);
if (act instanceof CpuTunerViewpagerActivity) {
((CpuTunerViewpagerActivity) act).addStateChangeListener(this);
}
}
@Override
public void onDestroy() {
Activity act = getActivity();
if (act instanceof CpuTunerViewpagerActivity) {
if (act != null) {
((CpuTunerViewpagerActivity) act).addStateChangeListener(this);
}
}
super.onDestroy();
}
private void setAnimation(final View v, int resID) {
final AnimationSet c = (AnimationSet) AnimationUtils.loadAnimation(getActivity(), resID);
c.setRepeatMode(Animation.RESTART);
c.setRepeatCount(Animation.INFINITE);
c.setAnimationListener(new AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationRepeat(Animation animation) {
Logger.i("Repeat anim");
}
@Override
public void onAnimationEnd(Animation animation) {
v.clearAnimation();
v.startAnimation(c);
}
});
v.clearAnimation();
v.startAnimation(c);
}
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
Uri uri = ContentUris.withAppendedId(DB.CpuProfile.CONTENT_URI, id);
startActivity(new Intent(Intent.ACTION_EDIT, uri));
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
getActivity().getMenuInflater().inflate(R.menu.db_list_context, menu);
}
@Override
public boolean onContextItemSelected(MenuItem item) {
if (!this.getClass().equals(PagerAdapter.getCurrentItem().getClass())) {
return false;
}
super.onContextItemSelected(item);
AdapterView.AdapterContextMenuInfo info;
try {
info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
} catch (ClassCastException e) {
Logger.e("bad menuInfo", e);
return false;
}
final Uri uri = ContentUris.withAppendedId(DB.CpuProfile.CONTENT_URI, info.id);
switch (item.getItemId()) {
case R.id.menuItemDelete:
deleteProfile(uri);
return true;
case R.id.menuItemEdit:
startActivity(new Intent(Intent.ACTION_EDIT, uri));
return true;
case R.id.menuItemInsertAsNew:
startActivity(new Intent(CpuTunerProvider.ACTION_INSERT_AS_NEW, uri));
return true;
default:
return handleCommonMenu(getActivity(), item);
}
}
private void deleteProfile(final Uri uri) {
final Activity act = getActivity();
Builder alertBuilder = new AlertDialog.Builder(act);
if (ModelAccess.getInstace(getActivity()).isProfileUsed(ContentUris.parseId(uri))) {
// no not delete
alertBuilder.setTitle(R.string.menuItemDelete);
alertBuilder.setMessage(R.string.msgDeleteTriggerNotPossible);
alertBuilder.setNegativeButton(android.R.string.ok, null);
} else {
alertBuilder.setTitle(R.string.menuItemDelete);
alertBuilder.setMessage(R.string.msg_delete_selected_item);
alertBuilder.setNegativeButton(android.R.string.no, null);
alertBuilder.setPositiveButton(android.R.string.yes, new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
ModelAccess.getInstace(getActivity()).delete(uri);
}
});
}
AlertDialog alert = alertBuilder.create();
alert.show();
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.list_option, menu);
}
@Override
public boolean onOptionsItemSelected(Activity act, MenuItem item) {
if (handleCommonMenu(act, item)) {
return true;
}
if (GeneralMenuHelper.onOptionsItemSelected(act, item, HelpActivity.PAGE_PROFILE)) {
return true;
}
return false;
}
private boolean handleCommonMenu(Activity act, MenuItem item) {
switch (item.getItemId()) {
case R.id.menuItemInsert:
act.startActivity(new Intent(Intent.ACTION_INSERT, DB.CpuProfile.CONTENT_URI));
return true;
}
return false;
}
@Override
public List<Action> getActions() {
List<Action> actions = new ArrayList<ActionBar.Action>(1);
actions.add(new Action() {
@Override
public void performAction(View view) {
Intent intent = new Intent(Intent.ACTION_INSERT, DB.CpuProfile.CONTENT_URI);
view.getContext().startActivity(intent);
}
@Override
public int getDrawable() {
return android.R.drawable.ic_menu_add;
}
});
return actions;
}
@Override
public void profileChanged() {
getListView().setAdapter(adapter);
}
@Override
public void deviceStatusChanged() {
}
@Override
public void triggerChanged() {
}
}
| true | true | public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Activity act = getActivity();
Cursor c = act.managedQuery(DB.CpuProfile.CONTENT_URI, DB.CpuProfile.PROJECTION_DEFAULT, null, null, DB.CpuProfile.SORTORDER_DEFAULT);
adapter = new SimpleCursorAdapter(act, R.layout.profile_item, c,
new String[] { DB.CpuProfile.NAME_PROFILE_NAME, DB.CpuProfile.NAME_GOVERNOR,
DB.CpuProfile.NAME_FREQUENCY_MIN, DB.CpuProfile.NAME_FREQUENCY_MAX, DB.CpuProfile.NAME_WIFI_STATE, DB.CpuProfile.NAME_GPS_STATE,
DB.CpuProfile.NAME_BLUETOOTH_STATE, DB.CpuProfile.NAME_MOBILEDATA_3G_STATE, DB.CpuProfile.NAME_BACKGROUND_SYNC_STATE,
DB.CpuProfile.NAME_MOBILEDATA_CONNECTION_STATE, DB.CpuProfile.NAME_AIRPLANEMODE_STATE },
new int[] { R.id.tvName, R.id.tvGov, R.id.tvFreqMin, R.id.tvFreqMax, R.id.ivServiceWifi, R.id.ivServiceGPS, R.id.ivServiceBluetooth,
R.id.ivServiceMD3g, R.id.ivServiceSync, R.id.ivServiceMDCon, R.id.ivServiceAirplane });
adapter.setViewBinder(new ViewBinder() {
@Override
public boolean setViewValue(View view, Cursor cursor, int
columnIndex) {
if (cursor == null) {
return false;
}
if (columnIndex == DB.CpuProfile.INDEX_PROFILE_NAME) {
ProfileModel currentProfile = PowerProfiles.getInstance().getCurrentProfile();
int color = Color.LTGRAY;
if (currentProfile != null && currentProfile.getDbId() == cursor.getLong(DB.INDEX_ID) && SettingsStorage.getInstance().isEnableProfiles()) {
color = getResources().getColor(R.color.cputuner_green);
}
((TextView) view).setTextColor(color);
} else if (columnIndex == DB.CpuProfile.INDEX_GOVERNOR) {
if (SettingsStorage.getInstance().isUseVirtualGovernors()) {
int virtGovId = cursor.getInt(CpuProfile.INDEX_VIRTUAL_GOVERNOR);
if (virtGovId > -1) {
Cursor virtGovCursor = getActivity().managedQuery(VirtualGovernor.CONTENT_URI, VirtualGovernor.PROJECTION_DEFAULT, DB.SELECTION_BY_ID,
new String[] { virtGovId + "" }, VirtualGovernor.SORTORDER_DEFAULT);
if (virtGovCursor.moveToFirst()) {
VirtualGovernorModel vgm = new VirtualGovernorModel(virtGovCursor);
((TextView) view).setText(vgm.getVirtualGovernorName());
((TextView) ((View) view.getParent()).findViewById(R.id.labelGovernor)).setText(R.string.labelVirtualGovernor);
return true;
}
}
}
StringBuilder sb = new StringBuilder();
sb.append(cursor.getString(DB.CpuProfile.INDEX_GOVERNOR));
int up = cursor.getInt(DB.CpuProfile.INDEX_GOVERNOR_THRESHOLD_UP);
if (up > 0) {
sb.append(" (");
int down = cursor.getInt(DB.CpuProfile.INDEX_GOVERNOR_THRESHOLD_DOWN);
if (down > 0) {
sb.append(down).append("% - ");
}
sb.append(up).append("%)");
}
((TextView) view).setText(sb.toString());
return true;
} else if (columnIndex == DB.CpuProfile.INDEX_FREQUENCY_MIN
|| columnIndex == DB.CpuProfile.INDEX_FREQUENCY_MAX) {
int freq = cursor.getInt(columnIndex);
if (freq == HardwareHandler.NO_VALUE_INT) {
((TextView) view).setText(R.string.notAvailable);
} else {
((TextView) view).setText(ProfileModel.convertFreq2GHz(freq));
}
return true;
} else if (columnIndex == DB.CpuProfile.INDEX_GPS_STATE) {
if (SettingsStorage.getInstance().isEnableSwitchGps()) {
view.setVisibility(View.VISIBLE);
setServiceStateIcon((ImageView) view, cursor.getInt(columnIndex));
} else {
view.setVisibility(View.GONE);
}
return true;
} else if (columnIndex == DB.CpuProfile.INDEX_WIFI_STATE) {
if (SettingsStorage.getInstance().isEnableSwitchWifi()) {
view.setVisibility(View.VISIBLE);
setServiceStateIcon((ImageView) view, cursor.getInt(columnIndex));
} else {
view.setVisibility(View.GONE);
}
return true;
} else if (columnIndex == DB.CpuProfile.INDEX_BLUETOOTH_STATE) {
if (SettingsStorage.getInstance().isEnableSwitchBluetooth()) {
view.setVisibility(View.VISIBLE);
setServiceStateIcon((ImageView) view, cursor.getInt(columnIndex));
} else {
view.setVisibility(View.GONE);
}
return true;
} else if (columnIndex == DB.CpuProfile.INDEX_BACKGROUND_SYNC_STATE) {
if (SettingsStorage.getInstance().isEnableSwitchBackgroundSync()) {
view.setVisibility(View.VISIBLE);
setServiceStateIcon((ImageView) view, cursor.getInt(columnIndex));
} else {
view.setVisibility(View.GONE);
}
return true;
} else if (columnIndex == DB.CpuProfile.INDEX_MOBILEDATA_3G_STATE) {
if (!SettingsStorage.getInstance().isEnableSwitchMobiledata3G()) {
view.setVisibility(View.GONE);
return true;
}
view.setVisibility(View.VISIBLE);
ImageView icon = (ImageView) view;
icon.clearAnimation();
int state = cursor.getInt(columnIndex);
if (state == PowerProfiles.SERVICE_STATE_2G) {
icon.setImageResource(R.drawable.serviceicon_md_2g);
} else if (state == PowerProfiles.SERVICE_STATE_2G_3G) {
icon.setImageResource(R.drawable.serviceicon_md_2g3g);
} else if (state == PowerProfiles.SERVICE_STATE_3G) {
icon.setImageResource(R.drawable.serviceicon_md_3g);
} else if (state == PowerProfiles.SERVICE_STATE_PREV) {
icon.setImageResource(R.drawable.serviceicon_md_2g3g);
setAnimation(icon, R.anim.back);
}
if (state == PowerProfiles.SERVICE_STATE_LEAVE) {
icon.setAlpha(ALPHA_LEAVE);
} else {
icon.setAlpha(ALPHA_ON);
}
return true;
} else if (columnIndex == DB.CpuProfile.INDEX_MOBILEDATA_CONNECTION_STATE) {
if (SettingsStorage.getInstance().isEnableSwitchMobiledataConnection()) {
view.setVisibility(View.VISIBLE);
setServiceStateIcon((ImageView) view, cursor.getInt(columnIndex));
} else {
view.setVisibility(View.GONE);
}
return true;
} else if (columnIndex == DB.CpuProfile.INDEX_AIRPLANEMODE_STATE) {
if (SettingsStorage.getInstance().isEnableAirplaneMode()) {
view.setVisibility(View.VISIBLE);
setServiceStateIcon((ImageView) view, cursor.getInt(columnIndex));
} else {
view.setVisibility(View.GONE);
}
return true;
}
return false;
}
private void setServiceStateIcon(ImageView icon, int state) {
icon.clearAnimation();
if (state == PowerProfiles.SERVICE_STATE_LEAVE) {
icon.setAlpha(ALPHA_LEAVE);
} else if (state == PowerProfiles.SERVICE_STATE_OFF) {
icon.setAlpha(ALPHA_OFF);
} else if (state == PowerProfiles.SERVICE_STATE_PREV) {
setAnimation(icon, R.anim.back);
} else if (state == PowerProfiles.SERVICE_STATE_PULSE) {
setAnimation(icon, R.anim.pluse);
} else {
icon.setAlpha(ALPHA_ON);
}
}
});
setListAdapter(adapter);
getListView().setOnCreateContextMenuListener(this);
if (act instanceof CpuTunerViewpagerActivity) {
((CpuTunerViewpagerActivity) act).addStateChangeListener(this);
}
}
| public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Activity act = getActivity();
Cursor c = act.managedQuery(DB.CpuProfile.CONTENT_URI, DB.CpuProfile.PROJECTION_DEFAULT, null, null, DB.CpuProfile.SORTORDER_DEFAULT);
adapter = new SimpleCursorAdapter(act, R.layout.profile_item, c,
new String[] { DB.CpuProfile.NAME_PROFILE_NAME, DB.CpuProfile.NAME_GOVERNOR,
DB.CpuProfile.NAME_FREQUENCY_MIN, DB.CpuProfile.NAME_FREQUENCY_MAX, DB.CpuProfile.NAME_WIFI_STATE, DB.CpuProfile.NAME_GPS_STATE,
DB.CpuProfile.NAME_BLUETOOTH_STATE, DB.CpuProfile.NAME_MOBILEDATA_3G_STATE, DB.CpuProfile.NAME_BACKGROUND_SYNC_STATE,
DB.CpuProfile.NAME_MOBILEDATA_CONNECTION_STATE, DB.CpuProfile.NAME_AIRPLANEMODE_STATE },
new int[] { R.id.tvName, R.id.tvGov, R.id.tvFreqMin, R.id.tvFreqMax, R.id.ivServiceWifi, R.id.ivServiceGPS, R.id.ivServiceBluetooth,
R.id.ivServiceMD3g, R.id.ivServiceSync, R.id.ivServiceMDCon, R.id.ivServiceAirplane });
adapter.setViewBinder(new ViewBinder() {
@Override
public boolean setViewValue(View view, Cursor cursor, int
columnIndex) {
if (cursor == null) {
return false;
}
if (columnIndex == DB.CpuProfile.INDEX_PROFILE_NAME) {
ProfileModel currentProfile = PowerProfiles.getInstance(getActivity()).getCurrentProfile();
int color = Color.LTGRAY;
if (currentProfile != null && currentProfile.getDbId() == cursor.getLong(DB.INDEX_ID) && SettingsStorage.getInstance().isEnableProfiles()) {
color = getResources().getColor(R.color.cputuner_green);
}
((TextView) view).setTextColor(color);
} else if (columnIndex == DB.CpuProfile.INDEX_GOVERNOR) {
if (SettingsStorage.getInstance().isUseVirtualGovernors()) {
int virtGovId = cursor.getInt(CpuProfile.INDEX_VIRTUAL_GOVERNOR);
if (virtGovId > -1) {
Cursor virtGovCursor = getActivity().managedQuery(VirtualGovernor.CONTENT_URI, VirtualGovernor.PROJECTION_DEFAULT, DB.SELECTION_BY_ID,
new String[] { virtGovId + "" }, VirtualGovernor.SORTORDER_DEFAULT);
if (virtGovCursor.moveToFirst()) {
VirtualGovernorModel vgm = new VirtualGovernorModel(virtGovCursor);
((TextView) view).setText(vgm.getVirtualGovernorName());
((TextView) ((View) view.getParent()).findViewById(R.id.labelGovernor)).setText(R.string.labelVirtualGovernor);
return true;
}
}
}
StringBuilder sb = new StringBuilder();
sb.append(cursor.getString(DB.CpuProfile.INDEX_GOVERNOR));
int up = cursor.getInt(DB.CpuProfile.INDEX_GOVERNOR_THRESHOLD_UP);
if (up > 0) {
sb.append(" (");
int down = cursor.getInt(DB.CpuProfile.INDEX_GOVERNOR_THRESHOLD_DOWN);
if (down > 0) {
sb.append(down).append("% - ");
}
sb.append(up).append("%)");
}
((TextView) view).setText(sb.toString());
return true;
} else if (columnIndex == DB.CpuProfile.INDEX_FREQUENCY_MIN
|| columnIndex == DB.CpuProfile.INDEX_FREQUENCY_MAX) {
int freq = cursor.getInt(columnIndex);
if (freq == HardwareHandler.NO_VALUE_INT) {
((TextView) view).setText(R.string.notAvailable);
} else {
((TextView) view).setText(ProfileModel.convertFreq2GHz(freq));
}
return true;
} else if (columnIndex == DB.CpuProfile.INDEX_GPS_STATE) {
if (SettingsStorage.getInstance().isEnableSwitchGps()) {
view.setVisibility(View.VISIBLE);
setServiceStateIcon((ImageView) view, cursor.getInt(columnIndex));
} else {
view.setVisibility(View.GONE);
}
return true;
} else if (columnIndex == DB.CpuProfile.INDEX_WIFI_STATE) {
if (SettingsStorage.getInstance().isEnableSwitchWifi()) {
view.setVisibility(View.VISIBLE);
setServiceStateIcon((ImageView) view, cursor.getInt(columnIndex));
} else {
view.setVisibility(View.GONE);
}
return true;
} else if (columnIndex == DB.CpuProfile.INDEX_BLUETOOTH_STATE) {
if (SettingsStorage.getInstance().isEnableSwitchBluetooth()) {
view.setVisibility(View.VISIBLE);
setServiceStateIcon((ImageView) view, cursor.getInt(columnIndex));
} else {
view.setVisibility(View.GONE);
}
return true;
} else if (columnIndex == DB.CpuProfile.INDEX_BACKGROUND_SYNC_STATE) {
if (SettingsStorage.getInstance().isEnableSwitchBackgroundSync()) {
view.setVisibility(View.VISIBLE);
setServiceStateIcon((ImageView) view, cursor.getInt(columnIndex));
} else {
view.setVisibility(View.GONE);
}
return true;
} else if (columnIndex == DB.CpuProfile.INDEX_MOBILEDATA_3G_STATE) {
if (!SettingsStorage.getInstance().isEnableSwitchMobiledata3G()) {
view.setVisibility(View.GONE);
return true;
}
view.setVisibility(View.VISIBLE);
ImageView icon = (ImageView) view;
icon.clearAnimation();
int state = cursor.getInt(columnIndex);
if (state == PowerProfiles.SERVICE_STATE_2G) {
icon.setImageResource(R.drawable.serviceicon_md_2g);
} else if (state == PowerProfiles.SERVICE_STATE_2G_3G) {
icon.setImageResource(R.drawable.serviceicon_md_2g3g);
} else if (state == PowerProfiles.SERVICE_STATE_3G) {
icon.setImageResource(R.drawable.serviceicon_md_3g);
} else if (state == PowerProfiles.SERVICE_STATE_PREV) {
icon.setImageResource(R.drawable.serviceicon_md_2g3g);
setAnimation(icon, R.anim.back);
}
if (state == PowerProfiles.SERVICE_STATE_LEAVE) {
icon.setAlpha(ALPHA_LEAVE);
} else {
icon.setAlpha(ALPHA_ON);
}
return true;
} else if (columnIndex == DB.CpuProfile.INDEX_MOBILEDATA_CONNECTION_STATE) {
if (SettingsStorage.getInstance().isEnableSwitchMobiledataConnection()) {
view.setVisibility(View.VISIBLE);
setServiceStateIcon((ImageView) view, cursor.getInt(columnIndex));
} else {
view.setVisibility(View.GONE);
}
return true;
} else if (columnIndex == DB.CpuProfile.INDEX_AIRPLANEMODE_STATE) {
if (SettingsStorage.getInstance().isEnableAirplaneMode()) {
view.setVisibility(View.VISIBLE);
setServiceStateIcon((ImageView) view, cursor.getInt(columnIndex));
} else {
view.setVisibility(View.GONE);
}
return true;
}
return false;
}
private void setServiceStateIcon(ImageView icon, int state) {
icon.clearAnimation();
if (state == PowerProfiles.SERVICE_STATE_LEAVE) {
icon.setAlpha(ALPHA_LEAVE);
} else if (state == PowerProfiles.SERVICE_STATE_OFF) {
icon.setAlpha(ALPHA_OFF);
} else if (state == PowerProfiles.SERVICE_STATE_PREV) {
setAnimation(icon, R.anim.back);
} else if (state == PowerProfiles.SERVICE_STATE_PULSE) {
setAnimation(icon, R.anim.pluse);
} else {
icon.setAlpha(ALPHA_ON);
}
}
});
setListAdapter(adapter);
getListView().setOnCreateContextMenuListener(this);
if (act instanceof CpuTunerViewpagerActivity) {
((CpuTunerViewpagerActivity) act).addStateChangeListener(this);
}
}
|
diff --git a/org.eclipse.jface.text/src/org/eclipse/jface/text/source/OverviewRuler.java b/org.eclipse.jface.text/src/org/eclipse/jface/text/source/OverviewRuler.java
index eeaf65c16..b4a07b87d 100644
--- a/org.eclipse.jface.text/src/org/eclipse/jface/text/source/OverviewRuler.java
+++ b/org.eclipse.jface.text/src/org/eclipse/jface/text/source/OverviewRuler.java
@@ -1,1233 +1,1233 @@
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jface.text.source;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.custom.ViewForm;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseMoveListener;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Cursor;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Canvas;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.ITextListener;
import org.eclipse.jface.text.ITextViewer;
import org.eclipse.jface.text.ITextViewerExtension5;
import org.eclipse.jface.text.Position;
import org.eclipse.jface.text.Region;
import org.eclipse.jface.text.TextEvent;
/**
* Ruler presented next to a source viewer showing all annotations of the
* viewer's annotation model in a compact format. The ruler has the same height
* as the source viewer.<p>
* Clients usually instantiate and configure objects of this class.
*
* @since 2.1
*/
public class OverviewRuler implements IOverviewRuler {
/**
* Internal listener class.
*/
class InternalListener implements ITextListener, IAnnotationModelListener {
/*
* @see ITextListener#textChanged
*/
public void textChanged(TextEvent e) {
if (fTextViewer != null && e.getDocumentEvent() == null && e.getViewerRedrawState()) {
// handle only changes of visible document
redraw();
}
}
/*
* @see IAnnotationModelListener#modelChanged(IAnnotationModel)
*/
public void modelChanged(IAnnotationModel model) {
update();
}
}
/**
* Enumerates the annotations of a specified type and characteristics
* of the associated annotation model.
*/
class FilterIterator implements Iterator {
private final static int IGNORE= 0;
private final static int TEMPORARY= 1;
private final static int PERSISTENT= 2;
private Iterator fIterator;
private Object fType;
private Annotation fNext;
private int fTemporary;
public FilterIterator() {
this(null, IGNORE);
}
public FilterIterator(Object annotationType) {
this(annotationType, IGNORE);
}
public FilterIterator(Object annotationType, boolean temporary) {
this(annotationType, temporary ? TEMPORARY : PERSISTENT);
}
private FilterIterator(Object annotationType, int temporary) {
fType= annotationType;
fTemporary= temporary;
if (fModel != null) {
fIterator= fModel.getAnnotationIterator();
skip();
}
}
public FilterIterator(Object annotationType, boolean temporary, Iterator iterator) {
fType= annotationType;
fTemporary= temporary ? TEMPORARY : PERSISTENT;
fIterator= iterator;
skip();
}
private void skip() {
while (fIterator.hasNext()) {
Annotation next= (Annotation) fIterator.next();
if (next.isMarkedDeleted())
continue;
fNext= next;
Object annotationType= next.getType();
if (fType == null || isSubtype(annotationType)) {
if (fTemporary == IGNORE) return;
boolean temporary= !next.isPersistent();
if (fTemporary == TEMPORARY && temporary) return;
if (fTemporary == PERSISTENT && !temporary) return;
}
}
fNext= null;
}
private boolean isSubtype(Object annotationType) {
if (fAnnotationAccess instanceof IAnnotationAccessExtension) {
IAnnotationAccessExtension extension= (IAnnotationAccessExtension) fAnnotationAccess;
return extension.isSubtype(annotationType, fType);
}
return fType.equals(annotationType);
}
/*
* @see Iterator#hasNext()
*/
public boolean hasNext() {
return fNext != null;
}
/*
* @see Iterator#next()
*/
public Object next() {
try {
return fNext;
} finally {
if (fIterator != null)
skip();
}
}
/*
* @see Iterator#remove()
*/
public void remove() {
throw new UnsupportedOperationException();
}
}
/**
* The painter of the overview ruler's header.
*/
class HeaderPainter implements PaintListener {
private Color fIndicatorColor;
private Color fSeparatorColor;
public HeaderPainter() {
fSeparatorColor= fSharedTextColors.getColor(ViewForm.borderInsideRGB);
}
public void setColor(Color color) {
fIndicatorColor= color;
}
private void drawBevelRect(GC gc, int x, int y, int w, int h, Color topLeft, Color bottomRight) {
gc.setForeground(topLeft == null ? fSeparatorColor : topLeft);
gc.drawLine(x, y, x + w -1, y);
gc.drawLine(x, y, x, y + h -1);
gc.setForeground(bottomRight == null ? fSeparatorColor : bottomRight);
gc.drawLine(x + w, y, x + w, y + h);
gc.drawLine(x, y + h, x + w, y + h);
}
public void paintControl(PaintEvent e) {
Point s= fHeader.getSize();
if (fIndicatorColor != null) {
e.gc.setBackground(fIndicatorColor);
Rectangle r= new Rectangle(INSET, (s.y - (2*ANNOTATION_HEIGHT)) / 2, s.x - (2*INSET), 2*ANNOTATION_HEIGHT);
e.gc.fillRectangle(r);
Display d= fHeader.getDisplay();
if (d != null)
// drawBevelRect(e.gc, r.x, r.y, r.width -1, r.height -1, d.getSystemColor(SWT.COLOR_WIDGET_NORMAL_SHADOW), d.getSystemColor(SWT.COLOR_WIDGET_HIGHLIGHT_SHADOW));
drawBevelRect(e.gc, r.x, r.y, r.width -1, r.height -1, null, null);
}
e.gc.setForeground(fSeparatorColor);
e.gc.setLineWidth(1);
e.gc.drawLine(0, s.y -1, s.x -1, s.y -1);
}
}
private static final int INSET= 2;
private static final int ANNOTATION_HEIGHT= 4;
private static boolean ANNOTATION_HEIGHT_SCALABLE= true;
/** The model of the overview ruler */
private IAnnotationModel fModel;
/** The view to which this ruler is connected */
private ITextViewer fTextViewer;
/** The ruler's canvas */
private Canvas fCanvas;
/** The ruler's header */
private Canvas fHeader;
/** The drawable for double buffering */
private Image fBuffer;
/** The internal listener */
private InternalListener fInternalListener= new InternalListener();
/** The width of this vertical ruler */
private int fWidth;
/** The hit detection cursor */
private Cursor fHitDetectionCursor;
/** The last cursor */
private Cursor fLastCursor;
/** The line of the last mouse button activity */
private int fLastMouseButtonActivityLine= -1;
/** The actual annotation height */
private int fAnnotationHeight= -1;
/** The annotation access */
private IAnnotationAccess fAnnotationAccess;
/** The header painter */
private HeaderPainter fHeaderPainter;
/**
* The list of annotation types to be shown in this ruler.
* @since 3.0
*/
private Set fConfiguredAnnotationTypes= new HashSet();
/**
* The list of annotation types to be shown in the header of this ruler.
* @since 3.0
*/
private Set fConfiguredHeaderAnnotationTypes= new HashSet();
/** The mapping between annotation types and colors */
private Map fAnnotationTypes2Colors= new HashMap();
/** The color manager */
private ISharedTextColors fSharedTextColors;
/**
* All available annotation types sorted by layer.
*
* @since 3.0
*/
private List fAnnotationsSortedByLayer= new ArrayList();
/**
* All available layers sorted by layer.
* This list may contain duplicates.
* @since 3.0
*/
private List fLayersSortedByLayer= new ArrayList();
/**
* Map of allowed annotation types.
* An allowed annotation type maps to <code>true</code>, a disallowed
* to <code>false</code>.
* @since 3.0
*/
private Map fAllowedAnnotationTypes= new HashMap();
/**
* Map of allowed header annotation types.
* An allowed annotation type maps to <code>true</code>, a disallowed
* to <code>false</code>.
* @since 3.0
*/
private Map fAllowedHeaderAnnotationTypes= new HashMap();
/**
* The cached annotations.
* @since 3.0
*/
private List fCachedAnnotations= new ArrayList();
/**
* Constructs a overview ruler of the given width using the given annotation access and the given
* color manager.
*
* @param annotationAccess the annotation access
* @param width the width of the vertical ruler
* @param sharedColors the color manager
*/
public OverviewRuler(IAnnotationAccess annotationAccess, int width, ISharedTextColors sharedColors) {
fAnnotationAccess= annotationAccess;
fWidth= width;
fSharedTextColors= sharedColors;
}
/*
* @see org.eclipse.jface.text.source.IVerticalRulerInfo#getControl()
*/
public Control getControl() {
return fCanvas;
}
/*
* @see org.eclipse.jface.text.source.IVerticalRulerInfo#getWidth()
*/
public int getWidth() {
return fWidth;
}
/*
* @see org.eclipse.jface.text.source.IVerticalRuler#setModel(org.eclipse.jface.text.source.IAnnotationModel)
*/
public void setModel(IAnnotationModel model) {
if (model != fModel || model != null) {
if (fModel != null)
fModel.removeAnnotationModelListener(fInternalListener);
fModel= model;
if (fModel != null)
fModel.addAnnotationModelListener(fInternalListener);
update();
}
}
/*
* @see org.eclipse.jface.text.source.IVerticalRuler#createControl(org.eclipse.swt.widgets.Composite, org.eclipse.jface.text.ITextViewer)
*/
public Control createControl(Composite parent, ITextViewer textViewer) {
fTextViewer= textViewer;
fHitDetectionCursor= new Cursor(parent.getDisplay(), SWT.CURSOR_HAND);
fHeader= new Canvas(parent, SWT.NONE);
fCanvas= new Canvas(parent, SWT.NO_BACKGROUND);
fCanvas.addPaintListener(new PaintListener() {
public void paintControl(PaintEvent event) {
if (fTextViewer != null)
doubleBufferPaint(event.gc);
}
});
fCanvas.addDisposeListener(new DisposeListener() {
public void widgetDisposed(DisposeEvent event) {
handleDispose();
fTextViewer= null;
}
});
fCanvas.addMouseListener(new MouseAdapter() {
public void mouseDown(MouseEvent event) {
handleMouseDown(event);
}
});
fCanvas.addMouseMoveListener(new MouseMoveListener() {
public void mouseMove(MouseEvent event) {
handleMouseMove(event);
}
});
if (fTextViewer != null)
fTextViewer.addTextListener(fInternalListener);
return fCanvas;
}
/**
* Disposes the ruler's resources.
*/
private void handleDispose() {
if (fTextViewer != null) {
fTextViewer.removeTextListener(fInternalListener);
fTextViewer= null;
}
if (fModel != null)
fModel.removeAnnotationModelListener(fInternalListener);
if (fBuffer != null) {
fBuffer.dispose();
fBuffer= null;
}
if (fHitDetectionCursor != null) {
fHitDetectionCursor.dispose();
fHitDetectionCursor= null;
}
fConfiguredAnnotationTypes.clear();
fAllowedAnnotationTypes.clear();
fConfiguredHeaderAnnotationTypes.clear();
fAllowedHeaderAnnotationTypes.clear();
fAnnotationTypes2Colors.clear();
fAnnotationsSortedByLayer.clear();
fLayersSortedByLayer.clear();
}
/**
* Double buffer drawing.
*
* @param dest the GC to draw into
*/
private void doubleBufferPaint(GC dest) {
Point size= fCanvas.getSize();
if (size.x <= 0 || size.y <= 0)
return;
if (fBuffer != null) {
Rectangle r= fBuffer.getBounds();
if (r.width != size.x || r.height != size.y) {
fBuffer.dispose();
fBuffer= null;
}
}
if (fBuffer == null)
fBuffer= new Image(fCanvas.getDisplay(), size.x, size.y);
GC gc= new GC(fBuffer);
try {
gc.setBackground(fCanvas.getBackground());
gc.fillRectangle(0, 0, size.x, size.y);
if (fTextViewer instanceof ITextViewerExtension5)
doPaint1(gc);
else
doPaint(gc);
} finally {
gc.dispose();
}
dest.drawImage(fBuffer, 0, 0);
}
/**
* Draws this overview ruler.
*
* @param gc the GC to draw into
*/
private void doPaint(GC gc) {
if (fTextViewer == null)
return;
Rectangle r= new Rectangle(0, 0, 0, 0);
int yy, hh= ANNOTATION_HEIGHT;
IDocument document= fTextViewer.getDocument();
IRegion visible= fTextViewer.getVisibleRegion();
StyledText textWidget= fTextViewer.getTextWidget();
int maxLines= textWidget.getLineCount();
Point size= fCanvas.getSize();
int writable= maxLines * textWidget.getLineHeight();
if (size.y > writable)
size.y= Math.max(writable - fHeader.getSize().y, 0);
for (Iterator iterator= fAnnotationsSortedByLayer.iterator(); iterator.hasNext();) {
Object annotationType= iterator.next();
if (skip(annotationType))
continue;
boolean[] temporary= new boolean[] { false, true };
for (int t=0; t < temporary.length; t++) {
Iterator e= new FilterIterator(annotationType, temporary[t]);
Color fill= getFillColor(annotationType, temporary[t]);
Color stroke= getStrokeColor(annotationType, temporary[t]);
for (int i= 0; e.hasNext(); i++) {
Annotation a= (Annotation) e.next();
Position p= fModel.getPosition(a);
if (p == null || !p.overlapsWith(visible.getOffset(), visible.getLength()))
continue;
int annotationOffset= Math.max(p.getOffset(), visible.getOffset());
int annotationEnd= Math.min(p.getOffset() + p.getLength(), visible.getOffset() + visible.getLength());
int annotationLength= annotationEnd - annotationOffset;
try {
if (ANNOTATION_HEIGHT_SCALABLE) {
int numbersOfLines= document.getNumberOfLines(annotationOffset, annotationLength);
// don't count empty trailing lines
IRegion lastLine= document.getLineInformationOfOffset(annotationOffset + annotationLength);
if (lastLine.getOffset() == annotationOffset + annotationLength) {
numbersOfLines -= 2;
hh= (numbersOfLines * size.y) / maxLines + ANNOTATION_HEIGHT;
if (hh < ANNOTATION_HEIGHT)
hh= ANNOTATION_HEIGHT;
} else
hh= ANNOTATION_HEIGHT;
}
fAnnotationHeight= hh;
int startLine= textWidget.getLineAtOffset(annotationOffset - visible.getOffset());
yy= Math.min((startLine * size.y) / maxLines, size.y - hh);
if (fill != null) {
gc.setBackground(fill);
gc.fillRectangle(INSET, yy, size.x-(2*INSET), hh);
}
if (stroke != null) {
gc.setForeground(stroke);
r.x= INSET;
r.y= yy;
r.width= size.x - (2 * INSET) - 1;
r.height= hh;
gc.setLineWidth(1);
gc.drawRectangle(r);
}
} catch (BadLocationException x) {
}
}
}
}
}
/**
* Draws this overview ruler. Uses <code>ITextViewerExtension5</code> for
* its implementation. Will replace <code>doPaint(GC)</code>.
*
* @param gc the GC to draw into
*/
private void doPaint1(GC gc) {
- if (fTextViewer == null)
+ if (fTextViewer == null || fModel == null)
return;
Rectangle r= new Rectangle(0, 0, 0, 0);
int yy, hh= ANNOTATION_HEIGHT;
ITextViewerExtension5 extension= (ITextViewerExtension5) fTextViewer;
IDocument document= fTextViewer.getDocument();
StyledText textWidget= fTextViewer.getTextWidget();
int maxLines= textWidget.getLineCount();
Point size= fCanvas.getSize();
int writable= maxLines * textWidget.getLineHeight();
if (size.y > writable)
size.y= Math.max(writable - fHeader.getSize().y, 0);
fCachedAnnotations.clear();
Iterator iter= fModel.getAnnotationIterator();
while (iter.hasNext()) {
Annotation annotation= (Annotation) iter.next();
if (annotation.isMarkedDeleted())
continue;
if (skip(annotation.getType()))
continue;
fCachedAnnotations.add(annotation);
}
for (Iterator iterator= fAnnotationsSortedByLayer.iterator(); iterator.hasNext();) {
Object annotationType= iterator.next();
if (skip(annotationType))
continue;
boolean[] temporary= new boolean[] { false, true };
for (int t=0; t < temporary.length; t++) {
Iterator e= new FilterIterator(annotationType, temporary[t], fCachedAnnotations.iterator());
Color fill= getFillColor(annotationType, temporary[t]);
Color stroke= getStrokeColor(annotationType, temporary[t]);
for (int i= 0; e.hasNext(); i++) {
Annotation a= (Annotation) e.next();
Position p= fModel.getPosition(a);
if (p == null)
continue;
IRegion widgetRegion= extension.modelRange2WidgetRange(new Region(p.getOffset(), p.getLength()));
if (widgetRegion == null)
continue;
try {
if (ANNOTATION_HEIGHT_SCALABLE) {
int numbersOfLines= document.getNumberOfLines(p.getOffset(), p.getLength());
// don't count empty trailing lines
IRegion lastLine= document.getLineInformationOfOffset(p.getOffset() + p.getLength());
if (lastLine.getOffset() == p.getOffset() + p.getLength()) {
numbersOfLines -= 2;
hh= (numbersOfLines * size.y) / maxLines + ANNOTATION_HEIGHT;
if (hh < ANNOTATION_HEIGHT)
hh= ANNOTATION_HEIGHT;
} else
hh= ANNOTATION_HEIGHT;
}
fAnnotationHeight= hh;
int startLine= textWidget.getLineAtOffset(widgetRegion.getOffset());
yy= Math.min((startLine * size.y) / maxLines, size.y - hh);
if (fill != null) {
gc.setBackground(fill);
gc.fillRectangle(INSET, yy, size.x-(2*INSET), hh);
}
if (stroke != null) {
gc.setForeground(stroke);
r.x= INSET;
r.y= yy;
r.width= size.x - (2 * INSET) - 1;
r.height= hh;
gc.setLineWidth(1);
gc.drawRectangle(r);
}
} catch (BadLocationException x) {
}
}
}
}
fCachedAnnotations.clear();
}
/*
* @see org.eclipse.jface.text.source.IVerticalRuler#update()
*/
public void update() {
if (fCanvas != null && !fCanvas.isDisposed()) {
Display d= fCanvas.getDisplay();
if (d != null) {
d.asyncExec(new Runnable() {
public void run() {
redraw();
updateHeader();
}
});
}
}
}
/**
* Redraws the overview ruler.
*/
private void redraw() {
if (fCanvas != null && !fCanvas.isDisposed()) {
GC gc= new GC(fCanvas);
doubleBufferPaint(gc);
gc.dispose();
}
}
/**
* Translates a given y-coordinate of this ruler into the corresponding
* document lines. The number of lines depends on the concrete scaling
* given as the ration between the height of this ruler and the length
* of the document.
*
* @param y_coordinate the y-coordinate
* @return the corresponding document lines
*/
private int[] toLineNumbers(int y_coordinate) {
StyledText textWidget= fTextViewer.getTextWidget();
int maxLines= textWidget.getContent().getLineCount();
int rulerLength= fCanvas.getSize().y;
int writable= maxLines * textWidget.getLineHeight();
if (rulerLength > writable)
rulerLength= Math.max(writable - fHeader.getSize().y, 0);
if (y_coordinate >= writable || y_coordinate >= rulerLength)
return new int[] {-1, -1};
int[] lines= new int[2];
int pixel= Math.max(y_coordinate - 1, 0);
lines[0]= (pixel * maxLines) / rulerLength;
pixel= Math.min(rulerLength, y_coordinate + 1);
lines[1]= (pixel * maxLines) / rulerLength;
if (fTextViewer instanceof ITextViewerExtension5) {
ITextViewerExtension5 extension= (ITextViewerExtension5) fTextViewer;
lines[0]= extension.widgetLine2ModelLine(lines[0]);
lines[1]= extension.widgetLine2ModelLine(lines[1]);
} else {
try {
IRegion visible= fTextViewer.getVisibleRegion();
int lineNumber= fTextViewer.getDocument().getLineOfOffset(visible.getOffset());
lines[0] += lineNumber;
lines[1] += lineNumber;
} catch (BadLocationException x) {
}
}
return lines;
}
/**
* Returns the position of the first annotation found in the given line range.
*
* @param lineNumbers the line range
* @param ignoreSelectedAnnotation whether to ignore the current selection
* @return the position of the first found annotation
*/
private Position getAnnotationPosition(int[] lineNumbers, boolean ignoreSelectedAnnotation) {
if (lineNumbers[0] == -1)
return null;
Position found= null;
try {
IDocument d= fTextViewer.getDocument();
IRegion line= d.getLineInformation(lineNumbers[0]);
Point currentSelection= fTextViewer.getSelectedRange();
int start= line.getOffset();
line= d.getLineInformation(lineNumbers[lineNumbers.length - 1]);
int end= line.getOffset() + line.getLength();
for (int i= fAnnotationsSortedByLayer.size() -1; i >= 0; i--) {
Object annotationType= fAnnotationsSortedByLayer.get(i);
Iterator e= new FilterIterator(annotationType);
while (e.hasNext() && found == null) {
Annotation a= (Annotation) e.next();
if (a.isMarkedDeleted())
continue;
if (skip(a.getType()))
continue;
Position p= fModel.getPosition(a);
if (p == null)
continue;
int posOffset= p.getOffset();
int posEnd= posOffset + p.getLength();
IRegion region= d.getLineInformationOfOffset(posEnd);
// trailing empty lines don't count
if (posEnd > posOffset && region.getOffset() == posEnd) {
posEnd--;
region= d.getLineInformationOfOffset(posEnd);
}
if (posOffset <= end && posEnd >= start) {
if ((found == null || posOffset < found.getOffset()) && (ignoreSelectedAnnotation || currentSelection.x != posOffset || currentSelection.y != p.getLength()))
found= p;
}
}
}
} catch (BadLocationException x) {
}
return found;
}
/**
* Returns the line which corresponds best to one of
* the underlying annotations at the given y-coordinate.
*
* @param lineNumbers the line numbers
* @return the best matching line or <code>-1</code> if no such line can be found
*/
private int findBestMatchingLineNumber(int[] lineNumbers) {
if (lineNumbers == null || lineNumbers.length < 1)
return -1;
try {
Position pos= getAnnotationPosition(lineNumbers, true);
if (pos == null)
return -1;
return fTextViewer.getDocument().getLineOfOffset(pos.getOffset());
} catch (BadLocationException ex) {
return -1;
}
}
/**
* Handles mouse clicks.
*
* @param event the mouse button down event
*/
private void handleMouseDown(MouseEvent event) {
if (fTextViewer != null) {
int[] lines= toLineNumbers(event.y);
Position p= getAnnotationPosition(lines, false);
if (p != null) {
fTextViewer.revealRange(p.getOffset(), p.getLength());
fTextViewer.setSelectedRange(p.getOffset(), p.getLength());
}
fTextViewer.getTextWidget().setFocus();
}
fLastMouseButtonActivityLine= toDocumentLineNumber(event.y);
}
/**
* Handles mouse moves.
*
* @param event the mouse move event
*/
private void handleMouseMove(MouseEvent event) {
if (fTextViewer != null) {
int[] lines= toLineNumbers(event.y);
Position p= getAnnotationPosition(lines, true);
Cursor cursor= (p != null ? fHitDetectionCursor : null);
if (cursor != fLastCursor) {
fCanvas.setCursor(cursor);
fLastCursor= cursor;
}
}
}
/*
* @see org.eclipse.jface.text.source.IOverviewRuler#addAnnotationType(java.lang.Object)
*/
public void addAnnotationType(Object annotationType) {
fConfiguredAnnotationTypes.add(annotationType);
fAllowedAnnotationTypes.clear();
}
/*
* @see org.eclipse.jface.text.source.IOverviewRuler#removeAnnotationType(java.lang.Object)
*/
public void removeAnnotationType(Object annotationType) {
fConfiguredAnnotationTypes.remove(annotationType);
fAllowedAnnotationTypes.clear();
}
/*
* @see org.eclipse.jface.text.source.IOverviewRuler#setAnnotationTypeLayer(java.lang.Object, int)
*/
public void setAnnotationTypeLayer(Object annotationType, int layer) {
Integer layerObj= new Integer(layer);
if (fAnnotationsSortedByLayer.remove(annotationType))
fLayersSortedByLayer.remove(layerObj);
if (layer >= 0) {
int i= 0;
int size= fLayersSortedByLayer.size();
while (i < size && layer >= ((Integer)fLayersSortedByLayer.get(i)).intValue())
i++;
fLayersSortedByLayer.add(i, layerObj);
fAnnotationsSortedByLayer.add(i, annotationType);
}
}
/*
* @see org.eclipse.jface.text.source.IOverviewRuler#setAnnotationTypeColor(java.lang.Object, org.eclipse.swt.graphics.Color)
*/
public void setAnnotationTypeColor(Object annotationType, Color color) {
if (color != null)
fAnnotationTypes2Colors.put(annotationType, color);
else
fAnnotationTypes2Colors.remove(annotationType);
}
/**
* Returns whether the given annotation type should be skipped by the drawing routine.
*
* @param annotationType the annotation type
* @return <code>true</code> if annotation of the given type should be skipped
*/
private boolean skip(Object annotationType) {
return !contains(annotationType, fAllowedAnnotationTypes, fConfiguredAnnotationTypes);
}
/**
* Returns whether the given annotation type should be skipped by the drawing routine of the header.
*
* @param annotationType the annotation type
* @return <code>true</code> if annotation of the given type should be skipped
* @since 3.0
*/
private boolean skipInHeader(Object annotationType) {
return !contains(annotationType, fAllowedHeaderAnnotationTypes, fConfiguredHeaderAnnotationTypes);
}
/**
* Returns whether the given annotation type is mapped to <code>true</code>
* in the given <code>allowed</code> map or covered by the <code>configured</code>
* set.
*
* @param annotationType the annotation type
* @param allowed the map with allowed annotation types mapped to booleans
* @param configured the set with configured annotation types
* @return <code>true</code> if annotation is contained, <code>false</code>
* otherwise
* @since 3.0
*/
private boolean contains(Object annotationType, Map allowed, Set configured) {
Boolean cached= (Boolean) allowed.get(annotationType);
if (cached != null)
return cached.booleanValue();
boolean covered= isCovered(annotationType, configured);
allowed.put(annotationType, covered ? Boolean.TRUE : Boolean.FALSE);
return covered;
}
/**
* Computes whether the annotations of the given type are covered by the given <code>configured</code>
* set. This is the case if either the type of the annotation or any of its
* super types is contained in the <code>configured</code> set.
*
* @param annotationType the annotation type
* @param configured the set with configured annotation types
* @return <code>true</code> if annotation is covered, <code>false</code>
* otherwise
* @since 3.0
*/
private boolean isCovered(Object annotationType, Set configured) {
if (fAnnotationAccess instanceof IAnnotationAccessExtension) {
IAnnotationAccessExtension extension= (IAnnotationAccessExtension) fAnnotationAccess;
Iterator e= configured.iterator();
while (e.hasNext()) {
if (extension.isSubtype(annotationType,e.next()))
return true;
}
return false;
}
return configured.contains(annotationType);
}
/**
* Returns a specification of a color that lies between the given
* foreground and background color using the given scale factor.
*
* @param fg the foreground color
* @param bg the background color
* @param scale the scale factor
* @return the interpolated color
*/
private static RGB interpolate(RGB fg, RGB bg, double scale) {
return new RGB(
(int) ((1.0-scale) * fg.red + scale * bg.red),
(int) ((1.0-scale) * fg.green + scale * bg.green),
(int) ((1.0-scale) * fg.blue + scale * bg.blue)
);
}
/**
* Returns the grey value in which the given color would be drawn in grey-scale.
*
* @param rgb the color
* @return the grey-scale value
*/
private static double greyLevel(RGB rgb) {
if (rgb.red == rgb.green && rgb.green == rgb.blue)
return rgb.red;
return (0.299 * rgb.red + 0.587 * rgb.green + 0.114 * rgb.blue + 0.5);
}
/**
* Returns whether the given color is dark or light depending on the colors grey-scale level.
*
* @param rgb the color
* @return <code>true</code> if the color is dark, <code>false</code> if it is light
*/
private static boolean isDark(RGB rgb) {
return greyLevel(rgb) > 128;
}
/**
* Returns a color based on the color configured for the given annotation type and the given scale factor.
*
* @param annotationType the annotation type
* @param scale the scale factor
* @return the computed color
*/
private Color getColor(Object annotationType, double scale) {
Color base= findColor(annotationType);
if (base == null)
return null;
RGB baseRGB= base.getRGB();
RGB background= fCanvas.getBackground().getRGB();
boolean darkBase= isDark(baseRGB);
boolean darkBackground= isDark(background);
if (darkBase && darkBackground)
background= new RGB(255, 255, 255);
else if (!darkBase && !darkBackground)
background= new RGB(0, 0, 0);
return fSharedTextColors.getColor(interpolate(baseRGB, background, scale));
}
/**
* Returns the color for the given annotation type
*
* @param annotationType the annotation type
* @return the color
* @since 3.0
*/
private Color findColor(Object annotationType) {
Color color= (Color) fAnnotationTypes2Colors.get(annotationType);
if (color != null)
return color;
if (fAnnotationAccess instanceof IAnnotationAccessExtension) {
IAnnotationAccessExtension extension= (IAnnotationAccessExtension) fAnnotationAccess;
Object[] superTypes= extension.getSupertypes(annotationType);
if (superTypes != null) {
for (int i= 0; i < superTypes.length; i++) {
color= (Color) fAnnotationTypes2Colors.get(superTypes[i]);
if (color != null)
return color;
}
}
}
return null;
}
/**
* Returns the stroke color for the given annotation type and characteristics.
*
* @param annotationType the annotation type
* @param temporary <code>true</code> if for temporary annotations
* @return the stroke color
*/
private Color getStrokeColor(Object annotationType, boolean temporary) {
return getColor(annotationType, temporary ? 0.5 : 0.2);
}
/**
* Returns the fill color for the given annotation type and characteristics.
*
* @param annotationType the annotation type
* @param temporary <code>true</code> if for temporary annotations
* @return the fill color
*/
private Color getFillColor(Object annotationType, boolean temporary) {
return getColor(annotationType, temporary ? 0.9 : 0.6);
}
/*
* @see IVerticalRulerInfo#getLineOfLastMouseButtonActivity()
*/
public int getLineOfLastMouseButtonActivity() {
return fLastMouseButtonActivityLine;
}
/*
* @see IVerticalRulerInfo#toDocumentLineNumber(int)
*/
public int toDocumentLineNumber(int y_coordinate) {
if (fTextViewer == null || y_coordinate == -1)
return -1;
int[] lineNumbers= toLineNumbers(y_coordinate);
int bestLine= findBestMatchingLineNumber(lineNumbers);
if (bestLine == -1 && lineNumbers.length > 0)
return lineNumbers[0];
return bestLine;
}
/*
* @see org.eclipse.jface.text.source.IVerticalRuler#getModel()
*/
public IAnnotationModel getModel() {
return fModel;
}
/*
* @see org.eclipse.jface.text.source.IOverviewRuler#getAnnotationHeight()
*/
public int getAnnotationHeight() {
return fAnnotationHeight;
}
/*
* @see org.eclipse.jface.text.source.IOverviewRuler#hasAnnotation(int)
*/
public boolean hasAnnotation(int y) {
return findBestMatchingLineNumber(toLineNumbers(y)) != -1;
}
/*
* @see org.eclipse.jface.text.source.IOverviewRuler#getHeaderControl()
*/
public Control getHeaderControl() {
return fHeader;
}
/*
* @see org.eclipse.jface.text.source.IOverviewRuler#addHeaderAnnotationType(java.lang.Object)
*/
public void addHeaderAnnotationType(Object annotationType) {
fConfiguredHeaderAnnotationTypes.add(annotationType);
fAllowedHeaderAnnotationTypes.clear();
}
/*
* @see org.eclipse.jface.text.source.IOverviewRuler#removeHeaderAnnotationType(java.lang.Object)
*/
public void removeHeaderAnnotationType(Object annotationType) {
fConfiguredHeaderAnnotationTypes.remove(annotationType);
fAllowedHeaderAnnotationTypes.clear();
}
/**
* Updates the header of this ruler.
*/
private void updateHeader() {
if (fHeader == null || fHeader.isDisposed())
return;
Object colorType= null;
outer: for (int i= fAnnotationsSortedByLayer.size() -1; i >= 0; i--) {
Object annotationType= fAnnotationsSortedByLayer.get(i);
if (skipInHeader(annotationType) || skip(annotationType))
continue;
for (Iterator e= new FilterIterator(annotationType); e.hasNext();) {
if (e.next() != null) {
colorType= annotationType;
break outer;
}
}
}
Color color= null;
if (colorType != null)
color= findColor(colorType);
if (color == null) {
if (fHeaderPainter != null)
fHeaderPainter.setColor(null);
} else {
if (fHeaderPainter == null) {
fHeaderPainter= new HeaderPainter();
fHeader.addPaintListener(fHeaderPainter);
}
fHeaderPainter.setColor(color);
}
fHeader.redraw();
updateHeaderToolTipText();
}
/**
* Updates the tool tip text of the header of this ruler.
*
* @since 3.0
*/
private void updateHeaderToolTipText() {
if (fHeader == null || fHeader.isDisposed())
return;
fHeader.setToolTipText(null);
if (!(fAnnotationAccess instanceof IAnnotationAccessExtension))
return;
String overview= ""; //$NON-NLS-1$
for (int i= fAnnotationsSortedByLayer.size() -1; i >= 0; i--) {
Object annotationType= fAnnotationsSortedByLayer.get(i);
if (skipInHeader(annotationType) || skip(annotationType))
continue;
int count= 0;
String annotationTypeLabel= null;
for (Iterator e= new FilterIterator(annotationType); e.hasNext();) {
Annotation annotation= (Annotation)e.next();
if (annotation != null) {
if (annotationTypeLabel == null)
annotationTypeLabel= ((IAnnotationAccessExtension)fAnnotationAccess).getTypeLabel(annotation);
count++;
}
}
if (annotationTypeLabel != null) {
if (overview.length() > 0)
overview += "\n"; //$NON-NLS-1$
overview += JFaceTextMessages.getFormattedString("OverviewRulerHeader.toolTipTextEntry", new Object[] {annotationTypeLabel, new Integer(count)}); //$NON-NLS-1$
}
}
if (overview.length() > 0)
fHeader.setToolTipText(overview);
}
}
| true | true | private void doPaint1(GC gc) {
if (fTextViewer == null)
return;
Rectangle r= new Rectangle(0, 0, 0, 0);
int yy, hh= ANNOTATION_HEIGHT;
ITextViewerExtension5 extension= (ITextViewerExtension5) fTextViewer;
IDocument document= fTextViewer.getDocument();
StyledText textWidget= fTextViewer.getTextWidget();
int maxLines= textWidget.getLineCount();
Point size= fCanvas.getSize();
int writable= maxLines * textWidget.getLineHeight();
if (size.y > writable)
size.y= Math.max(writable - fHeader.getSize().y, 0);
fCachedAnnotations.clear();
Iterator iter= fModel.getAnnotationIterator();
while (iter.hasNext()) {
Annotation annotation= (Annotation) iter.next();
if (annotation.isMarkedDeleted())
continue;
if (skip(annotation.getType()))
continue;
fCachedAnnotations.add(annotation);
}
for (Iterator iterator= fAnnotationsSortedByLayer.iterator(); iterator.hasNext();) {
Object annotationType= iterator.next();
if (skip(annotationType))
continue;
boolean[] temporary= new boolean[] { false, true };
for (int t=0; t < temporary.length; t++) {
Iterator e= new FilterIterator(annotationType, temporary[t], fCachedAnnotations.iterator());
Color fill= getFillColor(annotationType, temporary[t]);
Color stroke= getStrokeColor(annotationType, temporary[t]);
for (int i= 0; e.hasNext(); i++) {
Annotation a= (Annotation) e.next();
Position p= fModel.getPosition(a);
if (p == null)
continue;
IRegion widgetRegion= extension.modelRange2WidgetRange(new Region(p.getOffset(), p.getLength()));
if (widgetRegion == null)
continue;
try {
if (ANNOTATION_HEIGHT_SCALABLE) {
int numbersOfLines= document.getNumberOfLines(p.getOffset(), p.getLength());
// don't count empty trailing lines
IRegion lastLine= document.getLineInformationOfOffset(p.getOffset() + p.getLength());
if (lastLine.getOffset() == p.getOffset() + p.getLength()) {
numbersOfLines -= 2;
hh= (numbersOfLines * size.y) / maxLines + ANNOTATION_HEIGHT;
if (hh < ANNOTATION_HEIGHT)
hh= ANNOTATION_HEIGHT;
} else
hh= ANNOTATION_HEIGHT;
}
fAnnotationHeight= hh;
int startLine= textWidget.getLineAtOffset(widgetRegion.getOffset());
yy= Math.min((startLine * size.y) / maxLines, size.y - hh);
if (fill != null) {
gc.setBackground(fill);
gc.fillRectangle(INSET, yy, size.x-(2*INSET), hh);
}
if (stroke != null) {
gc.setForeground(stroke);
r.x= INSET;
r.y= yy;
r.width= size.x - (2 * INSET) - 1;
r.height= hh;
gc.setLineWidth(1);
gc.drawRectangle(r);
}
} catch (BadLocationException x) {
}
}
}
}
fCachedAnnotations.clear();
}
| private void doPaint1(GC gc) {
if (fTextViewer == null || fModel == null)
return;
Rectangle r= new Rectangle(0, 0, 0, 0);
int yy, hh= ANNOTATION_HEIGHT;
ITextViewerExtension5 extension= (ITextViewerExtension5) fTextViewer;
IDocument document= fTextViewer.getDocument();
StyledText textWidget= fTextViewer.getTextWidget();
int maxLines= textWidget.getLineCount();
Point size= fCanvas.getSize();
int writable= maxLines * textWidget.getLineHeight();
if (size.y > writable)
size.y= Math.max(writable - fHeader.getSize().y, 0);
fCachedAnnotations.clear();
Iterator iter= fModel.getAnnotationIterator();
while (iter.hasNext()) {
Annotation annotation= (Annotation) iter.next();
if (annotation.isMarkedDeleted())
continue;
if (skip(annotation.getType()))
continue;
fCachedAnnotations.add(annotation);
}
for (Iterator iterator= fAnnotationsSortedByLayer.iterator(); iterator.hasNext();) {
Object annotationType= iterator.next();
if (skip(annotationType))
continue;
boolean[] temporary= new boolean[] { false, true };
for (int t=0; t < temporary.length; t++) {
Iterator e= new FilterIterator(annotationType, temporary[t], fCachedAnnotations.iterator());
Color fill= getFillColor(annotationType, temporary[t]);
Color stroke= getStrokeColor(annotationType, temporary[t]);
for (int i= 0; e.hasNext(); i++) {
Annotation a= (Annotation) e.next();
Position p= fModel.getPosition(a);
if (p == null)
continue;
IRegion widgetRegion= extension.modelRange2WidgetRange(new Region(p.getOffset(), p.getLength()));
if (widgetRegion == null)
continue;
try {
if (ANNOTATION_HEIGHT_SCALABLE) {
int numbersOfLines= document.getNumberOfLines(p.getOffset(), p.getLength());
// don't count empty trailing lines
IRegion lastLine= document.getLineInformationOfOffset(p.getOffset() + p.getLength());
if (lastLine.getOffset() == p.getOffset() + p.getLength()) {
numbersOfLines -= 2;
hh= (numbersOfLines * size.y) / maxLines + ANNOTATION_HEIGHT;
if (hh < ANNOTATION_HEIGHT)
hh= ANNOTATION_HEIGHT;
} else
hh= ANNOTATION_HEIGHT;
}
fAnnotationHeight= hh;
int startLine= textWidget.getLineAtOffset(widgetRegion.getOffset());
yy= Math.min((startLine * size.y) / maxLines, size.y - hh);
if (fill != null) {
gc.setBackground(fill);
gc.fillRectangle(INSET, yy, size.x-(2*INSET), hh);
}
if (stroke != null) {
gc.setForeground(stroke);
r.x= INSET;
r.y= yy;
r.width= size.x - (2 * INSET) - 1;
r.height= hh;
gc.setLineWidth(1);
gc.drawRectangle(r);
}
} catch (BadLocationException x) {
}
}
}
}
fCachedAnnotations.clear();
}
|
diff --git a/src/cz/muni/stanse/cppparser/CppUnit.java b/src/cz/muni/stanse/cppparser/CppUnit.java
index 01971cf..d1a549a 100644
--- a/src/cz/muni/stanse/cppparser/CppUnit.java
+++ b/src/cz/muni/stanse/cppparser/CppUnit.java
@@ -1,76 +1,76 @@
/* Distributed under GPLv2 */
package cz.muni.stanse.cppparser;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
import cz.muni.stanse.Stanse;
import cz.muni.stanse.cfgparser.CfgUnit;
import cz.muni.stanse.codestructures.Unit;
import cz.muni.stanse.codestructures.ParserException;
import cz.muni.stanse.codestructures.CFG;
import cz.muni.stanse.codestructures.CFGHandle;
/**
* Holds all the code-related data for C++ compilation units (files).
*/
public final class CppUnit extends Unit {
private List<String> args = null;
public CppUnit(List<String> args) {
this.args = args;
this.fileName = new File(args.get(0));
}
public void parse() throws ParserException {
String command = Stanse.getInstance().getRootDirectory()
- + File.separator + "bin" + File.separator + "cppparser";
+ + File.separator + "bin" + File.separator + "cpp2sir";
List<String> parserArgs = new ArrayList<String>();
parserArgs.add(command);
parserArgs.add("-J");
parserArgs.addAll(args);
ProcessBuilder builder = new ProcessBuilder(parserArgs);
try {
final Process p = builder.start();
new Thread() {
public void run() {
java.io.InputStreamReader sr = new java.io.InputStreamReader(
p.getErrorStream());
java.io.BufferedReader br = new java.io.BufferedReader(sr);
try {
String line = br.readLine();
while (line != null) {
System.err.println(line);
line = br.readLine();
}
br.close();
} catch (IOException ex) {
}
}
}.start();
java.io.InputStreamReader sr = new java.io.InputStreamReader(
p.getInputStream());
JSONTokener jsonTokener = new JSONTokener(sr);
JSONObject jsonUnit = new JSONObject(jsonTokener);
CFGs = CfgUnit.parseUnit(this.fileName.getParentFile(), jsonUnit);
} catch (IOException e) {
throw new ParserException("parser: " + e.getLocalizedMessage(), e);
} catch (JSONException e) {
throw new ParserException("parser: " + e.getLocalizedMessage(), e);
}
this.CFGHs = new ArrayList<CFGHandle>();
for (CFG cfg : CFGs)
CFGHs.add(new CFGHandle(this, cfg));
}
}
| true | true | public void parse() throws ParserException {
String command = Stanse.getInstance().getRootDirectory()
+ File.separator + "bin" + File.separator + "cppparser";
List<String> parserArgs = new ArrayList<String>();
parserArgs.add(command);
parserArgs.add("-J");
parserArgs.addAll(args);
ProcessBuilder builder = new ProcessBuilder(parserArgs);
try {
final Process p = builder.start();
new Thread() {
public void run() {
java.io.InputStreamReader sr = new java.io.InputStreamReader(
p.getErrorStream());
java.io.BufferedReader br = new java.io.BufferedReader(sr);
try {
String line = br.readLine();
while (line != null) {
System.err.println(line);
line = br.readLine();
}
br.close();
} catch (IOException ex) {
}
}
}.start();
java.io.InputStreamReader sr = new java.io.InputStreamReader(
p.getInputStream());
JSONTokener jsonTokener = new JSONTokener(sr);
JSONObject jsonUnit = new JSONObject(jsonTokener);
CFGs = CfgUnit.parseUnit(this.fileName.getParentFile(), jsonUnit);
} catch (IOException e) {
throw new ParserException("parser: " + e.getLocalizedMessage(), e);
} catch (JSONException e) {
throw new ParserException("parser: " + e.getLocalizedMessage(), e);
}
this.CFGHs = new ArrayList<CFGHandle>();
for (CFG cfg : CFGs)
CFGHs.add(new CFGHandle(this, cfg));
}
| public void parse() throws ParserException {
String command = Stanse.getInstance().getRootDirectory()
+ File.separator + "bin" + File.separator + "cpp2sir";
List<String> parserArgs = new ArrayList<String>();
parserArgs.add(command);
parserArgs.add("-J");
parserArgs.addAll(args);
ProcessBuilder builder = new ProcessBuilder(parserArgs);
try {
final Process p = builder.start();
new Thread() {
public void run() {
java.io.InputStreamReader sr = new java.io.InputStreamReader(
p.getErrorStream());
java.io.BufferedReader br = new java.io.BufferedReader(sr);
try {
String line = br.readLine();
while (line != null) {
System.err.println(line);
line = br.readLine();
}
br.close();
} catch (IOException ex) {
}
}
}.start();
java.io.InputStreamReader sr = new java.io.InputStreamReader(
p.getInputStream());
JSONTokener jsonTokener = new JSONTokener(sr);
JSONObject jsonUnit = new JSONObject(jsonTokener);
CFGs = CfgUnit.parseUnit(this.fileName.getParentFile(), jsonUnit);
} catch (IOException e) {
throw new ParserException("parser: " + e.getLocalizedMessage(), e);
} catch (JSONException e) {
throw new ParserException("parser: " + e.getLocalizedMessage(), e);
}
this.CFGHs = new ArrayList<CFGHandle>();
for (CFG cfg : CFGs)
CFGHs.add(new CFGHandle(this, cfg));
}
|
diff --git a/tests/org.eclipse.xtext.generator.tests/src/org/eclipse/xtext/parser/AbstractXtextGrammarParsingTest.java b/tests/org.eclipse.xtext.generator.tests/src/org/eclipse/xtext/parser/AbstractXtextGrammarParsingTest.java
index 9d11989ed..e8c7f43e2 100644
--- a/tests/org.eclipse.xtext.generator.tests/src/org/eclipse/xtext/parser/AbstractXtextGrammarParsingTest.java
+++ b/tests/org.eclipse.xtext.generator.tests/src/org/eclipse/xtext/parser/AbstractXtextGrammarParsingTest.java
@@ -1,43 +1,43 @@
/*******************************************************************************
* Copyright (c) 2009 itemis AG (http://www.itemis.eu) and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************/
package org.eclipse.xtext.parser;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import org.eclipse.xtext.GenerateAllTestGrammars;
import org.eclipse.xtext.util.CollectionUtils;
import org.eclipse.xtext.util.Function;
import org.eclipse.xtext.util.Pair;
import org.eclipse.xtext.util.Tuples;
/**
* @author Sebastian Zarnekow - Initial contribution and API
*/
public abstract class AbstractXtextGrammarParsingTest extends AbstractPackratAntlrComparingTest {
@Override
protected Iterable<Pair<String, String>> getAllModels() {
List<Class<?>> classes = Arrays.asList(GenerateAllTestGrammars.testclasses);
return CollectionUtils.map(classes, new Function<Class<?>, Pair<String, String>>() {
public Pair<String, String> exec(Class<?> param) {
- String filename = "" + param.getName().replace('.', '/') + ".xtext";
+ String filename = GenerateAllTestGrammars.getGrammarFileName(param);
String model;
try {
model = readFileIntoString(filename);
}
catch (IOException e) {
throw new RuntimeException(e);
}
return Tuples.create(param.getSimpleName(), model);
}
});
}
}
| true | true | protected Iterable<Pair<String, String>> getAllModels() {
List<Class<?>> classes = Arrays.asList(GenerateAllTestGrammars.testclasses);
return CollectionUtils.map(classes, new Function<Class<?>, Pair<String, String>>() {
public Pair<String, String> exec(Class<?> param) {
String filename = "" + param.getName().replace('.', '/') + ".xtext";
String model;
try {
model = readFileIntoString(filename);
}
catch (IOException e) {
throw new RuntimeException(e);
}
return Tuples.create(param.getSimpleName(), model);
}
});
}
| protected Iterable<Pair<String, String>> getAllModels() {
List<Class<?>> classes = Arrays.asList(GenerateAllTestGrammars.testclasses);
return CollectionUtils.map(classes, new Function<Class<?>, Pair<String, String>>() {
public Pair<String, String> exec(Class<?> param) {
String filename = GenerateAllTestGrammars.getGrammarFileName(param);
String model;
try {
model = readFileIntoString(filename);
}
catch (IOException e) {
throw new RuntimeException(e);
}
return Tuples.create(param.getSimpleName(), model);
}
});
}
|
diff --git a/weasis-base/weasis-base-explorer/src/main/java/org/weasis/base/explorer/JIThumbnailCache.java b/weasis-base/weasis-base-explorer/src/main/java/org/weasis/base/explorer/JIThumbnailCache.java
index fd93329c6..d3d27e152 100644
--- a/weasis-base/weasis-base-explorer/src/main/java/org/weasis/base/explorer/JIThumbnailCache.java
+++ b/weasis-base/weasis-base-explorer/src/main/java/org/weasis/base/explorer/JIThumbnailCache.java
@@ -1,175 +1,177 @@
package org.weasis.base.explorer;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.File;
import java.io.IOException;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import javax.media.jai.PlanarImage;
import javax.media.jai.operator.SubsampleAverageDescriptor;
import javax.swing.Icon;
import org.weasis.core.api.gui.util.GuiExecutor;
import org.weasis.core.api.image.util.ImageFiler;
import org.weasis.core.api.media.data.ImageElement;
import org.weasis.core.api.media.data.Thumbnail;
import com.sun.media.jai.codec.FileSeekableStream;
import com.sun.media.jai.codec.ImageCodec;
import com.sun.media.jai.codec.ImageDecoder;
public final class JIThumbnailCache {
private static JIThumbnailCache instance;
// Set only one concurrent thread, because of the imageio issue with native library
// (https://jai-imageio-core.dev.java.net/issues/show_bug.cgi?id=126)
private static final ExecutorService qExecutor = Executors.newFixedThreadPool(1);
private final Map<String, ThumbnailIcon> cachedThumbnails;
private JIThumbnailCache() {
this.cachedThumbnails = Collections.synchronizedMap(new LinkedHashMap<String, ThumbnailIcon>(80) {
private static final int MAX_ENTRIES = 50;
@Override
protected boolean removeEldestEntry(final Map.Entry eldest) {
return size() > MAX_ENTRIES;
}
});
}
public static JIThumbnailCache getInstance() {
if (instance == null) {
instance = new JIThumbnailCache();
}
return instance;
}
public synchronized void invalidate() {
this.cachedThumbnails.clear();
}
public Icon getThumbnailFor(final ImageElement diskObject, final JIThumbnailList list, final int index) {
try {
final ThumbnailIcon jiIcon = this.cachedThumbnails.get(diskObject.getFile().getPath());
if (jiIcon != null) {
return jiIcon;
}
} catch (final Exception e) {
// log.debug(e);
}
if (!diskObject.isLoading()) {
loadThumbnail(diskObject, list, index);
}
return null;
}
private void loadThumbnail(final ImageElement diskObject, final JIThumbnailList thumbnailList, final int index) {
if ((index > thumbnailList.getLastVisibleIndex()) || (index < thumbnailList.getFirstVisibleIndex())) {
return;
}
try {
// ///////////////////////////////////////////////////////////////////////
JIThumbnailCache.qExecutor.execute(new Runnable() {
@Override
public void run() {
RenderedImage img = null;
String mime = diskObject.getMimeType();
if (mime == null) {
mime = "";
}
String cfile = diskObject.getFile().getAbsolutePath();
String tiled_File = thumbnailList.getThumbnailListModel().getFileInCache(cfile);
if (tiled_File != null) {
try {
ImageDecoder dec =
ImageCodec.createImageDecoder("tiff", new FileSeekableStream(tiled_File == null
? diskObject.getFile() : new File(JIListModel.EXPLORER_CACHE_DIR, tiled_File)),
null);
int count = dec.getNumPages();
if (count == 2) {
RenderedImage src2 = dec.decodeAsRenderedImage(1);
if (src2.getWidth() <= Thumbnail.MAX_SIZE) {
img = src2;
}
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
if (img == null) {
img = diskObject.getRenderedImage(diskObject.getImage(null));
}
if (img == null) {
return;
}
if (tiled_File == null) {
/*
* Make an image cache with its thumbnail when the image size is larger than a tile size and if
* not DICOM file
*/
if ((img.getWidth() > ImageFiler.TILESIZE || img.getHeight() > ImageFiler.TILESIZE)
&& !mime.contains("dicom")) {
File imgCacheFile = null;
try {
imgCacheFile = File.createTempFile("tiled_", ".tif", JIListModel.EXPLORER_CACHE_DIR); //$NON-NLS-1$ //$NON-NLS-2$
} catch (IOException e) {
e.printStackTrace();
}
if (ImageFiler.writeTIFF(imgCacheFile, img, true, true, false)) {
+ // Prevent to many files open on Linux (Ubuntu => 1024) and close image stream
+ diskObject.removeImageFromCache();
thumbnailList.getThumbnailListModel().putFileInCache(cfile, imgCacheFile.getName());
} else {
// TODO make it invalid
}
return;
}
}
final double scale =
Math.min(ThumbnailRenderer.ICON_DIM.height / (double) img.getHeight(),
ThumbnailRenderer.ICON_DIM.width / (double) img.getWidth());
final BufferedImage tIcon =
scale <= 1.0 ? scale > 0.005 ? SubsampleAverageDescriptor.create(img, scale, scale,
Thumbnail.DownScaleQualityHints).getAsBufferedImage() : null : PlanarImage
.wrapRenderedImage(img).getAsBufferedImage();
// Prevent to many files open on Linux (Ubuntu => 1024) and close image stream
diskObject.removeImageFromCache();
GuiExecutor.instance().execute(new Runnable() {
@Override
public void run() {
if (tIcon != null) {
JIThumbnailCache.this.cachedThumbnails.put(diskObject.getFile().getPath(),
new ThumbnailIcon(tIcon));
}
thumbnailList.getThumbnailListModel().notifyAsUpdated(index);
}
});
}
});
// ///////////////////////////////////////////////////////////////////////
} catch (final Exception exp) {
// log.debug(exp);
}
}
}
| true | true | private void loadThumbnail(final ImageElement diskObject, final JIThumbnailList thumbnailList, final int index) {
if ((index > thumbnailList.getLastVisibleIndex()) || (index < thumbnailList.getFirstVisibleIndex())) {
return;
}
try {
// ///////////////////////////////////////////////////////////////////////
JIThumbnailCache.qExecutor.execute(new Runnable() {
@Override
public void run() {
RenderedImage img = null;
String mime = diskObject.getMimeType();
if (mime == null) {
mime = "";
}
String cfile = diskObject.getFile().getAbsolutePath();
String tiled_File = thumbnailList.getThumbnailListModel().getFileInCache(cfile);
if (tiled_File != null) {
try {
ImageDecoder dec =
ImageCodec.createImageDecoder("tiff", new FileSeekableStream(tiled_File == null
? diskObject.getFile() : new File(JIListModel.EXPLORER_CACHE_DIR, tiled_File)),
null);
int count = dec.getNumPages();
if (count == 2) {
RenderedImage src2 = dec.decodeAsRenderedImage(1);
if (src2.getWidth() <= Thumbnail.MAX_SIZE) {
img = src2;
}
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
if (img == null) {
img = diskObject.getRenderedImage(diskObject.getImage(null));
}
if (img == null) {
return;
}
if (tiled_File == null) {
/*
* Make an image cache with its thumbnail when the image size is larger than a tile size and if
* not DICOM file
*/
if ((img.getWidth() > ImageFiler.TILESIZE || img.getHeight() > ImageFiler.TILESIZE)
&& !mime.contains("dicom")) {
File imgCacheFile = null;
try {
imgCacheFile = File.createTempFile("tiled_", ".tif", JIListModel.EXPLORER_CACHE_DIR); //$NON-NLS-1$ //$NON-NLS-2$
} catch (IOException e) {
e.printStackTrace();
}
if (ImageFiler.writeTIFF(imgCacheFile, img, true, true, false)) {
thumbnailList.getThumbnailListModel().putFileInCache(cfile, imgCacheFile.getName());
} else {
// TODO make it invalid
}
return;
}
}
final double scale =
Math.min(ThumbnailRenderer.ICON_DIM.height / (double) img.getHeight(),
ThumbnailRenderer.ICON_DIM.width / (double) img.getWidth());
final BufferedImage tIcon =
scale <= 1.0 ? scale > 0.005 ? SubsampleAverageDescriptor.create(img, scale, scale,
Thumbnail.DownScaleQualityHints).getAsBufferedImage() : null : PlanarImage
.wrapRenderedImage(img).getAsBufferedImage();
// Prevent to many files open on Linux (Ubuntu => 1024) and close image stream
diskObject.removeImageFromCache();
GuiExecutor.instance().execute(new Runnable() {
@Override
public void run() {
if (tIcon != null) {
JIThumbnailCache.this.cachedThumbnails.put(diskObject.getFile().getPath(),
new ThumbnailIcon(tIcon));
}
thumbnailList.getThumbnailListModel().notifyAsUpdated(index);
}
});
}
});
// ///////////////////////////////////////////////////////////////////////
} catch (final Exception exp) {
// log.debug(exp);
}
}
| private void loadThumbnail(final ImageElement diskObject, final JIThumbnailList thumbnailList, final int index) {
if ((index > thumbnailList.getLastVisibleIndex()) || (index < thumbnailList.getFirstVisibleIndex())) {
return;
}
try {
// ///////////////////////////////////////////////////////////////////////
JIThumbnailCache.qExecutor.execute(new Runnable() {
@Override
public void run() {
RenderedImage img = null;
String mime = diskObject.getMimeType();
if (mime == null) {
mime = "";
}
String cfile = diskObject.getFile().getAbsolutePath();
String tiled_File = thumbnailList.getThumbnailListModel().getFileInCache(cfile);
if (tiled_File != null) {
try {
ImageDecoder dec =
ImageCodec.createImageDecoder("tiff", new FileSeekableStream(tiled_File == null
? diskObject.getFile() : new File(JIListModel.EXPLORER_CACHE_DIR, tiled_File)),
null);
int count = dec.getNumPages();
if (count == 2) {
RenderedImage src2 = dec.decodeAsRenderedImage(1);
if (src2.getWidth() <= Thumbnail.MAX_SIZE) {
img = src2;
}
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
if (img == null) {
img = diskObject.getRenderedImage(diskObject.getImage(null));
}
if (img == null) {
return;
}
if (tiled_File == null) {
/*
* Make an image cache with its thumbnail when the image size is larger than a tile size and if
* not DICOM file
*/
if ((img.getWidth() > ImageFiler.TILESIZE || img.getHeight() > ImageFiler.TILESIZE)
&& !mime.contains("dicom")) {
File imgCacheFile = null;
try {
imgCacheFile = File.createTempFile("tiled_", ".tif", JIListModel.EXPLORER_CACHE_DIR); //$NON-NLS-1$ //$NON-NLS-2$
} catch (IOException e) {
e.printStackTrace();
}
if (ImageFiler.writeTIFF(imgCacheFile, img, true, true, false)) {
// Prevent to many files open on Linux (Ubuntu => 1024) and close image stream
diskObject.removeImageFromCache();
thumbnailList.getThumbnailListModel().putFileInCache(cfile, imgCacheFile.getName());
} else {
// TODO make it invalid
}
return;
}
}
final double scale =
Math.min(ThumbnailRenderer.ICON_DIM.height / (double) img.getHeight(),
ThumbnailRenderer.ICON_DIM.width / (double) img.getWidth());
final BufferedImage tIcon =
scale <= 1.0 ? scale > 0.005 ? SubsampleAverageDescriptor.create(img, scale, scale,
Thumbnail.DownScaleQualityHints).getAsBufferedImage() : null : PlanarImage
.wrapRenderedImage(img).getAsBufferedImage();
// Prevent to many files open on Linux (Ubuntu => 1024) and close image stream
diskObject.removeImageFromCache();
GuiExecutor.instance().execute(new Runnable() {
@Override
public void run() {
if (tIcon != null) {
JIThumbnailCache.this.cachedThumbnails.put(diskObject.getFile().getPath(),
new ThumbnailIcon(tIcon));
}
thumbnailList.getThumbnailListModel().notifyAsUpdated(index);
}
});
}
});
// ///////////////////////////////////////////////////////////////////////
} catch (final Exception exp) {
// log.debug(exp);
}
}
|
diff --git a/src/web/org/openmrs/web/filter/initialization/InitializationFilter.java b/src/web/org/openmrs/web/filter/initialization/InitializationFilter.java
index 23787c9f..84a72abb 100644
--- a/src/web/org/openmrs/web/filter/initialization/InitializationFilter.java
+++ b/src/web/org/openmrs/web/filter/initialization/InitializationFilter.java
@@ -1,848 +1,850 @@
/**
* The contents of this file are subject to the OpenMRS Public License
* Version 1.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://license.openmrs.org
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
* License for the specific language governing rights and limitations
* under the License.
*
* Copyright (C) OpenMRS, LLC. All Rights Reserved.
*/
package org.openmrs.web.filter.initialization;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Writer;
import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Random;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.runtime.RuntimeConstants;
import org.openmrs.ImplementationId;
import org.openmrs.api.PasswordException;
import org.openmrs.api.context.Context;
import org.openmrs.module.web.WebModuleUtil;
import org.openmrs.scheduler.SchedulerConstants;
import org.openmrs.scheduler.SchedulerUtil;
import org.openmrs.util.DatabaseUpdateException;
import org.openmrs.util.DatabaseUpdater;
import org.openmrs.util.InputRequiredException;
import org.openmrs.util.OpenmrsConstants;
import org.openmrs.util.OpenmrsUtil;
import org.openmrs.web.Listener;
import org.openmrs.web.WebConstants;
import org.springframework.web.context.ContextLoader;
/**
* This is the first filter that is processed. It is only active when starting OpenMRS for the very
* first time. It will redirect all requests to the {@link WebConstants#SETUP_PAGE_URL} if the
* {@link Listener} wasn't able to find any runtime properties
*/
public class InitializationFilter implements Filter {
protected final Log log = LogFactory.getLog(getClass());
private static final String LIQUIBASE_SCHEMA_DATA = "liquibase-schema-only.xml";
private static final String LIQUIBASE_CORE_DATA = "liquibase-core-data.xml";
private static final String LIQUIBASE_DEMO_DATA = "liquibase-demo-data.xml";
private static VelocityEngine velocityEngine = null;
/**
* The velocity macro page to redirect to if an error occurs or on initial startup
*/
private final String DEFAULT_PAGE = "databasesetup.vm";
/**
* Set by the {@link #init(FilterConfig)} method so that we have access to the current
* {@link ServletContext}
*/
private FilterConfig filterConfig = null;
/**
* The model object that holds all the properties that the rendered templates use. All
* attributes on this object are made available to all templates via reflection in the
* {@link #renderTemplate(String, Map, Writer)} method.
*/
private InitializationWizardModel wizardModel = null;
/**
* Variable set at the end of the wizard when spring is being restarted
*/
private boolean initializationComplete = false;
/**
* The web.xml file sets this {@link InitializationFilter} to be the first filter for all
* requests.
*
* @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest,
* javax.servlet.ServletResponse, javax.servlet.FilterChain)
*/
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
ServletException {
if (Listener.runtimePropertiesFound() || isInitializationComplete()) {
chain.doFilter(request, response);
} else {
// we only get here if the Listener didn't find a runtime
// properties files
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
String servletPath = httpRequest.getServletPath();
// for all /images files, write the path
if (servletPath.startsWith("/images") || servletPath.startsWith("/scripts")) {
// writes the actual image file path to the response
File file = new File(filterConfig.getServletContext().getRealPath(httpRequest.getServletPath()));
if (httpRequest.getPathInfo() != null)
file = new File(file, httpRequest.getPathInfo());
try {
InputStream imageFileInputStream = new FileInputStream(file);
OpenmrsUtil.copyFile(imageFileInputStream, httpResponse.getOutputStream());
imageFileInputStream.close();
}
catch (FileNotFoundException e) {
log.error("Unable to find file: " + file.getAbsolutePath());
}
} // for anything but /initialsetup
else if (!httpRequest.getServletPath().equals("/" + WebConstants.SETUP_PAGE_URL)) {
// send the user to the setup page
httpResponse.sendRedirect("/" + WebConstants.WEBAPP_NAME + "/" + WebConstants.SETUP_PAGE_URL);
} else {
// does the wizard
// clear the error message that was potentially there from
// the last page
wizardModel.workLog.clear();
wizardModel.errors.clear();
if (httpRequest.getMethod().equals("GET")) {
doGet(httpRequest, httpResponse);
} else if (httpRequest.getMethod().equals("POST")) {
doPost(httpRequest, httpResponse);
}
}
// Don't continue down the filter chain otherwise Spring complains
// that it hasn't been set up yet.
// The jsp and servlet filter are also on this chain, so writing to
// the response directly here is the only option
}
}
/**
* Convenience method to set up the velocity context properly
*/
private void initializeVelocity() {
if (velocityEngine == null) {
velocityEngine = new VelocityEngine();
Properties props = new Properties();
props.setProperty(RuntimeConstants.RUNTIME_LOG, "initial_wizard_vel.log");
// props.setProperty( RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS,
// "org.apache.velocity.runtime.log.CommonsLogLogChute" );
// props.setProperty(CommonsLogLogChute.LOGCHUTE_COMMONS_LOG_NAME,
// "initial_wizard_velocity");
// so the vm pages can import the header/footer
props.setProperty(RuntimeConstants.RESOURCE_LOADER, "class");
props.setProperty("class.resource.loader.description", "Velocity Classpath Resource Loader");
props.setProperty("class.resource.loader.class",
"org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
try {
velocityEngine.init(props);
}
catch (Exception e) {
log.error("velocity init failed, because: " + e);
}
}
}
/**
* Called by {@link #doFilter(ServletRequest, ServletResponse, FilterChain)} on GET requests
*
* @param httpRequest
* @param httpResponse
*/
private void doGet(HttpServletRequest httpRequest, HttpServletResponse httpResponse) throws IOException {
Writer writer = httpResponse.getWriter();
Map<String, Object> referenceMap = new HashMap<String, Object>();
File runtimeProperties = getRuntimePropertiesFile();
if (!runtimeProperties.exists()) {
try {
runtimeProperties.createNewFile();
}
catch (IOException io) {
wizardModel.canCreate = false;
wizardModel.cannotCreateErrorMessage = io.getMessage();
}
// check this before deleting the file again
wizardModel.canWrite = runtimeProperties.canWrite();
// delete the file again after testing the create/write
// so that if the user stops the webapp before finishing
// this wizard, they can still get back into it
runtimeProperties.delete();
} else {
wizardModel.canWrite = runtimeProperties.canWrite();
}
wizardModel.runtimePropertiesPath = runtimeProperties.getAbsolutePath();
// do step one of the wizard
renderTemplate(DEFAULT_PAGE, referenceMap, writer);
}
/**
* Called by {@link #doFilter(ServletRequest, ServletResponse, FilterChain)} on POST requests
*
* @param httpRequest
* @param httpResponse
*/
private void doPost(HttpServletRequest httpRequest, HttpServletResponse httpResponse) throws IOException {
String page = httpRequest.getParameter("page");
Map<String, Object> referenceMap = new HashMap<String, Object>();
Writer writer = httpResponse.getWriter();
// clear existing errors
wizardModel.errors.clear();
// step one
if ("databasesetup.vm".equals(page)) {
wizardModel.databaseConnection = httpRequest.getParameter("database_connection");
checkForEmptyValue(wizardModel.databaseConnection, wizardModel.errors, "Database connection string");
// asked the user for their desired database name
if ("yes".equals(httpRequest.getParameter("current_openmrs_database"))) {
wizardModel.databaseName = httpRequest.getParameter("openmrs_current_database_name");
checkForEmptyValue(wizardModel.databaseName, wizardModel.errors, "Current database name");
wizardModel.hasCurrentOpenmrsDatabase = true;
// TODO check to see if this is an active database
} else {
// mark this wizard as a "to create database" (done at the end)
wizardModel.hasCurrentOpenmrsDatabase = false;
wizardModel.createTables = true;
wizardModel.databaseName = httpRequest.getParameter("openmrs_new_database_name");
checkForEmptyValue(wizardModel.databaseName, wizardModel.errors, "New database name");
// TODO create database now to check if its possible?
wizardModel.createDatabaseUsername = httpRequest.getParameter("create_database_username");
checkForEmptyValue(wizardModel.createDatabaseUsername, wizardModel.errors,
"A user that has 'CREATE DATABASE' privileges");
wizardModel.createDatabasePassword = httpRequest.getParameter("create_database_password");
checkForEmptyValue(wizardModel.createDatabasePassword, wizardModel.errors,
"Password for user with 'CREATE DATABASE' privileges");
}
if (wizardModel.errors.isEmpty()) {
page = "databasetablesanduser.vm";
}
renderTemplate(page, referenceMap, writer);
} // step two
else if ("databasetablesanduser.vm".equals(page)) {
if ("Back".equals(httpRequest.getParameter("back"))) {
renderTemplate("databasesetup.vm", referenceMap, writer);
return;
}
if (wizardModel.hasCurrentOpenmrsDatabase) {
wizardModel.createTables = "yes".equals(httpRequest.getParameter("create_tables"));
}
wizardModel.addDemoData = "yes".equals(httpRequest.getParameter("add_demo_data"));
if ("yes".equals(httpRequest.getParameter("current_database_user"))) {
wizardModel.currentDatabaseUsername = httpRequest.getParameter("current_database_username");
checkForEmptyValue(wizardModel.currentDatabaseUsername, wizardModel.errors, "Curent user account");
wizardModel.currentDatabasePassword = httpRequest.getParameter("current_database_password");
checkForEmptyValue(wizardModel.currentDatabasePassword, wizardModel.errors, "Current user account password");
wizardModel.hasCurrentDatabaseUser = true;
wizardModel.createDatabaseUser = false;
} else {
wizardModel.hasCurrentDatabaseUser = false;
wizardModel.createDatabaseUser = true;
// asked for the root mysql username/password
wizardModel.createUserUsername = httpRequest.getParameter("create_user_username");
checkForEmptyValue(wizardModel.createUserUsername, wizardModel.errors,
"A user that has 'CREATE USER' privileges");
wizardModel.createUserPassword = httpRequest.getParameter("create_user_password");
checkForEmptyValue(wizardModel.createUserPassword, wizardModel.errors,
"Password for user that has 'CREATE USER' privileges");
}
if (wizardModel.errors.isEmpty()) { // go to next page
page = "otherruntimeproperties.vm";
}
renderTemplate(page, referenceMap, writer);
} // step three
else if ("otherruntimeproperties.vm".equals(page)) {
if ("Back".equals(httpRequest.getParameter("back"))) {
renderTemplate("databasetablesanduser.vm", referenceMap, writer);
return;
}
wizardModel.moduleWebAdmin = "yes".equals(httpRequest.getParameter("module_web_admin"));
wizardModel.autoUpdateDatabase = "yes".equals(httpRequest.getParameter("auto_update_database"));
if (wizardModel.createTables) { // go to next page if they are creating tables
page = "adminusersetup.vm";
} else { // skip a page
page = "implementationidsetup.vm";
}
renderTemplate(page, referenceMap, writer);
} // optional step four
else if ("adminusersetup.vm".equals(page)) {
if ("Back".equals(httpRequest.getParameter("back"))) {
renderTemplate("otherruntimeproperties.vm", referenceMap, writer);
return;
}
wizardModel.adminUserPassword = httpRequest.getParameter("new_admin_password");
String adminUserConfirm = httpRequest.getParameter("new_admin_password_confirm");
// throw back to admin user if passwords don't match
if (!wizardModel.adminUserPassword.equals(adminUserConfirm)) {
wizardModel.errors.add("Admin passwords don't match");
renderTemplate("adminusersetup.vm", referenceMap, writer);
return;
}
// throw back if the user didn't put in a password
if (wizardModel.adminUserPassword.equals("")) {
wizardModel.errors.add("An admin password is required");
renderTemplate("adminusersetup.vm", referenceMap, writer);
return;
}
try {
OpenmrsUtil.validatePassword("admin", wizardModel.adminUserPassword, "admin");
}
catch (PasswordException p) {
wizardModel.errors.add("The password is not long enough, does not contain both uppercase characters and a number, or matches the username.");
renderTemplate("adminusersetup.vm", referenceMap, writer);
return;
}
if (wizardModel.errors.isEmpty()) { // go to next page
page = "implementationidsetup.vm";
}
renderTemplate(page, referenceMap, writer);
} // optional step five
else if ("implementationidsetup.vm".equals(page)) {
if ("Back".equals(httpRequest.getParameter("back"))) {
if (wizardModel.createTables)
renderTemplate("adminusersetup.vm", referenceMap, writer);
else
renderTemplate("otherruntimeproperties.vm", referenceMap, writer);
return;
}
wizardModel.implementationIdName = httpRequest.getParameter("implementation_name");
wizardModel.implementationId = httpRequest.getParameter("implementation_id");
wizardModel.implementationIdPassPhrase = httpRequest.getParameter("pass_phrase");
wizardModel.implementationIdDescription = httpRequest.getParameter("description");
// throw back if the user-specified ID is invalid (contains ^ or |).
if (wizardModel.implementationId.indexOf('^') != -1 || wizardModel.implementationId.indexOf('|') != -1) {
wizardModel.errors.add("Implementation ID cannot contain '^' or '|'");
renderTemplate("implementationidsetup.vm", referenceMap, writer);
return;
}
if (wizardModel.errors.isEmpty()) { // go to next page
page = "wizardcomplete.vm";
}
renderTemplate(page, referenceMap, writer);
} else if ("wizardcomplete.vm".equals(page)) {
if ("Back".equals(httpRequest.getParameter("back"))) {
renderTemplate("implementationidsetup.vm", referenceMap, writer);
return;
}
Properties runtimeProperties = new Properties();
String connectionUsername;
String connectionPassword;
if (!wizardModel.hasCurrentOpenmrsDatabase) {
// connect via jdbc and create a database
String sql = "create database `?` default character set utf8";
int result = executeStatement(false, wizardModel.createDatabaseUsername, wizardModel.createDatabasePassword,
sql, wizardModel.databaseName);
// throw the user back to the main screen if this error occurs
if (result < 0) {
renderTemplate(DEFAULT_PAGE, null, writer);
return;
} else {
wizardModel.workLog.add("Created database " + wizardModel.databaseName);
}
}
if (wizardModel.createDatabaseUser) {
connectionUsername = wizardModel.databaseName + "_user";
if (connectionUsername.length() > 16)
connectionUsername = wizardModel.databaseName.substring(0, 11) + "_user"; // trim off enough to leave space for _user at the end
connectionPassword = "";
// generate random password from this subset of alphabet
// intentionally left out these characters: ufsb$() to prevent certain words forming randomly
String chars = "acdeghijklmnopqrtvwxyzACDEGHIJKLMNOPQRTVWXYZ0123456789.|~@#^&";
Random r = new Random();
for (int x = 0; x < 12; x++) {
connectionPassword += chars.charAt(r.nextInt(chars.length()));
}
// connect via jdbc with root user and create an openmrs user
String sql = "drop user '?'@'localhost'";
executeStatement(true, wizardModel.createUserUsername, wizardModel.createUserPassword, sql,
connectionUsername);
sql = "create user '?'@'localhost' identified by '?'";
if (-1 != executeStatement(false, wizardModel.createUserUsername, wizardModel.createUserPassword, sql,
connectionUsername, connectionPassword)) {
wizardModel.workLog.add("Created user " + connectionUsername);
} else {
// if error occurs stop
renderTemplate(DEFAULT_PAGE, null, writer);
return;
}
// grant the roles
sql = "GRANT ALL ON `?`.* TO '?'@'localhost'";
int result = executeStatement(false, wizardModel.createUserUsername, wizardModel.createUserPassword, sql,
wizardModel.databaseName, connectionUsername);
// throw the user back to the main screen if this error occurs
if (result < 0) {
renderTemplate(DEFAULT_PAGE, null, writer);
return;
} else {
wizardModel.workLog.add("Granted user " + connectionUsername + " all privileges to database "
+ wizardModel.databaseName);
}
} else {
connectionUsername = wizardModel.currentDatabaseUsername;
connectionPassword = wizardModel.currentDatabasePassword;
}
String finalDatabaseConnectionString = wizardModel.databaseConnection.replace("@DBNAME@",
wizardModel.databaseName);
// verify that the database connection works
if (!verifyConnection(connectionUsername, connectionPassword, finalDatabaseConnectionString)) {
// redirect to setup page if we got an error
renderTemplate(DEFAULT_PAGE, null, writer);
return;
}
// save the properties for startup purposes
runtimeProperties.put("connection.url", finalDatabaseConnectionString);
runtimeProperties.put("connection.username", connectionUsername);
runtimeProperties.put("connection.password", connectionPassword);
runtimeProperties.put("module.allow_web_admin", wizardModel.moduleWebAdmin.toString());
runtimeProperties.put("auto_update_database", wizardModel.autoUpdateDatabase.toString());
runtimeProperties.put(SchedulerConstants.SCHEDULER_USERNAME_PROPERTY, "admin");
runtimeProperties.put(SchedulerConstants.SCHEDULER_PASSWORD_PROPERTY, wizardModel.adminUserPassword);
Context.setRuntimeProperties(runtimeProperties);
if (wizardModel.createTables) {
// use liquibase to create core data + tables
try {
DatabaseUpdater.executeChangelog(LIQUIBASE_SCHEMA_DATA, null);
DatabaseUpdater.executeChangelog(LIQUIBASE_CORE_DATA, null);
wizardModel.workLog.add("Created database tables and added core data");
}
catch (Exception e) {
wizardModel.errors.add(e.getMessage() + " See the error log for more details"); // TODO internationalize this
log.warn("Error while trying to create tables and demo data", e);
}
}
// add demo data only if creating tables fresh and user selected the option add demo data
if (wizardModel.createTables && wizardModel.addDemoData) {
try {
DatabaseUpdater.executeChangelog(LIQUIBASE_DEMO_DATA, null);
wizardModel.workLog.add("Added demo data");
}
catch (Exception e) {
wizardModel.errors.add(e.getMessage() + " See the error log for more details"); // TODO internationalize this
log.warn("Error while trying to add demo data", e);
}
}
// update the database to the latest version
try {
DatabaseUpdater.update();
}
catch (Exception e) {
wizardModel.errors.add(e.getMessage() + " Error while trying to update to the latest database version"); // TODO internationalize this
log.warn("Error while trying to update to the latest database version", e);
renderTemplate(DEFAULT_PAGE, null, writer);
return;
}
// start spring
// after this point, all errors need to also call: contextLoader.closeWebApplicationContext(event.getServletContext())
// logic copied from org.springframework.web.context.ContextLoaderListener
ContextLoader contextLoader = new ContextLoader();
contextLoader.initWebApplicationContext(filterConfig.getServletContext());
// start openmrs
try {
+ Context.openSession();
Context.startup(runtimeProperties);
}
catch (DatabaseUpdateException updateEx) {
log.warn("Error while running the database update file", updateEx);
wizardModel.errors.add(updateEx.getMessage()
+ " There was an error while running the database update file: " + updateEx.getMessage()); // TODO internationalize this
renderTemplate(DEFAULT_PAGE, null, writer);
return;
}
catch (InputRequiredException inputRequiredEx) {
// TODO display a page looping over the required input and ask the user for each.
// When done and the user and put in their say, call DatabaseUpdater.update(Map);
// with the user's question/answer pairs
log
.warn("Unable to continue because user input is required for the db updates, but I am not doing anything about that right now");
wizardModel.errors
.add("Unable to continue because user input is required for the db updates, but I am not doing anything about that right now");
renderTemplate(DEFAULT_PAGE, null, writer);
return;
}
// TODO catch openmrs errors here and drop the user back out to the setup screen
if (!wizardModel.implementationId.equals("")) {
try {
Context.addProxyPrivilege(OpenmrsConstants.PRIV_MANAGE_GLOBAL_PROPERTIES);
Context.addProxyPrivilege(OpenmrsConstants.PRIV_MANAGE_CONCEPT_SOURCES);
Context.addProxyPrivilege(OpenmrsConstants.PRIV_VIEW_CONCEPT_SOURCES);
ImplementationId implId = new ImplementationId();
implId.setName(wizardModel.implementationIdName);
implId.setImplementationId(wizardModel.implementationId);
implId.setPassphrase(wizardModel.implementationIdPassPhrase);
implId.setDescription(wizardModel.implementationIdDescription);
Context.getAdministrationService().setImplementationId(implId);
}
catch (Throwable t) {
wizardModel.errors.add(t.getMessage() + " Implementation ID could not be set.");
log.warn("Implementation ID could not be set.", t);
renderTemplate(DEFAULT_PAGE, null, writer);
Context.shutdown();
WebModuleUtil.shutdownModules(filterConfig.getServletContext());
contextLoader.closeWebApplicationContext(filterConfig.getServletContext());
return;
}
finally {
Context.removeProxyPrivilege(OpenmrsConstants.PRIV_MANAGE_GLOBAL_PROPERTIES);
Context.removeProxyPrivilege(OpenmrsConstants.PRIV_MANAGE_CONCEPT_SOURCES);
Context.removeProxyPrivilege(OpenmrsConstants.PRIV_VIEW_CONCEPT_SOURCES);
}
}
try {
// change the admin user password from "test" to what they input above
if (wizardModel.createTables) {
Context.authenticate("admin", "test");
Context.getUserService().changePassword("test", wizardModel.adminUserPassword);
Context.logout();
}
// load modules
Listener.loadCoreModules(filterConfig.getServletContext());
// web load modules
Listener.performWebStartOfModules(filterConfig.getServletContext());
// start the scheduled tasks
SchedulerUtil.startup(runtimeProperties);
}
catch (Throwable t) {
Context.shutdown();
WebModuleUtil.shutdownModules(filterConfig.getServletContext());
contextLoader.closeWebApplicationContext(filterConfig.getServletContext());
wizardModel.errors.add(t.getMessage() + " Unable to complete the startup.");
log.warn("Unable to complete the startup.", t);
renderTemplate(DEFAULT_PAGE, null, writer);
return;
}
// output properties to the openmrs runtime properties file so that this wizard is not run again
FileOutputStream fos = null;
try {
fos = new FileOutputStream(getRuntimePropertiesFile());
runtimeProperties.store(fos, "Auto generated by OpenMRS initialization wizard");
wizardModel.workLog.add("Saved runtime properties file " + getRuntimePropertiesFile());
// don't need to catch errors here because we tested it at the beginning of the wizard
}
finally {
if (fos != null) {
fos.close();
}
}
// set this so that the wizard isn't run again on next page load
initializationComplete = true;
+ Context.closeSession();
// TODO send user to confirmation page with results of wizard, location of runtime props, etc instead?
httpResponse.sendRedirect("/" + WebConstants.WEBAPP_NAME);
}
}
/**
* Verify the database connection works.
*
* @param connectionUsername
* @param connectionPassword
* @param databaseConnectionFinalUrl
* @return true/false whether it was verified or not
*/
private boolean verifyConnection(String connectionUsername, String connectionPassword, String databaseConnectionFinalUrl) {
try {
// verify connection
// TODO how to get the driver for the other dbs...
Class.forName("com.mysql.jdbc.Driver").newInstance();
DriverManager.getConnection(databaseConnectionFinalUrl, connectionUsername, connectionPassword);
return true;
}
catch (Exception e) {
wizardModel.errors.add("User account " + connectionUsername + " does not work. " + e.getMessage()
+ " See the error log for more details"); // TODO internationalize this
log.warn("Error while checking the connection user account", e);
return false;
}
}
/**
* Convenience method to load the runtime properties in the application data directory
*
* @return
*/
private File getRuntimePropertiesFile() {
String filename = WebConstants.WEBAPP_NAME + "-runtime.properties";
File file = new File(OpenmrsUtil.getApplicationDataDirectory(), filename);
log.debug("Using file: " + file.getAbsolutePath());
return file;
}
/**
* All private attributes on this class are returned to the template via the velocity context
* and reflection
*
* @param templateName
* @param referenceMap
* @param writer
*/
private void renderTemplate(String templateName, Map<String, Object> referenceMap, Writer writer) throws IOException {
VelocityContext velocityContext = new VelocityContext();
if (referenceMap != null) {
for (Map.Entry<String, Object> entry : referenceMap.entrySet()) {
velocityContext.put(entry.getKey(), entry.getValue());
}
}
// put each of the private varibles into the template for convenience
for (Field field : InitializationWizardModel.class.getDeclaredFields()) {
try {
velocityContext.put(field.getName(), field.get(wizardModel));
}
catch (IllegalArgumentException e) {
log.error("Error generated while getting field value: " + field.getName(), e);
}
catch (IllegalAccessException e) {
log.error("Error generated while getting field value: " + field.getName(), e);
}
}
String fullTemplatePath = "org/openmrs/web/filter/initialization/" + templateName;
InputStream templateInputStream = getClass().getClassLoader().getResourceAsStream(fullTemplatePath);
if (templateInputStream == null) {
throw new IOException("Unable to find " + fullTemplatePath);
}
try {
velocityEngine.evaluate(velocityContext, writer, this.getClass().getName(), new InputStreamReader(
templateInputStream));
}
catch (Exception e) {
throw new RuntimeException("Unable to process template: " + fullTemplatePath, e);
}
}
/**
* @see javax.servlet.Filter#destroy()
*/
public void destroy() {
}
/**
* @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
*/
public void init(FilterConfig filterConfig) throws ServletException {
this.filterConfig = filterConfig;
initializeVelocity();
wizardModel = new InitializationWizardModel();
}
/**
* @param silent if this statement fails do not display stack trace or record an error in the
* wizard object.
* @param user username to connect with
* @param pw password to connect with
* @param sql String containing sql and question marks
* @param args the strings to fill into the question marks in the given sql
* @return result of executeUpdate or -1 for error
*/
private int executeStatement(boolean silent, String user, String pw, String sql, String... args) {
Connection connection = null;
try {
String replacedSql = sql;
// TODO how to get the driver for the other dbs...
if (wizardModel.databaseConnection.contains("mysql")) {
Class.forName("com.mysql.jdbc.Driver").newInstance();
} else {
replacedSql = replacedSql.replaceAll("`", "\"");
}
String tempDatabaseConnection = "";
if (sql.contains("create database")) {
tempDatabaseConnection = wizardModel.databaseConnection.replace("@DBNAME@", ""); // make this dbname agnostic so we can create the db
} else {
tempDatabaseConnection = wizardModel.databaseConnection.replace("@DBNAME@", wizardModel.databaseName);
}
connection = DriverManager.getConnection(tempDatabaseConnection, user, pw);
for (String arg : args) {
arg = arg.replace(";", "^"); // to prevent any sql injection
replacedSql = replacedSql.replaceFirst("\\?", arg);
}
// run the sql statement
Statement statement = connection.createStatement();
return statement.executeUpdate(replacedSql);
}
catch (SQLException sqlex) {
if (!silent) {
// log and add error
log.warn("error executing sql: " + sql, sqlex);
wizardModel.errors.add("Error executing sql: " + sql + " - " + sqlex.getMessage());
}
}
catch (InstantiationException e) {
log.error("Error generated", e);
}
catch (IllegalAccessException e) {
log.error("Error generated", e);
}
catch (ClassNotFoundException e) {
log.error("Error generated", e);
}
finally {
try {
if (connection != null) {
connection.close();
}
}
catch (Throwable t) {
log.warn("Error while closing connection", t);
}
}
return -1;
}
/**
* Convenience variable to know if this wizard has completed successfully and that this wizard
* does not need to be executed again
*
* @return
*/
private boolean isInitializationComplete() {
return initializationComplete;
}
/**
* Check if the given value is null or a zero-length String
*
* @param value the string to check
* @param errors the list of errors to append the errorMessage to if value is empty
* @param errorMessage the string error message to append if value is empty
* @return true if the value is non-empty
*/
private boolean checkForEmptyValue(String value, List<String> errors, String errorMessage) {
if (value != null && !value.equals("")) {
return true;
}
errors.add(errorMessage + " required.");
return false;
}
}
| false | true | private void doPost(HttpServletRequest httpRequest, HttpServletResponse httpResponse) throws IOException {
String page = httpRequest.getParameter("page");
Map<String, Object> referenceMap = new HashMap<String, Object>();
Writer writer = httpResponse.getWriter();
// clear existing errors
wizardModel.errors.clear();
// step one
if ("databasesetup.vm".equals(page)) {
wizardModel.databaseConnection = httpRequest.getParameter("database_connection");
checkForEmptyValue(wizardModel.databaseConnection, wizardModel.errors, "Database connection string");
// asked the user for their desired database name
if ("yes".equals(httpRequest.getParameter("current_openmrs_database"))) {
wizardModel.databaseName = httpRequest.getParameter("openmrs_current_database_name");
checkForEmptyValue(wizardModel.databaseName, wizardModel.errors, "Current database name");
wizardModel.hasCurrentOpenmrsDatabase = true;
// TODO check to see if this is an active database
} else {
// mark this wizard as a "to create database" (done at the end)
wizardModel.hasCurrentOpenmrsDatabase = false;
wizardModel.createTables = true;
wizardModel.databaseName = httpRequest.getParameter("openmrs_new_database_name");
checkForEmptyValue(wizardModel.databaseName, wizardModel.errors, "New database name");
// TODO create database now to check if its possible?
wizardModel.createDatabaseUsername = httpRequest.getParameter("create_database_username");
checkForEmptyValue(wizardModel.createDatabaseUsername, wizardModel.errors,
"A user that has 'CREATE DATABASE' privileges");
wizardModel.createDatabasePassword = httpRequest.getParameter("create_database_password");
checkForEmptyValue(wizardModel.createDatabasePassword, wizardModel.errors,
"Password for user with 'CREATE DATABASE' privileges");
}
if (wizardModel.errors.isEmpty()) {
page = "databasetablesanduser.vm";
}
renderTemplate(page, referenceMap, writer);
} // step two
else if ("databasetablesanduser.vm".equals(page)) {
if ("Back".equals(httpRequest.getParameter("back"))) {
renderTemplate("databasesetup.vm", referenceMap, writer);
return;
}
if (wizardModel.hasCurrentOpenmrsDatabase) {
wizardModel.createTables = "yes".equals(httpRequest.getParameter("create_tables"));
}
wizardModel.addDemoData = "yes".equals(httpRequest.getParameter("add_demo_data"));
if ("yes".equals(httpRequest.getParameter("current_database_user"))) {
wizardModel.currentDatabaseUsername = httpRequest.getParameter("current_database_username");
checkForEmptyValue(wizardModel.currentDatabaseUsername, wizardModel.errors, "Curent user account");
wizardModel.currentDatabasePassword = httpRequest.getParameter("current_database_password");
checkForEmptyValue(wizardModel.currentDatabasePassword, wizardModel.errors, "Current user account password");
wizardModel.hasCurrentDatabaseUser = true;
wizardModel.createDatabaseUser = false;
} else {
wizardModel.hasCurrentDatabaseUser = false;
wizardModel.createDatabaseUser = true;
// asked for the root mysql username/password
wizardModel.createUserUsername = httpRequest.getParameter("create_user_username");
checkForEmptyValue(wizardModel.createUserUsername, wizardModel.errors,
"A user that has 'CREATE USER' privileges");
wizardModel.createUserPassword = httpRequest.getParameter("create_user_password");
checkForEmptyValue(wizardModel.createUserPassword, wizardModel.errors,
"Password for user that has 'CREATE USER' privileges");
}
if (wizardModel.errors.isEmpty()) { // go to next page
page = "otherruntimeproperties.vm";
}
renderTemplate(page, referenceMap, writer);
} // step three
else if ("otherruntimeproperties.vm".equals(page)) {
if ("Back".equals(httpRequest.getParameter("back"))) {
renderTemplate("databasetablesanduser.vm", referenceMap, writer);
return;
}
wizardModel.moduleWebAdmin = "yes".equals(httpRequest.getParameter("module_web_admin"));
wizardModel.autoUpdateDatabase = "yes".equals(httpRequest.getParameter("auto_update_database"));
if (wizardModel.createTables) { // go to next page if they are creating tables
page = "adminusersetup.vm";
} else { // skip a page
page = "implementationidsetup.vm";
}
renderTemplate(page, referenceMap, writer);
} // optional step four
else if ("adminusersetup.vm".equals(page)) {
if ("Back".equals(httpRequest.getParameter("back"))) {
renderTemplate("otherruntimeproperties.vm", referenceMap, writer);
return;
}
wizardModel.adminUserPassword = httpRequest.getParameter("new_admin_password");
String adminUserConfirm = httpRequest.getParameter("new_admin_password_confirm");
// throw back to admin user if passwords don't match
if (!wizardModel.adminUserPassword.equals(adminUserConfirm)) {
wizardModel.errors.add("Admin passwords don't match");
renderTemplate("adminusersetup.vm", referenceMap, writer);
return;
}
// throw back if the user didn't put in a password
if (wizardModel.adminUserPassword.equals("")) {
wizardModel.errors.add("An admin password is required");
renderTemplate("adminusersetup.vm", referenceMap, writer);
return;
}
try {
OpenmrsUtil.validatePassword("admin", wizardModel.adminUserPassword, "admin");
}
catch (PasswordException p) {
wizardModel.errors.add("The password is not long enough, does not contain both uppercase characters and a number, or matches the username.");
renderTemplate("adminusersetup.vm", referenceMap, writer);
return;
}
if (wizardModel.errors.isEmpty()) { // go to next page
page = "implementationidsetup.vm";
}
renderTemplate(page, referenceMap, writer);
} // optional step five
else if ("implementationidsetup.vm".equals(page)) {
if ("Back".equals(httpRequest.getParameter("back"))) {
if (wizardModel.createTables)
renderTemplate("adminusersetup.vm", referenceMap, writer);
else
renderTemplate("otherruntimeproperties.vm", referenceMap, writer);
return;
}
wizardModel.implementationIdName = httpRequest.getParameter("implementation_name");
wizardModel.implementationId = httpRequest.getParameter("implementation_id");
wizardModel.implementationIdPassPhrase = httpRequest.getParameter("pass_phrase");
wizardModel.implementationIdDescription = httpRequest.getParameter("description");
// throw back if the user-specified ID is invalid (contains ^ or |).
if (wizardModel.implementationId.indexOf('^') != -1 || wizardModel.implementationId.indexOf('|') != -1) {
wizardModel.errors.add("Implementation ID cannot contain '^' or '|'");
renderTemplate("implementationidsetup.vm", referenceMap, writer);
return;
}
if (wizardModel.errors.isEmpty()) { // go to next page
page = "wizardcomplete.vm";
}
renderTemplate(page, referenceMap, writer);
} else if ("wizardcomplete.vm".equals(page)) {
if ("Back".equals(httpRequest.getParameter("back"))) {
renderTemplate("implementationidsetup.vm", referenceMap, writer);
return;
}
Properties runtimeProperties = new Properties();
String connectionUsername;
String connectionPassword;
if (!wizardModel.hasCurrentOpenmrsDatabase) {
// connect via jdbc and create a database
String sql = "create database `?` default character set utf8";
int result = executeStatement(false, wizardModel.createDatabaseUsername, wizardModel.createDatabasePassword,
sql, wizardModel.databaseName);
// throw the user back to the main screen if this error occurs
if (result < 0) {
renderTemplate(DEFAULT_PAGE, null, writer);
return;
} else {
wizardModel.workLog.add("Created database " + wizardModel.databaseName);
}
}
if (wizardModel.createDatabaseUser) {
connectionUsername = wizardModel.databaseName + "_user";
if (connectionUsername.length() > 16)
connectionUsername = wizardModel.databaseName.substring(0, 11) + "_user"; // trim off enough to leave space for _user at the end
connectionPassword = "";
// generate random password from this subset of alphabet
// intentionally left out these characters: ufsb$() to prevent certain words forming randomly
String chars = "acdeghijklmnopqrtvwxyzACDEGHIJKLMNOPQRTVWXYZ0123456789.|~@#^&";
Random r = new Random();
for (int x = 0; x < 12; x++) {
connectionPassword += chars.charAt(r.nextInt(chars.length()));
}
// connect via jdbc with root user and create an openmrs user
String sql = "drop user '?'@'localhost'";
executeStatement(true, wizardModel.createUserUsername, wizardModel.createUserPassword, sql,
connectionUsername);
sql = "create user '?'@'localhost' identified by '?'";
if (-1 != executeStatement(false, wizardModel.createUserUsername, wizardModel.createUserPassword, sql,
connectionUsername, connectionPassword)) {
wizardModel.workLog.add("Created user " + connectionUsername);
} else {
// if error occurs stop
renderTemplate(DEFAULT_PAGE, null, writer);
return;
}
// grant the roles
sql = "GRANT ALL ON `?`.* TO '?'@'localhost'";
int result = executeStatement(false, wizardModel.createUserUsername, wizardModel.createUserPassword, sql,
wizardModel.databaseName, connectionUsername);
// throw the user back to the main screen if this error occurs
if (result < 0) {
renderTemplate(DEFAULT_PAGE, null, writer);
return;
} else {
wizardModel.workLog.add("Granted user " + connectionUsername + " all privileges to database "
+ wizardModel.databaseName);
}
} else {
connectionUsername = wizardModel.currentDatabaseUsername;
connectionPassword = wizardModel.currentDatabasePassword;
}
String finalDatabaseConnectionString = wizardModel.databaseConnection.replace("@DBNAME@",
wizardModel.databaseName);
// verify that the database connection works
if (!verifyConnection(connectionUsername, connectionPassword, finalDatabaseConnectionString)) {
// redirect to setup page if we got an error
renderTemplate(DEFAULT_PAGE, null, writer);
return;
}
// save the properties for startup purposes
runtimeProperties.put("connection.url", finalDatabaseConnectionString);
runtimeProperties.put("connection.username", connectionUsername);
runtimeProperties.put("connection.password", connectionPassword);
runtimeProperties.put("module.allow_web_admin", wizardModel.moduleWebAdmin.toString());
runtimeProperties.put("auto_update_database", wizardModel.autoUpdateDatabase.toString());
runtimeProperties.put(SchedulerConstants.SCHEDULER_USERNAME_PROPERTY, "admin");
runtimeProperties.put(SchedulerConstants.SCHEDULER_PASSWORD_PROPERTY, wizardModel.adminUserPassword);
Context.setRuntimeProperties(runtimeProperties);
if (wizardModel.createTables) {
// use liquibase to create core data + tables
try {
DatabaseUpdater.executeChangelog(LIQUIBASE_SCHEMA_DATA, null);
DatabaseUpdater.executeChangelog(LIQUIBASE_CORE_DATA, null);
wizardModel.workLog.add("Created database tables and added core data");
}
catch (Exception e) {
wizardModel.errors.add(e.getMessage() + " See the error log for more details"); // TODO internationalize this
log.warn("Error while trying to create tables and demo data", e);
}
}
// add demo data only if creating tables fresh and user selected the option add demo data
if (wizardModel.createTables && wizardModel.addDemoData) {
try {
DatabaseUpdater.executeChangelog(LIQUIBASE_DEMO_DATA, null);
wizardModel.workLog.add("Added demo data");
}
catch (Exception e) {
wizardModel.errors.add(e.getMessage() + " See the error log for more details"); // TODO internationalize this
log.warn("Error while trying to add demo data", e);
}
}
// update the database to the latest version
try {
DatabaseUpdater.update();
}
catch (Exception e) {
wizardModel.errors.add(e.getMessage() + " Error while trying to update to the latest database version"); // TODO internationalize this
log.warn("Error while trying to update to the latest database version", e);
renderTemplate(DEFAULT_PAGE, null, writer);
return;
}
// start spring
// after this point, all errors need to also call: contextLoader.closeWebApplicationContext(event.getServletContext())
// logic copied from org.springframework.web.context.ContextLoaderListener
ContextLoader contextLoader = new ContextLoader();
contextLoader.initWebApplicationContext(filterConfig.getServletContext());
// start openmrs
try {
Context.startup(runtimeProperties);
}
catch (DatabaseUpdateException updateEx) {
log.warn("Error while running the database update file", updateEx);
wizardModel.errors.add(updateEx.getMessage()
+ " There was an error while running the database update file: " + updateEx.getMessage()); // TODO internationalize this
renderTemplate(DEFAULT_PAGE, null, writer);
return;
}
catch (InputRequiredException inputRequiredEx) {
// TODO display a page looping over the required input and ask the user for each.
// When done and the user and put in their say, call DatabaseUpdater.update(Map);
// with the user's question/answer pairs
log
.warn("Unable to continue because user input is required for the db updates, but I am not doing anything about that right now");
wizardModel.errors
.add("Unable to continue because user input is required for the db updates, but I am not doing anything about that right now");
renderTemplate(DEFAULT_PAGE, null, writer);
return;
}
// TODO catch openmrs errors here and drop the user back out to the setup screen
if (!wizardModel.implementationId.equals("")) {
try {
Context.addProxyPrivilege(OpenmrsConstants.PRIV_MANAGE_GLOBAL_PROPERTIES);
Context.addProxyPrivilege(OpenmrsConstants.PRIV_MANAGE_CONCEPT_SOURCES);
Context.addProxyPrivilege(OpenmrsConstants.PRIV_VIEW_CONCEPT_SOURCES);
ImplementationId implId = new ImplementationId();
implId.setName(wizardModel.implementationIdName);
implId.setImplementationId(wizardModel.implementationId);
implId.setPassphrase(wizardModel.implementationIdPassPhrase);
implId.setDescription(wizardModel.implementationIdDescription);
Context.getAdministrationService().setImplementationId(implId);
}
catch (Throwable t) {
wizardModel.errors.add(t.getMessage() + " Implementation ID could not be set.");
log.warn("Implementation ID could not be set.", t);
renderTemplate(DEFAULT_PAGE, null, writer);
Context.shutdown();
WebModuleUtil.shutdownModules(filterConfig.getServletContext());
contextLoader.closeWebApplicationContext(filterConfig.getServletContext());
return;
}
finally {
Context.removeProxyPrivilege(OpenmrsConstants.PRIV_MANAGE_GLOBAL_PROPERTIES);
Context.removeProxyPrivilege(OpenmrsConstants.PRIV_MANAGE_CONCEPT_SOURCES);
Context.removeProxyPrivilege(OpenmrsConstants.PRIV_VIEW_CONCEPT_SOURCES);
}
}
try {
// change the admin user password from "test" to what they input above
if (wizardModel.createTables) {
Context.authenticate("admin", "test");
Context.getUserService().changePassword("test", wizardModel.adminUserPassword);
Context.logout();
}
// load modules
Listener.loadCoreModules(filterConfig.getServletContext());
// web load modules
Listener.performWebStartOfModules(filterConfig.getServletContext());
// start the scheduled tasks
SchedulerUtil.startup(runtimeProperties);
}
catch (Throwable t) {
Context.shutdown();
WebModuleUtil.shutdownModules(filterConfig.getServletContext());
contextLoader.closeWebApplicationContext(filterConfig.getServletContext());
wizardModel.errors.add(t.getMessage() + " Unable to complete the startup.");
log.warn("Unable to complete the startup.", t);
renderTemplate(DEFAULT_PAGE, null, writer);
return;
}
// output properties to the openmrs runtime properties file so that this wizard is not run again
FileOutputStream fos = null;
try {
fos = new FileOutputStream(getRuntimePropertiesFile());
runtimeProperties.store(fos, "Auto generated by OpenMRS initialization wizard");
wizardModel.workLog.add("Saved runtime properties file " + getRuntimePropertiesFile());
// don't need to catch errors here because we tested it at the beginning of the wizard
}
finally {
if (fos != null) {
fos.close();
}
}
// set this so that the wizard isn't run again on next page load
initializationComplete = true;
// TODO send user to confirmation page with results of wizard, location of runtime props, etc instead?
httpResponse.sendRedirect("/" + WebConstants.WEBAPP_NAME);
}
}
| private void doPost(HttpServletRequest httpRequest, HttpServletResponse httpResponse) throws IOException {
String page = httpRequest.getParameter("page");
Map<String, Object> referenceMap = new HashMap<String, Object>();
Writer writer = httpResponse.getWriter();
// clear existing errors
wizardModel.errors.clear();
// step one
if ("databasesetup.vm".equals(page)) {
wizardModel.databaseConnection = httpRequest.getParameter("database_connection");
checkForEmptyValue(wizardModel.databaseConnection, wizardModel.errors, "Database connection string");
// asked the user for their desired database name
if ("yes".equals(httpRequest.getParameter("current_openmrs_database"))) {
wizardModel.databaseName = httpRequest.getParameter("openmrs_current_database_name");
checkForEmptyValue(wizardModel.databaseName, wizardModel.errors, "Current database name");
wizardModel.hasCurrentOpenmrsDatabase = true;
// TODO check to see if this is an active database
} else {
// mark this wizard as a "to create database" (done at the end)
wizardModel.hasCurrentOpenmrsDatabase = false;
wizardModel.createTables = true;
wizardModel.databaseName = httpRequest.getParameter("openmrs_new_database_name");
checkForEmptyValue(wizardModel.databaseName, wizardModel.errors, "New database name");
// TODO create database now to check if its possible?
wizardModel.createDatabaseUsername = httpRequest.getParameter("create_database_username");
checkForEmptyValue(wizardModel.createDatabaseUsername, wizardModel.errors,
"A user that has 'CREATE DATABASE' privileges");
wizardModel.createDatabasePassword = httpRequest.getParameter("create_database_password");
checkForEmptyValue(wizardModel.createDatabasePassword, wizardModel.errors,
"Password for user with 'CREATE DATABASE' privileges");
}
if (wizardModel.errors.isEmpty()) {
page = "databasetablesanduser.vm";
}
renderTemplate(page, referenceMap, writer);
} // step two
else if ("databasetablesanduser.vm".equals(page)) {
if ("Back".equals(httpRequest.getParameter("back"))) {
renderTemplate("databasesetup.vm", referenceMap, writer);
return;
}
if (wizardModel.hasCurrentOpenmrsDatabase) {
wizardModel.createTables = "yes".equals(httpRequest.getParameter("create_tables"));
}
wizardModel.addDemoData = "yes".equals(httpRequest.getParameter("add_demo_data"));
if ("yes".equals(httpRequest.getParameter("current_database_user"))) {
wizardModel.currentDatabaseUsername = httpRequest.getParameter("current_database_username");
checkForEmptyValue(wizardModel.currentDatabaseUsername, wizardModel.errors, "Curent user account");
wizardModel.currentDatabasePassword = httpRequest.getParameter("current_database_password");
checkForEmptyValue(wizardModel.currentDatabasePassword, wizardModel.errors, "Current user account password");
wizardModel.hasCurrentDatabaseUser = true;
wizardModel.createDatabaseUser = false;
} else {
wizardModel.hasCurrentDatabaseUser = false;
wizardModel.createDatabaseUser = true;
// asked for the root mysql username/password
wizardModel.createUserUsername = httpRequest.getParameter("create_user_username");
checkForEmptyValue(wizardModel.createUserUsername, wizardModel.errors,
"A user that has 'CREATE USER' privileges");
wizardModel.createUserPassword = httpRequest.getParameter("create_user_password");
checkForEmptyValue(wizardModel.createUserPassword, wizardModel.errors,
"Password for user that has 'CREATE USER' privileges");
}
if (wizardModel.errors.isEmpty()) { // go to next page
page = "otherruntimeproperties.vm";
}
renderTemplate(page, referenceMap, writer);
} // step three
else if ("otherruntimeproperties.vm".equals(page)) {
if ("Back".equals(httpRequest.getParameter("back"))) {
renderTemplate("databasetablesanduser.vm", referenceMap, writer);
return;
}
wizardModel.moduleWebAdmin = "yes".equals(httpRequest.getParameter("module_web_admin"));
wizardModel.autoUpdateDatabase = "yes".equals(httpRequest.getParameter("auto_update_database"));
if (wizardModel.createTables) { // go to next page if they are creating tables
page = "adminusersetup.vm";
} else { // skip a page
page = "implementationidsetup.vm";
}
renderTemplate(page, referenceMap, writer);
} // optional step four
else if ("adminusersetup.vm".equals(page)) {
if ("Back".equals(httpRequest.getParameter("back"))) {
renderTemplate("otherruntimeproperties.vm", referenceMap, writer);
return;
}
wizardModel.adminUserPassword = httpRequest.getParameter("new_admin_password");
String adminUserConfirm = httpRequest.getParameter("new_admin_password_confirm");
// throw back to admin user if passwords don't match
if (!wizardModel.adminUserPassword.equals(adminUserConfirm)) {
wizardModel.errors.add("Admin passwords don't match");
renderTemplate("adminusersetup.vm", referenceMap, writer);
return;
}
// throw back if the user didn't put in a password
if (wizardModel.adminUserPassword.equals("")) {
wizardModel.errors.add("An admin password is required");
renderTemplate("adminusersetup.vm", referenceMap, writer);
return;
}
try {
OpenmrsUtil.validatePassword("admin", wizardModel.adminUserPassword, "admin");
}
catch (PasswordException p) {
wizardModel.errors.add("The password is not long enough, does not contain both uppercase characters and a number, or matches the username.");
renderTemplate("adminusersetup.vm", referenceMap, writer);
return;
}
if (wizardModel.errors.isEmpty()) { // go to next page
page = "implementationidsetup.vm";
}
renderTemplate(page, referenceMap, writer);
} // optional step five
else if ("implementationidsetup.vm".equals(page)) {
if ("Back".equals(httpRequest.getParameter("back"))) {
if (wizardModel.createTables)
renderTemplate("adminusersetup.vm", referenceMap, writer);
else
renderTemplate("otherruntimeproperties.vm", referenceMap, writer);
return;
}
wizardModel.implementationIdName = httpRequest.getParameter("implementation_name");
wizardModel.implementationId = httpRequest.getParameter("implementation_id");
wizardModel.implementationIdPassPhrase = httpRequest.getParameter("pass_phrase");
wizardModel.implementationIdDescription = httpRequest.getParameter("description");
// throw back if the user-specified ID is invalid (contains ^ or |).
if (wizardModel.implementationId.indexOf('^') != -1 || wizardModel.implementationId.indexOf('|') != -1) {
wizardModel.errors.add("Implementation ID cannot contain '^' or '|'");
renderTemplate("implementationidsetup.vm", referenceMap, writer);
return;
}
if (wizardModel.errors.isEmpty()) { // go to next page
page = "wizardcomplete.vm";
}
renderTemplate(page, referenceMap, writer);
} else if ("wizardcomplete.vm".equals(page)) {
if ("Back".equals(httpRequest.getParameter("back"))) {
renderTemplate("implementationidsetup.vm", referenceMap, writer);
return;
}
Properties runtimeProperties = new Properties();
String connectionUsername;
String connectionPassword;
if (!wizardModel.hasCurrentOpenmrsDatabase) {
// connect via jdbc and create a database
String sql = "create database `?` default character set utf8";
int result = executeStatement(false, wizardModel.createDatabaseUsername, wizardModel.createDatabasePassword,
sql, wizardModel.databaseName);
// throw the user back to the main screen if this error occurs
if (result < 0) {
renderTemplate(DEFAULT_PAGE, null, writer);
return;
} else {
wizardModel.workLog.add("Created database " + wizardModel.databaseName);
}
}
if (wizardModel.createDatabaseUser) {
connectionUsername = wizardModel.databaseName + "_user";
if (connectionUsername.length() > 16)
connectionUsername = wizardModel.databaseName.substring(0, 11) + "_user"; // trim off enough to leave space for _user at the end
connectionPassword = "";
// generate random password from this subset of alphabet
// intentionally left out these characters: ufsb$() to prevent certain words forming randomly
String chars = "acdeghijklmnopqrtvwxyzACDEGHIJKLMNOPQRTVWXYZ0123456789.|~@#^&";
Random r = new Random();
for (int x = 0; x < 12; x++) {
connectionPassword += chars.charAt(r.nextInt(chars.length()));
}
// connect via jdbc with root user and create an openmrs user
String sql = "drop user '?'@'localhost'";
executeStatement(true, wizardModel.createUserUsername, wizardModel.createUserPassword, sql,
connectionUsername);
sql = "create user '?'@'localhost' identified by '?'";
if (-1 != executeStatement(false, wizardModel.createUserUsername, wizardModel.createUserPassword, sql,
connectionUsername, connectionPassword)) {
wizardModel.workLog.add("Created user " + connectionUsername);
} else {
// if error occurs stop
renderTemplate(DEFAULT_PAGE, null, writer);
return;
}
// grant the roles
sql = "GRANT ALL ON `?`.* TO '?'@'localhost'";
int result = executeStatement(false, wizardModel.createUserUsername, wizardModel.createUserPassword, sql,
wizardModel.databaseName, connectionUsername);
// throw the user back to the main screen if this error occurs
if (result < 0) {
renderTemplate(DEFAULT_PAGE, null, writer);
return;
} else {
wizardModel.workLog.add("Granted user " + connectionUsername + " all privileges to database "
+ wizardModel.databaseName);
}
} else {
connectionUsername = wizardModel.currentDatabaseUsername;
connectionPassword = wizardModel.currentDatabasePassword;
}
String finalDatabaseConnectionString = wizardModel.databaseConnection.replace("@DBNAME@",
wizardModel.databaseName);
// verify that the database connection works
if (!verifyConnection(connectionUsername, connectionPassword, finalDatabaseConnectionString)) {
// redirect to setup page if we got an error
renderTemplate(DEFAULT_PAGE, null, writer);
return;
}
// save the properties for startup purposes
runtimeProperties.put("connection.url", finalDatabaseConnectionString);
runtimeProperties.put("connection.username", connectionUsername);
runtimeProperties.put("connection.password", connectionPassword);
runtimeProperties.put("module.allow_web_admin", wizardModel.moduleWebAdmin.toString());
runtimeProperties.put("auto_update_database", wizardModel.autoUpdateDatabase.toString());
runtimeProperties.put(SchedulerConstants.SCHEDULER_USERNAME_PROPERTY, "admin");
runtimeProperties.put(SchedulerConstants.SCHEDULER_PASSWORD_PROPERTY, wizardModel.adminUserPassword);
Context.setRuntimeProperties(runtimeProperties);
if (wizardModel.createTables) {
// use liquibase to create core data + tables
try {
DatabaseUpdater.executeChangelog(LIQUIBASE_SCHEMA_DATA, null);
DatabaseUpdater.executeChangelog(LIQUIBASE_CORE_DATA, null);
wizardModel.workLog.add("Created database tables and added core data");
}
catch (Exception e) {
wizardModel.errors.add(e.getMessage() + " See the error log for more details"); // TODO internationalize this
log.warn("Error while trying to create tables and demo data", e);
}
}
// add demo data only if creating tables fresh and user selected the option add demo data
if (wizardModel.createTables && wizardModel.addDemoData) {
try {
DatabaseUpdater.executeChangelog(LIQUIBASE_DEMO_DATA, null);
wizardModel.workLog.add("Added demo data");
}
catch (Exception e) {
wizardModel.errors.add(e.getMessage() + " See the error log for more details"); // TODO internationalize this
log.warn("Error while trying to add demo data", e);
}
}
// update the database to the latest version
try {
DatabaseUpdater.update();
}
catch (Exception e) {
wizardModel.errors.add(e.getMessage() + " Error while trying to update to the latest database version"); // TODO internationalize this
log.warn("Error while trying to update to the latest database version", e);
renderTemplate(DEFAULT_PAGE, null, writer);
return;
}
// start spring
// after this point, all errors need to also call: contextLoader.closeWebApplicationContext(event.getServletContext())
// logic copied from org.springframework.web.context.ContextLoaderListener
ContextLoader contextLoader = new ContextLoader();
contextLoader.initWebApplicationContext(filterConfig.getServletContext());
// start openmrs
try {
Context.openSession();
Context.startup(runtimeProperties);
}
catch (DatabaseUpdateException updateEx) {
log.warn("Error while running the database update file", updateEx);
wizardModel.errors.add(updateEx.getMessage()
+ " There was an error while running the database update file: " + updateEx.getMessage()); // TODO internationalize this
renderTemplate(DEFAULT_PAGE, null, writer);
return;
}
catch (InputRequiredException inputRequiredEx) {
// TODO display a page looping over the required input and ask the user for each.
// When done and the user and put in their say, call DatabaseUpdater.update(Map);
// with the user's question/answer pairs
log
.warn("Unable to continue because user input is required for the db updates, but I am not doing anything about that right now");
wizardModel.errors
.add("Unable to continue because user input is required for the db updates, but I am not doing anything about that right now");
renderTemplate(DEFAULT_PAGE, null, writer);
return;
}
// TODO catch openmrs errors here and drop the user back out to the setup screen
if (!wizardModel.implementationId.equals("")) {
try {
Context.addProxyPrivilege(OpenmrsConstants.PRIV_MANAGE_GLOBAL_PROPERTIES);
Context.addProxyPrivilege(OpenmrsConstants.PRIV_MANAGE_CONCEPT_SOURCES);
Context.addProxyPrivilege(OpenmrsConstants.PRIV_VIEW_CONCEPT_SOURCES);
ImplementationId implId = new ImplementationId();
implId.setName(wizardModel.implementationIdName);
implId.setImplementationId(wizardModel.implementationId);
implId.setPassphrase(wizardModel.implementationIdPassPhrase);
implId.setDescription(wizardModel.implementationIdDescription);
Context.getAdministrationService().setImplementationId(implId);
}
catch (Throwable t) {
wizardModel.errors.add(t.getMessage() + " Implementation ID could not be set.");
log.warn("Implementation ID could not be set.", t);
renderTemplate(DEFAULT_PAGE, null, writer);
Context.shutdown();
WebModuleUtil.shutdownModules(filterConfig.getServletContext());
contextLoader.closeWebApplicationContext(filterConfig.getServletContext());
return;
}
finally {
Context.removeProxyPrivilege(OpenmrsConstants.PRIV_MANAGE_GLOBAL_PROPERTIES);
Context.removeProxyPrivilege(OpenmrsConstants.PRIV_MANAGE_CONCEPT_SOURCES);
Context.removeProxyPrivilege(OpenmrsConstants.PRIV_VIEW_CONCEPT_SOURCES);
}
}
try {
// change the admin user password from "test" to what they input above
if (wizardModel.createTables) {
Context.authenticate("admin", "test");
Context.getUserService().changePassword("test", wizardModel.adminUserPassword);
Context.logout();
}
// load modules
Listener.loadCoreModules(filterConfig.getServletContext());
// web load modules
Listener.performWebStartOfModules(filterConfig.getServletContext());
// start the scheduled tasks
SchedulerUtil.startup(runtimeProperties);
}
catch (Throwable t) {
Context.shutdown();
WebModuleUtil.shutdownModules(filterConfig.getServletContext());
contextLoader.closeWebApplicationContext(filterConfig.getServletContext());
wizardModel.errors.add(t.getMessage() + " Unable to complete the startup.");
log.warn("Unable to complete the startup.", t);
renderTemplate(DEFAULT_PAGE, null, writer);
return;
}
// output properties to the openmrs runtime properties file so that this wizard is not run again
FileOutputStream fos = null;
try {
fos = new FileOutputStream(getRuntimePropertiesFile());
runtimeProperties.store(fos, "Auto generated by OpenMRS initialization wizard");
wizardModel.workLog.add("Saved runtime properties file " + getRuntimePropertiesFile());
// don't need to catch errors here because we tested it at the beginning of the wizard
}
finally {
if (fos != null) {
fos.close();
}
}
// set this so that the wizard isn't run again on next page load
initializationComplete = true;
Context.closeSession();
// TODO send user to confirmation page with results of wizard, location of runtime props, etc instead?
httpResponse.sendRedirect("/" + WebConstants.WEBAPP_NAME);
}
}
|
diff --git a/wings/src/org/wings/SRootContainer.java b/wings/src/org/wings/SRootContainer.java
index 67b9085f..5831b163 100644
--- a/wings/src/org/wings/SRootContainer.java
+++ b/wings/src/org/wings/SRootContainer.java
@@ -1,126 +1,126 @@
/*
* $Id$
* (c) Copyright 2001 wingS development team.
*
* This file is part of wingS (http://wings.mercatis.de).
*
* wingS is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; either version 2.1
* of the License, or (at your option) any later version.
*
* Please see COPYING for the complete licence.
*/
package org.wings;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* A root container.
* The classes derived from this class ({@link SFrame} and
* {@link SInternalFrame}) render in the content pane of this RootContainer.
*
* <p>The RootContainer has a stack of components. Ususally, the stack
* contains only <em>one</em> element, the content pane; this is the bottommost
* component. When dialogs are added to the RootContainer, then these dialogs
* are stacked on top of this content pane, and only <em>this</em> dialog is
* visible then. This emulates the behaviour of modal dialogs in a windowing
* system.
*
* @author <a href="mailto:[email protected]">Holger Engels</a>
* @author <a href="mailto:[email protected]">Henner Zeller</a>
* @author <a href="mailto:[email protected]">Armin Haaf</a>
*/
public abstract class SRootContainer extends SContainer {
private final static Log logger = LogFactory.getLog("org.wings");
/**
* The container for the contentPane.
*/
protected final SContainer contentPane;
/**
* default constructor initializes the stack layout system of this
* SRootContainer.
*/
public SRootContainer() {
contentPane = new SPanel();
super.setLayout(new SRootLayout());
super.addComponent(getContentPane(), null, getComponentCount());
}
/**
* Push a new dialog on top of the stack. If this RootContainer is
* rendered, then only this dialog is shown.
* @param dialog the SDialog that is to be shown on top.
*/
public void pushDialog(SDialog dialog) {
super.addComponent(dialog, null, getComponentCount());
int count = getComponentCount();
logger.debug("pushDialog: " + count);
dialog.setFrame(this);
reload(ReloadManager.RELOAD_CODE);
}
/**
* remove the dialog, that is on top of the stack.
*
* @return the dialog, that is popped from the stack.
*/
public SDialog popDialog() {
int count = getComponentCount();
if (count <= 1)
throw new IllegalStateException("there's no dialog left!");
SDialog dialog = (SDialog) getComponent(count - 1);
super.remove(dialog);
logger.debug("popDialog: " + count);
- dialog.setFrame((SFrame) null);
+// dialog.setFrame((SFrame) null);
reload(ReloadManager.RELOAD_CODE);
return dialog;
}
public void removeDialog(SDialog dialog) {
super.remove(dialog);
dialog.setFrame((SFrame) null);
reload(ReloadManager.RELOAD_CODE);
}
/**
* @return the number of dialogs that are on the stack currently.
*/
public int getDialogCount() {
return getComponentCount() - 1;
}
/**
* returns the content pane of this RootContainer.
*/
public SContainer getContentPane() {
return contentPane;
}
/**
* Use getContentPane().addComponent(c) instead.
*/
public SComponent addComponent(SComponent c, Object constraint, int index) {
throw new IllegalArgumentException("use getContentPane().addComponent()");
}
/**
* Use getContentPane().removeComponent(c) instead.
*/
public void remove(SComponent c) {
throw new IllegalArgumentException("use getContentPane().removeComponent()");
}
}
/*
* Local variables:
* c-basic-offset: 4
* indent-tabs-mode: nil
* compile-command: "ant -emacs -find build.xml"
* End:
*/
| true | true | public SDialog popDialog() {
int count = getComponentCount();
if (count <= 1)
throw new IllegalStateException("there's no dialog left!");
SDialog dialog = (SDialog) getComponent(count - 1);
super.remove(dialog);
logger.debug("popDialog: " + count);
dialog.setFrame((SFrame) null);
reload(ReloadManager.RELOAD_CODE);
return dialog;
}
| public SDialog popDialog() {
int count = getComponentCount();
if (count <= 1)
throw new IllegalStateException("there's no dialog left!");
SDialog dialog = (SDialog) getComponent(count - 1);
super.remove(dialog);
logger.debug("popDialog: " + count);
// dialog.setFrame((SFrame) null);
reload(ReloadManager.RELOAD_CODE);
return dialog;
}
|
diff --git a/src/com/facebook/buck/cli/Main.java b/src/com/facebook/buck/cli/Main.java
index 58ea0a3cf2..66f548faeb 100644
--- a/src/com/facebook/buck/cli/Main.java
+++ b/src/com/facebook/buck/cli/Main.java
@@ -1,685 +1,690 @@
/*
* Copyright 2012-present Facebook, 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.facebook.buck.cli;
import com.facebook.buck.event.BuckEventBus;
import com.facebook.buck.event.BuckEventListener;
import com.facebook.buck.event.LogEvent;
import com.facebook.buck.event.listener.AbstractConsoleEventBusListener;
import com.facebook.buck.event.listener.ChromeTraceBuildListener;
import com.facebook.buck.event.listener.JavaUtilsLoggingBuildListener;
import com.facebook.buck.event.listener.SimpleConsoleEventBusListener;
import com.facebook.buck.event.listener.SuperConsoleEventBusListener;
import com.facebook.buck.httpserver.WebServer;
import com.facebook.buck.parser.Parser;
import com.facebook.buck.rules.BuildRule;
import com.facebook.buck.rules.KnownBuildRuleTypes;
import com.facebook.buck.rules.RuleKey;
import com.facebook.buck.rules.RuleKey.Builder;
import com.facebook.buck.rules.RuleKeyBuilderFactory;
import com.facebook.buck.timing.Clock;
import com.facebook.buck.timing.DefaultClock;
import com.facebook.buck.util.Ansi;
import com.facebook.buck.util.Console;
import com.facebook.buck.util.DefaultFileHashCache;
import com.facebook.buck.util.FileHashCache;
import com.facebook.buck.util.HumanReadableException;
import com.facebook.buck.util.MoreStrings;
import com.facebook.buck.util.ProjectFilesystem;
import com.facebook.buck.util.ProjectFilesystemWatcher;
import com.facebook.buck.util.Verbosity;
import com.facebook.buck.util.WatchServiceWatcher;
import com.facebook.buck.util.WatchmanWatcher;
import com.facebook.buck.util.concurrent.TimeSpan;
import com.facebook.buck.util.environment.DefaultExecutionEnvironment;
import com.facebook.buck.util.environment.ExecutionEnvironment;
import com.facebook.buck.util.environment.Platform;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.eventbus.EventBus;
import com.google.common.reflect.ClassPath;
import com.martiansoftware.nailgun.NGClientListener;
import com.martiansoftware.nailgun.NGContext;
import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.FileSystems;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import javax.annotation.Nullable;
public final class Main {
/**
* Trying again won't help.
*/
public static final int FAIL_EXIT_CODE = 1;
/**
* Trying again later might work.
*/
public static final int BUSY_EXIT_CODE = 2;
private static final String DEFAULT_BUCK_CONFIG_FILE_NAME = ".buckconfig";
private static final String DEFAULT_BUCK_CONFIG_OVERRIDE_FILE_NAME = ".buckconfig.local";
private static final String BUCK_VERSION_UID_KEY = "buck.version_uid";
private static final String BUCK_VERSION_UID = System.getProperty(BUCK_VERSION_UID_KEY, "N/A");
private static final String BUCKD_COLOR_DEFAULT_ENV_VAR = "BUCKD_COLOR_DEFAULT";
private static final int ARTIFACT_CACHE_TIMEOUT_IN_SECONDS = 15;
private static final TimeSpan SUPER_CONSOLE_REFRESH_RATE =
new TimeSpan(100, TimeUnit.MILLISECONDS);
/**
* Path to a directory of static content that should be served by the {@link WebServer}.
*/
private static final String STATIC_CONTENT_DIRECTORY = System.getProperty(
"buck.path_to_static_content", "webserver/static");
private final PrintStream stdOut;
private final PrintStream stdErr;
private static final Semaphore commandSemaphore = new Semaphore(1);
private final Platform platform;
/**
* Daemon used to monitor the file system and cache build rules between Main() method
* invocations is static so that it can outlive Main() objects and survive for the lifetime
* of the potentially long running Buck process.
*/
private final class Daemon implements Closeable {
private final Parser parser;
private final DefaultFileHashCache hashCache;
private final EventBus fileEventBus;
private final ProjectFilesystemWatcher filesystemWatcher;
private final BuckConfig config;
private final Optional<WebServer> webServer;
private final Console console;
public Daemon(ProjectFilesystem projectFilesystem,
BuckConfig config,
Console console) throws IOException {
this.config = Preconditions.checkNotNull(config);
this.console = Preconditions.checkNotNull(console);
this.hashCache = new DefaultFileHashCache(projectFilesystem, console);
this.parser = new Parser(projectFilesystem,
KnownBuildRuleTypes.getDefault(),
console,
config.getPythonInterpreter(),
config.getTempFilePatterns(),
createRuleKeyBuilderFactory(hashCache));
this.fileEventBus = new EventBus("file-change-events");
this.filesystemWatcher = createWatcher(projectFilesystem);
fileEventBus.register(parser);
fileEventBus.register(hashCache);
webServer = createWebServer(config, console, projectFilesystem);
JavaUtilsLoggingBuildListener.ensureLogFileIsWritten();
}
private ProjectFilesystemWatcher createWatcher(ProjectFilesystem projectFilesystem)
throws IOException {
if (System.getProperty("buck.buckd_watcher", "WatchService").equals("Watchman")) {
return new WatchmanWatcher(
projectFilesystem,
fileEventBus,
config.getIgnorePaths());
}
return new WatchServiceWatcher(
projectFilesystem,
fileEventBus,
config.getIgnorePaths(),
FileSystems.getDefault().newWatchService());
}
private Optional<WebServer> createWebServer(BuckConfig config,
Console console,
ProjectFilesystem projectFilesystem) {
// Enable the web httpserver if it is given by command line parameter or specified in
// .buckconfig. The presence of a port number is sufficient.
Optional<String> serverPort = Optional.fromNullable(System.getProperty("buck.httpserver.port"));
if (!serverPort.isPresent()) {
serverPort = config.getValue("httpserver", "port");
}
Optional<WebServer> webServer;
if (serverPort.isPresent()) {
String rawPort = serverPort.get();
try {
int port = Integer.parseInt(rawPort, 10);
webServer = Optional.of(new WebServer(port, projectFilesystem, STATIC_CONTENT_DIRECTORY));
} catch (NumberFormatException e) {
console.printErrorText(String.format("Could not parse port for httpserver: %s.", rawPort));
webServer = Optional.absent();
}
} else {
webServer = Optional.absent();
}
return webServer;
}
public Optional<WebServer> getWebServer() {
return webServer;
}
private Parser getParser() {
return parser;
}
private void watchClient(final NGContext context) {
context.addClientListener(new NGClientListener() {
@Override
public void clientDisconnected() throws InterruptedException {
// Synchronize on parser object so that the main command processing thread is not
// interrupted mid way through a Parser cache update by the Thread.interrupt() call
// triggered by System.exit(). The Parser cache will be reused by subsequent commands
// so needs to be left in a consistent state even if the current command is interrupted
// due to a client disconnection.
synchronized (parser) {
// Client should no longer be connected, but printing helps detect false disconnections.
context.err.println("Client disconnected.");
throw new InterruptedException("Client disconnected.");
}
}
});
}
private void watchFileSystem(Console console, CommandEvent commandEvent) throws IOException {
// Synchronize on parser object so that all outstanding watch events are processed
// as a single, atomic Parser cache update and are not interleaved with Parser cache
// invalidations triggered by requests to parse build files or interrupted by client
// disconnections.
synchronized (parser) {
parser.setConsole(console);
hashCache.setConsole(console);
fileEventBus.post(commandEvent);
filesystemWatcher.postEvents();
}
}
/** @return true if the web server was started successfully. */
private boolean initWebServer() {
if (webServer.isPresent()) {
try {
webServer.get().start();
return true;
} catch (WebServer.WebServerException e) {
e.printStackTrace(console.getStdErr());
}
}
return false;
}
public BuckConfig getConfig() {
return config;
}
@Override
public void close() throws IOException {
filesystemWatcher.close();
shutdownWebServer();
}
private void shutdownWebServer() {
if (webServer.isPresent()) {
try {
webServer.get().stop();
} catch (WebServer.WebServerException e) {
e.printStackTrace(console.getStdErr());
}
}
}
}
@Nullable volatile private static Daemon daemon;
/**
* Get or create Daemon.
*/
private Daemon getDaemon(ProjectFilesystem filesystem,
BuckConfig config,
Console console) throws IOException {
if (daemon == null) {
daemon = new Daemon(filesystem, config, console);
} else {
// Buck daemons cache build files within a single project root, changing to a different
// project root is not supported and will likely result in incorrect builds. The buck and
// buckd scripts attempt to enforce this, so a change in project root is an error that
// should be reported rather than silently worked around by invalidating the cache and
// creating a new daemon object.
File parserRoot = daemon.getParser().getProjectRoot();
if (!filesystem.getProjectRoot().equals(parserRoot)) {
throw new HumanReadableException(String.format("Unsupported root path change from %s to %s",
filesystem.getProjectRoot(), parserRoot));
}
// If Buck config has changed, invalidate the cache and create a new daemon.
if (!daemon.getConfig().equals(config)) {
daemon.close();
daemon = new Daemon(filesystem, config, console);
}
}
return daemon;
}
@VisibleForTesting
public Main(PrintStream stdOut, PrintStream stdErr) {
this.stdOut = Preconditions.checkNotNull(stdOut);
this.stdErr = Preconditions.checkNotNull(stdErr);
this.platform = Platform.detect();
}
/** Prints the usage message to standard error. */
@VisibleForTesting
int usage() {
stdErr.println("buck build tool");
stdErr.println("usage:");
stdErr.println(" buck [options]");
stdErr.println(" buck command --help");
stdErr.println(" buck command [command-options]");
stdErr.println("available commands:");
int lengthOfLongestCommand = 0;
for (Command command : Command.values()) {
String name = command.name();
if (name.length() > lengthOfLongestCommand) {
lengthOfLongestCommand = name.length();
}
}
for (Command command : Command.values()) {
String name = command.name().toLowerCase();
stdErr.printf(" %s%s %s\n",
name,
Strings.repeat(" ", lengthOfLongestCommand - name.length()),
command.getShortDescription());
}
stdErr.println("options:");
new GenericBuckOptions(stdOut, stdErr).printUsage();
return 1;
}
/**
* @param context an optional NGContext that is present if running inside a Nailgun server.
* @param args command line arguments
* @return an exit code or {@code null} if this is a process that should not exit
*/
public int runMainWithExitCode(File projectRoot, Optional<NGContext> context, String... args) throws IOException {
if (args.length == 0) {
return usage();
}
// Find and execute command.
int exitCode;
Command.ParseResult command = Command.parseCommandName(args[0]);
if (command.getCommand().isPresent()) {
return executeCommand(projectRoot, command, context, args);
} else {
exitCode = new GenericBuckOptions(stdOut, stdErr).execute(args);
if (exitCode == GenericBuckOptions.SHOW_MAIN_HELP_SCREEN_EXIT_CODE) {
return usage();
} else {
return exitCode;
}
}
}
/**
* @param context an optional NGContext that is present if running inside a Nailgun server.
* @param args command line arguments
* @return an exit code or {@code null} if this is a process that should not exit
*/
@SuppressWarnings("PMD.EmptyCatchBlock")
public int executeCommand(
File projectRoot,
Command.ParseResult commandParseResult,
Optional<NGContext> context,
String... args) throws IOException {
// Create common command parameters. projectFilesystem initialization looks odd because it needs
// ignorePaths from a BuckConfig instance, which in turn needs a ProjectFilesystem (i.e. this
// solves a bootstrapping issue).
ProjectFilesystem projectFilesystem = new ProjectFilesystem(
projectRoot,
createBuckConfig(new ProjectFilesystem(projectRoot), platform).getIgnorePaths());
BuckConfig config = createBuckConfig(projectFilesystem, platform);
Verbosity verbosity = VerbosityParser.parse(args);
Optional<String> color;
final boolean isDaemon = context.isPresent();
if (isDaemon && (context.get().getEnv() != null)) {
String colorString = context.get().getEnv().getProperty(BUCKD_COLOR_DEFAULT_ENV_VAR);
color = Optional.fromNullable(colorString);
} else {
color = Optional.absent();
}
final Console console = new Console(verbosity, stdOut, stdErr, config.createAnsi(color));
if (commandParseResult.getErrorText().isPresent()) {
console.getStdErr().println(commandParseResult.getErrorText().get());
}
// No more early outs: acquire the command semaphore and become the only executing command.
if (!commandSemaphore.tryAcquire()) {
return BUSY_EXIT_CODE;
}
int exitCode;
ImmutableList<BuckEventListener> eventListeners;
String buildId = MoreStrings.createRandomString();
Clock clock = new DefaultClock();
ExecutionEnvironment executionEnvironment = new DefaultExecutionEnvironment();
// The order of resources in the try-with-resources block is important: the BuckEventBus must
// be the last resource, so that it is closed first and can deliver its queued events to the
// other resources before they are closed.
try (AbstractConsoleEventBusListener consoleListener =
createConsoleEventListener(clock, console, verbosity, executionEnvironment);
BuckEventBus buildEventBus = new BuckEventBus(clock, buildId)) {
Optional<WebServer> webServer = getWebServerIfDaemon(context,
projectFilesystem,
config,
console);
eventListeners = addEventListeners(buildEventBus,
projectFilesystem,
config,
webServer,
consoleListener);
ImmutableList<String> remainingArgs = ImmutableList.copyOf(
Arrays.copyOfRange(args, 1, args.length));
Command executingCommand = commandParseResult.getCommand().get();
String commandName = executingCommand.name().toLowerCase();
CommandEvent commandEvent = CommandEvent.started(commandName, remainingArgs, isDaemon);
buildEventBus.post(commandEvent);
// The ArtifactCache is constructed lazily so that we do not try to connect to Cassandra when
// running commands such as `buck clean`.
ArtifactCacheFactory artifactCacheFactory = new LoggingArtifactCacheFactory(buildEventBus);
// Create or get Parser and invalidate cached command parameters.
Parser parser;
KnownBuildRuleTypes buildRuleTypes = KnownBuildRuleTypes.getConfigured(config);
if (isDaemon) {
parser = getParserFromDaemon(context, projectFilesystem, config, console, commandEvent);
} else {
// Initialize logging and create new Parser for new process.
JavaUtilsLoggingBuildListener.ensureLogFileIsWritten();
parser = new Parser(projectFilesystem,
buildRuleTypes,
console,
config.getPythonInterpreter(),
config.getTempFilePatterns(),
createRuleKeyBuilderFactory(new DefaultFileHashCache(projectFilesystem, console)));
}
exitCode = executingCommand.execute(remainingArgs,
config,
new CommandRunnerParams(
console,
projectFilesystem,
buildRuleTypes,
artifactCacheFactory,
buildEventBus,
parser,
platform));
// TODO(user): allocate artifactCacheFactory in the try-with-resources block to avoid leaks.
artifactCacheFactory.closeCreatedArtifactCaches(ARTIFACT_CACHE_TIMEOUT_IN_SECONDS);
// If the Daemon is running and serving web traffic, print the URL to the Chrome Trace.
if (webServer.isPresent()) {
int port = webServer.get().getPort();
buildEventBus.post(LogEvent.info(
"See trace at http://localhost:%s/trace/%s", port, buildId));
}
buildEventBus.post(CommandEvent.finished(commandName, remainingArgs, isDaemon, exitCode));
} finally {
commandSemaphore.release(); // Allow another command to execute while outputting traces.
}
if (isDaemon) {
context.get().in.close(); // Avoid client exit triggering client disconnection handling.
context.get().exit(exitCode); // Allow nailgun client to exit while outputting traces.
}
for (BuckEventListener eventListener : eventListeners) {
- eventListener.outputTrace(buildId);
+ try {
+ eventListener.outputTrace(buildId);
+ } catch (RuntimeException e) {
+ System.err.println("Skipping over non-fatal error");
+ e.printStackTrace();
+ }
}
return exitCode;
}
private Parser getParserFromDaemon(
Optional<NGContext> context,
ProjectFilesystem projectFilesystem,
BuckConfig config, Console console,
CommandEvent commandEvent) throws IOException {
// Wire up daemon to new client and console and get cached Parser.
Daemon daemon = getDaemon(projectFilesystem, config, console);
daemon.watchClient(context.get());
daemon.watchFileSystem(console, commandEvent);
daemon.initWebServer();
return daemon.getParser();
}
private Optional<WebServer> getWebServerIfDaemon(
Optional<NGContext> context,
ProjectFilesystem projectFilesystem,
BuckConfig config,
Console console) throws IOException {
if (context.isPresent()) {
return getDaemon(projectFilesystem, config, console).getWebServer();
}
return Optional.absent();
}
private void loadListenersFromBuckConfig(
ImmutableList.Builder<BuckEventListener> eventListeners,
ProjectFilesystem projectFilesystem,
BuckConfig config) {
final ImmutableSet<String> paths = config.getListenerJars();
if (paths.isEmpty()) {
return;
}
URL[] urlsArray = new URL[paths.size()];
try {
int i = 0;
for (String path : paths) {
String urlString = "file://" + projectFilesystem.getAbsolutifier().apply(Paths.get(path));
urlsArray[i] = new URL(urlString);
i++;
}
} catch (MalformedURLException e) {
throw new HumanReadableException(e.getMessage());
}
// This ClassLoader is disconnected to allow searching the JARs (and just the JARs) for classes.
ClassLoader isolatedClassLoader = URLClassLoader.newInstance(urlsArray, null);
ImmutableSet<ClassPath.ClassInfo> classInfos;
try {
ClassPath classPath = ClassPath.from(isolatedClassLoader);
classInfos = classPath.getTopLevelClasses();
} catch (IOException e) {
throw new HumanReadableException(e.getMessage());
}
// This ClassLoader will actually work, because it is joined to the parent ClassLoader.
URLClassLoader workingClassLoader = URLClassLoader.newInstance(urlsArray);
for (ClassPath.ClassInfo classInfo : classInfos) {
String className = classInfo.getName();
try {
Class<?> aClass = Class.forName(className, true, workingClassLoader);
if (BuckEventListener.class.isAssignableFrom(aClass)) {
BuckEventListener listener = aClass.asSubclass(BuckEventListener.class).newInstance();
eventListeners.add(listener);
}
} catch (ReflectiveOperationException e) {
throw new HumanReadableException("Error loading event listener class '%s': %s: %s",
className,
e.getClass(),
e.getMessage());
}
}
}
private ImmutableList<BuckEventListener> addEventListeners(
BuckEventBus buckEvents,
ProjectFilesystem projectFilesystem,
BuckConfig config,
Optional<WebServer> webServer,
AbstractConsoleEventBusListener consoleEventBusListener) {
ImmutableList.Builder<BuckEventListener> eventListenersBuilder =
ImmutableList.<BuckEventListener>builder()
.add(new JavaUtilsLoggingBuildListener())
.add(new ChromeTraceBuildListener(projectFilesystem, config.getMaxTraces()))
.add(consoleEventBusListener);
if (webServer.isPresent()) {
eventListenersBuilder.add(webServer.get().createListener());
}
loadListenersFromBuckConfig(eventListenersBuilder, projectFilesystem, config);
ImmutableList<BuckEventListener> eventListeners = eventListenersBuilder.build();
for (BuckEventListener eventListener : eventListeners) {
buckEvents.register(eventListener);
}
return eventListeners;
}
private AbstractConsoleEventBusListener createConsoleEventListener(
Clock clock,
Console console,
Verbosity verbosity,
ExecutionEnvironment executionEnvironment) {
if (console.getAnsi().isAnsiTerminal() && !verbosity.shouldPrintCommand()) {
SuperConsoleEventBusListener superConsole =
new SuperConsoleEventBusListener(console, clock, executionEnvironment);
superConsole.startRenderScheduler(SUPER_CONSOLE_REFRESH_RATE.getDuration(),
SUPER_CONSOLE_REFRESH_RATE.getUnit());
return superConsole;
}
return new SimpleConsoleEventBusListener(console, clock);
}
/**
* @param projectFilesystem The directory that is the root of the project being built.
*/
private static BuckConfig createBuckConfig(ProjectFilesystem projectFilesystem, Platform platform)
throws IOException {
ImmutableList.Builder<File> configFileBuilder = ImmutableList.builder();
File configFile = projectFilesystem.getFileForRelativePath(DEFAULT_BUCK_CONFIG_FILE_NAME);
if (configFile.isFile()) {
configFileBuilder.add(configFile);
}
File overrideConfigFile = projectFilesystem.getFileForRelativePath(
DEFAULT_BUCK_CONFIG_OVERRIDE_FILE_NAME);
if (overrideConfigFile.isFile()) {
configFileBuilder.add(overrideConfigFile);
}
ImmutableList<File> configFiles = configFileBuilder.build();
return BuckConfig.createFromFiles(projectFilesystem, configFiles, platform);
}
/**
* @param hashCache A cache of file content hashes, used to avoid reading and hashing input files.
*/
private static RuleKeyBuilderFactory createRuleKeyBuilderFactory(final FileHashCache hashCache) {
return new RuleKeyBuilderFactory() {
@Override
public Builder newInstance(BuildRule buildRule) {
RuleKey.Builder builder = RuleKey.builder(buildRule, hashCache);
builder.set("buckVersionUid", BUCK_VERSION_UID);
return builder;
}
};
}
@VisibleForTesting
int tryRunMainWithExitCode(File projectRoot, Optional<NGContext> context, String... args)
throws IOException {
// TODO(user): enforce write command exclusion, but allow concurrent read only commands?
try {
return runMainWithExitCode(projectRoot, context, args);
} catch (HumanReadableException e) {
Console console = new Console(Verbosity.STANDARD_INFORMATION,
stdOut,
stdErr,
new Ansi(platform));
console.printBuildFailure(e.getHumanReadableErrorMessage());
return FAIL_EXIT_CODE;
}
}
private void runMainThenExit(String[] args, Optional<NGContext> context) {
File projectRoot = new File(".");
int exitCode = FAIL_EXIT_CODE;
try {
exitCode = tryRunMainWithExitCode(projectRoot, context, args);
} catch (Throwable t) {
t.printStackTrace();
} finally {
// Exit explicitly so that non-daemon threads (of which we use many) don't
// keep the VM alive.
System.exit(exitCode);
}
}
public static void main(String[] args) {
new Main(System.out, System.err).runMainThenExit(args, Optional.<NGContext>absent());
}
/**
* When running as a daemon in the NailGun server, {@link #nailMain(NGContext)} is called instead
* of {@link #main(String[])} so that the given context can be used to listen for client
* disconnections and interrupt command processing when they occur.
*/
public static void nailMain(final NGContext context) throws InterruptedException {
new Main(context.out, context.err).runMainThenExit(context.getArgs(), Optional.of(context));
}
}
| true | true | public int executeCommand(
File projectRoot,
Command.ParseResult commandParseResult,
Optional<NGContext> context,
String... args) throws IOException {
// Create common command parameters. projectFilesystem initialization looks odd because it needs
// ignorePaths from a BuckConfig instance, which in turn needs a ProjectFilesystem (i.e. this
// solves a bootstrapping issue).
ProjectFilesystem projectFilesystem = new ProjectFilesystem(
projectRoot,
createBuckConfig(new ProjectFilesystem(projectRoot), platform).getIgnorePaths());
BuckConfig config = createBuckConfig(projectFilesystem, platform);
Verbosity verbosity = VerbosityParser.parse(args);
Optional<String> color;
final boolean isDaemon = context.isPresent();
if (isDaemon && (context.get().getEnv() != null)) {
String colorString = context.get().getEnv().getProperty(BUCKD_COLOR_DEFAULT_ENV_VAR);
color = Optional.fromNullable(colorString);
} else {
color = Optional.absent();
}
final Console console = new Console(verbosity, stdOut, stdErr, config.createAnsi(color));
if (commandParseResult.getErrorText().isPresent()) {
console.getStdErr().println(commandParseResult.getErrorText().get());
}
// No more early outs: acquire the command semaphore and become the only executing command.
if (!commandSemaphore.tryAcquire()) {
return BUSY_EXIT_CODE;
}
int exitCode;
ImmutableList<BuckEventListener> eventListeners;
String buildId = MoreStrings.createRandomString();
Clock clock = new DefaultClock();
ExecutionEnvironment executionEnvironment = new DefaultExecutionEnvironment();
// The order of resources in the try-with-resources block is important: the BuckEventBus must
// be the last resource, so that it is closed first and can deliver its queued events to the
// other resources before they are closed.
try (AbstractConsoleEventBusListener consoleListener =
createConsoleEventListener(clock, console, verbosity, executionEnvironment);
BuckEventBus buildEventBus = new BuckEventBus(clock, buildId)) {
Optional<WebServer> webServer = getWebServerIfDaemon(context,
projectFilesystem,
config,
console);
eventListeners = addEventListeners(buildEventBus,
projectFilesystem,
config,
webServer,
consoleListener);
ImmutableList<String> remainingArgs = ImmutableList.copyOf(
Arrays.copyOfRange(args, 1, args.length));
Command executingCommand = commandParseResult.getCommand().get();
String commandName = executingCommand.name().toLowerCase();
CommandEvent commandEvent = CommandEvent.started(commandName, remainingArgs, isDaemon);
buildEventBus.post(commandEvent);
// The ArtifactCache is constructed lazily so that we do not try to connect to Cassandra when
// running commands such as `buck clean`.
ArtifactCacheFactory artifactCacheFactory = new LoggingArtifactCacheFactory(buildEventBus);
// Create or get Parser and invalidate cached command parameters.
Parser parser;
KnownBuildRuleTypes buildRuleTypes = KnownBuildRuleTypes.getConfigured(config);
if (isDaemon) {
parser = getParserFromDaemon(context, projectFilesystem, config, console, commandEvent);
} else {
// Initialize logging and create new Parser for new process.
JavaUtilsLoggingBuildListener.ensureLogFileIsWritten();
parser = new Parser(projectFilesystem,
buildRuleTypes,
console,
config.getPythonInterpreter(),
config.getTempFilePatterns(),
createRuleKeyBuilderFactory(new DefaultFileHashCache(projectFilesystem, console)));
}
exitCode = executingCommand.execute(remainingArgs,
config,
new CommandRunnerParams(
console,
projectFilesystem,
buildRuleTypes,
artifactCacheFactory,
buildEventBus,
parser,
platform));
// TODO(user): allocate artifactCacheFactory in the try-with-resources block to avoid leaks.
artifactCacheFactory.closeCreatedArtifactCaches(ARTIFACT_CACHE_TIMEOUT_IN_SECONDS);
// If the Daemon is running and serving web traffic, print the URL to the Chrome Trace.
if (webServer.isPresent()) {
int port = webServer.get().getPort();
buildEventBus.post(LogEvent.info(
"See trace at http://localhost:%s/trace/%s", port, buildId));
}
buildEventBus.post(CommandEvent.finished(commandName, remainingArgs, isDaemon, exitCode));
} finally {
commandSemaphore.release(); // Allow another command to execute while outputting traces.
}
if (isDaemon) {
context.get().in.close(); // Avoid client exit triggering client disconnection handling.
context.get().exit(exitCode); // Allow nailgun client to exit while outputting traces.
}
for (BuckEventListener eventListener : eventListeners) {
eventListener.outputTrace(buildId);
}
return exitCode;
}
| public int executeCommand(
File projectRoot,
Command.ParseResult commandParseResult,
Optional<NGContext> context,
String... args) throws IOException {
// Create common command parameters. projectFilesystem initialization looks odd because it needs
// ignorePaths from a BuckConfig instance, which in turn needs a ProjectFilesystem (i.e. this
// solves a bootstrapping issue).
ProjectFilesystem projectFilesystem = new ProjectFilesystem(
projectRoot,
createBuckConfig(new ProjectFilesystem(projectRoot), platform).getIgnorePaths());
BuckConfig config = createBuckConfig(projectFilesystem, platform);
Verbosity verbosity = VerbosityParser.parse(args);
Optional<String> color;
final boolean isDaemon = context.isPresent();
if (isDaemon && (context.get().getEnv() != null)) {
String colorString = context.get().getEnv().getProperty(BUCKD_COLOR_DEFAULT_ENV_VAR);
color = Optional.fromNullable(colorString);
} else {
color = Optional.absent();
}
final Console console = new Console(verbosity, stdOut, stdErr, config.createAnsi(color));
if (commandParseResult.getErrorText().isPresent()) {
console.getStdErr().println(commandParseResult.getErrorText().get());
}
// No more early outs: acquire the command semaphore and become the only executing command.
if (!commandSemaphore.tryAcquire()) {
return BUSY_EXIT_CODE;
}
int exitCode;
ImmutableList<BuckEventListener> eventListeners;
String buildId = MoreStrings.createRandomString();
Clock clock = new DefaultClock();
ExecutionEnvironment executionEnvironment = new DefaultExecutionEnvironment();
// The order of resources in the try-with-resources block is important: the BuckEventBus must
// be the last resource, so that it is closed first and can deliver its queued events to the
// other resources before they are closed.
try (AbstractConsoleEventBusListener consoleListener =
createConsoleEventListener(clock, console, verbosity, executionEnvironment);
BuckEventBus buildEventBus = new BuckEventBus(clock, buildId)) {
Optional<WebServer> webServer = getWebServerIfDaemon(context,
projectFilesystem,
config,
console);
eventListeners = addEventListeners(buildEventBus,
projectFilesystem,
config,
webServer,
consoleListener);
ImmutableList<String> remainingArgs = ImmutableList.copyOf(
Arrays.copyOfRange(args, 1, args.length));
Command executingCommand = commandParseResult.getCommand().get();
String commandName = executingCommand.name().toLowerCase();
CommandEvent commandEvent = CommandEvent.started(commandName, remainingArgs, isDaemon);
buildEventBus.post(commandEvent);
// The ArtifactCache is constructed lazily so that we do not try to connect to Cassandra when
// running commands such as `buck clean`.
ArtifactCacheFactory artifactCacheFactory = new LoggingArtifactCacheFactory(buildEventBus);
// Create or get Parser and invalidate cached command parameters.
Parser parser;
KnownBuildRuleTypes buildRuleTypes = KnownBuildRuleTypes.getConfigured(config);
if (isDaemon) {
parser = getParserFromDaemon(context, projectFilesystem, config, console, commandEvent);
} else {
// Initialize logging and create new Parser for new process.
JavaUtilsLoggingBuildListener.ensureLogFileIsWritten();
parser = new Parser(projectFilesystem,
buildRuleTypes,
console,
config.getPythonInterpreter(),
config.getTempFilePatterns(),
createRuleKeyBuilderFactory(new DefaultFileHashCache(projectFilesystem, console)));
}
exitCode = executingCommand.execute(remainingArgs,
config,
new CommandRunnerParams(
console,
projectFilesystem,
buildRuleTypes,
artifactCacheFactory,
buildEventBus,
parser,
platform));
// TODO(user): allocate artifactCacheFactory in the try-with-resources block to avoid leaks.
artifactCacheFactory.closeCreatedArtifactCaches(ARTIFACT_CACHE_TIMEOUT_IN_SECONDS);
// If the Daemon is running and serving web traffic, print the URL to the Chrome Trace.
if (webServer.isPresent()) {
int port = webServer.get().getPort();
buildEventBus.post(LogEvent.info(
"See trace at http://localhost:%s/trace/%s", port, buildId));
}
buildEventBus.post(CommandEvent.finished(commandName, remainingArgs, isDaemon, exitCode));
} finally {
commandSemaphore.release(); // Allow another command to execute while outputting traces.
}
if (isDaemon) {
context.get().in.close(); // Avoid client exit triggering client disconnection handling.
context.get().exit(exitCode); // Allow nailgun client to exit while outputting traces.
}
for (BuckEventListener eventListener : eventListeners) {
try {
eventListener.outputTrace(buildId);
} catch (RuntimeException e) {
System.err.println("Skipping over non-fatal error");
e.printStackTrace();
}
}
return exitCode;
}
|
diff --git a/opentripplanner-graph-builder/src/main/java/org/opentripplanner/graph_builder/impl/osm/OpenStreetMapGraphBuilderImpl.java b/opentripplanner-graph-builder/src/main/java/org/opentripplanner/graph_builder/impl/osm/OpenStreetMapGraphBuilderImpl.java
index 2d5bc003c..92d1cc8d1 100644
--- a/opentripplanner-graph-builder/src/main/java/org/opentripplanner/graph_builder/impl/osm/OpenStreetMapGraphBuilderImpl.java
+++ b/opentripplanner-graph-builder/src/main/java/org/opentripplanner/graph_builder/impl/osm/OpenStreetMapGraphBuilderImpl.java
@@ -1,324 +1,327 @@
/* This program is free software: you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public License
as published by the Free Software Foundation, either version 3 of
the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. */
package org.opentripplanner.graph_builder.impl.osm;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import org.opentripplanner.common.geometry.PackedCoordinateSequence;
import org.opentripplanner.common.geometry.PackedCoordinateSequence.Float;
import org.opentripplanner.graph_builder.model.osm.OSMNode;
import org.opentripplanner.graph_builder.model.osm.OSMRelation;
import org.opentripplanner.graph_builder.model.osm.OSMWay;
import org.opentripplanner.graph_builder.services.GraphBuilder;
import org.opentripplanner.graph_builder.services.osm.OpenStreetMapContentHandler;
import org.opentripplanner.graph_builder.services.osm.OpenStreetMapProvider;
import org.opentripplanner.routing.core.Edge;
import org.opentripplanner.routing.core.Graph;
import org.opentripplanner.routing.core.Intersection;
import org.opentripplanner.routing.core.Vertex;
import org.opentripplanner.routing.edgetype.Street;
import org.opentripplanner.routing.edgetype.StreetTraversalPermission;
import org.opentripplanner.routing.edgetype.Turn;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.GeometryFactory;
import com.vividsolutions.jts.geom.LineString;
public class OpenStreetMapGraphBuilderImpl implements GraphBuilder {
private static Logger _log = LoggerFactory.getLogger(OpenStreetMapGraphBuilderImpl.class);
private static final GeometryFactory _geometryFactory = new GeometryFactory();
private List<OpenStreetMapProvider> _providers = new ArrayList<OpenStreetMapProvider>();
private Map<Object, Object> _uniques = new HashMap<Object, Object>();
public void setProvider(OpenStreetMapProvider provider) {
_providers.add(provider);
}
public void setProviders(List<OpenStreetMapProvider> providers) {
_providers.addAll(providers);
}
@Override
public void buildGraph(Graph graph) {
Handler handler = new Handler();
for (OpenStreetMapProvider provider : _providers) {
_log.debug("gathering osm from provider: " + provider);
provider.readOSM(handler);
}
_log.debug("building osm street graph");
handler.buildGraph(graph);
}
@SuppressWarnings("unchecked")
private <T> T unique(T value) {
Object v = _uniques.get(value);
if (v == null) {
_uniques.put(value, value);
v = value;
}
return (T) v;
}
private class Handler implements OpenStreetMapContentHandler {
private Map<Integer, OSMNode> _nodes = new HashMap<Integer, OSMNode>();
private Map<Integer, OSMWay> _ways = new HashMap<Integer, OSMWay>();
public void buildGraph(Graph graph) {
// We want to prune nodes that don't have any edges
Set<Integer> nodesWithNeighbors = new HashSet<Integer>();
for (OSMWay way : _ways.values()) {
List<Integer> nodes = way.getNodeRefs();
if (nodes.size() > 1)
nodesWithNeighbors.addAll(nodes);
}
// Remove all simple islands
_nodes.keySet().retainAll(nodesWithNeighbors);
pruneFloatingIslands();
HashMap<Coordinate, ArrayList<Edge>> edgesByLocation = new HashMap<Coordinate, ArrayList<Edge>>();
int wayIndex = 0;
for (OSMWay way : _ways.values()) {
if (wayIndex % 1000 == 0)
_log.debug("ways=" + wayIndex + "/" + _ways.size());
wayIndex++;
StreetTraversalPermission permissions = getPermissionsForWay(way);
List<Integer> nodes = way.getNodeRefs();
for (int i = 0; i < nodes.size() - 1; i++) {
Integer startNode = nodes.get(i);
String vFromId = getVertexIdForNodeId(startNode) + "_" + i + "_" + way.getId();
Integer endNode = nodes.get(i + 1);
String vToId = getVertexIdForNodeId(endNode) + "_" + i + "_" + way.getId();
OSMNode osmStartNode = _nodes.get(startNode);
OSMNode osmEndNode = _nodes.get(endNode);
if (osmStartNode == null || osmEndNode == null)
continue;
Vertex from = addVertex(graph, vFromId, osmStartNode);
Vertex to = addVertex(graph, vToId, osmEndNode);
double d = from.distance(to);
Street street = getEdgeForStreet(from, to, way, d, permissions);
graph.addEdge(street);
Street backStreet = getEdgeForStreet(to, from, way, d, permissions);
graph.addEdge(backStreet);
ArrayList<Edge> startEdges = edgesByLocation.get(from.getCoordinate());
if (startEdges == null) {
startEdges = new ArrayList<Edge>();
edgesByLocation.put(from.getCoordinate(), startEdges);
}
startEdges.add(street);
ArrayList<Edge> endEdges = edgesByLocation.get(to.getCoordinate());
if (endEdges == null) {
endEdges = new ArrayList<Edge>();
edgesByLocation.put(to.getCoordinate(), endEdges);
}
endEdges.add(backStreet);
}
}
// add turns
for (ArrayList<Edge> edges : edgesByLocation.values()) {
for (Edge in : edges) {
Vertex tov = in.getToVertex();
Coordinate c = tov.getCoordinate();
ArrayList<Edge> outEdges = edgesByLocation.get(c);
if (outEdges != null) {
/* If this is not an intersection or street name change, unify the vertices */
+ boolean unified = false;
if (outEdges.size() == 2) {
for (Edge out : outEdges) {
Vertex fromVertex = out.getFromVertex();
if (tov != fromVertex && out.getName() == in.getName()) {
Intersection v = (Intersection) tov;
v.mergeFrom(graph, (Intersection) fromVertex);
graph.removeVertex(fromVertex);
+ unified = true;
break;
}
}
- } else {
+ }
+ if (!unified) {
for (Edge out : outEdges) {
/*
* Only create a turn edge if: (a) the edge is not the one we are
* coming from (b) the edge is a Street (c) the edge is an outgoing
* edge from this location
*/
if (tov != out.getFromVertex() && out instanceof Street
&& out.getFromVertex().getCoordinate().equals(c)) {
graph.addEdge(new Turn(in, out));
}
}
}
}
}
}
}
private Vertex addVertex(Graph graph, String vertexId, OSMNode node) {
Intersection newVertex = new Intersection(vertexId, node.getLon(), node.getLat());
graph.addVertex(newVertex);
return newVertex;
}
private void pruneFloatingIslands() {
Map<Integer, HashSet<Integer>> subgraphs = new HashMap<Integer, HashSet<Integer>>();
Map<Integer, ArrayList<Integer>> neighborsForNode = new HashMap<Integer, ArrayList<Integer>>();
for (OSMWay way : _ways.values()) {
List<Integer> nodes = way.getNodeRefs();
for (int node : nodes) {
ArrayList<Integer> nodelist = neighborsForNode.get(node);
if (nodelist == null) {
nodelist = new ArrayList<Integer>();
neighborsForNode.put(node, nodelist);
}
nodelist.addAll(nodes);
}
}
/* associate each node with a subgraph */
for (int node : _nodes.keySet()) {
if (subgraphs.containsKey(node)) {
continue;
}
HashSet<Integer> subgraph = computeConnectedSubgraph(neighborsForNode, node);
for (int subnode : subgraph) {
subgraphs.put(subnode, subgraph);
}
}
/* find the largest subgraph */
HashSet<Integer> largestSubgraph = null;
for (HashSet<Integer> subgraph : subgraphs.values()) {
if (largestSubgraph == null || largestSubgraph.size() < subgraph.size()) {
largestSubgraph = subgraph;
}
}
/* delete the rest */
_nodes.keySet().retainAll(largestSubgraph);
}
private HashSet<Integer> computeConnectedSubgraph(
Map<Integer, ArrayList<Integer>> neighborsForNode, int startNode) {
HashSet<Integer> subgraph = new HashSet<Integer>();
Queue<Integer> q = new LinkedList<Integer>();
q.add(startNode);
while (!q.isEmpty()) {
int node = q.poll();
for (int neighbor : neighborsForNode.get(node)) {
if (!subgraph.contains(neighbor)) {
subgraph.add(neighbor);
q.add(neighbor);
}
}
}
return subgraph;
}
public void addNode(OSMNode node) {
if (_nodes.containsKey(node.getId()))
return;
_nodes.put(node.getId(), node);
if (_nodes.size() % 1000 == 0)
_log.debug("nodes=" + _nodes.size());
}
public void addWay(OSMWay way) {
if (_ways.containsKey(way.getId()))
return;
if (!(way.getTags().containsKey("highway") || "platform".equals(way.getTags().get(
"railway")))) {
return;
}
_ways.put(way.getId(), way);
if (_ways.size() % 1000 == 0)
_log.debug("ways=" + _ways.size());
}
public void addRelation(OSMRelation relation) {
}
private String getVertexIdForNodeId(int nodeId) {
return "osm node " + nodeId;
}
private Street getEdgeForStreet(Vertex from, Vertex to, OSMWay way, double d,
StreetTraversalPermission permissions) {
String id = "way " + way.getId();
id = unique(id);
String name = way.getTags().get("name");
if (name == null) {
name = id;
}
Street street = new Street(from, to, id, name, d, permissions);
Coordinate[] coordinates = { from.getCoordinate(), to.getCoordinate() };
Float sequence = new PackedCoordinateSequence.Float(coordinates, 2);
LineString lineString = _geometryFactory.createLineString(sequence);
street.setGeometry(lineString);
return street;
}
private StreetTraversalPermission getPermissionsForWay(OSMWay way) {
// TODO : Better mapping between OSM tags and travel permissions
Map<String, String> tags = way.getTags();
String value = tags.get("highway");
if (value == null || value.equals("motorway") || value.equals("motorway_link"))
return StreetTraversalPermission.CAR_ONLY;
if ("platform".equals(way.getTags().get("railway"))) {
return StreetTraversalPermission.PEDESTRIAN_AND_BICYCLE_ONLY;
}
return StreetTraversalPermission.ALL;
}
}
}
| false | true | public void buildGraph(Graph graph) {
// We want to prune nodes that don't have any edges
Set<Integer> nodesWithNeighbors = new HashSet<Integer>();
for (OSMWay way : _ways.values()) {
List<Integer> nodes = way.getNodeRefs();
if (nodes.size() > 1)
nodesWithNeighbors.addAll(nodes);
}
// Remove all simple islands
_nodes.keySet().retainAll(nodesWithNeighbors);
pruneFloatingIslands();
HashMap<Coordinate, ArrayList<Edge>> edgesByLocation = new HashMap<Coordinate, ArrayList<Edge>>();
int wayIndex = 0;
for (OSMWay way : _ways.values()) {
if (wayIndex % 1000 == 0)
_log.debug("ways=" + wayIndex + "/" + _ways.size());
wayIndex++;
StreetTraversalPermission permissions = getPermissionsForWay(way);
List<Integer> nodes = way.getNodeRefs();
for (int i = 0; i < nodes.size() - 1; i++) {
Integer startNode = nodes.get(i);
String vFromId = getVertexIdForNodeId(startNode) + "_" + i + "_" + way.getId();
Integer endNode = nodes.get(i + 1);
String vToId = getVertexIdForNodeId(endNode) + "_" + i + "_" + way.getId();
OSMNode osmStartNode = _nodes.get(startNode);
OSMNode osmEndNode = _nodes.get(endNode);
if (osmStartNode == null || osmEndNode == null)
continue;
Vertex from = addVertex(graph, vFromId, osmStartNode);
Vertex to = addVertex(graph, vToId, osmEndNode);
double d = from.distance(to);
Street street = getEdgeForStreet(from, to, way, d, permissions);
graph.addEdge(street);
Street backStreet = getEdgeForStreet(to, from, way, d, permissions);
graph.addEdge(backStreet);
ArrayList<Edge> startEdges = edgesByLocation.get(from.getCoordinate());
if (startEdges == null) {
startEdges = new ArrayList<Edge>();
edgesByLocation.put(from.getCoordinate(), startEdges);
}
startEdges.add(street);
ArrayList<Edge> endEdges = edgesByLocation.get(to.getCoordinate());
if (endEdges == null) {
endEdges = new ArrayList<Edge>();
edgesByLocation.put(to.getCoordinate(), endEdges);
}
endEdges.add(backStreet);
}
}
// add turns
for (ArrayList<Edge> edges : edgesByLocation.values()) {
for (Edge in : edges) {
Vertex tov = in.getToVertex();
Coordinate c = tov.getCoordinate();
ArrayList<Edge> outEdges = edgesByLocation.get(c);
if (outEdges != null) {
/* If this is not an intersection or street name change, unify the vertices */
if (outEdges.size() == 2) {
for (Edge out : outEdges) {
Vertex fromVertex = out.getFromVertex();
if (tov != fromVertex && out.getName() == in.getName()) {
Intersection v = (Intersection) tov;
v.mergeFrom(graph, (Intersection) fromVertex);
graph.removeVertex(fromVertex);
break;
}
}
} else {
for (Edge out : outEdges) {
/*
* Only create a turn edge if: (a) the edge is not the one we are
* coming from (b) the edge is a Street (c) the edge is an outgoing
* edge from this location
*/
if (tov != out.getFromVertex() && out instanceof Street
&& out.getFromVertex().getCoordinate().equals(c)) {
graph.addEdge(new Turn(in, out));
}
}
}
}
}
}
}
| public void buildGraph(Graph graph) {
// We want to prune nodes that don't have any edges
Set<Integer> nodesWithNeighbors = new HashSet<Integer>();
for (OSMWay way : _ways.values()) {
List<Integer> nodes = way.getNodeRefs();
if (nodes.size() > 1)
nodesWithNeighbors.addAll(nodes);
}
// Remove all simple islands
_nodes.keySet().retainAll(nodesWithNeighbors);
pruneFloatingIslands();
HashMap<Coordinate, ArrayList<Edge>> edgesByLocation = new HashMap<Coordinate, ArrayList<Edge>>();
int wayIndex = 0;
for (OSMWay way : _ways.values()) {
if (wayIndex % 1000 == 0)
_log.debug("ways=" + wayIndex + "/" + _ways.size());
wayIndex++;
StreetTraversalPermission permissions = getPermissionsForWay(way);
List<Integer> nodes = way.getNodeRefs();
for (int i = 0; i < nodes.size() - 1; i++) {
Integer startNode = nodes.get(i);
String vFromId = getVertexIdForNodeId(startNode) + "_" + i + "_" + way.getId();
Integer endNode = nodes.get(i + 1);
String vToId = getVertexIdForNodeId(endNode) + "_" + i + "_" + way.getId();
OSMNode osmStartNode = _nodes.get(startNode);
OSMNode osmEndNode = _nodes.get(endNode);
if (osmStartNode == null || osmEndNode == null)
continue;
Vertex from = addVertex(graph, vFromId, osmStartNode);
Vertex to = addVertex(graph, vToId, osmEndNode);
double d = from.distance(to);
Street street = getEdgeForStreet(from, to, way, d, permissions);
graph.addEdge(street);
Street backStreet = getEdgeForStreet(to, from, way, d, permissions);
graph.addEdge(backStreet);
ArrayList<Edge> startEdges = edgesByLocation.get(from.getCoordinate());
if (startEdges == null) {
startEdges = new ArrayList<Edge>();
edgesByLocation.put(from.getCoordinate(), startEdges);
}
startEdges.add(street);
ArrayList<Edge> endEdges = edgesByLocation.get(to.getCoordinate());
if (endEdges == null) {
endEdges = new ArrayList<Edge>();
edgesByLocation.put(to.getCoordinate(), endEdges);
}
endEdges.add(backStreet);
}
}
// add turns
for (ArrayList<Edge> edges : edgesByLocation.values()) {
for (Edge in : edges) {
Vertex tov = in.getToVertex();
Coordinate c = tov.getCoordinate();
ArrayList<Edge> outEdges = edgesByLocation.get(c);
if (outEdges != null) {
/* If this is not an intersection or street name change, unify the vertices */
boolean unified = false;
if (outEdges.size() == 2) {
for (Edge out : outEdges) {
Vertex fromVertex = out.getFromVertex();
if (tov != fromVertex && out.getName() == in.getName()) {
Intersection v = (Intersection) tov;
v.mergeFrom(graph, (Intersection) fromVertex);
graph.removeVertex(fromVertex);
unified = true;
break;
}
}
}
if (!unified) {
for (Edge out : outEdges) {
/*
* Only create a turn edge if: (a) the edge is not the one we are
* coming from (b) the edge is a Street (c) the edge is an outgoing
* edge from this location
*/
if (tov != out.getFromVertex() && out instanceof Street
&& out.getFromVertex().getCoordinate().equals(c)) {
graph.addEdge(new Turn(in, out));
}
}
}
}
}
}
}
|
diff --git a/org.eclipse.gmf.runtime/tests/org.eclipse.gmf.tests.runtime.common.core/src/org/eclipse/gmf/tests/runtime/common/core/internal/util/StringUtilTest.java b/org.eclipse.gmf.runtime/tests/org.eclipse.gmf.tests.runtime.common.core/src/org/eclipse/gmf/tests/runtime/common/core/internal/util/StringUtilTest.java
index 36bbebe6..e679bc22 100644
--- a/org.eclipse.gmf.runtime/tests/org.eclipse.gmf.tests.runtime.common.core/src/org/eclipse/gmf/tests/runtime/common/core/internal/util/StringUtilTest.java
+++ b/org.eclipse.gmf.runtime/tests/org.eclipse.gmf.tests.runtime.common.core/src/org/eclipse/gmf/tests/runtime/common/core/internal/util/StringUtilTest.java
@@ -1,81 +1,81 @@
/******************************************************************************
* Copyright (c) 2002, 2005 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
****************************************************************************/
package org.eclipse.gmf.tests.runtime.common.core.internal.util;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import junit.textui.TestRunner;
import org.eclipse.gmf.runtime.common.core.util.Proxy;
import org.eclipse.gmf.runtime.common.core.util.StringUtil;
/**
* Tests org.eclipse.gmf.runtime.common.core.internal.util.StringUtil
* @author Wayne Diu, wdiu
*/
public class StringUtilTest extends TestCase {
private final String src = "I am writing a test case with the word a.\nThe word a is a very important word because I want to replace all instances of it. It is a word. And I must test case sensitive replaces too, okay?"; //$NON-NLS-1$
protected static class Fixture extends Proxy {
protected Fixture(Object realObject) {
super(realObject);
}
}
public static void main(String[] args) {
TestRunner.run(suite());
}
public static Test suite() {
return new TestSuite(StringUtilTest.class);
}
public StringUtilTest(String name) {
super(name);
}
/*
* The test cases replace a with a a because that could result in
* infinite recursion if I did not write the replace methods correctly.
*/
public void test_Replace() {
assertTrue(StringUtil.replace(src, "a", "a a", false).equals("I a am writing a test case with the word a.\nThe word a is a very important word because I want to replace all instances of it. It is a word. And I must test case sensitive replaces too, okay?")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
assertTrue(StringUtil.replaceAll(src, "a", "a a", true).equals("I a am writing a a test ca ase with the word a a.\nThe word a a is a a very importa ant word beca ause I wa ant to repla ace a all insta ances of it. It is a a word. And I must test ca ase sensitive repla aces too, oka ay?")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
public void test_ReplaceWholeWords() {
assertTrue(StringUtil.replaceWholeWords(src, "a", "a a", true).equals("I am writing a a test case with the word a.\nThe word a is a very important word because I want to replace all instances of it. It is a word. And I must test case sensitive replaces too, okay?")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
assertTrue(StringUtil.replaceAllWholeWords(src, "a", "a a", false).equals("I am writing a a test case with the word a a.\nThe word a a is a a very important word because I want to replace all instances of it. It is a a word. And I must test case sensitive replaces too, okay?")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
public void test_dgdEncodeURL() {
//These should not change after encoding
assertTrue(StringUtil.encodeURL("http://www.ibm.ca/").equals("http://www.ibm.ca/")); //$NON-NLS-1$ //$NON-NLS-2$
assertTrue(StringUtil.encodeURL("http://www.ibm.ca").equals("http://www.ibm.ca")); //$NON-NLS-1$ //$NON-NLS-2$
assertTrue(StringUtil.encodeURL("C:\\dir\\sub").equals("C:\\dir\\sub")); //$NON-NLS-1$ //$NON-NLS-2$
- assertTrue(StringUtil.encodeURL("Fil�name with spaces.doc").equals("Fil�name with spaces.doc")); //$NON-NLS-1$ //$NON-NLS-2$
+ assertTrue(StringUtil.encodeURL("Fil\u00E9name with spaces.doc").equals("Fil\u00E9name with spaces.doc")); //$NON-NLS-1$ //$NON-NLS-2$
assertTrue(StringUtil.encodeURL("http://www.ibm.com/Search/?q=rational&v=14&lang=en&cc=ca").equals("http://www.ibm.com/Search/?q=rational&v=14&lang=en&cc=ca")); //$NON-NLS-1$ //$NON-NLS-2$
//These should change after encoding
- assertTrue(StringUtil.encodeURL("http://www.ibm.com/Search/?q=�����&v=14&lang=en&cc=ca").equals("http://www.ibm.com/Search/?q=%C3%A9%C3%A7%C3%A5%C3%A2%C3%A8&v=14&lang=en&cc=ca")); //$NON-NLS-1$ //$NON-NLS-2$
- assertTrue(StringUtil.encodeURL("http://www.ibm.com/Search/?q=�����%3d&v=14&lang=en&cc=ca").equals("http://www.ibm.com/Search/?q=%C3%A9%C3%A7%C3%A5%C3%A2%C3%A8%3d&v=14&lang=en&cc=ca")); //$NON-NLS-1$ //$NON-NLS-2$
- assertTrue(StringUtil.encodeURL("http://www.ibm.com/Search/?q=�����%a&v=14&lang=en&cc=ca").equals("http://www.ibm.com/Search/?q=%C3%A9%C3%A7%C3%A5%C3%A2%C3%A8%25a&v=14&lang=en&cc=ca")); //$NON-NLS-1$ //$NON-NLS-2$
- assertTrue(StringUtil.encodeURL("http://www.ibm.com/Search/?q=�����%fg%a&v=14&lang=en&cc=ca").equals("http://www.ibm.com/Search/?q=%C3%A9%C3%A7%C3%A5%C3%A2%C3%A8%25fg%25a&v=14&lang=en&cc=ca")); //$NON-NLS-1$ //$NON-NLS-2$
- assertTrue(StringUtil.encodeURL("http://www.ibm.com/Search/?q=�����%%a&v=14&lang=en&cc=ca").equals("http://www.ibm.com/Search/?q=%C3%A9%C3%A7%C3%A5%C3%A2%C3%A8%25%25a&v=14&lang=en&cc=ca")); //$NON-NLS-1$ //$NON-NLS-2$
- assertTrue(StringUtil.encodeURL("http://www.ibm.com/Search/?q=�����%&v=14&lang=en&cc=ca").equals("http://www.ibm.com/Search/?q=%C3%A9%C3%A7%C3%A5%C3%A2%C3%A8%25&v=14&lang=en&cc=ca")); //$NON-NLS-1$ //$NON-NLS-2$
+ assertTrue(StringUtil.encodeURL("http://www.ibm.com/Search/?q=\u00E9\u00E7\u00E5\u00E2\u00E8&v=14&lang=en&cc=ca").equals("http://www.ibm.com/Search/?q=%C3%A9%C3%A7%C3%A5%C3%A2%C3%A8&v=14&lang=en&cc=ca")); //$NON-NLS-1$ //$NON-NLS-2$
+ assertTrue(StringUtil.encodeURL("http://www.ibm.com/Search/?q=\u00E9\u00E7\u00E5\u00E2\u00E8%3d&v=14&lang=en&cc=ca").equals("http://www.ibm.com/Search/?q=%C3%A9%C3%A7%C3%A5%C3%A2%C3%A8%3d&v=14&lang=en&cc=ca")); //$NON-NLS-1$ //$NON-NLS-2$
+ assertTrue(StringUtil.encodeURL("http://www.ibm.com/Search/?q=\u00E9\u00E7\u00E5\u00E2\u00E8%a&v=14&lang=en&cc=ca").equals("http://www.ibm.com/Search/?q=%C3%A9%C3%A7%C3%A5%C3%A2%C3%A8%25a&v=14&lang=en&cc=ca")); //$NON-NLS-1$ //$NON-NLS-2$
+ assertTrue(StringUtil.encodeURL("http://www.ibm.com/Search/?q=\u00E9\u00E7\u00E5\u00E2\u00E8%fg%a&v=14&lang=en&cc=ca").equals("http://www.ibm.com/Search/?q=%C3%A9%C3%A7%C3%A5%C3%A2%C3%A8%25fg%25a&v=14&lang=en&cc=ca")); //$NON-NLS-1$ //$NON-NLS-2$
+ assertTrue(StringUtil.encodeURL("http://www.ibm.com/Search/?q=\u00E9\u00E7\u00E5\u00E2\u00E8%%a&v=14&lang=en&cc=ca").equals("http://www.ibm.com/Search/?q=%C3%A9%C3%A7%C3%A5%C3%A2%C3%A8%25%25a&v=14&lang=en&cc=ca")); //$NON-NLS-1$ //$NON-NLS-2$
+ assertTrue(StringUtil.encodeURL("http://www.ibm.com/Search/?q=\u00E9\u00E7\u00E5\u00E2\u00E8%&v=14&lang=en&cc=ca").equals("http://www.ibm.com/Search/?q=%C3%A9%C3%A7%C3%A5%C3%A2%C3%A8%25&v=14&lang=en&cc=ca")); //$NON-NLS-1$ //$NON-NLS-2$
}
}
| false | true | public void test_dgdEncodeURL() {
//These should not change after encoding
assertTrue(StringUtil.encodeURL("http://www.ibm.ca/").equals("http://www.ibm.ca/")); //$NON-NLS-1$ //$NON-NLS-2$
assertTrue(StringUtil.encodeURL("http://www.ibm.ca").equals("http://www.ibm.ca")); //$NON-NLS-1$ //$NON-NLS-2$
assertTrue(StringUtil.encodeURL("C:\\dir\\sub").equals("C:\\dir\\sub")); //$NON-NLS-1$ //$NON-NLS-2$
assertTrue(StringUtil.encodeURL("Fil�name with spaces.doc").equals("Fil�name with spaces.doc")); //$NON-NLS-1$ //$NON-NLS-2$
assertTrue(StringUtil.encodeURL("http://www.ibm.com/Search/?q=rational&v=14&lang=en&cc=ca").equals("http://www.ibm.com/Search/?q=rational&v=14&lang=en&cc=ca")); //$NON-NLS-1$ //$NON-NLS-2$
//These should change after encoding
assertTrue(StringUtil.encodeURL("http://www.ibm.com/Search/?q=�����&v=14&lang=en&cc=ca").equals("http://www.ibm.com/Search/?q=%C3%A9%C3%A7%C3%A5%C3%A2%C3%A8&v=14&lang=en&cc=ca")); //$NON-NLS-1$ //$NON-NLS-2$
assertTrue(StringUtil.encodeURL("http://www.ibm.com/Search/?q=�����%3d&v=14&lang=en&cc=ca").equals("http://www.ibm.com/Search/?q=%C3%A9%C3%A7%C3%A5%C3%A2%C3%A8%3d&v=14&lang=en&cc=ca")); //$NON-NLS-1$ //$NON-NLS-2$
assertTrue(StringUtil.encodeURL("http://www.ibm.com/Search/?q=�����%a&v=14&lang=en&cc=ca").equals("http://www.ibm.com/Search/?q=%C3%A9%C3%A7%C3%A5%C3%A2%C3%A8%25a&v=14&lang=en&cc=ca")); //$NON-NLS-1$ //$NON-NLS-2$
assertTrue(StringUtil.encodeURL("http://www.ibm.com/Search/?q=�����%fg%a&v=14&lang=en&cc=ca").equals("http://www.ibm.com/Search/?q=%C3%A9%C3%A7%C3%A5%C3%A2%C3%A8%25fg%25a&v=14&lang=en&cc=ca")); //$NON-NLS-1$ //$NON-NLS-2$
assertTrue(StringUtil.encodeURL("http://www.ibm.com/Search/?q=�����%%a&v=14&lang=en&cc=ca").equals("http://www.ibm.com/Search/?q=%C3%A9%C3%A7%C3%A5%C3%A2%C3%A8%25%25a&v=14&lang=en&cc=ca")); //$NON-NLS-1$ //$NON-NLS-2$
assertTrue(StringUtil.encodeURL("http://www.ibm.com/Search/?q=�����%&v=14&lang=en&cc=ca").equals("http://www.ibm.com/Search/?q=%C3%A9%C3%A7%C3%A5%C3%A2%C3%A8%25&v=14&lang=en&cc=ca")); //$NON-NLS-1$ //$NON-NLS-2$
}
| public void test_dgdEncodeURL() {
//These should not change after encoding
assertTrue(StringUtil.encodeURL("http://www.ibm.ca/").equals("http://www.ibm.ca/")); //$NON-NLS-1$ //$NON-NLS-2$
assertTrue(StringUtil.encodeURL("http://www.ibm.ca").equals("http://www.ibm.ca")); //$NON-NLS-1$ //$NON-NLS-2$
assertTrue(StringUtil.encodeURL("C:\\dir\\sub").equals("C:\\dir\\sub")); //$NON-NLS-1$ //$NON-NLS-2$
assertTrue(StringUtil.encodeURL("Fil\u00E9name with spaces.doc").equals("Fil\u00E9name with spaces.doc")); //$NON-NLS-1$ //$NON-NLS-2$
assertTrue(StringUtil.encodeURL("http://www.ibm.com/Search/?q=rational&v=14&lang=en&cc=ca").equals("http://www.ibm.com/Search/?q=rational&v=14&lang=en&cc=ca")); //$NON-NLS-1$ //$NON-NLS-2$
//These should change after encoding
assertTrue(StringUtil.encodeURL("http://www.ibm.com/Search/?q=\u00E9\u00E7\u00E5\u00E2\u00E8&v=14&lang=en&cc=ca").equals("http://www.ibm.com/Search/?q=%C3%A9%C3%A7%C3%A5%C3%A2%C3%A8&v=14&lang=en&cc=ca")); //$NON-NLS-1$ //$NON-NLS-2$
assertTrue(StringUtil.encodeURL("http://www.ibm.com/Search/?q=\u00E9\u00E7\u00E5\u00E2\u00E8%3d&v=14&lang=en&cc=ca").equals("http://www.ibm.com/Search/?q=%C3%A9%C3%A7%C3%A5%C3%A2%C3%A8%3d&v=14&lang=en&cc=ca")); //$NON-NLS-1$ //$NON-NLS-2$
assertTrue(StringUtil.encodeURL("http://www.ibm.com/Search/?q=\u00E9\u00E7\u00E5\u00E2\u00E8%a&v=14&lang=en&cc=ca").equals("http://www.ibm.com/Search/?q=%C3%A9%C3%A7%C3%A5%C3%A2%C3%A8%25a&v=14&lang=en&cc=ca")); //$NON-NLS-1$ //$NON-NLS-2$
assertTrue(StringUtil.encodeURL("http://www.ibm.com/Search/?q=\u00E9\u00E7\u00E5\u00E2\u00E8%fg%a&v=14&lang=en&cc=ca").equals("http://www.ibm.com/Search/?q=%C3%A9%C3%A7%C3%A5%C3%A2%C3%A8%25fg%25a&v=14&lang=en&cc=ca")); //$NON-NLS-1$ //$NON-NLS-2$
assertTrue(StringUtil.encodeURL("http://www.ibm.com/Search/?q=\u00E9\u00E7\u00E5\u00E2\u00E8%%a&v=14&lang=en&cc=ca").equals("http://www.ibm.com/Search/?q=%C3%A9%C3%A7%C3%A5%C3%A2%C3%A8%25%25a&v=14&lang=en&cc=ca")); //$NON-NLS-1$ //$NON-NLS-2$
assertTrue(StringUtil.encodeURL("http://www.ibm.com/Search/?q=\u00E9\u00E7\u00E5\u00E2\u00E8%&v=14&lang=en&cc=ca").equals("http://www.ibm.com/Search/?q=%C3%A9%C3%A7%C3%A5%C3%A2%C3%A8%25&v=14&lang=en&cc=ca")); //$NON-NLS-1$ //$NON-NLS-2$
}
|
diff --git a/test/src/com/rabbitmq/client/test/functional/FanoutTest.java b/test/src/com/rabbitmq/client/test/functional/FanoutTest.java
index 5c2012441..34d119bf5 100644
--- a/test/src/com/rabbitmq/client/test/functional/FanoutTest.java
+++ b/test/src/com/rabbitmq/client/test/functional/FanoutTest.java
@@ -1,51 +1,51 @@
package com.rabbitmq.client.test.functional;
import com.rabbitmq.client.MessageProperties;
import com.rabbitmq.client.GetResponse;
import java.util.List;
import java.util.ArrayList;
/**
* Functional test to verify fanout behaviour
*/
public class FanoutTest extends BrokerTestCase {
private static final int N = 10;
protected static final String X = "amq.fanout";
protected static final String K = "";
protected static final byte[] payload = (""+ System.currentTimeMillis()).getBytes();
// TODO: This setup code is copy and paste - maybe this should wander up to the super class?
protected void setUp() throws Exception {
openConnection();
openChannel();
}
protected void tearDown() throws Exception {
closeChannel();
closeConnection();
}
public void testFanout() throws Exception {
List<String> queues = new ArrayList<String>();
for (int i = 0; i < N; i++) {
String q = "Q-" + System.nanoTime();
channel.queueDeclare(ticket, q);
channel.queueBind(ticket, q, X, K);
queues.add(q);
}
- channel.basicPublish(ticket, X, K, MessageProperties.BASIC, payload);
+ channel.basicPublish(ticket, X, System.nanoTime() + "", MessageProperties.BASIC, payload);
for (String q : queues) {
GetResponse response = channel.basicGet(ticket, q, true);
assertNotNull("The response should not be null", response);
}
}
}
| true | true | public void testFanout() throws Exception {
List<String> queues = new ArrayList<String>();
for (int i = 0; i < N; i++) {
String q = "Q-" + System.nanoTime();
channel.queueDeclare(ticket, q);
channel.queueBind(ticket, q, X, K);
queues.add(q);
}
channel.basicPublish(ticket, X, K, MessageProperties.BASIC, payload);
for (String q : queues) {
GetResponse response = channel.basicGet(ticket, q, true);
assertNotNull("The response should not be null", response);
}
}
| public void testFanout() throws Exception {
List<String> queues = new ArrayList<String>();
for (int i = 0; i < N; i++) {
String q = "Q-" + System.nanoTime();
channel.queueDeclare(ticket, q);
channel.queueBind(ticket, q, X, K);
queues.add(q);
}
channel.basicPublish(ticket, X, System.nanoTime() + "", MessageProperties.BASIC, payload);
for (String q : queues) {
GetResponse response = channel.basicGet(ticket, q, true);
assertNotNull("The response should not be null", response);
}
}
|
diff --git a/src/rules/model/BackwardChaining.java b/src/rules/model/BackwardChaining.java
index 0ad56e6..3d627fd 100644
--- a/src/rules/model/BackwardChaining.java
+++ b/src/rules/model/BackwardChaining.java
@@ -1,118 +1,118 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package rules.model;
import java.util.Vector;
/**
*
* @author Martynas
*/
public class BackwardChaining extends AbstractAlgo {
private Vector<Fact> previouslyDeducted;
protected Vector<Production> productionsInUse;
// recursion level - only used for logging
private int rLevel = 0;
public BackwardChaining(Vector<Production> productions, Vector<Fact> gdb, Fact target, LogModel logger) {
super(productions, gdb, target, logger);
System.err.println(this);
previouslyDeducted = new Vector<Fact>();
productionsInUse = new Vector<Production>();
}
public boolean iterate() {
logger.log("Tikslas yra: %s.\n", target);
boolean result = get(target);
finished = true;
return result;
}
public boolean get(Fact f) {
// check if fact is in primary facts {1}
if (gdb.contains(f)) {
logger.log(" %s yra pradinis faktas.\n", f);
return true;
}
// check if the fact was previously deducted
if (previouslyDeducted.contains(f)) {
logger.log(" %s yra jau išvestas.\n", f);
return true;
}
rLevel++;
// check if the fact can be derived from the used productions
for (Production p: productionsInUse) {
if (p.getOutput().contains(f)) {
- trace("Ciklas su %s.\n", p);
+ trace("Ciklas dėl %s.\n", f);
rLevel--;
return false;
}
}
boolean factCanBeDerived = false;
for (int i = 0; i < productions.size(); i++) {
Production currentProduction = productions.elementAt(i);
if (currentProduction.getOutput().contains(f) && !usedProductions.contains(currentProduction)) { // {2}
factCanBeDerived = true;
boolean allInputsFound = true;
// mark the production, so it is not used from this point
productionsInUse.add(currentProduction);
// get all needed facts for this production.
// Stop after the first production which could not be found.
for (int j = 0; j < currentProduction.getInput().size() && allInputsFound; j++) { // {3}
trace("Naujas tikslas %s, nes %s galima išvesti iš %s.", currentProduction.getInput().elementAt(j), f, currentProduction);
boolean result = get(currentProduction.getInput().elementAt(j));
allInputsFound = allInputsFound && result;
if (result) {
previouslyDeducted.add(currentProduction.getInput().elementAt(j)); // {4}
}
}
if (allInputsFound) {
usedProductions.add(currentProduction); // {5}
rLevel--;
return true;
}
// not all inputs were found for this production,
// unmark this production as used
productionsInUse.remove(currentProduction);
}
}
if (!factCanBeDerived) {
trace("%s nerastas. Aklavietė.\n", f);
}
rLevel--;
return false; // {6}
}
public void trace(String s, Object... args) {
actionNum++;
logger.log("\n"+actionNum+". ");
for (int i = 0; i < rLevel; i++) {
logger.log(" ");
}
logger.log(String.format(s, args));
}
}
| true | true | public boolean get(Fact f) {
// check if fact is in primary facts {1}
if (gdb.contains(f)) {
logger.log(" %s yra pradinis faktas.\n", f);
return true;
}
// check if the fact was previously deducted
if (previouslyDeducted.contains(f)) {
logger.log(" %s yra jau išvestas.\n", f);
return true;
}
rLevel++;
// check if the fact can be derived from the used productions
for (Production p: productionsInUse) {
if (p.getOutput().contains(f)) {
trace("Ciklas su %s.\n", p);
rLevel--;
return false;
}
}
boolean factCanBeDerived = false;
for (int i = 0; i < productions.size(); i++) {
Production currentProduction = productions.elementAt(i);
if (currentProduction.getOutput().contains(f) && !usedProductions.contains(currentProduction)) { // {2}
factCanBeDerived = true;
boolean allInputsFound = true;
// mark the production, so it is not used from this point
productionsInUse.add(currentProduction);
// get all needed facts for this production.
// Stop after the first production which could not be found.
for (int j = 0; j < currentProduction.getInput().size() && allInputsFound; j++) { // {3}
trace("Naujas tikslas %s, nes %s galima išvesti iš %s.", currentProduction.getInput().elementAt(j), f, currentProduction);
boolean result = get(currentProduction.getInput().elementAt(j));
allInputsFound = allInputsFound && result;
if (result) {
previouslyDeducted.add(currentProduction.getInput().elementAt(j)); // {4}
}
}
if (allInputsFound) {
usedProductions.add(currentProduction); // {5}
rLevel--;
return true;
}
// not all inputs were found for this production,
// unmark this production as used
productionsInUse.remove(currentProduction);
}
}
if (!factCanBeDerived) {
trace("%s nerastas. Aklavietė.\n", f);
}
rLevel--;
return false; // {6}
}
| public boolean get(Fact f) {
// check if fact is in primary facts {1}
if (gdb.contains(f)) {
logger.log(" %s yra pradinis faktas.\n", f);
return true;
}
// check if the fact was previously deducted
if (previouslyDeducted.contains(f)) {
logger.log(" %s yra jau išvestas.\n", f);
return true;
}
rLevel++;
// check if the fact can be derived from the used productions
for (Production p: productionsInUse) {
if (p.getOutput().contains(f)) {
trace("Ciklas dėl %s.\n", f);
rLevel--;
return false;
}
}
boolean factCanBeDerived = false;
for (int i = 0; i < productions.size(); i++) {
Production currentProduction = productions.elementAt(i);
if (currentProduction.getOutput().contains(f) && !usedProductions.contains(currentProduction)) { // {2}
factCanBeDerived = true;
boolean allInputsFound = true;
// mark the production, so it is not used from this point
productionsInUse.add(currentProduction);
// get all needed facts for this production.
// Stop after the first production which could not be found.
for (int j = 0; j < currentProduction.getInput().size() && allInputsFound; j++) { // {3}
trace("Naujas tikslas %s, nes %s galima išvesti iš %s.", currentProduction.getInput().elementAt(j), f, currentProduction);
boolean result = get(currentProduction.getInput().elementAt(j));
allInputsFound = allInputsFound && result;
if (result) {
previouslyDeducted.add(currentProduction.getInput().elementAt(j)); // {4}
}
}
if (allInputsFound) {
usedProductions.add(currentProduction); // {5}
rLevel--;
return true;
}
// not all inputs were found for this production,
// unmark this production as used
productionsInUse.remove(currentProduction);
}
}
if (!factCanBeDerived) {
trace("%s nerastas. Aklavietė.\n", f);
}
rLevel--;
return false; // {6}
}
|
diff --git a/target_explorer/plugins/org.eclipse.tcf.te.ui.terminals.process/src/org/eclipse/tcf/te/ui/terminals/process/ProcessConnector.java b/target_explorer/plugins/org.eclipse.tcf.te.ui.terminals.process/src/org/eclipse/tcf/te/ui/terminals/process/ProcessConnector.java
index 233d940b8..7b8bff3f6 100644
--- a/target_explorer/plugins/org.eclipse.tcf.te.ui.terminals.process/src/org/eclipse/tcf/te/ui/terminals/process/ProcessConnector.java
+++ b/target_explorer/plugins/org.eclipse.tcf.te.ui.terminals.process/src/org/eclipse/tcf/te/ui/terminals/process/ProcessConnector.java
@@ -1,278 +1,278 @@
/*******************************************************************************
* Copyright (c) 2011, 2014 Wind River Systems, Inc. and others. All rights reserved.
* This program and the accompanying materials are made available under the terms
* of the Eclipse Public License v1.0 which accompanies this distribution, and is
* available at http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Wind River Systems - initial API and implementation
*******************************************************************************/
package org.eclipse.tcf.te.ui.terminals.process;
import java.io.File;
import java.io.IOException;
import java.io.StreamTokenizer;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.cdt.utils.pty.PTY;
import org.eclipse.cdt.utils.spawner.ProcessFactory;
import org.eclipse.core.runtime.Assert;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.osgi.util.NLS;
import org.eclipse.swt.custom.CTabItem;
import org.eclipse.tcf.te.runtime.services.interfaces.constants.ILineSeparatorConstants;
import org.eclipse.tcf.te.runtime.statushandler.StatusHandlerUtil;
import org.eclipse.tcf.te.runtime.utils.Env;
import org.eclipse.tcf.te.ui.terminals.manager.ConsoleManager;
import org.eclipse.tcf.te.ui.terminals.process.activator.UIPlugin;
import org.eclipse.tcf.te.ui.terminals.process.help.IContextHelpIds;
import org.eclipse.tcf.te.ui.terminals.process.nls.Messages;
import org.eclipse.tcf.te.ui.terminals.streams.AbstractStreamsConnector;
import org.eclipse.tm.internal.terminal.provisional.api.ISettingsPage;
import org.eclipse.tm.internal.terminal.provisional.api.ISettingsStore;
import org.eclipse.tm.internal.terminal.provisional.api.ITerminalControl;
import org.eclipse.tm.internal.terminal.provisional.api.TerminalState;
/**
* Process connector implementation.
*/
@SuppressWarnings("restriction")
public class ProcessConnector extends AbstractStreamsConnector {
// Reference to the process settings
private final ProcessSettings settings;
// Reference to the PTY instance.
private PTY pty;
// Reference to the launched process instance.
private Process process;
// Reference to the process monitor
private ProcessMonitor monitor;
// The terminal width and height. Initially unknown.
private int width = -1;
private int height = -1;
/**
* Constructor.
*/
public ProcessConnector() {
this(new ProcessSettings());
}
/**
* Constructor.
*
* @param settings The process settings. Must not be <code>null</code>
*/
public ProcessConnector(ProcessSettings settings) {
super();
Assert.isNotNull(settings);
this.settings = settings;
}
/**
* Returns the process object or <code>null</code> if the
* connector is connector.
*
* @return The process object or <code>null</code>.
*/
public Process getProcess() {
return process;
}
/* (non-Javadoc)
* @see org.eclipse.tcf.internal.terminal.provisional.api.provider.TerminalConnectorImpl#connect(org.eclipse.tcf.internal.terminal.provisional.api.ITerminalControl)
*/
@Override
public void connect(ITerminalControl control) {
Assert.isNotNull(control);
super.connect(control);
pty = null;
width = -1;
height = -1;
try {
// Try to determine process and PTY instance from the process settings
process = settings.getProcess();
pty = settings.getPTY();
// No process -> create PTY on supported platforms and execute
// process image.
if (process == null) {
if (PTY.isSupported(PTY.Mode.TERMINAL)) {
try {
pty = new PTY(PTY.Mode.TERMINAL);
} catch (IOException e) {
// PTY not supported
}
}
// Build up the command
StringBuilder command = new StringBuilder(settings.getImage());
String arguments = settings.getArguments();
if (arguments != null && !"".equals(arguments.trim())) { //$NON-NLS-1$
// Append to the command now
command.append(" "); //$NON-NLS-1$
command.append(arguments.trim());
}
File workingDir =null;
if (settings.getWorkingDir()!=null){
workingDir = new File(settings.getWorkingDir());
}
String[] envp = null;
if (settings.getEnvironment()!=null){
envp = settings.getEnvironment();
}
if (pty != null) {
// A PTY is available -> can use the ProcessFactory.
// Tokenize the command (ProcessFactory takes an array)
StreamTokenizer st = new StreamTokenizer(new StringReader(command.toString()));
st.resetSyntax();
st.whitespaceChars(0, 32);
st.whitespaceChars(0xa0, 0xa0);
st.wordChars(33, 255);
st.quoteChar('"');
st.quoteChar('\'');
List<String> argv = new ArrayList<String>();
int ttype = st.nextToken();
while (ttype != StreamTokenizer.TT_EOF) {
argv.add(st.sval);
ttype = st.nextToken();
}
// Execute the process
process = ProcessFactory.getFactory().exec(argv.toArray(new String[argv.size()]), Env.getEnvironment(envp, true), workingDir, pty);
} else {
// No PTY -> just execute via the standard Java Runtime implementation.
- process = Runtime.getRuntime().exec(command.toString(), Env.getEnvironment(envp, false), workingDir);
+ process = Runtime.getRuntime().exec(command.toString(), Env.getEnvironment(envp, true), workingDir);
}
}
String lineSeparator = settings.getLineSeparator();
if (lineSeparator == null) {
lineSeparator = System.getProperty("line.separator"); //$NON-NLS-1$
if ("\r".equals(lineSeparator)) { //$NON-NLS-1$
lineSeparator = ILineSeparatorConstants.LINE_SEPARATOR_CR;
}
else if ("\n".equals(lineSeparator)) { //$NON-NLS-1$
lineSeparator = ILineSeparatorConstants.LINE_SEPARATOR_LF;
}
else {
lineSeparator = ILineSeparatorConstants.LINE_SEPARATOR_CRLF;
}
}
// Setup the listeners
setStdoutListeners(settings.getStdOutListeners());
setStderrListeners(settings.getStdErrListeners());
// connect the streams
connectStreams(control, process.getOutputStream(), process.getInputStream(), (pty == null ? process.getErrorStream() : null), settings.isLocalEcho(), lineSeparator);
// Set the terminal control state to CONNECTED
control.setState(TerminalState.CONNECTED);
// Create the process monitor
monitor = new ProcessMonitor(this);
monitor.startMonitoring();
} catch (IOException e) {
// Disconnect right away
disconnect();
// Lookup the tab item
CTabItem item = ConsoleManager.getInstance().findConsole(control);
if (item != null) item.dispose();
// Get the error message from the exception
String msg = e.getLocalizedMessage() != null ? e.getLocalizedMessage() : ""; //$NON-NLS-1$
Assert.isNotNull(msg);
// Strip away "Exec_tty error:"
msg = msg.replace("Exec_tty error:", "").trim(); //$NON-NLS-1$ //$NON-NLS-2$
// Repackage into a more user friendly error
msg = NLS.bind(Messages.ProcessConnector_error_creatingProcess, settings.getImage(), msg);
// Create the status object
IStatus status = new Status(IStatus.ERROR, UIPlugin.getUniqueIdentifier(), msg, e);
StatusHandlerUtil.handleStatus(status, this, msg, Messages.ProcessConnector_error_title, IContextHelpIds.MESSAGE_CREATE_PROCESS_FAILED, this, null);
}
}
/* (non-Javadoc)
* @see org.eclipse.tcf.internal.terminal.provisional.api.provider.TerminalConnectorImpl#isLocalEcho()
*/
@Override
public boolean isLocalEcho() {
return settings.isLocalEcho();
}
/* (non-Javadoc)
* @see org.eclipse.tcf.internal.terminal.provisional.api.provider.TerminalConnectorImpl#doDisconnect()
*/
@Override
public void doDisconnect() {
// Dispose the process
if (process != null) { process.destroy(); process = null; }
// Dispose the streams
super.doDisconnect();
// Set the terminal control state to CLOSED.
fControl.setState(TerminalState.CLOSED);
}
// ***** Process Connector settings handling *****
/* (non-Javadoc)
* @see org.eclipse.tcf.internal.terminal.provisional.api.provider.TerminalConnectorImpl#makeSettingsPage()
*/
@Override
public ISettingsPage makeSettingsPage() {
return new ProcessSettingsPage(settings);
}
/* (non-Javadoc)
* @see org.eclipse.tcf.internal.terminal.provisional.api.provider.TerminalConnectorImpl#getSettingsSummary()
*/
@Override
public String getSettingsSummary() {
return settings.getImage() != null ? settings.getImage() : ""; //$NON-NLS-1$
}
/* (non-Javadoc)
* @see org.eclipse.tcf.internal.terminal.provisional.api.provider.TerminalConnectorImpl#load(org.eclipse.tcf.internal.terminal.provisional.api.ISettingsStore)
*/
@Override
public void load(ISettingsStore store) {
settings.load(store);
}
/* (non-Javadoc)
* @see org.eclipse.tcf.internal.terminal.provisional.api.provider.TerminalConnectorImpl#save(org.eclipse.tcf.internal.terminal.provisional.api.ISettingsStore)
*/
@Override
public void save(ISettingsStore store) {
settings.save(store);
}
/* (non-Javadoc)
* @see org.eclipse.tcf.internal.terminal.provisional.api.provider.TerminalConnectorImpl#setTerminalSize(int, int)
*/
@Override
public void setTerminalSize(int newWidth, int newHeight) {
if (width != newWidth || height != newHeight) {
width = newWidth;
height = newHeight;
if (pty != null) {
pty.setTerminalSize(newWidth, newHeight);
}
}
}
}
| true | true | public void connect(ITerminalControl control) {
Assert.isNotNull(control);
super.connect(control);
pty = null;
width = -1;
height = -1;
try {
// Try to determine process and PTY instance from the process settings
process = settings.getProcess();
pty = settings.getPTY();
// No process -> create PTY on supported platforms and execute
// process image.
if (process == null) {
if (PTY.isSupported(PTY.Mode.TERMINAL)) {
try {
pty = new PTY(PTY.Mode.TERMINAL);
} catch (IOException e) {
// PTY not supported
}
}
// Build up the command
StringBuilder command = new StringBuilder(settings.getImage());
String arguments = settings.getArguments();
if (arguments != null && !"".equals(arguments.trim())) { //$NON-NLS-1$
// Append to the command now
command.append(" "); //$NON-NLS-1$
command.append(arguments.trim());
}
File workingDir =null;
if (settings.getWorkingDir()!=null){
workingDir = new File(settings.getWorkingDir());
}
String[] envp = null;
if (settings.getEnvironment()!=null){
envp = settings.getEnvironment();
}
if (pty != null) {
// A PTY is available -> can use the ProcessFactory.
// Tokenize the command (ProcessFactory takes an array)
StreamTokenizer st = new StreamTokenizer(new StringReader(command.toString()));
st.resetSyntax();
st.whitespaceChars(0, 32);
st.whitespaceChars(0xa0, 0xa0);
st.wordChars(33, 255);
st.quoteChar('"');
st.quoteChar('\'');
List<String> argv = new ArrayList<String>();
int ttype = st.nextToken();
while (ttype != StreamTokenizer.TT_EOF) {
argv.add(st.sval);
ttype = st.nextToken();
}
// Execute the process
process = ProcessFactory.getFactory().exec(argv.toArray(new String[argv.size()]), Env.getEnvironment(envp, true), workingDir, pty);
} else {
// No PTY -> just execute via the standard Java Runtime implementation.
process = Runtime.getRuntime().exec(command.toString(), Env.getEnvironment(envp, false), workingDir);
}
}
String lineSeparator = settings.getLineSeparator();
if (lineSeparator == null) {
lineSeparator = System.getProperty("line.separator"); //$NON-NLS-1$
if ("\r".equals(lineSeparator)) { //$NON-NLS-1$
lineSeparator = ILineSeparatorConstants.LINE_SEPARATOR_CR;
}
else if ("\n".equals(lineSeparator)) { //$NON-NLS-1$
lineSeparator = ILineSeparatorConstants.LINE_SEPARATOR_LF;
}
else {
lineSeparator = ILineSeparatorConstants.LINE_SEPARATOR_CRLF;
}
}
// Setup the listeners
setStdoutListeners(settings.getStdOutListeners());
setStderrListeners(settings.getStdErrListeners());
// connect the streams
connectStreams(control, process.getOutputStream(), process.getInputStream(), (pty == null ? process.getErrorStream() : null), settings.isLocalEcho(), lineSeparator);
// Set the terminal control state to CONNECTED
control.setState(TerminalState.CONNECTED);
// Create the process monitor
monitor = new ProcessMonitor(this);
monitor.startMonitoring();
} catch (IOException e) {
// Disconnect right away
disconnect();
// Lookup the tab item
CTabItem item = ConsoleManager.getInstance().findConsole(control);
if (item != null) item.dispose();
// Get the error message from the exception
String msg = e.getLocalizedMessage() != null ? e.getLocalizedMessage() : ""; //$NON-NLS-1$
Assert.isNotNull(msg);
// Strip away "Exec_tty error:"
msg = msg.replace("Exec_tty error:", "").trim(); //$NON-NLS-1$ //$NON-NLS-2$
// Repackage into a more user friendly error
msg = NLS.bind(Messages.ProcessConnector_error_creatingProcess, settings.getImage(), msg);
// Create the status object
IStatus status = new Status(IStatus.ERROR, UIPlugin.getUniqueIdentifier(), msg, e);
StatusHandlerUtil.handleStatus(status, this, msg, Messages.ProcessConnector_error_title, IContextHelpIds.MESSAGE_CREATE_PROCESS_FAILED, this, null);
}
}
| public void connect(ITerminalControl control) {
Assert.isNotNull(control);
super.connect(control);
pty = null;
width = -1;
height = -1;
try {
// Try to determine process and PTY instance from the process settings
process = settings.getProcess();
pty = settings.getPTY();
// No process -> create PTY on supported platforms and execute
// process image.
if (process == null) {
if (PTY.isSupported(PTY.Mode.TERMINAL)) {
try {
pty = new PTY(PTY.Mode.TERMINAL);
} catch (IOException e) {
// PTY not supported
}
}
// Build up the command
StringBuilder command = new StringBuilder(settings.getImage());
String arguments = settings.getArguments();
if (arguments != null && !"".equals(arguments.trim())) { //$NON-NLS-1$
// Append to the command now
command.append(" "); //$NON-NLS-1$
command.append(arguments.trim());
}
File workingDir =null;
if (settings.getWorkingDir()!=null){
workingDir = new File(settings.getWorkingDir());
}
String[] envp = null;
if (settings.getEnvironment()!=null){
envp = settings.getEnvironment();
}
if (pty != null) {
// A PTY is available -> can use the ProcessFactory.
// Tokenize the command (ProcessFactory takes an array)
StreamTokenizer st = new StreamTokenizer(new StringReader(command.toString()));
st.resetSyntax();
st.whitespaceChars(0, 32);
st.whitespaceChars(0xa0, 0xa0);
st.wordChars(33, 255);
st.quoteChar('"');
st.quoteChar('\'');
List<String> argv = new ArrayList<String>();
int ttype = st.nextToken();
while (ttype != StreamTokenizer.TT_EOF) {
argv.add(st.sval);
ttype = st.nextToken();
}
// Execute the process
process = ProcessFactory.getFactory().exec(argv.toArray(new String[argv.size()]), Env.getEnvironment(envp, true), workingDir, pty);
} else {
// No PTY -> just execute via the standard Java Runtime implementation.
process = Runtime.getRuntime().exec(command.toString(), Env.getEnvironment(envp, true), workingDir);
}
}
String lineSeparator = settings.getLineSeparator();
if (lineSeparator == null) {
lineSeparator = System.getProperty("line.separator"); //$NON-NLS-1$
if ("\r".equals(lineSeparator)) { //$NON-NLS-1$
lineSeparator = ILineSeparatorConstants.LINE_SEPARATOR_CR;
}
else if ("\n".equals(lineSeparator)) { //$NON-NLS-1$
lineSeparator = ILineSeparatorConstants.LINE_SEPARATOR_LF;
}
else {
lineSeparator = ILineSeparatorConstants.LINE_SEPARATOR_CRLF;
}
}
// Setup the listeners
setStdoutListeners(settings.getStdOutListeners());
setStderrListeners(settings.getStdErrListeners());
// connect the streams
connectStreams(control, process.getOutputStream(), process.getInputStream(), (pty == null ? process.getErrorStream() : null), settings.isLocalEcho(), lineSeparator);
// Set the terminal control state to CONNECTED
control.setState(TerminalState.CONNECTED);
// Create the process monitor
monitor = new ProcessMonitor(this);
monitor.startMonitoring();
} catch (IOException e) {
// Disconnect right away
disconnect();
// Lookup the tab item
CTabItem item = ConsoleManager.getInstance().findConsole(control);
if (item != null) item.dispose();
// Get the error message from the exception
String msg = e.getLocalizedMessage() != null ? e.getLocalizedMessage() : ""; //$NON-NLS-1$
Assert.isNotNull(msg);
// Strip away "Exec_tty error:"
msg = msg.replace("Exec_tty error:", "").trim(); //$NON-NLS-1$ //$NON-NLS-2$
// Repackage into a more user friendly error
msg = NLS.bind(Messages.ProcessConnector_error_creatingProcess, settings.getImage(), msg);
// Create the status object
IStatus status = new Status(IStatus.ERROR, UIPlugin.getUniqueIdentifier(), msg, e);
StatusHandlerUtil.handleStatus(status, this, msg, Messages.ProcessConnector_error_title, IContextHelpIds.MESSAGE_CREATE_PROCESS_FAILED, this, null);
}
}
|
diff --git a/org.eclipse.scout.rt.ui.rap/src/org/eclipse/scout/rt/ui/rap/ext/browser/BrowserExtension.java b/org.eclipse.scout.rt.ui.rap/src/org/eclipse/scout/rt/ui/rap/ext/browser/BrowserExtension.java
index 5661808fcd..feabf9c7c7 100644
--- a/org.eclipse.scout.rt.ui.rap/src/org/eclipse/scout/rt/ui/rap/ext/browser/BrowserExtension.java
+++ b/org.eclipse.scout.rt.ui.rap/src/org/eclipse/scout/rt/ui/rap/ext/browser/BrowserExtension.java
@@ -1,254 +1,256 @@
/*******************************************************************************
* Copyright (c) 2011 BSI Business Systems Integration AG.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* BSI Business Systems Integration AG - initial API and implementation
*******************************************************************************/
package org.eclipse.scout.rt.ui.rap.ext.browser;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Constructor;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.ServletException;
import org.eclipse.rwt.RWT;
import org.eclipse.rwt.lifecycle.UICallBack;
import org.eclipse.rwt.resources.IResourceManager;
import org.eclipse.rwt.resources.IResourceManager.RegisterOptions;
import org.eclipse.rwt.service.IServiceHandler;
import org.eclipse.scout.commons.logger.IScoutLogger;
import org.eclipse.scout.commons.logger.ScoutLogManager;
import org.eclipse.swt.browser.Browser;
import org.eclipse.swt.browser.LocationEvent;
/**
* <h3>BrowserSupport</h3> adding hyperlink callback support as in normal swt to the rwt browser
* <p>
* Adding support for registering/unregistering (publishing) local resources.
*
* @author imo
* @since 3.8.0
*/
public class BrowserExtension {
private static final IScoutLogger LOG = ScoutLogManager.getLogger(BrowserExtension.class);
private static final Pattern LOCAL_URL_PATTERN = Pattern.compile("(['\"])(http://local[?/][^'\"]*)(['\"])", Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
private final Browser m_browser;
private final HashMap<String, String> m_hyperlinkMap;
private final String m_serviceHandlerId;
private IServiceHandler m_serviceHandler;
//
private HashSet<String> m_tempFileNames = new HashSet<String>();
public BrowserExtension(Browser b) {
m_browser = b;
m_hyperlinkMap = new HashMap<String, String>();
m_serviceHandlerId = UUID.randomUUID().toString();
}
/**
* @return the unique {@link UUID} serviceHandlerId
*/
public String getServiceHandlerId() {
return m_serviceHandlerId;
}
private String getUiCallbackId() {
return getClass().getName() + "" + hashCode();
}
public void attach() {
if (m_serviceHandler == null) {
UICallBack.activate(getUiCallbackId());
m_serviceHandler = new IServiceHandler() {
@Override
public void service() throws IOException, ServletException {
String localUrl = m_hyperlinkMap.get(RWT.getRequest().getParameter("p"));
if (localUrl == null) {
return;
}
fireLocationChangedEvent(localUrl);
}
};
RWT.getServiceManager().registerServiceHandler(m_serviceHandlerId, m_serviceHandler);
}
}
public void detach() {
UICallBack.deactivate(getUiCallbackId());
clearLocalHyperlinkCache();
clearResourceCache();
if (m_serviceHandler != null) {
m_serviceHandler = null;
RWT.getServiceManager().unregisterServiceHandler(m_serviceHandlerId);
}
}
/**
* @return the web url of the resource valid for calls from outside
*/
public String addResource(String name, InputStream content) {
return addResource(name, content, null, null);
}
/**
* Adds a text resource that is encoded with the given <code>charset</code>.
* <p>
* By specifying an <code>option</code> other than <code>NONE</code> the resource will be versioned and/or compressed.
* As compressing is only intended for resources that contain JavaScript, versioning might be useful for other
* resources as well. When versioning is enabled a version number is appended to the resources' name which is derived
* from its content.
* </p>
* <p>
*
* @param content
* the content of the resource to add.
* @param charset
* the name of the charset which was used when the resource
* was stored. If set to <code>null</code> neither charset nor options will be set.
* @param options
* an enumeration which specifies whether the resource will
* be versioned and/or compressed. If set to <code>null</code> neither charset nor options will be set.
* @return the web url of the resource valid for calls from outside
*/
public String addResource(String name, InputStream content, String charset, RegisterOptions options) {
name = name.replaceAll("\\\\", "/");
if (name == null || name.length() == 0) {
return null;
}
if (!name.startsWith("/")) {
name = "/" + name;
}
String uniqueName = m_serviceHandlerId + name;
m_tempFileNames.add(uniqueName);
IResourceManager resourceManager = RWT.getResourceManager();
if (charset != null && options != null) {
resourceManager.register(uniqueName, content, charset, options);
}
else {
resourceManager.register(uniqueName, content);
}
return resourceManager.getLocation(uniqueName);
}
public void clearResourceCache() {
IResourceManager resourceManager = RWT.getResourceManager();
try {
for (String name : m_tempFileNames) {
resourceManager.unregister(name);
}
}
finally {
m_tempFileNames.clear();
}
}
/**
* @param html
* replaces all http://local/... urls by a ajax callback with a {@link LocationEvent} in html text
* @param childDepth
* when the document is inside a iframe or thelike, then childDepth is 1, if it is in addition inside an
* embed tag (such as svg), then childDepth is 2.
*/
public String adaptLocalHyperlinks(String html, int childDepth) {
String p;
if (childDepth <= 0) {
p = "this";
}
else {
p = "parent";
for (int i = 1; i < childDepth; i++) {
p = "parent." + p;
}
}
return rewriteLocalHyperlinks(html, p, m_serviceHandlerId, m_hyperlinkMap);
}
public void clearLocalHyperlinkCache() {
m_hyperlinkMap.clear();
}
private void fireLocationChangedEvent(final String location) {
m_browser.getDisplay().asyncExec(new Runnable() {
@Override
public void run() {
try {
Constructor<?> c = LocationEvent.class.getDeclaredConstructor(Object.class, int.class, String.class);
c.setAccessible(true);
//send changing
LocationEvent event = (LocationEvent) c.newInstance(m_browser, LocationEvent.CHANGING, location);
event.top = true;
event.processEvent();
//send changed
event = (LocationEvent) c.newInstance(m_browser, LocationEvent.CHANGED, location);
event.top = true;
event.processEvent();
}
catch (Throwable t) {
//nop
}
}
});
}
/**
* Replace all href="http://local/... references in the html file and replace by an ajax call.
*
* @param html
* @param rwtServiceHandler
* is called with the parameter "p" containing the local url key to the generatedMapping
* @param generatedMappings
* is being filled up with the generated mappings
* @return the rewritten html
*/
private static String rewriteLocalHyperlinks(String html, String ajaxParentContext, String rwtServiceHandler, Map<String /*externalKey*/, String /*url*/> generatedMappings) {
if (html == null) {
return html;
}
StringBuilder buf = new StringBuilder();
Matcher m = LOCAL_URL_PATTERN.matcher(html);
int nextFind = 0;
while (m.find(nextFind)) {
String localUrl = m.group(2);
String externalKey = "" + generatedMappings.size();
StringBuilder urlBuf = new StringBuilder();
urlBuf.append("?");
+ urlBuf.append("nocache='+new Date().getTime()+'");
+ urlBuf.append("&");
urlBuf.append(IServiceHandler.REQUEST_PARAM);
urlBuf.append("=");
urlBuf.append(rwtServiceHandler);
urlBuf.append("&");
urlBuf.append("p");
urlBuf.append("=");
urlBuf.append(externalKey);
String encodedURL = RWT.getResponse().encodeURL(urlBuf.toString());
String callableURL = "javascript:a=" + ajaxParentContext + ".qx.net.HttpRequest.create();a.open('GET','" + encodedURL + "',true);a.send(null);";
buf.append(html.substring(nextFind, m.start()));
buf.append(m.group(1));
buf.append(callableURL);
buf.append(m.group(3));
//register
generatedMappings.put(externalKey, localUrl);
//next
nextFind = m.end();
}
if (nextFind == 0) {
return html;
}
if (nextFind < html.length()) {
buf.append(html.substring(nextFind));
}
return buf.toString();
}
}
| true | true | private static String rewriteLocalHyperlinks(String html, String ajaxParentContext, String rwtServiceHandler, Map<String /*externalKey*/, String /*url*/> generatedMappings) {
if (html == null) {
return html;
}
StringBuilder buf = new StringBuilder();
Matcher m = LOCAL_URL_PATTERN.matcher(html);
int nextFind = 0;
while (m.find(nextFind)) {
String localUrl = m.group(2);
String externalKey = "" + generatedMappings.size();
StringBuilder urlBuf = new StringBuilder();
urlBuf.append("?");
urlBuf.append(IServiceHandler.REQUEST_PARAM);
urlBuf.append("=");
urlBuf.append(rwtServiceHandler);
urlBuf.append("&");
urlBuf.append("p");
urlBuf.append("=");
urlBuf.append(externalKey);
String encodedURL = RWT.getResponse().encodeURL(urlBuf.toString());
String callableURL = "javascript:a=" + ajaxParentContext + ".qx.net.HttpRequest.create();a.open('GET','" + encodedURL + "',true);a.send(null);";
buf.append(html.substring(nextFind, m.start()));
buf.append(m.group(1));
buf.append(callableURL);
buf.append(m.group(3));
//register
generatedMappings.put(externalKey, localUrl);
//next
nextFind = m.end();
}
if (nextFind == 0) {
return html;
}
if (nextFind < html.length()) {
buf.append(html.substring(nextFind));
}
return buf.toString();
}
| private static String rewriteLocalHyperlinks(String html, String ajaxParentContext, String rwtServiceHandler, Map<String /*externalKey*/, String /*url*/> generatedMappings) {
if (html == null) {
return html;
}
StringBuilder buf = new StringBuilder();
Matcher m = LOCAL_URL_PATTERN.matcher(html);
int nextFind = 0;
while (m.find(nextFind)) {
String localUrl = m.group(2);
String externalKey = "" + generatedMappings.size();
StringBuilder urlBuf = new StringBuilder();
urlBuf.append("?");
urlBuf.append("nocache='+new Date().getTime()+'");
urlBuf.append("&");
urlBuf.append(IServiceHandler.REQUEST_PARAM);
urlBuf.append("=");
urlBuf.append(rwtServiceHandler);
urlBuf.append("&");
urlBuf.append("p");
urlBuf.append("=");
urlBuf.append(externalKey);
String encodedURL = RWT.getResponse().encodeURL(urlBuf.toString());
String callableURL = "javascript:a=" + ajaxParentContext + ".qx.net.HttpRequest.create();a.open('GET','" + encodedURL + "',true);a.send(null);";
buf.append(html.substring(nextFind, m.start()));
buf.append(m.group(1));
buf.append(callableURL);
buf.append(m.group(3));
//register
generatedMappings.put(externalKey, localUrl);
//next
nextFind = m.end();
}
if (nextFind == 0) {
return html;
}
if (nextFind < html.length()) {
buf.append(html.substring(nextFind));
}
return buf.toString();
}
|
diff --git a/nuxeo-platform-categorization-service/src/main/java/org/nuxeo/ecm/platform/categorization/categorizer/tfidf/TfIdfCategorizerFactory.java b/nuxeo-platform-categorization-service/src/main/java/org/nuxeo/ecm/platform/categorization/categorizer/tfidf/TfIdfCategorizerFactory.java
index 5ef0d9a..845a2cb 100644
--- a/nuxeo-platform-categorization-service/src/main/java/org/nuxeo/ecm/platform/categorization/categorizer/tfidf/TfIdfCategorizerFactory.java
+++ b/nuxeo-platform-categorization-service/src/main/java/org/nuxeo/ecm/platform/categorization/categorizer/tfidf/TfIdfCategorizerFactory.java
@@ -1,23 +1,23 @@
package org.nuxeo.ecm.platform.categorization.categorizer.tfidf;
import java.io.IOException;
import org.nuxeo.ecm.platform.categorization.service.Categorizer;
import org.nuxeo.ecm.platform.categorization.service.CategorizerFactory;
public class TfIdfCategorizerFactory implements CategorizerFactory {
public Categorizer loadInstance(String modelFile, boolean readonly)
throws IOException {
try {
TfIdfCategorizer categorizer = TfIdfCategorizer.load(modelFile);
if (readonly) {
categorizer.disableUpdate();
}
return categorizer;
} catch (ClassNotFoundException e) {
- throw new IOException(e);
+ throw new IOException(e.getMessage());
}
}
}
| true | true | public Categorizer loadInstance(String modelFile, boolean readonly)
throws IOException {
try {
TfIdfCategorizer categorizer = TfIdfCategorizer.load(modelFile);
if (readonly) {
categorizer.disableUpdate();
}
return categorizer;
} catch (ClassNotFoundException e) {
throw new IOException(e);
}
}
| public Categorizer loadInstance(String modelFile, boolean readonly)
throws IOException {
try {
TfIdfCategorizer categorizer = TfIdfCategorizer.load(modelFile);
if (readonly) {
categorizer.disableUpdate();
}
return categorizer;
} catch (ClassNotFoundException e) {
throw new IOException(e.getMessage());
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.