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/BetterBatteryStats/src/com/asksven/betterbatterystats/data/StatsProvider.java b/BetterBatteryStats/src/com/asksven/betterbatterystats/data/StatsProvider.java
index b6600583..b0a22fd9 100644
--- a/BetterBatteryStats/src/com/asksven/betterbatterystats/data/StatsProvider.java
+++ b/BetterBatteryStats/src/com/asksven/betterbatterystats/data/StatsProvider.java
@@ -1,1404 +1,1404 @@
/*
* Copyright (C) 2011-2012 asksven
*
* 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.asksven.betterbatterystats.data;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.StringTokenizer;
import android.app.ActivityManager;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.SystemClock;
import android.preference.PreferenceManager;
import android.util.Log;
import android.widget.Toast;
import com.asksven.android.common.kernelutils.Alarm;
import com.asksven.android.common.kernelutils.AlarmsDumpsys;
import com.asksven.android.common.kernelutils.NativeKernelWakelock;
import com.asksven.android.common.kernelutils.RootDetection;
import com.asksven.android.common.kernelutils.Wakelocks;
import com.asksven.android.common.privateapiproxies.BatteryStatsProxy;
import com.asksven.android.common.privateapiproxies.BatteryStatsTypes;
import com.asksven.android.common.privateapiproxies.Misc;
import com.asksven.android.common.privateapiproxies.NetworkUsage;
import com.asksven.android.common.privateapiproxies.Process;
import com.asksven.android.common.privateapiproxies.StatElement;
import com.asksven.android.common.privateapiproxies.Wakelock;
import com.asksven.android.common.utils.DataStorage;
import com.asksven.android.common.utils.DateUtils;
/**
* Singleton provider for all the statistics
* @author sven
*
*/
public class StatsProvider
{
/** the singleton instance */
static StatsProvider m_statsProvider = null;
/** the application context */
static Context m_context = null;
/** constant for custom stats */
// dependent on arrays.xml
public final static int STATS_CHARGED = 0;
public final static int STATS_UNPLUGGED = 3;
public final static int STATS_CUSTOM = 4;
/** the logger tag */
static String TAG = "StatsProvider";
/** the text when no custom reference is set */
static String NO_CUST_REF = "No custom reference was set";
/** the storage for references */
static References m_myRefs = null;
static References m_myRefSinceUnplugged = null;
static References m_myRefSinceCharged = null;
/**
* The constructor (hidden)
*/
private StatsProvider()
{
}
/**
* returns a singleton instance
* @param ctx the application context
* @return the singleton StatsProvider
*/
public static StatsProvider getInstance(Context ctx)
{
if (m_statsProvider == null)
{
m_statsProvider = new StatsProvider();
m_context = ctx;
m_myRefs = new References();
}
return m_statsProvider;
}
/**
* Get the Stat to be displayed
* @return a List of StatElements sorted (descending)
*/
public ArrayList<StatElement> getStatList(int iStat, int iStatType, int iSort)
{
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(m_context);
boolean bFilterStats = sharedPrefs.getBoolean("filter_data", true);
int iPctType = Integer.valueOf(sharedPrefs.getString("default_wl_ref", "0"));
try
{
switch (iStat)
{
// constants are related to arrays.xml string-array name="stats"
case 0:
return getProcessStatList(bFilterStats, iStatType, iSort);
case 1:
return getWakelockStatList(bFilterStats, iStatType, iPctType, iSort);
case 2:
return getOtherUsageStatList(bFilterStats, iStatType);
case 3:
return getNativeKernelWakelockStatList(bFilterStats, iStatType, iPctType, iSort);
case 4:
return getAlarmsStatList(bFilterStats, iStatType);
}
}
catch (Exception e)
{
Log.e(TAG, "Exception: " + e.getMessage());
}
return new ArrayList<StatElement>();
}
/**
* Get the Alarm Stat to be displayed
* @param bFilter defines if zero-values should be filtered out
* @return a List of Other usages sorted by duration (descending)
* @throws Exception if the API call failed
*/
public ArrayList<StatElement> getAlarmsStatList(boolean bFilter, int iStatType) throws Exception
{
ArrayList<StatElement> myStats = new ArrayList<StatElement>();
ArrayList<Alarm> myAlarms = AlarmsDumpsys.getAlarms();
Collections.sort(myAlarms);
ArrayList<Alarm> myRetAlarms = new ArrayList<Alarm>();
// if we are using custom ref. always retrieve "stats current"
// sort @see com.asksven.android.common.privateapiproxies.Walkelock.compareTo
String strCurrent = myAlarms.toString();
String strRef = "";
switch (iStatType)
{
case STATS_UNPLUGGED:
if ( (m_myRefSinceUnplugged != null) && (m_myRefSinceUnplugged.m_refAlarms != null) )
{
strRef = m_myRefSinceUnplugged.m_refAlarms.toString();
}
break;
case STATS_CHARGED:
if ( (m_myRefSinceCharged != null) && (m_myRefSinceCharged.m_refAlarms != null) )
{
strRef = m_myRefSinceCharged.m_refAlarms.toString();
}
break;
case STATS_CUSTOM:
if ( (m_myRefs != null) && (m_myRefs.m_refAlarms != null))
{
strRef = m_myRefs.m_refAlarms.toString();
}
break;
case BatteryStatsTypes.STATS_CURRENT:
strRef = "no reference to substract";
break;
default:
Log.e(TAG, "Unknown StatType " + iStatType + ". No reference found");
break;
}
Log.i(TAG, "Substracting " + strRef + " from " + strCurrent);
for (int i = 0; i < myAlarms.size(); i++)
{
Alarm alarm = myAlarms.get(i);
if ( (!bFilter) || ((alarm.getWakeups()) > 0) )
{
// native kernel wakelocks are parsed from /proc/wakelocks
// and do not know any references "since charged" and "since unplugged"
// those are implemented using special references
switch (iStatType)
{
case STATS_CUSTOM:
// case a)
// we need t return a delta containing
// if a process is in the new list but not in the custom ref
// the full time is returned
// if a process is in the reference return the delta
// a process can not have disapeared in btwn so we don't need
// to test the reverse case
if (m_myRefs != null)
{
alarm.substractFromRef(m_myRefs.m_refAlarms);
// we must recheck if the delta process is still above threshold
if ( (!bFilter) || ((alarm.getWakeups()) > 0) )
{
myRetAlarms.add( alarm);
}
}
else
{
myRetAlarms.clear();
myRetAlarms.add(new Alarm(NO_CUST_REF));
}
break;
case STATS_UNPLUGGED:
if (m_myRefSinceUnplugged != null)
{
alarm.substractFromRef(m_myRefSinceUnplugged.m_refAlarms);
// we must recheck if the delta process is still above threshold
if ( (!bFilter) || ((alarm.getWakeups()) > 0) )
{
myRetAlarms.add( alarm);
}
}
else
{
myRetAlarms.clear();
myRetAlarms.add(new Alarm("No reference since unplugged set yet"));
}
break;
case STATS_CHARGED:
if (m_myRefSinceCharged != null)
{
alarm.substractFromRef(m_myRefSinceCharged.m_refAlarms);
// we must recheck if the delta process is still above threshold
if ( (!bFilter) || ((alarm.getWakeups()) > 0) )
{
myRetAlarms.add(alarm);
}
}
else
{
myRetAlarms.clear();
myRetAlarms.add(new Alarm("No reference since charged yet"));
}
break;
case BatteryStatsTypes.STATS_CURRENT:
// we must recheck if the delta process is still above threshold
myRetAlarms.add(alarm);
break;
}
}
}
for (int i=0; i < myRetAlarms.size(); i++)
{
myStats.add((StatElement) myRetAlarms.get(i));
}
Log.i(TAG, "Result " + myStats.toString());
return myStats;
}
/**
* Get the Process Stat to be displayed
* @param bFilter defines if zero-values should be filtered out
* @return a List of Wakelocks sorted by duration (descending)
* @throws Exception if the API call failed
*/
public ArrayList<StatElement> getProcessStatList(boolean bFilter, int iStatType, int iSort) throws Exception
{
BatteryStatsProxy mStats = BatteryStatsProxy.getInstance(m_context);
ArrayList<StatElement> myStats = new ArrayList<StatElement>();
ArrayList<Process> myProcesses = null;
ArrayList<Process> myRetProcesses = new ArrayList<Process>();
// if we are using custom ref. always retrieve "stats current"
if (iStatType == STATS_CUSTOM)
{
myProcesses = mStats.getProcessStats(m_context, BatteryStatsTypes.STATS_CURRENT);
}
else
{
myProcesses = mStats.getProcessStats(m_context, iStatType);
}
// sort @see com.asksven.android.common.privateapiproxies.Walkelock.compareTo
//Collections.sort(myProcesses);
for (int i = 0; i < myProcesses.size(); i++)
{
Process ps = myProcesses.get(i);
if ( (!bFilter) || ((ps.getSystemTime() + ps.getUserTime()) > 0) )
{
// we must distinguish two situations
// a) we use custom stat type
// b) we use regular stat type
if (iStatType == STATS_CUSTOM)
{
// case a)
// we need t return a delta containing
// if a process is in the new list but not in the custom ref
// the full time is returned
// if a process is in the reference return the delta
// a process can not have disapeared in btwn so we don't need
// to test the reverse case
if (m_myRefs != null)
{
ps.substractFromRef(m_myRefs.m_refProcesses);
// we must recheck if the delta process is still above threshold
if ( (!bFilter) || ((ps.getSystemTime() + ps.getUserTime()) > 0) )
{
myRetProcesses.add(ps);
}
}
else
{
myRetProcesses.clear();
myRetProcesses.add(new Process(NO_CUST_REF, 1, 1, 1));
}
}
else
{
// case b) nothing special
myRetProcesses.add(ps);
}
}
}
// sort @see com.asksven.android.common.privateapiproxies.Walkelock.compareTo
switch (iSort)
{
case 0:
// by Duration
Comparator<Process> myCompTime = new Process.ProcessTimeComparator();
Collections.sort(myRetProcesses, myCompTime);
break;
case 1:
// by Count
Comparator<Process> myCompCount = new Process.ProcessCountComparator();
Collections.sort(myRetProcesses, myCompCount);
break;
}
for (int i=0; i < myRetProcesses.size(); i++)
{
myStats.add((StatElement) myRetProcesses.get(i));
}
return myStats;
}
/**
* Get the Wakelock Stat to be displayed
* @param bFilter defines if zero-values should be filtered out
* @return a List of Wakelocks sorted by duration (descending)
* @throws Exception if the API call failed
*/
public ArrayList<StatElement> getWakelockStatList(boolean bFilter, int iStatType, int iPctType, int iSort) throws Exception
{
ArrayList<StatElement> myStats = new ArrayList<StatElement>();
BatteryStatsProxy mStats = BatteryStatsProxy.getInstance(m_context);
ArrayList<Wakelock> myWakelocks = null;
ArrayList<Wakelock> myRetWakelocks = new ArrayList<Wakelock>();
// if we are using custom ref. always retrieve "stats current"
if (iStatType == STATS_CUSTOM)
{
myWakelocks = mStats.getWakelockStats(m_context, BatteryStatsTypes.WAKE_TYPE_PARTIAL, BatteryStatsTypes.STATS_CURRENT, iPctType);
}
else
{
myWakelocks = mStats.getWakelockStats(m_context, BatteryStatsTypes.WAKE_TYPE_PARTIAL, iStatType, iPctType);
}
// sort @see com.asksven.android.common.privateapiproxies.Walkelock.compareTo
Collections.sort(myWakelocks);
for (int i = 0; i < myWakelocks.size(); i++)
{
Wakelock wl = myWakelocks.get(i);
if ( (!bFilter) || ((wl.getDuration()/1000) > 0) )
{
// we must distinguish two situations
// a) we use custom stat type
// b) we use regular stat type
if (iStatType == STATS_CUSTOM)
{
// case a)
// we need t return a delta containing
// if a process is in the new list but not in the custom ref
// the full time is returned
// if a process is in the reference return the delta
// a process can not have disapeared in btwn so we don't need
// to test the reverse case
if (m_myRefs != null)
{
wl.substractFromRef(m_myRefs.m_refWakelocks);
// we must recheck if the delta process is still above threshold
if ( (!bFilter) || ((wl.getDuration()/1000) > 0) )
{
myRetWakelocks.add( wl);
}
}
else
{
myRetWakelocks.clear();
myRetWakelocks.add(new Wakelock(1, NO_CUST_REF, 1, 1, 1));
}
}
else
{
// case b) nothing special
myRetWakelocks.add(wl);
}
}
}
// sort @see com.asksven.android.common.privateapiproxies.Walkelock.compareTo
switch (iSort)
{
case 0:
// by Duration
Comparator<Wakelock> myCompTime = new Wakelock.WakelockTimeComparator();
Collections.sort(myRetWakelocks, myCompTime);
break;
case 1:
// by Count
Comparator<Wakelock> myCompCount = new Wakelock.WakelockCountComparator();
Collections.sort(myRetWakelocks, myCompCount);
break;
}
for (int i=0; i < myRetWakelocks.size(); i++)
{
myStats.add((StatElement) myRetWakelocks.get(i));
}
// @todo add sorting by settings here: Collections.sort......
return myStats;
}
/**
* Get the Kernel Wakelock Stat to be displayed
* @param bFilter defines if zero-values should be filtered out
* @return a List of Wakelocks sorted by duration (descending)
* @throws Exception if the API call failed
*/
public ArrayList<StatElement> getNativeKernelWakelockStatList(boolean bFilter, int iStatType, int iPctType, int iSort) throws Exception
{
ArrayList<StatElement> myStats = new ArrayList<StatElement>();
ArrayList<NativeKernelWakelock> myKernelWakelocks = Wakelocks.parseProcWakelocks();
ArrayList<NativeKernelWakelock> myRetKernelWakelocks = new ArrayList<NativeKernelWakelock>();
// if we are using custom ref. always retrieve "stats current"
// sort @see com.asksven.android.common.privateapiproxies.Walkelock.compareTo
Collections.sort(myKernelWakelocks);
String strCurrent = myKernelWakelocks.toString();
String strRef = "";
switch (iStatType)
{
case STATS_UNPLUGGED:
if ( (m_myRefSinceUnplugged != null) && (m_myRefSinceUnplugged.m_refKernelWakelocks != null) )
{
strRef = m_myRefSinceUnplugged.m_refKernelWakelocks.toString();
}
break;
case STATS_CHARGED:
if ( (m_myRefSinceCharged != null) && (m_myRefSinceCharged.m_refKernelWakelocks != null) )
{
strRef = m_myRefSinceCharged.m_refKernelWakelocks.toString();
}
break;
case STATS_CUSTOM:
if ( (m_myRefs != null) && (m_myRefs.m_refKernelWakelocks != null))
{
strRef = m_myRefs.m_refKernelWakelocks.toString();
}
break;
case BatteryStatsTypes.STATS_CURRENT:
strRef = "no reference to substract";
break;
default:
Log.e(TAG, "Unknown StatType " + iStatType + ". No reference found");
break;
}
Log.i(TAG, "Substracting " + strRef + " from " + strCurrent);
for (int i = 0; i < myKernelWakelocks.size(); i++)
{
NativeKernelWakelock wl = myKernelWakelocks.get(i);
if ( (!bFilter) || ((wl.getDuration()) > 0) )
{
// native kernel wakelocks are parsed from /proc/wakelocks
// and do not know any references "since charged" and "since unplugged"
// those are implemented using special references
switch (iStatType)
{
case STATS_CUSTOM:
// case a)
// we need t return a delta containing
// if a process is in the new list but not in the custom ref
// the full time is returned
// if a process is in the reference return the delta
// a process can not have disapeared in btwn so we don't need
// to test the reverse case
if (m_myRefs != null)
{
wl.substractFromRef(m_myRefs.m_refKernelWakelocks);
// we must recheck if the delta process is still above threshold
if ( (!bFilter) || ((wl.getDuration()) > 0) )
{
myRetKernelWakelocks.add( wl);
}
}
else
{
myRetKernelWakelocks.clear();
myRetKernelWakelocks.add(new NativeKernelWakelock(NO_CUST_REF, 1, 1, 1, 1, 1, 1, 1, 1, 1));
}
break;
case STATS_UNPLUGGED:
if (m_myRefSinceUnplugged != null)
{
wl.substractFromRef(m_myRefSinceUnplugged.m_refKernelWakelocks);
// we must recheck if the delta process is still above threshold
if ( (!bFilter) || ((wl.getDuration()) > 0) )
{
myRetKernelWakelocks.add( wl);
}
}
else
{
myRetKernelWakelocks.clear();
myRetKernelWakelocks.add(new NativeKernelWakelock("No reference since unplugged set yet", 1, 1, 1, 1, 1, 1, 1, 1, 1));
}
break;
case STATS_CHARGED:
if (m_myRefSinceCharged != null)
{
wl.substractFromRef(m_myRefSinceCharged.m_refKernelWakelocks);
// we must recheck if the delta process is still above threshold
if ( (!bFilter) || ((wl.getDuration()) > 0) )
{
myRetKernelWakelocks.add( wl);
}
}
else
{
myRetKernelWakelocks.clear();
myRetKernelWakelocks.add(new NativeKernelWakelock("No reference since charged yet", 1, 1, 1, 1, 1, 1, 1, 1, 1));
}
break;
case BatteryStatsTypes.STATS_CURRENT:
// we must recheck if the delta process is still above threshold
myRetKernelWakelocks.add( wl);
break;
}
}
}
// sort @see com.asksven.android.common.privateapiproxies.Walkelock.compareTo
switch (iSort)
{
case 0:
// by Duration
Comparator<NativeKernelWakelock> myCompTime = new NativeKernelWakelock.TimeComparator();
Collections.sort(myRetKernelWakelocks, myCompTime);
break;
case 1:
// by Count
Comparator<NativeKernelWakelock> myCompCount = new NativeKernelWakelock.CountComparator();
Collections.sort(myRetKernelWakelocks, myCompCount);
break;
}
for (int i=0; i < myRetKernelWakelocks.size(); i++)
{
myStats.add((StatElement) myRetKernelWakelocks.get(i));
}
Log.i(TAG, "Result " + myStats.toString());
return myStats;
}
/**
* Get the Network Usage Stat to be displayed
* @param bFilter defines if zero-values should be filtered out
* @return a List of Network usages sorted by duration (descending)
* @throws Exception if the API call failed
*/
public ArrayList<StatElement> getNetworkUsageStatList(boolean bFilter, int iStatType) throws Exception
{
ArrayList<StatElement> myStats = new ArrayList<StatElement>();
BatteryStatsProxy mStats = BatteryStatsProxy.getInstance(m_context);
ArrayList<NetworkUsage> myUsages = null;
// if we are using custom ref. always retrieve "stats current"
if (iStatType == STATS_CUSTOM)
{
myUsages = mStats.getNetworkUsageStats(m_context, BatteryStatsTypes.STATS_CURRENT);
}
else
{
myUsages = mStats.getNetworkUsageStats(m_context, iStatType);
}
// sort @see com.asksven.android.common.privateapiproxies.Walkelock.compareTo
Collections.sort(myUsages);
for (int i = 0; i < myUsages.size(); i++)
{
NetworkUsage usage = myUsages.get(i);
if ( (!bFilter) || ((usage.getBytesReceived() + usage.getBytesSent()) > 0) )
{
// we must distinguish two situations
// a) we use custom stat type
// b) we use regular stat type
if (iStatType == STATS_CUSTOM)
{
// case a)
// we need t return a delta containing
// if a process is in the new list but not in the custom ref
// the full time is returned
// if a process is in the reference return the delta
// a process can not have disapeared in btwn so we don't need
// to test the reverse case
usage.substractFromRef(m_myRefs.m_refNetwork);
// we must recheck if the delta process is still above threshold
if ( (!bFilter) || ((usage.getBytesReceived() + usage.getBytesSent()) > 0) )
{
myStats.add((StatElement) usage);
}
}
else
{
// case b) nothing special
myStats.add((StatElement) usage);
}
}
}
return myStats;
}
/**
* Get the Other Usage Stat to be displayed
* @param bFilter defines if zero-values should be filtered out
* @return a List of Other usages sorted by duration (descending)
* @throws Exception if the API call failed
*/
public ArrayList<StatElement> getOtherUsageStatList(boolean bFilter, int iStatType) throws Exception
{
BatteryStatsProxy mStats = BatteryStatsProxy.getInstance(m_context);
ArrayList<StatElement> myStats = new ArrayList<StatElement>();
// List to store the other usages to
ArrayList<Misc> myUsages = new ArrayList<Misc>();
long rawRealtime = SystemClock.elapsedRealtime() * 1000;
long batteryRealtime = mStats.getBatteryRealtime(rawRealtime);
long whichRealtime = 0;
long timeBatteryUp = 0;
long timeScreenOn = 0;
long timePhoneOn = 0;
long timeWifiOn = 0;
long timeWifiRunning = 0;
long timeWifiMulticast = 0;
long timeWifiLocked = 0;
long timeWifiScan = 0;
long timeAudioOn = 0;
long timeVideoOn = 0;
long timeBluetoothOn = 0;
// if we are using custom ref. always retrieve "stats current"
if (iStatType == STATS_CUSTOM)
{
whichRealtime = mStats.computeBatteryRealtime(rawRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000;
timeBatteryUp = mStats.computeBatteryUptime(SystemClock.uptimeMillis() * 1000, BatteryStatsTypes.STATS_CURRENT) / 1000;
timeScreenOn = mStats.getScreenOnTime(batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000;
timePhoneOn = mStats.getPhoneOnTime(batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000;
timeWifiOn = mStats.getWifiOnTime(batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000;
- timeWifiRunning = mStats.getWifiRunningTime(m_context, batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000;
+ timeWifiRunning = mStats.getGlobalWifiRunningTime(batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000;
timeWifiMulticast = mStats.getWifiMulticastTime(m_context, batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000;
timeWifiLocked = mStats.getFullWifiLockTime(m_context, batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000;
timeWifiScan = mStats.getScanWifiLockTime(m_context, batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000;
timeAudioOn = mStats.getAudioTurnedOnTime(m_context, batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000;
timeVideoOn = mStats.getVideoTurnedOnTime(m_context, batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000;
timeBluetoothOn = mStats.getBluetoothOnTime(batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000;
}
else
{
whichRealtime = mStats.computeBatteryRealtime(rawRealtime, iStatType) / 1000;
timeBatteryUp = mStats.computeBatteryUptime(SystemClock.uptimeMillis() * 1000, iStatType) / 1000;
timeScreenOn = mStats.getScreenOnTime(batteryRealtime, iStatType) / 1000;
timePhoneOn = mStats.getPhoneOnTime(batteryRealtime, iStatType) / 1000;
timeWifiOn = mStats.getWifiOnTime(batteryRealtime, iStatType) / 1000;
- timeWifiRunning = mStats.getWifiRunningTime(m_context, batteryRealtime, iStatType) / 1000;
+ timeWifiRunning = mStats.getGlobalWifiRunningTime(batteryRealtime, iStatType) / 1000;
timeWifiMulticast = mStats.getWifiMulticastTime(m_context, batteryRealtime, iStatType) / 1000;
timeWifiLocked = mStats.getFullWifiLockTime(m_context, batteryRealtime, iStatType) / 1000;
timeWifiScan = mStats.getScanWifiLockTime(m_context, batteryRealtime, iStatType) / 1000;
timeAudioOn = mStats.getAudioTurnedOnTime(m_context, batteryRealtime, iStatType) / 1000;
timeVideoOn = mStats.getVideoTurnedOnTime(m_context, batteryRealtime, iStatType) / 1000;
timeBluetoothOn = mStats.getBluetoothOnTime(batteryRealtime, iStatType) / 1000;
}
if (timeBatteryUp > 0)
{
myUsages.add(new Misc("Awake", timeBatteryUp, whichRealtime));
}
if (timeScreenOn > 0)
{
myUsages.add(new Misc("Screen On", timeScreenOn, whichRealtime));
}
if (timePhoneOn > 0)
{
myUsages.add(new Misc("Phone On", timePhoneOn, whichRealtime));
}
if (timeWifiOn > 0)
{
myUsages.add(new Misc("Wifi On", timeWifiOn, whichRealtime));
}
if (timeWifiRunning > 0)
{
myUsages.add(new Misc("Wifi Running", timeWifiRunning, whichRealtime));
}
if (timeBluetoothOn > 0)
{
myUsages.add(new Misc("Bluetooth On", timeBluetoothOn, whichRealtime));
}
// if (timeWifiMulticast > 0)
// {
// myUsages.add(new Misc("Wifi Multicast On", timeWifiMulticast, whichRealtime));
// }
//
// if (timeWifiLocked > 0)
// {
// myUsages.add(new Misc("Wifi Locked", timeWifiLocked, whichRealtime));
// }
//
// if (timeWifiScan > 0)
// {
// myUsages.add(new Misc("Wifi Scan", timeWifiScan, whichRealtime));
// }
//
// if (timeAudioOn > 0)
// {
// myUsages.add(new Misc("Video On", timeAudioOn, whichRealtime));
// }
//
// if (timeVideoOn > 0)
// {
// myUsages.add(new Misc("Video On", timeVideoOn, whichRealtime));
// }
// sort @see com.asksven.android.common.privateapiproxies.Walkelock.compareTo
Collections.sort(myUsages);
for (int i = 0; i < myUsages.size(); i++)
{
Misc usage = myUsages.get(i);
if ( (!bFilter) || (usage.getTimeOn() > 0) )
{
if (iStatType == STATS_CUSTOM)
{
// case a)
// we need t return a delta containing
// if a process is in the new list but not in the custom ref
// the full time is returned
// if a process is in the reference return the delta
// a process can not have disapeared in btwn so we don't need
// to test the reverse case
if (m_myRefs != null)
{
usage.substractFromRef(m_myRefs.m_refOther);
if ( (!bFilter) || (usage.getTimeOn() > 0) )
{
myStats.add((StatElement) usage);
}
}
else
{
myStats.clear();
myStats.add(new Misc(NO_CUST_REF, 1, 1));
}
}
else
{
// case b)
// nothing special
myStats.add((StatElement) usage);
}
}
}
return myStats;
}
/**
* Returns true if a custom ref was stored
* @return true is a custom ref exists
*/
public boolean hasCustomRef()
{
return ( (m_myRefs != null) && (m_myRefs.m_refOther != null) );
}
/**
* Returns true if a since charged ref was stored
* @return true is a since charged ref exists
*/
public boolean hasSinceChargedRef()
{
return ( (m_myRefSinceCharged != null) && (m_myRefSinceCharged.m_refKernelWakelocks != null) );
}
/**
* Returns true if a since unplugged ref was stored
* @return true is a since unplugged ref exists
*/
public boolean hasSinceUnpluggedRef()
{
return ( (m_myRefSinceUnplugged != null) && (m_myRefSinceUnplugged.m_refKernelWakelocks != null) );
}
/**
* Saves all data to a point in time defined by user
* This data will be used in a custom "since..." stat type
*/
public void setCustomReference(int iSort)
{
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(m_context);
boolean bFilterStats = sharedPrefs.getBoolean("filter_data", true);
int iPctType = Integer.valueOf(sharedPrefs.getString("default_wl_ref", "0"));
try
{
if (m_myRefs != null)
{
m_myRefs.m_refOther = null;
m_myRefs.m_refWakelocks = null;
m_myRefs.m_refKernelWakelocks = null;
m_myRefs.m_refAlarms = null;
m_myRefs.m_refProcesses = null;
m_myRefs.m_refNetwork = null;
}
else
{
m_myRefs = new References();
}
// create a copy of each list for further reference
m_myRefs.m_refOther = getOtherUsageStatList(
bFilterStats, BatteryStatsTypes.STATS_CURRENT);
m_myRefs.m_refWakelocks = getWakelockStatList(
bFilterStats, BatteryStatsTypes.STATS_CURRENT, iPctType, iSort);
m_myRefs.m_refKernelWakelocks = getNativeKernelWakelockStatList(
bFilterStats, BatteryStatsTypes.STATS_CURRENT, iPctType, iSort);
m_myRefs.m_refAlarms = getAlarmsStatList(
bFilterStats, BatteryStatsTypes.STATS_CURRENT);
m_myRefs.m_refProcesses = getProcessStatList(
bFilterStats, BatteryStatsTypes.STATS_CURRENT, iSort);
m_myRefs.m_refNetwork = getNetworkUsageStatList(
bFilterStats, BatteryStatsTypes.STATS_CURRENT);
m_myRefs.m_refBatteryRealtime = getBatteryRealtime(BatteryStatsTypes.STATS_CURRENT);
serializeCustomRefToFile();
}
catch (Exception e)
{
Log.e(TAG, "Exception: " + e.getMessage());
//Toast.makeText(m_context, "an error occured while creating the custom reference", Toast.LENGTH_SHORT).show();
m_myRefs.m_refOther = null;
m_myRefs.m_refWakelocks = null;
m_myRefs.m_refKernelWakelocks = null;
m_myRefs.m_refAlarms = null;
m_myRefs.m_refProcesses = null;
m_myRefs.m_refNetwork = null;
m_myRefs.m_refBatteryRealtime = 0;
}
}
/**
* Saves data when battery is fully charged
* This data will be used in the "since charged" stat type
*/
public void setReferenceSinceCharged(int iSort)
{
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(m_context);
boolean bFilterStats = sharedPrefs.getBoolean("filter_data", true);
int iPctType = Integer.valueOf(sharedPrefs.getString("default_wl_ref", "0"));
try
{
m_myRefSinceCharged = new References();
m_myRefSinceCharged.m_refOther = null;
m_myRefSinceCharged.m_refWakelocks = null;
m_myRefSinceCharged.m_refKernelWakelocks = null;
m_myRefSinceCharged.m_refAlarms = null;
m_myRefSinceCharged.m_refProcesses = null;
m_myRefSinceCharged.m_refNetwork = null;
m_myRefSinceCharged.m_refKernelWakelocks = getNativeKernelWakelockStatList(
bFilterStats, BatteryStatsTypes.STATS_CURRENT, iPctType, iSort);
m_myRefSinceCharged.m_refAlarms = getAlarmsStatList(
bFilterStats, BatteryStatsTypes.STATS_CURRENT);
m_myRefSinceCharged.m_refBatteryRealtime = getBatteryRealtime(BatteryStatsTypes.STATS_CURRENT);
serializeSinceChargedRefToFile();
}
catch (Exception e)
{
Log.e(TAG, "Exception: " + e.getMessage());
Toast.makeText(m_context, "an error occured while creating the custom reference", Toast.LENGTH_SHORT).show();
m_myRefSinceCharged.m_refOther = null;
m_myRefSinceCharged.m_refWakelocks = null;
m_myRefSinceCharged.m_refKernelWakelocks = null;
m_myRefSinceCharged.m_refAlarms = null;
m_myRefSinceCharged.m_refProcesses = null;
m_myRefSinceCharged.m_refNetwork = null;
m_myRefSinceCharged.m_refBatteryRealtime = 0;
}
}
/**
* Saves data when the phone is unplugged
* This data will be used in the "since unplugged" stat type
*/
public void setReferenceSinceUnplugged(int iSort)
{
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(m_context);
boolean bFilterStats = sharedPrefs.getBoolean("filter_data", true);
int iPctType = Integer.valueOf(sharedPrefs.getString("default_wl_ref", "0"));
try
{
m_myRefSinceUnplugged = new References();
m_myRefSinceUnplugged.m_refOther = null;
m_myRefSinceUnplugged.m_refWakelocks = null;
m_myRefSinceUnplugged.m_refKernelWakelocks = null;
m_myRefSinceUnplugged.m_refAlarms = null;
m_myRefSinceUnplugged.m_refProcesses = null;
m_myRefSinceUnplugged.m_refNetwork = null;
m_myRefSinceUnplugged.m_refKernelWakelocks = getNativeKernelWakelockStatList(
bFilterStats, BatteryStatsTypes.STATS_CURRENT, iPctType, iSort);
m_myRefSinceUnplugged.m_refAlarms = getAlarmsStatList(
bFilterStats, BatteryStatsTypes.STATS_CURRENT);
m_myRefSinceUnplugged.m_refBatteryRealtime = getBatteryRealtime(BatteryStatsTypes.STATS_CURRENT);
serializeSinceUnpluggedRefToFile();
}
catch (Exception e)
{
Log.e(TAG, "Exception: " + e.getMessage());
Toast.makeText(m_context, "an error occured while creating the custom reference", Toast.LENGTH_SHORT).show();
m_myRefSinceUnplugged.m_refOther = null;
m_myRefSinceUnplugged.m_refWakelocks = null;
m_myRefSinceUnplugged.m_refKernelWakelocks = null;
m_myRefSinceUnplugged.m_refAlarms = null;
m_myRefSinceUnplugged.m_refProcesses = null;
m_myRefSinceUnplugged.m_refNetwork = null;
m_myRefSinceUnplugged.m_refBatteryRealtime = 0;
}
}
/**
* Restores state from a bundle
* @param savedInstanceState a bundle
*/
public void restoreFromBundle(Bundle savedInstanceState)
{
m_myRefs.m_refWakelocks = (ArrayList<StatElement>) savedInstanceState.getSerializable("wakelockstate");
m_myRefs.m_refKernelWakelocks = (ArrayList<StatElement>) savedInstanceState.getSerializable("nativekernelwakelockstate");
m_myRefs.m_refAlarms = (ArrayList<StatElement>) savedInstanceState.getSerializable("alarmstate");
m_myRefs.m_refProcesses = (ArrayList<StatElement>) savedInstanceState.getSerializable("processstate");
m_myRefs.m_refOther = (ArrayList<StatElement>) savedInstanceState.getSerializable("otherstate");
m_myRefs.m_refBatteryRealtime = (Long) savedInstanceState.getSerializable("batteryrealtime");
}
/**
* Writes states to a bundle to be temporarily persisted
* @param savedInstanceState a bundle
*/
public void writeToBundle(Bundle savedInstanceState)
{
if (hasCustomRef())
{
savedInstanceState.putSerializable("wakelockstate", m_myRefs.m_refWakelocks);
savedInstanceState.putSerializable("nativekernelwakelockstate", m_myRefs.m_refKernelWakelocks);
savedInstanceState.putSerializable("alarmstate", m_myRefs.m_refAlarms);
savedInstanceState.putSerializable("processstate", m_myRefs.m_refProcesses);
savedInstanceState.putSerializable("otherstate", m_myRefs.m_refOther);
savedInstanceState.putSerializable("networkstate", m_myRefs.m_refNetwork);
savedInstanceState.putSerializable("batteryrealtime", m_myRefs.m_refBatteryRealtime);
}
}
public void serializeCustomRefToFile()
{
if (hasCustomRef())
{
DataStorage.objectToFile(m_context, "custom_ref", m_myRefs);
}
}
public void serializeSinceChargedRefToFile()
{
DataStorage.objectToFile(m_context, "since_charged_ref", m_myRefSinceCharged);
}
public void serializeSinceUnpluggedRefToFile()
{
DataStorage.objectToFile(m_context, "since_unplugged_ref", m_myRefSinceUnplugged);
}
public void deserializeFromFile()
{
m_myRefs = (References) DataStorage.fileToObject(m_context, "custom_ref");
m_myRefSinceCharged = (References) DataStorage.fileToObject(m_context, "since_charged_ref");
m_myRefSinceUnplugged = (References) DataStorage.fileToObject(m_context, "since_unplugged_ref");
}
public void deletedSerializedRefs()
{
References myEmptyRef = new References();
DataStorage.objectToFile(m_context, "custom_ref", myEmptyRef);
DataStorage.objectToFile(m_context, "since_charged_ref", myEmptyRef);
DataStorage.objectToFile(m_context, "since_unplugged_ref", myEmptyRef);
}
/**
* Returns the battery realtime since a given reference
* @param iStatType the reference
* @return the battery realtime
*/
public long getBatteryRealtime(int iStatType)
{
BatteryStatsProxy mStats = BatteryStatsProxy.getInstance(m_context);
if (mStats == null)
{
// an error has occured
return -1;
}
long whichRealtime = 0;
long rawRealtime = SystemClock.elapsedRealtime() * 1000;
if ( (iStatType == StatsProvider.STATS_CUSTOM) && (m_myRefs != null) )
{
whichRealtime = mStats.computeBatteryRealtime(rawRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000;
whichRealtime -= m_myRefs.m_refBatteryRealtime;
}
else
{
whichRealtime = mStats.computeBatteryRealtime(rawRealtime, iStatType) / 1000;
}
return whichRealtime;
}
/**
* Dumps relevant data to an output file
*
*/
public void writeDumpToFile(int iStat, int iStatType, int iSort)
{
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(m_context);
boolean bFilterStats = sharedPrefs.getBoolean("filter_data", true);
int iPctType = Integer.valueOf(sharedPrefs.getString("default_wl_ref", "0"));
if (!DataStorage.isExternalStorageWritable())
{
Log.e(TAG, "External storage can not be written");
Toast.makeText(m_context, "External Storage can not be written", Toast.LENGTH_SHORT).show();
}
try
{
// open file for writing
File root = Environment.getExternalStorageDirectory();
// check if file can be written
if (root.canWrite())
{
String strFilename = "BetterBatteryStats-" + DateUtils.now("yyyy-MM-dd_HHmmssSSS") + ".txt";
File dumpFile = new File(root, strFilename);
FileWriter fw = new FileWriter(dumpFile);
BufferedWriter out = new BufferedWriter(fw);
// write header
out.write("===================\n");
out.write("General Information\n");
out.write("===================\n");
PackageInfo pinfo = m_context.getPackageManager().getPackageInfo(m_context.getPackageName(), 0);
out.write("BetterBatteryStats version: " + pinfo.versionName + "\n");
out.write("Creation Date: " + DateUtils.now() + "\n");
out.write("Statistic Type: (" + iStatType + ") " + statTypeToLabel(iStatType) + "\n");
out.write("Since " + DateUtils.formatDuration(getBatteryRealtime(iStatType)) + "\n");
out.write("VERSION.RELEASE: " + Build.VERSION.RELEASE+"\n");
out.write("BRAND: "+Build.BRAND+"\n");
out.write("DEVICE: "+Build.DEVICE+"\n");
out.write("MANUFACTURER: "+Build.MANUFACTURER+"\n");
out.write("MODEL: "+Build.MODEL+"\n");
out.write("RADIO: "+Build.RADIO+"\n");
out.write("BOOTLOADER: "+Build.BOOTLOADER+"\n");
out.write("FINGERPRINT: "+Build.FINGERPRINT+"\n");
out.write("HARDWARE: "+Build.HARDWARE+"\n");
out.write("ID: "+Build.ID+"\n");
out.write("Rooted: "+ RootDetection.hasSuRights() + "\n");
// write timing info
boolean bDumpChapter = sharedPrefs.getBoolean("show_other", true);
if (bDumpChapter)
{
out.write("===========\n");
out.write("Other Usage\n");
out.write("===========\n");
dumpList(getOtherUsageStatList(bFilterStats, iStatType), out);
}
bDumpChapter = sharedPrefs.getBoolean("show_pwl", true);
if (bDumpChapter)
{
// write wakelock info
out.write("=========\n");
out.write("Wakelocks\n");
out.write("=========\n");
dumpList(getWakelockStatList(bFilterStats, iStatType, iPctType, iSort), out);
}
bDumpChapter = sharedPrefs.getBoolean("show_kwl", true);
if (bDumpChapter)
{
// write kernel wakelock info
out.write("================\n");
out.write("Kernel Wakelocks\n");
out.write("================\n");
dumpList(getNativeKernelWakelockStatList(bFilterStats, iStatType, iPctType, iSort), out);
}
bDumpChapter = sharedPrefs.getBoolean("show_proc", false);
if (bDumpChapter)
{
// write process info
out.write("=========\n");
out.write("Processes\n");
out.write("=========\n");
dumpList(getProcessStatList(bFilterStats, iStatType, iSort), out);
}
bDumpChapter = sharedPrefs.getBoolean("show_alarm", true);
if (bDumpChapter)
{
// write alarms info
out.write("======================\n");
out.write("Alarms (requires root)\n");
out.write("======================\n");
dumpList(getAlarmsStatList(bFilterStats, iStatType), out);
}
// write network info
//out.write("=======\n");
//out.write("Network\n");
//out.write("=======\n");
//dumpList(getNetworkUsageStatList(bFilterStats, m_iStatType), out);
bDumpChapter = sharedPrefs.getBoolean("show_serv", false);
if (bDumpChapter)
{
out.write("========\n");
out.write("Services\n");
out.write("========\n");
out.write("Active since: The time when the service was first made active, either by someone starting or binding to it.\n");
out.write("Last activity: The time when there was last activity in the service (either explicit requests to start it or clients binding to it)\n");
out.write("See http://developer.android.com/reference/android/app/ActivityManager.RunningServiceInfo.html\n");
ActivityManager am = (ActivityManager)m_context.getSystemService(m_context.ACTIVITY_SERVICE);
List<ActivityManager.RunningServiceInfo> rs = am.getRunningServices(50);
for (int i=0; i < rs.size(); i++) {
ActivityManager.RunningServiceInfo rsi = rs.get(i);
out.write(rsi.process + " (" + rsi.service.getClassName() + ")\n");
out.write(" Active since: " + DateUtils.formatDuration(rsi.activeSince) + "\n");
out.write(" Last activity: " + DateUtils.formatDuration(rsi.lastActivityTime) + "\n");
out.write(" Crash count:" + rsi.crashCount + "\n");
}
}
// see http://androidsnippets.com/show-all-running-services
// close file
out.close();
}
else
{
Log.i(TAG, "Write error. " + Environment.getExternalStorageDirectory() + " couldn't be written");
Toast.makeText(m_context, "No dump created. " + Environment.getExternalStorageDirectory() + " is probably unmounted.", Toast.LENGTH_SHORT).show();
}
}
catch (Exception e)
{
Log.e(TAG, "Exception: " + e.getMessage());
// Toast.makeText(m_context, "an error occured while dumping the statistics", Toast.LENGTH_SHORT).show();
}
}
/**
* Dump the elements on one list
* @param myList a list of StatElement
*/
private void dumpList(List<StatElement> myList, BufferedWriter out) throws IOException
{
if (myList != null)
{
for (int i = 0; i < myList.size(); i++)
{
out.write(myList.get(i).getDumpData(m_context) + "\n");
}
}
}
/**
* translate the stat type (see arrays.xml) to the corresponding label
* @param position the spinner position
* @return the stat type
*/
private String statTypeToLabel(int statType)
{
String strRet = "";
switch (statType)
{
case 0:
strRet = "Since Charged";
break;
case 1:
strRet = "Since Unplugged";
break;
case 2:
strRet = "Custom Reference";
break;
}
return strRet;
}
/**
* translate the stat type (see arrays.xml) to the corresponding label
* @param position the spinner position
* @return the stat type
*/
public String statTypeToUrl(int statType)
{
String strRet = statTypeToLabel(statType);
// remove spaces
StringTokenizer st = new StringTokenizer(strRet," ",false);
String strCleaned = "";
while (st.hasMoreElements())
{
strCleaned += st.nextElement();
}
return strCleaned;
}
/**
* translate the stat (see arrays.xml) to the corresponding label
* @param position the spinner position
* @return the stat
*/
private String statToLabel(int iStat)
{
String strRet = "";
switch (iStat)
{
// constants are related to arrays.xml string-array name="stats"
case 0:
strRet = "Process";
break;
case 1:
strRet = "Partial Wakelocks";
break;
case 2:
strRet = "Other";
break;
case 3:
strRet = "Kernel Wakelocks";
break;
case 4:
strRet = "Alarms";
break;
}
return strRet;
}
/**
* translate the stat (see arrays.xml) to the corresponding label
* @param position the spinner position
* @return the stat
*/
public String statToUrl(int stat)
{
String strRet = statToLabel(stat);
// remove spaces
StringTokenizer st = new StringTokenizer(strRet," ",false);
String strCleaned = "";
while (st.hasMoreElements())
{
strCleaned += st.nextElement();
}
return strCleaned;
}
}
| false | true | public ArrayList<StatElement> getOtherUsageStatList(boolean bFilter, int iStatType) throws Exception
{
BatteryStatsProxy mStats = BatteryStatsProxy.getInstance(m_context);
ArrayList<StatElement> myStats = new ArrayList<StatElement>();
// List to store the other usages to
ArrayList<Misc> myUsages = new ArrayList<Misc>();
long rawRealtime = SystemClock.elapsedRealtime() * 1000;
long batteryRealtime = mStats.getBatteryRealtime(rawRealtime);
long whichRealtime = 0;
long timeBatteryUp = 0;
long timeScreenOn = 0;
long timePhoneOn = 0;
long timeWifiOn = 0;
long timeWifiRunning = 0;
long timeWifiMulticast = 0;
long timeWifiLocked = 0;
long timeWifiScan = 0;
long timeAudioOn = 0;
long timeVideoOn = 0;
long timeBluetoothOn = 0;
// if we are using custom ref. always retrieve "stats current"
if (iStatType == STATS_CUSTOM)
{
whichRealtime = mStats.computeBatteryRealtime(rawRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000;
timeBatteryUp = mStats.computeBatteryUptime(SystemClock.uptimeMillis() * 1000, BatteryStatsTypes.STATS_CURRENT) / 1000;
timeScreenOn = mStats.getScreenOnTime(batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000;
timePhoneOn = mStats.getPhoneOnTime(batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000;
timeWifiOn = mStats.getWifiOnTime(batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000;
timeWifiRunning = mStats.getWifiRunningTime(m_context, batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000;
timeWifiMulticast = mStats.getWifiMulticastTime(m_context, batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000;
timeWifiLocked = mStats.getFullWifiLockTime(m_context, batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000;
timeWifiScan = mStats.getScanWifiLockTime(m_context, batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000;
timeAudioOn = mStats.getAudioTurnedOnTime(m_context, batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000;
timeVideoOn = mStats.getVideoTurnedOnTime(m_context, batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000;
timeBluetoothOn = mStats.getBluetoothOnTime(batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000;
}
else
{
whichRealtime = mStats.computeBatteryRealtime(rawRealtime, iStatType) / 1000;
timeBatteryUp = mStats.computeBatteryUptime(SystemClock.uptimeMillis() * 1000, iStatType) / 1000;
timeScreenOn = mStats.getScreenOnTime(batteryRealtime, iStatType) / 1000;
timePhoneOn = mStats.getPhoneOnTime(batteryRealtime, iStatType) / 1000;
timeWifiOn = mStats.getWifiOnTime(batteryRealtime, iStatType) / 1000;
timeWifiRunning = mStats.getWifiRunningTime(m_context, batteryRealtime, iStatType) / 1000;
timeWifiMulticast = mStats.getWifiMulticastTime(m_context, batteryRealtime, iStatType) / 1000;
timeWifiLocked = mStats.getFullWifiLockTime(m_context, batteryRealtime, iStatType) / 1000;
timeWifiScan = mStats.getScanWifiLockTime(m_context, batteryRealtime, iStatType) / 1000;
timeAudioOn = mStats.getAudioTurnedOnTime(m_context, batteryRealtime, iStatType) / 1000;
timeVideoOn = mStats.getVideoTurnedOnTime(m_context, batteryRealtime, iStatType) / 1000;
timeBluetoothOn = mStats.getBluetoothOnTime(batteryRealtime, iStatType) / 1000;
}
if (timeBatteryUp > 0)
{
myUsages.add(new Misc("Awake", timeBatteryUp, whichRealtime));
}
if (timeScreenOn > 0)
{
myUsages.add(new Misc("Screen On", timeScreenOn, whichRealtime));
}
if (timePhoneOn > 0)
{
myUsages.add(new Misc("Phone On", timePhoneOn, whichRealtime));
}
if (timeWifiOn > 0)
{
myUsages.add(new Misc("Wifi On", timeWifiOn, whichRealtime));
}
if (timeWifiRunning > 0)
{
myUsages.add(new Misc("Wifi Running", timeWifiRunning, whichRealtime));
}
if (timeBluetoothOn > 0)
{
myUsages.add(new Misc("Bluetooth On", timeBluetoothOn, whichRealtime));
}
// if (timeWifiMulticast > 0)
// {
// myUsages.add(new Misc("Wifi Multicast On", timeWifiMulticast, whichRealtime));
// }
//
// if (timeWifiLocked > 0)
// {
// myUsages.add(new Misc("Wifi Locked", timeWifiLocked, whichRealtime));
// }
//
// if (timeWifiScan > 0)
// {
// myUsages.add(new Misc("Wifi Scan", timeWifiScan, whichRealtime));
// }
//
// if (timeAudioOn > 0)
// {
// myUsages.add(new Misc("Video On", timeAudioOn, whichRealtime));
// }
//
// if (timeVideoOn > 0)
// {
// myUsages.add(new Misc("Video On", timeVideoOn, whichRealtime));
// }
// sort @see com.asksven.android.common.privateapiproxies.Walkelock.compareTo
Collections.sort(myUsages);
for (int i = 0; i < myUsages.size(); i++)
{
Misc usage = myUsages.get(i);
if ( (!bFilter) || (usage.getTimeOn() > 0) )
{
if (iStatType == STATS_CUSTOM)
{
// case a)
// we need t return a delta containing
// if a process is in the new list but not in the custom ref
// the full time is returned
// if a process is in the reference return the delta
// a process can not have disapeared in btwn so we don't need
// to test the reverse case
if (m_myRefs != null)
{
usage.substractFromRef(m_myRefs.m_refOther);
if ( (!bFilter) || (usage.getTimeOn() > 0) )
{
myStats.add((StatElement) usage);
}
}
else
{
myStats.clear();
myStats.add(new Misc(NO_CUST_REF, 1, 1));
}
}
else
{
// case b)
// nothing special
myStats.add((StatElement) usage);
}
}
}
return myStats;
}
| public ArrayList<StatElement> getOtherUsageStatList(boolean bFilter, int iStatType) throws Exception
{
BatteryStatsProxy mStats = BatteryStatsProxy.getInstance(m_context);
ArrayList<StatElement> myStats = new ArrayList<StatElement>();
// List to store the other usages to
ArrayList<Misc> myUsages = new ArrayList<Misc>();
long rawRealtime = SystemClock.elapsedRealtime() * 1000;
long batteryRealtime = mStats.getBatteryRealtime(rawRealtime);
long whichRealtime = 0;
long timeBatteryUp = 0;
long timeScreenOn = 0;
long timePhoneOn = 0;
long timeWifiOn = 0;
long timeWifiRunning = 0;
long timeWifiMulticast = 0;
long timeWifiLocked = 0;
long timeWifiScan = 0;
long timeAudioOn = 0;
long timeVideoOn = 0;
long timeBluetoothOn = 0;
// if we are using custom ref. always retrieve "stats current"
if (iStatType == STATS_CUSTOM)
{
whichRealtime = mStats.computeBatteryRealtime(rawRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000;
timeBatteryUp = mStats.computeBatteryUptime(SystemClock.uptimeMillis() * 1000, BatteryStatsTypes.STATS_CURRENT) / 1000;
timeScreenOn = mStats.getScreenOnTime(batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000;
timePhoneOn = mStats.getPhoneOnTime(batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000;
timeWifiOn = mStats.getWifiOnTime(batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000;
timeWifiRunning = mStats.getGlobalWifiRunningTime(batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000;
timeWifiMulticast = mStats.getWifiMulticastTime(m_context, batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000;
timeWifiLocked = mStats.getFullWifiLockTime(m_context, batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000;
timeWifiScan = mStats.getScanWifiLockTime(m_context, batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000;
timeAudioOn = mStats.getAudioTurnedOnTime(m_context, batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000;
timeVideoOn = mStats.getVideoTurnedOnTime(m_context, batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000;
timeBluetoothOn = mStats.getBluetoothOnTime(batteryRealtime, BatteryStatsTypes.STATS_CURRENT) / 1000;
}
else
{
whichRealtime = mStats.computeBatteryRealtime(rawRealtime, iStatType) / 1000;
timeBatteryUp = mStats.computeBatteryUptime(SystemClock.uptimeMillis() * 1000, iStatType) / 1000;
timeScreenOn = mStats.getScreenOnTime(batteryRealtime, iStatType) / 1000;
timePhoneOn = mStats.getPhoneOnTime(batteryRealtime, iStatType) / 1000;
timeWifiOn = mStats.getWifiOnTime(batteryRealtime, iStatType) / 1000;
timeWifiRunning = mStats.getGlobalWifiRunningTime(batteryRealtime, iStatType) / 1000;
timeWifiMulticast = mStats.getWifiMulticastTime(m_context, batteryRealtime, iStatType) / 1000;
timeWifiLocked = mStats.getFullWifiLockTime(m_context, batteryRealtime, iStatType) / 1000;
timeWifiScan = mStats.getScanWifiLockTime(m_context, batteryRealtime, iStatType) / 1000;
timeAudioOn = mStats.getAudioTurnedOnTime(m_context, batteryRealtime, iStatType) / 1000;
timeVideoOn = mStats.getVideoTurnedOnTime(m_context, batteryRealtime, iStatType) / 1000;
timeBluetoothOn = mStats.getBluetoothOnTime(batteryRealtime, iStatType) / 1000;
}
if (timeBatteryUp > 0)
{
myUsages.add(new Misc("Awake", timeBatteryUp, whichRealtime));
}
if (timeScreenOn > 0)
{
myUsages.add(new Misc("Screen On", timeScreenOn, whichRealtime));
}
if (timePhoneOn > 0)
{
myUsages.add(new Misc("Phone On", timePhoneOn, whichRealtime));
}
if (timeWifiOn > 0)
{
myUsages.add(new Misc("Wifi On", timeWifiOn, whichRealtime));
}
if (timeWifiRunning > 0)
{
myUsages.add(new Misc("Wifi Running", timeWifiRunning, whichRealtime));
}
if (timeBluetoothOn > 0)
{
myUsages.add(new Misc("Bluetooth On", timeBluetoothOn, whichRealtime));
}
// if (timeWifiMulticast > 0)
// {
// myUsages.add(new Misc("Wifi Multicast On", timeWifiMulticast, whichRealtime));
// }
//
// if (timeWifiLocked > 0)
// {
// myUsages.add(new Misc("Wifi Locked", timeWifiLocked, whichRealtime));
// }
//
// if (timeWifiScan > 0)
// {
// myUsages.add(new Misc("Wifi Scan", timeWifiScan, whichRealtime));
// }
//
// if (timeAudioOn > 0)
// {
// myUsages.add(new Misc("Video On", timeAudioOn, whichRealtime));
// }
//
// if (timeVideoOn > 0)
// {
// myUsages.add(new Misc("Video On", timeVideoOn, whichRealtime));
// }
// sort @see com.asksven.android.common.privateapiproxies.Walkelock.compareTo
Collections.sort(myUsages);
for (int i = 0; i < myUsages.size(); i++)
{
Misc usage = myUsages.get(i);
if ( (!bFilter) || (usage.getTimeOn() > 0) )
{
if (iStatType == STATS_CUSTOM)
{
// case a)
// we need t return a delta containing
// if a process is in the new list but not in the custom ref
// the full time is returned
// if a process is in the reference return the delta
// a process can not have disapeared in btwn so we don't need
// to test the reverse case
if (m_myRefs != null)
{
usage.substractFromRef(m_myRefs.m_refOther);
if ( (!bFilter) || (usage.getTimeOn() > 0) )
{
myStats.add((StatElement) usage);
}
}
else
{
myStats.clear();
myStats.add(new Misc(NO_CUST_REF, 1, 1));
}
}
else
{
// case b)
// nothing special
myStats.add((StatElement) usage);
}
}
}
return myStats;
}
|
diff --git a/bfio-android-sample/src/com/bfio/sample/MainActivity.java b/bfio-android-sample/src/com/bfio/sample/MainActivity.java
index e99f632..9572c79 100644
--- a/bfio-android-sample/src/com/bfio/sample/MainActivity.java
+++ b/bfio-android-sample/src/com/bfio/sample/MainActivity.java
@@ -1,104 +1,104 @@
package com.bfio.sample;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Toast;
import com.bfio.ad.BFIOErrorCode;
import com.bfio.ad.BFIOInterstitial;
import com.bfio.ad.model.BFIOInterstitalAd;
public class MainActivity extends Activity implements
BFIOInterstitial.InterstitialListener, OnClickListener {
BFIOInterstitial interstitial;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.request).setOnClickListener(this);
interstitial = new BFIOInterstitial(MainActivity.this, this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
protected void onDestroy() {
interstitial.onDestroy();
super.onDestroy();
}
@Override
public void onInterstitialFailed(BFIOErrorCode errorCode) {
Toast.makeText(MainActivity.this, "Interstitial not received",
Toast.LENGTH_SHORT).show();
}
@Override
public void onInterstitialClicked() {
Toast.makeText(MainActivity.this, "Interstitial Clicked",
Toast.LENGTH_SHORT).show();
}
@Override
public void onInterstitialDismissed() {
Toast.makeText(MainActivity.this, "Interstitial dismissed",
Toast.LENGTH_SHORT).show();
}
@Override
public void onReceiveInterstitial(BFIOInterstitalAd ad) {
Toast.makeText(MainActivity.this, "Received interstitial",
Toast.LENGTH_SHORT).show();
interstitial.showInterstitial(ad);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.request:
// interactive
-// interstitial.requestInterstitial(
-// "e04fd6b0-4eb2-4dc8-b8d3-accfb7cf8043", // appID
-// "e4471497-53ec-42f8-af58-cba7464d9e5a"); // adUnitId
+ interstitial.requestInterstitial(
+ "e04fd6b0-4eb2-4dc8-b8d3-accfb7cf8043", // appID
+ "e4471497-53ec-42f8-af58-cba7464d9e5a"); // adUnitId
// non interactive
- interstitial.requestInterstitial(
- "fd298c64-e28b-4a28-f3b6-410d24be3b73", // appID
- "2f529a17-97ff-4b34-b02d-a75cdaa0f1a9"); // adUnitId
+ // interstitial.requestInterstitial(
+ // "fd298c64-e28b-4a28-f3b6-410d24be3b73", // appID
+ // "2f529a17-97ff-4b34-b02d-a75cdaa0f1a9"); // adUnitId
Toast.makeText(MainActivity.this, "Interstitial request sent",
Toast.LENGTH_SHORT).show();
break;
default:
break;
}
}
@Override
public void onInterstitialCompleted() {
Toast.makeText(MainActivity.this, "Interstitial play completed",
Toast.LENGTH_SHORT).show();
}
@Override
public void onInterstitialStarted() {
Toast.makeText(MainActivity.this, "Interstitial started",
Toast.LENGTH_SHORT).show();
}
}
| false | true | public void onClick(View v) {
switch (v.getId()) {
case R.id.request:
// interactive
// interstitial.requestInterstitial(
// "e04fd6b0-4eb2-4dc8-b8d3-accfb7cf8043", // appID
// "e4471497-53ec-42f8-af58-cba7464d9e5a"); // adUnitId
// non interactive
interstitial.requestInterstitial(
"fd298c64-e28b-4a28-f3b6-410d24be3b73", // appID
"2f529a17-97ff-4b34-b02d-a75cdaa0f1a9"); // adUnitId
Toast.makeText(MainActivity.this, "Interstitial request sent",
Toast.LENGTH_SHORT).show();
break;
default:
break;
}
}
| public void onClick(View v) {
switch (v.getId()) {
case R.id.request:
// interactive
interstitial.requestInterstitial(
"e04fd6b0-4eb2-4dc8-b8d3-accfb7cf8043", // appID
"e4471497-53ec-42f8-af58-cba7464d9e5a"); // adUnitId
// non interactive
// interstitial.requestInterstitial(
// "fd298c64-e28b-4a28-f3b6-410d24be3b73", // appID
// "2f529a17-97ff-4b34-b02d-a75cdaa0f1a9"); // adUnitId
Toast.makeText(MainActivity.this, "Interstitial request sent",
Toast.LENGTH_SHORT).show();
break;
default:
break;
}
}
|
diff --git a/src/core/org/pathvisio/data/GexTxtImporter.java b/src/core/org/pathvisio/data/GexTxtImporter.java
index a7f37f85..84acd3f2 100644
--- a/src/core/org/pathvisio/data/GexTxtImporter.java
+++ b/src/core/org/pathvisio/data/GexTxtImporter.java
@@ -1,305 +1,305 @@
// PathVisio,
// a tool for data visualization and analysis using Biological Pathways
// Copyright 2006-2007 BiGCaT Bioinformatics
//
// 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.pathvisio.data;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintStream;
import java.sql.Types;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;
import org.pathvisio.debug.Logger;
import org.pathvisio.debug.StopWatch;
import org.pathvisio.model.DataSource;
import org.pathvisio.model.Xref;
import org.pathvisio.util.FileUtils;
import org.pathvisio.util.ProgressKeeper;
/**
* Functions to create a new Gex database
* based on a text file.
*/
public class GexTxtImporter
{
/**
* Imports expression data from a text file and saves it to an hsqldb expression database
* @param info {@link GexImportWizard.ImportInformation} object that contains the
* information needed to import the data
* @param p {@link ProgressKeeper} that reports the progress of the process and enables
* the user to cancel. May be null for headless mode operation.
*/
public static void importFromTxt(ImportInformation info, ProgressKeeper p, Gdb currentGdb)
{
SimpleGex result = null;
int importWork = 0;
int finalizeWork = 0;
if (p != null)
{
importWork = (int)(p.getTotalWork() * 0.8);
finalizeWork = (int)(p.getTotalWork() * 0.2);
}
// Open a connection to the error file
String errorFile = info.getDbName() + ".ex.txt";
int errors = 0;
PrintStream error = null;
try {
File ef = new File(errorFile);
ef.getParentFile().mkdirs();
error = new PrintStream(errorFile);
} catch(IOException ex) {
if (p != null) p.report("Error: could not open exception file: " + ex.getMessage());
error = System.out;
}
StopWatch timer = new StopWatch();
try
{
if (p != null) p.report("\nCreating expression dataset");
//Create a new expression database (or overwrite existing)
result = new SimpleGex(info.getDbName(), true, GexManager.getCurrent().getDBConnector());
if (p != null)
{
p.report("Importing data");
p.report("> Processing headers");
}
timer.start();
BufferedReader in = new BufferedReader(new FileReader(info.getTxtFile()));
//Get the number of lines in the file (for progress)
int nrLines = FileUtils.getNrLines(info.getTxtFile().toString());
String[] headers = info.getColNames();
//Parse sample names and add to Sample table
result.prepare();
int sampleId = 0;
ArrayList<Integer> dataCols = new ArrayList<Integer>();
for(int i = 0; i < headers.length; i++)
{
if(p != null && p.isCancelled())
{
//User pressed cancel
result.close();
error.close();
return;
}
//skip the gene and systemcode column if there is one
if(
(info.getSyscodeColumn() && i != info.getIdColumn() && i != info.getCodeColumn()) ||
(!info.getSyscodeColumn() && i != info.getIdColumn())
)
{
try {
result.addSample(
sampleId++,
headers[i],
info.isStringCol(i) ? Types.CHAR : Types.REAL);
dataCols.add(i);
}
catch(Error e) {
errors = reportError(info, error, "Error in headerline, can't add column " + i +
" due to: " + e.getMessage(), errors);
}
}
}
if (p != null) p.report("> Processing lines");
//Check ids and add expression data
for(int i = 1; i < info.getFirstDataRow(); i++) in.readLine(); //Go to line where data starts
String line = null;
int n = info.getFirstDataRow() - 1;
int added = 0;
int worked = importWork / nrLines;
boolean maximumNotSet = true;
boolean minimumNotSet = true;
double maximum = 1; // Dummy value
double minimum = 1; // Dummy value
DecimalFormat nf = new DecimalFormat();
DecimalFormatSymbols dfs = nf.getDecimalFormatSymbols();
DecimalFormat df = new DecimalFormat();
if (info.digitIsDot())
{
dfs.setGroupingSeparator('.');
dfs.setDecimalSeparator(',');
}
while((line = in.readLine()) != null)
{
if(p != null && p.isCancelled())
{
result.close();
error.close();
return;
} //User pressed cancel
String[] data = line.split(info.getDelimiter(), headers.length);
n++;
if(n == info.headerRow) continue; //Don't add header row (very unlikely that this will happen)
if(data.length < headers.length) {
errors = reportError(info, error, "Number of columns in line " + n +
"doesn't match number of header columns",
errors);
continue;
}
if (p != null) p.setTaskName("Importing expression data - processing line " + n + "; " + errors + " exceptions");
//Check id and add data
String id = data[info.getIdColumn()].trim();
/*Set the system code to the one found in the dataset if there is a system code column,
* otherwise set the system code to the one selected (either by the user or by regular
* expressions.*/
DataSource ds;
if (info.getSyscodeColumn())
{
ds = DataSource.getBySystemCode(data[info.getCodeColumn()].trim());
}
else
{
ds = info.getDataSource();
}
Xref ref = new Xref (id, ds);
//Find the Ensembl genes for current gene
List<String> ensIds = currentGdb.ref2EnsIds(ref);
if(ensIds == null || ensIds.size() == 0) //No Ensembl gene found
{
errors = reportError(info, error, "Line " + n + ":\t" + ref +
"\tNo Ensembl gene found for this identifier", errors);
} else { //Gene maps to an Ensembl id, so add it
boolean success = true;
for( String ensId : ensIds) //For every Ensembl id add the data
{
for(int col : dataCols)
{
String value = data[col];
if(!info.isStringCol(col)
&& (value == null || value.equals(""))) {
value = "NaN";
}
//Determine maximum and minimum values.
try
{
- value = "" + nf.parse(value);
- double dNumber = new Double(value).doubleValue();
+ double dNumber = nf.parse(value).doubleValue();
+ value = "" + dNumber;
if(maximumNotSet || dNumber>maximum)
{
maximum=dNumber;
maximumNotSet=false;
}
if(minimumNotSet || dNumber<minimum)
{
minimum=dNumber;
minimumNotSet=false;
}
}
catch (NumberFormatException e)
{
// we've got a number in a non-number column.
// safe to ignore
Logger.log.warn ("Number format exception in non-string column " + e.getMessage());
}
//End of determining maximum and minimum values. After the data has been read,
//maximum and minimum will have their correct values.
try
{
//TODO: use autocommit (false) and commit only every 1000 queries or so.
result.addExpr(
ref,
ensId,
Integer.toString(dataCols.indexOf(col)),
value,
added);
}
catch (Exception e)
{
errors = reportError(info, error, "Line " + n + ":\t" + line + "\n" +
"\tException: " + e.getMessage(), errors);
success = false;
}
}
}
if(success) added++;
}
if (p != null) p.worked(worked);
}
//Data is read and written to the database
//Writing maximum and minimum to ImportInformation
info.setMaximum(maximum);
info.setMinimum(minimum);
if (p != null) p.report(added + " genes were added succesfully to the expression dataset");
if(errors > 0)
{
if (p != null) p.report(errors + " exceptions occured, see file '" + errorFile + "' for details");
} else {
new File(errorFile).delete(); // If no errors were found, delete the error file
}
if (p != null) p.setTaskName("Closing database connection");
result.finalize();
if (p != null) p.worked(finalizeWork);
error.println("Time to create expression dataset: " + timer.stop());
error.close();
GexManager.getCurrent().setCurrentGex(result.getDbName(), false);
if (p != null) p.finished();
}
catch(Exception e)
{
if (p != null) p.report("Import aborted due to error: " + e.getMessage());
Logger.log.error("Expression data import error", e);
try
{
result.close();
}
catch (DataException f)
{ Logger.log.error ("Exception while aborting database", f); }
error.close();
}
}
private static int reportError(ImportInformation info, PrintStream log, String message, int nrError)
{
info.addError(message);
log.println(message);
nrError++;
return nrError;
}
}
| true | true | public static void importFromTxt(ImportInformation info, ProgressKeeper p, Gdb currentGdb)
{
SimpleGex result = null;
int importWork = 0;
int finalizeWork = 0;
if (p != null)
{
importWork = (int)(p.getTotalWork() * 0.8);
finalizeWork = (int)(p.getTotalWork() * 0.2);
}
// Open a connection to the error file
String errorFile = info.getDbName() + ".ex.txt";
int errors = 0;
PrintStream error = null;
try {
File ef = new File(errorFile);
ef.getParentFile().mkdirs();
error = new PrintStream(errorFile);
} catch(IOException ex) {
if (p != null) p.report("Error: could not open exception file: " + ex.getMessage());
error = System.out;
}
StopWatch timer = new StopWatch();
try
{
if (p != null) p.report("\nCreating expression dataset");
//Create a new expression database (or overwrite existing)
result = new SimpleGex(info.getDbName(), true, GexManager.getCurrent().getDBConnector());
if (p != null)
{
p.report("Importing data");
p.report("> Processing headers");
}
timer.start();
BufferedReader in = new BufferedReader(new FileReader(info.getTxtFile()));
//Get the number of lines in the file (for progress)
int nrLines = FileUtils.getNrLines(info.getTxtFile().toString());
String[] headers = info.getColNames();
//Parse sample names and add to Sample table
result.prepare();
int sampleId = 0;
ArrayList<Integer> dataCols = new ArrayList<Integer>();
for(int i = 0; i < headers.length; i++)
{
if(p != null && p.isCancelled())
{
//User pressed cancel
result.close();
error.close();
return;
}
//skip the gene and systemcode column if there is one
if(
(info.getSyscodeColumn() && i != info.getIdColumn() && i != info.getCodeColumn()) ||
(!info.getSyscodeColumn() && i != info.getIdColumn())
)
{
try {
result.addSample(
sampleId++,
headers[i],
info.isStringCol(i) ? Types.CHAR : Types.REAL);
dataCols.add(i);
}
catch(Error e) {
errors = reportError(info, error, "Error in headerline, can't add column " + i +
" due to: " + e.getMessage(), errors);
}
}
}
if (p != null) p.report("> Processing lines");
//Check ids and add expression data
for(int i = 1; i < info.getFirstDataRow(); i++) in.readLine(); //Go to line where data starts
String line = null;
int n = info.getFirstDataRow() - 1;
int added = 0;
int worked = importWork / nrLines;
boolean maximumNotSet = true;
boolean minimumNotSet = true;
double maximum = 1; // Dummy value
double minimum = 1; // Dummy value
DecimalFormat nf = new DecimalFormat();
DecimalFormatSymbols dfs = nf.getDecimalFormatSymbols();
DecimalFormat df = new DecimalFormat();
if (info.digitIsDot())
{
dfs.setGroupingSeparator('.');
dfs.setDecimalSeparator(',');
}
while((line = in.readLine()) != null)
{
if(p != null && p.isCancelled())
{
result.close();
error.close();
return;
} //User pressed cancel
String[] data = line.split(info.getDelimiter(), headers.length);
n++;
if(n == info.headerRow) continue; //Don't add header row (very unlikely that this will happen)
if(data.length < headers.length) {
errors = reportError(info, error, "Number of columns in line " + n +
"doesn't match number of header columns",
errors);
continue;
}
if (p != null) p.setTaskName("Importing expression data - processing line " + n + "; " + errors + " exceptions");
//Check id and add data
String id = data[info.getIdColumn()].trim();
/*Set the system code to the one found in the dataset if there is a system code column,
* otherwise set the system code to the one selected (either by the user or by regular
* expressions.*/
DataSource ds;
if (info.getSyscodeColumn())
{
ds = DataSource.getBySystemCode(data[info.getCodeColumn()].trim());
}
else
{
ds = info.getDataSource();
}
Xref ref = new Xref (id, ds);
//Find the Ensembl genes for current gene
List<String> ensIds = currentGdb.ref2EnsIds(ref);
if(ensIds == null || ensIds.size() == 0) //No Ensembl gene found
{
errors = reportError(info, error, "Line " + n + ":\t" + ref +
"\tNo Ensembl gene found for this identifier", errors);
} else { //Gene maps to an Ensembl id, so add it
boolean success = true;
for( String ensId : ensIds) //For every Ensembl id add the data
{
for(int col : dataCols)
{
String value = data[col];
if(!info.isStringCol(col)
&& (value == null || value.equals(""))) {
value = "NaN";
}
//Determine maximum and minimum values.
try
{
value = "" + nf.parse(value);
double dNumber = new Double(value).doubleValue();
if(maximumNotSet || dNumber>maximum)
{
maximum=dNumber;
maximumNotSet=false;
}
if(minimumNotSet || dNumber<minimum)
{
minimum=dNumber;
minimumNotSet=false;
}
}
catch (NumberFormatException e)
{
// we've got a number in a non-number column.
// safe to ignore
Logger.log.warn ("Number format exception in non-string column " + e.getMessage());
}
//End of determining maximum and minimum values. After the data has been read,
//maximum and minimum will have their correct values.
try
{
//TODO: use autocommit (false) and commit only every 1000 queries or so.
result.addExpr(
ref,
ensId,
Integer.toString(dataCols.indexOf(col)),
value,
added);
}
catch (Exception e)
{
errors = reportError(info, error, "Line " + n + ":\t" + line + "\n" +
"\tException: " + e.getMessage(), errors);
success = false;
}
}
}
if(success) added++;
}
if (p != null) p.worked(worked);
}
//Data is read and written to the database
//Writing maximum and minimum to ImportInformation
info.setMaximum(maximum);
info.setMinimum(minimum);
if (p != null) p.report(added + " genes were added succesfully to the expression dataset");
if(errors > 0)
{
if (p != null) p.report(errors + " exceptions occured, see file '" + errorFile + "' for details");
} else {
new File(errorFile).delete(); // If no errors were found, delete the error file
}
if (p != null) p.setTaskName("Closing database connection");
result.finalize();
if (p != null) p.worked(finalizeWork);
error.println("Time to create expression dataset: " + timer.stop());
error.close();
GexManager.getCurrent().setCurrentGex(result.getDbName(), false);
if (p != null) p.finished();
}
catch(Exception e)
{
if (p != null) p.report("Import aborted due to error: " + e.getMessage());
Logger.log.error("Expression data import error", e);
try
{
result.close();
}
catch (DataException f)
{ Logger.log.error ("Exception while aborting database", f); }
error.close();
}
}
| public static void importFromTxt(ImportInformation info, ProgressKeeper p, Gdb currentGdb)
{
SimpleGex result = null;
int importWork = 0;
int finalizeWork = 0;
if (p != null)
{
importWork = (int)(p.getTotalWork() * 0.8);
finalizeWork = (int)(p.getTotalWork() * 0.2);
}
// Open a connection to the error file
String errorFile = info.getDbName() + ".ex.txt";
int errors = 0;
PrintStream error = null;
try {
File ef = new File(errorFile);
ef.getParentFile().mkdirs();
error = new PrintStream(errorFile);
} catch(IOException ex) {
if (p != null) p.report("Error: could not open exception file: " + ex.getMessage());
error = System.out;
}
StopWatch timer = new StopWatch();
try
{
if (p != null) p.report("\nCreating expression dataset");
//Create a new expression database (or overwrite existing)
result = new SimpleGex(info.getDbName(), true, GexManager.getCurrent().getDBConnector());
if (p != null)
{
p.report("Importing data");
p.report("> Processing headers");
}
timer.start();
BufferedReader in = new BufferedReader(new FileReader(info.getTxtFile()));
//Get the number of lines in the file (for progress)
int nrLines = FileUtils.getNrLines(info.getTxtFile().toString());
String[] headers = info.getColNames();
//Parse sample names and add to Sample table
result.prepare();
int sampleId = 0;
ArrayList<Integer> dataCols = new ArrayList<Integer>();
for(int i = 0; i < headers.length; i++)
{
if(p != null && p.isCancelled())
{
//User pressed cancel
result.close();
error.close();
return;
}
//skip the gene and systemcode column if there is one
if(
(info.getSyscodeColumn() && i != info.getIdColumn() && i != info.getCodeColumn()) ||
(!info.getSyscodeColumn() && i != info.getIdColumn())
)
{
try {
result.addSample(
sampleId++,
headers[i],
info.isStringCol(i) ? Types.CHAR : Types.REAL);
dataCols.add(i);
}
catch(Error e) {
errors = reportError(info, error, "Error in headerline, can't add column " + i +
" due to: " + e.getMessage(), errors);
}
}
}
if (p != null) p.report("> Processing lines");
//Check ids and add expression data
for(int i = 1; i < info.getFirstDataRow(); i++) in.readLine(); //Go to line where data starts
String line = null;
int n = info.getFirstDataRow() - 1;
int added = 0;
int worked = importWork / nrLines;
boolean maximumNotSet = true;
boolean minimumNotSet = true;
double maximum = 1; // Dummy value
double minimum = 1; // Dummy value
DecimalFormat nf = new DecimalFormat();
DecimalFormatSymbols dfs = nf.getDecimalFormatSymbols();
DecimalFormat df = new DecimalFormat();
if (info.digitIsDot())
{
dfs.setGroupingSeparator('.');
dfs.setDecimalSeparator(',');
}
while((line = in.readLine()) != null)
{
if(p != null && p.isCancelled())
{
result.close();
error.close();
return;
} //User pressed cancel
String[] data = line.split(info.getDelimiter(), headers.length);
n++;
if(n == info.headerRow) continue; //Don't add header row (very unlikely that this will happen)
if(data.length < headers.length) {
errors = reportError(info, error, "Number of columns in line " + n +
"doesn't match number of header columns",
errors);
continue;
}
if (p != null) p.setTaskName("Importing expression data - processing line " + n + "; " + errors + " exceptions");
//Check id and add data
String id = data[info.getIdColumn()].trim();
/*Set the system code to the one found in the dataset if there is a system code column,
* otherwise set the system code to the one selected (either by the user or by regular
* expressions.*/
DataSource ds;
if (info.getSyscodeColumn())
{
ds = DataSource.getBySystemCode(data[info.getCodeColumn()].trim());
}
else
{
ds = info.getDataSource();
}
Xref ref = new Xref (id, ds);
//Find the Ensembl genes for current gene
List<String> ensIds = currentGdb.ref2EnsIds(ref);
if(ensIds == null || ensIds.size() == 0) //No Ensembl gene found
{
errors = reportError(info, error, "Line " + n + ":\t" + ref +
"\tNo Ensembl gene found for this identifier", errors);
} else { //Gene maps to an Ensembl id, so add it
boolean success = true;
for( String ensId : ensIds) //For every Ensembl id add the data
{
for(int col : dataCols)
{
String value = data[col];
if(!info.isStringCol(col)
&& (value == null || value.equals(""))) {
value = "NaN";
}
//Determine maximum and minimum values.
try
{
double dNumber = nf.parse(value).doubleValue();
value = "" + dNumber;
if(maximumNotSet || dNumber>maximum)
{
maximum=dNumber;
maximumNotSet=false;
}
if(minimumNotSet || dNumber<minimum)
{
minimum=dNumber;
minimumNotSet=false;
}
}
catch (NumberFormatException e)
{
// we've got a number in a non-number column.
// safe to ignore
Logger.log.warn ("Number format exception in non-string column " + e.getMessage());
}
//End of determining maximum and minimum values. After the data has been read,
//maximum and minimum will have their correct values.
try
{
//TODO: use autocommit (false) and commit only every 1000 queries or so.
result.addExpr(
ref,
ensId,
Integer.toString(dataCols.indexOf(col)),
value,
added);
}
catch (Exception e)
{
errors = reportError(info, error, "Line " + n + ":\t" + line + "\n" +
"\tException: " + e.getMessage(), errors);
success = false;
}
}
}
if(success) added++;
}
if (p != null) p.worked(worked);
}
//Data is read and written to the database
//Writing maximum and minimum to ImportInformation
info.setMaximum(maximum);
info.setMinimum(minimum);
if (p != null) p.report(added + " genes were added succesfully to the expression dataset");
if(errors > 0)
{
if (p != null) p.report(errors + " exceptions occured, see file '" + errorFile + "' for details");
} else {
new File(errorFile).delete(); // If no errors were found, delete the error file
}
if (p != null) p.setTaskName("Closing database connection");
result.finalize();
if (p != null) p.worked(finalizeWork);
error.println("Time to create expression dataset: " + timer.stop());
error.close();
GexManager.getCurrent().setCurrentGex(result.getDbName(), false);
if (p != null) p.finished();
}
catch(Exception e)
{
if (p != null) p.report("Import aborted due to error: " + e.getMessage());
Logger.log.error("Expression data import error", e);
try
{
result.close();
}
catch (DataException f)
{ Logger.log.error ("Exception while aborting database", f); }
error.close();
}
}
|
diff --git a/src/org/flowvisor/message/actions/FVActionVirtualLanPriorityCodePoint.java b/src/org/flowvisor/message/actions/FVActionVirtualLanPriorityCodePoint.java
index 086f96d..4c7ef8f 100644
--- a/src/org/flowvisor/message/actions/FVActionVirtualLanPriorityCodePoint.java
+++ b/src/org/flowvisor/message/actions/FVActionVirtualLanPriorityCodePoint.java
@@ -1,49 +1,50 @@
package org.flowvisor.message.actions;
import java.util.Iterator;
import java.util.List;
import org.flowvisor.classifier.FVClassifier;
import org.flowvisor.exceptions.ActionDisallowedException;
import org.flowvisor.flows.FlowEntry;
import org.flowvisor.flows.SliceAction;
import org.flowvisor.log.FVLog;
import org.flowvisor.log.LogLevel;
import org.flowvisor.openflow.protocol.FVMatch;
import org.flowvisor.slicer.FVSlicer;
import org.openflow.protocol.OFMatch;
import org.openflow.protocol.OFError.OFBadActionCode;
import org.openflow.protocol.action.OFAction;
import org.openflow.protocol.action.OFActionVirtualLanPriorityCodePoint;
public class FVActionVirtualLanPriorityCodePoint extends
OFActionVirtualLanPriorityCodePoint implements SlicableAction {
@Override
public void slice(List<OFAction> approvedActions, OFMatch match,
FVClassifier fvClassifier, FVSlicer fvSlicer)
throws ActionDisallowedException {
FVMatch neoMatch = new FVMatch(match);
- match.setDataLayerVirtualLanPriorityCodePoint(this.virtualLanPriorityCodePoint);
+ neoMatch.setDataLayerVirtualLanPriorityCodePoint(this.virtualLanPriorityCodePoint);
List<FlowEntry> flowEntries = fvClassifier.getSwitchFlowMap().matches(fvClassifier.getDPID(), neoMatch);
for (FlowEntry fe : flowEntries) {
Iterator<OFAction> it = fe.getActionsList().iterator();
while (it.hasNext()) {
OFAction act = it.next();
if (act instanceof SliceAction) {
SliceAction action = (SliceAction) act;
if (action.getSliceName().equals(fvSlicer.getSliceName())) {
FVLog.log(LogLevel.DEBUG, fvSlicer, "Approving " + this +
" for " + match);
approvedActions.add(this);
+ return;
}
}
}
}
throw new ActionDisallowedException(
"Slice " + fvSlicer.getSliceName() + " may not rewrite vlan " +
"priority to " + this.getVirtualLanPriorityCodePoint(),
OFBadActionCode.OFPBAC_BAD_ARGUMENT);
}
}
| false | true | public void slice(List<OFAction> approvedActions, OFMatch match,
FVClassifier fvClassifier, FVSlicer fvSlicer)
throws ActionDisallowedException {
FVMatch neoMatch = new FVMatch(match);
match.setDataLayerVirtualLanPriorityCodePoint(this.virtualLanPriorityCodePoint);
List<FlowEntry> flowEntries = fvClassifier.getSwitchFlowMap().matches(fvClassifier.getDPID(), neoMatch);
for (FlowEntry fe : flowEntries) {
Iterator<OFAction> it = fe.getActionsList().iterator();
while (it.hasNext()) {
OFAction act = it.next();
if (act instanceof SliceAction) {
SliceAction action = (SliceAction) act;
if (action.getSliceName().equals(fvSlicer.getSliceName())) {
FVLog.log(LogLevel.DEBUG, fvSlicer, "Approving " + this +
" for " + match);
approvedActions.add(this);
}
}
}
}
throw new ActionDisallowedException(
"Slice " + fvSlicer.getSliceName() + " may not rewrite vlan " +
"priority to " + this.getVirtualLanPriorityCodePoint(),
OFBadActionCode.OFPBAC_BAD_ARGUMENT);
}
| public void slice(List<OFAction> approvedActions, OFMatch match,
FVClassifier fvClassifier, FVSlicer fvSlicer)
throws ActionDisallowedException {
FVMatch neoMatch = new FVMatch(match);
neoMatch.setDataLayerVirtualLanPriorityCodePoint(this.virtualLanPriorityCodePoint);
List<FlowEntry> flowEntries = fvClassifier.getSwitchFlowMap().matches(fvClassifier.getDPID(), neoMatch);
for (FlowEntry fe : flowEntries) {
Iterator<OFAction> it = fe.getActionsList().iterator();
while (it.hasNext()) {
OFAction act = it.next();
if (act instanceof SliceAction) {
SliceAction action = (SliceAction) act;
if (action.getSliceName().equals(fvSlicer.getSliceName())) {
FVLog.log(LogLevel.DEBUG, fvSlicer, "Approving " + this +
" for " + match);
approvedActions.add(this);
return;
}
}
}
}
throw new ActionDisallowedException(
"Slice " + fvSlicer.getSliceName() + " may not rewrite vlan " +
"priority to " + this.getVirtualLanPriorityCodePoint(),
OFBadActionCode.OFPBAC_BAD_ARGUMENT);
}
|
diff --git a/src/main/java/net/citizensnpcs/api/ai/SimpleGoalController.java b/src/main/java/net/citizensnpcs/api/ai/SimpleGoalController.java
index 8096ec4..ebf5796 100644
--- a/src/main/java/net/citizensnpcs/api/ai/SimpleGoalController.java
+++ b/src/main/java/net/citizensnpcs/api/ai/SimpleGoalController.java
@@ -1,178 +1,182 @@
package net.citizensnpcs.api.ai;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import net.citizensnpcs.api.CitizensAPI;
import org.bukkit.Bukkit;
import org.bukkit.event.HandlerList;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
public class SimpleGoalController implements GoalController {
private final List<Goal> executingGoals = Lists.newArrayList();
private int executingPriority = -1;
private Goal executingRootGoal;
private volatile boolean paused;
private final List<SimpleGoalEntry> possibleGoals = Lists.newArrayList();
private final GoalSelector selector = new SimpleGoalSelector();
@Override
public void addGoal(Goal goal, int priority) {
Preconditions.checkNotNull(goal, "goal cannot be null");
Preconditions.checkState(priority > 0 && priority < Integer.MAX_VALUE,
"priority must be greater than 0");
SimpleGoalEntry entry = new SimpleGoalEntry(goal, priority);
if (possibleGoals.contains(entry))
return;
possibleGoals.add(entry);
Collections.sort(possibleGoals);
}
private void addGoalToExecution(Goal goal) {
Bukkit.getPluginManager().registerEvents(goal, CitizensAPI.getPlugin());
executingGoals.add(goal);
}
@Override
public void clear() {
finishCurrentGoalExecution();
possibleGoals.clear();
}
private void finishCurrentGoalExecution() {
resetGoalList();
executingPriority = -1;
executingRootGoal = null;
}
@Override
public boolean isPaused() {
return paused;
}
@Override
public Iterator<GoalEntry> iterator() {
final Iterator<SimpleGoalEntry> itr = possibleGoals.iterator();
return new Iterator<GoalEntry>() {
GoalEntry cur;
@Override
public boolean hasNext() {
return itr.hasNext();
}
@Override
public GoalEntry next() {
return (cur = itr.next());
}
@Override
public void remove() {
itr.remove();
if (cur.getGoal() == executingRootGoal)
finishCurrentGoalExecution();
}
};
}
@Override
public void removeGoal(Goal goal) {
Preconditions.checkNotNull(goal, "goal cannot be null");
for (int j = 0; j < possibleGoals.size(); ++j) {
Goal test = possibleGoals.get(j).goal;
if (!test.equals(goal))
continue;
possibleGoals.remove(j--);
if (test == executingRootGoal)
finishCurrentGoalExecution();
}
}
private void resetGoalList() {
for (int i = 0; i < executingGoals.size(); ++i) {
Goal goal = executingGoals.remove(i--);
goal.reset();
HandlerList.unregisterAll(goal);
}
}
@Override
public void run() {
if (possibleGoals.isEmpty() || paused)
return;
trySelectGoal();
for (int i = 0; i < executingGoals.size(); ++i) {
executingGoals.get(i).run();
}
}
@Override
public void setPaused(boolean paused) {
this.paused = paused;
}
private void setupExecution(SimpleGoalEntry entry) {
finishCurrentGoalExecution();
executingPriority = entry.priority;
executingRootGoal = entry.goal;
addGoalToExecution(entry.goal);
}
private void trySelectGoal() {
int searchPriority = Math.min(executingPriority, 1);
for (int i = possibleGoals.size() - 1; i >= 0; --i) {
SimpleGoalEntry entry = possibleGoals.get(i);
if (searchPriority > entry.priority)
return;
if (entry.goal == executingRootGoal || !entry.goal.shouldExecute(selector))
continue;
+ if (i == 0) {
+ setupExecution(entry);
+ return;
+ }
for (int j = i - 1; j >= 0; --j) {
SimpleGoalEntry next = possibleGoals.get(j);
if (next.priority != entry.priority) {
int ran = (int) Math.floor(Math.random() * (i + 1) + (j + 1));
SimpleGoalEntry selected = possibleGoals.get(ran);
if (selected.priority != entry.priority) {
System.err.println("[Citizens]: bug - inform fullwall");
setupExecution(entry);
break;
}
setupExecution(selected);
break;
}
}
return;
}
}
public class SimpleGoalSelector implements GoalSelector {
@Override
public void finish() {
finishCurrentGoalExecution();
}
@Override
public void finishAndRemove() {
Goal toRemove = executingRootGoal;
finish();
if (toRemove != null)
removeGoal(toRemove);
}
@Override
public void select(Goal goal) {
resetGoalList();
addGoalToExecution(goal);
}
@Override
public void selectAdditional(Goal... goals) {
for (Goal goal : goals) {
addGoalToExecution(goal);
}
}
}
}
| true | true | private void trySelectGoal() {
int searchPriority = Math.min(executingPriority, 1);
for (int i = possibleGoals.size() - 1; i >= 0; --i) {
SimpleGoalEntry entry = possibleGoals.get(i);
if (searchPriority > entry.priority)
return;
if (entry.goal == executingRootGoal || !entry.goal.shouldExecute(selector))
continue;
for (int j = i - 1; j >= 0; --j) {
SimpleGoalEntry next = possibleGoals.get(j);
if (next.priority != entry.priority) {
int ran = (int) Math.floor(Math.random() * (i + 1) + (j + 1));
SimpleGoalEntry selected = possibleGoals.get(ran);
if (selected.priority != entry.priority) {
System.err.println("[Citizens]: bug - inform fullwall");
setupExecution(entry);
break;
}
setupExecution(selected);
break;
}
}
return;
}
}
| private void trySelectGoal() {
int searchPriority = Math.min(executingPriority, 1);
for (int i = possibleGoals.size() - 1; i >= 0; --i) {
SimpleGoalEntry entry = possibleGoals.get(i);
if (searchPriority > entry.priority)
return;
if (entry.goal == executingRootGoal || !entry.goal.shouldExecute(selector))
continue;
if (i == 0) {
setupExecution(entry);
return;
}
for (int j = i - 1; j >= 0; --j) {
SimpleGoalEntry next = possibleGoals.get(j);
if (next.priority != entry.priority) {
int ran = (int) Math.floor(Math.random() * (i + 1) + (j + 1));
SimpleGoalEntry selected = possibleGoals.get(ran);
if (selected.priority != entry.priority) {
System.err.println("[Citizens]: bug - inform fullwall");
setupExecution(entry);
break;
}
setupExecution(selected);
break;
}
}
return;
}
}
|
diff --git a/src/com/android/settings/inputmethod/InputMethodAndSubtypeUtil.java b/src/com/android/settings/inputmethod/InputMethodAndSubtypeUtil.java
index 80030418a..362fbb5bd 100644
--- a/src/com/android/settings/inputmethod/InputMethodAndSubtypeUtil.java
+++ b/src/com/android/settings/inputmethod/InputMethodAndSubtypeUtil.java
@@ -1,339 +1,345 @@
/*
* Copyright (C) 2010 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.settings.inputmethod;
import com.android.settings.SettingsPreferenceFragment;
import android.content.ContentResolver;
import android.content.pm.ApplicationInfo;
import android.preference.CheckBoxPreference;
import android.preference.Preference;
import android.preference.PreferenceScreen;
import android.provider.Settings;
import android.provider.Settings.SettingNotFoundException;
import android.text.TextUtils;
import android.util.Log;
import android.view.inputmethod.InputMethodInfo;
import android.view.inputmethod.InputMethodSubtype;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
public class InputMethodAndSubtypeUtil {
private static final boolean DEBUG = false;
static final String TAG = "InputMethdAndSubtypeUtil";
private static final char INPUT_METHOD_SEPARATER = ':';
private static final char INPUT_METHOD_SUBTYPE_SEPARATER = ';';
private static final int NOT_A_SUBTYPE_ID = -1;
private static final TextUtils.SimpleStringSplitter sStringInputMethodSplitter
= new TextUtils.SimpleStringSplitter(INPUT_METHOD_SEPARATER);
private static final TextUtils.SimpleStringSplitter sStringInputMethodSubtypeSplitter
= new TextUtils.SimpleStringSplitter(INPUT_METHOD_SUBTYPE_SEPARATER);
private static void buildEnabledInputMethodsString(
StringBuilder builder, String imi, HashSet<String> subtypes) {
builder.append(imi);
// Inputmethod and subtypes are saved in the settings as follows:
// ime0;subtype0;subtype1:ime1;subtype0:ime2:ime3;subtype0;subtype1
for (String subtypeId: subtypes) {
builder.append(INPUT_METHOD_SUBTYPE_SEPARATER).append(subtypeId);
}
}
public static void buildInputMethodsAndSubtypesString(
StringBuilder builder, HashMap<String, HashSet<String>> imsList) {
boolean needsAppendSeparator = false;
for (String imi: imsList.keySet()) {
if (needsAppendSeparator) {
builder.append(INPUT_METHOD_SEPARATER);
} else {
needsAppendSeparator = true;
}
buildEnabledInputMethodsString(builder, imi, imsList.get(imi));
}
}
public static void buildDisabledSystemInputMethods(
StringBuilder builder, HashSet<String> imes) {
boolean needsAppendSeparator = false;
for (String ime: imes) {
if (needsAppendSeparator) {
builder.append(INPUT_METHOD_SEPARATER);
} else {
needsAppendSeparator = true;
}
builder.append(ime);
}
}
private static int getInputMethodSubtypeSelected(ContentResolver resolver) {
try {
return Settings.Secure.getInt(resolver,
Settings.Secure.SELECTED_INPUT_METHOD_SUBTYPE);
} catch (SettingNotFoundException e) {
return NOT_A_SUBTYPE_ID;
}
}
private static boolean isInputMethodSubtypeSelected(ContentResolver resolver) {
return getInputMethodSubtypeSelected(resolver) != NOT_A_SUBTYPE_ID;
}
private static void putSelectedInputMethodSubtype(ContentResolver resolver, int hashCode) {
Settings.Secure.putInt(resolver, Settings.Secure.SELECTED_INPUT_METHOD_SUBTYPE, hashCode);
}
// Needs to modify InputMethodManageService if you want to change the format of saved string.
private static HashMap<String, HashSet<String>> getEnabledInputMethodsAndSubtypeList(
ContentResolver resolver) {
final String enabledInputMethodsStr = Settings.Secure.getString(
resolver, Settings.Secure.ENABLED_INPUT_METHODS);
HashMap<String, HashSet<String>> imsList
= new HashMap<String, HashSet<String>>();
if (DEBUG) {
Log.d(TAG, "--- Load enabled input methods: " + enabledInputMethodsStr);
}
if (TextUtils.isEmpty(enabledInputMethodsStr)) {
return imsList;
}
sStringInputMethodSplitter.setString(enabledInputMethodsStr);
while (sStringInputMethodSplitter.hasNext()) {
String nextImsStr = sStringInputMethodSplitter.next();
sStringInputMethodSubtypeSplitter.setString(nextImsStr);
if (sStringInputMethodSubtypeSplitter.hasNext()) {
HashSet<String> subtypeHashes = new HashSet<String>();
// The first element is ime id.
String imeId = sStringInputMethodSubtypeSplitter.next();
while (sStringInputMethodSubtypeSplitter.hasNext()) {
subtypeHashes.add(sStringInputMethodSubtypeSplitter.next());
}
imsList.put(imeId, subtypeHashes);
}
}
return imsList;
}
private static HashSet<String> getDisabledSystemIMEs(ContentResolver resolver) {
HashSet<String> set = new HashSet<String>();
String disabledIMEsStr = Settings.Secure.getString(
resolver, Settings.Secure.DISABLED_SYSTEM_INPUT_METHODS);
if (TextUtils.isEmpty(disabledIMEsStr)) {
return set;
}
sStringInputMethodSplitter.setString(disabledIMEsStr);
while(sStringInputMethodSplitter.hasNext()) {
set.add(sStringInputMethodSplitter.next());
}
return set;
}
public static void saveInputMethodSubtypeList(SettingsPreferenceFragment context,
ContentResolver resolver, List<InputMethodInfo> inputMethodInfos,
boolean hasHardKeyboard) {
String currentInputMethodId = Settings.Secure.getString(resolver,
Settings.Secure.DEFAULT_INPUT_METHOD);
final int selectedInputMethodSubtype = getInputMethodSubtypeSelected(resolver);
HashMap<String, HashSet<String>> enabledIMEAndSubtypesMap =
getEnabledInputMethodsAndSubtypeList(resolver);
HashSet<String> disabledSystemIMEs = getDisabledSystemIMEs(resolver);
final boolean onlyOneIME = inputMethodInfos.size() == 1;
- boolean existsSelectedSubtype = false;
+ boolean needsToResetSelectedSubtype = false;
for (InputMethodInfo imi : inputMethodInfos) {
final String imiId = imi.getId();
Preference pref = context.findPreference(imiId);
if (pref == null) continue;
// In the Configure input method screen or in the subtype enabler screen.
// pref is instance of CheckBoxPreference in the Configure input method screen.
final boolean isImeChecked = (pref instanceof CheckBoxPreference) ?
((CheckBoxPreference) pref).isChecked()
: enabledIMEAndSubtypesMap.containsKey(imiId);
boolean isCurrentInputMethod = imiId.equals(currentInputMethodId);
boolean systemIme = isSystemIme(imi);
if (((onlyOneIME || systemIme) && !hasHardKeyboard) || isImeChecked) {
if (!enabledIMEAndSubtypesMap.containsKey(imiId)) {
// imiId has just been enabled
enabledIMEAndSubtypesMap.put(imiId, new HashSet<String>());
}
HashSet<String> subtypesSet = enabledIMEAndSubtypesMap.get(imiId);
- boolean subtypeCleared = false;
+ boolean subtypePrefFound = false;
final int subtypeCount = imi.getSubtypeCount();
for (int i = 0; i < subtypeCount; ++i) {
InputMethodSubtype subtype = imi.getSubtypeAt(i);
final String subtypeHashCodeStr = String.valueOf(subtype.hashCode());
CheckBoxPreference subtypePref = (CheckBoxPreference) context.findPreference(
imiId + subtypeHashCodeStr);
// In the Configure input method screen which does not have subtype preferences.
if (subtypePref == null) continue;
- // Once subtype checkbox is found, subtypeSet needs to be cleared.
- // Because of system change, hashCode value could have been changed.
- if (!subtypeCleared) {
+ if (!subtypePrefFound) {
+ // Once subtype checkbox is found, subtypeSet needs to be cleared.
+ // Because of system change, hashCode value could have been changed.
subtypesSet.clear();
- subtypeCleared = true;
+ // If selected subtype preference is disabled, needs to reset.
+ needsToResetSelectedSubtype = true;
+ subtypePrefFound = true;
}
if (subtypePref.isChecked()) {
subtypesSet.add(subtypeHashCodeStr);
if (isCurrentInputMethod) {
if (selectedInputMethodSubtype == subtype.hashCode()) {
- existsSelectedSubtype = true;
+ // Selected subtype is still enabled, there is no need to reset
+ // selected subtype.
+ needsToResetSelectedSubtype = false;
}
}
} else {
subtypesSet.remove(subtypeHashCodeStr);
}
}
} else {
enabledIMEAndSubtypesMap.remove(imiId);
if (isCurrentInputMethod) {
// We are processing the current input method, but found that it's not enabled.
// This means that the current input method has been uninstalled.
// If currentInputMethod is already uninstalled, InputMethodManagerService will
// find the applicable IME from the history and the system locale.
if (DEBUG) {
Log.d(TAG, "Current IME was uninstalled or disabled.");
}
currentInputMethodId = null;
}
}
// If it's a disabled system ime, add it to the disabled list so that it
// doesn't get enabled automatically on any changes to the package list
if (systemIme && hasHardKeyboard) {
if (disabledSystemIMEs.contains(imiId)) {
if (isImeChecked) {
disabledSystemIMEs.remove(imiId);
}
} else {
if (!isImeChecked) {
disabledSystemIMEs.add(imiId);
}
}
}
}
StringBuilder builder = new StringBuilder();
buildInputMethodsAndSubtypesString(builder, enabledIMEAndSubtypesMap);
StringBuilder disabledSysImesBuilder = new StringBuilder();
buildDisabledSystemInputMethods(disabledSysImesBuilder, disabledSystemIMEs);
if (DEBUG) {
Log.d(TAG, "--- Save enabled inputmethod settings. :" + builder.toString());
Log.d(TAG, "--- Save disable system inputmethod settings. :"
+ disabledSysImesBuilder.toString());
Log.d(TAG, "--- Save default inputmethod settings. :" + currentInputMethodId);
+ Log.d(TAG, "--- Needs to reset the selected subtype :" + needsToResetSelectedSubtype);
+ Log.d(TAG, "--- Subtype is selected :" + isInputMethodSubtypeSelected(resolver));
}
// Redefines SelectedSubtype when all subtypes are unchecked or there is no subtype
// selected. And if the selected subtype of the current input method was disabled,
// We should reset the selected input method's subtype.
- if (!existsSelectedSubtype || !isInputMethodSubtypeSelected(resolver)) {
+ if (needsToResetSelectedSubtype || !isInputMethodSubtypeSelected(resolver)) {
if (DEBUG) {
Log.d(TAG, "--- Reset inputmethod subtype because it's not defined.");
}
putSelectedInputMethodSubtype(resolver, NOT_A_SUBTYPE_ID);
}
Settings.Secure.putString(resolver,
Settings.Secure.ENABLED_INPUT_METHODS, builder.toString());
if (disabledSysImesBuilder.length() > 0) {
Settings.Secure.putString(resolver, Settings.Secure.DISABLED_SYSTEM_INPUT_METHODS,
disabledSysImesBuilder.toString());
}
// If the current input method is unset, InputMethodManagerService will find the applicable
// IME from the history and the system locale.
Settings.Secure.putString(resolver, Settings.Secure.DEFAULT_INPUT_METHOD,
currentInputMethodId != null ? currentInputMethodId : "");
}
public static void loadInputMethodSubtypeList(
SettingsPreferenceFragment context, ContentResolver resolver,
List<InputMethodInfo> inputMethodInfos,
final Map<String, List<Preference>> inputMethodPrefsMap) {
HashMap<String, HashSet<String>> enabledSubtypes =
getEnabledInputMethodsAndSubtypeList(resolver);
for (InputMethodInfo imi : inputMethodInfos) {
final String imiId = imi.getId();
Preference pref = context.findPreference(imiId);
if (pref != null && pref instanceof CheckBoxPreference) {
CheckBoxPreference checkBoxPreference = (CheckBoxPreference) pref;
boolean isEnabled = enabledSubtypes.containsKey(imiId);
checkBoxPreference.setChecked(isEnabled);
if (inputMethodPrefsMap != null) {
for (Preference childPref: inputMethodPrefsMap.get(imiId)) {
childPref.setEnabled(isEnabled);
}
}
setSubtypesPreferenceEnabled(context, inputMethodInfos, imiId, isEnabled);
updateSubtypesPreferenceChecked(context, inputMethodInfos, enabledSubtypes);
}
}
}
public static void setSubtypesPreferenceEnabled(SettingsPreferenceFragment context,
List<InputMethodInfo> inputMethodProperties, String id, boolean enabled) {
PreferenceScreen preferenceScreen = context.getPreferenceScreen();
for (InputMethodInfo imi : inputMethodProperties) {
if (id.equals(imi.getId())) {
final int subtypeCount = imi.getSubtypeCount();
for (int i = 0; i < subtypeCount; ++i) {
InputMethodSubtype subtype = imi.getSubtypeAt(i);
CheckBoxPreference pref = (CheckBoxPreference) preferenceScreen.findPreference(
id + subtype.hashCode());
if (pref != null) {
pref.setEnabled(enabled);
}
}
}
}
}
public static void updateSubtypesPreferenceChecked(SettingsPreferenceFragment context,
List<InputMethodInfo> inputMethodProperties,
HashMap<String, HashSet<String>> enabledSubtypes) {
PreferenceScreen preferenceScreen = context.getPreferenceScreen();
for (InputMethodInfo imi : inputMethodProperties) {
String id = imi.getId();
HashSet<String> enabledSubtypesSet = enabledSubtypes.get(id);
final int subtypeCount = imi.getSubtypeCount();
for (int i = 0; i < subtypeCount; ++i) {
InputMethodSubtype subtype = imi.getSubtypeAt(i);
String hashCode = String.valueOf(subtype.hashCode());
if (DEBUG) {
Log.d(TAG, "--- Set checked state: " + "id" + ", " + hashCode + ", "
+ enabledSubtypesSet.contains(hashCode));
}
CheckBoxPreference pref = (CheckBoxPreference) preferenceScreen.findPreference(
id + hashCode);
if (pref != null) {
pref.setChecked(enabledSubtypesSet.contains(hashCode));
}
}
}
}
public static boolean isSystemIme(InputMethodInfo property) {
return (property.getServiceInfo().applicationInfo.flags
& ApplicationInfo.FLAG_SYSTEM) != 0;
}
}
| false | true | public static void saveInputMethodSubtypeList(SettingsPreferenceFragment context,
ContentResolver resolver, List<InputMethodInfo> inputMethodInfos,
boolean hasHardKeyboard) {
String currentInputMethodId = Settings.Secure.getString(resolver,
Settings.Secure.DEFAULT_INPUT_METHOD);
final int selectedInputMethodSubtype = getInputMethodSubtypeSelected(resolver);
HashMap<String, HashSet<String>> enabledIMEAndSubtypesMap =
getEnabledInputMethodsAndSubtypeList(resolver);
HashSet<String> disabledSystemIMEs = getDisabledSystemIMEs(resolver);
final boolean onlyOneIME = inputMethodInfos.size() == 1;
boolean existsSelectedSubtype = false;
for (InputMethodInfo imi : inputMethodInfos) {
final String imiId = imi.getId();
Preference pref = context.findPreference(imiId);
if (pref == null) continue;
// In the Configure input method screen or in the subtype enabler screen.
// pref is instance of CheckBoxPreference in the Configure input method screen.
final boolean isImeChecked = (pref instanceof CheckBoxPreference) ?
((CheckBoxPreference) pref).isChecked()
: enabledIMEAndSubtypesMap.containsKey(imiId);
boolean isCurrentInputMethod = imiId.equals(currentInputMethodId);
boolean systemIme = isSystemIme(imi);
if (((onlyOneIME || systemIme) && !hasHardKeyboard) || isImeChecked) {
if (!enabledIMEAndSubtypesMap.containsKey(imiId)) {
// imiId has just been enabled
enabledIMEAndSubtypesMap.put(imiId, new HashSet<String>());
}
HashSet<String> subtypesSet = enabledIMEAndSubtypesMap.get(imiId);
boolean subtypeCleared = false;
final int subtypeCount = imi.getSubtypeCount();
for (int i = 0; i < subtypeCount; ++i) {
InputMethodSubtype subtype = imi.getSubtypeAt(i);
final String subtypeHashCodeStr = String.valueOf(subtype.hashCode());
CheckBoxPreference subtypePref = (CheckBoxPreference) context.findPreference(
imiId + subtypeHashCodeStr);
// In the Configure input method screen which does not have subtype preferences.
if (subtypePref == null) continue;
// Once subtype checkbox is found, subtypeSet needs to be cleared.
// Because of system change, hashCode value could have been changed.
if (!subtypeCleared) {
subtypesSet.clear();
subtypeCleared = true;
}
if (subtypePref.isChecked()) {
subtypesSet.add(subtypeHashCodeStr);
if (isCurrentInputMethod) {
if (selectedInputMethodSubtype == subtype.hashCode()) {
existsSelectedSubtype = true;
}
}
} else {
subtypesSet.remove(subtypeHashCodeStr);
}
}
} else {
enabledIMEAndSubtypesMap.remove(imiId);
if (isCurrentInputMethod) {
// We are processing the current input method, but found that it's not enabled.
// This means that the current input method has been uninstalled.
// If currentInputMethod is already uninstalled, InputMethodManagerService will
// find the applicable IME from the history and the system locale.
if (DEBUG) {
Log.d(TAG, "Current IME was uninstalled or disabled.");
}
currentInputMethodId = null;
}
}
// If it's a disabled system ime, add it to the disabled list so that it
// doesn't get enabled automatically on any changes to the package list
if (systemIme && hasHardKeyboard) {
if (disabledSystemIMEs.contains(imiId)) {
if (isImeChecked) {
disabledSystemIMEs.remove(imiId);
}
} else {
if (!isImeChecked) {
disabledSystemIMEs.add(imiId);
}
}
}
}
StringBuilder builder = new StringBuilder();
buildInputMethodsAndSubtypesString(builder, enabledIMEAndSubtypesMap);
StringBuilder disabledSysImesBuilder = new StringBuilder();
buildDisabledSystemInputMethods(disabledSysImesBuilder, disabledSystemIMEs);
if (DEBUG) {
Log.d(TAG, "--- Save enabled inputmethod settings. :" + builder.toString());
Log.d(TAG, "--- Save disable system inputmethod settings. :"
+ disabledSysImesBuilder.toString());
Log.d(TAG, "--- Save default inputmethod settings. :" + currentInputMethodId);
}
// Redefines SelectedSubtype when all subtypes are unchecked or there is no subtype
// selected. And if the selected subtype of the current input method was disabled,
// We should reset the selected input method's subtype.
if (!existsSelectedSubtype || !isInputMethodSubtypeSelected(resolver)) {
if (DEBUG) {
Log.d(TAG, "--- Reset inputmethod subtype because it's not defined.");
}
putSelectedInputMethodSubtype(resolver, NOT_A_SUBTYPE_ID);
}
Settings.Secure.putString(resolver,
Settings.Secure.ENABLED_INPUT_METHODS, builder.toString());
if (disabledSysImesBuilder.length() > 0) {
Settings.Secure.putString(resolver, Settings.Secure.DISABLED_SYSTEM_INPUT_METHODS,
disabledSysImesBuilder.toString());
}
// If the current input method is unset, InputMethodManagerService will find the applicable
// IME from the history and the system locale.
Settings.Secure.putString(resolver, Settings.Secure.DEFAULT_INPUT_METHOD,
currentInputMethodId != null ? currentInputMethodId : "");
}
| public static void saveInputMethodSubtypeList(SettingsPreferenceFragment context,
ContentResolver resolver, List<InputMethodInfo> inputMethodInfos,
boolean hasHardKeyboard) {
String currentInputMethodId = Settings.Secure.getString(resolver,
Settings.Secure.DEFAULT_INPUT_METHOD);
final int selectedInputMethodSubtype = getInputMethodSubtypeSelected(resolver);
HashMap<String, HashSet<String>> enabledIMEAndSubtypesMap =
getEnabledInputMethodsAndSubtypeList(resolver);
HashSet<String> disabledSystemIMEs = getDisabledSystemIMEs(resolver);
final boolean onlyOneIME = inputMethodInfos.size() == 1;
boolean needsToResetSelectedSubtype = false;
for (InputMethodInfo imi : inputMethodInfos) {
final String imiId = imi.getId();
Preference pref = context.findPreference(imiId);
if (pref == null) continue;
// In the Configure input method screen or in the subtype enabler screen.
// pref is instance of CheckBoxPreference in the Configure input method screen.
final boolean isImeChecked = (pref instanceof CheckBoxPreference) ?
((CheckBoxPreference) pref).isChecked()
: enabledIMEAndSubtypesMap.containsKey(imiId);
boolean isCurrentInputMethod = imiId.equals(currentInputMethodId);
boolean systemIme = isSystemIme(imi);
if (((onlyOneIME || systemIme) && !hasHardKeyboard) || isImeChecked) {
if (!enabledIMEAndSubtypesMap.containsKey(imiId)) {
// imiId has just been enabled
enabledIMEAndSubtypesMap.put(imiId, new HashSet<String>());
}
HashSet<String> subtypesSet = enabledIMEAndSubtypesMap.get(imiId);
boolean subtypePrefFound = false;
final int subtypeCount = imi.getSubtypeCount();
for (int i = 0; i < subtypeCount; ++i) {
InputMethodSubtype subtype = imi.getSubtypeAt(i);
final String subtypeHashCodeStr = String.valueOf(subtype.hashCode());
CheckBoxPreference subtypePref = (CheckBoxPreference) context.findPreference(
imiId + subtypeHashCodeStr);
// In the Configure input method screen which does not have subtype preferences.
if (subtypePref == null) continue;
if (!subtypePrefFound) {
// Once subtype checkbox is found, subtypeSet needs to be cleared.
// Because of system change, hashCode value could have been changed.
subtypesSet.clear();
// If selected subtype preference is disabled, needs to reset.
needsToResetSelectedSubtype = true;
subtypePrefFound = true;
}
if (subtypePref.isChecked()) {
subtypesSet.add(subtypeHashCodeStr);
if (isCurrentInputMethod) {
if (selectedInputMethodSubtype == subtype.hashCode()) {
// Selected subtype is still enabled, there is no need to reset
// selected subtype.
needsToResetSelectedSubtype = false;
}
}
} else {
subtypesSet.remove(subtypeHashCodeStr);
}
}
} else {
enabledIMEAndSubtypesMap.remove(imiId);
if (isCurrentInputMethod) {
// We are processing the current input method, but found that it's not enabled.
// This means that the current input method has been uninstalled.
// If currentInputMethod is already uninstalled, InputMethodManagerService will
// find the applicable IME from the history and the system locale.
if (DEBUG) {
Log.d(TAG, "Current IME was uninstalled or disabled.");
}
currentInputMethodId = null;
}
}
// If it's a disabled system ime, add it to the disabled list so that it
// doesn't get enabled automatically on any changes to the package list
if (systemIme && hasHardKeyboard) {
if (disabledSystemIMEs.contains(imiId)) {
if (isImeChecked) {
disabledSystemIMEs.remove(imiId);
}
} else {
if (!isImeChecked) {
disabledSystemIMEs.add(imiId);
}
}
}
}
StringBuilder builder = new StringBuilder();
buildInputMethodsAndSubtypesString(builder, enabledIMEAndSubtypesMap);
StringBuilder disabledSysImesBuilder = new StringBuilder();
buildDisabledSystemInputMethods(disabledSysImesBuilder, disabledSystemIMEs);
if (DEBUG) {
Log.d(TAG, "--- Save enabled inputmethod settings. :" + builder.toString());
Log.d(TAG, "--- Save disable system inputmethod settings. :"
+ disabledSysImesBuilder.toString());
Log.d(TAG, "--- Save default inputmethod settings. :" + currentInputMethodId);
Log.d(TAG, "--- Needs to reset the selected subtype :" + needsToResetSelectedSubtype);
Log.d(TAG, "--- Subtype is selected :" + isInputMethodSubtypeSelected(resolver));
}
// Redefines SelectedSubtype when all subtypes are unchecked or there is no subtype
// selected. And if the selected subtype of the current input method was disabled,
// We should reset the selected input method's subtype.
if (needsToResetSelectedSubtype || !isInputMethodSubtypeSelected(resolver)) {
if (DEBUG) {
Log.d(TAG, "--- Reset inputmethod subtype because it's not defined.");
}
putSelectedInputMethodSubtype(resolver, NOT_A_SUBTYPE_ID);
}
Settings.Secure.putString(resolver,
Settings.Secure.ENABLED_INPUT_METHODS, builder.toString());
if (disabledSysImesBuilder.length() > 0) {
Settings.Secure.putString(resolver, Settings.Secure.DISABLED_SYSTEM_INPUT_METHODS,
disabledSysImesBuilder.toString());
}
// If the current input method is unset, InputMethodManagerService will find the applicable
// IME from the history and the system locale.
Settings.Secure.putString(resolver, Settings.Secure.DEFAULT_INPUT_METHOD,
currentInputMethodId != null ? currentInputMethodId : "");
}
|
diff --git a/modules/resin/src/com/caucho/log/handler/EventHandler.java b/modules/resin/src/com/caucho/log/handler/EventHandler.java
index 154e298f7..da86dccd0 100644
--- a/modules/resin/src/com/caucho/log/handler/EventHandler.java
+++ b/modules/resin/src/com/caucho/log/handler/EventHandler.java
@@ -1,96 +1,96 @@
/*
* Copyright (c) 1998-2008 Caucho Technology -- all rights reserved
*
* This file is part of Resin(R) Open Source
*
* Each copy or derived work must preserve the copyright notice and this
* notice unmodified.
*
* Resin Open Source 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.
*
* Resin Open Source 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, or any warranty
* of NON-INFRINGEMENT. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License
* along with Resin Open Source; if not, write to the
*
* Free Software Foundation, Inc.
* 59 Temple Place, Suite 330
* Boston, MA 02111-1307 USA
*
* @author Scott Ferguson
*/
package com.caucho.log.handler;
import com.caucho.config.ConfigException;
import com.caucho.config.types.*;
import com.caucho.log.*;
import com.caucho.util.L10N;
import com.caucho.vfs.*;
import com.caucho.webbeans.manager.*;
import javax.annotation.PostConstruct;
import javax.management.*;
import javax.webbeans.*;
import javax.jms.*;
import java.io.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.logging.Logger;
import java.util.logging.LogRecord;
import java.util.logging.Level;
import java.util.logging.Filter;
import java.util.logging.Formatter;
import java.util.logging.Handler;
/**
* raises a LogRecord as an event
*/
public class EventHandler extends Handler {
private static final Logger log
= Logger.getLogger(EventHandler.class.getName());
private static final L10N L = new L10N(EventHandler.class);
private WebBeansContainer _webBeans = WebBeansContainer.create();
/**
* Publishes the record.
*/
public void publish(LogRecord record)
{
if (record.getLevel().intValue() < getLevel().intValue())
return;
Filter filter = getFilter();
if (filter != null && ! filter.isLoggable(record))
return;
- _webBeans.raiseEvent(record);
+ _webBeans.fireEvent(record);
}
/**
* Flushes the buffer.
*/
public void flush()
{
}
/**
* Closes the handler.
*/
public void close()
{
}
public String toString()
{
return getClass().getSimpleName() + "[]";
}
}
| true | true | public void publish(LogRecord record)
{
if (record.getLevel().intValue() < getLevel().intValue())
return;
Filter filter = getFilter();
if (filter != null && ! filter.isLoggable(record))
return;
_webBeans.raiseEvent(record);
}
| public void publish(LogRecord record)
{
if (record.getLevel().intValue() < getLevel().intValue())
return;
Filter filter = getFilter();
if (filter != null && ! filter.isLoggable(record))
return;
_webBeans.fireEvent(record);
}
|
diff --git a/extrabiomes/src/extrabiomes/plugin/trees/Tree.java b/extrabiomes/src/extrabiomes/plugin/trees/Tree.java
index c59b0edc..2b4e2da0 100644
--- a/extrabiomes/src/extrabiomes/plugin/trees/Tree.java
+++ b/extrabiomes/src/extrabiomes/plugin/trees/Tree.java
@@ -1,165 +1,165 @@
/**
* This mod is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license
* located in /MMPL-1.0.txt
*/
package extrabiomes.plugin.trees;
import static extrabiomes.trees.TreeBlocks.Type.ACACIA;
import static extrabiomes.trees.TreeBlocks.Type.BROWN;
import static extrabiomes.trees.TreeBlocks.Type.FIR;
import static extrabiomes.trees.TreeBlocks.Type.ORANGE;
import static extrabiomes.trees.TreeBlocks.Type.PURPLE;
import static extrabiomes.trees.TreeBlocks.Type.REDWOOD;
import static extrabiomes.trees.TreeBlocks.Type.YELLOW;
import java.io.File;
import java.util.logging.Level;
import net.minecraft.src.Block;
import net.minecraft.src.ItemStack;
import net.minecraftforge.common.Configuration;
import com.google.common.base.Optional;
import cpw.mods.fml.common.Mod;
import cpw.mods.fml.common.Mod.Init;
import cpw.mods.fml.common.Mod.Instance;
import cpw.mods.fml.common.Mod.PreInit;
import cpw.mods.fml.common.SidedProxy;
import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import cpw.mods.fml.common.network.NetworkMod;
import extrabiomes.CommonProxy;
import extrabiomes.ExtrabiomesLog;
import extrabiomes.trees.TreeBlocks;
@Mod(modid = "EBXLTree", name = "ExtrabiomesXL Custom Trees Plugin", version = "3.0")
@NetworkMod(clientSideRequired = true, serverSideRequired = false)
public class Tree {
@SidedProxy(clientSide = "extrabiomes.client.ClientProxy", serverSide = "extrabiomes.CommonProxy")
public static CommonProxy proxy;
@Instance("EBXLTree")
public static Tree instance;
private static int autumnLeavesID;
private static int greenLeavesID;
private static int saplingID;
private static Optional<Block> autumnLeaves = Optional.absent();
private static Optional<Block> greenLeaves = Optional.absent();
static Optional<Block> sapling = Optional.absent();
@Init
public static void init(FMLInitializationEvent event) {
proxy.registerRenderInformation();
if (isAutumnLeavesEnabled()) {
autumnLeaves = Optional.of(new BlockAutumnLeaves(
autumnLeavesID).setBlockName("autumnleaves"));
proxy.registerBlock(autumnLeaves,
extrabiomes.ItemCustomLeaves.class);
for (final AutumnLeafType type : AutumnLeafType.values())
proxy.addName(
new ItemStack(autumnLeaves.get(), 1, type
.metadata()), type.itemName());
TreeBlocks.setBlocks(BROWN, Block.wood.blockID, 0,
autumnLeavesID, AutumnLeafType.BROWN.metadata());
TreeBlocks.setBlocks(ORANGE, Block.wood.blockID, 0,
autumnLeavesID, AutumnLeafType.ORANGE.metadata());
TreeBlocks.setBlocks(PURPLE, Block.wood.blockID, 0,
autumnLeavesID, AutumnLeafType.PURPLE.metadata());
TreeBlocks.setBlocks(YELLOW, Block.wood.blockID, 0,
autumnLeavesID, AutumnLeafType.YELLOW.metadata());
}
if (isGreenLeavesEnabled()) {
- greenLeaves = Optional.of(new BlockAutumnLeaves(
+ greenLeaves = Optional.of(new BlockGreenLeaves(
greenLeavesID).setBlockName("greenleaves"));
proxy.registerBlock(greenLeaves,
extrabiomes.ItemCustomLeaves.class);
for (final GreenLeafType type : GreenLeafType.values())
proxy.addName(
new ItemStack(greenLeaves.get(), 1, type
.metadata()), type.itemName());
TreeBlocks.setBlocks(FIR, Block.wood.blockID, 0,
- autumnLeavesID, GreenLeafType.FIR.metadata());
+ greenLeavesID, GreenLeafType.FIR.metadata());
TreeBlocks.setBlocks(REDWOOD, Block.wood.blockID, 0,
- autumnLeavesID, GreenLeafType.REDWOOD.metadata());
+ greenLeavesID, GreenLeafType.REDWOOD.metadata());
TreeBlocks.setBlocks(ACACIA, Block.wood.blockID, 0,
- autumnLeavesID, GreenLeafType.ACACIA.metadata());
+ greenLeavesID, GreenLeafType.ACACIA.metadata());
}
if (isSaplingEnabled()) {
- sapling = Optional.of(new BlockAutumnLeaves(saplingID)
+ sapling = Optional.of(new BlockCustomSapling(saplingID)
.setBlockName("sapling"));
proxy.registerBlock(sapling,
extrabiomes.utility.MultiItemBlock.class);
for (final SaplingType type : SaplingType.values())
proxy.addName(
new ItemStack(sapling.get(), 1, type.metadata()),
type.itemName());
proxy.registerFuelHandler(new FuelHandler(saplingID));
}
}
public static boolean isAutumnLeavesEnabled() {
return 0 < autumnLeavesID;
}
public static boolean isGreenLeavesEnabled() {
return 0 < greenLeavesID;
}
public static boolean isSaplingEnabled() {
return 0 < saplingID;
}
@PreInit
public static void preInit(FMLPreInitializationEvent event) {
ExtrabiomesLog.configureLogging();
final Configuration cfg = new Configuration(new File(
event.getModConfigurationDirectory(),
"/extrabiomes/extrabiomes.cfg"));
try {
cfg.load();
autumnLeavesID = cfg.getOrCreateBlockIdProperty(
"autumnleaves.id", 150).getInt(0);
if (!isAutumnLeavesEnabled())
ExtrabiomesLog
.info("autumnleaves.id = 0, so autumn leaves have been disabled.");
greenLeavesID = cfg.getOrCreateBlockIdProperty(
"greenleaves.id", 155).getInt(0);
if (!isGreenLeavesEnabled())
ExtrabiomesLog
.info("greenleaves.id = 0, so green leaves have been disabled.");
saplingID = cfg.getOrCreateBlockIdProperty("sapling.id",
159).getInt(0);
if (!isSaplingEnabled())
ExtrabiomesLog
.info("sapling.id = 0, so saplings have been disabled.");
} catch (final Exception e) {
ExtrabiomesLog
.log(Level.SEVERE, e,
"ExtrabiomesXL had a problem loading it's configuration.");
} finally {
cfg.save();
}
}
}
| false | true | public static void init(FMLInitializationEvent event) {
proxy.registerRenderInformation();
if (isAutumnLeavesEnabled()) {
autumnLeaves = Optional.of(new BlockAutumnLeaves(
autumnLeavesID).setBlockName("autumnleaves"));
proxy.registerBlock(autumnLeaves,
extrabiomes.ItemCustomLeaves.class);
for (final AutumnLeafType type : AutumnLeafType.values())
proxy.addName(
new ItemStack(autumnLeaves.get(), 1, type
.metadata()), type.itemName());
TreeBlocks.setBlocks(BROWN, Block.wood.blockID, 0,
autumnLeavesID, AutumnLeafType.BROWN.metadata());
TreeBlocks.setBlocks(ORANGE, Block.wood.blockID, 0,
autumnLeavesID, AutumnLeafType.ORANGE.metadata());
TreeBlocks.setBlocks(PURPLE, Block.wood.blockID, 0,
autumnLeavesID, AutumnLeafType.PURPLE.metadata());
TreeBlocks.setBlocks(YELLOW, Block.wood.blockID, 0,
autumnLeavesID, AutumnLeafType.YELLOW.metadata());
}
if (isGreenLeavesEnabled()) {
greenLeaves = Optional.of(new BlockAutumnLeaves(
greenLeavesID).setBlockName("greenleaves"));
proxy.registerBlock(greenLeaves,
extrabiomes.ItemCustomLeaves.class);
for (final GreenLeafType type : GreenLeafType.values())
proxy.addName(
new ItemStack(greenLeaves.get(), 1, type
.metadata()), type.itemName());
TreeBlocks.setBlocks(FIR, Block.wood.blockID, 0,
autumnLeavesID, GreenLeafType.FIR.metadata());
TreeBlocks.setBlocks(REDWOOD, Block.wood.blockID, 0,
autumnLeavesID, GreenLeafType.REDWOOD.metadata());
TreeBlocks.setBlocks(ACACIA, Block.wood.blockID, 0,
autumnLeavesID, GreenLeafType.ACACIA.metadata());
}
if (isSaplingEnabled()) {
sapling = Optional.of(new BlockAutumnLeaves(saplingID)
.setBlockName("sapling"));
proxy.registerBlock(sapling,
extrabiomes.utility.MultiItemBlock.class);
for (final SaplingType type : SaplingType.values())
proxy.addName(
new ItemStack(sapling.get(), 1, type.metadata()),
type.itemName());
proxy.registerFuelHandler(new FuelHandler(saplingID));
}
}
| public static void init(FMLInitializationEvent event) {
proxy.registerRenderInformation();
if (isAutumnLeavesEnabled()) {
autumnLeaves = Optional.of(new BlockAutumnLeaves(
autumnLeavesID).setBlockName("autumnleaves"));
proxy.registerBlock(autumnLeaves,
extrabiomes.ItemCustomLeaves.class);
for (final AutumnLeafType type : AutumnLeafType.values())
proxy.addName(
new ItemStack(autumnLeaves.get(), 1, type
.metadata()), type.itemName());
TreeBlocks.setBlocks(BROWN, Block.wood.blockID, 0,
autumnLeavesID, AutumnLeafType.BROWN.metadata());
TreeBlocks.setBlocks(ORANGE, Block.wood.blockID, 0,
autumnLeavesID, AutumnLeafType.ORANGE.metadata());
TreeBlocks.setBlocks(PURPLE, Block.wood.blockID, 0,
autumnLeavesID, AutumnLeafType.PURPLE.metadata());
TreeBlocks.setBlocks(YELLOW, Block.wood.blockID, 0,
autumnLeavesID, AutumnLeafType.YELLOW.metadata());
}
if (isGreenLeavesEnabled()) {
greenLeaves = Optional.of(new BlockGreenLeaves(
greenLeavesID).setBlockName("greenleaves"));
proxy.registerBlock(greenLeaves,
extrabiomes.ItemCustomLeaves.class);
for (final GreenLeafType type : GreenLeafType.values())
proxy.addName(
new ItemStack(greenLeaves.get(), 1, type
.metadata()), type.itemName());
TreeBlocks.setBlocks(FIR, Block.wood.blockID, 0,
greenLeavesID, GreenLeafType.FIR.metadata());
TreeBlocks.setBlocks(REDWOOD, Block.wood.blockID, 0,
greenLeavesID, GreenLeafType.REDWOOD.metadata());
TreeBlocks.setBlocks(ACACIA, Block.wood.blockID, 0,
greenLeavesID, GreenLeafType.ACACIA.metadata());
}
if (isSaplingEnabled()) {
sapling = Optional.of(new BlockCustomSapling(saplingID)
.setBlockName("sapling"));
proxy.registerBlock(sapling,
extrabiomes.utility.MultiItemBlock.class);
for (final SaplingType type : SaplingType.values())
proxy.addName(
new ItemStack(sapling.get(), 1, type.metadata()),
type.itemName());
proxy.registerFuelHandler(new FuelHandler(saplingID));
}
}
|
diff --git a/android/src/com/freshplanet/alert/functions/AirAlertShowAlert.java b/android/src/com/freshplanet/alert/functions/AirAlertShowAlert.java
index 92a8835..bd6c7a4 100644
--- a/android/src/com/freshplanet/alert/functions/AirAlertShowAlert.java
+++ b/android/src/com/freshplanet/alert/functions/AirAlertShowAlert.java
@@ -1,77 +1,77 @@
//////////////////////////////////////////////////////////////////////////////////////
//
// Copyright 2012 Freshplanet (http://freshplanet.com | [email protected])
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//////////////////////////////////////////////////////////////////////////////////////
package com.freshplanet.alert.functions;
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.os.Build;
import com.adobe.fre.FREContext;
import com.adobe.fre.FREFunction;
import com.adobe.fre.FREObject;
import com.freshplanet.alert.Extension;
@TargetApi(14)
public class AirAlertShowAlert implements FREFunction
{
@Override
public FREObject call(FREContext context, FREObject[] args)
{
// Retrieve alert parameters
String title = null;
String message = null;
String button1 = null;
String button2 = null;
try
{
title = args[0].getAsString();
message = args[1].getAsString();
button1 = args[2].getAsString();
if (args.length > 3) button2 = args[3].getAsString();
}
catch (Exception e)
{
e.printStackTrace();
return null;
}
// Create alert builder with a theme depending on Android version
AlertDialog.Builder alertBuilder;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH)
{
alertBuilder = new AlertDialog.Builder(context.getActivity(), AlertDialog.THEME_DEVICE_DEFAULT_DARK);
}
else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
{
alertBuilder = new AlertDialog.Builder(context.getActivity(), AlertDialog.THEME_HOLO_DARK);
}
else
{
alertBuilder = new AlertDialog.Builder(context.getActivity());
}
// Setup and show the alert
- alertBuilder.setTitle(title).setMessage(message).setNeutralButton(button1, Extension.context);
+ alertBuilder.setTitle(title).setMessage(message).setCancelable(false).setNeutralButton(button1, Extension.context);
if (button2 != null) alertBuilder.setPositiveButton(button2, Extension.context);
alertBuilder.show();
return null;
}
}
| true | true | public FREObject call(FREContext context, FREObject[] args)
{
// Retrieve alert parameters
String title = null;
String message = null;
String button1 = null;
String button2 = null;
try
{
title = args[0].getAsString();
message = args[1].getAsString();
button1 = args[2].getAsString();
if (args.length > 3) button2 = args[3].getAsString();
}
catch (Exception e)
{
e.printStackTrace();
return null;
}
// Create alert builder with a theme depending on Android version
AlertDialog.Builder alertBuilder;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH)
{
alertBuilder = new AlertDialog.Builder(context.getActivity(), AlertDialog.THEME_DEVICE_DEFAULT_DARK);
}
else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
{
alertBuilder = new AlertDialog.Builder(context.getActivity(), AlertDialog.THEME_HOLO_DARK);
}
else
{
alertBuilder = new AlertDialog.Builder(context.getActivity());
}
// Setup and show the alert
alertBuilder.setTitle(title).setMessage(message).setNeutralButton(button1, Extension.context);
if (button2 != null) alertBuilder.setPositiveButton(button2, Extension.context);
alertBuilder.show();
return null;
}
| public FREObject call(FREContext context, FREObject[] args)
{
// Retrieve alert parameters
String title = null;
String message = null;
String button1 = null;
String button2 = null;
try
{
title = args[0].getAsString();
message = args[1].getAsString();
button1 = args[2].getAsString();
if (args.length > 3) button2 = args[3].getAsString();
}
catch (Exception e)
{
e.printStackTrace();
return null;
}
// Create alert builder with a theme depending on Android version
AlertDialog.Builder alertBuilder;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH)
{
alertBuilder = new AlertDialog.Builder(context.getActivity(), AlertDialog.THEME_DEVICE_DEFAULT_DARK);
}
else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
{
alertBuilder = new AlertDialog.Builder(context.getActivity(), AlertDialog.THEME_HOLO_DARK);
}
else
{
alertBuilder = new AlertDialog.Builder(context.getActivity());
}
// Setup and show the alert
alertBuilder.setTitle(title).setMessage(message).setCancelable(false).setNeutralButton(button1, Extension.context);
if (button2 != null) alertBuilder.setPositiveButton(button2, Extension.context);
alertBuilder.show();
return null;
}
|
diff --git a/ps3mediaserver/net/pms/PMS.java b/ps3mediaserver/net/pms/PMS.java
index f3a933a0..7c926c82 100644
--- a/ps3mediaserver/net/pms/PMS.java
+++ b/ps3mediaserver/net/pms/PMS.java
@@ -1,1433 +1,1435 @@
/*
* PS3 Media Server, for streaming any medias to your PS3.
* Copyright (C) 2008 A.Brochard
*
* 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; version 2
* of the License only.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package net.pms;
import java.awt.GraphicsEnvironment;
import java.awt.Toolkit;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.io.PrintStream;
import java.net.BindException;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.URI;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.UUID;
import java.util.logging.LogManager;
import net.pms.configuration.MapFileConfiguration;
import net.pms.configuration.PmsConfiguration;
import net.pms.configuration.RendererConfiguration;
import net.pms.dlna.AudiosFeed;
import net.pms.dlna.DLNAMediaDatabase;
import net.pms.dlna.DLNAResource;
import net.pms.dlna.ImagesFeed;
import net.pms.dlna.RealFile;
import net.pms.dlna.RootFolder;
import net.pms.dlna.VideosFeed;
import net.pms.dlna.WebAudioStream;
import net.pms.dlna.WebVideoStream;
import net.pms.dlna.virtual.MediaLibrary;
import net.pms.dlna.virtual.VirtualFolder;
import net.pms.dlna.virtual.VirtualVideoAction;
import net.pms.encoders.FFMpegAudio;
import net.pms.encoders.FFMpegDVRMSRemux;
import net.pms.encoders.FFMpegVideo;
import net.pms.encoders.MEncoderAviSynth;
import net.pms.encoders.MEncoderVideo;
import net.pms.encoders.MEncoderWebVideo;
import net.pms.encoders.MPlayerAudio;
import net.pms.encoders.MPlayerWebAudio;
import net.pms.encoders.MPlayerWebVideoDump;
import net.pms.encoders.Player;
import net.pms.encoders.RAWThumbnailer;
import net.pms.encoders.TSMuxerVideo;
import net.pms.encoders.TsMuxerAudio;
import net.pms.encoders.VideoLanAudioStreaming;
import net.pms.encoders.VideoLanVideoStreaming;
import net.pms.external.AdditionalFolderAtRoot;
import net.pms.external.AdditionalFoldersAtRoot;
import net.pms.external.ExternalFactory;
import net.pms.external.ExternalListener;
import net.pms.formats.DVRMS;
import net.pms.formats.FLAC;
import net.pms.formats.Format;
import net.pms.formats.GIF;
import net.pms.formats.ISO;
import net.pms.formats.JPG;
import net.pms.formats.M4A;
import net.pms.formats.MKV;
import net.pms.formats.MP3;
import net.pms.formats.MPG;
import net.pms.formats.OGG;
import net.pms.formats.PNG;
import net.pms.formats.RAW;
import net.pms.formats.TIF;
import net.pms.formats.WEB;
import net.pms.gui.DummyFrame;
import net.pms.gui.IFrame;
import net.pms.io.OutputParams;
import net.pms.io.OutputTextConsumer;
import net.pms.io.ProcessWrapperImpl;
import net.pms.io.WinUtils;
import net.pms.logging.LoggingConfigFileLoader;
import net.pms.network.HTTPServer;
import net.pms.network.ProxyServer;
import net.pms.network.UPNPHelper;
import net.pms.newgui.LooksFrame;
import net.pms.newgui.NetworkTab;
import net.pms.update.AutoUpdater;
import net.pms.util.PMSUtil;
import net.pms.util.ProcessUtil;
import net.pms.util.SystemErrWrapper;
import net.pms.xmlwise.Plist;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.lang.StringUtils;
import com.sun.jna.Platform;
public class PMS {
private static final String SCROLLBARS = "scrollbars"; //$NON-NLS-1$
private static final String NATIVELOOK = "nativelook"; //$NON-NLS-1$
private static final String CONSOLE = "console"; //$NON-NLS-1$
private static final String NOCONSOLE = "noconsole"; //$NON-NLS-1$
/**
* Update URL used in the {@link AutoUpdater}.
*/
private static final String UPDATE_SERVER_URL = "http://ps3mediaserver.googlecode.com/svn/trunk/ps3mediaserver/update.data"; //$NON-NLS-1$
/**
* Version showed in the UPnP XML descriptor and logs.
*/
public static final String VERSION = "1.23.0"; //$NON-NLS-1$
public static final String AVS_SEPARATOR = "\1"; //$NON-NLS-1$
// (innot): The logger used for all logging.
public static final Logger logger = LoggerFactory.getLogger(PMS.class);
// TODO(tcox): This shouldn't be static
private static PmsConfiguration configuration;
/**Returns a pointer to the main PMS GUI.
* @return {@link IFrame} Main PMS window.
*/
public IFrame getFrame() {
return frame;
}
/**getRootFolder returns the Root Folder for a given renderer. There could be the case
* where a given media renderer needs a different root structure.
* @param renderer {@link RendererConfiguration} is the renderer for which to get the RootFolder structure. If <b>null</b>, then
* the default renderer is used.
* @return {@link RootFolder} The root folder structure for a given renderer
*/
public RootFolder getRootFolder(RendererConfiguration renderer) {
return getRootFolder(renderer, true);
}
private RootFolder getRootFolder(RendererConfiguration renderer, boolean initialize) {
// something to do here for multiple directories views for each renderer
if (renderer == null) {
renderer = RendererConfiguration.getDefaultConf();
}
return renderer.getRootFolder(initialize);
}
/**
* Pointer to a running PMS server.
*/
private static PMS instance = null;
/**
* Semaphore used in order to not create two PMS instances at the same time.
*/
private static byte[] lock = null;
static {
lock = new byte[0];
sdfHour = new SimpleDateFormat("HH:mm:ss.SSS", Locale.US); //$NON-NLS-1$
sdfDate = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.US); //$NON-NLS-1$
}
/**
* Array of {@link RendererConfiguration} that have been found by PMS.
*/
private final ArrayList<RendererConfiguration> foundRenderers = new ArrayList<RendererConfiguration>();
/**Adds a {@link RendererConfiguration} to the list of media renderers found. The list is being used, for
* example, to give the user a graphical representation of the found media renderers.
* @param mediarenderer {@link RendererConfiguration}
*/
public void setRendererfound(RendererConfiguration mediarenderer) {
if (!foundRenderers.contains(mediarenderer) && !mediarenderer.isFDSSDP()) {
foundRenderers.add(mediarenderer);
frame.addRendererIcon(mediarenderer.getRank(), mediarenderer.getRendererNameWithAddress(), mediarenderer.getRendererIcon());
if (mediarenderer.isPS3()) {
frame.setStatusCode(0, Messages.getString("PMS.5"), "clients/ps3slim_220.png"); //$NON-NLS-1$ //$NON-NLS-2$
}
}
/*if (mediarenderer == HTTPResource.PS3) {
frame.setStatusCode(0, Messages.getString("PMS.5"), "PS3_2.png"); //$NON-NLS-1$ //$NON-NLS-2$
} else if (mediarenderer == HTTPResource.XBOX && !foundRenderers.contains(HTTPResource.PS3)) {
frame.setStatusCode(0, "Xbox found", "xbox360.png"); //$NON-NLS-1$ //$NON-NLS-2$
}*/
}
/**
* HTTP server that serves the XML files needed by UPnP server and the media files.
*/
private HTTPServer server;
/**
* User friendly name for the server.
*/
private String serverName;
private ArrayList<Format> extensions;
/**
* List of registered {@link Player}s.
*/
private ArrayList<Player> players;
private ArrayList<Player> allPlayers;
/**
* @return ArrayList of {@link Player}s.
*/
public ArrayList<Player> getAllPlayers() {
return allPlayers;
}
private ProxyServer proxyServer;
public ProxyServer getProxy() {
return proxyServer;
}
public static SimpleDateFormat sdfDate;
public static SimpleDateFormat sdfHour;
public ArrayList<Process> currentProcesses = new ArrayList<Process>();
private PMS() {
}
/**
* {@link IFrame} object that represents PMS GUI.
*/
IFrame frame;
/**
* @see Platform#isWindows()
*/
public boolean isWindows() {
return Platform.isWindows();
}
private int proxy;
/**Interface to Windows specific functions, like Windows Registry. registry is set by {@link #init()}.
* @see WinUtils
*/
private WinUtils registry;
/**
* @see WinUtils
*/
public WinUtils getRegistry() {
return registry;
}
/**Executes a new Process and creates a fork that waits for its results.
* TODO:Extend explanation on where this is being used.
* @param name Symbolic name for the process to be launched, only used in the trace log
* @param error (boolean) Set to true if you want PMS to add error messages to the trace pane
* @param workDir (File) optional working directory to run the process in
* @param params (array of Strings) array containing the command to call and its arguments
* @return Returns true if the command exited as expected
* @throws Exception TODO: Check which exceptions to use
*/
private boolean checkProcessExistence(String name, boolean error, File workDir, String... params) throws Exception {
info("launching: " + params[0]); //$NON-NLS-1$
try {
ProcessBuilder pb = new ProcessBuilder(params);
if (workDir != null) {
pb.directory(workDir);
}
final Process process = pb.start();
OutputTextConsumer stderrConsumer = new OutputTextConsumer(process.getErrorStream(), false);
stderrConsumer.start();
OutputTextConsumer outConsumer = new OutputTextConsumer(process.getInputStream(), false);
outConsumer.start();
Runnable r = new Runnable() {
public void run() {
ProcessUtil.waitFor(process);
}
};
Thread checkThread = new Thread(r);
checkThread.start();
checkThread.join(60000);
checkThread.interrupt();
checkThread = null;
// XXX no longer used
if (params[0].equals("vlc") && stderrConsumer.getResults().get(0).startsWith("VLC")) //$NON-NLS-1$ //$NON-NLS-2$
{
return true;
}
// XXX no longer used
if (params[0].equals("ffmpeg") && stderrConsumer.getResults().get(0).startsWith("FF")) //$NON-NLS-1$ //$NON-NLS-2$
{
return true;
}
int exit = process.exitValue();
if (exit != 0) {
if (error) {
minimal("[" + exit + "] Cannot launch " + name + " / Check the presence of " + params[0] + " ..."); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
}
return false;
}
return true;
} catch (Exception e) {
if (error) {
logger.error("Cannot launch " + name + " / Check the presence of " + params[0] + " ...", e); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
return false;
}
}
/**
* @see System#err
*/
@SuppressWarnings("unused")
private final PrintStream stderr = System.err;
/**Main resource database that supports search capabilities. Also known as media cache.
* @see DLNAMediaDatabase
*/
private DLNAMediaDatabase database;
/**Used to get the database. Needed in the case of the Xbox 360, that requires a database.
* for its queries.
* @return (DLNAMediaDatabase) If there exists a database register with the program, a pointer to it is returned.
* If there is no database in memory, a new one is created. If the option to use a "cache" is deactivated, returns <b>null</b>.
*/
public synchronized DLNAMediaDatabase getDatabase() {
if (configuration.getUseCache()) {
if (database == null) {
database = new DLNAMediaDatabase("medias"); //$NON-NLS-1$
database.init(false);
/*try {
org.h2.tools.Server server = org.h2.tools.Server.createWebServer(null);
server.start();
minimal("Starting H2 console on port " + server.getPort());
} catch (Exception e) {
e.printStackTrace();
}*/
}
return database;
}
return null;
}
/**Initialisation procedure for PMS.
* @return true if the server has been initialized correctly. false if the server could
* not be set to listen on the UPnP port.
* @throws Exception
*/
private boolean init() throws Exception {
registry = new WinUtils();
AutoUpdater autoUpdater = new AutoUpdater(UPDATE_SERVER_URL, VERSION);
if (System.getProperty(CONSOLE) == null) {//$NON-NLS-1$
frame = new LooksFrame(autoUpdater, configuration);
autoUpdater.pollServer();
} else {
System.out.println("GUI environment not available"); //$NON-NLS-1$
System.out.println("Switching to console mode"); //$NON-NLS-1$
frame = new DummyFrame();
}
frame.setStatusCode(0, Messages.getString("PMS.130"), "connect_no-220.png"); //$NON-NLS-1$ //$NON-NLS-2$
proxy = -1;
minimal("Starting PS3 Media Server " + VERSION); //$NON-NLS-1$
minimal("by shagrath / 2008-2011"); //$NON-NLS-1$
minimal("http://ps3mediaserver.org"); //$NON-NLS-1$
minimal("http://code.google.com/p/ps3mediaserver"); //$NON-NLS-1$
minimal("http://ps3mediaserver.blogspot.com"); //$NON-NLS-1$
minimal(""); //$NON-NLS-1$
minimal("Java: " + System.getProperty("java.version") + "-" + System.getProperty("java.vendor")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
minimal("OS: " + System.getProperty("os.name") + " " + System.getProperty("os.arch") + " " + System.getProperty("os.version")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
minimal("Encoding: " + System.getProperty("file.encoding")); //$NON-NLS-1$ //$NON-NLS-2$
String cwd = new File("").getAbsolutePath();
minimal("Working directory: " + cwd);
minimal("Temp folder: " + configuration.getTempFolder()); //$NON-NLS-1$
minimal("Logging config file: " + LoggingConfigFileLoader.getConfigFilePath()); //$NON-NLS-1$
minimal(""); //$NON-NLS-1$
minimal("Profile directory: " + configuration.getProfileDir());
String profilePath = configuration.getProfilePath();
minimal("Profile path: " + profilePath);
File profileFile = new File(profilePath);
if (profileFile.exists()) {
String status = String.format("%s%s",
profileFile.canRead() ? "r" : "-",
profileFile.canWrite() ? "w" : "-"
);
minimal("Profile status: " + status);
} else {
minimal("Profile status: no such file");
}
minimal("Profile name: " + configuration.getProfileName()); //$NON-NLS-1$
minimal(""); //$NON-NLS-1$
RendererConfiguration.loadRendererConfigurations();
minimal("Checking MPlayer font cache. It can take a minute or so.");
checkProcessExistence("MPlayer", true, null, configuration.getMplayerPath(), "dummy");
- checkProcessExistence("MPlayer", true, getConfiguration().getTempFolder(), configuration.getMplayerPath(), "dummy");
+ if(isWindows()) {
+ checkProcessExistence("MPlayer", true, getConfiguration().getTempFolder(), configuration.getMplayerPath(), "dummy");
+ }
minimal("Done!");
// check the existence of Vsfilter.dll
if (registry.isAvis() && registry.getAvsPluginsDir() != null) {
minimal("Found AviSynth plugins dir: " + registry.getAvsPluginsDir().getAbsolutePath()); //$NON-NLS-1$
File vsFilterdll = new File(registry.getAvsPluginsDir(), "VSFilter.dll"); //$NON-NLS-1$
if (!vsFilterdll.exists()) {
minimal("VSFilter.dll is not in the AviSynth plugins directory. This can cause problems when trying to play subtitled videos with AviSynth"); //$NON-NLS-1$
}
}
if (registry.getVlcv() != null && registry.getVlcp() != null) {
minimal("Found VideoLAN version " + registry.getVlcv() + " at: " + registry.getVlcp()); //$NON-NLS-1$ //$NON-NLS-2$
}
//check if Kerio is installed
if (registry.isKerioFirewall()) {
//todo: Warning message
}
// force use of specific dvr ms muxer when it's installed in the right place
File dvrsMsffmpegmuxer = new File("win32/dvrms/ffmpeg_MPGMUX.exe"); //$NON-NLS-1$
if (dvrsMsffmpegmuxer.exists()) {
configuration.setFfmpegAlternativePath(dvrsMsffmpegmuxer.getAbsolutePath());
}
// disable jaudiotagger logging
LogManager.getLogManager().readConfiguration(new ByteArrayInputStream("org.jaudiotagger.level=OFF".getBytes())); //$NON-NLS-1$
// wrap System.err
System.setErr(new PrintStream(new SystemErrWrapper(), true));
extensions = new ArrayList<Format>();
players = new ArrayList<Player>();
allPlayers = new ArrayList<Player>();
server = new HTTPServer(configuration.getServerPort());
registerExtensions();
/*
* XXX: keep this here (i.e. after registerExtensions and before registerPlayers) so that plugins
* can register custom players correctly (e.g. in the GUI) and/or add/replace custom formats
*
* XXX: if a plugin requires initialization/notification even earlier than
* this, then a new external listener implementing a new callback should be added
* e.g. StartupListener.registeredExtensions()
*/
try {
ExternalFactory.lookup();
} catch (Exception e) {
logger.error("Error loading plugins", e);
}
// a static block in Player doesn't work (i.e. is called too late).
// this must always be called *after* the plugins have loaded.
// here's as good a place as any
Player.initializeFinalizeTranscoderArgsListeners();
registerPlayers();
getRootFolder(RendererConfiguration.getDefaultConf());
boolean binding = false;
try {
binding = server.start();
} catch (BindException b) {
minimal("FATAL ERROR: Unable to bind on port: " + configuration.getServerPort() + ", because: " + b.getMessage()); //$NON-NLS-1$ //$NON-NLS-2$
minimal("Maybe another process is running or the hostname is wrong."); //$NON-NLS-1$
}
new Thread() {
@Override
public void run() {
try {
Thread.sleep(7000);
} catch (InterruptedException e) {
}
boolean ps3found = false;
for (RendererConfiguration r : foundRenderers) {
if (r.isPS3()) {
ps3found = true;
}
}
if (!ps3found) {
if (foundRenderers.isEmpty()) {
frame.setStatusCode(0, Messages.getString("PMS.0"), "messagebox_critical-220.png"); //$NON-NLS-1$ //$NON-NLS-2$
} else {
frame.setStatusCode(0, Messages.getString("PMS.15"), "messagebox_warning-220.png"); //$NON-NLS-1$ //$NON-NLS-2$
}
}
}
}.start();
if (!binding) {
return false;
}
if (proxy > 0) {
minimal("Starting HTTP Proxy Server on port: " + proxy); //$NON-NLS-1$
proxyServer = new ProxyServer(proxy);
}
if (getDatabase() != null) {
minimal("A tiny media library admin interface is available at: http://" + server.getHost() + ":" + server.getPort() + "/console/home");
}
frame.serverReady();
//UPNPHelper.sendByeBye();
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
try {
for (ExternalListener l : ExternalFactory.getExternalListeners()) {
l.shutdown();
}
UPNPHelper.shutDownListener();
UPNPHelper.sendByeBye();
info("Forcing shutdown of all active processes"); //$NON-NLS-1$
for (Process p : currentProcesses) {
try {
p.exitValue();
} catch (IllegalThreadStateException ise) {
debug("Forcing shutdown of process: " + p); //$NON-NLS-1$
ProcessUtil.destroy(p);
}
}
get().getServer().stop();
Thread.sleep(500);
} catch (Exception e) {
}
}
});
UPNPHelper.sendAlive();
debug("Waiting 250 milliseconds..."); //$NON-NLS-1$
Thread.sleep(250);
UPNPHelper.listen();
return true;
}
/**Creates a new Root folder for a given configuration. It adds following folders in this order:
* <ol><li>Directory folders as stated in the configuration pane
* <li>Web nodes
* <li>iPhoto
* <li>iTunes
* <li>Media Library
* <li>Folders created by plugins
* <li>Video settings
* </ol>
* @param renderer {@link RendererConfiguration} to be managed.
* @throws IOException
*/
public void manageRoot(RendererConfiguration renderer) throws IOException {
File files[] = loadFoldersConf(configuration.getFolders(), true);
if (files == null || files.length == 0) {
files = File.listRoots();
}
/*
* initialize == false: make sure renderer.getRootFolder() doesn't call back into this method
* if it creates a new root folder
*
* this avoids a redundant call to this method, and prevents loadFoldersConf()
* being called twice for each renderer
*/
RootFolder rootFolder = getRootFolder(renderer, false);
rootFolder.browse(files);
rootFolder.browse(MapFileConfiguration.parse(configuration.getVirtualFolders()));
// FIXME: this (the WEB.conf path) should be fully configurable
File webConf = new File(PMS.getConfiguration().getProfileDir(), "WEB.conf"); //$NON-NLS-1$
if (webConf.exists()) {
try {
LineNumberReader br = new LineNumberReader(new InputStreamReader(new FileInputStream(webConf), "UTF-8")); //$NON-NLS-1$
String line = null;
while ((line = br.readLine()) != null) {
line = line.trim();
if (line.length() > 0 && !line.startsWith("#") && line.indexOf("=") > -1) { //$NON-NLS-1$ //$NON-NLS-2$
String key = line.substring(0, line.indexOf("=")); //$NON-NLS-1$
String value = line.substring(line.indexOf("=") + 1); //$NON-NLS-1$
String keys[] = parseFeedKey(key);
try {
if (keys[0].equals("imagefeed")
|| keys[0].equals("audiofeed")
|| keys[0].equals("videofeed")
|| keys[0].equals("audiostream")
|| keys[0].equals("videostream")) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
String values[] = parseFeedValue(value);
DLNAResource parent = null;
if (keys[1] != null) {
StringTokenizer st = new StringTokenizer(keys[1], ","); //$NON-NLS-1$
DLNAResource currentRoot = rootFolder;
while (st.hasMoreTokens()) {
String folder = st.nextToken();
parent = currentRoot.searchByName(folder);
if (parent == null) {
parent = new VirtualFolder(folder, ""); //$NON-NLS-1$
currentRoot.addChild(parent);
}
currentRoot = parent;
}
}
if (parent == null) {
parent = rootFolder;
}
if (keys[0].equals("imagefeed")) { //$NON-NLS-1$
parent.addChild(new ImagesFeed(values[0]));
} else if (keys[0].equals("videofeed")) { //$NON-NLS-1$
parent.addChild(new VideosFeed(values[0]));
} else if (keys[0].equals("audiofeed")) { //$NON-NLS-1$
parent.addChild(new AudiosFeed(values[0]));
} else if (keys[0].equals("audiostream")) { //$NON-NLS-1$
parent.addChild(new WebAudioStream(values[0], values[1], values[2]));
} else if (keys[0].equals("videostream")) { //$NON-NLS-1$
parent.addChild(new WebVideoStream(values[0], values[1], values[2]));
}
}
// catch exception here and go with parsing
} catch (ArrayIndexOutOfBoundsException e) {
minimal("Error at line " + br.getLineNumber() + " of WEB.conf: " + e.getMessage()); //$NON-NLS-1$
}
}
}
br.close();
} catch (Exception e) {
e.printStackTrace();
minimal("Unexpected error in WEB.conf: " + e.getMessage()); //$NON-NLS-1$
}
}
if (Platform.isMac()) {
if (getConfiguration().getIphotoEnabled()) {
addiPhotoFolder(renderer);
}
}
if (Platform.isMac() || Platform.isWindows()) {
if (getConfiguration().getItunesEnabled()) {
addiTunesFolder(renderer);
}
}
addMediaLibraryFolder(renderer);
addAdditionalFoldersAtRoot(renderer);
addVideoSettingssFolder(renderer);
rootFolder.closeChildren(0, false);
}
/**Adds iPhoto folder. Used by manageRoot, so it is usually used as a folder at the
* root folder. Only works when PMS is run on MacOsX.
* TODO: Requirements for iPhoto.
* @param renderer
*/
public void addiPhotoFolder(RendererConfiguration renderer) {
if (Platform.isMac()) {
Map<String, Object> iPhotoLib;
ArrayList<?> ListofRolls;
HashMap<?, ?> Roll;
HashMap<?, ?> PhotoList;
HashMap<?, ?> Photo;
ArrayList<?> RollPhotos;
try {
Process prc = Runtime.getRuntime().exec("defaults read com.apple.iApps iPhotoRecentDatabases");
BufferedReader in = new BufferedReader(
new InputStreamReader(prc.getInputStream()));
String line = null;
if ((line = in.readLine()) != null) {
line = in.readLine(); //we want the 2nd line
line = line.trim(); //remove extra spaces
line = line.substring(1, line.length() - 1); // remove quotes and spaces
}
in.close();
if (line != null) {
URI tURI = new URI(line);
iPhotoLib = Plist.load(URLDecoder.decode(tURI.toURL().getFile(), System.getProperty("file.encoding"))); // loads the (nested) properties.
PhotoList = (HashMap<?, ?>) iPhotoLib.get("Master Image List"); // the list of photos
ListofRolls = (ArrayList<?>) iPhotoLib.get("List of Rolls"); // the list of events (rolls)
VirtualFolder vf = new VirtualFolder("iPhoto Library", null); //$NON-NLS-1$
for (Object item : ListofRolls) {
Roll = (HashMap<?, ?>) item;
VirtualFolder rf = new VirtualFolder(Roll.get("RollName").toString(), null); //$NON-NLS-1$
RollPhotos = (ArrayList<?>) Roll.get("KeyList"); // list of photos in an event (roll)
for (Object p : RollPhotos) {
Photo = (HashMap<?, ?>) PhotoList.get(p);
RealFile file = new RealFile(new File(Photo.get("ImagePath").toString()));
rf.addChild(file);
}
vf.addChild(rf); //$NON-NLS-1$
}
getRootFolder(renderer).addChild(vf);
} else {
minimal("iPhoto folder not found !?");
}
} catch (Exception e) {
logger.error("Something went wrong with the iPhoto Library scan: ", e); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
}
}
/**Returns the iTunes XML file. This file has all the information of the iTunes
* database. The methods used in this function depends on whether PMS runs on
* MacOsX or Windows.
* @param isOsx deprecated and not used
* @return (String) Absolute path to the iTunes XML file.
* @throws Exception
* @see {@link PMS#addiTunesFolder(RendererConfiguration)}
*/
@SuppressWarnings("deprecation")
private String getiTunesFile(boolean isOsx) throws Exception {
String line = null;
String iTunesFile = null;
if (Platform.isMac()) {
Process prc = Runtime.getRuntime().exec("defaults read com.apple.iApps iTunesRecentDatabases");
BufferedReader in = new BufferedReader(new InputStreamReader(prc.getInputStream()));
if ((line = in.readLine()) != null) {
line = in.readLine(); //we want the 2nd line
line = line.trim(); //remove extra spaces
line = line.substring(1, line.length() - 1); // remove quotes and spaces
URI tURI = new URI(line);
iTunesFile = URLDecoder.decode(tURI.toURL().getFile());
}
if (in != null) {
in.close();
}
} else if (Platform.isWindows()) {
Process prc = Runtime.getRuntime().exec("reg query \"HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders\" /v \"My Music\"");
BufferedReader in = new BufferedReader(new InputStreamReader(prc.getInputStream()));
String location = null;
while ((line = in.readLine()) != null) {
final String LOOK_FOR = "REG_SZ";
if (line.contains(LOOK_FOR)) {
location = line.substring(line.indexOf(LOOK_FOR) + LOOK_FOR.length()).trim();
}
}
if (in != null) {
in.close();
}
if (location != null) {
// add the itunes folder to the end
location = location + "\\iTunes\\iTunes Music Library.xml";
iTunesFile = location;
} else {
logger.info("Could not find the My Music folder");
}
}
return iTunesFile;
}
/**Adds iTunes folder. Used by manageRoot, so it is usually used as a folder at the
* root folder. Only works when PMS is run on MacOsX or Windows.<p>
* The iTunes XML is parsed fully when this method is called, so it can take some time for
* larger (+1000 albums) databases. TODO: Check if only music is being added.<P>
* This method does not support genius playlists and does not provide a media library.
* @param renderer {@link RendererConfiguration} Which media renderer to add this folder to.
* @see PMS#manageRoot(RendererConfiguration)
* @see PMS#getiTunesFile(boolean)
*/
public void addiTunesFolder(RendererConfiguration renderer) {
if (Platform.isMac() || Platform.isWindows()) {
Map<String, Object> iTunesLib;
ArrayList<?> Playlists;
HashMap<?, ?> Playlist;
HashMap<?, ?> Tracks;
HashMap<?, ?> Track;
ArrayList<?> PlaylistTracks;
try {
String iTunesFile = getiTunesFile(Platform.isMac());
if (iTunesFile != null && (new File(iTunesFile)).exists()) {
iTunesLib = Plist.load(URLDecoder.decode(iTunesFile, System.getProperty("file.encoding"))); // loads the (nested) properties.
Tracks = (HashMap<?, ?>) iTunesLib.get("Tracks"); // the list of tracks
Playlists = (ArrayList<?>) iTunesLib.get("Playlists"); // the list of Playlists
VirtualFolder vf = new VirtualFolder("iTunes Library", null); //$NON-NLS-1$
for (Object item : Playlists) {
Playlist = (HashMap<?, ?>) item;
VirtualFolder pf = new VirtualFolder(Playlist.get("Name").toString(), null); //$NON-NLS-1$
PlaylistTracks = (ArrayList<?>) Playlist.get("Playlist Items"); // list of tracks in a playlist
if (PlaylistTracks != null) {
for (Object t : PlaylistTracks) {
HashMap<?, ?> td = (HashMap<?, ?>) t;
Track = (HashMap<?, ?>) Tracks.get(td.get("Track ID").toString());
if (Track.get("Location").toString().startsWith("file://")) {
URI tURI2 = new URI(Track.get("Location").toString());
RealFile file = new RealFile(new File(URLDecoder.decode(tURI2.toURL().getFile(), "UTF-8")));
pf.addChild(file);
}
}
}
vf.addChild(pf); //$NON-NLS-1$
}
getRootFolder(renderer).addChild(vf);
} else {
logger.info("Could not find the iTunes file");
}
} catch (Exception e) {
logger.error("Something went wrong with the iTunes Library scan: ", e); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
}
}
/**Adds Video Settings folder. Used by manageRoot, so it is usually used as a folder at the
* root folder. Child objects are created when this folder is created.
* @param renderer {@link RendererConfiguration} Which media renderer to add this folder to.
* @see PMS#manageRoot(RendererConfiguration)
*/
public void addVideoSettingssFolder(RendererConfiguration renderer) {
if (!configuration.getHideVideoSettings()) {
VirtualFolder vf = new VirtualFolder(Messages.getString("PMS.37"), null); //$NON-NLS-1$
VirtualFolder vfSub = new VirtualFolder(Messages.getString("PMS.8"), null); //$NON-NLS-1$
vf.addChild(vfSub);
vf.addChild(new VirtualVideoAction(Messages.getString("PMS.3"), configuration.isMencoderNoOutOfSync()) { //$NON-NLS-1$
@Override
public boolean enable() {
configuration.setMencoderNoOutOfSync(!configuration.isMencoderNoOutOfSync());
return configuration.isMencoderNoOutOfSync();
}
});
vf.addChild(new VirtualVideoAction(Messages.getString("PMS.14"), configuration.isMencoderMuxWhenCompatible()) { //$NON-NLS-1$
@Override
public boolean enable() {
configuration.setMencoderMuxWhenCompatible(!configuration.isMencoderMuxWhenCompatible());
return configuration.isMencoderMuxWhenCompatible();
}
});
vf.addChild(new VirtualVideoAction(" !!-- Fix 23.976/25fps A/V Mismatch --!!", getConfiguration().isFix25FPSAvMismatch()) { //$NON-NLS-1$
@Override
public boolean enable() {
getConfiguration().setMencoderForceFps(!getConfiguration().isFix25FPSAvMismatch());
getConfiguration().setFix25FPSAvMismatch(!getConfiguration().isFix25FPSAvMismatch());
return getConfiguration().isFix25FPSAvMismatch();
}
});
vf.addChild(new VirtualVideoAction(Messages.getString("PMS.4"), configuration.isMencoderYadif()) { //$NON-NLS-1$
@Override
public boolean enable() {
configuration.setMencoderYadif(!configuration.isMencoderYadif());
return configuration.isMencoderYadif();
}
});
vfSub.addChild(new VirtualVideoAction(Messages.getString("PMS.10"), configuration.isMencoderDisableSubs()) { //$NON-NLS-1$
@Override
public boolean enable() {
boolean oldValue = configuration.isMencoderDisableSubs();
boolean newValue = !oldValue;
configuration.setMencoderDisableSubs(newValue);
return newValue;
}
});
vfSub.addChild(new VirtualVideoAction(Messages.getString("PMS.6"), configuration.getUseSubtitles()) { //$NON-NLS-1$
@Override
public boolean enable() {
boolean oldValue = configuration.getUseSubtitles();
boolean newValue = !oldValue;
configuration.setUseSubtitles(newValue);
return newValue;
}
});
vfSub.addChild(new VirtualVideoAction(Messages.getString("MEncoderVideo.36"), configuration.isMencoderAssDefaultStyle()) { //$NON-NLS-1$
@Override
public boolean enable() {
boolean oldValue = configuration.isMencoderAssDefaultStyle();
boolean newValue = !oldValue;
configuration.setMencoderAssDefaultStyle(newValue);
return newValue;
}
});
vf.addChild(new VirtualVideoAction(Messages.getString("PMS.7"), configuration.getSkipLoopFilterEnabled()) { //$NON-NLS-1$
@Override
public boolean enable() {
configuration.setSkipLoopFilterEnabled(!configuration.getSkipLoopFilterEnabled());
return configuration.getSkipLoopFilterEnabled();
}
});
vf.addChild(new VirtualVideoAction(Messages.getString("PMS.27"), true) { //$NON-NLS-1$
@Override
public boolean enable() {
try {
configuration.save();
} catch (ConfigurationException e) {
}
return true;
}
});
vf.addChild(new VirtualVideoAction(Messages.getString("LooksFrame.12"), true) { //$NON-NLS-1$
@Override
public boolean enable() {
try {
get().reset();
} catch (IOException e) {
}
return true;
}
});
//vf.closeChildren(0, false);
getRootFolder(renderer).addChild(vf);
}
}
/**Adds as many folders as plugins providing root folders are loaded into memory (need to implement AdditionalFolderAtRoot)
* @param renderer {@link RendererConfiguration} Which media renderer to add this folder to.
* @see PMS#manageRoot(RendererConfiguration)
*/
private void addAdditionalFoldersAtRoot(RendererConfiguration renderer) {
RootFolder rootFolder = getRootFolder(renderer);
for (ExternalListener listener : ExternalFactory.getExternalListeners()) {
if (listener instanceof AdditionalFolderAtRoot) {
rootFolder.addChild(((AdditionalFolderAtRoot) listener).getChild());
} else if (listener instanceof AdditionalFoldersAtRoot) {
java.util.Iterator<DLNAResource> folders = ((AdditionalFoldersAtRoot) listener).getChildren();
while (folders.hasNext()) {
rootFolder.addChild(folders.next());
}
}
}
}
//private boolean mediaLibraryAdded = false;
private MediaLibrary library;
/**Returns the MediaLibrary used by PMS.
* @return (MediaLibrary) Used library, if any. null if none is in use.
*/
public MediaLibrary getLibrary() {
return library;
}
/**Creates a new MediaLibrary object and adds the Media Library folder at root. This method
* can only be run once, or the previous MediaLibrary object can be lost.<P>
* @param renderer {@link RendererConfiguration} Which media renderer to add this folder to.
* @return true if the settings allow to have a MediaLibrary.
* @see PMS#manageRoot(RendererConfiguration)
*/
public boolean addMediaLibraryFolder(RendererConfiguration renderer) {
if (configuration.getUseCache() && !renderer.isMediaLibraryAdded()) {
library = new MediaLibrary();
if (!configuration.isHideMediaLibraryFolder()) {
getRootFolder(renderer).addChild(library);
}
renderer.setMediaLibraryAdded(true);
return true;
}
return false;
}
/**Executes the needed commands in order to make PMS a Windows service that starts whenever the machine is started.
* This function is called from the Network tab.
* @return true if PMS could be installed as a Windows service.
* @see NetworkTab#build()
*/
public boolean installWin32Service() {
minimal(Messages.getString("PMS.41")); //$NON-NLS-1$
String cmdArray[] = new String[]{"win32/service/wrapper.exe", "-r", "wrapper.conf"}; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
OutputParams output = new OutputParams(configuration);
output.noexitcheck = true;
ProcessWrapperImpl pwuninstall = new ProcessWrapperImpl(cmdArray, output);
pwuninstall.run();
cmdArray = new String[]{"win32/service/wrapper.exe", "-i", "wrapper.conf"}; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
ProcessWrapperImpl pwinstall = new ProcessWrapperImpl(cmdArray, new OutputParams(configuration));
pwinstall.run();
return pwinstall.isSuccess();
}
/**Splits the first part of a WEB.conf spec into a pair of Strings representing the resource type and its DLNA folder.<P>
* Used by {@link PMS#manageRoot(RendererConfiguration)} in the WEB.conf section.
* @param spec (String) to be split
* @return Array of (String) that represents the tokenized entry.
* @see PMS#manageRoot(RendererConfiguration)
*/
private String[] parseFeedKey(String spec) {
String[] pair = StringUtils.split(spec, ".", 2);
if (pair == null || pair.length < 2) {
pair = new String[2];
}
if (pair[0] == null) {
pair[0] = "";
}
return pair;
}
/**Splits the second part of a WEB.conf spec into a triple of Strings representing the DLNA path, resource URI and optional thumbnail URI.<P>
* Used by {@link PMS#manageRoot(RendererConfiguration)} in the WEB.conf section.
* @param spec (String) to be split
* @return Array of (String) that represents the tokenized entry.
* @see PMS#manageRoot(RendererConfiguration)
*/
private String[] parseFeedValue(String spec) {
StringTokenizer st = new StringTokenizer(spec, ","); //$NON-NLS-1$
String triple[] = new String[3];
int i = 0;
while (st.hasMoreTokens()) {
triple[i++] = st.nextToken();
}
return triple;
}
/**Add a known set of extensions to the extensions list.
* @see PMS#init()
*/
private void registerExtensions() {
extensions.add(new WEB());
extensions.add(new MKV());
extensions.add(new M4A());
extensions.add(new MP3());
extensions.add(new ISO());
extensions.add(new MPG());
extensions.add(new JPG());
extensions.add(new OGG());
extensions.add(new PNG());
extensions.add(new GIF());
extensions.add(new TIF());
extensions.add(new FLAC());
extensions.add(new DVRMS());
extensions.add(new RAW());
}
/**Register a known set of audio/video transform tools (known as {@link Player}s). Used in PMS#init().
* @see PMS#init()
*/
private void registerPlayers() {
assert configuration != null;
if (Platform.isWindows()) {
registerPlayer(new FFMpegVideo());
}
registerPlayer(new FFMpegAudio(configuration));
registerPlayer(new MEncoderVideo(configuration));
if (Platform.isWindows()) {
registerPlayer(new MEncoderAviSynth(configuration));
}
registerPlayer(new MPlayerAudio(configuration));
registerPlayer(new MEncoderWebVideo(configuration));
registerPlayer(new MPlayerWebVideoDump(configuration));
registerPlayer(new MPlayerWebAudio(configuration));
registerPlayer(new TSMuxerVideo(configuration));
registerPlayer(new TsMuxerAudio(configuration));
registerPlayer(new VideoLanAudioStreaming(configuration));
registerPlayer(new VideoLanVideoStreaming(configuration));
if (Platform.isWindows()) {
registerPlayer(new FFMpegDVRMSRemux());
}
registerPlayer(new RAWThumbnailer());
frame.addEngines();
}
/**Adds a single {@link Player} to the list of Players. Used by {@link PMS#registerPlayers()}.
* @param p (Player) to be added to the list
* @see Player
* @see PMS#registerPlayers()
*/
public void registerPlayer(Player p) {
allPlayers.add(p);
boolean ok = false;
if (Player.NATIVE.equals(p.executable())) {
ok = true;
} else {
if (isWindows()) {
if (p.executable() == null) {
logger.info("Executable of transcoder profile " + p + " not found"); //$NON-NLS-1$ //$NON-NLS-2$
return;
}
File executable = new File(p.executable());
File executable2 = new File(p.executable() + ".exe"); //$NON-NLS-1$
if (executable.exists() || executable2.exists()) {
ok = true;
} else {
logger.info("Executable of transcoder profile " + p + " not found"); //$NON-NLS-1$ //$NON-NLS-2$
return;
}
if (p.avisynth()) {
ok = false;
if (registry.isAvis()) {
ok = true;
} else {
logger.info("Transcoder profile " + p + " will not be used because AviSynth was not found"); //$NON-NLS-1$ //$NON-NLS-2$
}
}
} else if (!p.avisynth()) {
ok = true;
}
}
if (ok) {
logger.info("Registering transcoding engine: " + p /*+ (p.avisynth()?(" with " + (forceMPlayer?"MPlayer":"AviSynth")):"")*/); //$NON-NLS-1$
players.add(p);
}
}
/**Transforms a comma separated list of directory entries into an array of {@link String}.
* Checks that the directory exists and is a valid directory.
* @param folders {@link String} Comma separated list of directories.
* @param log whether to output log information
* @return {@link File}[] Array of directories.
* @throws IOException
* @see {@link PMS#manageRoot(RendererConfiguration)}
*/
// this is called *way* too often (e.g. a dozen times with 1 renderer and 1 shared folder),
// so log it by default so we can fix it.
// BUT it's also called when the GUI is initialized (to populate the list of shared folders),
// and we don't want this message to appear *before* the PMS banner, so allow that call to suppress logging
public File[] loadFoldersConf(String folders, boolean log) throws IOException {
if (folders == null || folders.length() == 0) {
return null;
}
ArrayList<File> directories = new ArrayList<File>();
String[] foldersArray = folders.split(","); //$NON-NLS-1$
for (String folder : foldersArray) {
// unescape embedded commas. note: backslashing isn't safe as it conflicts with
// Windows path separators:
// http://ps3mediaserver.org/forum/viewtopic.php?f=14&t=8883&start=250#p43520
folder = folder.replaceAll(",", ","); //$NON-NLS-1$ //$NON-NLS-2$
if (log) {
debug("Checking shared folder: " + folder); //$NON-NLS-1$
}
File file = new File(folder);
if (file.exists()) {
if (!file.isDirectory()) {
logger.warn("The file " + folder + " is not a directory! Please remove it from your Shared folders list on the Navigation/Share Settings tab"); //$NON-NLS-1$ //$NON-NLS-2$
}
} else {
logger.warn("The directory " + folder + " does not exist. Please remove it from your Shared folders list on the Navigation/Share Settings tab"); //$NON-NLS-1$ //$NON-NLS-2$
}
// add the file even if there are problems so that the user can update the shared folders as required.
directories.add(file);
}
File f[] = new File[directories.size()];
directories.toArray(f);
return f;
}
/**Restarts the servers. The trigger is either a button on the main PMS window or via
* an action item added via {@link PMS#addVideoSettingssFolder(RendererConfiguration).
* @throws IOException
*/
// XXX: don't try to optimize this by reusing the same server instance.
// see the comment above HTTPServer.stop()
public void reset() throws IOException {
debug("Waiting 1 second..."); //$NON-NLS-1$
UPNPHelper.sendByeBye();
server.stop();
server = null;
RendererConfiguration.resetAllRenderers();
manageRoot(RendererConfiguration.getDefaultConf());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
server = new HTTPServer(configuration.getServerPort());
server.start();
frame.setReloadable(false);
UPNPHelper.sendAlive();
}
// (innot): A note on Level names: PMS uses the following logging levels
// in ascending order: DEBUG, INFO, TRACE/minimal, ERROR
// The SLF4J logging API uses TRACE, DEBUG, INFO, WARN and ERROR
// So the levels get remapped in the following convenience methods.
// TODO: remove these methods and replace their callers with direct
// calls to the SLF4J API.
/**Adds a message to the debug stream, or {@link System#out} in case the
* debug stream has not been set up yet.
* @param msg {@link String} to be added to the debug stream.
*/
public static void debug(String msg) {
logger.trace(msg);
}
/**Adds a message to the info stream.
* @param msg {@link String} to be added to the info stream.
*/
public static void info(String msg) {
logger.debug(msg);
}
/**Adds a message to the minimal stream. This stream is also
* shown in the Trace tab.
* @param msg {@link String} to be added to the minimal stream.
*/
public static void minimal(String msg) {
logger.info(msg);
}
/**Adds a message to the error stream. This is usually called by
* statements that are in a try/catch block.
* @param msg {@link String} to be added to the error stream
* @param t {@link Throwable} comes from an {@link Exception}
*/
public static void error(String msg, Throwable t) {
logger.error(msg, t);
}
/**Universally Unique Identifier used in the UPnP server.
*
*/
private String uuid;
/**Creates a new {@link #uuid} for the UPnP server to use. Tries to follow the RFCs for creating the UUID based on the link MAC address.
* Defaults to a random one if that method is not available.
* @return {@link String} with an Universally Unique Identifier.
*/
public String usn() {
if (uuid == null) {
boolean uuidBasedOnMAC = false;
NetworkInterface ni = null;
try {
if (getConfiguration().getServerHostname() != null && getConfiguration().getServerHostname().length() > 0) {
try {
ni = NetworkInterface.getByInetAddress(InetAddress.getByName(getConfiguration().getServerHostname()));
} catch (Exception e) {
}
} else if (get().getServer().getNi() != null) {
ni = get().getServer().getNi();
}
if (ni != null) {
byte[] addr = PMSUtil.getHardwareAddress(ni); // return null when java.net.preferIPv4Stack=true
if (addr != null) {
uuid = UUID.nameUUIDFromBytes(addr).toString();
uuidBasedOnMAC = true;
} else {
logger.info("Unable to retrieve MAC address for UUID creation: using a random one..."); //$NON-NLS-1$
}
}
} catch (Throwable e) {
logger.info("Switching to random UUID cause there's an error in getting UUID from MAC address: " + e.getMessage()); //$NON-NLS-1$
}
if (!uuidBasedOnMAC) {
if (ni != null && (ni.getDisplayName() != null || ni.getName() != null)) {
uuid = UUID.nameUUIDFromBytes((ni.getDisplayName() != null ? ni.getDisplayName() : (ni.getName() != null ? ni.getName() : "dummy")).getBytes()).toString(); //$NON-NLS-1$
} else {
uuid = UUID.randomUUID().toString();
}
}
logger.info("Using the following UUID: " + uuid); //$NON-NLS-1$
}
return "uuid:" + uuid; //$NON-NLS-1$ //$NON-NLS-2$
//return "uuid:1234567890TOTO::";
}
/**Returns the user friendly name of the UPnP server.
* @return {@link String} with the user friendly name.
*/
public String getServerName() {
if (serverName == null) {
StringBuffer sb = new StringBuffer();
sb.append(System.getProperty("os.name").replace(" ", "_")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
sb.append("-"); //$NON-NLS-1$
sb.append(System.getProperty("os.arch").replace(" ", "_")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
sb.append("-"); //$NON-NLS-1$
sb.append(System.getProperty("os.version").replace(" ", "_")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
sb.append(", UPnP/1.0, PMS/" + VERSION); //$NON-NLS-1$
serverName = sb.toString();
}
return serverName;
}
/**Returns the PMS instance. New instance is created if needed.
* @return {@link PMS}
*/
public static PMS get() {
if (instance == null) {
synchronized (lock) {
if (instance == null) {
instance = new PMS();
try {
if (instance.init()) {
logger.info("The server should now appear on your renderer"); //$NON-NLS-1$
} else {
logger.error("A serious error occurred during PMS init"); //$NON-NLS-1$
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
return instance;
}
/**
* @param filename
* @return
*/
public Format getAssociatedExtension(String filename) {
debug("Search extension for " + filename); //$NON-NLS-1$
for (Format ext : extensions) {
if (ext.match(filename)) {
debug("Found 1! " + ext.getClass().getName()); //$NON-NLS-1$
return ext.duplicate();
}
}
return null;
}
public Player getPlayer(Class<? extends Player> profileClass, Format ext) {
for (Player p : players) {
if (p.getClass().equals(profileClass) && p.type() == ext.getType() && !p.excludeFormat(ext)) {
return p;
}
}
return null;
}
public ArrayList<Player> getPlayers(ArrayList<Class<? extends Player>> profileClasses, int type) {
ArrayList<Player> compatiblePlayers = new ArrayList<Player>();
for (Player p : players) {
if (profileClasses.contains(p.getClass()) && p.type() == type) {
compatiblePlayers.add(p);
}
}
return compatiblePlayers;
}
public static void main(String args[]) throws IOException, ConfigurationException {
if (args.length > 0) {
for (int a = 0; a < args.length; a++) {
if (args[a].equals(CONSOLE)) {
System.setProperty(CONSOLE, Boolean.toString(true));
} else if (args[a].equals(NATIVELOOK)) {
System.setProperty(NATIVELOOK, Boolean.toString(true));
} else if (args[a].equals(SCROLLBARS)) {
System.setProperty(SCROLLBARS, Boolean.toString(true));
} else if (args[a].equals(NOCONSOLE)) {
System.setProperty(NOCONSOLE, Boolean.toString(true));
}
}
}
try {
Toolkit.getDefaultToolkit();
if (GraphicsEnvironment.isHeadless() && System.getProperty(NOCONSOLE) == null) {
System.setProperty(CONSOLE, Boolean.toString(true));
}
} catch (Throwable t) {
System.err.println("Toolkit error: " + t.getMessage());
if (System.getProperty(NOCONSOLE) == null) {
System.setProperty(CONSOLE, Boolean.toString(true));
}
}
configuration = new PmsConfiguration();
// Load the (optional) logback config file. This has to be called after 'new PmsConfiguration'
// as the logging starts immediately and some filters need the PmsConfiguration.
LoggingConfigFileLoader.load();
get();
try {
// let's allow us time to show up serious errors in the GUI before quitting
Thread.sleep(60000);
} catch (InterruptedException e) {
}
}
public HTTPServer getServer() {
return server;
}
public ArrayList<Format> getExtensions() {
return extensions;
}
public ArrayList<Player> getPlayers() {
return players;
}
public void save() {
try {
configuration.save();
} catch (ConfigurationException e) {
logger.error("Could not save configuration", e); //$NON-NLS-1$
}
}
public static PmsConfiguration getConfiguration() {
assert configuration != null;
return configuration;
}
}
| true | true | private boolean init() throws Exception {
registry = new WinUtils();
AutoUpdater autoUpdater = new AutoUpdater(UPDATE_SERVER_URL, VERSION);
if (System.getProperty(CONSOLE) == null) {//$NON-NLS-1$
frame = new LooksFrame(autoUpdater, configuration);
autoUpdater.pollServer();
} else {
System.out.println("GUI environment not available"); //$NON-NLS-1$
System.out.println("Switching to console mode"); //$NON-NLS-1$
frame = new DummyFrame();
}
frame.setStatusCode(0, Messages.getString("PMS.130"), "connect_no-220.png"); //$NON-NLS-1$ //$NON-NLS-2$
proxy = -1;
minimal("Starting PS3 Media Server " + VERSION); //$NON-NLS-1$
minimal("by shagrath / 2008-2011"); //$NON-NLS-1$
minimal("http://ps3mediaserver.org"); //$NON-NLS-1$
minimal("http://code.google.com/p/ps3mediaserver"); //$NON-NLS-1$
minimal("http://ps3mediaserver.blogspot.com"); //$NON-NLS-1$
minimal(""); //$NON-NLS-1$
minimal("Java: " + System.getProperty("java.version") + "-" + System.getProperty("java.vendor")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
minimal("OS: " + System.getProperty("os.name") + " " + System.getProperty("os.arch") + " " + System.getProperty("os.version")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
minimal("Encoding: " + System.getProperty("file.encoding")); //$NON-NLS-1$ //$NON-NLS-2$
String cwd = new File("").getAbsolutePath();
minimal("Working directory: " + cwd);
minimal("Temp folder: " + configuration.getTempFolder()); //$NON-NLS-1$
minimal("Logging config file: " + LoggingConfigFileLoader.getConfigFilePath()); //$NON-NLS-1$
minimal(""); //$NON-NLS-1$
minimal("Profile directory: " + configuration.getProfileDir());
String profilePath = configuration.getProfilePath();
minimal("Profile path: " + profilePath);
File profileFile = new File(profilePath);
if (profileFile.exists()) {
String status = String.format("%s%s",
profileFile.canRead() ? "r" : "-",
profileFile.canWrite() ? "w" : "-"
);
minimal("Profile status: " + status);
} else {
minimal("Profile status: no such file");
}
minimal("Profile name: " + configuration.getProfileName()); //$NON-NLS-1$
minimal(""); //$NON-NLS-1$
RendererConfiguration.loadRendererConfigurations();
minimal("Checking MPlayer font cache. It can take a minute or so.");
checkProcessExistence("MPlayer", true, null, configuration.getMplayerPath(), "dummy");
checkProcessExistence("MPlayer", true, getConfiguration().getTempFolder(), configuration.getMplayerPath(), "dummy");
minimal("Done!");
// check the existence of Vsfilter.dll
if (registry.isAvis() && registry.getAvsPluginsDir() != null) {
minimal("Found AviSynth plugins dir: " + registry.getAvsPluginsDir().getAbsolutePath()); //$NON-NLS-1$
File vsFilterdll = new File(registry.getAvsPluginsDir(), "VSFilter.dll"); //$NON-NLS-1$
if (!vsFilterdll.exists()) {
minimal("VSFilter.dll is not in the AviSynth plugins directory. This can cause problems when trying to play subtitled videos with AviSynth"); //$NON-NLS-1$
}
}
if (registry.getVlcv() != null && registry.getVlcp() != null) {
minimal("Found VideoLAN version " + registry.getVlcv() + " at: " + registry.getVlcp()); //$NON-NLS-1$ //$NON-NLS-2$
}
//check if Kerio is installed
if (registry.isKerioFirewall()) {
//todo: Warning message
}
// force use of specific dvr ms muxer when it's installed in the right place
File dvrsMsffmpegmuxer = new File("win32/dvrms/ffmpeg_MPGMUX.exe"); //$NON-NLS-1$
if (dvrsMsffmpegmuxer.exists()) {
configuration.setFfmpegAlternativePath(dvrsMsffmpegmuxer.getAbsolutePath());
}
// disable jaudiotagger logging
LogManager.getLogManager().readConfiguration(new ByteArrayInputStream("org.jaudiotagger.level=OFF".getBytes())); //$NON-NLS-1$
// wrap System.err
System.setErr(new PrintStream(new SystemErrWrapper(), true));
extensions = new ArrayList<Format>();
players = new ArrayList<Player>();
allPlayers = new ArrayList<Player>();
server = new HTTPServer(configuration.getServerPort());
registerExtensions();
/*
* XXX: keep this here (i.e. after registerExtensions and before registerPlayers) so that plugins
* can register custom players correctly (e.g. in the GUI) and/or add/replace custom formats
*
* XXX: if a plugin requires initialization/notification even earlier than
* this, then a new external listener implementing a new callback should be added
* e.g. StartupListener.registeredExtensions()
*/
try {
ExternalFactory.lookup();
} catch (Exception e) {
logger.error("Error loading plugins", e);
}
// a static block in Player doesn't work (i.e. is called too late).
// this must always be called *after* the plugins have loaded.
// here's as good a place as any
Player.initializeFinalizeTranscoderArgsListeners();
registerPlayers();
getRootFolder(RendererConfiguration.getDefaultConf());
boolean binding = false;
try {
binding = server.start();
} catch (BindException b) {
minimal("FATAL ERROR: Unable to bind on port: " + configuration.getServerPort() + ", because: " + b.getMessage()); //$NON-NLS-1$ //$NON-NLS-2$
minimal("Maybe another process is running or the hostname is wrong."); //$NON-NLS-1$
}
new Thread() {
@Override
public void run() {
try {
Thread.sleep(7000);
} catch (InterruptedException e) {
}
boolean ps3found = false;
for (RendererConfiguration r : foundRenderers) {
if (r.isPS3()) {
ps3found = true;
}
}
if (!ps3found) {
if (foundRenderers.isEmpty()) {
frame.setStatusCode(0, Messages.getString("PMS.0"), "messagebox_critical-220.png"); //$NON-NLS-1$ //$NON-NLS-2$
} else {
frame.setStatusCode(0, Messages.getString("PMS.15"), "messagebox_warning-220.png"); //$NON-NLS-1$ //$NON-NLS-2$
}
}
}
}.start();
if (!binding) {
return false;
}
if (proxy > 0) {
minimal("Starting HTTP Proxy Server on port: " + proxy); //$NON-NLS-1$
proxyServer = new ProxyServer(proxy);
}
if (getDatabase() != null) {
minimal("A tiny media library admin interface is available at: http://" + server.getHost() + ":" + server.getPort() + "/console/home");
}
frame.serverReady();
//UPNPHelper.sendByeBye();
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
try {
for (ExternalListener l : ExternalFactory.getExternalListeners()) {
l.shutdown();
}
UPNPHelper.shutDownListener();
UPNPHelper.sendByeBye();
info("Forcing shutdown of all active processes"); //$NON-NLS-1$
for (Process p : currentProcesses) {
try {
p.exitValue();
} catch (IllegalThreadStateException ise) {
debug("Forcing shutdown of process: " + p); //$NON-NLS-1$
ProcessUtil.destroy(p);
}
}
get().getServer().stop();
Thread.sleep(500);
} catch (Exception e) {
}
}
});
UPNPHelper.sendAlive();
debug("Waiting 250 milliseconds..."); //$NON-NLS-1$
Thread.sleep(250);
UPNPHelper.listen();
return true;
}
| private boolean init() throws Exception {
registry = new WinUtils();
AutoUpdater autoUpdater = new AutoUpdater(UPDATE_SERVER_URL, VERSION);
if (System.getProperty(CONSOLE) == null) {//$NON-NLS-1$
frame = new LooksFrame(autoUpdater, configuration);
autoUpdater.pollServer();
} else {
System.out.println("GUI environment not available"); //$NON-NLS-1$
System.out.println("Switching to console mode"); //$NON-NLS-1$
frame = new DummyFrame();
}
frame.setStatusCode(0, Messages.getString("PMS.130"), "connect_no-220.png"); //$NON-NLS-1$ //$NON-NLS-2$
proxy = -1;
minimal("Starting PS3 Media Server " + VERSION); //$NON-NLS-1$
minimal("by shagrath / 2008-2011"); //$NON-NLS-1$
minimal("http://ps3mediaserver.org"); //$NON-NLS-1$
minimal("http://code.google.com/p/ps3mediaserver"); //$NON-NLS-1$
minimal("http://ps3mediaserver.blogspot.com"); //$NON-NLS-1$
minimal(""); //$NON-NLS-1$
minimal("Java: " + System.getProperty("java.version") + "-" + System.getProperty("java.vendor")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
minimal("OS: " + System.getProperty("os.name") + " " + System.getProperty("os.arch") + " " + System.getProperty("os.version")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
minimal("Encoding: " + System.getProperty("file.encoding")); //$NON-NLS-1$ //$NON-NLS-2$
String cwd = new File("").getAbsolutePath();
minimal("Working directory: " + cwd);
minimal("Temp folder: " + configuration.getTempFolder()); //$NON-NLS-1$
minimal("Logging config file: " + LoggingConfigFileLoader.getConfigFilePath()); //$NON-NLS-1$
minimal(""); //$NON-NLS-1$
minimal("Profile directory: " + configuration.getProfileDir());
String profilePath = configuration.getProfilePath();
minimal("Profile path: " + profilePath);
File profileFile = new File(profilePath);
if (profileFile.exists()) {
String status = String.format("%s%s",
profileFile.canRead() ? "r" : "-",
profileFile.canWrite() ? "w" : "-"
);
minimal("Profile status: " + status);
} else {
minimal("Profile status: no such file");
}
minimal("Profile name: " + configuration.getProfileName()); //$NON-NLS-1$
minimal(""); //$NON-NLS-1$
RendererConfiguration.loadRendererConfigurations();
minimal("Checking MPlayer font cache. It can take a minute or so.");
checkProcessExistence("MPlayer", true, null, configuration.getMplayerPath(), "dummy");
if(isWindows()) {
checkProcessExistence("MPlayer", true, getConfiguration().getTempFolder(), configuration.getMplayerPath(), "dummy");
}
minimal("Done!");
// check the existence of Vsfilter.dll
if (registry.isAvis() && registry.getAvsPluginsDir() != null) {
minimal("Found AviSynth plugins dir: " + registry.getAvsPluginsDir().getAbsolutePath()); //$NON-NLS-1$
File vsFilterdll = new File(registry.getAvsPluginsDir(), "VSFilter.dll"); //$NON-NLS-1$
if (!vsFilterdll.exists()) {
minimal("VSFilter.dll is not in the AviSynth plugins directory. This can cause problems when trying to play subtitled videos with AviSynth"); //$NON-NLS-1$
}
}
if (registry.getVlcv() != null && registry.getVlcp() != null) {
minimal("Found VideoLAN version " + registry.getVlcv() + " at: " + registry.getVlcp()); //$NON-NLS-1$ //$NON-NLS-2$
}
//check if Kerio is installed
if (registry.isKerioFirewall()) {
//todo: Warning message
}
// force use of specific dvr ms muxer when it's installed in the right place
File dvrsMsffmpegmuxer = new File("win32/dvrms/ffmpeg_MPGMUX.exe"); //$NON-NLS-1$
if (dvrsMsffmpegmuxer.exists()) {
configuration.setFfmpegAlternativePath(dvrsMsffmpegmuxer.getAbsolutePath());
}
// disable jaudiotagger logging
LogManager.getLogManager().readConfiguration(new ByteArrayInputStream("org.jaudiotagger.level=OFF".getBytes())); //$NON-NLS-1$
// wrap System.err
System.setErr(new PrintStream(new SystemErrWrapper(), true));
extensions = new ArrayList<Format>();
players = new ArrayList<Player>();
allPlayers = new ArrayList<Player>();
server = new HTTPServer(configuration.getServerPort());
registerExtensions();
/*
* XXX: keep this here (i.e. after registerExtensions and before registerPlayers) so that plugins
* can register custom players correctly (e.g. in the GUI) and/or add/replace custom formats
*
* XXX: if a plugin requires initialization/notification even earlier than
* this, then a new external listener implementing a new callback should be added
* e.g. StartupListener.registeredExtensions()
*/
try {
ExternalFactory.lookup();
} catch (Exception e) {
logger.error("Error loading plugins", e);
}
// a static block in Player doesn't work (i.e. is called too late).
// this must always be called *after* the plugins have loaded.
// here's as good a place as any
Player.initializeFinalizeTranscoderArgsListeners();
registerPlayers();
getRootFolder(RendererConfiguration.getDefaultConf());
boolean binding = false;
try {
binding = server.start();
} catch (BindException b) {
minimal("FATAL ERROR: Unable to bind on port: " + configuration.getServerPort() + ", because: " + b.getMessage()); //$NON-NLS-1$ //$NON-NLS-2$
minimal("Maybe another process is running or the hostname is wrong."); //$NON-NLS-1$
}
new Thread() {
@Override
public void run() {
try {
Thread.sleep(7000);
} catch (InterruptedException e) {
}
boolean ps3found = false;
for (RendererConfiguration r : foundRenderers) {
if (r.isPS3()) {
ps3found = true;
}
}
if (!ps3found) {
if (foundRenderers.isEmpty()) {
frame.setStatusCode(0, Messages.getString("PMS.0"), "messagebox_critical-220.png"); //$NON-NLS-1$ //$NON-NLS-2$
} else {
frame.setStatusCode(0, Messages.getString("PMS.15"), "messagebox_warning-220.png"); //$NON-NLS-1$ //$NON-NLS-2$
}
}
}
}.start();
if (!binding) {
return false;
}
if (proxy > 0) {
minimal("Starting HTTP Proxy Server on port: " + proxy); //$NON-NLS-1$
proxyServer = new ProxyServer(proxy);
}
if (getDatabase() != null) {
minimal("A tiny media library admin interface is available at: http://" + server.getHost() + ":" + server.getPort() + "/console/home");
}
frame.serverReady();
//UPNPHelper.sendByeBye();
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
try {
for (ExternalListener l : ExternalFactory.getExternalListeners()) {
l.shutdown();
}
UPNPHelper.shutDownListener();
UPNPHelper.sendByeBye();
info("Forcing shutdown of all active processes"); //$NON-NLS-1$
for (Process p : currentProcesses) {
try {
p.exitValue();
} catch (IllegalThreadStateException ise) {
debug("Forcing shutdown of process: " + p); //$NON-NLS-1$
ProcessUtil.destroy(p);
}
}
get().getServer().stop();
Thread.sleep(500);
} catch (Exception e) {
}
}
});
UPNPHelper.sendAlive();
debug("Waiting 250 milliseconds..."); //$NON-NLS-1$
Thread.sleep(250);
UPNPHelper.listen();
return true;
}
|
diff --git a/src/org/openstreetmap/josm/plugins/notes/gui/action/SearchAction.java b/src/org/openstreetmap/josm/plugins/notes/gui/action/SearchAction.java
index 71c56a7..6304240 100644
--- a/src/org/openstreetmap/josm/plugins/notes/gui/action/SearchAction.java
+++ b/src/org/openstreetmap/josm/plugins/notes/gui/action/SearchAction.java
@@ -1,101 +1,101 @@
package org.openstreetmap.josm.plugins.notes.gui.action;
import static org.openstreetmap.josm.tools.I18n.tr;
import java.awt.event.ActionEvent;
import java.util.LinkedList;
import java.util.List;
import javax.swing.JOptionPane;
import org.openstreetmap.josm.Main;
import org.openstreetmap.josm.gui.widgets.HistoryChangedListener;
import org.openstreetmap.josm.plugins.notes.ConfigKeys;
import org.openstreetmap.josm.plugins.notes.Note;
import org.openstreetmap.josm.plugins.notes.NotesPlugin;
import org.openstreetmap.josm.plugins.notes.api.util.NotesApi;
import org.openstreetmap.josm.plugins.notes.gui.NotesDialog;
import org.openstreetmap.josm.plugins.notes.gui.dialogs.TextInputDialog;
public class SearchAction extends NotesAction {
private static final long serialVersionUID = 1L;
private NotesPlugin plugin;
private String searchTerm;
public SearchAction(NotesDialog dialog, NotesPlugin plugin) {
super(tr("Reopen note"), dialog);
this.plugin = plugin;
}
@Override
protected void doActionPerformed(ActionEvent e) throws Exception {
if(Main.pref.getBoolean(ConfigKeys.NOTES_API_OFFLINE)) {
JOptionPane.showMessageDialog(Main.map, "You must be in online mode to use the search feature");
canceled = true;
return;
}
List<String> history = new LinkedList<String>(Main.pref.getCollection(ConfigKeys.NOTES_SEARCH_HISTORY, new LinkedList<String>()));
HistoryChangedListener l = new HistoryChangedListener() {
public void historyChanged(List<String> history) {
Main.pref.putCollection(ConfigKeys.NOTES_SEARCH_HISTORY, history);
}
};
searchTerm = TextInputDialog.showDialog(Main.map,
tr("Search for notes?"),
tr("<html>Search for notes (will go into offline mode)</html>"),
NotesPlugin.loadIcon("find_notes.png"),
history, l);
if(searchTerm == null) {
canceled = true;
return;
}
dialog.refreshNoteStatus();
}
@Override
public void execute() throws Exception {
int noteLimit = Main.pref.getInteger(ConfigKeys.NOTES_SEARCH_LIMIT, 1000);
int daysClosed = Main.pref.getInteger(ConfigKeys.NOTES_SEARCH_DAYS_CLOSED, 0);
//make sure values are within API limits
if(noteLimit < 1) {
- System.out.println("Note download too low. Setting to 1");
- noteLimit = 1;
- Main.pref.putInteger(ConfigKeys.NOTES_SEARCH_LIMIT, noteLimit);
+ System.out.println("Note download too low. Setting to 1");
+ noteLimit = 1;
+ Main.pref.putInteger(ConfigKeys.NOTES_SEARCH_LIMIT, noteLimit);
}
if(noteLimit > NotesApi.NOTE_DOWNLOAD_LIMIT) {
- System.out.println("Note download limit too high. Setting to API limit");
- noteLimit = NotesApi.NOTE_DOWNLOAD_LIMIT;
- Main.pref.putInteger(ConfigKeys.NOTES_SEARCH_LIMIT, noteLimit);
+ System.out.println("Note download limit too high. Setting to API limit");
+ noteLimit = NotesApi.NOTE_DOWNLOAD_LIMIT;
+ Main.pref.putInteger(ConfigKeys.NOTES_SEARCH_LIMIT, noteLimit);
}
if(daysClosed < -1) {
- System.out.println("Days closed parameter too low. Setting to -1");
- daysClosed = -1;
- Main.pref.putInteger(ConfigKeys.NOTES_SEARCH_DAYS_CLOSED, daysClosed);
+ System.out.println("Days closed parameter too low. Setting to -1");
+ daysClosed = -1;
+ Main.pref.putInteger(ConfigKeys.NOTES_SEARCH_DAYS_CLOSED, daysClosed);
}
List<Note> searchResults = NotesApi.getNotesApi().searchNotes(searchTerm, noteLimit, daysClosed);
System.out.println("search results: " + searchResults.size());
plugin.getDataSet().clear();
plugin.getDataSet().addAll(searchResults);
plugin.updateGui();
dialog.setConnectionMode(true);
dialog.showQueuePanel();
Main.pref.put(ConfigKeys.NOTES_API_OFFLINE, true);
}
@Override
public String toString() {
return tr("Search term: " + searchTerm);
}
@Override
public NotesAction clone() {
SearchAction action = new SearchAction(dialog, plugin);
action.canceled = canceled;
action.searchTerm = searchTerm;
return action;
}
}
| false | true | public void execute() throws Exception {
int noteLimit = Main.pref.getInteger(ConfigKeys.NOTES_SEARCH_LIMIT, 1000);
int daysClosed = Main.pref.getInteger(ConfigKeys.NOTES_SEARCH_DAYS_CLOSED, 0);
//make sure values are within API limits
if(noteLimit < 1) {
System.out.println("Note download too low. Setting to 1");
noteLimit = 1;
Main.pref.putInteger(ConfigKeys.NOTES_SEARCH_LIMIT, noteLimit);
}
if(noteLimit > NotesApi.NOTE_DOWNLOAD_LIMIT) {
System.out.println("Note download limit too high. Setting to API limit");
noteLimit = NotesApi.NOTE_DOWNLOAD_LIMIT;
Main.pref.putInteger(ConfigKeys.NOTES_SEARCH_LIMIT, noteLimit);
}
if(daysClosed < -1) {
System.out.println("Days closed parameter too low. Setting to -1");
daysClosed = -1;
Main.pref.putInteger(ConfigKeys.NOTES_SEARCH_DAYS_CLOSED, daysClosed);
}
List<Note> searchResults = NotesApi.getNotesApi().searchNotes(searchTerm, noteLimit, daysClosed);
System.out.println("search results: " + searchResults.size());
plugin.getDataSet().clear();
plugin.getDataSet().addAll(searchResults);
plugin.updateGui();
dialog.setConnectionMode(true);
dialog.showQueuePanel();
Main.pref.put(ConfigKeys.NOTES_API_OFFLINE, true);
}
| public void execute() throws Exception {
int noteLimit = Main.pref.getInteger(ConfigKeys.NOTES_SEARCH_LIMIT, 1000);
int daysClosed = Main.pref.getInteger(ConfigKeys.NOTES_SEARCH_DAYS_CLOSED, 0);
//make sure values are within API limits
if(noteLimit < 1) {
System.out.println("Note download too low. Setting to 1");
noteLimit = 1;
Main.pref.putInteger(ConfigKeys.NOTES_SEARCH_LIMIT, noteLimit);
}
if(noteLimit > NotesApi.NOTE_DOWNLOAD_LIMIT) {
System.out.println("Note download limit too high. Setting to API limit");
noteLimit = NotesApi.NOTE_DOWNLOAD_LIMIT;
Main.pref.putInteger(ConfigKeys.NOTES_SEARCH_LIMIT, noteLimit);
}
if(daysClosed < -1) {
System.out.println("Days closed parameter too low. Setting to -1");
daysClosed = -1;
Main.pref.putInteger(ConfigKeys.NOTES_SEARCH_DAYS_CLOSED, daysClosed);
}
List<Note> searchResults = NotesApi.getNotesApi().searchNotes(searchTerm, noteLimit, daysClosed);
System.out.println("search results: " + searchResults.size());
plugin.getDataSet().clear();
plugin.getDataSet().addAll(searchResults);
plugin.updateGui();
dialog.setConnectionMode(true);
dialog.showQueuePanel();
Main.pref.put(ConfigKeys.NOTES_API_OFFLINE, true);
}
|
diff --git a/src/main/java/com/impetus/kundera/ycsb/runner/YCSBRunner.java b/src/main/java/com/impetus/kundera/ycsb/runner/YCSBRunner.java
index 077cc9d..cdaaeeb 100644
--- a/src/main/java/com/impetus/kundera/ycsb/runner/YCSBRunner.java
+++ b/src/main/java/com/impetus/kundera/ycsb/runner/YCSBRunner.java
@@ -1,230 +1,244 @@
/**
* Copyright 2012 Impetus Infotech.
*
* 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.impetus.kundera.ycsb.runner;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.math.MathContext;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.configuration.Configuration;
import com.impetus.kundera.ycsb.entities.PerformanceNoInfo;
import com.impetus.kundera.ycsb.utils.HibernateCRUDUtils;
import common.Logger;
/**
* @author vivek.mishra
*
*/
public abstract class YCSBRunner
{
protected HibernateCRUDUtils crudUtils;
protected String schema;
protected String columnFamilyOrTable;
private String clientjarlocation;
private String ycsbJarLocation;
private String propertyFile;
protected int noOfThreads;
protected String runType;
protected double releaseNo;
protected String host;
protected int port;
protected String[] clients;
protected String workLoad;
protected String currentClient;
protected String password;
protected Map<String, Double> timeTakenByClient = new HashMap<String, Double>();
private static Logger logger = Logger.getLogger(YCSBRunner.class);
public YCSBRunner(final String propertyFile, final Configuration config)
{
this.propertyFile=propertyFile;
ycsbJarLocation = config.getString("ycsbjar.location");
clientjarlocation = config.getString("clientjar.location");
host = config.getString("hosts");
schema = config.getString("schema");
columnFamilyOrTable = config.getString("columnfamilyOrTable");
releaseNo = config.getDouble("release.no");
runType = config.getString("run.type", "load");
port = config.getInt("port");
password= config.getString("password");
clients= config.getStringArray("clients");
}
public void run(final String workLoad, final int threadCount) throws IOException
{
int runCounter = crudUtils.getMaxRunSequence(new Date(), runType);
runCounter = runCounter + 1;
noOfThreads = threadCount;
// id column of performanceNoInfo table
Date id = new Date();
int counter=1;
for (String client : clients)
{
currentClient = client;
if (clientjarlocation != null && ycsbJarLocation != null && client != null && runType != null
&& host != null && schema != null && columnFamilyOrTable != null)
{
Runtime runtime = Runtime.getRuntime();
//start server
startServer(performDelete(counter),runtime);
counter++;
String runCommand = getCommandString(client,workLoad);
logger.info(runCommand);
double totalTime = 0.0;
long noOfOperations = 0;
Process process = runtime.exec(runCommand);
+ process.getErrorStream();
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line = null;
BigDecimal avgLatency=null;
BigDecimal throughput=null;
+ boolean processed = false;
while ((line = br.readLine()) != null)
{
+ processed = true;
if (line.contains("RunTime"))
{
totalTime = Double.parseDouble(line.substring(line.lastIndexOf(", ") + 2));
logger.info("Total time taken " + totalTime);
}
if (line.contains("Operations") && noOfOperations == 0)
{
noOfOperations = Long.parseLong(line.substring(line.lastIndexOf(", ") + 2));
logger.info("Total no of oprations " + noOfOperations);
}
if(line.contains("Throughput"))
{
throughput = new BigDecimal(line.substring(line.lastIndexOf(", ") + 2));
logger.info("Throughput(ops/sec) " + line);
}
if(line.contains("AverageLatency"))
{
if(avgLatency == null)
{
avgLatency = new BigDecimal(line.substring(line.lastIndexOf(", ") + 2));
logger.info("AverageLatency " + line);
}
}
/* if(line.contains("MinLatency"))
{
logger.info("MinLatency " + line);
}
if(line.contains("MaxLatency"))
{
logger.info("MaxLatency " + line);
}
*/
// if(!(line.contains("CLEANUP") || line.contains("UPDATE") || line.contains("INSERT") )){
// logger.info(line);
// }
}
+ if(!processed)
+ {
+ is = process.getErrorStream();
+ isr = new InputStreamReader(is);
+ br = new BufferedReader(isr);
+ line = null;
+ while((line=br.readLine()) != null)
+ {
+ logger.info(line);
+ }
+ }
timeTakenByClient.put(client, totalTime);
PerformanceNoInfo info = new PerformanceNoInfo(id, releaseNo, client.substring(client.lastIndexOf(".")+1), runType, noOfThreads,
noOfOperations, totalTime, runCounter);
if(avgLatency != null)
{
info.setAvgLatency(avgLatency.round(MathContext.DECIMAL32));
}
if(throughput != null)
{
info.setThroughput(throughput.round(MathContext.DECIMAL32));
}
crudUtils.persistInfo(info);
//Stop server
stopServer(runtime);
}
}
sendMail();
}
protected String getCommandString(String clazz, String workLoad)
{
StringBuilder command = new StringBuilder("java -cp ");
command.append(clientjarlocation);
command.append(":");
command.append(ycsbJarLocation);
command.append("* com.yahoo.ycsb.Client -db ");
command.append(clazz);
command.append(" -s -P ");
command.append(workLoad);
command.append(" -P ");
command.append(propertyFile);
if (noOfThreads > 1)
{
command.append(" -threads ");
command.append(noOfThreads);
}
command.append(" -");
command.append(runType);
return command.toString();
}
protected abstract void startServer(boolean performDelete, Runtime runTime);
protected abstract void stopServer(Runtime runTime);
protected abstract void sendMail();
/**
* If multiple clients are running, clear data for first time but only in case of load.
*
* @param counter client counter
* @return true, if delete needs to be performed, else false.s
*/
private boolean performDelete(int counter)
{
if(runType.equals("load"))
{
return counter == 1;
}
return false;
}
}
| false | true | public void run(final String workLoad, final int threadCount) throws IOException
{
int runCounter = crudUtils.getMaxRunSequence(new Date(), runType);
runCounter = runCounter + 1;
noOfThreads = threadCount;
// id column of performanceNoInfo table
Date id = new Date();
int counter=1;
for (String client : clients)
{
currentClient = client;
if (clientjarlocation != null && ycsbJarLocation != null && client != null && runType != null
&& host != null && schema != null && columnFamilyOrTable != null)
{
Runtime runtime = Runtime.getRuntime();
//start server
startServer(performDelete(counter),runtime);
counter++;
String runCommand = getCommandString(client,workLoad);
logger.info(runCommand);
double totalTime = 0.0;
long noOfOperations = 0;
Process process = runtime.exec(runCommand);
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line = null;
BigDecimal avgLatency=null;
BigDecimal throughput=null;
while ((line = br.readLine()) != null)
{
if (line.contains("RunTime"))
{
totalTime = Double.parseDouble(line.substring(line.lastIndexOf(", ") + 2));
logger.info("Total time taken " + totalTime);
}
if (line.contains("Operations") && noOfOperations == 0)
{
noOfOperations = Long.parseLong(line.substring(line.lastIndexOf(", ") + 2));
logger.info("Total no of oprations " + noOfOperations);
}
if(line.contains("Throughput"))
{
throughput = new BigDecimal(line.substring(line.lastIndexOf(", ") + 2));
logger.info("Throughput(ops/sec) " + line);
}
if(line.contains("AverageLatency"))
{
if(avgLatency == null)
{
avgLatency = new BigDecimal(line.substring(line.lastIndexOf(", ") + 2));
logger.info("AverageLatency " + line);
}
}
/* if(line.contains("MinLatency"))
{
logger.info("MinLatency " + line);
}
if(line.contains("MaxLatency"))
{
logger.info("MaxLatency " + line);
}
*/
// if(!(line.contains("CLEANUP") || line.contains("UPDATE") || line.contains("INSERT") )){
// logger.info(line);
// }
}
timeTakenByClient.put(client, totalTime);
PerformanceNoInfo info = new PerformanceNoInfo(id, releaseNo, client.substring(client.lastIndexOf(".")+1), runType, noOfThreads,
noOfOperations, totalTime, runCounter);
if(avgLatency != null)
{
info.setAvgLatency(avgLatency.round(MathContext.DECIMAL32));
}
if(throughput != null)
{
info.setThroughput(throughput.round(MathContext.DECIMAL32));
}
crudUtils.persistInfo(info);
//Stop server
stopServer(runtime);
}
}
sendMail();
}
| public void run(final String workLoad, final int threadCount) throws IOException
{
int runCounter = crudUtils.getMaxRunSequence(new Date(), runType);
runCounter = runCounter + 1;
noOfThreads = threadCount;
// id column of performanceNoInfo table
Date id = new Date();
int counter=1;
for (String client : clients)
{
currentClient = client;
if (clientjarlocation != null && ycsbJarLocation != null && client != null && runType != null
&& host != null && schema != null && columnFamilyOrTable != null)
{
Runtime runtime = Runtime.getRuntime();
//start server
startServer(performDelete(counter),runtime);
counter++;
String runCommand = getCommandString(client,workLoad);
logger.info(runCommand);
double totalTime = 0.0;
long noOfOperations = 0;
Process process = runtime.exec(runCommand);
process.getErrorStream();
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line = null;
BigDecimal avgLatency=null;
BigDecimal throughput=null;
boolean processed = false;
while ((line = br.readLine()) != null)
{
processed = true;
if (line.contains("RunTime"))
{
totalTime = Double.parseDouble(line.substring(line.lastIndexOf(", ") + 2));
logger.info("Total time taken " + totalTime);
}
if (line.contains("Operations") && noOfOperations == 0)
{
noOfOperations = Long.parseLong(line.substring(line.lastIndexOf(", ") + 2));
logger.info("Total no of oprations " + noOfOperations);
}
if(line.contains("Throughput"))
{
throughput = new BigDecimal(line.substring(line.lastIndexOf(", ") + 2));
logger.info("Throughput(ops/sec) " + line);
}
if(line.contains("AverageLatency"))
{
if(avgLatency == null)
{
avgLatency = new BigDecimal(line.substring(line.lastIndexOf(", ") + 2));
logger.info("AverageLatency " + line);
}
}
/* if(line.contains("MinLatency"))
{
logger.info("MinLatency " + line);
}
if(line.contains("MaxLatency"))
{
logger.info("MaxLatency " + line);
}
*/
// if(!(line.contains("CLEANUP") || line.contains("UPDATE") || line.contains("INSERT") )){
// logger.info(line);
// }
}
if(!processed)
{
is = process.getErrorStream();
isr = new InputStreamReader(is);
br = new BufferedReader(isr);
line = null;
while((line=br.readLine()) != null)
{
logger.info(line);
}
}
timeTakenByClient.put(client, totalTime);
PerformanceNoInfo info = new PerformanceNoInfo(id, releaseNo, client.substring(client.lastIndexOf(".")+1), runType, noOfThreads,
noOfOperations, totalTime, runCounter);
if(avgLatency != null)
{
info.setAvgLatency(avgLatency.round(MathContext.DECIMAL32));
}
if(throughput != null)
{
info.setThroughput(throughput.round(MathContext.DECIMAL32));
}
crudUtils.persistInfo(info);
//Stop server
stopServer(runtime);
}
}
sendMail();
}
|
diff --git a/modules/dCache/diskCacheV111/services/PnfsManagerFileMetaDataSource.java b/modules/dCache/diskCacheV111/services/PnfsManagerFileMetaDataSource.java
index fd405cce44..77f84bdc85 100644
--- a/modules/dCache/diskCacheV111/services/PnfsManagerFileMetaDataSource.java
+++ b/modules/dCache/diskCacheV111/services/PnfsManagerFileMetaDataSource.java
@@ -1,66 +1,66 @@
package diskCacheV111.services;
import diskCacheV111.util.CacheException;
import diskCacheV111.util.FileMetaData;
import diskCacheV111.util.FileMetaDataX;
import diskCacheV111.util.PnfsHandler;
import diskCacheV111.util.PnfsId;
import diskCacheV111.vehicles.PnfsGetFileMetaDataMessage;
import dmg.cells.nucleus.CellAdapter;
import dmg.cells.nucleus.CellPath;
public class PnfsManagerFileMetaDataSource implements FileMetaDataSource {
private final CellAdapter _cell ;
private static final int __pnfsTimeout = 5 * 60 * 1000 ;
private final PnfsHandler _handler;
public PnfsManagerFileMetaDataSource(CellAdapter cell) {
_cell = cell;
String pnfsManager = _cell.getArgs().getOpt("pnfsManager");
if(pnfsManager == null ) {
pnfsManager = "PnfsManager";
}
_handler = new PnfsHandler( _cell , new CellPath( pnfsManager ) ) ;
- _handler.setPnfsTimeout(__pnfsTimeout*1000L);
+ _handler.setPnfsTimeout(__pnfsTimeout);
}
public FileMetaData getMetaData(String path) throws CacheException {
PnfsGetFileMetaDataMessage info = _handler.getFileMetaDataByPath(path);
if( info.getReturnCode() != 0) {
throw new CacheException( info.getReturnCode(), "unable to get metadata of " + path);
}
return info.getMetaData();
}
public FileMetaData getMetaData(PnfsId pnfsId) throws CacheException {
PnfsGetFileMetaDataMessage info = _handler.getFileMetaDataById(pnfsId);
if( info.getReturnCode() != 0) {
throw new CacheException( info.getReturnCode(), "unable to get metadata of " + pnfsId);
}
return info.getMetaData();
}
public FileMetaDataX getXMetaData(String path) throws CacheException {
PnfsGetFileMetaDataMessage info = _handler.getFileMetaDataByPath(path);
if( info.getReturnCode() != 0) {
throw new CacheException( info.getReturnCode(), "unable to get metadata of " + path);
}
return new FileMetaDataX(info.getPnfsId(), info.getMetaData() );
}
public FileMetaDataX getXMetaData(PnfsId pnfsId) throws CacheException {
return new FileMetaDataX(pnfsId, getMetaData(pnfsId) );
}
}
| true | true | public PnfsManagerFileMetaDataSource(CellAdapter cell) {
_cell = cell;
String pnfsManager = _cell.getArgs().getOpt("pnfsManager");
if(pnfsManager == null ) {
pnfsManager = "PnfsManager";
}
_handler = new PnfsHandler( _cell , new CellPath( pnfsManager ) ) ;
_handler.setPnfsTimeout(__pnfsTimeout*1000L);
}
| public PnfsManagerFileMetaDataSource(CellAdapter cell) {
_cell = cell;
String pnfsManager = _cell.getArgs().getOpt("pnfsManager");
if(pnfsManager == null ) {
pnfsManager = "PnfsManager";
}
_handler = new PnfsHandler( _cell , new CellPath( pnfsManager ) ) ;
_handler.setPnfsTimeout(__pnfsTimeout);
}
|
diff --git a/src/com/android/mms/transaction/TransactionSettings.java b/src/com/android/mms/transaction/TransactionSettings.java
index a0862989..ba37d19c 100644
--- a/src/com/android/mms/transaction/TransactionSettings.java
+++ b/src/com/android/mms/transaction/TransactionSettings.java
@@ -1,166 +1,170 @@
/*
* Copyright (C) 2007-2008 Esmertec AG.
* Copyright (C) 2007-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.mms.transaction;
import android.database.sqlite.SqliteWrapper;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import com.android.internal.telephony.Phone;
import com.android.mms.LogTag;
import android.net.NetworkUtils;
import android.provider.Telephony;
import android.text.TextUtils;
import android.util.Log;
/**
* Container of transaction settings. Instances of this class are contained
* within Transaction instances to allow overriding of the default APN
* settings or of the MMS Client.
*/
public class TransactionSettings {
private static final String TAG = "TransactionSettings";
private static final boolean DEBUG = true;
private static final boolean LOCAL_LOGV = false;
private String mServiceCenter;
private String mProxyAddress;
private int mProxyPort = -1;
private static final String[] APN_PROJECTION = {
Telephony.Carriers.TYPE, // 0
Telephony.Carriers.MMSC, // 1
Telephony.Carriers.MMSPROXY, // 2
Telephony.Carriers.MMSPORT // 3
};
private static final int COLUMN_TYPE = 0;
private static final int COLUMN_MMSC = 1;
private static final int COLUMN_MMSPROXY = 2;
private static final int COLUMN_MMSPORT = 3;
/**
* Constructor that uses the default settings of the MMS Client.
*
* @param context The context of the MMS Client
*/
public TransactionSettings(Context context, String apnName) {
- String selection = TextUtils.isEmpty(apnName) ? null :
- Telephony.Carriers.APN + "='" + apnName.trim() + "'";
+ String selection = Telephony.Carriers.CURRENT + " IS NOT NULL";
+ String[] selectionArgs = null;
+ if (apnName != null) {
+ selection += " AND " + Telephony.Carriers.APN + "=?";
+ selectionArgs = new String[]{ apnName.trim() };
+ }
Cursor cursor = SqliteWrapper.query(context, context.getContentResolver(),
- Uri.withAppendedPath(Telephony.Carriers.CONTENT_URI, "current"),
- APN_PROJECTION, selection, null, null);
+ Telephony.Carriers.CONTENT_URI,
+ APN_PROJECTION, selection, selectionArgs, null);
if (Log.isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
Log.v(TAG, "TransactionSettings looking for apn: " + selection + " returned: " +
(cursor ==null ? "null cursor" : (cursor.getCount() + " hits")));
}
if (cursor == null) {
Log.e(TAG, "Apn is not found in Database!");
return;
}
boolean sawValidApn = false;
try {
while (cursor.moveToNext() && TextUtils.isEmpty(mServiceCenter)) {
// Read values from APN settings
if (isValidApnType(cursor.getString(COLUMN_TYPE), Phone.APN_TYPE_MMS)) {
sawValidApn = true;
mServiceCenter = NetworkUtils.trimV4AddrZeros(
cursor.getString(COLUMN_MMSC).trim());
mProxyAddress = NetworkUtils.trimV4AddrZeros(
cursor.getString(COLUMN_MMSPROXY));
if (isProxySet()) {
String portString = cursor.getString(COLUMN_MMSPORT);
try {
mProxyPort = Integer.parseInt(portString);
} catch (NumberFormatException e) {
if (TextUtils.isEmpty(portString)) {
Log.w(TAG, "mms port not set!");
} else {
Log.e(TAG, "Bad port number format: " + portString, e);
}
}
}
}
}
} finally {
cursor.close();
}
Log.v(TAG, "APN setting: MMSC: " + mServiceCenter + " looked for: " + selection);
if (sawValidApn && TextUtils.isEmpty(mServiceCenter)) {
Log.e(TAG, "Invalid APN setting: MMSC is empty");
}
}
/**
* Constructor that overrides the default settings of the MMS Client.
*
* @param mmscUrl The MMSC URL
* @param proxyAddr The proxy address
* @param proxyPort The port used by the proxy address
* immediately start a SendTransaction upon completion of a NotificationTransaction,
* false otherwise.
*/
public TransactionSettings(String mmscUrl, String proxyAddr, int proxyPort) {
mServiceCenter = mmscUrl != null ? mmscUrl.trim() : null;
mProxyAddress = proxyAddr;
mProxyPort = proxyPort;
if (Log.isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
Log.v(TAG, "TransactionSettings: " + mServiceCenter +
" proxyAddress: " + mProxyAddress +
" proxyPort: " + mProxyPort);
}
}
public String getMmscUrl() {
return mServiceCenter;
}
public String getProxyAddress() {
return mProxyAddress;
}
public int getProxyPort() {
return mProxyPort;
}
public boolean isProxySet() {
return (mProxyAddress != null) && (mProxyAddress.trim().length() != 0);
}
static private boolean isValidApnType(String types, String requestType) {
// If APN type is unspecified, assume APN_TYPE_ALL.
if (TextUtils.isEmpty(types)) {
return true;
}
for (String t : types.split(",")) {
if (t.equals(requestType) || t.equals(Phone.APN_TYPE_ALL)) {
return true;
}
}
return false;
}
}
| false | true | public TransactionSettings(Context context, String apnName) {
String selection = TextUtils.isEmpty(apnName) ? null :
Telephony.Carriers.APN + "='" + apnName.trim() + "'";
Cursor cursor = SqliteWrapper.query(context, context.getContentResolver(),
Uri.withAppendedPath(Telephony.Carriers.CONTENT_URI, "current"),
APN_PROJECTION, selection, null, null);
if (Log.isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
Log.v(TAG, "TransactionSettings looking for apn: " + selection + " returned: " +
(cursor ==null ? "null cursor" : (cursor.getCount() + " hits")));
}
if (cursor == null) {
Log.e(TAG, "Apn is not found in Database!");
return;
}
boolean sawValidApn = false;
try {
while (cursor.moveToNext() && TextUtils.isEmpty(mServiceCenter)) {
// Read values from APN settings
if (isValidApnType(cursor.getString(COLUMN_TYPE), Phone.APN_TYPE_MMS)) {
sawValidApn = true;
mServiceCenter = NetworkUtils.trimV4AddrZeros(
cursor.getString(COLUMN_MMSC).trim());
mProxyAddress = NetworkUtils.trimV4AddrZeros(
cursor.getString(COLUMN_MMSPROXY));
if (isProxySet()) {
String portString = cursor.getString(COLUMN_MMSPORT);
try {
mProxyPort = Integer.parseInt(portString);
} catch (NumberFormatException e) {
if (TextUtils.isEmpty(portString)) {
Log.w(TAG, "mms port not set!");
} else {
Log.e(TAG, "Bad port number format: " + portString, e);
}
}
}
}
}
} finally {
cursor.close();
}
Log.v(TAG, "APN setting: MMSC: " + mServiceCenter + " looked for: " + selection);
if (sawValidApn && TextUtils.isEmpty(mServiceCenter)) {
Log.e(TAG, "Invalid APN setting: MMSC is empty");
}
}
| public TransactionSettings(Context context, String apnName) {
String selection = Telephony.Carriers.CURRENT + " IS NOT NULL";
String[] selectionArgs = null;
if (apnName != null) {
selection += " AND " + Telephony.Carriers.APN + "=?";
selectionArgs = new String[]{ apnName.trim() };
}
Cursor cursor = SqliteWrapper.query(context, context.getContentResolver(),
Telephony.Carriers.CONTENT_URI,
APN_PROJECTION, selection, selectionArgs, null);
if (Log.isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
Log.v(TAG, "TransactionSettings looking for apn: " + selection + " returned: " +
(cursor ==null ? "null cursor" : (cursor.getCount() + " hits")));
}
if (cursor == null) {
Log.e(TAG, "Apn is not found in Database!");
return;
}
boolean sawValidApn = false;
try {
while (cursor.moveToNext() && TextUtils.isEmpty(mServiceCenter)) {
// Read values from APN settings
if (isValidApnType(cursor.getString(COLUMN_TYPE), Phone.APN_TYPE_MMS)) {
sawValidApn = true;
mServiceCenter = NetworkUtils.trimV4AddrZeros(
cursor.getString(COLUMN_MMSC).trim());
mProxyAddress = NetworkUtils.trimV4AddrZeros(
cursor.getString(COLUMN_MMSPROXY));
if (isProxySet()) {
String portString = cursor.getString(COLUMN_MMSPORT);
try {
mProxyPort = Integer.parseInt(portString);
} catch (NumberFormatException e) {
if (TextUtils.isEmpty(portString)) {
Log.w(TAG, "mms port not set!");
} else {
Log.e(TAG, "Bad port number format: " + portString, e);
}
}
}
}
}
} finally {
cursor.close();
}
Log.v(TAG, "APN setting: MMSC: " + mServiceCenter + " looked for: " + selection);
if (sawValidApn && TextUtils.isEmpty(mServiceCenter)) {
Log.e(TAG, "Invalid APN setting: MMSC is empty");
}
}
|
diff --git a/src/main/java/com/helemus/maven/misc/ScmInitMojo.java b/src/main/java/com/helemus/maven/misc/ScmInitMojo.java
index 81046b9..2bcb68c 100644
--- a/src/main/java/com/helemus/maven/misc/ScmInitMojo.java
+++ b/src/main/java/com/helemus/maven/misc/ScmInitMojo.java
@@ -1,115 +1,118 @@
package com.helemus.maven.misc;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import org.apache.maven.model.Model;
import org.apache.maven.model.Scm;
import org.apache.maven.model.io.xpp3.MavenXpp3Reader;
import org.apache.maven.model.io.xpp3.MavenXpp3Writer;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.codehaus.plexus.util.cli.CommandLineException;
import org.codehaus.plexus.util.cli.CommandLineUtils;
import org.codehaus.plexus.util.cli.Commandline;
import org.codehaus.plexus.util.cli.StreamConsumer;
/**
* Goal which sets up the scm info in a pom.
*
* @goal init-scm
*/
public class ScmInitMojo extends AbstractMojo {
/**
* Location of the base directory.
*
* @parameter expression="${basedir}"
* @required
*/
private File basedir;
/**
* Location of the pom file.
*
* @parameter expression="${basedir}/pom.xml"
* @required
*/
private File pomFile;
public void execute() throws MojoExecutionException {
try {
MavenXpp3Reader mavenReader = new MavenXpp3Reader();
Model model = mavenReader.read(new FileReader(pomFile));
if (model.getScm() == null) {
String scmURL = getGitUrl();
if (scmURL != null) {
Scm scm = new Scm();
scm.setConnection(scmURL);
scm.setDeveloperConnection(scmURL);
String viewURL = getViewURL(scmURL);
if (viewURL != null) {
scm.setUrl(viewURL);
}
model.setScm(scm);
new MavenXpp3Writer().write(new FileWriter(pomFile), model);
return;
}
getLog().warn("No SCM found.");
} else {
getLog().info("POM already has SCM section.");
}
} catch (Exception e) {
throw new MojoExecutionException("Unable to execute", e);
}
}
private String getViewURL(String url) {
if (url.startsWith("scm:git:[email protected]:")) {
String str = "http://github.com/" + url.substring("scm:git:git://github.com:".length());
return str.substring(0, str.length() - 4);
}
return null;
}
private String getGitUrl() throws CommandLineException {
Commandline cmd = new Commandline("git remote show origin");
cmd.setWorkingDirectory(basedir);
final StringBuilder builder = new StringBuilder();
CommandLineUtils.executeCommandLine(cmd, new StreamConsumer() {
public void consumeLine(String line) {
getLog().debug("** " + line);
- int idx = line.indexOf("URL:");
- if (idx >= 0) {
- getLog().debug("found url line '" + line+"'");
- String postUrl = line.trim().substring(idx+3);
- getLog().debug("post url = '" + postUrl+"'");
- builder.append(postUrl);
+ if (builder.length() == 0) {
+ int idx = line.indexOf("URL:");
+ if (idx >= 0) {
+ getLog().debug("found url line '" + line + "'");
+ String postUrl = line.trim().substring(idx + 3);
+ getLog().debug("post url = '" + postUrl + "'");
+ builder.append(postUrl);
+ }
}
}
}, new StreamConsumer() {
public void consumeLine(String line) {
getLog().error(line);
}
});
String str = builder.toString();
- getLog().debug("got string '" + str+"'");
+ getLog().debug("got string '" + str + "'");
if (builder.length() > 0) {
- /*if (str.startsWith("git@")) {
- return "scm:git:git://" + str.substring(4);
- } else {*/
- return "scm:git:" + str;
- //}
+ /*
+ * if (str.startsWith("git@")) { return "scm:git:git://" +
+ * str.substring(4); } else {
+ */
+ return "scm:git:" + str;
+ // }
}
return null;
}
}
| false | true | private String getGitUrl() throws CommandLineException {
Commandline cmd = new Commandline("git remote show origin");
cmd.setWorkingDirectory(basedir);
final StringBuilder builder = new StringBuilder();
CommandLineUtils.executeCommandLine(cmd, new StreamConsumer() {
public void consumeLine(String line) {
getLog().debug("** " + line);
int idx = line.indexOf("URL:");
if (idx >= 0) {
getLog().debug("found url line '" + line+"'");
String postUrl = line.trim().substring(idx+3);
getLog().debug("post url = '" + postUrl+"'");
builder.append(postUrl);
}
}
}, new StreamConsumer() {
public void consumeLine(String line) {
getLog().error(line);
}
});
String str = builder.toString();
getLog().debug("got string '" + str+"'");
if (builder.length() > 0) {
/*if (str.startsWith("git@")) {
return "scm:git:git://" + str.substring(4);
} else {*/
return "scm:git:" + str;
//}
}
return null;
}
| private String getGitUrl() throws CommandLineException {
Commandline cmd = new Commandline("git remote show origin");
cmd.setWorkingDirectory(basedir);
final StringBuilder builder = new StringBuilder();
CommandLineUtils.executeCommandLine(cmd, new StreamConsumer() {
public void consumeLine(String line) {
getLog().debug("** " + line);
if (builder.length() == 0) {
int idx = line.indexOf("URL:");
if (idx >= 0) {
getLog().debug("found url line '" + line + "'");
String postUrl = line.trim().substring(idx + 3);
getLog().debug("post url = '" + postUrl + "'");
builder.append(postUrl);
}
}
}
}, new StreamConsumer() {
public void consumeLine(String line) {
getLog().error(line);
}
});
String str = builder.toString();
getLog().debug("got string '" + str + "'");
if (builder.length() > 0) {
/*
* if (str.startsWith("git@")) { return "scm:git:git://" +
* str.substring(4); } else {
*/
return "scm:git:" + str;
// }
}
return null;
}
|
diff --git a/components/patient-measurements/migrations/src/main/java/edu/toronto/cs/internal/R45390PhenoTips433DataMigration.java b/components/patient-measurements/migrations/src/main/java/edu/toronto/cs/internal/R45390PhenoTips433DataMigration.java
index bbcfabe1d..c436d05bd 100644
--- a/components/patient-measurements/migrations/src/main/java/edu/toronto/cs/internal/R45390PhenoTips433DataMigration.java
+++ b/components/patient-measurements/migrations/src/main/java/edu/toronto/cs/internal/R45390PhenoTips433DataMigration.java
@@ -1,156 +1,156 @@
/*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* This 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 software 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 software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package edu.toronto.cs.internal;
import java.util.Collections;
import java.util.List;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.xwiki.component.annotation.Component;
import org.xwiki.model.EntityType;
import org.xwiki.model.reference.DocumentReference;
import org.xwiki.model.reference.DocumentReferenceResolver;
import org.xwiki.model.reference.EntityReference;
import org.xwiki.model.reference.EntityReferenceSerializer;
import com.xpn.xwiki.XWiki;
import com.xpn.xwiki.XWikiContext;
import com.xpn.xwiki.XWikiException;
import com.xpn.xwiki.doc.XWikiDocument;
import com.xpn.xwiki.objects.BaseObject;
import com.xpn.xwiki.objects.BaseProperty;
import com.xpn.xwiki.store.XWikiHibernateBaseStore.HibernateCallback;
import com.xpn.xwiki.store.XWikiHibernateStore;
import com.xpn.xwiki.store.migration.DataMigrationException;
import com.xpn.xwiki.store.migration.XWikiDBVersion;
import com.xpn.xwiki.store.migration.hibernate.AbstractHibernateDataMigration;
/**
* Migration for PhenoTips issue #433: Automatically migrate existing old
* {@code ClinicalInformationCode.MeasurementsClass} to the new {@code PhenoTips.MeasurementsClass}.
*
* @version $Id$
* @since 1.0M6
*/
@Component
@Named("R45390Phenotips#433")
@Singleton
public class R45390PhenoTips433DataMigration extends AbstractHibernateDataMigration
{
/** The old class, without a wiki specified. */
private static final EntityReference OLD_CLASS = new EntityReference("MeasurementsClass", EntityType.DOCUMENT,
new EntityReference("ClinicalInformationCode", EntityType.SPACE));
/** The new class, without a wiki specified. */
private static final EntityReference NEW_CLASS = new EntityReference(OLD_CLASS.getName(), EntityType.DOCUMENT,
new EntityReference("PhenoTips", EntityType.SPACE));
/** Resolves unprefixed document names to the current wiki. */
@Inject
@Named("current")
private DocumentReferenceResolver<String> resolver;
/** Resolves class names to the current wiki. */
@Inject
@Named("current")
private DocumentReferenceResolver<EntityReference> entityResolver;
/** Serializes the class name without the wiki prefix, to be used in the database query. */
@Inject
@Named("compactwiki")
private EntityReferenceSerializer<String> serializer;
@Override
public String getDescription()
{
return "Migrate existing old ClinicalInformationCode.MeasurementsClass to the new PhenoTips.MeasurementsClass";
}
@Override
public XWikiDBVersion getVersion()
{
return new XWikiDBVersion(45390);
}
@Override
public void hibernateMigrate() throws DataMigrationException, XWikiException
{
getStore().executeWrite(getXWikiContext(), new MigrateObjectsCallback());
}
/**
* Searches for all documents containing {@code ClinicalInformationCode.MeasurementsClass} objects, and for each
* such documents and foreach such object, creates a new {@code PhenoTips.MeasurementsClass} object and copies all
* the values from the deprecated object to the new one, and then deletes the old objects.
*/
private class MigrateObjectsCallback implements HibernateCallback<Object>
{
@Override
public Object doInHibernate(Session session) throws HibernateException, XWikiException
{
XWikiContext context = getXWikiContext();
XWiki xwiki = context.getWiki();
DocumentReference oldClassReference =
R45390PhenoTips433DataMigration.this.entityResolver.resolve(OLD_CLASS);
DocumentReference newClassReference =
R45390PhenoTips433DataMigration.this.entityResolver.resolve(NEW_CLASS);
Query q =
session.createQuery("select distinct o.name from BaseObject o where o.className = '"
+ R45390PhenoTips433DataMigration.this.serializer.serialize(oldClassReference) + "'");
List<String> documents = q.list();
for (String docName : documents) {
XWikiDocument doc =
xwiki.getDocument(R45390PhenoTips433DataMigration.this.resolver.resolve(docName), context);
for (BaseObject oldObject : doc.getXObjects(oldClassReference)) {
BaseObject newObject = oldObject.duplicate();
newObject.setXClassReference(newClassReference);
doc.addXObject(newObject);
// "head_circumference" has been renamed to "hc"
BaseProperty hc = (BaseProperty) newObject.get("head_circumference");
if (hc != null && hc.getValue() != null) {
newObject.removeField(hc.getName());
newObject.setFieldsToRemove(Collections.emptyList());
newObject.safeput("hc", hc);
}
}
doc.removeXObjects(oldClassReference);
doc.setComment("Migrated measurements");
doc.setMinorEdit(true);
try {
// There's a bug in XWiki which prevents saving an object in the same session that it was loaded,
// so we must clear the session cache first.
session.clear();
- ((XWikiHibernateStore) getStore()).saveXWikiDoc(doc, context, true);
+ ((XWikiHibernateStore) getStore()).saveXWikiDoc(doc, context, false);
session.flush();
} catch (DataMigrationException e) {
// We're in the middle of a migration, we're not expecting another migration
}
}
return null;
}
}
}
| true | true | public Object doInHibernate(Session session) throws HibernateException, XWikiException
{
XWikiContext context = getXWikiContext();
XWiki xwiki = context.getWiki();
DocumentReference oldClassReference =
R45390PhenoTips433DataMigration.this.entityResolver.resolve(OLD_CLASS);
DocumentReference newClassReference =
R45390PhenoTips433DataMigration.this.entityResolver.resolve(NEW_CLASS);
Query q =
session.createQuery("select distinct o.name from BaseObject o where o.className = '"
+ R45390PhenoTips433DataMigration.this.serializer.serialize(oldClassReference) + "'");
List<String> documents = q.list();
for (String docName : documents) {
XWikiDocument doc =
xwiki.getDocument(R45390PhenoTips433DataMigration.this.resolver.resolve(docName), context);
for (BaseObject oldObject : doc.getXObjects(oldClassReference)) {
BaseObject newObject = oldObject.duplicate();
newObject.setXClassReference(newClassReference);
doc.addXObject(newObject);
// "head_circumference" has been renamed to "hc"
BaseProperty hc = (BaseProperty) newObject.get("head_circumference");
if (hc != null && hc.getValue() != null) {
newObject.removeField(hc.getName());
newObject.setFieldsToRemove(Collections.emptyList());
newObject.safeput("hc", hc);
}
}
doc.removeXObjects(oldClassReference);
doc.setComment("Migrated measurements");
doc.setMinorEdit(true);
try {
// There's a bug in XWiki which prevents saving an object in the same session that it was loaded,
// so we must clear the session cache first.
session.clear();
((XWikiHibernateStore) getStore()).saveXWikiDoc(doc, context, true);
session.flush();
} catch (DataMigrationException e) {
// We're in the middle of a migration, we're not expecting another migration
}
}
return null;
}
| public Object doInHibernate(Session session) throws HibernateException, XWikiException
{
XWikiContext context = getXWikiContext();
XWiki xwiki = context.getWiki();
DocumentReference oldClassReference =
R45390PhenoTips433DataMigration.this.entityResolver.resolve(OLD_CLASS);
DocumentReference newClassReference =
R45390PhenoTips433DataMigration.this.entityResolver.resolve(NEW_CLASS);
Query q =
session.createQuery("select distinct o.name from BaseObject o where o.className = '"
+ R45390PhenoTips433DataMigration.this.serializer.serialize(oldClassReference) + "'");
List<String> documents = q.list();
for (String docName : documents) {
XWikiDocument doc =
xwiki.getDocument(R45390PhenoTips433DataMigration.this.resolver.resolve(docName), context);
for (BaseObject oldObject : doc.getXObjects(oldClassReference)) {
BaseObject newObject = oldObject.duplicate();
newObject.setXClassReference(newClassReference);
doc.addXObject(newObject);
// "head_circumference" has been renamed to "hc"
BaseProperty hc = (BaseProperty) newObject.get("head_circumference");
if (hc != null && hc.getValue() != null) {
newObject.removeField(hc.getName());
newObject.setFieldsToRemove(Collections.emptyList());
newObject.safeput("hc", hc);
}
}
doc.removeXObjects(oldClassReference);
doc.setComment("Migrated measurements");
doc.setMinorEdit(true);
try {
// There's a bug in XWiki which prevents saving an object in the same session that it was loaded,
// so we must clear the session cache first.
session.clear();
((XWikiHibernateStore) getStore()).saveXWikiDoc(doc, context, false);
session.flush();
} catch (DataMigrationException e) {
// We're in the middle of a migration, we're not expecting another migration
}
}
return null;
}
|
diff --git a/src/main/java/org/fusesource/camel/component/salesforce/api/DefaultRestClient.java b/src/main/java/org/fusesource/camel/component/salesforce/api/DefaultRestClient.java
index c1fc2ca..785d5a8 100644
--- a/src/main/java/org/fusesource/camel/component/salesforce/api/DefaultRestClient.java
+++ b/src/main/java/org/fusesource/camel/component/salesforce/api/DefaultRestClient.java
@@ -1,390 +1,393 @@
/**
* 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.fusesource.camel.component.salesforce.api;
import com.thoughtworks.xstream.XStream;
import org.apache.http.Consts;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.*;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.util.EntityUtils;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;
import org.fusesource.camel.component.salesforce.api.dto.RestError;
import org.fusesource.camel.component.salesforce.internal.dto.RestErrors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;
public class DefaultRestClient implements RestClient {
private static final Logger LOG = LoggerFactory.getLogger(DefaultRestClient.class);
private static final int SESSION_EXPIRED = 401;
private static final String SERVICES_DATA = "/services/data/";
private static final ContentType APPLICATION_JSON_UTF8 = ContentType.create("application/json", Consts.UTF_8);
private static final ContentType APPLICATION_XML_UTF8 = ContentType.create("application/xml", Consts.UTF_8);
private HttpClient httpClient;
private String version;
private String format;
private SalesforceSession session;
private ObjectMapper objectMapper;
private String accessToken;
private String instanceUrl;
private XStream xStream;
public DefaultRestClient(HttpClient httpClient, String version, String format, SalesforceSession session) {
this.httpClient = httpClient;
this.version = version;
this.format = format;
this.session = session;
// initialize error parsers for JSON and XML
this.objectMapper = new ObjectMapper();
this.xStream = new XStream();
xStream.processAnnotations(RestErrors.class);
// local cache
this.accessToken = session.getAccessToken();
this.instanceUrl = session.getInstanceUrl();
}
private InputStream doHttpRequest(HttpUriRequest request) throws RestException {
HttpResponse httpResponse = null;
try {
// set standard headers for all requests
final String contentType = ("json".equals(format) ? APPLICATION_JSON_UTF8 : APPLICATION_XML_UTF8).toString();
request.setHeader("Accept", contentType);
request.setHeader("Accept-Charset", Consts.UTF_8.toString());
// request content type and charset is set by the request entity
// execute the request
httpResponse = httpClient.execute(request);
// check response for session timeout
final StatusLine statusLine = httpResponse.getStatusLine();
if (statusLine.getStatusCode() == SESSION_EXPIRED) {
// use the session to get a new accessToken and try the request again
LOG.warn("Retrying {} on session expiry: {}", request.getMethod(), statusLine.getReasonPhrase());
accessToken = session.login(accessToken);
instanceUrl = session.getInstanceUrl();
setAccessToken(request);
httpResponse = httpClient.execute(request);
}
final int statusCode = httpResponse.getStatusLine().getStatusCode();
if (statusCode < 200 || statusCode >= 300) {
+ LOG.error(String.format("Error {%s:%s} executing {%s:%s}",
+ statusCode, statusLine.getReasonPhrase(),
+ request.getMethod(),request.getURI()));
throw createRestException(httpResponse);
} else {
return (httpResponse.getEntity() == null) ?
null : httpResponse.getEntity().getContent();
}
} catch (IOException e) {
request.abort();
if (httpResponse != null) {
EntityUtils.consumeQuietly(httpResponse.getEntity());
}
String msg = "Unexpected Error: " + e.getMessage();
LOG.error(msg, e);
throw new RestException(msg, e);
} catch (RuntimeException e) {
request.abort();
if (httpResponse != null) {
EntityUtils.consumeQuietly(httpResponse.getEntity());
}
String msg = "Unexpected Error: " + e.getMessage();
LOG.error(msg, e);
throw new RestException(msg, e);
}
}
private void setAccessToken(HttpRequest httpRequest) {
httpRequest.setHeader("Authorization", "Bearer " + accessToken);
}
private RestException createRestException(HttpResponse response) {
StatusLine statusLine = response.getStatusLine();
// try parsing response according to format
try {
if ("json".equals(format)) {
List<RestError> restErrors = objectMapper.readValue(response.getEntity().getContent(), new TypeReference<List<RestError>>(){});
return new RestException(restErrors, statusLine.getStatusCode());
} else {
RestErrors errors = new RestErrors();
xStream.fromXML(response.getEntity().getContent(), errors);
return new RestException(errors.getErrors(), statusLine.getStatusCode());
}
} catch (IOException e) {
// log and ignore
String msg = "Unexpected Error parsing " + format + " error response: " + e.getMessage();
LOG.warn(msg, e);
} catch (RuntimeException e) {
// log and ignore
String msg = "Unexpected Error parsing " + format + " error response: " + e.getMessage();
LOG.warn(msg, e);
} finally {
EntityUtils.consumeQuietly(response.getEntity());
}
// just report HTTP status info
return new RestException(statusLine.getReasonPhrase(), statusLine.getStatusCode());
}
@Override
public InputStream getVersions() throws RestException {
HttpGet get = new HttpGet(servicesDataUrl());
// does not require authorization token
return doHttpRequest(get);
}
@Override
public void setVersion(String version) {
this.version = version;
}
@Override
public InputStream getResources() throws RestException {
HttpGet get = new HttpGet(versionUrl());
// requires authorization token
setAccessToken(get);
return doHttpRequest(get);
}
@Override
public InputStream getGlobalObjects() throws RestException {
HttpGet get = new HttpGet(sobjectsUrl(""));
// requires authorization token
setAccessToken(get);
return doHttpRequest(get);
}
@Override
public InputStream getSObjectBasicInfo(String sObjectName) throws RestException {
HttpGet get = new HttpGet(sobjectsUrl(sObjectName + "/"));
// requires authorization token
setAccessToken(get);
return doHttpRequest(get);
}
@Override
public InputStream getSObjectDescription(String sObjectName) throws RestException {
HttpGet get = new HttpGet(sobjectsUrl(sObjectName + "/describe/"));
// requires authorization token
setAccessToken(get);
return doHttpRequest(get);
}
@Override
public InputStream getSObjectById(String sObjectName, String id, String[] fields) throws RestException {
// parse fields if set
String params = "";
if (fields != null && fields.length > 0) {
StringBuilder fieldsValue = new StringBuilder("?fields=");
for (int i = 0; i < fields.length; i++) {
fieldsValue.append(fields[i]);
if (i < (fields.length - 1)) {
fieldsValue.append(',');
}
}
params = fieldsValue.toString();
}
HttpGet get = new HttpGet(sobjectsUrl(sObjectName + "/" + id + params));
// requires authorization token
setAccessToken(get);
return doHttpRequest(get);
}
@Override
public InputStream createSObject(String sObjectName, InputStream sObject) throws RestException {
// post the sObject
final HttpPost post = new HttpPost(sobjectsUrl(sObjectName));
// authorization
setAccessToken(post);
// input stream as entity content
post.setEntity(new InputStreamEntity(sObject, -1,
"json".equals(format) ? APPLICATION_JSON_UTF8 : APPLICATION_XML_UTF8));
return doHttpRequest(post);
}
@Override
public void updateSObjectById(String sObjectName, String id, InputStream sObject) throws RestException {
final HttpPatch patch = new HttpPatch(sobjectsUrl(sObjectName + "/" + id));
// requires authorization token
setAccessToken(patch);
// input stream as entity content
patch.setEntity(new InputStreamEntity(sObject, -1,
"json".equals(format) ? APPLICATION_JSON_UTF8 : APPLICATION_XML_UTF8));
doHttpRequest(patch);
}
@Override
public void deleteSObjectById(String sObjectName, String id) throws RestException {
final HttpDelete delete = new HttpDelete(sobjectsUrl(sObjectName + "/" + id));
// requires authorization token
setAccessToken(delete);
doHttpRequest(delete);
}
@Override
public InputStream getSObjectByExternalId(String sObjectName, String fieldName, String fieldValue) throws RestException {
final HttpGet get = new HttpGet(sobjectsExternalIdUrl(sObjectName, fieldName, fieldValue));
// requires authorization token
setAccessToken(get);
return doHttpRequest(get);
}
@Override
public InputStream createOrUpdateSObjectByExternalId(String sObjectName, String fieldName, String fieldValue, InputStream sObject) throws RestException {
final HttpPatch patch = new HttpPatch(sobjectsExternalIdUrl(sObjectName, fieldName, fieldValue));
// requires authorization token
setAccessToken(patch);
// input stream as entity content
patch.setEntity(new InputStreamEntity(sObject, -1,
"json".equals(format) ? ContentType.APPLICATION_JSON : ContentType.APPLICATION_XML));
return doHttpRequest(patch);
}
@Override
public void deleteSObjectByExternalId(String sObjectName, String fieldName, String fieldValue) throws RestException {
final HttpDelete delete = new HttpDelete(sobjectsExternalIdUrl(sObjectName, fieldName, fieldValue));
// requires authorization token
setAccessToken(delete);
doHttpRequest(delete);
}
@Override
public InputStream executeQuery(String soqlQuery) throws RestException {
try {
String encodedQuery = URLEncoder.encode(soqlQuery, Consts.UTF_8.toString());
// URLEncoder likes to use '+' for spaces
encodedQuery = encodedQuery.replace("+", "%20");
final HttpGet get = new HttpGet(versionUrl() + "query/?q=" + encodedQuery);
// requires authorization token
setAccessToken(get);
return doHttpRequest(get);
} catch (UnsupportedEncodingException e) {
String msg = "Unexpected error: " + e.getMessage();
LOG.error(msg, e);
throw new RestException(msg, e);
}
}
@Override
public InputStream getQueryRecords(String nextRecordsUrl) throws RestException {
final HttpGet get = new HttpGet(instanceUrl + nextRecordsUrl);
// requires authorization token
setAccessToken(get);
return doHttpRequest(get);
}
@Override
public InputStream executeSearch(String soslQuery) throws RestException {
try {
String encodedQuery = URLEncoder.encode(soslQuery, Consts.UTF_8.toString());
// URLEncoder likes to use '+' for spaces
encodedQuery = encodedQuery.replace("+", "%20");
final HttpGet get = new HttpGet(versionUrl() + "search/?q=" + encodedQuery);
// requires authorization token
setAccessToken(get);
return doHttpRequest(get);
} catch (UnsupportedEncodingException e) {
String msg = "Unexpected error: " + e.getMessage();
LOG.error(msg, e);
throw new RestException(msg, e);
}
}
private String servicesDataUrl() {
return instanceUrl + SERVICES_DATA;
}
private String versionUrl() throws RestException {
if (version == null) {
throw new RestException("NULL API version", new NullPointerException("version"));
}
return servicesDataUrl() + "v" + version + "/";
}
private String sobjectsUrl(String sObjectName) throws RestException {
if (sObjectName == null) {
throw new RestException("Null SObject name", new NullPointerException("sObjectName"));
}
return versionUrl() + "sobjects/" + sObjectName;
}
private String sobjectsExternalIdUrl(String sObjectName, String fieldName, String fieldValue) throws RestException {
if (fieldName == null || fieldValue == null) {
throw new RestException("External field name and value cannot be NULL",
new NullPointerException("fieldName,fieldValue"));
}
try {
String encodedValue = URLEncoder.encode(fieldValue, Consts.UTF_8.toString());
// URLEncoder likes to use '+' for spaces
encodedValue = encodedValue.replace("+", "%20");
return sobjectsUrl(sObjectName + "/" + fieldName + "/" + encodedValue);
} catch (UnsupportedEncodingException e) {
String msg = "Unexpected error: " + e.getMessage();
LOG.error(msg, e);
throw new RestException(msg, e);
}
}
}
| true | true | private InputStream doHttpRequest(HttpUriRequest request) throws RestException {
HttpResponse httpResponse = null;
try {
// set standard headers for all requests
final String contentType = ("json".equals(format) ? APPLICATION_JSON_UTF8 : APPLICATION_XML_UTF8).toString();
request.setHeader("Accept", contentType);
request.setHeader("Accept-Charset", Consts.UTF_8.toString());
// request content type and charset is set by the request entity
// execute the request
httpResponse = httpClient.execute(request);
// check response for session timeout
final StatusLine statusLine = httpResponse.getStatusLine();
if (statusLine.getStatusCode() == SESSION_EXPIRED) {
// use the session to get a new accessToken and try the request again
LOG.warn("Retrying {} on session expiry: {}", request.getMethod(), statusLine.getReasonPhrase());
accessToken = session.login(accessToken);
instanceUrl = session.getInstanceUrl();
setAccessToken(request);
httpResponse = httpClient.execute(request);
}
final int statusCode = httpResponse.getStatusLine().getStatusCode();
if (statusCode < 200 || statusCode >= 300) {
throw createRestException(httpResponse);
} else {
return (httpResponse.getEntity() == null) ?
null : httpResponse.getEntity().getContent();
}
} catch (IOException e) {
request.abort();
if (httpResponse != null) {
EntityUtils.consumeQuietly(httpResponse.getEntity());
}
String msg = "Unexpected Error: " + e.getMessage();
LOG.error(msg, e);
throw new RestException(msg, e);
} catch (RuntimeException e) {
request.abort();
if (httpResponse != null) {
EntityUtils.consumeQuietly(httpResponse.getEntity());
}
String msg = "Unexpected Error: " + e.getMessage();
LOG.error(msg, e);
throw new RestException(msg, e);
}
}
| private InputStream doHttpRequest(HttpUriRequest request) throws RestException {
HttpResponse httpResponse = null;
try {
// set standard headers for all requests
final String contentType = ("json".equals(format) ? APPLICATION_JSON_UTF8 : APPLICATION_XML_UTF8).toString();
request.setHeader("Accept", contentType);
request.setHeader("Accept-Charset", Consts.UTF_8.toString());
// request content type and charset is set by the request entity
// execute the request
httpResponse = httpClient.execute(request);
// check response for session timeout
final StatusLine statusLine = httpResponse.getStatusLine();
if (statusLine.getStatusCode() == SESSION_EXPIRED) {
// use the session to get a new accessToken and try the request again
LOG.warn("Retrying {} on session expiry: {}", request.getMethod(), statusLine.getReasonPhrase());
accessToken = session.login(accessToken);
instanceUrl = session.getInstanceUrl();
setAccessToken(request);
httpResponse = httpClient.execute(request);
}
final int statusCode = httpResponse.getStatusLine().getStatusCode();
if (statusCode < 200 || statusCode >= 300) {
LOG.error(String.format("Error {%s:%s} executing {%s:%s}",
statusCode, statusLine.getReasonPhrase(),
request.getMethod(),request.getURI()));
throw createRestException(httpResponse);
} else {
return (httpResponse.getEntity() == null) ?
null : httpResponse.getEntity().getContent();
}
} catch (IOException e) {
request.abort();
if (httpResponse != null) {
EntityUtils.consumeQuietly(httpResponse.getEntity());
}
String msg = "Unexpected Error: " + e.getMessage();
LOG.error(msg, e);
throw new RestException(msg, e);
} catch (RuntimeException e) {
request.abort();
if (httpResponse != null) {
EntityUtils.consumeQuietly(httpResponse.getEntity());
}
String msg = "Unexpected Error: " + e.getMessage();
LOG.error(msg, e);
throw new RestException(msg, e);
}
}
|
diff --git a/src/flow/netbeans/markdown/MarkdownViewHtmlAction.java b/src/flow/netbeans/markdown/MarkdownViewHtmlAction.java
index d06fef0..369d6a7 100644
--- a/src/flow/netbeans/markdown/MarkdownViewHtmlAction.java
+++ b/src/flow/netbeans/markdown/MarkdownViewHtmlAction.java
@@ -1,91 +1,91 @@
package flow.netbeans.markdown;
import flow.netbeans.markdown.options.MarkdownGlobalOptions;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.net.URL;
import java.nio.charset.Charset;
import javax.swing.text.BadLocationException;
import javax.swing.text.StyledDocument;
import org.netbeans.api.queries.FileEncodingQuery;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.awt.ActionReferences;
import org.openide.awt.ActionRegistration;
import org.openide.awt.HtmlBrowser.URLDisplayer;
import org.openide.cookies.EditorCookie;
import org.openide.filesystems.FileObject;
import org.openide.util.Exceptions;
import org.openide.util.NbBundle.Messages;
import org.pegdown.PegDownProcessor;
@ActionID(category = "File",
id = "flow.netbeans.markdown.MarkdownViewHtmlAction")
@ActionRegistration(displayName = "#CTL_MarkdownViewHtmlAction", iconBase = "flow/netbeans/markdown/resources/action-view.png")
@ActionReferences({
@ActionReference(path = "Editors/text/x-markdown/Toolbars/Default", position = 270100),
@ActionReference(path = "Editors/text/x-markdown/Popup", position = 0),
@ActionReference(path = "Loaders/text/x-markdown/Actions", position = 251)
})
@Messages("CTL_MarkdownViewHtmlAction=View HTML")
public final class MarkdownViewHtmlAction implements ActionListener {
private final MarkdownDataObject context;
public MarkdownViewHtmlAction(MarkdownDataObject context) throws IOException {
this.context = context;
}
@Override
public void actionPerformed(ActionEvent ev) {
try {
MarkdownGlobalOptions markdownOptions = MarkdownGlobalOptions.getInstance();
PegDownProcessor markdownProcessor = new PegDownProcessor(markdownOptions.getExtensionsValue());
// get document
EditorCookie ec = context.getLookup().lookup(EditorCookie.class);
StyledDocument document = ec.getDocument();
// get file object
FileObject f = context.getPrimaryFile();
if (f == null) {
return;
}
String markdownSource = "";
if (document != null) {
markdownSource = document.getText(0, document.getLength());
} else {
markdownSource = f.asText();
}
String html = markdownProcessor.markdownToHtml(markdownSource);
String full = markdownOptions.getHtmlTemplate()
.replace("{%CONTENT%}", html.toString())
.replace("{%TITLE%}", context.getPrimaryFile().getName());
- File temp = File.createTempFile(context.getPrimaryFile().getName(), ".html");
+ File temp = File.createTempFile("preview-" + context.getPrimaryFile().getName(), ".html");
PrintStream out;
if (document != null) {
// get file encoding
Charset encoding = FileEncodingQuery.getEncoding(f);
out = new PrintStream(new FileOutputStream(temp), false, encoding.name());
} else {
out = new PrintStream(new FileOutputStream(temp));
}
out.print(full);
out.close();
URLDisplayer.getDefault().showURL(new URL("file://" + temp.toString()));
temp.deleteOnExit();
} catch (IOException ex) {
Exceptions.printStackTrace(ex);
} catch (BadLocationException ex) {
Exceptions.printStackTrace(ex);
}
}
}
| true | true | public void actionPerformed(ActionEvent ev) {
try {
MarkdownGlobalOptions markdownOptions = MarkdownGlobalOptions.getInstance();
PegDownProcessor markdownProcessor = new PegDownProcessor(markdownOptions.getExtensionsValue());
// get document
EditorCookie ec = context.getLookup().lookup(EditorCookie.class);
StyledDocument document = ec.getDocument();
// get file object
FileObject f = context.getPrimaryFile();
if (f == null) {
return;
}
String markdownSource = "";
if (document != null) {
markdownSource = document.getText(0, document.getLength());
} else {
markdownSource = f.asText();
}
String html = markdownProcessor.markdownToHtml(markdownSource);
String full = markdownOptions.getHtmlTemplate()
.replace("{%CONTENT%}", html.toString())
.replace("{%TITLE%}", context.getPrimaryFile().getName());
File temp = File.createTempFile(context.getPrimaryFile().getName(), ".html");
PrintStream out;
if (document != null) {
// get file encoding
Charset encoding = FileEncodingQuery.getEncoding(f);
out = new PrintStream(new FileOutputStream(temp), false, encoding.name());
} else {
out = new PrintStream(new FileOutputStream(temp));
}
out.print(full);
out.close();
URLDisplayer.getDefault().showURL(new URL("file://" + temp.toString()));
temp.deleteOnExit();
} catch (IOException ex) {
Exceptions.printStackTrace(ex);
} catch (BadLocationException ex) {
Exceptions.printStackTrace(ex);
}
}
| public void actionPerformed(ActionEvent ev) {
try {
MarkdownGlobalOptions markdownOptions = MarkdownGlobalOptions.getInstance();
PegDownProcessor markdownProcessor = new PegDownProcessor(markdownOptions.getExtensionsValue());
// get document
EditorCookie ec = context.getLookup().lookup(EditorCookie.class);
StyledDocument document = ec.getDocument();
// get file object
FileObject f = context.getPrimaryFile();
if (f == null) {
return;
}
String markdownSource = "";
if (document != null) {
markdownSource = document.getText(0, document.getLength());
} else {
markdownSource = f.asText();
}
String html = markdownProcessor.markdownToHtml(markdownSource);
String full = markdownOptions.getHtmlTemplate()
.replace("{%CONTENT%}", html.toString())
.replace("{%TITLE%}", context.getPrimaryFile().getName());
File temp = File.createTempFile("preview-" + context.getPrimaryFile().getName(), ".html");
PrintStream out;
if (document != null) {
// get file encoding
Charset encoding = FileEncodingQuery.getEncoding(f);
out = new PrintStream(new FileOutputStream(temp), false, encoding.name());
} else {
out = new PrintStream(new FileOutputStream(temp));
}
out.print(full);
out.close();
URLDisplayer.getDefault().showURL(new URL("file://" + temp.toString()));
temp.deleteOnExit();
} catch (IOException ex) {
Exceptions.printStackTrace(ex);
} catch (BadLocationException ex) {
Exceptions.printStackTrace(ex);
}
}
|
diff --git a/src/com/carbonfive/db/migration/ResourceMigrationResolver.java b/src/com/carbonfive/db/migration/ResourceMigrationResolver.java
index d15de20..2fb0cd8 100644
--- a/src/com/carbonfive/db/migration/ResourceMigrationResolver.java
+++ b/src/com/carbonfive/db/migration/ResourceMigrationResolver.java
@@ -1,119 +1,119 @@
package com.carbonfive.db.migration;
import com.carbonfive.jdbc.DatabaseType;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.util.*;
import static org.apache.commons.collections.CollectionUtils.find;
import static org.apache.commons.lang.StringUtils.isBlank;
/**
* A MigrationResolver which leverages Spring's robust Resource loading mechanism, supporting 'file:', 'classpath:', and standard url format resources.
* <p/>
* Migration Location Examples: <ul> <li>classpath:/db/migrations/</li> <li>file:src/main/db/migrations/</li> <li>file:src/main/resources/db/migrations/</li>
* </ul> All of the resources found in the migrations location which do not start with a '.' will be considered migrations.
* <p/>
* Configured out of the box with a SimpleVersionExtractor and the default resource pattern CLASSPATH_MIGRATIONS_SQL.
*
* @see Resource
* @see VersionExtractor
* @see MigrationFactory
*/
public class ResourceMigrationResolver implements MigrationResolver {
private static final String PATH_MIGRATIONS_SQL = "conf/migrations";
protected final Logger logger = LoggerFactory.getLogger(getClass());
private String migrationsLocation;
private VersionExtractor versionExtractor;
private MigrationFactory migrationFactory = new MigrationFactory();
public ResourceMigrationResolver() {
this(PATH_MIGRATIONS_SQL);
}
public ResourceMigrationResolver(String migrationsLocation) {
this(migrationsLocation, new SimpleVersionExtractor());
}
public ResourceMigrationResolver(String migrationsLocation, VersionExtractor versionExtractor) {
setMigrationsLocation(migrationsLocation);
setVersionExtractor(versionExtractor);
}
public Set<Migration> resolve(DatabaseType dbType) {
Set<Migration> migrations = new HashSet<Migration>();
// Find all resources in the migrations location.
File path = new File(migrationsLocation);
List<Resource> resources = new ArrayList<Resource>();
- Collection<File> files = FileUtils.listFiles(path, new String[]{"*.sql"}, true);
+ Collection<File> files = FileUtils.listFiles(path, new String[]{"sql"}, true);
for (File file : files) {
resources.add(new Resource(file));
}
if (resources.isEmpty()) {
String message = "No migrations were found from path '" + path.getAbsolutePath() + "'.";
logger.error(message);
throw new MigrationException(message);
}
if (logger.isDebugEnabled()) {
logger.debug("Found " + resources.size() + " resources: " + resources);
}
// Extract versions and create executable migrations for each resource.
for (Resource resource : resources) {
String version = versionExtractor.extractVersion(resource.getFilename());
if (find(migrations, new Migration.MigrationVersionPredicate(version)) != null) {
String message = "Non-unique migration version.";
logger.error(message);
throw new MigrationException(message);
}
migrations.add(migrationFactory.create(version, resource));
}
return migrations;
}
public Set<Migration> resolve() {
return resolve(DatabaseType.UNKNOWN);
}
protected String convertMigrationsLocation(String migrationsLocation, DatabaseType dbType) {
String converted = migrationsLocation;
if (!(isBlank(FilenameUtils.getName(converted)) || FilenameUtils.getName(converted).contains("*"))) {
converted += "/";
}
if (!FilenameUtils.getName(converted).contains("*")) {
converted += "*";
}
if (!(converted.startsWith("file:") || converted.startsWith("classpath:"))) {
converted = "file:" + converted;
}
return converted;
}
public void setMigrationsLocation(String migrationsLocation) {
this.migrationsLocation = migrationsLocation;
}
public void setVersionExtractor(VersionExtractor versionExtractor) {
this.versionExtractor = versionExtractor;
}
public void setMigrationFactory(MigrationFactory migrationFactory) {
this.migrationFactory = migrationFactory;
}
}
| true | true | public Set<Migration> resolve(DatabaseType dbType) {
Set<Migration> migrations = new HashSet<Migration>();
// Find all resources in the migrations location.
File path = new File(migrationsLocation);
List<Resource> resources = new ArrayList<Resource>();
Collection<File> files = FileUtils.listFiles(path, new String[]{"*.sql"}, true);
for (File file : files) {
resources.add(new Resource(file));
}
if (resources.isEmpty()) {
String message = "No migrations were found from path '" + path.getAbsolutePath() + "'.";
logger.error(message);
throw new MigrationException(message);
}
if (logger.isDebugEnabled()) {
logger.debug("Found " + resources.size() + " resources: " + resources);
}
// Extract versions and create executable migrations for each resource.
for (Resource resource : resources) {
String version = versionExtractor.extractVersion(resource.getFilename());
if (find(migrations, new Migration.MigrationVersionPredicate(version)) != null) {
String message = "Non-unique migration version.";
logger.error(message);
throw new MigrationException(message);
}
migrations.add(migrationFactory.create(version, resource));
}
return migrations;
}
| public Set<Migration> resolve(DatabaseType dbType) {
Set<Migration> migrations = new HashSet<Migration>();
// Find all resources in the migrations location.
File path = new File(migrationsLocation);
List<Resource> resources = new ArrayList<Resource>();
Collection<File> files = FileUtils.listFiles(path, new String[]{"sql"}, true);
for (File file : files) {
resources.add(new Resource(file));
}
if (resources.isEmpty()) {
String message = "No migrations were found from path '" + path.getAbsolutePath() + "'.";
logger.error(message);
throw new MigrationException(message);
}
if (logger.isDebugEnabled()) {
logger.debug("Found " + resources.size() + " resources: " + resources);
}
// Extract versions and create executable migrations for each resource.
for (Resource resource : resources) {
String version = versionExtractor.extractVersion(resource.getFilename());
if (find(migrations, new Migration.MigrationVersionPredicate(version)) != null) {
String message = "Non-unique migration version.";
logger.error(message);
throw new MigrationException(message);
}
migrations.add(migrationFactory.create(version, resource));
}
return migrations;
}
|
diff --git a/src/com/sargant/bukkit/powerarmour/PowerArmourEntityListener.java b/src/com/sargant/bukkit/powerarmour/PowerArmourEntityListener.java
index 20eead1..08cb767 100644
--- a/src/com/sargant/bukkit/powerarmour/PowerArmourEntityListener.java
+++ b/src/com/sargant/bukkit/powerarmour/PowerArmourEntityListener.java
@@ -1,64 +1,64 @@
package com.sargant.bukkit.powerarmour;
import org.bukkit.Material;
import org.bukkit.entity.HumanEntity;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.EntityListener;
import com.sargant.bukkit.powerarmour.PowerArmour;
public class PowerArmourEntityListener extends EntityListener
{
private PowerArmour parent;
public PowerArmourEntityListener(PowerArmour instance) {
parent = instance;
}
@Override
public void onEntityDamage(EntityDamageEvent event) {
if(event.isCancelled()) {
return;
}
if(!(event.getEntity() instanceof HumanEntity)) {
return;
}
HumanEntity human = (HumanEntity) event.getEntity();
PowerArmourComponents loadout = new PowerArmourComponents();
loadout.head = human.getInventory().getHelmet().getType();
loadout.body = human.getInventory().getChestplate().getType();
loadout.legs = human.getInventory().getLeggings().getType();
loadout.feet = human.getInventory().getBoots().getType();
loadout.hand = human.getItemInHand().getType();
parent.log.info(parent.armourList.keySet().toString());
for(PowerArmourAbilities a : parent.armourList.keySet()) {
PowerArmourComponents c = parent.armourList.get(a);
if(c.head != Material.AIR && loadout.head != c.head) { continue; }
if(c.body != Material.AIR && loadout.body != c.body) { continue; }
if(c.legs != Material.AIR && loadout.legs != c.legs) { continue; }
if(c.feet != Material.AIR && loadout.feet != c.feet) { continue; }
- if(c.hand != Material.AIR && loadout.hand != c.hand) { parent.log.info("failed on hand check - wanted " + c.hand + ", got" + loadout.hand); continue; }
+ if(c.hand != Material.AIR && loadout.hand != c.hand) { continue; }
// The loadout is correct for the current power ability
// Does the current damage type match a corresponding proof-ness?
if(a.getAbilities().contains(event.getCause())) {
event.setCancelled(true);
if(event.getCause().toString().toUpperCase().contains("FIRE"))
{
human.setFireTicks(0);
}
return;
}
}
}
}
| true | true | public void onEntityDamage(EntityDamageEvent event) {
if(event.isCancelled()) {
return;
}
if(!(event.getEntity() instanceof HumanEntity)) {
return;
}
HumanEntity human = (HumanEntity) event.getEntity();
PowerArmourComponents loadout = new PowerArmourComponents();
loadout.head = human.getInventory().getHelmet().getType();
loadout.body = human.getInventory().getChestplate().getType();
loadout.legs = human.getInventory().getLeggings().getType();
loadout.feet = human.getInventory().getBoots().getType();
loadout.hand = human.getItemInHand().getType();
parent.log.info(parent.armourList.keySet().toString());
for(PowerArmourAbilities a : parent.armourList.keySet()) {
PowerArmourComponents c = parent.armourList.get(a);
if(c.head != Material.AIR && loadout.head != c.head) { continue; }
if(c.body != Material.AIR && loadout.body != c.body) { continue; }
if(c.legs != Material.AIR && loadout.legs != c.legs) { continue; }
if(c.feet != Material.AIR && loadout.feet != c.feet) { continue; }
if(c.hand != Material.AIR && loadout.hand != c.hand) { parent.log.info("failed on hand check - wanted " + c.hand + ", got" + loadout.hand); continue; }
// The loadout is correct for the current power ability
// Does the current damage type match a corresponding proof-ness?
if(a.getAbilities().contains(event.getCause())) {
event.setCancelled(true);
if(event.getCause().toString().toUpperCase().contains("FIRE"))
{
human.setFireTicks(0);
}
return;
}
}
}
| public void onEntityDamage(EntityDamageEvent event) {
if(event.isCancelled()) {
return;
}
if(!(event.getEntity() instanceof HumanEntity)) {
return;
}
HumanEntity human = (HumanEntity) event.getEntity();
PowerArmourComponents loadout = new PowerArmourComponents();
loadout.head = human.getInventory().getHelmet().getType();
loadout.body = human.getInventory().getChestplate().getType();
loadout.legs = human.getInventory().getLeggings().getType();
loadout.feet = human.getInventory().getBoots().getType();
loadout.hand = human.getItemInHand().getType();
parent.log.info(parent.armourList.keySet().toString());
for(PowerArmourAbilities a : parent.armourList.keySet()) {
PowerArmourComponents c = parent.armourList.get(a);
if(c.head != Material.AIR && loadout.head != c.head) { continue; }
if(c.body != Material.AIR && loadout.body != c.body) { continue; }
if(c.legs != Material.AIR && loadout.legs != c.legs) { continue; }
if(c.feet != Material.AIR && loadout.feet != c.feet) { continue; }
if(c.hand != Material.AIR && loadout.hand != c.hand) { continue; }
// The loadout is correct for the current power ability
// Does the current damage type match a corresponding proof-ness?
if(a.getAbilities().contains(event.getCause())) {
event.setCancelled(true);
if(event.getCause().toString().toUpperCase().contains("FIRE"))
{
human.setFireTicks(0);
}
return;
}
}
}
|
diff --git a/app/src/processing/app/tools/AutoFormat.java b/app/src/processing/app/tools/AutoFormat.java
index b6b23bc7..8cad9138 100644
--- a/app/src/processing/app/tools/AutoFormat.java
+++ b/app/src/processing/app/tools/AutoFormat.java
@@ -1,954 +1,951 @@
/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */
/*
Part of the Processing project - http://processing.org
Original Copyright (c) 1997, 1998 Van Di-Han HO. All Rights Reserved.
Updates Copyright (c) 2001 Jason Pell.
Further updates Copyright (c) 2003 Martin Gomez, Ateneo de Manila University
Bug fixes Copyright (c) 2005-09 Ben Fry and Casey Reas
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, version 2.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software Foundation,
Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package processing.app.tools;
import processing.app.*;
import processing.core.PApplet;
import static processing.app.I18n._;
import java.io.*;
/**
* Handler for dealing with auto format.
* Contributed by Martin Gomez, additional bug fixes by Ben Fry.
*
* After some further digging, this code in fact appears to be a modified
* version of Jason Pell's GPLed "Java Beautifier" class found here:
* http://www.geocities.com/jasonpell/programs.html
* Which is itself based on code from Van Di-Han Ho:
* http://www.geocities.com/~starkville/vancbj_idx.html
* [Ben Fry, August 2009]
*/
public class AutoFormat implements Tool {
Editor editor;
static final int BLOCK_MAXLEN = 1024;
StringBuffer strOut;
int indentValue;
String indentChar;
int EOF;
CharArrayReader reader;
int readCount, indexBlock, lineLength, lineNumber;
char chars[];
String strBlock;
int s_level[];
int c_level;
int sp_flg[][];
int s_ind[][];
int s_if_lev[];
int s_if_flg[];
int if_lev, if_flg, level;
int ind[];
int e_flg, paren;
static int p_flg[];
char l_char, p_char;
int a_flg, q_flg, ct;
int s_tabs[][];
String w_if_, w_else, w_for, w_ds, w_case, w_cpp_comment, w_jdoc;
int jdoc, j;
char string[];
char cc;
int s_flg;
int peek;
char peekc;
int tabs;
char last_char;
char c;
String line_feed;
public void init(Editor editor) {
this.editor = editor;
}
public String getMenuTitle() {
return _("Auto Format");
}
public void comment() throws IOException {
int save_s_flg;
save_s_flg = s_flg;
int done = 0;
c = string[j++] = getchr(); // extra char
while (done == 0) {
c = string[j++] = getchr();
while ((c != '/') && (j < string.length) && EOF == 0) {
if(c == '\n' || c == '\r') {
lineNumber++;
putcoms();
s_flg = 1;
}
c = string[j++] = getchr();
}
//String tmpstr = new String(string);
if (j>1 && string[j-2] == '*') {
done = 1;
jdoc = 0;
} else if (EOF != 0) {
done = 1;
}
}
putcoms();
s_flg = save_s_flg;
jdoc = 0;
return;
}
public char get_string() throws IOException {
char ch;
ch = '*';
while (true) {
switch (ch) {
default:
ch = string[j++] = getchr();
if (ch == '\\') {
string[j++] = getchr();
break;
}
if (ch == '\'' || ch == '"') {
cc = string[j++] = getchr();
while (cc != ch && EOF == 0) {
if (cc == '\\') string[j++] = getchr();
cc = string[j++] = getchr();
}
break;
}
if (ch == '\n' || ch == '\r') {
indent_puts();
a_flg = 1;
break;
} else {
return(ch);
}
}
}
}
public void indent_puts() {
string[j] = '\0';
if (j > 0) {
if (s_flg != 0) {
if((tabs > 0) && (string[0] != '{') && (a_flg == 1)) {
tabs++;
}
p_tabs();
s_flg = 0;
if ((tabs > 0) && (string[0] != '{') && (a_flg == 1)) {
tabs--;
}
a_flg = 0;
}
String j_string = new String(string);
strOut.append(j_string.substring(0,j));
for (int i=0; i<j; i++) string[i] = '\0';
j = 0;
} else {
if (s_flg != 0) {
s_flg = 0;
a_flg = 0;
}
}
}
//public void fprintf(int outfil, String out_string) {
public void fprintf(String out_string) {
//int out_len = out_string.length();
//String j_string = new String(string);
strOut.append(out_string);
}
public int grabLines() {
return lineNumber;
}
/* special edition of put string for comment processing */
public void putcoms()
{
int i = 0;
int sav_s_flg = s_flg;
if(j > 0)
{
if(s_flg != 0)
{
p_tabs();
s_flg = 0;
}
string[j] = '\0';
i = 0;
while (string[i] == ' ' && EOF == 0) i++;
if (lookup_com(w_jdoc) == 1) jdoc = 1;
String strBuffer = new String(string,0,j);
if (string[i] == '/' && string[i+1]=='*')
{
if ((last_char != ';') && (sav_s_flg==1) )
{
//fprintf(outfil, strBuffer.substring(i,j));
fprintf(strBuffer.substring(i,j));
}
else
{
//fprintf(outfil, strBuffer);
fprintf(strBuffer);
}
}
else
{
if (string[i]=='*' || jdoc == 0)
//fprintf (outfil, " "+strBuffer.substring(i,j));
fprintf (" "+strBuffer.substring(i,j));
else
//fprintf (outfil, " * "+strBuffer.substring(i,j));
fprintf (" * "+strBuffer.substring(i,j));
}
j = 0;
string[0] = '\0';
}
}
public void cpp_comment() throws IOException
{
c = getchr();
while(c != '\n' && c != '\r' && EOF == 0)
{
string[j++] = c;
c = getchr();
}
lineNumber++;
indent_puts();
s_flg = 1;
}
/* expand indentValue into tabs and spaces */
public void p_tabs()
{
int i,k;
if (tabs<0) tabs = 0;
if (tabs==0) return;
i = tabs * indentValue; // calc number of spaces
//j = i/8; /* calc number of tab chars */
for (k=0; k < i; k++) {
strOut.append(indentChar);
}
}
public char getchr() throws IOException
{
if((peek < 0) && (last_char != ' ') && (last_char != '\t'))
{
if((last_char != '\n') && (last_char != '\r'))
p_char = last_char;
}
if(peek > 0) /* char was read previously */
{
last_char = peekc;
peek = -1;
}
else /* read next char in string */
{
indexBlock++;
if (indexBlock >= lineLength)
{
for (int ib=0; ib<readCount; ib++) chars[ib] = '\0';
lineLength = readCount = 0;
reader.mark(1);
if (reader.read() != -1)
{
reader.reset(); // back to the mark
readCount = reader.read(chars);
lineLength = readCount;
strBlock = new String(chars);
indexBlock = 0;
last_char = strBlock.charAt(indexBlock);
peek = -1;
peekc = '`';
}
else
{
EOF = 1;
peekc = '\0';
}
}
else
{
last_char = strBlock.charAt(indexBlock);
}
}
peek = -1;
if (last_char == '\r')
{
last_char = getchr();
}
return last_char;
}
/* else processing */
public void gotelse()
{
tabs = s_tabs[c_level][if_lev];
p_flg[level] = sp_flg[c_level][if_lev];
ind[level] = s_ind[c_level][if_lev];
if_flg = 1;
}
/* read to new_line */
public int getnl() throws IOException
{
int save_s_flg;
save_s_flg = tabs;
peekc = getchr();
//while ((peekc == '\t' || peekc == ' ') &&
// (j < string.length)) {
while ((peekc == '\t' || peekc == ' ') && EOF == 0) {
string[j++] = peekc;
peek = -1;
peekc = '`';
peekc = getchr();
peek = 1;
}
peek = 1;
if (peekc == '/')
{
peek = -1;
peekc = '`';
peekc = getchr();
if (peekc == '*')
{
string[j++] = '/';
string[j++] = '*';
peek = -1;
peekc = '`';
comment();
}
else if (peekc == '/')
{
string[j++] = '/';
string[j++] = '/';
peek = -1;
peekc = '`';
cpp_comment();
return (1);
}
else
{
string[j++] = '/';
peek = 1;
}
}
peekc = getchr();
if(peekc == '\n')
{
lineNumber++;
peek = -1;
peekc = '`';
tabs = save_s_flg;
return(1);
}
else
{
peek = 1;
}
return 0;
}
public int lookup (String keyword)
{
char r;
int l,kk; //,k,i;
String j_string = new String(string);
if (j<1) return (0);
kk=0;
while(string[kk] == ' ' && EOF == 0)kk++;
l=0;
l = j_string.indexOf(keyword);
if (l<0 || l!=kk)
{
return 0;
}
r = string[kk+keyword.length()];
if(r >= 'a' && r <= 'z') return(0);
if(r >= 'A' && r <= 'Z') return(0);
if(r >= '0' && r <= '9') return(0);
if(r == '_' || r == '&') return(0);
return (1);
}
public int lookup_com (String keyword)
{
//char r;
int l,kk; //,k,i;
String j_string = new String(string);
if (j<1) return (0);
kk=0;
while(string[kk] == ' ' && EOF == 0) kk++;
l=0;
l = j_string.indexOf(keyword);
if (l<0 || l!=kk)
{
return 0;
}
return (1);
}
public void run() {
StringBuffer onechar;
// Adding an additional newline as a hack around other errors
String originalText = editor.getText() + "\n";
strOut = new StringBuffer();
indentValue = Preferences.getInteger("editor.tabs.size");
indentChar = new String(" ");
lineNumber = 0;
c_level = if_lev = level = e_flg = paren = 0;
a_flg = q_flg = j = tabs = 0;
if_flg = peek = -1;
peekc = '`';
s_flg = 1;
jdoc = 0;
s_level = new int[10];
sp_flg = new int[20][10];
s_ind = new int[20][10];
s_if_lev = new int[10];
s_if_flg = new int[10];
ind = new int[10];
p_flg = new int[10];
s_tabs = new int[20][10];
w_else = new String ("else");
w_if_ = new String ("if");
w_for = new String ("for");
w_ds = new String ("default");
w_case = new String ("case");
w_cpp_comment = new String ("//");
w_jdoc = new String ("/**");
line_feed = new String ("\n");
// read as long as there is something to read
EOF = 0; // = 1 set in getchr when EOF
chars = new char[BLOCK_MAXLEN];
string = new char[BLOCK_MAXLEN];
try { // the whole process
// open for input
reader = new CharArrayReader(originalText.toCharArray());
// add buffering to that InputStream
// bin = new BufferedInputStream(in);
for (int ib = 0; ib < BLOCK_MAXLEN; ib++) chars[ib] = '\0';
lineLength = readCount = 0;
// read up a block - remember how many bytes read
readCount = reader.read(chars);
strBlock = new String(chars);
lineLength = readCount;
lineNumber = 1;
indexBlock = -1;
j = 0;
while (EOF == 0)
{
c = getchr();
switch(c)
{
default:
string[j++] = c;
if(c != ',')
{
l_char = c;
}
break;
case ' ':
case '\t':
if(lookup(w_else) == 1)
{
gotelse();
if(s_flg == 0 || j > 0)string[j++] = c;
indent_puts();
s_flg = 0;
break;
}
if(s_flg == 0 || j > 0)string[j++] = c;
break;
case '\r': // <CR> for MS Windows 95
case '\n':
lineNumber++;
if (EOF==1)
{
break;
}
//String j_string = new String(string);
e_flg = lookup(w_else);
if(e_flg == 1) gotelse();
if (lookup_com(w_cpp_comment) == 1)
{
if (string[j] == '\n')
{
string[j] = '\0';
j--;
}
}
indent_puts();
//fprintf(outfil, line_feed);
fprintf(line_feed);
s_flg = 1;
if(e_flg == 1)
{
p_flg[level]++;
tabs++;
}
else
if(p_char == l_char)
{
a_flg = 1;
}
break;
case '{':
if(lookup(w_else) == 1)gotelse();
if (s_if_lev.length == c_level) {
s_if_lev = PApplet.expand(s_if_lev);
s_if_flg = PApplet.expand(s_if_flg);
}
s_if_lev[c_level] = if_lev;
s_if_flg[c_level] = if_flg;
if_lev = if_flg = 0;
c_level++;
if(s_flg == 1 && p_flg[level] != 0)
{
p_flg[level]--;
tabs--;
}
string[j++] = c;
indent_puts();
getnl() ;
indent_puts();
//fprintf(outfil,"\n");
fprintf("\n");
tabs++;
s_flg = 1;
if(p_flg[level] > 0)
{
ind[level] = 1;
level++;
s_level[level] = c_level;
}
break;
case '}':
c_level--;
if (c_level < 0)
{
EOF = 1;
//System.out.println("eof b");
string[j++] = c;
indent_puts();
break;
}
if ((if_lev = s_if_lev[c_level]-1) < 0)
if_lev = 0;
if_flg = s_if_flg[c_level];
indent_puts();
tabs--;
p_tabs();
peekc = getchr();
if( peekc == ';')
{
onechar = new StringBuffer();
onechar.append(c); // the }
onechar.append(';');
//fprintf(outfil, onechar.toString());
fprintf(onechar.toString());
peek = -1;
peekc = '`';
}
else
{
onechar = new StringBuffer();
onechar.append(c);
//fprintf(outfil, onechar.toString());
fprintf(onechar.toString());
peek = 1;
}
getnl();
indent_puts();
//fprintf(outfil,"\n");
fprintf("\n");
s_flg = 1;
if(c_level < s_level[level])
if(level > 0) level--;
if(ind[level] != 0)
{
tabs -= p_flg[level];
p_flg[level] = 0;
ind[level] = 0;
}
break;
case '"':
case '\'':
string[j++] = c;
cc = getchr();
int count = 0;
while(cc != c && EOF == 0)
{
- if (++count % 100000 == 0) {
- System.err.println("Stuck: " + count);
- }
// max. length of line should be 256
string[j++] = cc;
if(cc == '\\')
{
cc = string[j++] = getchr();
}
if(cc == '\n')
{
lineNumber++;
indent_puts();
s_flg = 1;
}
cc = getchr();
}
string[j++] = cc;
if(getnl() == 1)
{
l_char = cc;
peek = 1;
peekc = '\n';
}
break;
case ';':
string[j++] = c;
indent_puts();
if(p_flg[level] > 0 && ind[level] == 0)
{
tabs -= p_flg[level];
p_flg[level] = 0;
}
getnl();
indent_puts();
//fprintf(outfil,"\n");
fprintf("\n");
s_flg = 1;
if(if_lev > 0)
if(if_flg == 1)
{
if_lev--;
if_flg = 0;
}
else if_lev = 0;
break;
case '\\':
string[j++] = c;
string[j++] = getchr();
break;
case '?':
q_flg = 1;
string[j++] = c;
break;
case ':':
string[j++] = c;
peekc = getchr();
if(peekc == ':')
{
indent_puts();
//fprintf (outfil,":");
fprintf(":");
peek = -1;
peekc = '`';
break;
}
else
{
//int double_colon = 0;
peek = 1;
}
if(q_flg == 1)
{
q_flg = 0;
break;
}
if(lookup(w_ds) == 0 && lookup(w_case) == 0)
{
s_flg = 0;
indent_puts();
}
else
{
tabs--;
indent_puts();
tabs++;
}
peekc = getchr();
if(peekc == ';')
{
fprintf(";");
peek = -1;
peekc = '`';
}
else
{
peek = 1;
}
getnl();
indent_puts();
fprintf("\n");
s_flg = 1;
break;
case '/':
string[j++] = c;
peekc = getchr();
if(peekc == '/')
{
string[j++] = peekc;
peekc = '`';
peek = -1;
cpp_comment();
//fprintf(outfil,"\n");
fprintf("\n");
break;
}
else
{
peek = 1;
}
if(peekc != '*') {
break;
}
else
{
if (j > 0) string[j--] = '\0';
if (j > 0) indent_puts();
string[j++] = '/';
string[j++] = '*';
peek = -1;
peekc = '`';
comment();
break;
}
case '#':
string[j++] = c;
cc = getchr();
while(cc != '\n' && EOF == 0)
{
string[j++] = cc;
cc = getchr();
}
string[j++] = cc;
s_flg = 0;
indent_puts();
s_flg = 1;
break;
case ')':
paren--;
if (paren < 0)
{
EOF = 1;
//System.out.println("eof c");
}
string[j++] = c;
indent_puts();
if(getnl() == 1)
{
peekc = '\n';
peek = 1;
if(paren != 0)
{
a_flg = 1;
}
else if(tabs > 0)
{
p_flg[level]++;
tabs++;
ind[level] = 0;
}
}
break;
case '(':
string[j++] = c;
paren++;
if ((lookup(w_for) == 1))
{
c = get_string();
while(c != ';' && EOF == 0) c = get_string();
ct=0;
int for_done = 0;
while (for_done == 0 && EOF == 0)
{
c = get_string();
while(c != ')' && EOF == 0)
{
if(c == '(') ct++;
c = get_string();
}
if(ct != 0)
{
ct--;
}
else for_done = 1;
} // endwhile for_done
paren--;
if (paren < 0)
{
EOF = 1;
//System.out.println("eof d");
}
indent_puts();
if(getnl() == 1)
{
peekc = '\n';
peek = 1;
p_flg[level]++;
tabs++;
ind[level] = 0;
}
break;
}
if(lookup(w_if_) == 1)
{
indent_puts();
s_tabs[c_level][if_lev] = tabs;
sp_flg[c_level][if_lev] = p_flg[level];
s_ind[c_level][if_lev] = ind[level];
if_lev++;
if_flg = 1;
}
} // end switch
//System.out.println("string len is " + string.length);
//if (EOF == 1) System.out.println(string);
//String j_string = new String(string);
} // end while not EOF
/*
int bad;
while ((bad = bin.read()) != -1) {
System.out.print((char) bad);
}
*/
/*
char bad;
//while ((bad = getchr()) != 0) {
while (true) {
getchr();
if (peek != -1) {
System.out.print(last_char);
} else {
break;
}
}
*/
// save current (rough) selection point
int selectionEnd = editor.getSelectionStop();
// make sure the caret would be past the end of the text
if (strOut.length() < selectionEnd - 1) {
selectionEnd = strOut.length() - 1;
}
reader.close(); // close buff
String formattedText = strOut.toString();
if (formattedText.equals(originalText)) {
editor.statusNotice(_("No changes necessary for Auto Format."));
} else if (paren != 0) {
// warn user if there are too many parens in either direction
if (paren < 0) {
editor.statusError(
_("Auto Format Canceled: Too many right parentheses."));
} else {
editor.statusError(
_("Auto Format Canceled: Too many left parentheses."));
}
} else if (c_level != 0) { // check braces only if parens are ok
if (c_level < 0) {
editor.statusError(
_("Auto Format Canceled: Too many right curly braces."));
} else {
editor.statusError(
_("Auto Format Canceled: Too many left curly braces."));
}
} else {
// replace with new bootiful text
// selectionEnd hopefully at least in the neighborhood
editor.setText(formattedText);
editor.setSelection(selectionEnd, selectionEnd);
editor.getSketch().setModified(true);
// mark as finished
editor.statusNotice(_("Auto Format finished."));
}
} catch (Exception e) {
editor.statusError(e);
}
}
}
| true | true | public void run() {
StringBuffer onechar;
// Adding an additional newline as a hack around other errors
String originalText = editor.getText() + "\n";
strOut = new StringBuffer();
indentValue = Preferences.getInteger("editor.tabs.size");
indentChar = new String(" ");
lineNumber = 0;
c_level = if_lev = level = e_flg = paren = 0;
a_flg = q_flg = j = tabs = 0;
if_flg = peek = -1;
peekc = '`';
s_flg = 1;
jdoc = 0;
s_level = new int[10];
sp_flg = new int[20][10];
s_ind = new int[20][10];
s_if_lev = new int[10];
s_if_flg = new int[10];
ind = new int[10];
p_flg = new int[10];
s_tabs = new int[20][10];
w_else = new String ("else");
w_if_ = new String ("if");
w_for = new String ("for");
w_ds = new String ("default");
w_case = new String ("case");
w_cpp_comment = new String ("//");
w_jdoc = new String ("/**");
line_feed = new String ("\n");
// read as long as there is something to read
EOF = 0; // = 1 set in getchr when EOF
chars = new char[BLOCK_MAXLEN];
string = new char[BLOCK_MAXLEN];
try { // the whole process
// open for input
reader = new CharArrayReader(originalText.toCharArray());
// add buffering to that InputStream
// bin = new BufferedInputStream(in);
for (int ib = 0; ib < BLOCK_MAXLEN; ib++) chars[ib] = '\0';
lineLength = readCount = 0;
// read up a block - remember how many bytes read
readCount = reader.read(chars);
strBlock = new String(chars);
lineLength = readCount;
lineNumber = 1;
indexBlock = -1;
j = 0;
while (EOF == 0)
{
c = getchr();
switch(c)
{
default:
string[j++] = c;
if(c != ',')
{
l_char = c;
}
break;
case ' ':
case '\t':
if(lookup(w_else) == 1)
{
gotelse();
if(s_flg == 0 || j > 0)string[j++] = c;
indent_puts();
s_flg = 0;
break;
}
if(s_flg == 0 || j > 0)string[j++] = c;
break;
case '\r': // <CR> for MS Windows 95
case '\n':
lineNumber++;
if (EOF==1)
{
break;
}
//String j_string = new String(string);
e_flg = lookup(w_else);
if(e_flg == 1) gotelse();
if (lookup_com(w_cpp_comment) == 1)
{
if (string[j] == '\n')
{
string[j] = '\0';
j--;
}
}
indent_puts();
//fprintf(outfil, line_feed);
fprintf(line_feed);
s_flg = 1;
if(e_flg == 1)
{
p_flg[level]++;
tabs++;
}
else
if(p_char == l_char)
{
a_flg = 1;
}
break;
case '{':
if(lookup(w_else) == 1)gotelse();
if (s_if_lev.length == c_level) {
s_if_lev = PApplet.expand(s_if_lev);
s_if_flg = PApplet.expand(s_if_flg);
}
s_if_lev[c_level] = if_lev;
s_if_flg[c_level] = if_flg;
if_lev = if_flg = 0;
c_level++;
if(s_flg == 1 && p_flg[level] != 0)
{
p_flg[level]--;
tabs--;
}
string[j++] = c;
indent_puts();
getnl() ;
indent_puts();
//fprintf(outfil,"\n");
fprintf("\n");
tabs++;
s_flg = 1;
if(p_flg[level] > 0)
{
ind[level] = 1;
level++;
s_level[level] = c_level;
}
break;
case '}':
c_level--;
if (c_level < 0)
{
EOF = 1;
//System.out.println("eof b");
string[j++] = c;
indent_puts();
break;
}
if ((if_lev = s_if_lev[c_level]-1) < 0)
if_lev = 0;
if_flg = s_if_flg[c_level];
indent_puts();
tabs--;
p_tabs();
peekc = getchr();
if( peekc == ';')
{
onechar = new StringBuffer();
onechar.append(c); // the }
onechar.append(';');
//fprintf(outfil, onechar.toString());
fprintf(onechar.toString());
peek = -1;
peekc = '`';
}
else
{
onechar = new StringBuffer();
onechar.append(c);
//fprintf(outfil, onechar.toString());
fprintf(onechar.toString());
peek = 1;
}
getnl();
indent_puts();
//fprintf(outfil,"\n");
fprintf("\n");
s_flg = 1;
if(c_level < s_level[level])
if(level > 0) level--;
if(ind[level] != 0)
{
tabs -= p_flg[level];
p_flg[level] = 0;
ind[level] = 0;
}
break;
case '"':
case '\'':
string[j++] = c;
cc = getchr();
int count = 0;
while(cc != c && EOF == 0)
{
if (++count % 100000 == 0) {
System.err.println("Stuck: " + count);
}
// max. length of line should be 256
string[j++] = cc;
if(cc == '\\')
{
cc = string[j++] = getchr();
}
if(cc == '\n')
{
lineNumber++;
indent_puts();
s_flg = 1;
}
cc = getchr();
}
string[j++] = cc;
if(getnl() == 1)
{
l_char = cc;
peek = 1;
peekc = '\n';
}
break;
case ';':
string[j++] = c;
indent_puts();
if(p_flg[level] > 0 && ind[level] == 0)
{
tabs -= p_flg[level];
p_flg[level] = 0;
}
getnl();
indent_puts();
//fprintf(outfil,"\n");
fprintf("\n");
s_flg = 1;
if(if_lev > 0)
if(if_flg == 1)
{
if_lev--;
if_flg = 0;
}
else if_lev = 0;
break;
case '\\':
string[j++] = c;
string[j++] = getchr();
break;
case '?':
q_flg = 1;
string[j++] = c;
break;
case ':':
string[j++] = c;
peekc = getchr();
if(peekc == ':')
{
indent_puts();
//fprintf (outfil,":");
fprintf(":");
peek = -1;
peekc = '`';
break;
}
else
{
//int double_colon = 0;
peek = 1;
}
if(q_flg == 1)
{
q_flg = 0;
break;
}
if(lookup(w_ds) == 0 && lookup(w_case) == 0)
{
s_flg = 0;
indent_puts();
}
else
{
tabs--;
indent_puts();
tabs++;
}
peekc = getchr();
if(peekc == ';')
{
fprintf(";");
peek = -1;
peekc = '`';
}
else
{
peek = 1;
}
getnl();
indent_puts();
fprintf("\n");
s_flg = 1;
break;
case '/':
string[j++] = c;
peekc = getchr();
if(peekc == '/')
{
string[j++] = peekc;
peekc = '`';
peek = -1;
cpp_comment();
//fprintf(outfil,"\n");
fprintf("\n");
break;
}
else
{
peek = 1;
}
if(peekc != '*') {
break;
}
else
{
if (j > 0) string[j--] = '\0';
if (j > 0) indent_puts();
string[j++] = '/';
string[j++] = '*';
peek = -1;
peekc = '`';
comment();
break;
}
case '#':
string[j++] = c;
cc = getchr();
while(cc != '\n' && EOF == 0)
{
string[j++] = cc;
cc = getchr();
}
string[j++] = cc;
s_flg = 0;
indent_puts();
s_flg = 1;
break;
case ')':
paren--;
if (paren < 0)
{
EOF = 1;
//System.out.println("eof c");
}
string[j++] = c;
indent_puts();
if(getnl() == 1)
{
peekc = '\n';
peek = 1;
if(paren != 0)
{
a_flg = 1;
}
else if(tabs > 0)
{
p_flg[level]++;
tabs++;
ind[level] = 0;
}
}
break;
case '(':
string[j++] = c;
paren++;
if ((lookup(w_for) == 1))
{
c = get_string();
while(c != ';' && EOF == 0) c = get_string();
ct=0;
int for_done = 0;
while (for_done == 0 && EOF == 0)
{
c = get_string();
while(c != ')' && EOF == 0)
{
if(c == '(') ct++;
c = get_string();
}
if(ct != 0)
{
ct--;
}
else for_done = 1;
} // endwhile for_done
paren--;
if (paren < 0)
{
EOF = 1;
//System.out.println("eof d");
}
indent_puts();
if(getnl() == 1)
{
peekc = '\n';
peek = 1;
p_flg[level]++;
tabs++;
ind[level] = 0;
}
break;
}
if(lookup(w_if_) == 1)
{
indent_puts();
s_tabs[c_level][if_lev] = tabs;
sp_flg[c_level][if_lev] = p_flg[level];
s_ind[c_level][if_lev] = ind[level];
if_lev++;
if_flg = 1;
}
} // end switch
//System.out.println("string len is " + string.length);
//if (EOF == 1) System.out.println(string);
//String j_string = new String(string);
} // end while not EOF
/*
int bad;
while ((bad = bin.read()) != -1) {
System.out.print((char) bad);
}
*/
/*
char bad;
//while ((bad = getchr()) != 0) {
while (true) {
getchr();
if (peek != -1) {
System.out.print(last_char);
} else {
break;
}
}
*/
// save current (rough) selection point
int selectionEnd = editor.getSelectionStop();
// make sure the caret would be past the end of the text
if (strOut.length() < selectionEnd - 1) {
selectionEnd = strOut.length() - 1;
}
reader.close(); // close buff
String formattedText = strOut.toString();
if (formattedText.equals(originalText)) {
editor.statusNotice(_("No changes necessary for Auto Format."));
} else if (paren != 0) {
// warn user if there are too many parens in either direction
if (paren < 0) {
editor.statusError(
_("Auto Format Canceled: Too many right parentheses."));
} else {
editor.statusError(
_("Auto Format Canceled: Too many left parentheses."));
}
} else if (c_level != 0) { // check braces only if parens are ok
if (c_level < 0) {
editor.statusError(
_("Auto Format Canceled: Too many right curly braces."));
} else {
editor.statusError(
_("Auto Format Canceled: Too many left curly braces."));
}
} else {
// replace with new bootiful text
// selectionEnd hopefully at least in the neighborhood
editor.setText(formattedText);
editor.setSelection(selectionEnd, selectionEnd);
editor.getSketch().setModified(true);
// mark as finished
editor.statusNotice(_("Auto Format finished."));
}
} catch (Exception e) {
| public void run() {
StringBuffer onechar;
// Adding an additional newline as a hack around other errors
String originalText = editor.getText() + "\n";
strOut = new StringBuffer();
indentValue = Preferences.getInteger("editor.tabs.size");
indentChar = new String(" ");
lineNumber = 0;
c_level = if_lev = level = e_flg = paren = 0;
a_flg = q_flg = j = tabs = 0;
if_flg = peek = -1;
peekc = '`';
s_flg = 1;
jdoc = 0;
s_level = new int[10];
sp_flg = new int[20][10];
s_ind = new int[20][10];
s_if_lev = new int[10];
s_if_flg = new int[10];
ind = new int[10];
p_flg = new int[10];
s_tabs = new int[20][10];
w_else = new String ("else");
w_if_ = new String ("if");
w_for = new String ("for");
w_ds = new String ("default");
w_case = new String ("case");
w_cpp_comment = new String ("//");
w_jdoc = new String ("/**");
line_feed = new String ("\n");
// read as long as there is something to read
EOF = 0; // = 1 set in getchr when EOF
chars = new char[BLOCK_MAXLEN];
string = new char[BLOCK_MAXLEN];
try { // the whole process
// open for input
reader = new CharArrayReader(originalText.toCharArray());
// add buffering to that InputStream
// bin = new BufferedInputStream(in);
for (int ib = 0; ib < BLOCK_MAXLEN; ib++) chars[ib] = '\0';
lineLength = readCount = 0;
// read up a block - remember how many bytes read
readCount = reader.read(chars);
strBlock = new String(chars);
lineLength = readCount;
lineNumber = 1;
indexBlock = -1;
j = 0;
while (EOF == 0)
{
c = getchr();
switch(c)
{
default:
string[j++] = c;
if(c != ',')
{
l_char = c;
}
break;
case ' ':
case '\t':
if(lookup(w_else) == 1)
{
gotelse();
if(s_flg == 0 || j > 0)string[j++] = c;
indent_puts();
s_flg = 0;
break;
}
if(s_flg == 0 || j > 0)string[j++] = c;
break;
case '\r': // <CR> for MS Windows 95
case '\n':
lineNumber++;
if (EOF==1)
{
break;
}
//String j_string = new String(string);
e_flg = lookup(w_else);
if(e_flg == 1) gotelse();
if (lookup_com(w_cpp_comment) == 1)
{
if (string[j] == '\n')
{
string[j] = '\0';
j--;
}
}
indent_puts();
//fprintf(outfil, line_feed);
fprintf(line_feed);
s_flg = 1;
if(e_flg == 1)
{
p_flg[level]++;
tabs++;
}
else
if(p_char == l_char)
{
a_flg = 1;
}
break;
case '{':
if(lookup(w_else) == 1)gotelse();
if (s_if_lev.length == c_level) {
s_if_lev = PApplet.expand(s_if_lev);
s_if_flg = PApplet.expand(s_if_flg);
}
s_if_lev[c_level] = if_lev;
s_if_flg[c_level] = if_flg;
if_lev = if_flg = 0;
c_level++;
if(s_flg == 1 && p_flg[level] != 0)
{
p_flg[level]--;
tabs--;
}
string[j++] = c;
indent_puts();
getnl() ;
indent_puts();
//fprintf(outfil,"\n");
fprintf("\n");
tabs++;
s_flg = 1;
if(p_flg[level] > 0)
{
ind[level] = 1;
level++;
s_level[level] = c_level;
}
break;
case '}':
c_level--;
if (c_level < 0)
{
EOF = 1;
//System.out.println("eof b");
string[j++] = c;
indent_puts();
break;
}
if ((if_lev = s_if_lev[c_level]-1) < 0)
if_lev = 0;
if_flg = s_if_flg[c_level];
indent_puts();
tabs--;
p_tabs();
peekc = getchr();
if( peekc == ';')
{
onechar = new StringBuffer();
onechar.append(c); // the }
onechar.append(';');
//fprintf(outfil, onechar.toString());
fprintf(onechar.toString());
peek = -1;
peekc = '`';
}
else
{
onechar = new StringBuffer();
onechar.append(c);
//fprintf(outfil, onechar.toString());
fprintf(onechar.toString());
peek = 1;
}
getnl();
indent_puts();
//fprintf(outfil,"\n");
fprintf("\n");
s_flg = 1;
if(c_level < s_level[level])
if(level > 0) level--;
if(ind[level] != 0)
{
tabs -= p_flg[level];
p_flg[level] = 0;
ind[level] = 0;
}
break;
case '"':
case '\'':
string[j++] = c;
cc = getchr();
int count = 0;
while(cc != c && EOF == 0)
{
// max. length of line should be 256
string[j++] = cc;
if(cc == '\\')
{
cc = string[j++] = getchr();
}
if(cc == '\n')
{
lineNumber++;
indent_puts();
s_flg = 1;
}
cc = getchr();
}
string[j++] = cc;
if(getnl() == 1)
{
l_char = cc;
peek = 1;
peekc = '\n';
}
break;
case ';':
string[j++] = c;
indent_puts();
if(p_flg[level] > 0 && ind[level] == 0)
{
tabs -= p_flg[level];
p_flg[level] = 0;
}
getnl();
indent_puts();
//fprintf(outfil,"\n");
fprintf("\n");
s_flg = 1;
if(if_lev > 0)
if(if_flg == 1)
{
if_lev--;
if_flg = 0;
}
else if_lev = 0;
break;
case '\\':
string[j++] = c;
string[j++] = getchr();
break;
case '?':
q_flg = 1;
string[j++] = c;
break;
case ':':
string[j++] = c;
peekc = getchr();
if(peekc == ':')
{
indent_puts();
//fprintf (outfil,":");
fprintf(":");
peek = -1;
peekc = '`';
break;
}
else
{
//int double_colon = 0;
peek = 1;
}
if(q_flg == 1)
{
q_flg = 0;
break;
}
if(lookup(w_ds) == 0 && lookup(w_case) == 0)
{
s_flg = 0;
indent_puts();
}
else
{
tabs--;
indent_puts();
tabs++;
}
peekc = getchr();
if(peekc == ';')
{
fprintf(";");
peek = -1;
peekc = '`';
}
else
{
peek = 1;
}
getnl();
indent_puts();
fprintf("\n");
s_flg = 1;
break;
case '/':
string[j++] = c;
peekc = getchr();
if(peekc == '/')
{
string[j++] = peekc;
peekc = '`';
peek = -1;
cpp_comment();
//fprintf(outfil,"\n");
fprintf("\n");
break;
}
else
{
peek = 1;
}
if(peekc != '*') {
break;
}
else
{
if (j > 0) string[j--] = '\0';
if (j > 0) indent_puts();
string[j++] = '/';
string[j++] = '*';
peek = -1;
peekc = '`';
comment();
break;
}
case '#':
string[j++] = c;
cc = getchr();
while(cc != '\n' && EOF == 0)
{
string[j++] = cc;
cc = getchr();
}
string[j++] = cc;
s_flg = 0;
indent_puts();
s_flg = 1;
break;
case ')':
paren--;
if (paren < 0)
{
EOF = 1;
//System.out.println("eof c");
}
string[j++] = c;
indent_puts();
if(getnl() == 1)
{
peekc = '\n';
peek = 1;
if(paren != 0)
{
a_flg = 1;
}
else if(tabs > 0)
{
p_flg[level]++;
tabs++;
ind[level] = 0;
}
}
break;
case '(':
string[j++] = c;
paren++;
if ((lookup(w_for) == 1))
{
c = get_string();
while(c != ';' && EOF == 0) c = get_string();
ct=0;
int for_done = 0;
while (for_done == 0 && EOF == 0)
{
c = get_string();
while(c != ')' && EOF == 0)
{
if(c == '(') ct++;
c = get_string();
}
if(ct != 0)
{
ct--;
}
else for_done = 1;
} // endwhile for_done
paren--;
if (paren < 0)
{
EOF = 1;
//System.out.println("eof d");
}
indent_puts();
if(getnl() == 1)
{
peekc = '\n';
peek = 1;
p_flg[level]++;
tabs++;
ind[level] = 0;
}
break;
}
if(lookup(w_if_) == 1)
{
indent_puts();
s_tabs[c_level][if_lev] = tabs;
sp_flg[c_level][if_lev] = p_flg[level];
s_ind[c_level][if_lev] = ind[level];
if_lev++;
if_flg = 1;
}
} // end switch
//System.out.println("string len is " + string.length);
//if (EOF == 1) System.out.println(string);
//String j_string = new String(string);
} // end while not EOF
/*
int bad;
while ((bad = bin.read()) != -1) {
System.out.print((char) bad);
}
*/
/*
char bad;
//while ((bad = getchr()) != 0) {
while (true) {
getchr();
if (peek != -1) {
System.out.print(last_char);
} else {
break;
}
}
*/
// save current (rough) selection point
int selectionEnd = editor.getSelectionStop();
// make sure the caret would be past the end of the text
if (strOut.length() < selectionEnd - 1) {
selectionEnd = strOut.length() - 1;
}
reader.close(); // close buff
String formattedText = strOut.toString();
if (formattedText.equals(originalText)) {
editor.statusNotice(_("No changes necessary for Auto Format."));
} else if (paren != 0) {
// warn user if there are too many parens in either direction
if (paren < 0) {
editor.statusError(
_("Auto Format Canceled: Too many right parentheses."));
} else {
editor.statusError(
_("Auto Format Canceled: Too many left parentheses."));
}
} else if (c_level != 0) { // check braces only if parens are ok
if (c_level < 0) {
editor.statusError(
_("Auto Format Canceled: Too many right curly braces."));
} else {
editor.statusError(
_("Auto Format Canceled: Too many left curly braces."));
}
} else {
// replace with new bootiful text
// selectionEnd hopefully at least in the neighborhood
editor.setText(formattedText);
editor.setSelection(selectionEnd, selectionEnd);
editor.getSketch().setModified(true);
// mark as finished
editor.statusNotice(_("Auto Format finished."));
}
} catch (Exception e) {
|
diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/repository/MetadataRepositoryManagerTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/repository/MetadataRepositoryManagerTest.java
index 7ad00da1d..80e8872b7 100644
--- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/repository/MetadataRepositoryManagerTest.java
+++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/metadata/repository/MetadataRepositoryManagerTest.java
@@ -1,192 +1,192 @@
/*******************************************************************************
* Copyright (c) 2007, 2008 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.equinox.p2.tests.metadata.repository;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.*;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper;
import org.eclipse.equinox.internal.p2.core.helpers.URLUtil;
import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException;
import org.eclipse.equinox.internal.provisional.p2.core.location.AgentLocation;
import org.eclipse.equinox.internal.provisional.p2.core.repository.IRepository;
import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepository;
import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepositoryManager;
import org.eclipse.equinox.p2.tests.AbstractProvisioningTest;
import org.eclipse.equinox.p2.tests.TestActivator;
/**
* Tests for API of {@link IMetadataRepositoryManager}.
*/
public class MetadataRepositoryManagerTest extends AbstractProvisioningTest {
protected IMetadataRepositoryManager manager;
/**
* Contains temp File handles that should be deleted at the end of the test.
*/
private final List toDelete = new ArrayList();
public static Test suite() {
return new TestSuite(MetadataRepositoryManagerTest.class);
}
protected void setUp() throws Exception {
super.setUp();
manager = (IMetadataRepositoryManager) ServiceHelper.getService(TestActivator.context, IMetadataRepositoryManager.class.getName());
}
protected void tearDown() throws Exception {
super.tearDown();
for (Iterator it = toDelete.iterator(); it.hasNext();)
delete((File) it.next());
toDelete.clear();
}
public void testBasicAddRemove() throws MalformedURLException {
File tempFile = new File(System.getProperty("java.io.tmpdir"));
URL location = tempFile.toURL();
assertTrue(!managerContains(location));
manager.addRepository(location);
assertTrue(managerContains(location));
manager.removeRepository(location);
assertTrue(!managerContains(location));
}
public void testGetKnownRepositories() throws MalformedURLException, ProvisionException {
int nonSystemCount = manager.getKnownRepositories(IMetadataRepositoryManager.REPOSITORIES_NON_SYSTEM).length;
int systemCount = manager.getKnownRepositories(IMetadataRepositoryManager.REPOSITORIES_SYSTEM).length;
int allCount = manager.getKnownRepositories(IMetadataRepositoryManager.REPOSITORIES_ALL).length;
assertEquals("1.0", allCount, nonSystemCount + systemCount);
//create a new repository
File repoLocation = getTempLocation();
IMetadataRepository testRepo = manager.createRepository(repoLocation.toURL(), "MetadataRepositoryManagerTest", IMetadataRepositoryManager.TYPE_SIMPLE_REPOSITORY);
manager.addRepository(testRepo.getLocation());
int newNonSystemCount = manager.getKnownRepositories(IMetadataRepositoryManager.REPOSITORIES_NON_SYSTEM).length;
int newSystemCount = manager.getKnownRepositories(IMetadataRepositoryManager.REPOSITORIES_SYSTEM).length;
int newAllCount = manager.getKnownRepositories(IMetadataRepositoryManager.REPOSITORIES_ALL).length;
//there should be one more non-system repository
assertEquals("2.0", nonSystemCount + 1, newNonSystemCount);
assertEquals("2.1", systemCount, newSystemCount);
assertEquals("2.2", allCount + 1, newAllCount);
//make the repository a system repository
testRepo.setProperty(IRepository.PROP_SYSTEM, Boolean.TRUE.toString());
//there should be one more system repository
newNonSystemCount = manager.getKnownRepositories(IMetadataRepositoryManager.REPOSITORIES_NON_SYSTEM).length;
newSystemCount = manager.getKnownRepositories(IMetadataRepositoryManager.REPOSITORIES_SYSTEM).length;
newAllCount = manager.getKnownRepositories(IMetadataRepositoryManager.REPOSITORIES_ALL).length;
assertEquals("3.0", nonSystemCount, newNonSystemCount);
assertEquals("3.1", systemCount + 1, newSystemCount);
assertEquals("3.2", allCount + 1, newAllCount);
}
/**
* Tests that we don't create a local cache when contacting a local metadata repository.
*/
public void testMetadataCachingLocalRepo() throws MalformedURLException, ProvisionException {
File repoLocation = getTempLocation();
AgentLocation agentLocation = (AgentLocation) ServiceHelper.getService(TestActivator.getContext(), AgentLocation.class.getName());
URL dataArea = agentLocation.getDataArea("org.eclipse.equinox.p2.metadata.repository/cache/");
File dataAreaFile = URLUtil.toFile(dataArea);
File cacheFileXML = new File(dataAreaFile, "content" + repoLocation.hashCode() + ".xml");
File cacheFileJAR = new File(dataAreaFile, "content" + repoLocation.hashCode() + ".jar");
// create a local repository
IMetadataRepository testRepo = manager.createRepository(repoLocation.toURL(), "MetadataRepositoryCachingTest", IMetadataRepositoryManager.TYPE_SIMPLE_REPOSITORY);
manager.loadRepository(repoLocation.toURL(), null);
// check that a local cache was not created
assertFalse("Cache file was created.", cacheFileXML.exists() || cacheFileJAR.exists());
}
/**
* Tests that local caching of remote metadata repositories works, and that the
* cache is updated when it becomes stale.
*/
public void testMetadataCachingRemoteRepo() throws MalformedURLException, ProvisionException {
- URL repoLocation = new URL("http://download.eclipse.org/eclipse/testUpdates/");
+ URL repoLocation = new URL("http://fullmoon.ottawa.ibm.com/eclipse/updates/3.4milestones/");
AgentLocation agentLocation = (AgentLocation) ServiceHelper.getService(TestActivator.getContext(), AgentLocation.class.getName());
URL dataArea = agentLocation.getDataArea("org.eclipse.equinox.p2.metadata.repository/cache/");
File dataAreaFile = URLUtil.toFile(dataArea);
- File cacheFileXML = new File(dataAreaFile, "content" + repoLocation.hashCode() + ".xml");
- File cacheFileJAR = new File(dataAreaFile, "content" + repoLocation.hashCode() + ".jar");
+ File cacheFileXML = new File(dataAreaFile, "content" + repoLocation.toExternalForm().hashCode() + ".xml");
+ File cacheFileJAR = new File(dataAreaFile, "content" + repoLocation.toExternalForm().hashCode() + ".jar");
File cacheFile;
// load a remote repository and check that a local cache was created
manager.loadRepository(repoLocation, null);
assertTrue("Cache file was not created.", cacheFileXML.exists() || cacheFileJAR.exists());
if (cacheFileXML.exists())
cacheFile = cacheFileXML;
else
cacheFile = cacheFileJAR;
// modify the last modified date to be older than the remote file
cacheFile.setLastModified(0);
// reload the repository and check that the cache was updated
manager.removeRepository(repoLocation);
manager.loadRepository(repoLocation, null);
long lastModified = cacheFile.lastModified();
assertTrue(0 != lastModified);
// reload the repository and check that the cache was not updated
manager.removeRepository(repoLocation);
manager.loadRepository(repoLocation, null);
assertTrue(lastModified == cacheFile.lastModified());
cacheFile.delete();
}
/**
* Returns a non-existent file that can be used to write a temporary
* file or directory. The location will be deleted in the test tearDown method.
*/
private File getTempLocation() {
File tempDir = new File(System.getProperty("java.io.tmpdir"));
File tempFile = new File(tempDir, "MetadataRepositoryManagerTest");
delete(tempFile);
assertTrue(!tempFile.exists());
return tempFile;
}
public void testFailureAddRemove() {
try {
manager.addRepository(null);
fail();
} catch (RuntimeException e) {
//expected
}
try {
manager.removeRepository(null);
fail();
} catch (RuntimeException e) {
//expected
}
}
/**
* Returns whether {@link IMetadataRepositoryManager} contains a reference
* to a repository at the given location.
*/
private boolean managerContains(URL location) {
URL[] locations = manager.getKnownRepositories(IMetadataRepositoryManager.REPOSITORIES_ALL);
for (int i = 0; i < locations.length; i++) {
if (locations[i].equals(location))
return true;
}
return false;
}
}
| false | true | public void testMetadataCachingRemoteRepo() throws MalformedURLException, ProvisionException {
URL repoLocation = new URL("http://download.eclipse.org/eclipse/testUpdates/");
AgentLocation agentLocation = (AgentLocation) ServiceHelper.getService(TestActivator.getContext(), AgentLocation.class.getName());
URL dataArea = agentLocation.getDataArea("org.eclipse.equinox.p2.metadata.repository/cache/");
File dataAreaFile = URLUtil.toFile(dataArea);
File cacheFileXML = new File(dataAreaFile, "content" + repoLocation.hashCode() + ".xml");
File cacheFileJAR = new File(dataAreaFile, "content" + repoLocation.hashCode() + ".jar");
File cacheFile;
// load a remote repository and check that a local cache was created
manager.loadRepository(repoLocation, null);
assertTrue("Cache file was not created.", cacheFileXML.exists() || cacheFileJAR.exists());
if (cacheFileXML.exists())
cacheFile = cacheFileXML;
else
cacheFile = cacheFileJAR;
// modify the last modified date to be older than the remote file
cacheFile.setLastModified(0);
// reload the repository and check that the cache was updated
manager.removeRepository(repoLocation);
manager.loadRepository(repoLocation, null);
long lastModified = cacheFile.lastModified();
assertTrue(0 != lastModified);
// reload the repository and check that the cache was not updated
manager.removeRepository(repoLocation);
manager.loadRepository(repoLocation, null);
assertTrue(lastModified == cacheFile.lastModified());
cacheFile.delete();
}
| public void testMetadataCachingRemoteRepo() throws MalformedURLException, ProvisionException {
URL repoLocation = new URL("http://fullmoon.ottawa.ibm.com/eclipse/updates/3.4milestones/");
AgentLocation agentLocation = (AgentLocation) ServiceHelper.getService(TestActivator.getContext(), AgentLocation.class.getName());
URL dataArea = agentLocation.getDataArea("org.eclipse.equinox.p2.metadata.repository/cache/");
File dataAreaFile = URLUtil.toFile(dataArea);
File cacheFileXML = new File(dataAreaFile, "content" + repoLocation.toExternalForm().hashCode() + ".xml");
File cacheFileJAR = new File(dataAreaFile, "content" + repoLocation.toExternalForm().hashCode() + ".jar");
File cacheFile;
// load a remote repository and check that a local cache was created
manager.loadRepository(repoLocation, null);
assertTrue("Cache file was not created.", cacheFileXML.exists() || cacheFileJAR.exists());
if (cacheFileXML.exists())
cacheFile = cacheFileXML;
else
cacheFile = cacheFileJAR;
// modify the last modified date to be older than the remote file
cacheFile.setLastModified(0);
// reload the repository and check that the cache was updated
manager.removeRepository(repoLocation);
manager.loadRepository(repoLocation, null);
long lastModified = cacheFile.lastModified();
assertTrue(0 != lastModified);
// reload the repository and check that the cache was not updated
manager.removeRepository(repoLocation);
manager.loadRepository(repoLocation, null);
assertTrue(lastModified == cacheFile.lastModified());
cacheFile.delete();
}
|
diff --git a/modules/org.restlet/src/org/restlet/engine/http/header/AcceptReader.java b/modules/org.restlet/src/org/restlet/engine/http/header/AcceptReader.java
index 6c0aa87ff..050ab676d 100644
--- a/modules/org.restlet/src/org/restlet/engine/http/header/AcceptReader.java
+++ b/modules/org.restlet/src/org/restlet/engine/http/header/AcceptReader.java
@@ -1,349 +1,350 @@
/**
* Copyright 2005-2010 Noelios Technologies.
*
* The contents of this file are subject to the terms of one of the following
* open source licenses: LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL 1.0 (the
* "Licenses"). You can select the license that you prefer but you may not use
* this file except in compliance with one of these Licenses.
*
* You can obtain a copy of the LGPL 3.0 license at
* http://www.opensource.org/licenses/lgpl-3.0.html
*
* You can obtain a copy of the LGPL 2.1 license at
* http://www.opensource.org/licenses/lgpl-2.1.php
*
* You can obtain a copy of the CDDL 1.0 license at
* http://www.opensource.org/licenses/cddl1.php
*
* You can obtain a copy of the EPL 1.0 license at
* http://www.opensource.org/licenses/eclipse-1.0.php
*
* See the Licenses for the specific language governing permissions and
* limitations under the Licenses.
*
* Alternatively, you can obtain a royalty free commercial license with less
* limitations, transferable or non-transferable, directly at
* http://www.noelios.com/products/restlet-engine
*
* Restlet is a registered trademark of Noelios Technologies.
*/
package org.restlet.engine.http.header;
import java.io.IOException;
import java.util.Iterator;
import static org.restlet.engine.http.header.HeaderUtils.*;
import org.restlet.data.CharacterSet;
import org.restlet.data.Encoding;
import org.restlet.data.Form;
import org.restlet.data.Language;
import org.restlet.data.MediaType;
import org.restlet.data.Metadata;
import org.restlet.data.Parameter;
import org.restlet.data.Preference;
import org.restlet.util.Series;
/**
* Accept-* headers reader. Works for character sets, encodings, languages or
* media types.
*
* @author Jerome Louvel
*/
public class AcceptReader<T extends Metadata> extends
HeaderReader<Preference<T>> {
public static final int TYPE_CHARACTER_SET = 1;
public static final int TYPE_ENCODING = 2;
public static final int TYPE_LANGUAGE = 3;
public static final int TYPE_MEDIA_TYPE = 4;
/** The type of metadata read. */
private volatile int type;
/**
* Constructor.
*
* @param type
* The type of metadata read.
* @param header
* The header to read.
*/
public AcceptReader(int type, String header) {
super(header);
this.type = type;
}
/**
* Creates a new preference.
*
* @param metadata
* The metadata name.
* @param parameters
* The parameters list.
* @return The new preference.
*/
@SuppressWarnings("unchecked")
protected Preference<T> createPreference(CharSequence metadata,
Series<Parameter> parameters) {
Preference<T> result;
if (parameters == null) {
result = new Preference<T>();
switch (this.type) {
case TYPE_CHARACTER_SET:
result.setMetadata((T) CharacterSet
.valueOf(metadata.toString()));
break;
case TYPE_ENCODING:
result.setMetadata((T) Encoding.valueOf(metadata.toString()));
break;
case TYPE_LANGUAGE:
result.setMetadata((T) Language.valueOf(metadata.toString()));
break;
case TYPE_MEDIA_TYPE:
result.setMetadata((T) MediaType.valueOf(metadata.toString()));
break;
}
} else {
final Series<Parameter> mediaParams = extractMediaParams(parameters);
final float quality = extractQuality(parameters);
result = new Preference<T>(null, quality, parameters);
switch (this.type) {
case TYPE_CHARACTER_SET:
result.setMetadata((T) new CharacterSet(metadata.toString()));
break;
case TYPE_ENCODING:
result.setMetadata((T) new Encoding(metadata.toString()));
break;
case TYPE_LANGUAGE:
result.setMetadata((T) new Language(metadata.toString()));
break;
case TYPE_MEDIA_TYPE:
result.setMetadata((T) new MediaType(metadata.toString(),
mediaParams));
break;
}
}
return result;
}
/**
* Extract the media parameters. Only leave as the quality parameter if
* found. Modifies the parameters list.
*
* @param parameters
* All the preference parameters.
* @return The media parameters.
*/
protected Series<Parameter> extractMediaParams(Series<Parameter> parameters) {
Series<Parameter> result = null;
boolean qualityFound = false;
Parameter param = null;
if (parameters != null) {
result = new Form();
for (final Iterator<Parameter> iter = parameters.iterator(); !qualityFound
&& iter.hasNext();) {
param = iter.next();
if (param.getName().equals("q")) {
qualityFound = true;
} else {
iter.remove();
result.add(param);
}
}
}
return result;
}
/**
* Extract the quality value. If the value is not found, 1 is returned.
*
* @param parameters
* The preference parameters.
* @return The quality value.
*/
protected float extractQuality(Series<Parameter> parameters) {
float result = 1F;
boolean found = false;
if (parameters != null) {
Parameter param = null;
for (final Iterator<Parameter> iter = parameters.iterator(); !found
&& iter.hasNext();) {
param = iter.next();
if (param.getName().equals("q")) {
result = PreferenceUtils.parseQuality(param.getValue());
found = true;
// Remove the quality parameter as we will directly store it
// in the Preference object
iter.remove();
}
}
}
return result;
}
/**
* Read the next preference.
*
* @return The next preference.
*/
public Preference<T> readValue() throws IOException {
Preference<T> result = null;
boolean readingMetadata = true;
boolean readingParamName = false;
boolean readingParamValue = false;
StringBuilder metadataBuffer = new StringBuilder();
StringBuilder paramNameBuffer = null;
StringBuilder paramValueBuffer = null;
Series<Parameter> parameters = null;
int next = 0;
while (result == null) {
next = read();
if (readingMetadata) {
if ((next == -1) || isComma(next)) {
if (metadataBuffer.length() > 0) {
// End of metadata section
// No parameters detected
result = createPreference(metadataBuffer, null);
} else {
// Ignore empty metadata name
+ break;
}
} else if (next == ';') {
if (metadataBuffer.length() > 0) {
// End of metadata section
// Parameters detected
readingMetadata = false;
readingParamName = true;
paramNameBuffer = new StringBuilder();
parameters = new Form();
} else {
throw new IOException("Empty metadata name detected.");
}
} else if (isSpace(next)) {
// Ignore spaces
} else if (isText(next)) {
metadataBuffer.append((char) next);
} else {
throw new IOException("Unexpected character \""
+ (char) next + "\" detected.");
}
} else if (readingParamName) {
if (next == '=') {
if (paramNameBuffer.length() > 0) {
// End of parameter name section
readingParamName = false;
readingParamValue = true;
paramValueBuffer = new StringBuilder();
} else {
throw new IOException("Empty parameter name detected.");
}
} else if ((next == -1) || isComma(next)) {
if (paramNameBuffer.length() > 0) {
// End of parameters section
parameters.add(Parameter.create(paramNameBuffer, null));
result = createPreference(metadataBuffer, parameters);
} else {
throw new IOException("Empty parameter name detected.");
}
} else if (next == ';') {
// End of parameter
parameters.add(Parameter.create(paramNameBuffer, null));
paramNameBuffer = new StringBuilder();
readingParamName = true;
readingParamValue = false;
} else if (isSpace(next) && (paramNameBuffer.length() == 0)) {
// Ignore white spaces
} else if (isTokenChar(next)) {
paramNameBuffer.append((char) next);
} else {
throw new IOException("Unexpected character \""
+ (char) next + "\" detected.");
}
} else if (readingParamValue) {
if ((next == -1) || isComma(next) || isSpace(next)) {
if (paramValueBuffer.length() > 0) {
// End of parameters section
parameters.add(Parameter.create(paramNameBuffer,
paramValueBuffer));
result = createPreference(metadataBuffer, parameters);
} else {
throw new IOException("Empty parameter value detected");
}
} else if (next == ';') {
// End of parameter
parameters.add(Parameter.create(paramNameBuffer,
paramValueBuffer));
paramNameBuffer = new StringBuilder();
readingParamName = true;
readingParamValue = false;
} else if ((next == '"') && (paramValueBuffer.length() == 0)) {
// Parse the quoted string
boolean done = false;
boolean quotedPair = false;
while ((!done) && (next != -1)) {
next = read();
if (quotedPair) {
// End of quoted pair (escape sequence)
if (isText(next)) {
paramValueBuffer.append((char) next);
quotedPair = false;
} else {
throw new IOException(
"Invalid character detected in quoted string. Please check your value");
}
} else if (isDoubleQuote(next)) {
// End of quoted string
done = true;
} else if (next == '\\') {
// Begin of quoted pair (escape sequence)
quotedPair = true;
} else if (isText(next)) {
paramValueBuffer.append((char) next);
} else {
throw new IOException(
"Invalid character detected in quoted string. Please check your value");
}
}
} else if (isTokenChar(next)) {
paramValueBuffer.append((char) next);
} else {
throw new IOException("Unexpected character \""
+ (char) next + "\" detected.");
}
}
}
if (isComma(next)) {
// Unread character which isn't part of the value
unread();
}
return result;
}
}
| true | true | public Preference<T> readValue() throws IOException {
Preference<T> result = null;
boolean readingMetadata = true;
boolean readingParamName = false;
boolean readingParamValue = false;
StringBuilder metadataBuffer = new StringBuilder();
StringBuilder paramNameBuffer = null;
StringBuilder paramValueBuffer = null;
Series<Parameter> parameters = null;
int next = 0;
while (result == null) {
next = read();
if (readingMetadata) {
if ((next == -1) || isComma(next)) {
if (metadataBuffer.length() > 0) {
// End of metadata section
// No parameters detected
result = createPreference(metadataBuffer, null);
} else {
// Ignore empty metadata name
}
} else if (next == ';') {
if (metadataBuffer.length() > 0) {
// End of metadata section
// Parameters detected
readingMetadata = false;
readingParamName = true;
paramNameBuffer = new StringBuilder();
parameters = new Form();
} else {
throw new IOException("Empty metadata name detected.");
}
} else if (isSpace(next)) {
// Ignore spaces
} else if (isText(next)) {
metadataBuffer.append((char) next);
} else {
throw new IOException("Unexpected character \""
+ (char) next + "\" detected.");
}
} else if (readingParamName) {
if (next == '=') {
if (paramNameBuffer.length() > 0) {
// End of parameter name section
readingParamName = false;
readingParamValue = true;
paramValueBuffer = new StringBuilder();
} else {
throw new IOException("Empty parameter name detected.");
}
} else if ((next == -1) || isComma(next)) {
if (paramNameBuffer.length() > 0) {
// End of parameters section
parameters.add(Parameter.create(paramNameBuffer, null));
result = createPreference(metadataBuffer, parameters);
} else {
throw new IOException("Empty parameter name detected.");
}
} else if (next == ';') {
// End of parameter
parameters.add(Parameter.create(paramNameBuffer, null));
paramNameBuffer = new StringBuilder();
readingParamName = true;
readingParamValue = false;
} else if (isSpace(next) && (paramNameBuffer.length() == 0)) {
// Ignore white spaces
} else if (isTokenChar(next)) {
paramNameBuffer.append((char) next);
} else {
throw new IOException("Unexpected character \""
+ (char) next + "\" detected.");
}
} else if (readingParamValue) {
if ((next == -1) || isComma(next) || isSpace(next)) {
if (paramValueBuffer.length() > 0) {
// End of parameters section
parameters.add(Parameter.create(paramNameBuffer,
paramValueBuffer));
result = createPreference(metadataBuffer, parameters);
} else {
throw new IOException("Empty parameter value detected");
}
} else if (next == ';') {
// End of parameter
parameters.add(Parameter.create(paramNameBuffer,
paramValueBuffer));
paramNameBuffer = new StringBuilder();
readingParamName = true;
readingParamValue = false;
} else if ((next == '"') && (paramValueBuffer.length() == 0)) {
// Parse the quoted string
boolean done = false;
boolean quotedPair = false;
while ((!done) && (next != -1)) {
next = read();
if (quotedPair) {
// End of quoted pair (escape sequence)
if (isText(next)) {
paramValueBuffer.append((char) next);
quotedPair = false;
} else {
throw new IOException(
"Invalid character detected in quoted string. Please check your value");
}
} else if (isDoubleQuote(next)) {
// End of quoted string
done = true;
} else if (next == '\\') {
// Begin of quoted pair (escape sequence)
quotedPair = true;
} else if (isText(next)) {
paramValueBuffer.append((char) next);
} else {
throw new IOException(
"Invalid character detected in quoted string. Please check your value");
}
}
} else if (isTokenChar(next)) {
paramValueBuffer.append((char) next);
} else {
throw new IOException("Unexpected character \""
+ (char) next + "\" detected.");
}
}
}
if (isComma(next)) {
// Unread character which isn't part of the value
unread();
}
return result;
}
| public Preference<T> readValue() throws IOException {
Preference<T> result = null;
boolean readingMetadata = true;
boolean readingParamName = false;
boolean readingParamValue = false;
StringBuilder metadataBuffer = new StringBuilder();
StringBuilder paramNameBuffer = null;
StringBuilder paramValueBuffer = null;
Series<Parameter> parameters = null;
int next = 0;
while (result == null) {
next = read();
if (readingMetadata) {
if ((next == -1) || isComma(next)) {
if (metadataBuffer.length() > 0) {
// End of metadata section
// No parameters detected
result = createPreference(metadataBuffer, null);
} else {
// Ignore empty metadata name
break;
}
} else if (next == ';') {
if (metadataBuffer.length() > 0) {
// End of metadata section
// Parameters detected
readingMetadata = false;
readingParamName = true;
paramNameBuffer = new StringBuilder();
parameters = new Form();
} else {
throw new IOException("Empty metadata name detected.");
}
} else if (isSpace(next)) {
// Ignore spaces
} else if (isText(next)) {
metadataBuffer.append((char) next);
} else {
throw new IOException("Unexpected character \""
+ (char) next + "\" detected.");
}
} else if (readingParamName) {
if (next == '=') {
if (paramNameBuffer.length() > 0) {
// End of parameter name section
readingParamName = false;
readingParamValue = true;
paramValueBuffer = new StringBuilder();
} else {
throw new IOException("Empty parameter name detected.");
}
} else if ((next == -1) || isComma(next)) {
if (paramNameBuffer.length() > 0) {
// End of parameters section
parameters.add(Parameter.create(paramNameBuffer, null));
result = createPreference(metadataBuffer, parameters);
} else {
throw new IOException("Empty parameter name detected.");
}
} else if (next == ';') {
// End of parameter
parameters.add(Parameter.create(paramNameBuffer, null));
paramNameBuffer = new StringBuilder();
readingParamName = true;
readingParamValue = false;
} else if (isSpace(next) && (paramNameBuffer.length() == 0)) {
// Ignore white spaces
} else if (isTokenChar(next)) {
paramNameBuffer.append((char) next);
} else {
throw new IOException("Unexpected character \""
+ (char) next + "\" detected.");
}
} else if (readingParamValue) {
if ((next == -1) || isComma(next) || isSpace(next)) {
if (paramValueBuffer.length() > 0) {
// End of parameters section
parameters.add(Parameter.create(paramNameBuffer,
paramValueBuffer));
result = createPreference(metadataBuffer, parameters);
} else {
throw new IOException("Empty parameter value detected");
}
} else if (next == ';') {
// End of parameter
parameters.add(Parameter.create(paramNameBuffer,
paramValueBuffer));
paramNameBuffer = new StringBuilder();
readingParamName = true;
readingParamValue = false;
} else if ((next == '"') && (paramValueBuffer.length() == 0)) {
// Parse the quoted string
boolean done = false;
boolean quotedPair = false;
while ((!done) && (next != -1)) {
next = read();
if (quotedPair) {
// End of quoted pair (escape sequence)
if (isText(next)) {
paramValueBuffer.append((char) next);
quotedPair = false;
} else {
throw new IOException(
"Invalid character detected in quoted string. Please check your value");
}
} else if (isDoubleQuote(next)) {
// End of quoted string
done = true;
} else if (next == '\\') {
// Begin of quoted pair (escape sequence)
quotedPair = true;
} else if (isText(next)) {
paramValueBuffer.append((char) next);
} else {
throw new IOException(
"Invalid character detected in quoted string. Please check your value");
}
}
} else if (isTokenChar(next)) {
paramValueBuffer.append((char) next);
} else {
throw new IOException("Unexpected character \""
+ (char) next + "\" detected.");
}
}
}
if (isComma(next)) {
// Unread character which isn't part of the value
unread();
}
return result;
}
|
diff --git a/android/src/com/freshplanet/flurry/functions/analytics/StartSessionFunction.java b/android/src/com/freshplanet/flurry/functions/analytics/StartSessionFunction.java
index 95e4e0f..5a8e71a 100644
--- a/android/src/com/freshplanet/flurry/functions/analytics/StartSessionFunction.java
+++ b/android/src/com/freshplanet/flurry/functions/analytics/StartSessionFunction.java
@@ -1,89 +1,90 @@
//////////////////////////////////////////////////////////////////////////////////////
//
// Copyright 2012 Freshplanet (http://freshplanet.com | [email protected])
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//////////////////////////////////////////////////////////////////////////////////////
package com.freshplanet.flurry.functions.analytics;
import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.util.Log;
import com.adobe.fre.FREContext;
import com.adobe.fre.FREFunction;
import com.adobe.fre.FREObject;
import com.flurry.android.FlurryAgent;
import com.freshplanet.flurry.ExtensionContext;
public class StartSessionFunction implements FREFunction
{
private static String TAG = "Flurry - StartSessionFunction";
@Override
public FREObject call(FREContext arg0, FREObject[] arg1)
{
String apiKey = null;
try
{
apiKey = arg1[0].getAsString();
}
catch (Exception e)
{
e.printStackTrace();
}
if (apiKey != null)
{
// Set Flurry logs
- FlurryAgent.setLogEnabled(true);
+ FlurryAgent.setLogEnabled(false);
FlurryAgent.setLogLevel(Log.DEBUG);
// Start Flurry session and initialize ads
FlurryAgent.onStartSession(arg0.getActivity(), apiKey);
+ FlurryAgent.enableTestAds(false);
FlurryAgent.initializeAds(arg0.getActivity());
FlurryAgent.setAdListener((ExtensionContext)arg0);
Log.d(TAG, "Started session and initalized ads");
// Listen to the user location
LocationManager locationManager = (LocationManager)(arg0.getActivity().getSystemService(Context.LOCATION_SERVICE));
Criteria locationCriteria = new Criteria();
locationCriteria.setAccuracy(Criteria.ACCURACY_COARSE);
String locationProvider = locationManager.getBestProvider(locationCriteria, true);
Location location = locationManager.getLastKnownLocation(locationProvider);
if (location != null)
{
float latitude = (float)location.getLatitude();
float longitude = (float)location.getLongitude();
FlurryAgent.setLocation(latitude, longitude);
Log.d(TAG, "Retrieved user location: ("+latitude+", "+longitude+")");
}
else
{
Log.d(TAG, "Couldn't retrieve user location (locationProvider = " + locationProvider + ")");
}
}
else
{
Log.e(TAG, "API Key is null");
}
return null;
}
}
| false | true | public FREObject call(FREContext arg0, FREObject[] arg1)
{
String apiKey = null;
try
{
apiKey = arg1[0].getAsString();
}
catch (Exception e)
{
e.printStackTrace();
}
if (apiKey != null)
{
// Set Flurry logs
FlurryAgent.setLogEnabled(true);
FlurryAgent.setLogLevel(Log.DEBUG);
// Start Flurry session and initialize ads
FlurryAgent.onStartSession(arg0.getActivity(), apiKey);
FlurryAgent.initializeAds(arg0.getActivity());
FlurryAgent.setAdListener((ExtensionContext)arg0);
Log.d(TAG, "Started session and initalized ads");
// Listen to the user location
LocationManager locationManager = (LocationManager)(arg0.getActivity().getSystemService(Context.LOCATION_SERVICE));
Criteria locationCriteria = new Criteria();
locationCriteria.setAccuracy(Criteria.ACCURACY_COARSE);
String locationProvider = locationManager.getBestProvider(locationCriteria, true);
Location location = locationManager.getLastKnownLocation(locationProvider);
if (location != null)
{
float latitude = (float)location.getLatitude();
float longitude = (float)location.getLongitude();
FlurryAgent.setLocation(latitude, longitude);
Log.d(TAG, "Retrieved user location: ("+latitude+", "+longitude+")");
}
else
{
Log.d(TAG, "Couldn't retrieve user location (locationProvider = " + locationProvider + ")");
}
}
else
{
Log.e(TAG, "API Key is null");
}
return null;
}
| public FREObject call(FREContext arg0, FREObject[] arg1)
{
String apiKey = null;
try
{
apiKey = arg1[0].getAsString();
}
catch (Exception e)
{
e.printStackTrace();
}
if (apiKey != null)
{
// Set Flurry logs
FlurryAgent.setLogEnabled(false);
FlurryAgent.setLogLevel(Log.DEBUG);
// Start Flurry session and initialize ads
FlurryAgent.onStartSession(arg0.getActivity(), apiKey);
FlurryAgent.enableTestAds(false);
FlurryAgent.initializeAds(arg0.getActivity());
FlurryAgent.setAdListener((ExtensionContext)arg0);
Log.d(TAG, "Started session and initalized ads");
// Listen to the user location
LocationManager locationManager = (LocationManager)(arg0.getActivity().getSystemService(Context.LOCATION_SERVICE));
Criteria locationCriteria = new Criteria();
locationCriteria.setAccuracy(Criteria.ACCURACY_COARSE);
String locationProvider = locationManager.getBestProvider(locationCriteria, true);
Location location = locationManager.getLastKnownLocation(locationProvider);
if (location != null)
{
float latitude = (float)location.getLatitude();
float longitude = (float)location.getLongitude();
FlurryAgent.setLocation(latitude, longitude);
Log.d(TAG, "Retrieved user location: ("+latitude+", "+longitude+")");
}
else
{
Log.d(TAG, "Couldn't retrieve user location (locationProvider = " + locationProvider + ")");
}
}
else
{
Log.e(TAG, "API Key is null");
}
return null;
}
|
diff --git a/src/groupone/AddCoupon.java b/src/groupone/AddCoupon.java
index cf8070a..7096941 100644
--- a/src/groupone/AddCoupon.java
+++ b/src/groupone/AddCoupon.java
@@ -1,65 +1,65 @@
package groupone;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* Servlet implementation class AddCoupon
*/
@WebServlet("/AddCoupon")
public class AddCoupon extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public AddCoupon() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
HttpSession userSession = request.getSession(false);
String vendorId = (String) userSession.getAttribute("accountId");
String title = request.getParameter("title").toString();
String month = request.getParameter("month").toString();
String day = request.getParameter("day").toString();
String year = request.getParameter("year").toString();
String date = year + "-" + month + "-" + day;
String quantity = request.getParameter("quantity").toString();
String price = request.getParameter("price").toString();
String category = request.getParameter("category").toString();
if(DBOperation.addCoupon(title, date, quantity, price, category, vendorId))
{
request.setAttribute("couponAdded", "Coupon has been added!");
- request.getRequestDispatcher("/add_coupon.jsp").forward(request, response);
+ request.getRequestDispatcher("/page_addCoupon.jsp").forward(request, response);
}
else
{
request.setAttribute("couponError", "There was An error adding Coupon");
- request.getRequestDispatcher("/add_coupon.jsp").forward(request, response);
+ request.getRequestDispatcher("/page_addCoupon.jsp").forward(request, response);
}
}
}
| false | true | protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
HttpSession userSession = request.getSession(false);
String vendorId = (String) userSession.getAttribute("accountId");
String title = request.getParameter("title").toString();
String month = request.getParameter("month").toString();
String day = request.getParameter("day").toString();
String year = request.getParameter("year").toString();
String date = year + "-" + month + "-" + day;
String quantity = request.getParameter("quantity").toString();
String price = request.getParameter("price").toString();
String category = request.getParameter("category").toString();
if(DBOperation.addCoupon(title, date, quantity, price, category, vendorId))
{
request.setAttribute("couponAdded", "Coupon has been added!");
request.getRequestDispatcher("/add_coupon.jsp").forward(request, response);
}
else
{
request.setAttribute("couponError", "There was An error adding Coupon");
request.getRequestDispatcher("/add_coupon.jsp").forward(request, response);
}
}
| protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
HttpSession userSession = request.getSession(false);
String vendorId = (String) userSession.getAttribute("accountId");
String title = request.getParameter("title").toString();
String month = request.getParameter("month").toString();
String day = request.getParameter("day").toString();
String year = request.getParameter("year").toString();
String date = year + "-" + month + "-" + day;
String quantity = request.getParameter("quantity").toString();
String price = request.getParameter("price").toString();
String category = request.getParameter("category").toString();
if(DBOperation.addCoupon(title, date, quantity, price, category, vendorId))
{
request.setAttribute("couponAdded", "Coupon has been added!");
request.getRequestDispatcher("/page_addCoupon.jsp").forward(request, response);
}
else
{
request.setAttribute("couponError", "There was An error adding Coupon");
request.getRequestDispatcher("/page_addCoupon.jsp").forward(request, response);
}
}
|
diff --git a/src/com/ichi2/anki/Feedback.java b/src/com/ichi2/anki/Feedback.java
index 5e650571..5b33c462 100644
--- a/src/com/ichi2/anki/Feedback.java
+++ b/src/com/ichi2/anki/Feedback.java
@@ -1,567 +1,567 @@
/***************************************************************************************
* 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 com.ichi2.anki;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Application;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import com.ichi2.async.Connection;
import com.ichi2.async.Connection.Payload;
import com.tomgibara.android.veecheck.util.PrefSettings;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;
import java.util.UUID;
public class Feedback extends Activity {
protected static String REPORT_ASK = "2";
protected static String REPORT_NEVER = "1";
protected static String REPORT_ALWAYS = "0";
public static String STATE_WAITING = "0";
public static String STATE_UPLOADING = "1";
public static String STATE_SUCCESSFUL = "2";
public static String STATE_FAILED = "3";
public static String TYPE_STACKTRACE = "crash-stacktrace";
public static String TYPE_FEEDBACK = "feedback";
public static String TYPE_ERROR_FEEDBACK = "error-feedback";
public static String TYPE_OTHER_ERROR = "other-error";
protected static SimpleDateFormat df1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS", Locale.US);
protected static SimpleDateFormat df2 = new SimpleDateFormat("Z", Locale.US);
protected static TimeZone localTz = TimeZone.getDefault();
// This is used to group the batch of bugs and notes sent on the server side
protected long mNonce;
protected List<HashMap<String, String>> mErrorReports;
protected SimpleAdapter mErrorAdapter;
protected ListView mLvErrorList;
protected EditText mEtFeedbackText;
protected boolean mPostingFeedback;
protected InputMethodManager mImm = null;
protected AlertDialog mNoConnectionAlert = null;
protected String mReportErrorMode;
protected String mFeedbackUrl;
protected String mErrorUrl;
@Override
public void onBackPressed() {
deleteFiles(true, false);
setResult(RESULT_OK);
finish();
}
/**
* Create AlertDialogs used on all the activity
*/
private void initAllAlertDialogs() {
Resources res = getResources();
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(res.getString(R.string.connection_error_title));
builder.setIcon(android.R.drawable.ic_dialog_alert);
builder.setMessage(res.getString(R.string.connection_needed));
builder.setPositiveButton(res.getString(R.string.ok), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
mPostingFeedback = false;
refreshInterface();
}
});
mNoConnectionAlert = builder.create();
}
private void refreshInterface() {
if (mReportErrorMode.equals(REPORT_ASK)) {
Resources res = getResources();
Button btnSend = (Button) findViewById(R.id.btnFeedbackSend);
Button btnKeepLatest = (Button) findViewById(R.id.btnFeedbackKeepLatest);
Button btnClearAll = (Button) findViewById(R.id.btnFeedbackClearAll);
ProgressBar pbSpinner = (ProgressBar) findViewById(R.id.pbFeedbackSpinner);
int numErrors = mErrorReports.size();
if (numErrors == 0) {
mLvErrorList.setVisibility(View.GONE);
btnKeepLatest.setVisibility(View.GONE);
btnClearAll.setVisibility(View.GONE);
btnSend.setText(res.getString(R.string.feedback_send_feedback));
} else {
mLvErrorList.setVisibility(View.VISIBLE);
btnKeepLatest.setVisibility(View.VISIBLE);
btnClearAll.setVisibility(View.VISIBLE);
btnSend.setText(res.getString(R.string.feedback_send_feedback_and_errors));
refreshErrorListView();
if (numErrors == 1) {
btnKeepLatest.setEnabled(false);
} else {
btnKeepLatest.setEnabled(true);
}
}
if (mPostingFeedback) {
int buttonHeight = btnSend.getHeight();
btnSend.setVisibility(View.GONE);
pbSpinner.setVisibility(View.VISIBLE);
LinearLayout topLine = (LinearLayout) findViewById(R.id.llFeedbackTopLine);
topLine.setMinimumHeight(buttonHeight);
mEtFeedbackText.setEnabled(false);
mImm.hideSoftInputFromWindow(mEtFeedbackText.getWindowToken(), 0);
} else {
btnSend.setVisibility(View.VISIBLE);
pbSpinner.setVisibility(View.GONE);
mEtFeedbackText.setEnabled(true);
}
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Resources res = getResources();
Context context = getBaseContext();
SharedPreferences sharedPreferences = PrefSettings.getSharedPrefs(context);
mReportErrorMode = sharedPreferences.getString("reportErrorMode", REPORT_ASK);
mNonce = UUID.randomUUID().getMostSignificantBits();
mFeedbackUrl = res.getString(R.string.feedback_post_url);
mErrorUrl = res.getString(R.string.error_post_url);
mImm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
mPostingFeedback = false;
initAllAlertDialogs();
getErrorFiles();
if (mReportErrorMode.equals(REPORT_ALWAYS)) { // Always report
try {
String feedback = "Automatically sent";
Connection.sendFeedback(mSendListener, new Payload(new Object[] {
mFeedbackUrl, mErrorUrl, feedback, mErrorReports, mNonce, getApplication()}));
if (mErrorReports.size() > 0) {
mPostingFeedback = true;
}
if (feedback.length() > 0) {
mPostingFeedback = true;
}
} catch (Exception e) {
Log.e(AnkiDroidApp.TAG, e.toString());
}
deleteFiles(true, false);
setResult(RESULT_OK);
finish();
return;
} else if (mReportErrorMode.equals(REPORT_NEVER)) { // Never report
deleteFiles(false, false);
- //setResult(RESULT_OK);
- //finish();
+ setResult(RESULT_OK);
+ finish();
}
setContentView(R.layout.feedback);
Button btnSend = (Button) findViewById(R.id.btnFeedbackSend);
Button btnKeepLatest = (Button) findViewById(R.id.btnFeedbackKeepLatest);
Button btnClearAll = (Button) findViewById(R.id.btnFeedbackClearAll);
mEtFeedbackText = (EditText) findViewById(R.id.etFeedbackText);
mLvErrorList = (ListView) findViewById(R.id.lvFeedbackErrorList);
mErrorAdapter = new SimpleAdapter(this, mErrorReports,
R.layout.error_item, new String[] {"name", "state", "result"}, new int[] {
R.id.error_item_text, R.id.error_item_progress, R.id.error_item_status});
mErrorAdapter.setViewBinder(new SimpleAdapter.ViewBinder() {
@Override
public boolean setViewValue(View view, Object arg1, String text) {
switch(view.getId()) {
case R.id.error_item_progress:
if (text.equals(STATE_UPLOADING)) {
view.setVisibility(View.VISIBLE);
} else {
view.setVisibility(View.GONE);
}
return true;
case R.id.error_item_status:
if (text.length() == 0) {
view.setVisibility(View.GONE);
return true;
} else {
view.setVisibility(View.VISIBLE);
return false;
}
}
return false;
}
});
btnClearAll.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
deleteFiles(false, false);
refreshErrorListView();
refreshInterface();
}
});
mLvErrorList.setAdapter(mErrorAdapter);
btnSend.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (!mPostingFeedback) {
String feedback = mEtFeedbackText.getText().toString();
Connection.sendFeedback(mSendListener, new Payload(new Object[] {
mFeedbackUrl, mErrorUrl, feedback, mErrorReports, mNonce, getApplication()}));
if (mErrorReports.size() > 0) {
mPostingFeedback = true;
}
if (feedback.length() > 0) {
mPostingFeedback = true;
}
refreshInterface();
}
}
});
btnKeepLatest.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
deleteFiles(false, true);
refreshErrorListView();
refreshInterface();
}
});
refreshInterface();
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN |
WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
}
private void refreshErrorListView() {
if (mReportErrorMode.equals(REPORT_ASK)) {
mErrorAdapter.notifyDataSetChanged();
}
}
private void getErrorFiles() {
mErrorReports = new ArrayList<HashMap<String, String>>();
String[] errors = fileList();
for (String file : errors) {
if (file.endsWith(".stacktrace")) {
HashMap<String, String> error = new HashMap<String, String>();
error.put("filename", file);
error.put("name", file);
error.put("state", STATE_WAITING);
error.put("result", "");
mErrorReports.add(error);
}
}
}
/**
* Delete the crash log files.
* @param onlyProcessed only delete the log files that have been sent.
* @param keepLatest keep the latest log file. If the file has not been sent yet, it is
* not deleted even if this value is set to false.
*/
private void deleteFiles(boolean onlyProcessed, boolean keepLatest) {
for (int i = (keepLatest? 1: 0); i < mErrorReports.size(); ) {
try {
String errorState = mErrorReports.get(i).get("state");
if (!onlyProcessed || errorState.equals(STATE_SUCCESSFUL)) {
deleteFile(mErrorReports.get(i).get("filename"));
mErrorReports.remove(i);
} else {
i++;
}
} catch (Exception e) {
Log.e(AnkiDroidApp.TAG, String.format("Could not delete file: %s", mErrorReports.get(i)));
}
}
}
public static boolean isErrorType(String postType) {
return !(postType.equals(TYPE_FEEDBACK) || postType.equals(TYPE_ERROR_FEEDBACK));
}
Connection.TaskListener mSendListener = new Connection.TaskListener() {
@Override
public void onDisconnected() {
if (mNoConnectionAlert != null) {
mNoConnectionAlert.show();
}
}
@Override
public void onPostExecute(Payload data) {
mPostingFeedback = false;
deleteFiles(true, false);
refreshInterface();
}
@Override
public void onPreExecute() {
// pass
}
@Override
public void onProgressUpdate(Object... values) {
Resources res = getResources();
String postType = (String)values[0];
int errorIndex = (Integer)values[1];
String state = (String)values[2];
if (isErrorType(postType)) {
mErrorReports.get(errorIndex).put("state", state);
if (!state.equals(Feedback.STATE_UPLOADING)) {
int returnCode = (Integer)values[3];
if (returnCode == 200) {
// The result is either: "new" (for first encountered bug), "known" (for existing bugs) or
// ("issue:xxx:<status>" for known and linked)
String result = (String)values[4];
if (result.equalsIgnoreCase("new")) {
mErrorReports.get(errorIndex).put("name", res.getString(R.string.feedback_error_reply_new));
} else if (result.equalsIgnoreCase("known")) {
mErrorReports.get(errorIndex).put("name", res.getString(R.string.feedback_error_reply_known));
} else if (result.startsWith("issue:")) {
String[] resultPieces = result.split(":");
int issue = Integer.parseInt(resultPieces[1]);
String status = "";
if (resultPieces.length > 1) {
if (resultPieces.length > 2) {
status = resultPieces[2];
}
if (status.length() == 0) {
mErrorReports.get(errorIndex).put("name",
res.getString(R.string.feedback_error_reply_issue_unknown, issue));
} else if (status.equalsIgnoreCase("fixed")) {
mErrorReports.get(errorIndex).put("name",
res.getString(R.string.feedback_error_reply_issue_fixed_prod, issue));
} else if (status.equalsIgnoreCase("fixedindev")) {
mErrorReports.get(errorIndex).put("name",
res.getString(R.string.feedback_error_reply_issue_fixed_dev, issue));
} else {
mErrorReports.get(errorIndex).put("name",
res.getString(R.string.feedback_error_reply_issue_status, issue, status));
}
} else {
mErrorReports.get(errorIndex).put("result",
res.getString(R.string.feedback_error_reply_malformed));
}
} else {
mErrorReports.get(errorIndex).put("result",
res.getString(R.string.feedback_error_reply_malformed));
}
} else {
mErrorReports.get(errorIndex).put("result", res.getString(R.string.feedback_error_reply_failed));
}
}
refreshErrorListView();
} else {
if (mReportErrorMode.equals(REPORT_ASK)) {
if (state.equals(STATE_SUCCESSFUL)) {
mEtFeedbackText.setText("");
Toast.makeText(Feedback.this,
res.getString(R.string.feedback_message_sent_success), Toast.LENGTH_LONG).show();
} else if (state.equals(STATE_FAILED)) {
int respCode = (Integer)values[3];
if (respCode == 0) {
onDisconnected();
} else {
Toast.makeText(Feedback.this, res.getString(R.string.feedback_message_sent_failure, respCode),
Toast.LENGTH_LONG).show();
}
}
}
}
}
};
// Run in AsyncTask
private static void addTimestamp(List<NameValuePair> pairs) {
Date ts = new Date();
df1.setTimeZone(TimeZone.getTimeZone("UTC"));
String reportsentutc = String.format("%s", df1.format(ts));
String reportsenttzoffset = String.format("%s", df2.format(ts));
String reportsenttz = String.format("%s", localTz.getID());
pairs.add(new BasicNameValuePair("reportsentutc", reportsentutc));
pairs.add(new BasicNameValuePair("reportsenttzoffset", reportsenttzoffset));
pairs.add(new BasicNameValuePair("reportsenttz", reportsenttz));
}
private static List<NameValuePair> extractPairsFromError(String type, String errorFile, String groupId, int index, Application app) {
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("type", "crash-stacktrace"));
pairs.add(new BasicNameValuePair("groupid", groupId));
pairs.add(new BasicNameValuePair("index", String.valueOf(index)));
addTimestamp(pairs);
String singleLine = null;
try {
BufferedReader br = new BufferedReader(new InputStreamReader(app.openFileInput(errorFile)));
while((singleLine = br.readLine()) != null) {
int indexOfEquals = singleLine.indexOf('=');
if(indexOfEquals==-1)
continue;
String key = singleLine.substring(0, indexOfEquals).toLowerCase();
String value = singleLine.substring(indexOfEquals+1,singleLine.length());
if(key.equals("stacktrace")) {
StringBuilder sb = new StringBuilder(value);
while((singleLine = br.readLine()) != null) {
sb.append(singleLine);
sb.append("\n");
}
value = sb.toString();
}
pairs.add(new BasicNameValuePair(key, value));
}
br.close();
} catch (FileNotFoundException e) {
Log.w(AnkiDroidApp.TAG, "Couldn't open crash report " + errorFile);
return null;
} catch (IOException e) {
Log.w(AnkiDroidApp.TAG, "Couldn't read crash report " + errorFile);
return null;
}
return pairs;
}
/**
* Posting feedback or error info to the server.
* This is called from the AsyncTask.
* @param url The url to post the feedback to.
* @param type The type of the info, eg Feedback.TYPE_CRASH_STACKTRACE.
* @param feedback For feedback types this is the message. For error/crash types this is the path to the error file.
* @param groupId A single time generated ID, so that errors/feedback send together can be grouped together.
* @param index The index of the error in the list
* @return A Payload file showing success, response code and response message.
*/
public static Payload postFeedback(String url, String type, String feedback, String groupId, int index, Application app) {
Payload result = new Payload(null);
List<NameValuePair> pairs = null;
if (!isErrorType(type)) {
pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("type", type));
pairs.add(new BasicNameValuePair("groupid", groupId));
pairs.add(new BasicNameValuePair("index", "0"));
pairs.add(new BasicNameValuePair("message", feedback));
addTimestamp(pairs);
} else {
pairs = Feedback.extractPairsFromError(type, feedback, groupId, index, app);
if (pairs == null) {
result.success = false;
result.result = null;
}
}
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.addHeader("User-Agent", "AnkiDroid");
try {
httpPost.setEntity(new UrlEncodedFormEntity(pairs));
HttpResponse response = httpClient.execute(httpPost);
Log.e(AnkiDroidApp.TAG, String.format("Bug report posted to %s", url));
int respCode = response.getStatusLine().getStatusCode();
switch(respCode) {
case 200:
result.success = true;
result.returnType = respCode;
result.result = Utils.convertStreamToString(response.getEntity().getContent());
Log.i(AnkiDroidApp.TAG, String.format("postFeedback OK: %s", result.result));
break;
default:
Log.e(AnkiDroidApp.TAG, String.format("postFeedback failure: %d - %s",
response.getStatusLine().getStatusCode(),
response.getStatusLine().getReasonPhrase()));
result.success = false;
result.returnType = respCode;
result.result = response.getStatusLine().getReasonPhrase();
break;
}
} catch (ClientProtocolException ex) {
Log.e(AnkiDroidApp.TAG, "ClientProtocolException: " + ex.toString());
result.success = false;
result.result = ex.toString();
} catch (IOException ex) {
Log.e(AnkiDroidApp.TAG, "IOException: " + ex.toString());
result.success = false;
result.result = ex.toString();
}
return result;
}
}
| true | true | protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Resources res = getResources();
Context context = getBaseContext();
SharedPreferences sharedPreferences = PrefSettings.getSharedPrefs(context);
mReportErrorMode = sharedPreferences.getString("reportErrorMode", REPORT_ASK);
mNonce = UUID.randomUUID().getMostSignificantBits();
mFeedbackUrl = res.getString(R.string.feedback_post_url);
mErrorUrl = res.getString(R.string.error_post_url);
mImm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
mPostingFeedback = false;
initAllAlertDialogs();
getErrorFiles();
if (mReportErrorMode.equals(REPORT_ALWAYS)) { // Always report
try {
String feedback = "Automatically sent";
Connection.sendFeedback(mSendListener, new Payload(new Object[] {
mFeedbackUrl, mErrorUrl, feedback, mErrorReports, mNonce, getApplication()}));
if (mErrorReports.size() > 0) {
mPostingFeedback = true;
}
if (feedback.length() > 0) {
mPostingFeedback = true;
}
} catch (Exception e) {
Log.e(AnkiDroidApp.TAG, e.toString());
}
deleteFiles(true, false);
setResult(RESULT_OK);
finish();
return;
} else if (mReportErrorMode.equals(REPORT_NEVER)) { // Never report
deleteFiles(false, false);
//setResult(RESULT_OK);
//finish();
}
setContentView(R.layout.feedback);
Button btnSend = (Button) findViewById(R.id.btnFeedbackSend);
Button btnKeepLatest = (Button) findViewById(R.id.btnFeedbackKeepLatest);
Button btnClearAll = (Button) findViewById(R.id.btnFeedbackClearAll);
mEtFeedbackText = (EditText) findViewById(R.id.etFeedbackText);
mLvErrorList = (ListView) findViewById(R.id.lvFeedbackErrorList);
mErrorAdapter = new SimpleAdapter(this, mErrorReports,
R.layout.error_item, new String[] {"name", "state", "result"}, new int[] {
R.id.error_item_text, R.id.error_item_progress, R.id.error_item_status});
mErrorAdapter.setViewBinder(new SimpleAdapter.ViewBinder() {
@Override
public boolean setViewValue(View view, Object arg1, String text) {
switch(view.getId()) {
case R.id.error_item_progress:
if (text.equals(STATE_UPLOADING)) {
view.setVisibility(View.VISIBLE);
} else {
view.setVisibility(View.GONE);
}
return true;
case R.id.error_item_status:
if (text.length() == 0) {
view.setVisibility(View.GONE);
return true;
} else {
view.setVisibility(View.VISIBLE);
return false;
}
}
return false;
}
});
btnClearAll.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
deleteFiles(false, false);
refreshErrorListView();
refreshInterface();
}
});
mLvErrorList.setAdapter(mErrorAdapter);
btnSend.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (!mPostingFeedback) {
String feedback = mEtFeedbackText.getText().toString();
Connection.sendFeedback(mSendListener, new Payload(new Object[] {
mFeedbackUrl, mErrorUrl, feedback, mErrorReports, mNonce, getApplication()}));
if (mErrorReports.size() > 0) {
mPostingFeedback = true;
}
if (feedback.length() > 0) {
mPostingFeedback = true;
}
refreshInterface();
}
}
});
btnKeepLatest.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
deleteFiles(false, true);
refreshErrorListView();
refreshInterface();
}
});
refreshInterface();
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN |
WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
}
| protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Resources res = getResources();
Context context = getBaseContext();
SharedPreferences sharedPreferences = PrefSettings.getSharedPrefs(context);
mReportErrorMode = sharedPreferences.getString("reportErrorMode", REPORT_ASK);
mNonce = UUID.randomUUID().getMostSignificantBits();
mFeedbackUrl = res.getString(R.string.feedback_post_url);
mErrorUrl = res.getString(R.string.error_post_url);
mImm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
mPostingFeedback = false;
initAllAlertDialogs();
getErrorFiles();
if (mReportErrorMode.equals(REPORT_ALWAYS)) { // Always report
try {
String feedback = "Automatically sent";
Connection.sendFeedback(mSendListener, new Payload(new Object[] {
mFeedbackUrl, mErrorUrl, feedback, mErrorReports, mNonce, getApplication()}));
if (mErrorReports.size() > 0) {
mPostingFeedback = true;
}
if (feedback.length() > 0) {
mPostingFeedback = true;
}
} catch (Exception e) {
Log.e(AnkiDroidApp.TAG, e.toString());
}
deleteFiles(true, false);
setResult(RESULT_OK);
finish();
return;
} else if (mReportErrorMode.equals(REPORT_NEVER)) { // Never report
deleteFiles(false, false);
setResult(RESULT_OK);
finish();
}
setContentView(R.layout.feedback);
Button btnSend = (Button) findViewById(R.id.btnFeedbackSend);
Button btnKeepLatest = (Button) findViewById(R.id.btnFeedbackKeepLatest);
Button btnClearAll = (Button) findViewById(R.id.btnFeedbackClearAll);
mEtFeedbackText = (EditText) findViewById(R.id.etFeedbackText);
mLvErrorList = (ListView) findViewById(R.id.lvFeedbackErrorList);
mErrorAdapter = new SimpleAdapter(this, mErrorReports,
R.layout.error_item, new String[] {"name", "state", "result"}, new int[] {
R.id.error_item_text, R.id.error_item_progress, R.id.error_item_status});
mErrorAdapter.setViewBinder(new SimpleAdapter.ViewBinder() {
@Override
public boolean setViewValue(View view, Object arg1, String text) {
switch(view.getId()) {
case R.id.error_item_progress:
if (text.equals(STATE_UPLOADING)) {
view.setVisibility(View.VISIBLE);
} else {
view.setVisibility(View.GONE);
}
return true;
case R.id.error_item_status:
if (text.length() == 0) {
view.setVisibility(View.GONE);
return true;
} else {
view.setVisibility(View.VISIBLE);
return false;
}
}
return false;
}
});
btnClearAll.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
deleteFiles(false, false);
refreshErrorListView();
refreshInterface();
}
});
mLvErrorList.setAdapter(mErrorAdapter);
btnSend.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (!mPostingFeedback) {
String feedback = mEtFeedbackText.getText().toString();
Connection.sendFeedback(mSendListener, new Payload(new Object[] {
mFeedbackUrl, mErrorUrl, feedback, mErrorReports, mNonce, getApplication()}));
if (mErrorReports.size() > 0) {
mPostingFeedback = true;
}
if (feedback.length() > 0) {
mPostingFeedback = true;
}
refreshInterface();
}
}
});
btnKeepLatest.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
deleteFiles(false, true);
refreshErrorListView();
refreshInterface();
}
});
refreshInterface();
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN |
WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
}
|
diff --git a/src/DiskSpaceInformer.java b/src/DiskSpaceInformer.java
index a19f287..f88a73d 100644
--- a/src/DiskSpaceInformer.java
+++ b/src/DiskSpaceInformer.java
@@ -1,538 +1,538 @@
import javax.swing.*;
import javax.swing.event.TreeModelListener;
import javax.swing.tree.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.io.FileFilter;
import java.text.DecimalFormat;
import java.util.*;
/*
* DiskSpaceInformer.java
*/
public class DiskSpaceInformer extends JPanel
implements ActionListener, PropertyChangeListener {
static private final String newline = "\n";
private static String version = "Disk Space Informer v0.1d";
private final JButton checkButton;
JButton openButton, summaryButton, clearButton;
JTextArea log;
JFileChooser fileChooser;
JProgressBar jProgressBar;
JTree tree;
JScrollPane treeScrollPane;
private FindFileAndFolderSizes task;
private ProgressMonitor progressMonitor;
private File selection;
//private static float progress = 0.0f;
private long folderSize = 0;
class FindFileAndFolderSizes extends SwingWorker<Void, Void> {
private File file;
private boolean summary = false;
FindFileAndFolderSizes(File file, boolean summary) {
this(file);
this.summary = summary;
}
FindFileAndFolderSizes(File file) {
this.file = file;
}
@Override
public Void doInBackground() {
if (file.isFile()) {
prettyPrint(file);
return null;
}
Map<String, Long> listing = new HashMap<String, Long>();
jProgressBar.setString("Determining files to scan");
jProgressBar.setStringPainted(true);
jProgressBar.setVisible(true);
jProgressBar.setIndeterminate(true);
int count = file.list().length;
float increment = 0.0f;
if (count != 0) {
increment = 100.0f / count;
}
float progress = 0.0f;
setProgress(0);
long totalSize = 0L;
for (File file : this.file.listFiles(new IgnoreFilter())) {
if (file.isFile()) {
progress += increment;
//log.append("progress: " + progress);
setProgress(Math.min((int) Math.round(progress), 100));
long size = file.length();
totalSize += size;
listing.put(file.getName(), size);
} else {
folderSize = 0;
progress += increment;
//log.append("progress: " + progress);
setProgress(Math.min((int) Math.round(progress), 100));
getFolderSize(file);
totalSize += folderSize;
listing.put(file.getName(), folderSize);
}
}
jProgressBar.setString("Sorting Listing...");
ValueComparator vc = new ValueComparator(listing);
Map<String, Long> sortedMap = new TreeMap<String, Long>(vc);
sortedMap.putAll(listing);
jProgressBar.setIndeterminate(false);
if (summary) {
int lastDoc = log.getDocument().getLength();
prettyPrint(file, totalSize);
log.setCaretPosition(lastDoc);
} else {
int lastDoc = log.getDocument().getLength();
prettyPrint(file, totalSize, sortedMap);
log.setCaretPosition(lastDoc);
}
return null;
}
private long getFolderSize(File file) {
if (file.isFile()) {
folderSize += file.length();
} else {
//log.append("\nProcessing size: " + file);
String[] contents = file.list();
if (contents != null) { //take care of empty folders
for (File f : file.listFiles(new IgnoreFilter())) {
jProgressBar.setString(file.toString());
getFolderSize(f);
}
}
}
return folderSize;
}
@Override
public void done() {
Toolkit.getDefaultToolkit().beep();
progressMonitor.close();
}
}
/**
* The methods in this class allow the JTree component to traverse
* the file system tree and display the files and directories.
*/
class FileTreeModel implements TreeModel {
// We specify the root directory when we create the model.
protected File root;
public FileTreeModel(File root) {
this.root = root;
}
// The model knows how to return the root object of the tree
public Object getRoot() {
return root;
}
// Tell JTree whether an object in the tree is a leaf
public boolean isLeaf(Object node) {
return ((File) node).isFile();
}
// Tell JTree how many children a node has
public int getChildCount(Object parent) {
String[] children = ((File) parent).list();
if (children == null) return 0;
return children.length;
}
// Fetch any numbered child of a node for the JTree.
// Our model returns File objects for all nodes in the tree. The
// JTree displays these by calling the File.toString() method.
public Object getChild(Object parent, int index) {
String[] children = ((File) parent).list();
if ((children == null) || (index >= children.length)) return null;
return new File((File) parent, children[index]);
}
// Figure out a child's position in its parent node.
public int getIndexOfChild(Object parent, Object child) {
String[] children = ((File) parent).list();
if (children == null) return -1;
String childname = ((File) child).getName();
for (int i = 0; i < children.length; i++) {
if (childname.equals(children[i])) return i;
}
return -1;
}
// This method is invoked by the JTree only for editable trees.
// This TreeModel does not allow editing, so we do not implement
// this method. The JTree editable property is false by default.
public void valueForPathChanged(TreePath path, Object newvalue) {
}
// Since this is not an editable tree model, we never fire any events,
// so we don't actually have to keep track of interested listeners
public void addTreeModelListener(TreeModelListener l) {
}
public void removeTreeModelListener(TreeModelListener l) {
}
}
class DirectoryFilter implements FileFilter {
public boolean accept(File file) {
if (file.isDirectory()) {
return true; //To change body of implemented methods use File | Settings | File Templates.
}
return false;
}
}
class LeftClickMouseListener extends MouseAdapter {
@Override
public void mouseClicked(MouseEvent e) {
if (SwingUtilities.isLeftMouseButton(e)) {
if (e.getClickCount() == 2) {
int rowLocation = tree.getRowForLocation(e.getX(), e.getY());
File lastPathComponent = (File) tree.getPathForRow(rowLocation).getLastPathComponent();
if (lastPathComponent.isFile()) {
task = new FindFileAndFolderSizes(lastPathComponent);
task.addPropertyChangeListener(DiskSpaceInformer.this);
task.execute();
}
}
}
}
}
;
class RightClickMouseListener extends MouseAdapter {
@Override
public void mouseClicked(MouseEvent e) {
JTree tree;
if (SwingUtilities.isRightMouseButton(e)) {
tree = (JTree) e.getSource();
TreePath path = tree.getPathForLocation(e.getX(), e.getY());
Rectangle pathBounds = tree.getUI().getPathBounds(tree, path);
if (pathBounds != null && pathBounds.contains(e.getX(), e.getY())) {
JPopupMenu menu = new JPopupMenu();
JMenuItem jMenuItem = new JMenuItem("check space");
jMenuItem.addActionListener(new MenuActionListener());
menu.add(jMenuItem);
menu.show(tree, pathBounds.x, pathBounds.y + pathBounds.height);
}
}
}
}
;
class MenuActionListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
Object selection = tree.getLastSelectedPathComponent();
if (selection.equals("listings:")) return;
progressMonitor = new ProgressMonitor(DiskSpaceInformer.this,
"Getting Folder sizes",
"", 0, 100);
progressMonitor.setProgress(0);
TreePath[] selectionPaths = tree.getSelectionPaths();
for (TreePath path : selectionPaths) {
FindFileAndFolderSizes task;
if (selectionPaths.length > 1) { //more than one thing
boolean summary = true;
task = new FindFileAndFolderSizes((File) path.getLastPathComponent(), summary);
} else {
task = new FindFileAndFolderSizes((File) path.getLastPathComponent());
}
task.addPropertyChangeListener(DiskSpaceInformer.this);
task.execute();
}
//log.setCaretPosition(log.getDocument().getLength());
//tree.repaint();
}
}
;
public static final class OsUtils {
private static String OS = null;
public static String getOsName() {
if (OS == null) {
OS = System.getProperty("os.name");
}
return OS;
}
public static boolean isWindows() {
return getOsName().startsWith("Windows");
}
public static boolean isUnix() {
return false;
} // and so on
}
public DiskSpaceInformer() {
super(new BorderLayout());
log = new JTextArea(30, 40);
log.setMargin(new Insets(5, 5, 5, 5));
log.setEditable(false);
log.append("- Select drive or folder: click [Choose Folder]"+newline +newline);
log.append("- Space usage: right click tree item & Check Space"+newline);
log.append("- Alternative: select tree item & click [Check Space]"+newline+newline);
- log.append("- Multiple items: select multiple items [Check Space]"+newline);
- log.append("- Alternative: select multiple items right click]"+newline+newline);
+ log.append("- Multiple items: select multiple items right click"+newline);
+ log.append("- Alternative: select multiple items [Check Space]"+newline+newline);
log.append("- All drives: overview of system [Storage Info]"+newline+newline);
log.append("- Clear screen: overview of system [Storage Info]"+newline);
JScrollPane logScrollPane = new JScrollPane(log);
logScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
logScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
//Create a file chooser
String os = System.getProperty("os.name");
fileChooser = new JFileChooser();
fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
//fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
openButton = new JButton("Choose Folder");
openButton.addActionListener(this);
checkButton = new JButton("Check Space");
checkButton.addActionListener(this);
summaryButton = new JButton("Storage Info");
summaryButton.addActionListener(this);
clearButton = new JButton("Clear Log...");
clearButton.addActionListener(this);
//flow layout
JPanel buttonPanel = new JPanel();
buttonPanel.add(openButton);
buttonPanel.add(checkButton);
buttonPanel.add(summaryButton);
buttonPanel.add(clearButton);
jProgressBar = new JProgressBar();
JPanel progressPanel = new JPanel();
// progressPanel.setMinimumSize(new Dimension(200, 200));
progressPanel.add(jProgressBar);
// Create a TreeModel object to represent our tree of files
// File root = new File(System.getProperty("user.home"));
File root;
if (OsUtils.isWindows()) {
root = new File("c:\\");
} else {
root = new File("/");
}
FileTreeModel model = new FileTreeModel(root);
// Create a JTree and tell it to display our model
tree = new JTree();
tree.setModel(model);
tree.addMouseListener(new LeftClickMouseListener());
tree.addMouseListener(new RightClickMouseListener());
// The JTree can get big, so allow it to scroll
treeScrollPane = new JScrollPane(tree);
JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,
treeScrollPane, logScrollPane);
splitPane.setOneTouchExpandable(true);
splitPane.setDividerLocation(250);
//Provide minimum sizes for the two components in the split pane
// Dimension minimumSize = new Dimension(30, 70);
// treeScrollPane.setMinimumSize(minimumSize);
// logScrollPane.setMinimumSize(minimumSize);
//Add bits to the panel.
add(buttonPanel, BorderLayout.NORTH);
add(splitPane, BorderLayout.CENTER);
add(progressPanel, BorderLayout.SOUTH);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == openButton) { //open
int returnVal = fileChooser.showOpenDialog(DiskSpaceInformer.this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File dir = fileChooser.getSelectedFile();
// Create a JTree and tell it to display our model
tree = new JTree();
tree.setModel(new FileTreeModel(dir));
tree.addMouseListener(new RightClickMouseListener());
// The JTree can get big, so allow it to scroll
treeScrollPane.setViewportView(tree);
} else {
log.append("Open command cancelled by user." + newline);
}
} else if (e.getSource() == checkButton) {
//log.append(checkSpaceAvailable()); //check
progressMonitor = new ProgressMonitor(DiskSpaceInformer.this,
"Getting Folder sizes",
"", 0, 100);
progressMonitor.setProgress(0);
TreePath[] selectionPaths = tree.getSelectionPaths();
if (null == selectionPaths) { //more than one thing
log.append(newline +"Error: Please select a file or folder in the tree"+ newline);
}
for (TreePath path : selectionPaths) {
if (selectionPaths.length > 1) { //more than one thing
boolean summary = true;
task = new FindFileAndFolderSizes((File) path.getLastPathComponent(), summary);
} else {
task = new FindFileAndFolderSizes((File) path.getLastPathComponent());
}
task.addPropertyChangeListener(this);
task.execute();
}
// log.setCaretPosition(log.getDocument().getLength());
} else if (e.getSource() == summaryButton) {
log.append(checkSpaceAvailable()); //check
log.setCaretPosition(log.getDocument().getLength());
} else if (e.getSource() == clearButton) {
log.setText(""); //clear
}
}
private String checkSpaceAvailable() {
StringBuffer sb = new StringBuffer();
File[] roots = File.listRoots();
for (File root : roots) {
long totalSpace = root.getTotalSpace();
long freeSpace = root.getFreeSpace();
long usedSpace = totalSpace - freeSpace;
String title = "Checking: [ " + root + " ]";
String underline = String.format(String.format("%%0%dd", title.length()), 0).replace("0", "=");
sb.append(underline + "\n" + title + "\n" + underline);
sb.append(String.format("\nTotal Space is: [%s]\nUsed space is: [%s] \nFree space is: [%s] \n\n",
readableFileSize(totalSpace),
readableFileSize(usedSpace),
readableFileSize(freeSpace))
);
}
return sb.toString();
}
@Override
public void propertyChange(PropertyChangeEvent evt) {
if ("progress" == evt.getPropertyName()) {
int progress = (Integer) evt.getNewValue();
progressMonitor.setProgress(progress);
String message =
String.format("Completed %d%%.\n", progress);
progressMonitor.setNote(message);
//log.append(message); // see it print increments
if (progressMonitor.isCanceled() || task.isDone()) {
Toolkit.getDefaultToolkit().beep();
if (progressMonitor.isCanceled()) {
jProgressBar.setString("Task cancelled");
log.append("Task canceled.\n");
task.cancel(true);
} else {
jProgressBar.setString("Task completed");
// log.append("Task completed.\n");
}
}
}
}
private void prettyPrint(File file, long total, Map<String, Long> sortedFileFolderSizes) {
String title = file.getName() + ": [" + readableFileSize(total) + "]";
String underline = String.format(String.format("%%0%dd", title.length()), 0).replace("0", "=");
log.append(underline + newline);
log.append(title + newline);
log.append(underline + newline);
for (Map.Entry<String, Long> entry : sortedFileFolderSizes.entrySet()) {
log.append("[ " + readableFileSize(entry.getValue()) + " ]");
log.append(" --> " + entry.getKey() + "\n");
}
log.append(newline);
}
private void prettyPrint(File file, long total) {
String s = String.format("%s: [%s]\n", file.getName(), readableFileSize(total));
log.append(s);
}
private void prettyPrint(File file) {
String s = String.format("%s: [%s]\n", file.getName(), readableFileSize(file.length()));
log.append(s);
}
public static String readableFileSize(long size) {
if (size <= 0) return "0";
final String[] units = new String[]{"B", "KB", "MB", "GB", "TB"};
int digitGroups = (int) (Math.log10(size) / Math.log10(1024));
return new DecimalFormat("#,##0.#").format(size / Math.pow(1024, digitGroups)) + " " + units[digitGroups];
}
private static void setupAndShowUI() {
JFrame frame = new JFrame(version);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Add content to the window.
frame.add(new DiskSpaceInformer());
//Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
UIManager.put("swing.boldMetal", Boolean.FALSE);
setupAndShowUI();
}
});
}
}
| true | true | public DiskSpaceInformer() {
super(new BorderLayout());
log = new JTextArea(30, 40);
log.setMargin(new Insets(5, 5, 5, 5));
log.setEditable(false);
log.append("- Select drive or folder: click [Choose Folder]"+newline +newline);
log.append("- Space usage: right click tree item & Check Space"+newline);
log.append("- Alternative: select tree item & click [Check Space]"+newline+newline);
log.append("- Multiple items: select multiple items [Check Space]"+newline);
log.append("- Alternative: select multiple items right click]"+newline+newline);
log.append("- All drives: overview of system [Storage Info]"+newline+newline);
log.append("- Clear screen: overview of system [Storage Info]"+newline);
JScrollPane logScrollPane = new JScrollPane(log);
logScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
logScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
//Create a file chooser
String os = System.getProperty("os.name");
fileChooser = new JFileChooser();
fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
//fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
openButton = new JButton("Choose Folder");
openButton.addActionListener(this);
checkButton = new JButton("Check Space");
checkButton.addActionListener(this);
summaryButton = new JButton("Storage Info");
summaryButton.addActionListener(this);
clearButton = new JButton("Clear Log...");
clearButton.addActionListener(this);
//flow layout
JPanel buttonPanel = new JPanel();
buttonPanel.add(openButton);
buttonPanel.add(checkButton);
buttonPanel.add(summaryButton);
buttonPanel.add(clearButton);
jProgressBar = new JProgressBar();
JPanel progressPanel = new JPanel();
// progressPanel.setMinimumSize(new Dimension(200, 200));
progressPanel.add(jProgressBar);
// Create a TreeModel object to represent our tree of files
// File root = new File(System.getProperty("user.home"));
File root;
if (OsUtils.isWindows()) {
root = new File("c:\\");
} else {
root = new File("/");
}
FileTreeModel model = new FileTreeModel(root);
// Create a JTree and tell it to display our model
tree = new JTree();
tree.setModel(model);
tree.addMouseListener(new LeftClickMouseListener());
tree.addMouseListener(new RightClickMouseListener());
// The JTree can get big, so allow it to scroll
treeScrollPane = new JScrollPane(tree);
JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,
treeScrollPane, logScrollPane);
splitPane.setOneTouchExpandable(true);
splitPane.setDividerLocation(250);
//Provide minimum sizes for the two components in the split pane
// Dimension minimumSize = new Dimension(30, 70);
// treeScrollPane.setMinimumSize(minimumSize);
// logScrollPane.setMinimumSize(minimumSize);
//Add bits to the panel.
add(buttonPanel, BorderLayout.NORTH);
add(splitPane, BorderLayout.CENTER);
add(progressPanel, BorderLayout.SOUTH);
}
| public DiskSpaceInformer() {
super(new BorderLayout());
log = new JTextArea(30, 40);
log.setMargin(new Insets(5, 5, 5, 5));
log.setEditable(false);
log.append("- Select drive or folder: click [Choose Folder]"+newline +newline);
log.append("- Space usage: right click tree item & Check Space"+newline);
log.append("- Alternative: select tree item & click [Check Space]"+newline+newline);
log.append("- Multiple items: select multiple items right click"+newline);
log.append("- Alternative: select multiple items [Check Space]"+newline+newline);
log.append("- All drives: overview of system [Storage Info]"+newline+newline);
log.append("- Clear screen: overview of system [Storage Info]"+newline);
JScrollPane logScrollPane = new JScrollPane(log);
logScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
logScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
//Create a file chooser
String os = System.getProperty("os.name");
fileChooser = new JFileChooser();
fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
//fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
openButton = new JButton("Choose Folder");
openButton.addActionListener(this);
checkButton = new JButton("Check Space");
checkButton.addActionListener(this);
summaryButton = new JButton("Storage Info");
summaryButton.addActionListener(this);
clearButton = new JButton("Clear Log...");
clearButton.addActionListener(this);
//flow layout
JPanel buttonPanel = new JPanel();
buttonPanel.add(openButton);
buttonPanel.add(checkButton);
buttonPanel.add(summaryButton);
buttonPanel.add(clearButton);
jProgressBar = new JProgressBar();
JPanel progressPanel = new JPanel();
// progressPanel.setMinimumSize(new Dimension(200, 200));
progressPanel.add(jProgressBar);
// Create a TreeModel object to represent our tree of files
// File root = new File(System.getProperty("user.home"));
File root;
if (OsUtils.isWindows()) {
root = new File("c:\\");
} else {
root = new File("/");
}
FileTreeModel model = new FileTreeModel(root);
// Create a JTree and tell it to display our model
tree = new JTree();
tree.setModel(model);
tree.addMouseListener(new LeftClickMouseListener());
tree.addMouseListener(new RightClickMouseListener());
// The JTree can get big, so allow it to scroll
treeScrollPane = new JScrollPane(tree);
JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,
treeScrollPane, logScrollPane);
splitPane.setOneTouchExpandable(true);
splitPane.setDividerLocation(250);
//Provide minimum sizes for the two components in the split pane
// Dimension minimumSize = new Dimension(30, 70);
// treeScrollPane.setMinimumSize(minimumSize);
// logScrollPane.setMinimumSize(minimumSize);
//Add bits to the panel.
add(buttonPanel, BorderLayout.NORTH);
add(splitPane, BorderLayout.CENTER);
add(progressPanel, BorderLayout.SOUTH);
}
|
diff --git a/test/utils/ConfigTest.java b/test/utils/ConfigTest.java
index 54013c20..333d9d8a 100644
--- a/test/utils/ConfigTest.java
+++ b/test/utils/ConfigTest.java
@@ -1,65 +1,65 @@
package utils;
import java.util.HashMap;
import org.junit.Test;
import play.test.FakeApplication;
import play.test.Helpers;
import static org.fest.assertions.Assertions.assertThat;
public class ConfigTest {
@Test
public void getScheme() {
FakeApplication app;
HashMap<String, String> additionalConfiguration = support.Config.makeTestConfig();
additionalConfiguration.put("application.scheme", "http");
app = Helpers.fakeApplication(additionalConfiguration);
Helpers.start(app);
assertThat(Config.getScheme("https")).isEqualTo("http");
Helpers.stop(app);
additionalConfiguration.put("application.scheme", "");
app = Helpers.fakeApplication(additionalConfiguration);
Helpers.start(app);
assertThat(Config.getScheme("https")).isEqualTo("https");
Helpers.stop(app);
}
@Test
public void getHostname() {
FakeApplication app;
HashMap<String, String> additionalConfiguration = support.Config.makeTestConfig();
- additionalConfiguration.put("application.hostname", "www.nforge.com");
+ additionalConfiguration.put("application.hostname", "test.yobi.com");
additionalConfiguration.put("application.port", "8080");
app = Helpers.fakeApplication(additionalConfiguration);
Helpers.start(app);
- assertThat(Config.getHostport("localhost")).isEqualTo("www.nforge.com:8080");
+ assertThat(Config.getHostport("localhost")).isEqualTo("test.yobi.com:8080");
Helpers.stop(app);
- additionalConfiguration.put("application.hostname", "www.nforge.com");
+ additionalConfiguration.put("application.hostname", "test.yobi.com");
additionalConfiguration.put("application.port", null);
app = Helpers.fakeApplication(additionalConfiguration);
Helpers.start(app);
- assertThat(Config.getHostport("localhost:9000")).isEqualTo("www.nforge.com");
+ assertThat(Config.getHostport("localhost:9000")).isEqualTo("test.yobi.com");
Helpers.stop(app);
additionalConfiguration.put("application.hostname", null);
additionalConfiguration.put("application.port", "8080");
app = Helpers.fakeApplication(additionalConfiguration);
Helpers.start(app);
assertThat(Config.getHostport("localhost:9000")).isEqualTo("localhost:9000");
Helpers.stop(app);
additionalConfiguration.put("application.hostname", null);
additionalConfiguration.put("application.port", null);
app = Helpers.fakeApplication(additionalConfiguration);
Helpers.start(app);
assertThat(Config.getHostport("localhost:9000")).isEqualTo("localhost:9000");
Helpers.stop(app);
}
}
| false | true | public void getHostname() {
FakeApplication app;
HashMap<String, String> additionalConfiguration = support.Config.makeTestConfig();
additionalConfiguration.put("application.hostname", "www.nforge.com");
additionalConfiguration.put("application.port", "8080");
app = Helpers.fakeApplication(additionalConfiguration);
Helpers.start(app);
assertThat(Config.getHostport("localhost")).isEqualTo("www.nforge.com:8080");
Helpers.stop(app);
additionalConfiguration.put("application.hostname", "www.nforge.com");
additionalConfiguration.put("application.port", null);
app = Helpers.fakeApplication(additionalConfiguration);
Helpers.start(app);
assertThat(Config.getHostport("localhost:9000")).isEqualTo("www.nforge.com");
Helpers.stop(app);
additionalConfiguration.put("application.hostname", null);
additionalConfiguration.put("application.port", "8080");
app = Helpers.fakeApplication(additionalConfiguration);
Helpers.start(app);
assertThat(Config.getHostport("localhost:9000")).isEqualTo("localhost:9000");
Helpers.stop(app);
additionalConfiguration.put("application.hostname", null);
additionalConfiguration.put("application.port", null);
app = Helpers.fakeApplication(additionalConfiguration);
Helpers.start(app);
assertThat(Config.getHostport("localhost:9000")).isEqualTo("localhost:9000");
Helpers.stop(app);
}
| public void getHostname() {
FakeApplication app;
HashMap<String, String> additionalConfiguration = support.Config.makeTestConfig();
additionalConfiguration.put("application.hostname", "test.yobi.com");
additionalConfiguration.put("application.port", "8080");
app = Helpers.fakeApplication(additionalConfiguration);
Helpers.start(app);
assertThat(Config.getHostport("localhost")).isEqualTo("test.yobi.com:8080");
Helpers.stop(app);
additionalConfiguration.put("application.hostname", "test.yobi.com");
additionalConfiguration.put("application.port", null);
app = Helpers.fakeApplication(additionalConfiguration);
Helpers.start(app);
assertThat(Config.getHostport("localhost:9000")).isEqualTo("test.yobi.com");
Helpers.stop(app);
additionalConfiguration.put("application.hostname", null);
additionalConfiguration.put("application.port", "8080");
app = Helpers.fakeApplication(additionalConfiguration);
Helpers.start(app);
assertThat(Config.getHostport("localhost:9000")).isEqualTo("localhost:9000");
Helpers.stop(app);
additionalConfiguration.put("application.hostname", null);
additionalConfiguration.put("application.port", null);
app = Helpers.fakeApplication(additionalConfiguration);
Helpers.start(app);
assertThat(Config.getHostport("localhost:9000")).isEqualTo("localhost:9000");
Helpers.stop(app);
}
|
diff --git a/src/java/com/idega/block/boxoffice/data/BoxCategoryBMPBean.java b/src/java/com/idega/block/boxoffice/data/BoxCategoryBMPBean.java
index 934c89a..c03c371 100644
--- a/src/java/com/idega/block/boxoffice/data/BoxCategoryBMPBean.java
+++ b/src/java/com/idega/block/boxoffice/data/BoxCategoryBMPBean.java
@@ -1,100 +1,100 @@
// idega 2000 - Laddi
package com.idega.block.boxoffice.data;
import java.sql.SQLException;
import java.util.Locale;
import javax.transaction.TransactionManager;
import com.idega.block.text.business.TextFinder;
import com.idega.block.text.data.LocalizedText;
import com.idega.data.GenericEntity;
import com.idega.transaction.IdegaTransactionManager;
import com.idega.user.data.UserBMPBean;
public class BoxCategoryBMPBean extends com.idega.data.GenericEntity implements
com.idega.block.boxoffice.data.BoxCategory {
public BoxCategoryBMPBean() {
super();
}
public BoxCategoryBMPBean(int id) throws SQLException {
super(id);
}
public void insertStartData() throws Exception {
- String[] entries = { "�mislegt", "Tenglar", "Greinar", "St�riskj�l", "Lei�beiningar", "Misc", "Links",
+ String[] entries = { "Ýmislegt", "Tenglar", "Greinar", "Stýriskjöl", "Leiðbeiningar", "Misc", "Links",
"Articles", "Documents", "Instructions" };
TransactionManager t = IdegaTransactionManager.getInstance();
t.begin();
try {
for (int a = 0; a < 5; a++) {
BoxCategory cat = ((com.idega.block.boxoffice.data.BoxCategoryHome) com.idega.data.IDOLookup.getHomeLegacy(BoxCategory.class)).createLegacy();
LocalizedText text = ((com.idega.block.text.data.LocalizedTextHome) com.idega.data.IDOLookup.getHomeLegacy(LocalizedText.class)).createLegacy();
text.setLocaleId(TextFinder.getLocaleId(new Locale("is", "IS")));
text.setHeadline(entries[a]);
LocalizedText text2 = ((com.idega.block.text.data.LocalizedTextHome) com.idega.data.IDOLookup.getHomeLegacy(LocalizedText.class)).createLegacy();
text2.setLocaleId(TextFinder.getLocaleId(Locale.ENGLISH));
text2.setHeadline(entries[a + 5]);
cat.insert();
text.insert();
text2.insert();
text.addTo(cat);
text2.addTo(cat);
}
t.commit();
}
catch (Exception e) {
e.printStackTrace();
t.rollback();
}
}
public void initializeAttributes() {
addAttribute(getIDColumnName());
addAttribute(getColumnNameUserID(), "User", true, true, Integer.class);
this.addManyToManyRelationShip(LocalizedText.class, "BX_CATEGORY_LOCALIZED_TEXT");
}
public static String getColumnNameBoxCategoryID() {
return "BX_CATEGORY_ID";
}
public static String getColumnNameUserID() {
return UserBMPBean.getColumnNameUserID();
}
public static String getEntityTableName() {
return "BX_CATEGORY";
}
public String getIDColumnName() {
return getColumnNameBoxCategoryID();
}
public String getEntityName() {
return getEntityTableName();
}
public int getUserID() {
return getIntColumnValue(getColumnNameUserID());
}
public void setUserID(int userID) {
setColumn(getColumnNameUserID(), userID);
}
public void delete() throws SQLException {
BoxLink[] link = (BoxLink[]) GenericEntity.getStaticInstance(BoxLink.class).findAllByColumn(
getColumnNameBoxCategoryID(), getID());
if (link != null) {
for (int a = 0; a < link.length; a++) {
link[a].delete();
}
}
removeFrom(GenericEntity.getStaticInstance(LocalizedText.class));
removeFrom(GenericEntity.getStaticInstance(BoxEntity.class));
super.delete();
}
}
| true | true | public void insertStartData() throws Exception {
String[] entries = { "�mislegt", "Tenglar", "Greinar", "St�riskj�l", "Lei�beiningar", "Misc", "Links",
"Articles", "Documents", "Instructions" };
TransactionManager t = IdegaTransactionManager.getInstance();
t.begin();
try {
for (int a = 0; a < 5; a++) {
BoxCategory cat = ((com.idega.block.boxoffice.data.BoxCategoryHome) com.idega.data.IDOLookup.getHomeLegacy(BoxCategory.class)).createLegacy();
LocalizedText text = ((com.idega.block.text.data.LocalizedTextHome) com.idega.data.IDOLookup.getHomeLegacy(LocalizedText.class)).createLegacy();
text.setLocaleId(TextFinder.getLocaleId(new Locale("is", "IS")));
text.setHeadline(entries[a]);
LocalizedText text2 = ((com.idega.block.text.data.LocalizedTextHome) com.idega.data.IDOLookup.getHomeLegacy(LocalizedText.class)).createLegacy();
text2.setLocaleId(TextFinder.getLocaleId(Locale.ENGLISH));
text2.setHeadline(entries[a + 5]);
cat.insert();
text.insert();
text2.insert();
text.addTo(cat);
text2.addTo(cat);
}
t.commit();
}
catch (Exception e) {
e.printStackTrace();
t.rollback();
}
}
| public void insertStartData() throws Exception {
String[] entries = { "Ýmislegt", "Tenglar", "Greinar", "Stýriskjöl", "Leiðbeiningar", "Misc", "Links",
"Articles", "Documents", "Instructions" };
TransactionManager t = IdegaTransactionManager.getInstance();
t.begin();
try {
for (int a = 0; a < 5; a++) {
BoxCategory cat = ((com.idega.block.boxoffice.data.BoxCategoryHome) com.idega.data.IDOLookup.getHomeLegacy(BoxCategory.class)).createLegacy();
LocalizedText text = ((com.idega.block.text.data.LocalizedTextHome) com.idega.data.IDOLookup.getHomeLegacy(LocalizedText.class)).createLegacy();
text.setLocaleId(TextFinder.getLocaleId(new Locale("is", "IS")));
text.setHeadline(entries[a]);
LocalizedText text2 = ((com.idega.block.text.data.LocalizedTextHome) com.idega.data.IDOLookup.getHomeLegacy(LocalizedText.class)).createLegacy();
text2.setLocaleId(TextFinder.getLocaleId(Locale.ENGLISH));
text2.setHeadline(entries[a + 5]);
cat.insert();
text.insert();
text2.insert();
text.addTo(cat);
text2.addTo(cat);
}
t.commit();
}
catch (Exception e) {
e.printStackTrace();
t.rollback();
}
}
|
diff --git a/org.eclipse.bpmn2.modeler.ui/src/org/eclipse/bpmn2/modeler/ui/property/diagrams/DataItemsPropertiesComposite.java b/org.eclipse.bpmn2.modeler.ui/src/org/eclipse/bpmn2/modeler/ui/property/diagrams/DataItemsPropertiesComposite.java
index 2fd1855b..0ef5e59f 100644
--- a/org.eclipse.bpmn2.modeler.ui/src/org/eclipse/bpmn2/modeler/ui/property/diagrams/DataItemsPropertiesComposite.java
+++ b/org.eclipse.bpmn2.modeler.ui/src/org/eclipse/bpmn2/modeler/ui/property/diagrams/DataItemsPropertiesComposite.java
@@ -1,69 +1,70 @@
/*******************************************************************************
* Copyright (c) 2011 Red Hat, Inc.
* All rights reserved.
* This program is 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:
* Red Hat, Inc. - initial API and implementation
*
* @author Bob Brodt
******************************************************************************/
package org.eclipse.bpmn2.modeler.ui.property.diagrams;
import org.eclipse.bpmn2.Definitions;
import org.eclipse.bpmn2.Import;
import org.eclipse.bpmn2.impl.DefinitionsImpl;
import org.eclipse.bpmn2.modeler.core.utils.ModelUtil;
import org.eclipse.bpmn2.modeler.ui.property.AbstractBpmn2PropertySection;
import org.eclipse.bpmn2.modeler.ui.property.AbstractBpmn2TableComposite;
import org.eclipse.bpmn2.modeler.ui.property.DefaultPropertiesComposite;
import org.eclipse.bpmn2.modeler.ui.property.DefaultPropertiesComposite.AbstractPropertiesProvider;
import org.eclipse.bpmn2.modeler.ui.property.diagrams.DefinitionsPropertyComposite.ImportsTable;
import org.eclipse.bpmn2.modeler.ui.property.dialogs.SchemaImportDialog;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EStructuralFeature;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.wst.wsdl.Definition;
/**
* @author Bob Brodt
*
*/
public class DataItemsPropertiesComposite extends DefaultPropertiesComposite {
private AbstractPropertiesProvider propertiesProvider;
public DataItemsPropertiesComposite(Composite parent, int style) {
super(parent, style);
}
/**
* @param section
*/
public DataItemsPropertiesComposite(AbstractBpmn2PropertySection section) {
super(section);
}
@Override
public AbstractPropertiesProvider getPropertiesProvider(EObject object) {
if (propertiesProvider==null) {
propertiesProvider = new AbstractPropertiesProvider(object) {
String[] properties = new String[] {
"rootElements.ItemDefinition",
"rootElements.DataStore",
- "rootElements.Message"
+ "rootElements.Message",
+ "rootElements.Error"
};
@Override
public String[] getProperties() {
return properties;
}
};
}
return propertiesProvider;
}
}
| true | true | public AbstractPropertiesProvider getPropertiesProvider(EObject object) {
if (propertiesProvider==null) {
propertiesProvider = new AbstractPropertiesProvider(object) {
String[] properties = new String[] {
"rootElements.ItemDefinition",
"rootElements.DataStore",
"rootElements.Message"
};
@Override
public String[] getProperties() {
return properties;
}
};
}
return propertiesProvider;
}
| public AbstractPropertiesProvider getPropertiesProvider(EObject object) {
if (propertiesProvider==null) {
propertiesProvider = new AbstractPropertiesProvider(object) {
String[] properties = new String[] {
"rootElements.ItemDefinition",
"rootElements.DataStore",
"rootElements.Message",
"rootElements.Error"
};
@Override
public String[] getProperties() {
return properties;
}
};
}
return propertiesProvider;
}
|
diff --git a/src/org/eclipse/jface/action/ActionContributionItem.java b/src/org/eclipse/jface/action/ActionContributionItem.java
index da5af77c..8e5cd85b 100644
--- a/src/org/eclipse/jface/action/ActionContributionItem.java
+++ b/src/org/eclipse/jface/action/ActionContributionItem.java
@@ -1,1022 +1,1026 @@
/*******************************************************************************
* Copyright (c) 2000, 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.jface.action;
import org.eclipse.jface.action.ExternalActionManager.IBindingManagerCallback;
import org.eclipse.jface.bindings.Trigger;
import org.eclipse.jface.bindings.TriggerSequence;
import org.eclipse.jface.bindings.keys.IKeyLookup;
import org.eclipse.jface.bindings.keys.KeyLookupFactory;
import org.eclipse.jface.bindings.keys.KeyStroke;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.jface.resource.LocalResourceManager;
import org.eclipse.jface.resource.ResourceManager;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.Policy;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Item;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.swt.widgets.ToolItem;
import org.eclipse.swt.widgets.Widget;
/**
* A contribution item which delegates to an action.
* <p>
* This class may be instantiated; it is not intended to be subclassed.
* </p>
*/
public class ActionContributionItem extends ContributionItem {
/**
* Mode bit: Show text on tool items, even if an image is present.
* If this mode bit is not set, text is only shown on tool items if there is
* no image present.
*
* @since 3.0
*/
public static int MODE_FORCE_TEXT = 1;
/** a string inserted in the middle of text that has been shortened */
private static final String ellipsis = "..."; //$NON-NLS-1$
private static boolean USE_COLOR_ICONS = true;
/**
* Returns whether color icons should be used in toolbars.
*
* @return <code>true</code> if color icons should be used in toolbars,
* <code>false</code> otherwise
*/
public static boolean getUseColorIconsInToolbars() {
return USE_COLOR_ICONS;
}
/**
* Sets whether color icons should be used in toolbars.
*
* @param useColorIcons <code>true</code> if color icons should be used in toolbars,
* <code>false</code> otherwise
*/
public static void setUseColorIconsInToolbars(boolean useColorIcons) {
USE_COLOR_ICONS = useColorIcons;
}
/**
* The presentation mode.
*/
private int mode = 0;
/**
* The action.
*/
private IAction action;
/**
* The listener for changes to the text of the action contributed by an
* external source.
*/
private final IPropertyChangeListener actionTextListener = new IPropertyChangeListener() {
/**
* @see IPropertyChangeListener#propertyChange(PropertyChangeEvent)
*/
public void propertyChange(PropertyChangeEvent event) {
update(event.getProperty());
}
};
/**
* Remembers all images in use by this contribution item
*/
private LocalResourceManager imageManager;
/**
* Listener for SWT button widget events.
*/
private Listener buttonListener;
/**
* Listener for SWT menu item widget events.
*/
private Listener menuItemListener;
/**
* Listener for action property change notifications.
*/
private final IPropertyChangeListener propertyListener = new IPropertyChangeListener() {
public void propertyChange(PropertyChangeEvent event) {
actionPropertyChange(event);
}
};
/**
* Listener for SWT tool item widget events.
*/
private Listener toolItemListener;
/**
* The widget created for this item; <code>null</code>
* before creation and after disposal.
*/
private Widget widget = null;
/**
* Creates a new contribution item from the given action. The id of the
* action is used as the id of the item.
*
* @param action
* the action
*/
public ActionContributionItem(IAction action) {
super(action.getId());
this.action = action;
}
/**
* Handles a property change event on the action (forwarded by nested listener).
*/
private void actionPropertyChange(final PropertyChangeEvent e) {
// This code should be removed. Avoid using free asyncExec
if (isVisible() && widget != null) {
Display display = widget.getDisplay();
if (display.getThread() == Thread.currentThread()) {
update(e.getProperty());
} else {
display.asyncExec(new Runnable() {
public void run() {
update(e.getProperty());
}
});
}
}
}
/**
* Compares this action contribution item with another object.
* Two action contribution items are equal if they refer to the identical Action.
*/
public boolean equals(Object o) {
if (!(o instanceof ActionContributionItem)) {
return false;
}
return action.equals(((ActionContributionItem) o).action);
}
/**
* The <code>ActionContributionItem</code> implementation of this
* <code>IContributionItem</code> method creates an SWT <code>Button</code> for
* the action using the action's style. If the action's checked property has
* been set, the button is created and primed to the value of the checked
* property.
*/
public void fill(Composite parent) {
if (widget == null && parent != null) {
int flags = SWT.PUSH;
if (action != null) {
if (action.getStyle() == IAction.AS_CHECK_BOX)
flags = SWT.TOGGLE;
if (action.getStyle() == IAction.AS_RADIO_BUTTON)
flags = SWT.RADIO;
}
Button b = new Button(parent, flags);
b.setData(this);
b.addListener(SWT.Dispose, getButtonListener());
// Don't hook a dispose listener on the parent
b.addListener(SWT.Selection, getButtonListener());
if (action.getHelpListener() != null)
b.addHelpListener(action.getHelpListener());
widget = b;
update(null);
// Attach some extra listeners.
action.addPropertyChangeListener(propertyListener);
if (action != null) {
String commandId = action.getActionDefinitionId();
ExternalActionManager.ICallback callback = ExternalActionManager
.getInstance().getCallback();
if ((callback != null) && (commandId != null)) {
callback.addPropertyChangeListener(commandId,
actionTextListener);
}
}
}
}
/**
* The <code>ActionContributionItem</code> implementation of this
* <code>IContributionItem</code> method creates an SWT <code>MenuItem</code>
* for the action using the action's style. If the action's checked property has
* been set, a button is created and primed to the value of the checked
* property. If the action's menu creator property has been set, a cascading
* submenu is created.
*/
public void fill(Menu parent, int index) {
if (widget == null && parent != null) {
Menu subMenu = null;
int flags = SWT.PUSH;
if (action != null) {
int style = action.getStyle();
if (style == IAction.AS_CHECK_BOX)
flags = SWT.CHECK;
else if (style == IAction.AS_RADIO_BUTTON)
flags = SWT.RADIO;
else if (style == IAction.AS_DROP_DOWN_MENU) {
IMenuCreator mc = action.getMenuCreator();
if (mc != null) {
subMenu = mc.getMenu(parent);
flags = SWT.CASCADE;
}
}
}
MenuItem mi = null;
if (index >= 0)
mi = new MenuItem(parent, flags, index);
else
mi = new MenuItem(parent, flags);
widget = mi;
mi.setData(this);
mi.addListener(SWT.Dispose, getMenuItemListener());
mi.addListener(SWT.Selection, getMenuItemListener());
if (action.getHelpListener() != null)
mi.addHelpListener(action.getHelpListener());
if (subMenu != null)
mi.setMenu(subMenu);
update(null);
// Attach some extra listeners.
action.addPropertyChangeListener(propertyListener);
if (action != null) {
String commandId = action.getActionDefinitionId();
ExternalActionManager.ICallback callback = ExternalActionManager
.getInstance().getCallback();
if ((callback != null) && (commandId != null)) {
callback.addPropertyChangeListener(commandId,
actionTextListener);
}
}
}
}
/**
* The <code>ActionContributionItem</code> implementation of this ,
* <code>IContributionItem</code> method creates an SWT <code>ToolItem</code>
* for the action using the action's style. If the action's checked property has
* been set, a button is created and primed to the value of the checked
* property. If the action's menu creator property has been set, a drop-down
* tool item is created.
*/
public void fill(ToolBar parent, int index) {
if (widget == null && parent != null) {
int flags = SWT.PUSH;
if (action != null) {
int style = action.getStyle();
if (style == IAction.AS_CHECK_BOX)
flags = SWT.CHECK;
else if (style == IAction.AS_RADIO_BUTTON)
flags = SWT.RADIO;
else if (style == IAction.AS_DROP_DOWN_MENU)
flags = SWT.DROP_DOWN;
}
ToolItem ti = null;
if (index >= 0)
ti = new ToolItem(parent, flags, index);
else
ti = new ToolItem(parent, flags);
ti.setData(this);
ti.addListener(SWT.Selection, getToolItemListener());
ti.addListener(SWT.Dispose, getToolItemListener());
widget = ti;
update(null);
// Attach some extra listeners.
action.addPropertyChangeListener(propertyListener);
if (action != null) {
String commandId = action.getActionDefinitionId();
ExternalActionManager.ICallback callback = ExternalActionManager
.getInstance().getCallback();
if ((callback != null) && (commandId != null)) {
callback.addPropertyChangeListener(commandId,
actionTextListener);
}
}
}
}
/**
* Returns the action associated with this contribution item.
*
* @return the action
*/
public IAction getAction() {
return action;
}
/**
* Returns the listener for SWT button widget events.
*
* @return a listener for button events
*/
private Listener getButtonListener() {
if (buttonListener == null) {
buttonListener = new Listener() {
public void handleEvent(Event event) {
switch (event.type) {
case SWT.Dispose:
handleWidgetDispose(event);
break;
case SWT.Selection:
Widget ew = event.widget;
if (ew != null) {
handleWidgetSelection(event, ((Button) ew)
.getSelection());
}
break;
}
}
};
}
return buttonListener;
}
/**
* Returns the listener for SWT menu item widget events.
*
* @return a listener for menu item events
*/
private Listener getMenuItemListener() {
if (menuItemListener == null) {
menuItemListener = new Listener() {
public void handleEvent(Event event) {
switch (event.type) {
case SWT.Dispose:
handleWidgetDispose(event);
break;
case SWT.Selection:
Widget ew = event.widget;
if (ew != null) {
handleWidgetSelection(event, ((MenuItem) ew)
.getSelection());
}
break;
}
}
};
}
return menuItemListener;
}
/**
* Returns the presentation mode, which is the bitwise-or of the
* <code>MODE_*</code> constants. The default mode setting is 0, meaning
* that for menu items, both text and image are shown (if present), but for
* tool items, the text is shown only if there is no image.
*
* @return the presentation mode settings
*
* @since 3.0
*/
public int getMode() {
return mode;
}
/**
* Returns the listener for SWT tool item widget events.
*
* @return a listener for tool item events
*/
private Listener getToolItemListener() {
if (toolItemListener == null) {
toolItemListener = new Listener() {
public void handleEvent(Event event) {
switch (event.type) {
case SWT.Dispose:
handleWidgetDispose(event);
break;
case SWT.Selection:
Widget ew = event.widget;
if (ew != null) {
handleWidgetSelection(event, ((ToolItem) ew)
.getSelection());
}
break;
}
}
};
}
return toolItemListener;
}
/**
* Handles a widget dispose event for the widget corresponding to this item.
*/
private void handleWidgetDispose(Event e) {
// Check if our widget is the one being disposed.
if (e.widget == widget) {
// Dispose of the menu creator.
if (action.getStyle() == IAction.AS_DROP_DOWN_MENU) {
IMenuCreator mc = action.getMenuCreator();
if (mc != null) {
mc.dispose();
}
}
// Unhook all of the listeners.
action.removePropertyChangeListener(propertyListener);
if (action != null) {
String commandId = action.getActionDefinitionId();
ExternalActionManager.ICallback callback = ExternalActionManager
.getInstance().getCallback();
if ((callback != null) && (commandId != null)) {
callback.removePropertyChangeListener(commandId,
actionTextListener);
}
}
// Clear the widget field.
widget = null;
disposeOldImages();
}
}
/**
* Handles a widget selection event.
*/
private void handleWidgetSelection(Event e, boolean selection) {
Widget item = e.widget;
if (item != null) {
int style = item.getStyle();
if ((style & (SWT.TOGGLE | SWT.CHECK)) != 0) {
if (action.getStyle() == IAction.AS_CHECK_BOX) {
action.setChecked(selection);
}
} else if ((style & SWT.RADIO) != 0) {
if (action.getStyle() == IAction.AS_RADIO_BUTTON) {
action.setChecked(selection);
}
} else if ((style & SWT.DROP_DOWN) != 0) {
if (e.detail == 4) { // on drop-down button
if (action.getStyle() == IAction.AS_DROP_DOWN_MENU) {
IMenuCreator mc = action.getMenuCreator();
ToolItem ti = (ToolItem) item;
// we create the menu as a sub-menu of "dummy" so that we can use
// it in a cascading menu too.
// If created on a SWT control we would get an SWT error...
//Menu dummy= new Menu(ti.getParent());
//Menu m= mc.getMenu(dummy);
//dummy.dispose();
if (mc != null) {
Menu m = mc.getMenu(ti.getParent());
if (m != null) {
// position the menu below the drop down item
Rectangle b = ti.getBounds();
Point p = ti.getParent().toDisplay(
new Point(b.x, b.y + b.height));
m.setLocation(p.x, p.y); // waiting for SWT 0.42
m.setVisible(true);
return; // we don't fire the action
}
}
}
}
}
// Ensure action is enabled first.
// See 1GAN3M6: ITPUI:WINNT - Any IAction in the workbench can be executed while disabled.
if (action.isEnabled()) {
boolean trace = Policy.TRACE_ACTIONS;
long ms = System.currentTimeMillis();
if (trace)
System.out.println("Running action: " + action.getText()); //$NON-NLS-1$
action.runWithEvent(e);
if (trace)
System.out.println((System.currentTimeMillis() - ms)
+ " ms to run action: " + action.getText()); //$NON-NLS-1$
}
}
}
/* (non-Javadoc)
* Method declared on Object.
*/
public int hashCode() {
return action.hashCode();
}
/**
* Returns whether the given action has any images.
*
* @param actionToCheck the action
* @return <code>true</code> if the action has any images, <code>false</code> if not
*/
private boolean hasImages(IAction actionToCheck) {
return actionToCheck.getImageDescriptor() != null
|| actionToCheck.getHoverImageDescriptor() != null
|| actionToCheck.getDisabledImageDescriptor() != null;
}
/**
* Returns whether the command corresponding to this action
* is active.
*/
private boolean isCommandActive() {
IAction actionToCheck = getAction();
if (actionToCheck != null) {
String commandId = actionToCheck.getActionDefinitionId();
ExternalActionManager.ICallback callback = ExternalActionManager
.getInstance().getCallback();
if (callback != null)
return callback.isActive(commandId);
}
return true;
}
/**
* The action item implementation of this <code>IContributionItem</code>
* method returns <code>true</code> for menu items and <code>false</code>
* for everything else.
*/
public boolean isDynamic() {
if (widget instanceof MenuItem) {
//Optimization. Only recreate the item is the check or radio style has changed.
boolean itemIsCheck = (widget.getStyle() & SWT.CHECK) != 0;
boolean actionIsCheck = getAction() != null
&& getAction().getStyle() == IAction.AS_CHECK_BOX;
boolean itemIsRadio = (widget.getStyle() & SWT.RADIO) != 0;
boolean actionIsRadio = getAction() != null
&& getAction().getStyle() == IAction.AS_RADIO_BUTTON;
return (itemIsCheck != actionIsCheck)
|| (itemIsRadio != actionIsRadio);
}
return false;
}
/* (non-Javadoc)
* Method declared on IContributionItem.
*/
public boolean isEnabled() {
return action != null && action.isEnabled();
}
/**
* Returns <code>true</code> if this item is allowed to enable,
* <code>false</code> otherwise.
*
* @return if this item is allowed to be enabled
* @since 2.0
*/
protected boolean isEnabledAllowed() {
if (getParent() == null)
return true;
Boolean value = getParent().getOverrides().getEnabled(this);
return (value == null) ? true : value.booleanValue();
}
/**
* The <code>ActionContributionItem</code> implementation of this
* <code>ContributionItem</code> method extends the super implementation
* by also checking whether the command corresponding to this action is active.
*/
public boolean isVisible() {
return super.isVisible() && isCommandActive();
}
/**
* Sets the presentation mode, which is the bitwise-or of the
* <code>MODE_*</code> constants.
*
* @param mode the presentation mode settings
*
* @since 3.0
*/
public void setMode(int mode) {
this.mode = mode;
update();
}
/**
* The action item implementation of this <code>IContributionItem</code>
* method calls <code>update(null)</code>.
*/
public final void update() {
update(null);
}
/**
* Synchronizes the UI with the given property.
*
* @param propertyName the name of the property, or <code>null</code> meaning all applicable
* properties
*/
public void update(String propertyName) {
if (widget != null) {
// determine what to do
boolean textChanged = propertyName == null
|| propertyName.equals(IAction.TEXT);
boolean imageChanged = propertyName == null
|| propertyName.equals(IAction.IMAGE);
boolean tooltipTextChanged = propertyName == null
|| propertyName.equals(IAction.TOOL_TIP_TEXT);
boolean enableStateChanged = propertyName == null
|| propertyName.equals(IAction.ENABLED)
|| propertyName
.equals(IContributionManagerOverrides.P_ENABLED);
boolean checkChanged = (action.getStyle() == IAction.AS_CHECK_BOX || action
.getStyle() == IAction.AS_RADIO_BUTTON)
&& (propertyName == null || propertyName
.equals(IAction.CHECKED));
if (widget instanceof ToolItem) {
ToolItem ti = (ToolItem) widget;
String text = action.getText();
// the set text is shown only if there is no image or if forced by MODE_FORCE_TEXT
boolean showText = text != null
&& ((getMode() & MODE_FORCE_TEXT) != 0 || !hasImages(action));
// only do the trimming if the text will be used
if (showText && text != null) {
text = Action.removeAcceleratorText(text);
text = Action.removeMnemonics(text);
}
if (textChanged) {
String textToSet = showText ? text : ""; //$NON-NLS-1$
boolean rightStyle = (ti.getParent().getStyle() & SWT.RIGHT) != 0;
if (rightStyle || !ti.getText().equals(textToSet)) {
// In addition to being required to update the text if it
// gets nulled out in the action, this is also a workaround
// for bug 50151: Using SWT.RIGHT on a ToolBar leaves blank space
ti.setText(textToSet);
}
}
if (imageChanged) {
// only substitute a missing image if it has no text
updateImages(!showText);
}
if (tooltipTextChanged || textChanged) {
String toolTip = action.getToolTipText();
- // if the text is showing, then only set the tooltip if different
+ if ((toolTip == null) || (toolTip.length() == 0)) {
+ toolTip = text;
+ }
+ // if the text is showing, then only set the tooltip if
+ // different
if (!showText || toolTip != null && !toolTip.equals(text)) {
ti.setToolTipText(toolTip);
} else {
ti.setToolTipText(null);
}
}
if (enableStateChanged) {
boolean shouldBeEnabled = action.isEnabled()
&& isEnabledAllowed();
if (ti.getEnabled() != shouldBeEnabled)
ti.setEnabled(shouldBeEnabled);
}
if (checkChanged) {
boolean bv = action.isChecked();
if (ti.getSelection() != bv)
ti.setSelection(bv);
}
return;
}
if (widget instanceof MenuItem) {
MenuItem mi = (MenuItem) widget;
if (textChanged) {
int accelerator = 0;
String acceleratorText = null;
IAction updatedAction = getAction();
String text = null;
accelerator = updatedAction.getAccelerator();
ExternalActionManager.ICallback callback = ExternalActionManager
.getInstance().getCallback();
// Block accelerators that are already in use.
if ((accelerator != 0) && (callback != null)
&& (callback.isAcceleratorInUse(accelerator))) {
accelerator = 0;
}
/*
* Process accelerators on GTK in a special way to avoid Bug
* 42009. We will override the native input method by
* allowing these reserved accelerators to be placed on the
* menu. We will only do this for "Ctrl+Shift+[0-9A-FU]".
*/
final String commandId = updatedAction
.getActionDefinitionId();
if (("gtk".equals(SWT.getPlatform())) && (callback instanceof IBindingManagerCallback) //$NON-NLS-1$
&& (commandId != null)) {
final IBindingManagerCallback bindingManagerCallback = (IBindingManagerCallback) callback;
final IKeyLookup lookup = KeyLookupFactory.getDefault();
final TriggerSequence[] triggerSequences = bindingManagerCallback
.getActiveBindingsFor(commandId);
for (int i = 0; i < triggerSequences.length; i++) {
final TriggerSequence triggerSequence = triggerSequences[i];
final Trigger[] triggers = triggerSequence
.getTriggers();
if (triggers.length == 1) {
final Trigger trigger = triggers[0];
if (trigger instanceof KeyStroke) {
final KeyStroke currentKeyStroke = (KeyStroke) trigger;
final int currentNaturalKey = currentKeyStroke
.getNaturalKey();
if ((currentKeyStroke.getModifierKeys() == (lookup
.getCtrl() | lookup.getShift()))
&& ((currentNaturalKey >= '0' && currentNaturalKey <= '9')
|| (currentNaturalKey >= 'A' && currentNaturalKey <= 'F') || (currentNaturalKey == 'U'))) {
accelerator = currentKeyStroke
.getModifierKeys()
| currentNaturalKey;
acceleratorText = triggerSequence
.format();
break;
}
}
}
}
}
if (accelerator == 0) {
if ((callback != null) && (commandId != null)) {
acceleratorText = callback
.getAcceleratorText(commandId);
}
} else {
acceleratorText = Action
.convertAccelerator(accelerator);
}
IContributionManagerOverrides overrides = null;
if (getParent() != null)
overrides = getParent().getOverrides();
if (overrides != null)
text = getParent().getOverrides().getText(this);
mi.setAccelerator(accelerator);
if (text == null)
text = updatedAction.getText();
if (text == null)
text = ""; //$NON-NLS-1$
else
text = Action.removeAcceleratorText(text);
if (acceleratorText == null)
mi.setText(text);
else
mi.setText(text + '\t' + acceleratorText);
}
if (imageChanged)
updateImages(false);
if (enableStateChanged) {
boolean shouldBeEnabled = action.isEnabled()
&& isEnabledAllowed();
if (mi.getEnabled() != shouldBeEnabled)
mi.setEnabled(shouldBeEnabled);
}
if (checkChanged) {
boolean bv = action.isChecked();
if (mi.getSelection() != bv)
mi.setSelection(bv);
}
return;
}
if (widget instanceof Button) {
Button button = (Button) widget;
if (imageChanged && updateImages(false))
textChanged = false; // don't update text if it has an image
if (textChanged) {
String text = action.getText();
if (text == null)
text = ""; //$NON-NLS-1$
else
text = Action.removeAcceleratorText(text);
button.setText(text);
}
if (tooltipTextChanged)
button.setToolTipText(action.getToolTipText());
if (enableStateChanged) {
boolean shouldBeEnabled = action.isEnabled()
&& isEnabledAllowed();
if (button.getEnabled() != shouldBeEnabled)
button.setEnabled(shouldBeEnabled);
}
if (checkChanged) {
boolean bv = action.isChecked();
if (button.getSelection() != bv)
button.setSelection(bv);
}
return;
}
}
}
/**
* Updates the images for this action.
*
* @param forceImage <code>true</code> if some form of image is compulsory,
* and <code>false</code> if it is acceptable for this item to have no image
* @return <code>true</code> if there are images for this action, <code>false</code> if not
*/
private boolean updateImages(boolean forceImage) {
ResourceManager parentResourceManager = JFaceResources.getResources();
if (widget instanceof ToolItem) {
if (USE_COLOR_ICONS) {
ImageDescriptor image = action.getHoverImageDescriptor();
if (image == null) {
image = action.getImageDescriptor();
}
ImageDescriptor disabledImage = action
.getDisabledImageDescriptor();
// Make sure there is a valid image.
if (image == null && forceImage) {
image = ImageDescriptor.getMissingImageDescriptor();
}
LocalResourceManager localManager = new LocalResourceManager(parentResourceManager);
// performance: more efficient in SWT to set disabled and hot image before regular image
((ToolItem) widget).setDisabledImage(disabledImage == null ? null : localManager.createImageWithDefault(disabledImage));
((ToolItem) widget).setImage(image == null ? null : localManager.createImageWithDefault(image));
disposeOldImages();
imageManager = localManager;
return image != null;
}
ImageDescriptor image = action.getImageDescriptor();
ImageDescriptor hoverImage = action
.getHoverImageDescriptor();
ImageDescriptor disabledImage = action
.getDisabledImageDescriptor();
// If there is no regular image, but there is a hover image,
// convert the hover image to gray and use it as the regular image.
if (image == null && hoverImage != null) {
image = ImageDescriptor.createWithFlags(action.getHoverImageDescriptor(), SWT.IMAGE_GRAY);
} else {
// If there is no hover image, use the regular image as the hover image,
// and convert the regular image to gray
if (hoverImage == null && image != null) {
hoverImage = image;
image = ImageDescriptor.createWithFlags(action.getImageDescriptor(), SWT.IMAGE_GRAY);
}
}
// Make sure there is a valid image.
if (hoverImage == null && image == null && forceImage) {
image = ImageDescriptor.getMissingImageDescriptor();
}
// Create a local resource manager to remember the images we've allocated for this tool item
LocalResourceManager localManager = new LocalResourceManager(parentResourceManager);
// performance: more efficient in SWT to set disabled and hot image before regular image
((ToolItem) widget).setDisabledImage(disabledImage == null? null : localManager.createImageWithDefault(disabledImage));
((ToolItem) widget).setHotImage(hoverImage == null? null : localManager.createImageWithDefault(hoverImage));
((ToolItem) widget).setImage(image == null? null : localManager.createImageWithDefault(image));
// Now that we're no longer referencing the old images, clear them out.
disposeOldImages();
imageManager = localManager;
return image != null;
} else if (widget instanceof Item || widget instanceof Button) {
// Use hover image if there is one, otherwise use regular image.
ImageDescriptor image = action.getHoverImageDescriptor();
if (image == null) {
image = action.getImageDescriptor();
}
// Make sure there is a valid image.
if (image == null && forceImage) {
image = ImageDescriptor.getMissingImageDescriptor();
}
// Create a local resource manager to remember the images we've allocated for this widget
LocalResourceManager localManager = new LocalResourceManager(parentResourceManager);
if (widget instanceof Item) {
((Item) widget).setImage(image == null ? null : localManager.createImageWithDefault(image));
} else if (widget instanceof Button) {
((Button) widget).setImage(image == null ? null : localManager.createImageWithDefault(image));
}
// Now that we're no longer referencing the old images, clear them out.
disposeOldImages();
imageManager = localManager;
return image != null;
}
return false;
}
/**
* Dispose any images allocated for this contribution item
*/
private void disposeOldImages() {
if (imageManager != null) {
imageManager.dispose();
imageManager = null;
}
}
/**
* Shorten the given text <code>t</code> so that its length doesn't
* exceed the given width. The default implementation replaces characters
* in the center of the original string with an ellipsis ("..."). Override
* if you need a different strategy.
*/
protected String shortenText(String textValue, ToolItem item) {
if (textValue == null)
return null;
GC gc = new GC(item.getParent());
int maxWidth = item.getImage().getBounds().width * 4;
if (gc.textExtent(textValue).x < maxWidth) {
gc.dispose();
return textValue;
}
for (int i = textValue.length(); i > 0; i--) {
String test = textValue.substring(0, i);
test = test + ellipsis;
if (gc.textExtent(test).x < maxWidth) {
gc.dispose();
return test;
}
}
gc.dispose();
//If for some reason we fall through abort
return textValue;
}
}
| true | true | public void update(String propertyName) {
if (widget != null) {
// determine what to do
boolean textChanged = propertyName == null
|| propertyName.equals(IAction.TEXT);
boolean imageChanged = propertyName == null
|| propertyName.equals(IAction.IMAGE);
boolean tooltipTextChanged = propertyName == null
|| propertyName.equals(IAction.TOOL_TIP_TEXT);
boolean enableStateChanged = propertyName == null
|| propertyName.equals(IAction.ENABLED)
|| propertyName
.equals(IContributionManagerOverrides.P_ENABLED);
boolean checkChanged = (action.getStyle() == IAction.AS_CHECK_BOX || action
.getStyle() == IAction.AS_RADIO_BUTTON)
&& (propertyName == null || propertyName
.equals(IAction.CHECKED));
if (widget instanceof ToolItem) {
ToolItem ti = (ToolItem) widget;
String text = action.getText();
// the set text is shown only if there is no image or if forced by MODE_FORCE_TEXT
boolean showText = text != null
&& ((getMode() & MODE_FORCE_TEXT) != 0 || !hasImages(action));
// only do the trimming if the text will be used
if (showText && text != null) {
text = Action.removeAcceleratorText(text);
text = Action.removeMnemonics(text);
}
if (textChanged) {
String textToSet = showText ? text : ""; //$NON-NLS-1$
boolean rightStyle = (ti.getParent().getStyle() & SWT.RIGHT) != 0;
if (rightStyle || !ti.getText().equals(textToSet)) {
// In addition to being required to update the text if it
// gets nulled out in the action, this is also a workaround
// for bug 50151: Using SWT.RIGHT on a ToolBar leaves blank space
ti.setText(textToSet);
}
}
if (imageChanged) {
// only substitute a missing image if it has no text
updateImages(!showText);
}
if (tooltipTextChanged || textChanged) {
String toolTip = action.getToolTipText();
// if the text is showing, then only set the tooltip if different
if (!showText || toolTip != null && !toolTip.equals(text)) {
ti.setToolTipText(toolTip);
} else {
ti.setToolTipText(null);
}
}
if (enableStateChanged) {
boolean shouldBeEnabled = action.isEnabled()
&& isEnabledAllowed();
if (ti.getEnabled() != shouldBeEnabled)
ti.setEnabled(shouldBeEnabled);
}
if (checkChanged) {
boolean bv = action.isChecked();
if (ti.getSelection() != bv)
ti.setSelection(bv);
}
return;
}
if (widget instanceof MenuItem) {
MenuItem mi = (MenuItem) widget;
if (textChanged) {
int accelerator = 0;
String acceleratorText = null;
IAction updatedAction = getAction();
String text = null;
accelerator = updatedAction.getAccelerator();
ExternalActionManager.ICallback callback = ExternalActionManager
.getInstance().getCallback();
// Block accelerators that are already in use.
if ((accelerator != 0) && (callback != null)
&& (callback.isAcceleratorInUse(accelerator))) {
accelerator = 0;
}
/*
* Process accelerators on GTK in a special way to avoid Bug
* 42009. We will override the native input method by
* allowing these reserved accelerators to be placed on the
* menu. We will only do this for "Ctrl+Shift+[0-9A-FU]".
*/
final String commandId = updatedAction
.getActionDefinitionId();
if (("gtk".equals(SWT.getPlatform())) && (callback instanceof IBindingManagerCallback) //$NON-NLS-1$
&& (commandId != null)) {
final IBindingManagerCallback bindingManagerCallback = (IBindingManagerCallback) callback;
final IKeyLookup lookup = KeyLookupFactory.getDefault();
final TriggerSequence[] triggerSequences = bindingManagerCallback
.getActiveBindingsFor(commandId);
for (int i = 0; i < triggerSequences.length; i++) {
final TriggerSequence triggerSequence = triggerSequences[i];
final Trigger[] triggers = triggerSequence
.getTriggers();
if (triggers.length == 1) {
final Trigger trigger = triggers[0];
if (trigger instanceof KeyStroke) {
final KeyStroke currentKeyStroke = (KeyStroke) trigger;
final int currentNaturalKey = currentKeyStroke
.getNaturalKey();
if ((currentKeyStroke.getModifierKeys() == (lookup
.getCtrl() | lookup.getShift()))
&& ((currentNaturalKey >= '0' && currentNaturalKey <= '9')
|| (currentNaturalKey >= 'A' && currentNaturalKey <= 'F') || (currentNaturalKey == 'U'))) {
accelerator = currentKeyStroke
.getModifierKeys()
| currentNaturalKey;
acceleratorText = triggerSequence
.format();
break;
}
}
}
}
}
if (accelerator == 0) {
if ((callback != null) && (commandId != null)) {
acceleratorText = callback
.getAcceleratorText(commandId);
}
} else {
acceleratorText = Action
.convertAccelerator(accelerator);
}
IContributionManagerOverrides overrides = null;
if (getParent() != null)
overrides = getParent().getOverrides();
if (overrides != null)
text = getParent().getOverrides().getText(this);
mi.setAccelerator(accelerator);
if (text == null)
text = updatedAction.getText();
if (text == null)
text = ""; //$NON-NLS-1$
else
text = Action.removeAcceleratorText(text);
if (acceleratorText == null)
mi.setText(text);
else
mi.setText(text + '\t' + acceleratorText);
}
if (imageChanged)
updateImages(false);
if (enableStateChanged) {
boolean shouldBeEnabled = action.isEnabled()
&& isEnabledAllowed();
if (mi.getEnabled() != shouldBeEnabled)
mi.setEnabled(shouldBeEnabled);
}
if (checkChanged) {
boolean bv = action.isChecked();
if (mi.getSelection() != bv)
mi.setSelection(bv);
}
return;
}
if (widget instanceof Button) {
Button button = (Button) widget;
if (imageChanged && updateImages(false))
textChanged = false; // don't update text if it has an image
if (textChanged) {
String text = action.getText();
if (text == null)
text = ""; //$NON-NLS-1$
else
text = Action.removeAcceleratorText(text);
button.setText(text);
}
if (tooltipTextChanged)
button.setToolTipText(action.getToolTipText());
if (enableStateChanged) {
boolean shouldBeEnabled = action.isEnabled()
&& isEnabledAllowed();
if (button.getEnabled() != shouldBeEnabled)
button.setEnabled(shouldBeEnabled);
}
if (checkChanged) {
boolean bv = action.isChecked();
if (button.getSelection() != bv)
button.setSelection(bv);
}
return;
}
}
}
| public void update(String propertyName) {
if (widget != null) {
// determine what to do
boolean textChanged = propertyName == null
|| propertyName.equals(IAction.TEXT);
boolean imageChanged = propertyName == null
|| propertyName.equals(IAction.IMAGE);
boolean tooltipTextChanged = propertyName == null
|| propertyName.equals(IAction.TOOL_TIP_TEXT);
boolean enableStateChanged = propertyName == null
|| propertyName.equals(IAction.ENABLED)
|| propertyName
.equals(IContributionManagerOverrides.P_ENABLED);
boolean checkChanged = (action.getStyle() == IAction.AS_CHECK_BOX || action
.getStyle() == IAction.AS_RADIO_BUTTON)
&& (propertyName == null || propertyName
.equals(IAction.CHECKED));
if (widget instanceof ToolItem) {
ToolItem ti = (ToolItem) widget;
String text = action.getText();
// the set text is shown only if there is no image or if forced by MODE_FORCE_TEXT
boolean showText = text != null
&& ((getMode() & MODE_FORCE_TEXT) != 0 || !hasImages(action));
// only do the trimming if the text will be used
if (showText && text != null) {
text = Action.removeAcceleratorText(text);
text = Action.removeMnemonics(text);
}
if (textChanged) {
String textToSet = showText ? text : ""; //$NON-NLS-1$
boolean rightStyle = (ti.getParent().getStyle() & SWT.RIGHT) != 0;
if (rightStyle || !ti.getText().equals(textToSet)) {
// In addition to being required to update the text if it
// gets nulled out in the action, this is also a workaround
// for bug 50151: Using SWT.RIGHT on a ToolBar leaves blank space
ti.setText(textToSet);
}
}
if (imageChanged) {
// only substitute a missing image if it has no text
updateImages(!showText);
}
if (tooltipTextChanged || textChanged) {
String toolTip = action.getToolTipText();
if ((toolTip == null) || (toolTip.length() == 0)) {
toolTip = text;
}
// if the text is showing, then only set the tooltip if
// different
if (!showText || toolTip != null && !toolTip.equals(text)) {
ti.setToolTipText(toolTip);
} else {
ti.setToolTipText(null);
}
}
if (enableStateChanged) {
boolean shouldBeEnabled = action.isEnabled()
&& isEnabledAllowed();
if (ti.getEnabled() != shouldBeEnabled)
ti.setEnabled(shouldBeEnabled);
}
if (checkChanged) {
boolean bv = action.isChecked();
if (ti.getSelection() != bv)
ti.setSelection(bv);
}
return;
}
if (widget instanceof MenuItem) {
MenuItem mi = (MenuItem) widget;
if (textChanged) {
int accelerator = 0;
String acceleratorText = null;
IAction updatedAction = getAction();
String text = null;
accelerator = updatedAction.getAccelerator();
ExternalActionManager.ICallback callback = ExternalActionManager
.getInstance().getCallback();
// Block accelerators that are already in use.
if ((accelerator != 0) && (callback != null)
&& (callback.isAcceleratorInUse(accelerator))) {
accelerator = 0;
}
/*
* Process accelerators on GTK in a special way to avoid Bug
* 42009. We will override the native input method by
* allowing these reserved accelerators to be placed on the
* menu. We will only do this for "Ctrl+Shift+[0-9A-FU]".
*/
final String commandId = updatedAction
.getActionDefinitionId();
if (("gtk".equals(SWT.getPlatform())) && (callback instanceof IBindingManagerCallback) //$NON-NLS-1$
&& (commandId != null)) {
final IBindingManagerCallback bindingManagerCallback = (IBindingManagerCallback) callback;
final IKeyLookup lookup = KeyLookupFactory.getDefault();
final TriggerSequence[] triggerSequences = bindingManagerCallback
.getActiveBindingsFor(commandId);
for (int i = 0; i < triggerSequences.length; i++) {
final TriggerSequence triggerSequence = triggerSequences[i];
final Trigger[] triggers = triggerSequence
.getTriggers();
if (triggers.length == 1) {
final Trigger trigger = triggers[0];
if (trigger instanceof KeyStroke) {
final KeyStroke currentKeyStroke = (KeyStroke) trigger;
final int currentNaturalKey = currentKeyStroke
.getNaturalKey();
if ((currentKeyStroke.getModifierKeys() == (lookup
.getCtrl() | lookup.getShift()))
&& ((currentNaturalKey >= '0' && currentNaturalKey <= '9')
|| (currentNaturalKey >= 'A' && currentNaturalKey <= 'F') || (currentNaturalKey == 'U'))) {
accelerator = currentKeyStroke
.getModifierKeys()
| currentNaturalKey;
acceleratorText = triggerSequence
.format();
break;
}
}
}
}
}
if (accelerator == 0) {
if ((callback != null) && (commandId != null)) {
acceleratorText = callback
.getAcceleratorText(commandId);
}
} else {
acceleratorText = Action
.convertAccelerator(accelerator);
}
IContributionManagerOverrides overrides = null;
if (getParent() != null)
overrides = getParent().getOverrides();
if (overrides != null)
text = getParent().getOverrides().getText(this);
mi.setAccelerator(accelerator);
if (text == null)
text = updatedAction.getText();
if (text == null)
text = ""; //$NON-NLS-1$
else
text = Action.removeAcceleratorText(text);
if (acceleratorText == null)
mi.setText(text);
else
mi.setText(text + '\t' + acceleratorText);
}
if (imageChanged)
updateImages(false);
if (enableStateChanged) {
boolean shouldBeEnabled = action.isEnabled()
&& isEnabledAllowed();
if (mi.getEnabled() != shouldBeEnabled)
mi.setEnabled(shouldBeEnabled);
}
if (checkChanged) {
boolean bv = action.isChecked();
if (mi.getSelection() != bv)
mi.setSelection(bv);
}
return;
}
if (widget instanceof Button) {
Button button = (Button) widget;
if (imageChanged && updateImages(false))
textChanged = false; // don't update text if it has an image
if (textChanged) {
String text = action.getText();
if (text == null)
text = ""; //$NON-NLS-1$
else
text = Action.removeAcceleratorText(text);
button.setText(text);
}
if (tooltipTextChanged)
button.setToolTipText(action.getToolTipText());
if (enableStateChanged) {
boolean shouldBeEnabled = action.isEnabled()
&& isEnabledAllowed();
if (button.getEnabled() != shouldBeEnabled)
button.setEnabled(shouldBeEnabled);
}
if (checkChanged) {
boolean bv = action.isChecked();
if (button.getSelection() != bv)
button.setSelection(bv);
}
return;
}
}
}
|
diff --git a/src/main/java/signature/AbstractVertexSignature.java b/src/main/java/signature/AbstractVertexSignature.java
index 8febef4..f7598c2 100644
--- a/src/main/java/signature/AbstractVertexSignature.java
+++ b/src/main/java/signature/AbstractVertexSignature.java
@@ -1,544 +1,546 @@
package signature;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* The base class for signatures that are created from a vertex of a graph. A
* concrete derived class will implement the methods (getConnected,
* getVertexCount() etc.) that communicate between the graph and the signature.
*
* @author maclean
*
*/
public abstract class AbstractVertexSignature {
public static final char START_BRANCH_SYMBOL = '(';
public static final char END_BRANCH_SYMBOL = ')';
public static final char BLANK_SYMBOL = '\u0000';
private final char startNodeSymbol;
private final char endNodeSymbol;
/**
* If true, the signature uses start/end symbols to surround the node
*/
private final boolean hasNodeBracketSymbols;
private DAG dag;
/**
* If the signature is considered as a tree, the height is the maximum
* distance from the root to the leaves. A height of -1 is taken to mean
* the same as the maximum possible height, which is the graph diameter
*/
private int height;
/**
* The number of vertices from the graph that were visited to make the
* signature. This is either the number of vertices in the graph - if the
* height is equal to the graph diameter - or the number of vertices seen up
* to that height
*/
private int vertexCount;
/**
* Mapping between the vertex indices stored in the Nodes and the vertex
* indices in the original graph. This is necessary for signatures with a
* height less than the graph diameter. It is also the order in which the
* vertices were visited to make the DAG.
*/
private Map<Integer, Integer> vertexMapping;
private List<Integer> currentCanonicalLabelMapping;
private List<Integer> canonicalLabelMapping;
/**
* Create an abstract vertex signature with no start or end node symbols.
*/
public AbstractVertexSignature() {
startNodeSymbol = AbstractVertexSignature.BLANK_SYMBOL;
endNodeSymbol = AbstractVertexSignature.BLANK_SYMBOL;
hasNodeBracketSymbols = false;
this.vertexCount = 0;
this.currentCanonicalLabelMapping = new ArrayList<Integer>();
}
/**
* Create an abstract vertex signature with supplied start and end symbols.
*
* @param startNodeSymbol
* @param endNodeSymbol
*/
public AbstractVertexSignature(char startNodeSymbol, char endNodeSymbol) {
this.startNodeSymbol = startNodeSymbol;
this.endNodeSymbol = endNodeSymbol;
hasNodeBracketSymbols = true;
this.vertexCount = 0;
this.currentCanonicalLabelMapping = new ArrayList<Integer>();
}
/**
* Get the height of the signature.
*
* @return the height
*/
public int getHeight() {
return this.height;
}
/**
* Look up the original graph vertex that <code>vertexIndex</code> maps to.
*
* @param vertexIndex the internal vertex index that
* @return the vertex index in the original graph
*/
public int getOriginalVertexIndex(int vertexIndex) {
for (int originalVertexIndex : vertexMapping.keySet()) {
int internalVertexIndex = vertexMapping.get(originalVertexIndex);
if (internalVertexIndex == vertexIndex) {
return originalVertexIndex;
}
}
return -1;
}
/**
* This is a kind of constructor that builds the internal representation of
* the signature given the index of the vertex to use as a root.
*
* @param rootVertexIndex
* the index in the graph of the root for this signature
* @param graphVertexCount
* the number of vertices in the graph
*/
public void createMaximumHeight(int rootVertexIndex, int graphVertexCount) {
create(rootVertexIndex, graphVertexCount, -1);
}
/**
* This is a kind of constructor that builds the internal representation of
* the signature given the index of the vertex to use as a root. It also
* takes a maximum height, which limits how many vertices will be visited.
*
* @param rootVertexIndex
* the index in the graph of the root for this signature
* @param graphVertexCount
* the number of vertices in the graph
* @param height
* the maximum height of the signature
*/
public void create(int rootVertexIndex, int graphVertexCount, int height) {
this.height = height;
vertexMapping = new HashMap<Integer, Integer>();
vertexMapping.put(rootVertexIndex, 0);
dag = new DAG(0, graphVertexCount, getVertexSymbol(rootVertexIndex));
vertexCount = 1;
build(1, dag.getRootLayer(), new ArrayList<DAG.Arc>(), height);
dag.initialize(vertexCount);
}
private void build(int layer,
List<DAG.Node> previousLayer, List<DAG.Arc> usedArcs, int height) {
if (height == 0) return;
List<DAG.Node> nextLayer = new ArrayList<DAG.Node>();
List<DAG.Arc> layerArcs = new ArrayList<DAG.Arc>();
for (DAG.Node node : previousLayer) {
int mappedIndex = getOriginalVertexIndex(node.vertexIndex);
int[] connected = getConnected(mappedIndex);
Arrays.sort(connected);
for (int connectedVertex : connected) {
addNode(
layer, node, connectedVertex, layerArcs, usedArcs, nextLayer);
}
}
usedArcs.addAll(layerArcs);
if (nextLayer.isEmpty()) {
return;
} else {
dag.addLayer(nextLayer);
build(layer + 1, nextLayer, usedArcs, height - 1);
}
}
private void addNode(int layer, DAG.Node parentNode, int vertexIndex,
List<DAG.Arc> layerArcs, List<DAG.Arc> usedArcs,
List<DAG.Node> nextLayer) {
// look up the mapping or create a new mapping for the vertex index
int mappedVertexIndex;
if (vertexMapping.containsKey(vertexIndex)) {
mappedVertexIndex = vertexMapping.get(vertexIndex);
} else {
vertexMapping.put(vertexIndex, vertexCount);
mappedVertexIndex = vertexCount;
vertexCount++;
}
// System.out.println("layer " + layer + " parentNode " + parentNode +
// " vertexIndex " + vertexIndex + " mappedVertexIndex "
// + mappedVertexIndex + " " + vertexMapping);
// find an existing node if there is one
DAG.Arc arc = dag.new Arc(parentNode.vertexIndex, mappedVertexIndex);
if (usedArcs.contains(arc)) return;
DAG.Node existingNode = null;
for (DAG.Node otherNode : nextLayer) {
if (otherNode.vertexIndex == mappedVertexIndex) {
existingNode = otherNode;
break;
}
}
// if there isn't, make a new node and add it to the layer
if (existingNode == null) {
existingNode =
dag.makeNode(
mappedVertexIndex, layer, getVertexSymbol(vertexIndex));
nextLayer.add(existingNode);
}
dag.addRelation(existingNode, parentNode);
layerArcs.add(arc);
}
/**
* Convert this signature into a canonical signature string.
*
* @return the canonical string form
*/
public String toCanonicalString() {
StringBuffer stringBuffer = new StringBuffer();
this.canonize(1, stringBuffer);
return stringBuffer.toString();
}
/**
* Find the minimal signature string by trying all colors.
*
* @param color the current color to use
* @param canonicalVertexSignature the buffer to fill
*/
public void canonize(int color, StringBuffer canonicalVertexSignature) {
// assume that the atom invariants have been initialized
if (this.getVertexCount() == 0) return;
// Only add a new list of Integers if this is the first time this
// function is called for a particular root vertex.
// The labelling that corresponds to the mapping for the vertex
// signature should be the only one stored.
if ( color == 1 ) {
this.currentCanonicalLabelMapping = new ArrayList<Integer>();
}
this.dag.updateVertexInvariants();
List<Integer> orbit = this.dag.createOrbit();
if (orbit.size() < 2) {
// Color all uncolored atoms having two parents
// or more according to their invariant.
for (InvariantIntIntPair pair : this.dag.getInvariantPairs()) {
this.dag.setColor(pair.index, color);
color++;
}
// Creating the root signature string.
String signature = this.toString();
if (signature.compareTo(canonicalVertexSignature.toString()) > 0) {
int l = canonicalVertexSignature.length();
canonicalVertexSignature.replace(0, l, signature);
this.canonicalLabelMapping = this.currentCanonicalLabelMapping;
}
return;
} else {
for (int o : orbit) {
this.dag.setColor(o, color);
Invariants invariantsCopy = this.dag.copyInvariants();
this.canonize(color + 1, canonicalVertexSignature);
this.dag.setInvariants(invariantsCopy);
this.dag.setColor(o, 0);
}
}
}
/**
* Get a canonical labelling for this signature.
*
* @return
* the permutation necessary to transform the graph into a canonical form
*/
public int[] getCanonicalLabelling() {
CanonicalLabellingVisitor labeller =
new CanonicalLabellingVisitor(this.getVertexCount());
this.dag.accept(labeller);
return labeller.getLabelling();
}
public List<Integer> getCanonicalLabelMapping() {
return this.canonicalLabelMapping;
}
/**
* Get the number of vertices.
*
* @return the number of vertices seen when making the signature, which may
* be less than the number in the full graph, depending on the
* height
*/
public int getVertexCount() {
return this.vertexCount;
}
/**
* Get the symbol to use in the output signature string for this vertex of
* the input graph.
*
* @param vertexIndex the index of the vertex in the input graph
* @return a String symbol
*/
public abstract String getVertexSymbol(int vertexIndex);
/**
* Get a list of the indices of the vertices connected to the vertex with
* the supplied index.
*
* @param vertexIndex the index of the vertex to use
* @return the indices of connected vertices in the input graph
*/
public abstract int[] getConnected(int vertexIndex);
/**
* Get the symbol (if any) for the edge between the vertices with these two
* indices.
*
* @param vertexIndex the index of one of the vertices in the edge
* @param otherVertexIndex the index of the other vertex in the edge
* @return a string symbol for this edge
*/
public abstract String getEdgeSymbol(int vertexIndex, int otherVertexIndex);
/**
* Recursively print the signature into the buffer.
*
* @param buffer the string buffer to print into
* @param node the current node of the signature
* @param parent the parent node, or null
* @param arcs the list of already visited arcs
*/
private void print(StringBuffer buffer, DAG.Node node,
DAG.Node parent, List<DAG.Arc> arcs) {
+ int vertexIndex = getOriginalVertexIndex(node.vertexIndex);
// Add the vertexIndex to the labels if it hasn't already been added.
- if (!(this.currentCanonicalLabelMapping.contains(node.vertexIndex))) {
- this.currentCanonicalLabelMapping.add(node.vertexIndex);
+ if (!(this.currentCanonicalLabelMapping.contains(vertexIndex))) {
+ this.currentCanonicalLabelMapping.add(vertexIndex);
}
// print out any symbol for the edge in the input graph
if (parent != null) {
- buffer.append(getEdgeSymbol(node.vertexIndex, parent.vertexIndex));
+ int parentVertexIndex = getOriginalVertexIndex(parent.vertexIndex);
+ buffer.append(getEdgeSymbol(vertexIndex, parentVertexIndex));
}
// print out the text that represents the node itself
buffer.append(this.startNodeSymbol);
- buffer.append(getVertexSymbol(node.vertexIndex));
+ buffer.append(getVertexSymbol(vertexIndex));
int color = dag.colorFor(node.vertexIndex);
if (color != 0) {
buffer.append(',').append(color);
}
buffer.append(this.endNodeSymbol);
// Need to sort the children here, so that they are printed in an order
// according to their invariants.
Collections.sort(node.children);
// now print the sorted children, surrounded by branch symbols
boolean addedBranchSymbol = false;
for (DAG.Node child : node.children) {
DAG.Arc arc = dag.new Arc(node.vertexIndex, child.vertexIndex);
if (arcs.contains(arc)) {
continue;
} else {
if (!addedBranchSymbol) {
buffer.append(AbstractVertexSignature.START_BRANCH_SYMBOL);
addedBranchSymbol = true;
}
arcs.add(arc);
print(buffer, child, node, arcs);
}
}
if (addedBranchSymbol) {
buffer.append(AbstractVertexSignature.END_BRANCH_SYMBOL);
}
}
/*
* Convert this vertex signature into a signature string.
*/
public String toString() {
StringBuffer buffer = new StringBuffer();
print(buffer, this.dag.getRoot(), null, new ArrayList<DAG.Arc>());
return buffer.toString();
}
public List<Integer> groupwiseCanonicalLabelling(
List<SymmetryClass> symmetryClasses) {
List<Integer> labels = new ArrayList<Integer>();
groupwise(labels, symmetryClasses,
this.dag.getRoot(), new ArrayList<DAG.Arc>());
return labels;
}
private void groupwise(List<Integer> labels,
List<SymmetryClass> symmetryClasses,
DAG.Node node, List<DAG.Arc> arcs) {
int index = findIndex(node.vertexIndex, symmetryClasses, labels);
if (!labels.contains(index)) {
labels.add(index);
}
Collections.sort(node.children);
for (int i = 0; i < node.children.size(); i++) {
DAG.Node child = node.children.get(i);
DAG.Arc arc = dag.new Arc(node.vertexIndex, child.vertexIndex);
if (arcs.contains(arc)) {
continue;
} else {
arcs.add(arc);
groupwise(labels, symmetryClasses, child, arcs);
}
}
}
private int findIndex(int vertexIndex,
List<SymmetryClass> symmetryClasses, List<Integer> labels) {
for (SymmetryClass symmetryClass : symmetryClasses) {
int index = symmetryClass.getMinimal(vertexIndex, labels);
if (index == -1) {
continue;
} else {
return index;
}
}
// should really raise an exception here, as the symmetry classes must
// be a partition of the vertices...
return -1;
}
public List<Integer> postorderCanonicalLabelling() {
List<Integer> labelling = new ArrayList<Integer>();
postorder(labelling, this.dag.getRoot(), new ArrayList<DAG.Arc>());
return labelling;
}
private void postorder(
List<Integer> labelling, DAG.Node node, List<DAG.Arc> arcs) {
if (!labelling.contains(node.vertexIndex)) {
labelling.add(node.vertexIndex);
}
// for (int i = node.children.size() - 1; i > -1; i--) {
for (int i = 0; i < node.children.size(); i++) {
DAG.Node child = node.children.get(i);
DAG.Arc arc = dag.new Arc(node.vertexIndex, child.vertexIndex);
if (arcs.contains(arc)) {
continue;
} else {
arcs.add(arc);
postorder(labelling, child, arcs);
}
}
}
public static ColoredTree parseWithoutNodeSymbols(String s) {
// TODO FIXME for unlabelled graph signatures
ColoredTree tree = null;
ColoredTree.Node parent = null;
ColoredTree.Node current = null;
int currentHeight = 1;
int color = 0;
int j = 0;
int k = 0;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == AbstractVertexSignature.START_BRANCH_SYMBOL) {
parent = current;
currentHeight++;
tree.updateHeight(currentHeight);
} else if (c == AbstractVertexSignature.END_BRANCH_SYMBOL) {
parent = parent.parent;
currentHeight--;
} else if (c == ',') {
k = i + 1;
} else {
String ss;
if (k < j) { // no color
ss = s.substring(j, i);
color = 0;
} else { // color
ss = s.substring(j, k - 1);
color = Integer.parseInt(s.substring(k, i));
}
if (tree == null) {
tree = new ColoredTree(ss);
parent = tree.getRoot();
current = tree.getRoot();
} else {
current = tree.makeNode(ss, parent, currentHeight, color);
}
}
}
return tree;
}
public static ColoredTree parseWithNodeSymbols(
String s, char startNodeSymbol, char endNodeSymbol) {
ColoredTree tree = null;
ColoredTree.Node parent = null;
ColoredTree.Node current = null;
int currentHeight = 1;
int color = 0;
int j = 0;
int k = 0;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == AbstractVertexSignature.START_BRANCH_SYMBOL) {
parent = current;
currentHeight++;
tree.updateHeight(currentHeight);
} else if (c == AbstractVertexSignature.END_BRANCH_SYMBOL) {
parent = parent.parent;
currentHeight--;
} else if (c == startNodeSymbol) {
j = i + 1;
} else if (c == endNodeSymbol) {
String ss;
if (k < j) { // no color
ss = s.substring(j, i);
color = 0;
} else { // color
ss = s.substring(j, k - 1);
color = Integer.parseInt(s.substring(k, i));
}
if (tree == null) {
tree = new ColoredTree(ss);
parent = tree.getRoot();
current = tree.getRoot();
} else {
current = tree.makeNode(ss, parent, currentHeight, color);
}
} else if (c == ',') {
k = i + 1;
}
}
return tree;
}
}
| false | true | private void print(StringBuffer buffer, DAG.Node node,
DAG.Node parent, List<DAG.Arc> arcs) {
// Add the vertexIndex to the labels if it hasn't already been added.
if (!(this.currentCanonicalLabelMapping.contains(node.vertexIndex))) {
this.currentCanonicalLabelMapping.add(node.vertexIndex);
}
// print out any symbol for the edge in the input graph
if (parent != null) {
buffer.append(getEdgeSymbol(node.vertexIndex, parent.vertexIndex));
}
// print out the text that represents the node itself
buffer.append(this.startNodeSymbol);
buffer.append(getVertexSymbol(node.vertexIndex));
int color = dag.colorFor(node.vertexIndex);
if (color != 0) {
buffer.append(',').append(color);
}
buffer.append(this.endNodeSymbol);
// Need to sort the children here, so that they are printed in an order
// according to their invariants.
Collections.sort(node.children);
// now print the sorted children, surrounded by branch symbols
boolean addedBranchSymbol = false;
for (DAG.Node child : node.children) {
DAG.Arc arc = dag.new Arc(node.vertexIndex, child.vertexIndex);
if (arcs.contains(arc)) {
continue;
} else {
if (!addedBranchSymbol) {
buffer.append(AbstractVertexSignature.START_BRANCH_SYMBOL);
addedBranchSymbol = true;
}
arcs.add(arc);
print(buffer, child, node, arcs);
}
}
if (addedBranchSymbol) {
buffer.append(AbstractVertexSignature.END_BRANCH_SYMBOL);
}
}
| private void print(StringBuffer buffer, DAG.Node node,
DAG.Node parent, List<DAG.Arc> arcs) {
int vertexIndex = getOriginalVertexIndex(node.vertexIndex);
// Add the vertexIndex to the labels if it hasn't already been added.
if (!(this.currentCanonicalLabelMapping.contains(vertexIndex))) {
this.currentCanonicalLabelMapping.add(vertexIndex);
}
// print out any symbol for the edge in the input graph
if (parent != null) {
int parentVertexIndex = getOriginalVertexIndex(parent.vertexIndex);
buffer.append(getEdgeSymbol(vertexIndex, parentVertexIndex));
}
// print out the text that represents the node itself
buffer.append(this.startNodeSymbol);
buffer.append(getVertexSymbol(vertexIndex));
int color = dag.colorFor(node.vertexIndex);
if (color != 0) {
buffer.append(',').append(color);
}
buffer.append(this.endNodeSymbol);
// Need to sort the children here, so that they are printed in an order
// according to their invariants.
Collections.sort(node.children);
// now print the sorted children, surrounded by branch symbols
boolean addedBranchSymbol = false;
for (DAG.Node child : node.children) {
DAG.Arc arc = dag.new Arc(node.vertexIndex, child.vertexIndex);
if (arcs.contains(arc)) {
continue;
} else {
if (!addedBranchSymbol) {
buffer.append(AbstractVertexSignature.START_BRANCH_SYMBOL);
addedBranchSymbol = true;
}
arcs.add(arc);
print(buffer, child, node, arcs);
}
}
if (addedBranchSymbol) {
buffer.append(AbstractVertexSignature.END_BRANCH_SYMBOL);
}
}
|
diff --git a/src/org/opensolaris/opengrok/index/Indexer.java b/src/org/opensolaris/opengrok/index/Indexer.java
index 5486fa8..1a5b982 100644
--- a/src/org/opensolaris/opengrok/index/Indexer.java
+++ b/src/org/opensolaris/opengrok/index/Indexer.java
@@ -1,627 +1,627 @@
/*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the
* Common Development and Distribution License (the "License").
* You may not use this file except in compliance with the License.
*
* See LICENSE.txt included in this distribution for the specific
* language governing permissions and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each
* file and include the License file at LICENSE.txt.
* If applicable, add the following below this CDDL HEADER, with the
* fields enclosed by brackets "[]" replaced with your own identifying
* information: Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*/
/*
* Copyright 2007 Sun Microsystems, Inc. All rights reserved.
* Use is subject to license terms.
*/
package org.opensolaris.opengrok.index;
import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.opensolaris.opengrok.Info;
import org.opensolaris.opengrok.OpenGrokLogger;
import org.opensolaris.opengrok.analysis.AnalyzerGuru;
import org.opensolaris.opengrok.configuration.Project;
import org.opensolaris.opengrok.configuration.RuntimeEnvironment;
import org.opensolaris.opengrok.history.HistoryGuru;
import org.opensolaris.opengrok.util.Getopt;
/**
* Creates and updates an inverted source index
* as well as generates Xref, file stats etc., if specified
* in the options
*/
@SuppressWarnings({"PMD.AvoidPrintStackTrace", "PMD.SystemPrintln"})
public final class Indexer {
private final static String ON = "on";
private final static String OFF = "off";
private static Indexer index = new Indexer();
private static final Logger log = Logger.getLogger(Indexer.class.getName());
private static final String DERBY_EMBEDDED_DRIVER =
"org.apache.derby.jdbc.EmbeddedDriver";
private static final String DERBY_CLIENT_DRIVER =
"org.apache.derby.jdbc.ClientDriver";
public static Indexer getInstance() {
return index;
}
/**
* Program entry point
* @param argv argument vector
*/
@SuppressWarnings("PMD.UseStringBufferForStringAppends")
public static void main(String argv[]) {
RuntimeEnvironment env = RuntimeEnvironment.getInstance();
boolean runIndex = true;
boolean update = true;
boolean optimizedChanged = false;
CommandLineOptions cmdOptions = new CommandLineOptions();
if (argv.length == 0) {
System.err.println(cmdOptions.getUsage());
System.exit(1);
} else {
boolean searchRepositories = false;
ArrayList<String> subFiles = new ArrayList<String>();
ArrayList<String> repositories = new ArrayList<String>();
String configFilename = null;
String configHost = null;
boolean addProjects = false;
boolean refreshHistory = false;
String defaultProject = null;
boolean listFiles = false;
boolean createDict = false;
int noThreads = Runtime.getRuntime().availableProcessors();
// Parse command line options:
Getopt getopt = new Getopt(argv, cmdOptions.getCommandString());
try {
getopt.parse();
} catch (ParseException ex) {
System.err.println("OpenGrok: " + ex.getMessage());
System.err.println(cmdOptions.getUsage());
System.exit(1);
}
try {
int cmd;
// We need to read the configuration file first, since we
// will try to overwrite options..
while ((cmd = getopt.getOpt()) != -1) {
if (cmd == 'R') {
env.readConfiguration(new File(getopt.getOptarg()));
break;
}
}
String databaseDriver = env.getDatabaseDriver();
String databaseURL = env.getDatabaseUrl();
// Now we can handle all the other options..
getopt.reset();
while ((cmd = getopt.getOpt()) != -1) {
switch (cmd) {
case 't':
createDict = true;
runIndex = false;
break;
case 'q':
env.setVerbose(false);
break;
case 'e':
env.setGenerateHtml(false);
break;
case 'P':
addProjects = true;
break;
case 'p':
defaultProject = getopt.getOptarg();
break;
case 'c':
env.setCtags(getopt.getOptarg());
break;
case 'w':
{
String webapp = getopt.getOptarg();
if (webapp.charAt(0) != '/' && !webapp.startsWith("http")) {
webapp = "/" + webapp;
}
if (webapp.endsWith("/")) {
env.setUrlPrefix(webapp + "s?");
} else {
env.setUrlPrefix(webapp + "/s?");
}
}
break;
case 'W':
configFilename = getopt.getOptarg();
break;
case 'U':
configHost = getopt.getOptarg();
break;
case 'R':
// already handled
break;
case 'n':
runIndex = false;
break;
case 'H':
refreshHistory = true;
break;
case 'h':
repositories.add(getopt.getOptarg());
break;
case 'D':
env.setStoreHistoryCacheInDB(true);
break;
case 'j':
databaseDriver = getopt.getOptarg();
// Should be a full class name, but we also accept
// the shorthands "client" and "embedded". Expand
// the shorthands here.
- if (databaseDriver.equals("client")) {
+ if ("client".equals(databaseDriver)) {
databaseDriver = DERBY_CLIENT_DRIVER;
- } else if (databaseDriver.equals("embedded")) {
+ } else if ("embedded".equals(databaseDriver)) {
databaseDriver = DERBY_EMBEDDED_DRIVER;
}
break;
case 'u':
databaseURL = getopt.getOptarg();
break;
case 'r':
{
if (getopt.getOptarg().equalsIgnoreCase(ON)) {
env.setRemoteScmSupported(true);
} else if (getopt.getOptarg().equalsIgnoreCase(OFF)) {
env.setRemoteScmSupported(false);
} else {
System.err.println("ERROR: You should pass either \"on\" or \"off\" as argument to -r");
System.err.println(" Ex: \"-r on\" will allow retrival for remote SCM systems");
System.err.println(" \"-r off\" will ignore SCM for remote systems");
}
}
break;
case 'O':
{
boolean oldval = env.isOptimizeDatabase();
if (getopt.getOptarg().equalsIgnoreCase(ON)) {
env.setOptimizeDatabase(true);
} else if (getopt.getOptarg().equalsIgnoreCase(OFF)) {
env.setOptimizeDatabase(false);
} else {
System.err.println("ERROR: You should pass either \"on\" or \"off\" as argument to -O");
System.err.println(" Ex: \"-O on\" will optimize the database as part of the index generation");
System.err.println(" \"-O off\" disable optimization of the index database");
}
if (oldval != env.isOptimizeDatabase()) {
optimizedChanged = true;
}
}
break;
case 'v':
env.setVerbose(true);
break;
case 's':
{
env.setSourceRoot(getopt.getOptarg());
File file = env.getSourceRootFile();
if (!file.isDirectory()) {
System.err.println("ERROR: source root must be a directory: " + file.toString());
System.exit(1);
}
}
break;
case 'd':
{
env.setDataRoot(getopt.getOptarg());
File file = env.getDataRootFile();
if (!file.isDirectory()) {
System.err.println("ERROR: data root must be a directory: " + file.toString());
System.exit(1);
}
}
break;
case 'i':
env.getIgnoredNames().add(getopt.getOptarg());
break;
case 'S':
searchRepositories = true;
break;
case 'Q':
if (getopt.getOptarg().equalsIgnoreCase(ON)) {
env.setQuickContextScan(true);
} else if (getopt.getOptarg().equalsIgnoreCase(OFF)) {
env.setQuickContextScan(false);
} else {
System.err.println("ERROR: You should pass either \"on\" or \"off\" as argument to -Q");
System.err.println(" Ex: \"-Q on\" will just scan a \"chunk\" of the file and insert \"[..all..]\"");
System.err.println(" \"-Q off\" will try to build a more accurate list by reading the complete file.");
}
break;
case 'm': {
try {
env.setIndexWordLimit(Integer.parseInt(getopt.getOptarg()));
} catch (NumberFormatException exp) {
System.err.println("ERROR: Failed to parse argument to \"-m\": " + exp.getMessage());
System.exit(1);
}
break;
}
case 'a':
if (getopt.getOptarg().equalsIgnoreCase(ON)) {
env.setAllowLeadingWildcard(true);
} else if (getopt.getOptarg().equalsIgnoreCase(OFF)) {
env.setAllowLeadingWildcard(false);
} else {
System.err.println("ERROR: You should pass either \"on\" or \"off\" as argument to -a");
System.err.println(" Ex: \"-a on\" will allow a search to start with a wildcard");
System.err.println(" \"-a off\" will disallow a search to start with a wildcard");
System.exit(1);
}
break;
case 'A':
{
String[] arg = getopt.getOptarg().split(":");
if (arg.length != 2) {
System.err.println("ERROR: You must specify: -A extension:class");
System.err.println(" Ex: -A foo:org.opensolaris.opengrok.analysis.c.CAnalyzer");
System.err.println(" will use the C analyzer for all files ending with .foo");
System.err.println(" Ex: -A c:-");
System.err.println(" will disable the c-analyzer for for all files ending with .c");
System.exit(1);
}
arg[0] = arg[0].substring(arg[0].lastIndexOf('.') + 1).toUpperCase();
if (arg[1].equals("-")) {
AnalyzerGuru.addExtension(arg[0], null);
break;
}
try {
AnalyzerGuru.addExtension(
arg[0],
AnalyzerGuru.findFactory(arg[1]));
} catch (Exception e) {
System.err.println("Unable to use " + arg[1] +
" as a FileAnalyzerFactory");
e.printStackTrace();
System.exit(1);
}
}
break;
case 'L':
env.setWebappLAF(getopt.getOptarg());
break;
case 'T':
try {
noThreads = Integer.parseInt(getopt.getOptarg());
} catch (NumberFormatException exp) {
System.err.println("ERROR: Failed to parse argument to \"-T\": " + exp.getMessage());
System.exit(1);
}
break;
case 'l':
if (getopt.getOptarg().equalsIgnoreCase(ON)) {
env.setUsingLuceneLocking(true);
} else if (getopt.getOptarg().equalsIgnoreCase(OFF)) {
env.setUsingLuceneLocking(false);
} else {
System.err.println("ERROR: You should pass either \"on\" or \"off\" as argument to -l");
System.err.println(" Ex: \"-l on\" will enable locks in Lucene");
System.err.println(" \"-l off\" will disable locks in Lucene");
}
break;
case 'V':
System.out.println(Info.getFullVersion());
System.exit(0);
break;
case '?':
System.err.println(cmdOptions.getUsage());
System.exit(0);
break;
default:
System.err.println("Internal Error - Unimplemented cmdline option: " + (char) cmd);
System.exit(1);
}
}
int optind = getopt.getOptind();
if (optind != -1) {
while (optind < argv.length) {
subFiles.add(argv[optind]);
++optind;
}
}
if (env.storeHistoryCacheInDB()) {
// The default database driver is Derby's client driver.
if (databaseDriver == null) {
databaseDriver = DERBY_CLIENT_DRIVER;
}
// The default URL depends on the database driver.
if (databaseURL == null) {
StringBuilder defaultURL = new StringBuilder();
defaultURL.append("jdbc:derby:");
if (databaseDriver.equals(DERBY_EMBEDDED_DRIVER)) {
defaultURL
.append(env.getDataRootPath())
.append(File.separator);
} else {
defaultURL.append("//localhost/");
}
defaultURL.append("cachedb;create=true");
databaseURL = defaultURL.toString();
}
}
env.setDatabaseDriver(databaseDriver);
env.setDatabaseUrl(databaseURL);
getInstance().prepareIndexer(env, searchRepositories, addProjects,
defaultProject, configFilename, refreshHistory,
listFiles, createDict, subFiles, repositories);
if (runIndex || (optimizedChanged && env.isOptimizeDatabase())) {
IndexChangedListener progress = new DefaultIndexChangedListener();
getInstance().doIndexerExecution(update, noThreads, subFiles,
progress);
}
getInstance().sendToConfigHost(env, configHost);
} catch (IndexerException ex) {
OpenGrokLogger.getLogger().log(Level.SEVERE, "Exception running indexer", ex);
System.err.println(cmdOptions.getUsage());
System.exit(1);
} catch (IOException ioe) {
System.err.println("Got IOException " + ioe);
OpenGrokLogger.getLogger().log(Level.SEVERE, "Exception running indexer", ioe);
System.exit(1);
}
}
}
public void prepareIndexer(RuntimeEnvironment env,
boolean searchRepositories,
boolean addProjects,
String defaultProject,
String configFilename,
boolean refreshHistory,
boolean listFiles,
boolean createDict,
List<String> subFiles,
List<String> repositories) throws IndexerException, IOException {
if (env.getDataRootPath() == null) {
throw new IndexerException("ERROR: Please specify a DATA ROOT path");
}
if (env.getSourceRootFile() == null) {
throw new IndexerException("ERROR: please specify a SRC_ROOT with option -s !");
}
if (!env.validateExuberantCtags()) {
throw new IndexerException("Didn't find Exuberant Ctags");
}
if (searchRepositories) {
if (env.isVerbose()) {
System.out.println("Scanning for repositories...");
}
long start = System.currentTimeMillis();
HistoryGuru.getInstance().addRepositories(env.getSourceRootPath());
long time = (System.currentTimeMillis() - start) / 1000;
if (env.isVerbose()) {
System.out.println("Done searching for repositories (" + time + "s)");
}
}
if (addProjects) {
File files[] = env.getSourceRootFile().listFiles();
List<Project> projects = env.getProjects();
projects.clear();
for (File file : files) {
if (!file.getName().startsWith(".") && file.isDirectory()) {
Project p = new Project();
String name = file.getName();
p.setDescription(name);
p.setPath("/" + name);
projects.add(p);
}
}
// The projects should be sorted...
Collections.sort(projects, new Comparator<Project>() {
public int compare(Project p1, Project p2) {
String s1 = p1.getDescription();
String s2 = p2.getDescription();
int ret;
if (s1 == null) {
ret = (s2 == null) ? 0 : 1;
} else {
ret = s1.compareTo(s2);
}
return ret;
}
});
}
if (defaultProject != null) {
for (Project p : env.getProjects()) {
if (p.getPath().equals(defaultProject)) {
env.setDefaultProject(p);
break;
}
}
}
if (configFilename != null) {
if (env.isVerbose()) {
System.out.println("Writing configuration to " + configFilename);
System.out.flush();
}
env.writeConfiguration(new File(configFilename));
if (env.isVerbose()) {
System.out.println("Done...");
System.out.flush();
}
}
if (refreshHistory) {
HistoryGuru.getInstance().createCache();
} else if (repositories != null && !repositories.isEmpty()) {
HistoryGuru.getInstance().createCache(repositories);
}
if (listFiles) {
IndexDatabase.listAllFiles(subFiles);
}
if (createDict) {
IndexDatabase.listFrequentTokens(subFiles);
}
}
public void doIndexerExecution(final boolean update, int noThreads, List<String> subFiles,
IndexChangedListener progress)
throws IOException {
RuntimeEnvironment env = RuntimeEnvironment.getInstance();
env.register();
log.info("Starting indexExecution");
ExecutorService executor = Executors.newFixedThreadPool(noThreads);
if (subFiles == null || subFiles.isEmpty()) {
if (update) {
IndexDatabase.updateAll(executor, progress);
} else if (env.isOptimizeDatabase()) {
IndexDatabase.optimizeAll(executor);
}
} else {
List<IndexDatabase> dbs = new ArrayList<IndexDatabase>();
for (String path : subFiles) {
Project project = Project.getProject(path);
if (project == null && env.hasProjects()) {
System.err.println("Warning: Could not find a project for \"" + path + "\"");
} else {
IndexDatabase db;
if (project == null) {
db = new IndexDatabase();
} else {
db = new IndexDatabase(project);
}
int idx = dbs.indexOf(db);
if (idx != -1) {
db = dbs.get(idx);
}
if (db.addDirectory(path)) {
if (idx == -1) {
dbs.add(db);
}
} else {
System.err.println("Warning: Directory does not exist \"" + path + "\"");
}
}
}
for (final IndexDatabase db : dbs) {
final boolean optimize = env.isOptimizeDatabase();
db.addIndexChangedListener(progress);
executor.submit(new Runnable() {
public void run() {
try {
if (update) {
db.update();
} else if (optimize) {
db.optimize();
}
} catch (Exception e) {
if (update) {
OpenGrokLogger.getLogger().log(Level.WARNING, "An error occured while updating index", e);
} else {
OpenGrokLogger.getLogger().log(Level.WARNING, "An error occured while optimizing index", e);
}
e.printStackTrace();
}
}
});
}
}
executor.shutdown();
while (!executor.isTerminated()) {
try {
// Wait forever
// @newjdk : 999,TimeUnit.DAYS
executor.awaitTermination(999*60*60*24, TimeUnit.SECONDS);
} catch (InterruptedException exp) {
OpenGrokLogger.getLogger().log(Level.WARNING, "Received interrupt while waiting for executor to finish", exp);
}
}
}
public void sendToConfigHost(RuntimeEnvironment env, String configHost) {
if (configHost != null) {
String[] cfg = configHost.split(":");
if (env.isVerbose()) {
log.info("Send configuration to: " + configHost);
}
if (cfg.length == 2) {
try {
InetAddress host = InetAddress.getByName(cfg[0]);
RuntimeEnvironment.getInstance().writeConfiguration(host, Integer.parseInt(cfg[1]));
} catch (Exception ex) {
log.log(Level.SEVERE, "Failed to send configuration to " + configHost, ex);
}
} else {
System.err.println("Syntax error: ");
for (String s : cfg) {
System.err.print("[" + s + "]");
}
System.err.println();
}
if (env.isVerbose()) {
log.info("Configuration successfully updated");
}
}
}
private Indexer() {
}
}
| false | true | public static void main(String argv[]) {
RuntimeEnvironment env = RuntimeEnvironment.getInstance();
boolean runIndex = true;
boolean update = true;
boolean optimizedChanged = false;
CommandLineOptions cmdOptions = new CommandLineOptions();
if (argv.length == 0) {
System.err.println(cmdOptions.getUsage());
System.exit(1);
} else {
boolean searchRepositories = false;
ArrayList<String> subFiles = new ArrayList<String>();
ArrayList<String> repositories = new ArrayList<String>();
String configFilename = null;
String configHost = null;
boolean addProjects = false;
boolean refreshHistory = false;
String defaultProject = null;
boolean listFiles = false;
boolean createDict = false;
int noThreads = Runtime.getRuntime().availableProcessors();
// Parse command line options:
Getopt getopt = new Getopt(argv, cmdOptions.getCommandString());
try {
getopt.parse();
} catch (ParseException ex) {
System.err.println("OpenGrok: " + ex.getMessage());
System.err.println(cmdOptions.getUsage());
System.exit(1);
}
try {
int cmd;
// We need to read the configuration file first, since we
// will try to overwrite options..
while ((cmd = getopt.getOpt()) != -1) {
if (cmd == 'R') {
env.readConfiguration(new File(getopt.getOptarg()));
break;
}
}
String databaseDriver = env.getDatabaseDriver();
String databaseURL = env.getDatabaseUrl();
// Now we can handle all the other options..
getopt.reset();
while ((cmd = getopt.getOpt()) != -1) {
switch (cmd) {
case 't':
createDict = true;
runIndex = false;
break;
case 'q':
env.setVerbose(false);
break;
case 'e':
env.setGenerateHtml(false);
break;
case 'P':
addProjects = true;
break;
case 'p':
defaultProject = getopt.getOptarg();
break;
case 'c':
env.setCtags(getopt.getOptarg());
break;
case 'w':
{
String webapp = getopt.getOptarg();
if (webapp.charAt(0) != '/' && !webapp.startsWith("http")) {
webapp = "/" + webapp;
}
if (webapp.endsWith("/")) {
env.setUrlPrefix(webapp + "s?");
} else {
env.setUrlPrefix(webapp + "/s?");
}
}
break;
case 'W':
configFilename = getopt.getOptarg();
break;
case 'U':
configHost = getopt.getOptarg();
break;
case 'R':
// already handled
break;
case 'n':
runIndex = false;
break;
case 'H':
refreshHistory = true;
break;
case 'h':
repositories.add(getopt.getOptarg());
break;
case 'D':
env.setStoreHistoryCacheInDB(true);
break;
case 'j':
databaseDriver = getopt.getOptarg();
// Should be a full class name, but we also accept
// the shorthands "client" and "embedded". Expand
// the shorthands here.
if (databaseDriver.equals("client")) {
databaseDriver = DERBY_CLIENT_DRIVER;
} else if (databaseDriver.equals("embedded")) {
databaseDriver = DERBY_EMBEDDED_DRIVER;
}
break;
case 'u':
databaseURL = getopt.getOptarg();
break;
case 'r':
{
if (getopt.getOptarg().equalsIgnoreCase(ON)) {
env.setRemoteScmSupported(true);
} else if (getopt.getOptarg().equalsIgnoreCase(OFF)) {
env.setRemoteScmSupported(false);
} else {
System.err.println("ERROR: You should pass either \"on\" or \"off\" as argument to -r");
System.err.println(" Ex: \"-r on\" will allow retrival for remote SCM systems");
System.err.println(" \"-r off\" will ignore SCM for remote systems");
}
}
break;
case 'O':
{
boolean oldval = env.isOptimizeDatabase();
if (getopt.getOptarg().equalsIgnoreCase(ON)) {
env.setOptimizeDatabase(true);
} else if (getopt.getOptarg().equalsIgnoreCase(OFF)) {
env.setOptimizeDatabase(false);
} else {
System.err.println("ERROR: You should pass either \"on\" or \"off\" as argument to -O");
System.err.println(" Ex: \"-O on\" will optimize the database as part of the index generation");
System.err.println(" \"-O off\" disable optimization of the index database");
}
if (oldval != env.isOptimizeDatabase()) {
optimizedChanged = true;
}
}
break;
case 'v':
env.setVerbose(true);
break;
case 's':
{
env.setSourceRoot(getopt.getOptarg());
File file = env.getSourceRootFile();
if (!file.isDirectory()) {
System.err.println("ERROR: source root must be a directory: " + file.toString());
System.exit(1);
}
}
break;
case 'd':
{
env.setDataRoot(getopt.getOptarg());
File file = env.getDataRootFile();
if (!file.isDirectory()) {
System.err.println("ERROR: data root must be a directory: " + file.toString());
System.exit(1);
}
}
break;
case 'i':
env.getIgnoredNames().add(getopt.getOptarg());
break;
case 'S':
searchRepositories = true;
break;
case 'Q':
if (getopt.getOptarg().equalsIgnoreCase(ON)) {
env.setQuickContextScan(true);
} else if (getopt.getOptarg().equalsIgnoreCase(OFF)) {
env.setQuickContextScan(false);
} else {
System.err.println("ERROR: You should pass either \"on\" or \"off\" as argument to -Q");
System.err.println(" Ex: \"-Q on\" will just scan a \"chunk\" of the file and insert \"[..all..]\"");
System.err.println(" \"-Q off\" will try to build a more accurate list by reading the complete file.");
}
break;
case 'm': {
try {
env.setIndexWordLimit(Integer.parseInt(getopt.getOptarg()));
} catch (NumberFormatException exp) {
System.err.println("ERROR: Failed to parse argument to \"-m\": " + exp.getMessage());
System.exit(1);
}
break;
}
case 'a':
if (getopt.getOptarg().equalsIgnoreCase(ON)) {
env.setAllowLeadingWildcard(true);
} else if (getopt.getOptarg().equalsIgnoreCase(OFF)) {
env.setAllowLeadingWildcard(false);
} else {
System.err.println("ERROR: You should pass either \"on\" or \"off\" as argument to -a");
System.err.println(" Ex: \"-a on\" will allow a search to start with a wildcard");
System.err.println(" \"-a off\" will disallow a search to start with a wildcard");
System.exit(1);
}
break;
case 'A':
{
String[] arg = getopt.getOptarg().split(":");
if (arg.length != 2) {
System.err.println("ERROR: You must specify: -A extension:class");
System.err.println(" Ex: -A foo:org.opensolaris.opengrok.analysis.c.CAnalyzer");
System.err.println(" will use the C analyzer for all files ending with .foo");
System.err.println(" Ex: -A c:-");
System.err.println(" will disable the c-analyzer for for all files ending with .c");
System.exit(1);
}
arg[0] = arg[0].substring(arg[0].lastIndexOf('.') + 1).toUpperCase();
if (arg[1].equals("-")) {
AnalyzerGuru.addExtension(arg[0], null);
break;
}
try {
AnalyzerGuru.addExtension(
arg[0],
AnalyzerGuru.findFactory(arg[1]));
} catch (Exception e) {
System.err.println("Unable to use " + arg[1] +
" as a FileAnalyzerFactory");
e.printStackTrace();
System.exit(1);
}
}
break;
case 'L':
env.setWebappLAF(getopt.getOptarg());
break;
case 'T':
try {
noThreads = Integer.parseInt(getopt.getOptarg());
} catch (NumberFormatException exp) {
System.err.println("ERROR: Failed to parse argument to \"-T\": " + exp.getMessage());
System.exit(1);
}
break;
case 'l':
if (getopt.getOptarg().equalsIgnoreCase(ON)) {
env.setUsingLuceneLocking(true);
} else if (getopt.getOptarg().equalsIgnoreCase(OFF)) {
env.setUsingLuceneLocking(false);
} else {
System.err.println("ERROR: You should pass either \"on\" or \"off\" as argument to -l");
System.err.println(" Ex: \"-l on\" will enable locks in Lucene");
System.err.println(" \"-l off\" will disable locks in Lucene");
}
break;
case 'V':
System.out.println(Info.getFullVersion());
System.exit(0);
break;
case '?':
System.err.println(cmdOptions.getUsage());
System.exit(0);
break;
default:
System.err.println("Internal Error - Unimplemented cmdline option: " + (char) cmd);
System.exit(1);
}
}
int optind = getopt.getOptind();
if (optind != -1) {
while (optind < argv.length) {
subFiles.add(argv[optind]);
++optind;
}
}
if (env.storeHistoryCacheInDB()) {
// The default database driver is Derby's client driver.
if (databaseDriver == null) {
databaseDriver = DERBY_CLIENT_DRIVER;
}
// The default URL depends on the database driver.
if (databaseURL == null) {
StringBuilder defaultURL = new StringBuilder();
defaultURL.append("jdbc:derby:");
if (databaseDriver.equals(DERBY_EMBEDDED_DRIVER)) {
defaultURL
.append(env.getDataRootPath())
.append(File.separator);
} else {
defaultURL.append("//localhost/");
}
defaultURL.append("cachedb;create=true");
databaseURL = defaultURL.toString();
}
}
env.setDatabaseDriver(databaseDriver);
env.setDatabaseUrl(databaseURL);
getInstance().prepareIndexer(env, searchRepositories, addProjects,
defaultProject, configFilename, refreshHistory,
listFiles, createDict, subFiles, repositories);
if (runIndex || (optimizedChanged && env.isOptimizeDatabase())) {
IndexChangedListener progress = new DefaultIndexChangedListener();
getInstance().doIndexerExecution(update, noThreads, subFiles,
progress);
}
getInstance().sendToConfigHost(env, configHost);
} catch (IndexerException ex) {
OpenGrokLogger.getLogger().log(Level.SEVERE, "Exception running indexer", ex);
System.err.println(cmdOptions.getUsage());
System.exit(1);
} catch (IOException ioe) {
System.err.println("Got IOException " + ioe);
OpenGrokLogger.getLogger().log(Level.SEVERE, "Exception running indexer", ioe);
System.exit(1);
}
}
}
| public static void main(String argv[]) {
RuntimeEnvironment env = RuntimeEnvironment.getInstance();
boolean runIndex = true;
boolean update = true;
boolean optimizedChanged = false;
CommandLineOptions cmdOptions = new CommandLineOptions();
if (argv.length == 0) {
System.err.println(cmdOptions.getUsage());
System.exit(1);
} else {
boolean searchRepositories = false;
ArrayList<String> subFiles = new ArrayList<String>();
ArrayList<String> repositories = new ArrayList<String>();
String configFilename = null;
String configHost = null;
boolean addProjects = false;
boolean refreshHistory = false;
String defaultProject = null;
boolean listFiles = false;
boolean createDict = false;
int noThreads = Runtime.getRuntime().availableProcessors();
// Parse command line options:
Getopt getopt = new Getopt(argv, cmdOptions.getCommandString());
try {
getopt.parse();
} catch (ParseException ex) {
System.err.println("OpenGrok: " + ex.getMessage());
System.err.println(cmdOptions.getUsage());
System.exit(1);
}
try {
int cmd;
// We need to read the configuration file first, since we
// will try to overwrite options..
while ((cmd = getopt.getOpt()) != -1) {
if (cmd == 'R') {
env.readConfiguration(new File(getopt.getOptarg()));
break;
}
}
String databaseDriver = env.getDatabaseDriver();
String databaseURL = env.getDatabaseUrl();
// Now we can handle all the other options..
getopt.reset();
while ((cmd = getopt.getOpt()) != -1) {
switch (cmd) {
case 't':
createDict = true;
runIndex = false;
break;
case 'q':
env.setVerbose(false);
break;
case 'e':
env.setGenerateHtml(false);
break;
case 'P':
addProjects = true;
break;
case 'p':
defaultProject = getopt.getOptarg();
break;
case 'c':
env.setCtags(getopt.getOptarg());
break;
case 'w':
{
String webapp = getopt.getOptarg();
if (webapp.charAt(0) != '/' && !webapp.startsWith("http")) {
webapp = "/" + webapp;
}
if (webapp.endsWith("/")) {
env.setUrlPrefix(webapp + "s?");
} else {
env.setUrlPrefix(webapp + "/s?");
}
}
break;
case 'W':
configFilename = getopt.getOptarg();
break;
case 'U':
configHost = getopt.getOptarg();
break;
case 'R':
// already handled
break;
case 'n':
runIndex = false;
break;
case 'H':
refreshHistory = true;
break;
case 'h':
repositories.add(getopt.getOptarg());
break;
case 'D':
env.setStoreHistoryCacheInDB(true);
break;
case 'j':
databaseDriver = getopt.getOptarg();
// Should be a full class name, but we also accept
// the shorthands "client" and "embedded". Expand
// the shorthands here.
if ("client".equals(databaseDriver)) {
databaseDriver = DERBY_CLIENT_DRIVER;
} else if ("embedded".equals(databaseDriver)) {
databaseDriver = DERBY_EMBEDDED_DRIVER;
}
break;
case 'u':
databaseURL = getopt.getOptarg();
break;
case 'r':
{
if (getopt.getOptarg().equalsIgnoreCase(ON)) {
env.setRemoteScmSupported(true);
} else if (getopt.getOptarg().equalsIgnoreCase(OFF)) {
env.setRemoteScmSupported(false);
} else {
System.err.println("ERROR: You should pass either \"on\" or \"off\" as argument to -r");
System.err.println(" Ex: \"-r on\" will allow retrival for remote SCM systems");
System.err.println(" \"-r off\" will ignore SCM for remote systems");
}
}
break;
case 'O':
{
boolean oldval = env.isOptimizeDatabase();
if (getopt.getOptarg().equalsIgnoreCase(ON)) {
env.setOptimizeDatabase(true);
} else if (getopt.getOptarg().equalsIgnoreCase(OFF)) {
env.setOptimizeDatabase(false);
} else {
System.err.println("ERROR: You should pass either \"on\" or \"off\" as argument to -O");
System.err.println(" Ex: \"-O on\" will optimize the database as part of the index generation");
System.err.println(" \"-O off\" disable optimization of the index database");
}
if (oldval != env.isOptimizeDatabase()) {
optimizedChanged = true;
}
}
break;
case 'v':
env.setVerbose(true);
break;
case 's':
{
env.setSourceRoot(getopt.getOptarg());
File file = env.getSourceRootFile();
if (!file.isDirectory()) {
System.err.println("ERROR: source root must be a directory: " + file.toString());
System.exit(1);
}
}
break;
case 'd':
{
env.setDataRoot(getopt.getOptarg());
File file = env.getDataRootFile();
if (!file.isDirectory()) {
System.err.println("ERROR: data root must be a directory: " + file.toString());
System.exit(1);
}
}
break;
case 'i':
env.getIgnoredNames().add(getopt.getOptarg());
break;
case 'S':
searchRepositories = true;
break;
case 'Q':
if (getopt.getOptarg().equalsIgnoreCase(ON)) {
env.setQuickContextScan(true);
} else if (getopt.getOptarg().equalsIgnoreCase(OFF)) {
env.setQuickContextScan(false);
} else {
System.err.println("ERROR: You should pass either \"on\" or \"off\" as argument to -Q");
System.err.println(" Ex: \"-Q on\" will just scan a \"chunk\" of the file and insert \"[..all..]\"");
System.err.println(" \"-Q off\" will try to build a more accurate list by reading the complete file.");
}
break;
case 'm': {
try {
env.setIndexWordLimit(Integer.parseInt(getopt.getOptarg()));
} catch (NumberFormatException exp) {
System.err.println("ERROR: Failed to parse argument to \"-m\": " + exp.getMessage());
System.exit(1);
}
break;
}
case 'a':
if (getopt.getOptarg().equalsIgnoreCase(ON)) {
env.setAllowLeadingWildcard(true);
} else if (getopt.getOptarg().equalsIgnoreCase(OFF)) {
env.setAllowLeadingWildcard(false);
} else {
System.err.println("ERROR: You should pass either \"on\" or \"off\" as argument to -a");
System.err.println(" Ex: \"-a on\" will allow a search to start with a wildcard");
System.err.println(" \"-a off\" will disallow a search to start with a wildcard");
System.exit(1);
}
break;
case 'A':
{
String[] arg = getopt.getOptarg().split(":");
if (arg.length != 2) {
System.err.println("ERROR: You must specify: -A extension:class");
System.err.println(" Ex: -A foo:org.opensolaris.opengrok.analysis.c.CAnalyzer");
System.err.println(" will use the C analyzer for all files ending with .foo");
System.err.println(" Ex: -A c:-");
System.err.println(" will disable the c-analyzer for for all files ending with .c");
System.exit(1);
}
arg[0] = arg[0].substring(arg[0].lastIndexOf('.') + 1).toUpperCase();
if (arg[1].equals("-")) {
AnalyzerGuru.addExtension(arg[0], null);
break;
}
try {
AnalyzerGuru.addExtension(
arg[0],
AnalyzerGuru.findFactory(arg[1]));
} catch (Exception e) {
System.err.println("Unable to use " + arg[1] +
" as a FileAnalyzerFactory");
e.printStackTrace();
System.exit(1);
}
}
break;
case 'L':
env.setWebappLAF(getopt.getOptarg());
break;
case 'T':
try {
noThreads = Integer.parseInt(getopt.getOptarg());
} catch (NumberFormatException exp) {
System.err.println("ERROR: Failed to parse argument to \"-T\": " + exp.getMessage());
System.exit(1);
}
break;
case 'l':
if (getopt.getOptarg().equalsIgnoreCase(ON)) {
env.setUsingLuceneLocking(true);
} else if (getopt.getOptarg().equalsIgnoreCase(OFF)) {
env.setUsingLuceneLocking(false);
} else {
System.err.println("ERROR: You should pass either \"on\" or \"off\" as argument to -l");
System.err.println(" Ex: \"-l on\" will enable locks in Lucene");
System.err.println(" \"-l off\" will disable locks in Lucene");
}
break;
case 'V':
System.out.println(Info.getFullVersion());
System.exit(0);
break;
case '?':
System.err.println(cmdOptions.getUsage());
System.exit(0);
break;
default:
System.err.println("Internal Error - Unimplemented cmdline option: " + (char) cmd);
System.exit(1);
}
}
int optind = getopt.getOptind();
if (optind != -1) {
while (optind < argv.length) {
subFiles.add(argv[optind]);
++optind;
}
}
if (env.storeHistoryCacheInDB()) {
// The default database driver is Derby's client driver.
if (databaseDriver == null) {
databaseDriver = DERBY_CLIENT_DRIVER;
}
// The default URL depends on the database driver.
if (databaseURL == null) {
StringBuilder defaultURL = new StringBuilder();
defaultURL.append("jdbc:derby:");
if (databaseDriver.equals(DERBY_EMBEDDED_DRIVER)) {
defaultURL
.append(env.getDataRootPath())
.append(File.separator);
} else {
defaultURL.append("//localhost/");
}
defaultURL.append("cachedb;create=true");
databaseURL = defaultURL.toString();
}
}
env.setDatabaseDriver(databaseDriver);
env.setDatabaseUrl(databaseURL);
getInstance().prepareIndexer(env, searchRepositories, addProjects,
defaultProject, configFilename, refreshHistory,
listFiles, createDict, subFiles, repositories);
if (runIndex || (optimizedChanged && env.isOptimizeDatabase())) {
IndexChangedListener progress = new DefaultIndexChangedListener();
getInstance().doIndexerExecution(update, noThreads, subFiles,
progress);
}
getInstance().sendToConfigHost(env, configHost);
} catch (IndexerException ex) {
OpenGrokLogger.getLogger().log(Level.SEVERE, "Exception running indexer", ex);
System.err.println(cmdOptions.getUsage());
System.exit(1);
} catch (IOException ioe) {
System.err.println("Got IOException " + ioe);
OpenGrokLogger.getLogger().log(Level.SEVERE, "Exception running indexer", ioe);
System.exit(1);
}
}
}
|
diff --git a/src/java/org/infoglue/cms/applications/structuretool/actions/ViewListSiteNodeVersionAction.java b/src/java/org/infoglue/cms/applications/structuretool/actions/ViewListSiteNodeVersionAction.java
index 89f4961ae..005c88520 100755
--- a/src/java/org/infoglue/cms/applications/structuretool/actions/ViewListSiteNodeVersionAction.java
+++ b/src/java/org/infoglue/cms/applications/structuretool/actions/ViewListSiteNodeVersionAction.java
@@ -1,254 +1,254 @@
/* ===============================================================================
*
* Part of the InfoGlue SiteNode Management Platform (www.infoglue.org)
*
* ===============================================================================
*
* Copyright (C)
*
* 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. See the file LICENSE.html for more information.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY, including the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc. / 59 Temple
* Place, Suite 330 / Boston, MA 02111-1307 / USA.
*
* ===============================================================================
*/
package org.infoglue.cms.applications.structuretool.actions;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import org.apache.log4j.Logger;
import org.infoglue.cms.applications.common.actions.InfoGlueAbstractAction;
import org.infoglue.cms.applications.databeans.LinkBean;
import org.infoglue.cms.controllers.kernel.impl.simple.AccessRightController;
import org.infoglue.cms.controllers.kernel.impl.simple.ContentControllerProxy;
import org.infoglue.cms.controllers.kernel.impl.simple.ContentVersionController;
import org.infoglue.cms.controllers.kernel.impl.simple.LanguageController;
import org.infoglue.cms.controllers.kernel.impl.simple.RepositoryController;
import org.infoglue.cms.controllers.kernel.impl.simple.SiteNodeVersionController;
import org.infoglue.cms.controllers.kernel.impl.simple.SiteNodeVersionControllerProxy;
import org.infoglue.cms.entities.content.ContentVO;
import org.infoglue.cms.entities.content.ContentVersionVO;
import org.infoglue.cms.entities.management.LanguageVO;
import org.infoglue.cms.entities.management.RepositoryVO;
import org.infoglue.cms.entities.structure.SiteNodeVersionVO;
import org.infoglue.cms.exception.AccessConstraintException;
import org.infoglue.cms.util.AccessConstraintExceptionBuffer;
import org.infoglue.cms.util.CmsPropertyHandler;
import org.infoglue.cms.util.sorters.ReflectionComparator;
/**
*
* @author Mattias Bogeblad
*
* Present a list of siteNodeVersions under a given siteNode, recursing down in the hierarcy.
* Used to publish an entire hierarchy of pages.
*
*/
public class ViewListSiteNodeVersionAction extends InfoGlueAbstractAction
{
private final static Logger logger = Logger.getLogger(ViewListSiteNodeVersionAction.class.getName());
private static final long serialVersionUID = 1L;
private Set siteNodeVersionVOList = new TreeSet(Collections.reverseOrder(new ReflectionComparator("modifiedDateTime")));
private Set contentVersionVOList = new TreeSet(Collections.reverseOrder(new ReflectionComparator("modifiedDateTime")));
private Integer siteNodeVersionId;
private Integer siteNodeId;
private Integer languageId;
private Integer contentId;
private Integer repositoryId;
private String returnAddress;
private boolean recurseSiteNodes = true;
private String originalAddress;
private String userSessionKey;
private String attemptDirectPublishing;
protected String doExecute() throws Exception
{
logger.info("siteNodeId:" + this.siteNodeId);
logger.info("siteNodeVersionId:" + this.siteNodeVersionId);
if(this.siteNodeVersionId == null)
{
SiteNodeVersionVO siteNodeVersionVO = SiteNodeVersionControllerProxy.getSiteNodeVersionControllerProxy().getACLatestActiveSiteNodeVersionVO(this.getInfoGluePrincipal(), siteNodeId);
if(siteNodeVersionVO != null)
this.siteNodeVersionId = siteNodeVersionVO.getId();
}
if(this.siteNodeVersionId != null)
{
AccessConstraintExceptionBuffer ceb = new AccessConstraintExceptionBuffer();
Integer protectedSiteNodeVersionId = SiteNodeVersionControllerProxy.getSiteNodeVersionControllerProxy().getProtectedSiteNodeVersionId(siteNodeVersionId);
if(protectedSiteNodeVersionId != null && !AccessRightController.getController().getIsPrincipalAuthorized(this.getInfoGluePrincipal(), "SiteNodeVersion.SubmitToPublish", protectedSiteNodeVersionId.toString()))
ceb.add(new AccessConstraintException("SiteNodeVersion.siteNodeVersionId", "1005"));
ceb.throwIfNotEmpty();
if(contentId != null && contentId > -1)
{
Integer protectedContentId = ContentControllerProxy.getController().getProtectedContentId(contentId);
if(protectedContentId == null || AccessRightController.getController().getIsPrincipalAuthorized(this.getInfoGluePrincipal(), "Content.SubmitToPublish", protectedContentId.toString()))
{
ContentVO contentVO = ContentControllerProxy.getController().getACContentVOWithId(getInfoGluePrincipal(), contentId);
List languageVOList = LanguageController.getController().getLanguageVOList(contentVO.getRepositoryId());
Iterator languageVOListIterator = languageVOList.iterator();
while(languageVOListIterator.hasNext())
{
LanguageVO language = (LanguageVO)languageVOListIterator.next();
ContentVersionVO contentVersionVO = ContentVersionController.getContentVersionController().getLatestActiveContentVersionVO(contentId, language.getId());
- if(contentVersionVO.getStateId().equals(ContentVersionVO.WORKING_STATE))
+ if(contentVersionVO != null && contentVersionVO.getStateId().equals(ContentVersionVO.WORKING_STATE))
{
this.contentVersionVOList.add(contentVersionVO);
}
}
}
}
SiteNodeVersionController.getController().getSiteNodeAndAffectedItemsRecursive(this.siteNodeId, SiteNodeVersionVO.WORKING_STATE, this.siteNodeVersionVOList, this.contentVersionVOList, false, recurseSiteNodes, this.getInfoGluePrincipal());
}
return "success";
}
public String doV3() throws Exception
{
doExecute();
userSessionKey = "" + System.currentTimeMillis();
addActionLink(userSessionKey, new LinkBean("currentPageUrl", getLocalizedString(getLocale(), "tool.common.publishing.publishingInlineOperationBackToCurrentPageLinkText"), getLocalizedString(getLocale(), "tool.common.publishing.publishingInlineOperationBackToCurrentPageTitleText"), getLocalizedString(getLocale(), "tool.common.publishing.publishingInlineOperationBackToCurrentPageTitleText"), this.originalAddress, false, ""));
setActionExtraData(userSessionKey, "disableCloseLink", "true");
return "successV3";
}
public Set getSiteNodeVersions()
{
return this.siteNodeVersionVOList;
}
public Integer getSiteNodeId()
{
return siteNodeId;
}
public void setSiteNodeId(Integer siteNodeId)
{
this.siteNodeId = siteNodeId;
}
public Integer getLanguageId()
{
return languageId;
}
public void setLanguageId(Integer languageId)
{
this.languageId = languageId;
}
public void setContentId(Integer contentId)
{
this.contentId = contentId;
}
public Integer getSiteNodeVersionId()
{
return siteNodeVersionId;
}
public void setSiteNodeVersionId(Integer siteNodeVersionId)
{
this.siteNodeVersionId = siteNodeVersionId;
}
public Integer getRepositoryId()
{
return repositoryId;
}
public void setRepositoryId(Integer repositoryId)
{
this.repositoryId = repositoryId;
}
public Set getContentVersionVOList()
{
return contentVersionVOList;
}
public Set getSiteNodeVersionVOList()
{
return siteNodeVersionVOList;
}
public String getReturnAddress()
{
return returnAddress;
}
public void setReturnAddress(String returnAddress)
{
this.returnAddress = returnAddress;
}
public boolean isRecurseSiteNodes()
{
return recurseSiteNodes;
}
public void setRecurseSiteNodes(boolean recurseSiteNodes)
{
this.recurseSiteNodes = recurseSiteNodes;
}
public String getUserSessionKey()
{
return userSessionKey;
}
public void setUserSessionKey(String userSessionKey)
{
this.userSessionKey = userSessionKey;
}
public String getOriginalAddress()
{
return originalAddress;
}
public void setOriginalAddress(String originalAddress)
{
this.originalAddress = originalAddress;
}
public String getAttemptDirectPublishing()
{
return attemptDirectPublishing;
}
public void setAttemptDirectPublishing(String attemptDirectPublishing)
{
this.attemptDirectPublishing = attemptDirectPublishing;
}
}
| true | true | protected String doExecute() throws Exception
{
logger.info("siteNodeId:" + this.siteNodeId);
logger.info("siteNodeVersionId:" + this.siteNodeVersionId);
if(this.siteNodeVersionId == null)
{
SiteNodeVersionVO siteNodeVersionVO = SiteNodeVersionControllerProxy.getSiteNodeVersionControllerProxy().getACLatestActiveSiteNodeVersionVO(this.getInfoGluePrincipal(), siteNodeId);
if(siteNodeVersionVO != null)
this.siteNodeVersionId = siteNodeVersionVO.getId();
}
if(this.siteNodeVersionId != null)
{
AccessConstraintExceptionBuffer ceb = new AccessConstraintExceptionBuffer();
Integer protectedSiteNodeVersionId = SiteNodeVersionControllerProxy.getSiteNodeVersionControllerProxy().getProtectedSiteNodeVersionId(siteNodeVersionId);
if(protectedSiteNodeVersionId != null && !AccessRightController.getController().getIsPrincipalAuthorized(this.getInfoGluePrincipal(), "SiteNodeVersion.SubmitToPublish", protectedSiteNodeVersionId.toString()))
ceb.add(new AccessConstraintException("SiteNodeVersion.siteNodeVersionId", "1005"));
ceb.throwIfNotEmpty();
if(contentId != null && contentId > -1)
{
Integer protectedContentId = ContentControllerProxy.getController().getProtectedContentId(contentId);
if(protectedContentId == null || AccessRightController.getController().getIsPrincipalAuthorized(this.getInfoGluePrincipal(), "Content.SubmitToPublish", protectedContentId.toString()))
{
ContentVO contentVO = ContentControllerProxy.getController().getACContentVOWithId(getInfoGluePrincipal(), contentId);
List languageVOList = LanguageController.getController().getLanguageVOList(contentVO.getRepositoryId());
Iterator languageVOListIterator = languageVOList.iterator();
while(languageVOListIterator.hasNext())
{
LanguageVO language = (LanguageVO)languageVOListIterator.next();
ContentVersionVO contentVersionVO = ContentVersionController.getContentVersionController().getLatestActiveContentVersionVO(contentId, language.getId());
if(contentVersionVO.getStateId().equals(ContentVersionVO.WORKING_STATE))
{
this.contentVersionVOList.add(contentVersionVO);
}
}
}
}
SiteNodeVersionController.getController().getSiteNodeAndAffectedItemsRecursive(this.siteNodeId, SiteNodeVersionVO.WORKING_STATE, this.siteNodeVersionVOList, this.contentVersionVOList, false, recurseSiteNodes, this.getInfoGluePrincipal());
}
return "success";
}
| protected String doExecute() throws Exception
{
logger.info("siteNodeId:" + this.siteNodeId);
logger.info("siteNodeVersionId:" + this.siteNodeVersionId);
if(this.siteNodeVersionId == null)
{
SiteNodeVersionVO siteNodeVersionVO = SiteNodeVersionControllerProxy.getSiteNodeVersionControllerProxy().getACLatestActiveSiteNodeVersionVO(this.getInfoGluePrincipal(), siteNodeId);
if(siteNodeVersionVO != null)
this.siteNodeVersionId = siteNodeVersionVO.getId();
}
if(this.siteNodeVersionId != null)
{
AccessConstraintExceptionBuffer ceb = new AccessConstraintExceptionBuffer();
Integer protectedSiteNodeVersionId = SiteNodeVersionControllerProxy.getSiteNodeVersionControllerProxy().getProtectedSiteNodeVersionId(siteNodeVersionId);
if(protectedSiteNodeVersionId != null && !AccessRightController.getController().getIsPrincipalAuthorized(this.getInfoGluePrincipal(), "SiteNodeVersion.SubmitToPublish", protectedSiteNodeVersionId.toString()))
ceb.add(new AccessConstraintException("SiteNodeVersion.siteNodeVersionId", "1005"));
ceb.throwIfNotEmpty();
if(contentId != null && contentId > -1)
{
Integer protectedContentId = ContentControllerProxy.getController().getProtectedContentId(contentId);
if(protectedContentId == null || AccessRightController.getController().getIsPrincipalAuthorized(this.getInfoGluePrincipal(), "Content.SubmitToPublish", protectedContentId.toString()))
{
ContentVO contentVO = ContentControllerProxy.getController().getACContentVOWithId(getInfoGluePrincipal(), contentId);
List languageVOList = LanguageController.getController().getLanguageVOList(contentVO.getRepositoryId());
Iterator languageVOListIterator = languageVOList.iterator();
while(languageVOListIterator.hasNext())
{
LanguageVO language = (LanguageVO)languageVOListIterator.next();
ContentVersionVO contentVersionVO = ContentVersionController.getContentVersionController().getLatestActiveContentVersionVO(contentId, language.getId());
if(contentVersionVO != null && contentVersionVO.getStateId().equals(ContentVersionVO.WORKING_STATE))
{
this.contentVersionVOList.add(contentVersionVO);
}
}
}
}
SiteNodeVersionController.getController().getSiteNodeAndAffectedItemsRecursive(this.siteNodeId, SiteNodeVersionVO.WORKING_STATE, this.siteNodeVersionVOList, this.contentVersionVOList, false, recurseSiteNodes, this.getInfoGluePrincipal());
}
return "success";
}
|
diff --git a/core/src/main/java/brooklyn/util/task/BasicTask.java b/core/src/main/java/brooklyn/util/task/BasicTask.java
index d3779822e..806efb15f 100644
--- a/core/src/main/java/brooklyn/util/task/BasicTask.java
+++ b/core/src/main/java/brooklyn/util/task/BasicTask.java
@@ -1,444 +1,443 @@
package brooklyn.util.task;
import static brooklyn.util.JavaGroovyEquivalents.asString;
import static brooklyn.util.JavaGroovyEquivalents.elvisString;
import static brooklyn.util.JavaGroovyEquivalents.join;
import groovy.lang.Closure;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.management.LockInfo;
import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import brooklyn.management.ExecutionManager;
import brooklyn.management.Task;
import brooklyn.util.GroovyJavaMethods;
import com.google.common.base.Throwables;
/**
* The basic concrete implementation of a {@link Task} to be executed.
*
* A {@link Task} is a wrapper for an executable unit, such as a {@link Closure} or a {@link Runnable} or
* {@link Callable} and will run in its own {@link Thread}.
* <p>
* The task can be given an optional displayName and description in its constructor (as named
* arguments in the first {@link Map} parameter). It is guaranteed to have {@link Object#notify()} called
* once whenever the task starts running and once again when the task is about to complete. Due to
* the way executors work it is ugly to guarantee notification <em>after</em> completion, so instead we
* notify just before then expect the user to call {@link #get()} - which will throw errors if the underlying job
* did so - or {@link #blockUntilEnded()} which will not throw errors.
*
* @see BasicTaskStub
*/
public class BasicTask<T> extends BasicTaskStub implements Task<T> {
protected static final Logger log = LoggerFactory.getLogger(BasicTask.class);
protected Callable<T> job;
public final String displayName;
public final String description;
protected final Set tags = new LinkedHashSet();
protected String blockingDetails = null;
/**
* Constructor needed to prevent confusion in groovy stubs when looking for default constructor,
*
* The generics on {@link Closure} break it if that is first constructor.
*/
protected BasicTask() { this(Collections.emptyMap()); }
protected BasicTask(Map flags) { this(flags, (Closure) null); }
public BasicTask(Closure<T> job) { this(Collections.emptyMap(), job); }
public BasicTask(Map flags, Closure<T> job) {
this.job = job;
if (flags.containsKey("tag")) tags.add(flags.remove("tag"));
Object ftags = flags.remove("tags");
if (ftags!=null) {
if (ftags instanceof Collection) tags.addAll((Collection)ftags);
else {
log.info("discouraged use of non-collection argument for 'tags' ("+ftags+") in "+this, new Throwable("trace of discouraged use of non-colleciton tags argument"));
tags.add(ftags);
}
}
description = elvisString(flags.remove("description"), "");
String d = asString(flags.remove("displayName"));
if (d==null) d = join(tags, "-");
displayName = d;
}
public BasicTask(Runnable job) { this(GroovyJavaMethods.closureFromRunnable(job)); }
public BasicTask(Map flags, Runnable job) { this(flags, GroovyJavaMethods.closureFromRunnable(job)); }
public BasicTask(Callable<T> job) { this(GroovyJavaMethods.closureFromCallable(job)); }
public BasicTask(Map flags, Callable<T> job) { this(flags, GroovyJavaMethods.closureFromCallable(job)); }
@Override
public String toString() {
return "Task["+(displayName!=null && displayName.length()>0?displayName+
(tags!=null && !tags.isEmpty()?"":";")+" ":"")+
(tags!=null && !tags.isEmpty()?tags+"; ":"")+getId()+"]";
}
// housekeeping --------------------
/*
* These flags are set by BasicExecutionManager.submit.
*
* Order is guaranteed to be as shown below, in order of #. Within each # line it is currently in the order specified by commas but this is not guaranteed.
* (The spaces between the # section indicate longer delays / logical separation ... it should be clear!)
*
* # submitter, submit time set, tags and other submit-time fields set, task tag-linked preprocessors onSubmit invoked
*
* # thread set, ThreadLocal getCurrentTask set
* # start time set, isBegun is true
* # task tag-linked preprocessors onStart invoked
* # task end callback run, if supplied
*
* # task runs
*
* # task end callback run, if supplied
* # task tag-linked preprocessors onEnd invoked (in reverse order of tags)
* # end time set
* # thread cleared, ThreadLocal getCurrentTask set
* # Task.notifyAll()
* # Task.get() (result.get()) available, Task.isDone is true
*
* Few _consumers_ should care, but internally we rely on this so that, for example, status is displayed correctly.
* Tests should catch most things, but be careful if you change any of the above semantics.
*/
protected long submitTimeUtc = -1;
protected long startTimeUtc = -1;
protected long endTimeUtc = -1;
protected Task<?> submittedByTask;
protected volatile Thread thread = null;
private volatile boolean cancelled = false;
protected Future<T> result = null;
protected ExecutionManager em = null;
void initExecutionManager(ExecutionManager em) {
this.em = em;
}
synchronized void initResult(Future result) {
if (this.result != null)
throw new IllegalStateException("task "+this+" is being given a result twice");
this.result = result;
notifyAll();
}
// metadata accessors ------------
public Set<Object> getTags() { return Collections.unmodifiableSet(new LinkedHashSet(tags)); }
public long getSubmitTimeUtc() { return submitTimeUtc; }
public long getStartTimeUtc() { return startTimeUtc; }
public long getEndTimeUtc() { return endTimeUtc; }
public Future<T> getResult() { return result; }
public Task<?> getSubmittedByTask() { return submittedByTask; }
/** the thread where the task is running, if it is running */
public Thread getThread() { return thread; }
// basic fields --------------------
public boolean isSubmitted() {
return submitTimeUtc >= 0;
}
public boolean isBegun() {
return startTimeUtc >= 0;
}
public synchronized boolean cancel() { return cancel(true); }
public synchronized boolean cancel(boolean mayInterruptIfRunning) {
if (isDone()) return false;
boolean cancel = true;
if (GroovyJavaMethods.truth(result)) { cancel = result.cancel(mayInterruptIfRunning); }
cancelled = true;
notifyAll();
return cancel;
}
public boolean isCancelled() {
return cancelled || (result!=null && result.isCancelled());
}
public boolean isDone() {
return cancelled || (result!=null && result.isDone());
}
/**
* Returns true if the task has had an error.
*
* Only true if calling {@link #get()} will throw an exception when it completes (including cancel).
* Implementations may set this true before completion if they have that insight, or
* (the default) they may compute it lazily after completion (returning false before completion).
*/
public boolean isError() {
if (!isDone()) return false;
if (isCancelled()) return true;
try {
get();
return false;
} catch (Throwable t) {
return true;
}
}
public T get() throws InterruptedException, ExecutionException {
blockUntilStarted();
return result.get();
}
// future value --------------------
public synchronized void blockUntilStarted() {
while (true) {
if (cancelled) throw new CancellationException();
if (result==null)
try {
wait();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
Throwables.propagate(e);
}
if (result!=null) return;
}
}
public void blockUntilEnded() {
try { blockUntilStarted(); } catch (Throwable t) {
if (log.isDebugEnabled())
log.debug("call from "+Thread.currentThread()+" blocking until "+this+" finishes ended with error: "+t);
/* contract is just to log errors at debug, otherwise do nothing */
return;
}
try { result.get(); } catch (Throwable t) {
if (log.isDebugEnabled())
log.debug("call from "+Thread.currentThread()+" blocking until "+this+" finishes ended with error: "+t);
/* contract is just to log errors at debug, otherwise do nothing */
return;
}
}
public T get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
long start = System.currentTimeMillis();
long milliseconds = TimeUnit.MILLISECONDS.convert(timeout, unit);
long end = start + milliseconds;
while (end > System.currentTimeMillis()) {
if (cancelled) throw new CancellationException();
if (result == null) wait(end - System.currentTimeMillis());
if (result != null) break;
}
long remaining = end - System.currentTimeMillis();
if (remaining > 0) {
return result.get(remaining, TimeUnit.MILLISECONDS);
} else {
throw new TimeoutException();
}
}
/**
* Returns a brief status string
*
* Plain-text format. Reported status if there is one, otherwise state which will be one of:
* <ul>
* <li>Not submitted
* <li>Submitted for execution
* <li>Ended by error
* <li>Ended by cancellation
* <li>Ended normally
* <li>Running
* <li>Waiting
* </ul>
*/
public String getStatusSummary() {
return getStatusString(0);
}
/**
* Returns detailed status, suitable for a hover
*
* Plain-text format, with new-lines (and sometimes extra info) if multiline enabled.
*/
public String getStatusDetail(boolean multiline) {
return getStatusString(multiline?2:1);
}
/**
* This method is useful for callers to see the status of a task.
*
* Also for developers to see best practices for examining status fields etc
*
* @param verbosity 0 = brief, 1 = one-line with some detail, 2 = lots of detail
*/
protected String getStatusString(int verbosity) {
// Thread t = getThread();
String rv;
if (submitTimeUtc <= 0) rv = "Not submitted";
else if (!isCancelled() && startTimeUtc <= 0) {
rv = "Submitted for execution";
if (verbosity>0) {
long elapsed = System.currentTimeMillis() - submitTimeUtc;
rv += " "+elapsed+" ms ago";
}
} else if (isDone()) {
long elapsed = endTimeUtc - submitTimeUtc;
String duration = ""+elapsed+" ms";
rv = "Ended ";
if (isCancelled()) {
rv += "by cancellation";
if (verbosity >= 1) rv+=" after "+duration;
} else if (isError()) {
rv += "by error";
if (verbosity >= 1) {
rv += " after "+duration;
Object error;
try { String rvx = ""+get(); error = "no error, return value "+rvx; /* shouldn't happen */ }
catch (Throwable tt) { error = tt; }
//remove outer ExecException which is reported by the get(), we want the exception the task threw
if (error instanceof ExecutionException) error = ((Throwable)error).getCause();
if (verbosity == 1) rv += " ("+error+")";
else {
StringWriter sw = new StringWriter();
- if (error instanceof ExecutionException)
- ((Throwable)error).printStackTrace(new PrintWriter(sw));
+ ((Throwable)error).printStackTrace(new PrintWriter(sw));
rv += "\n"+sw.getBuffer();
}
}
} else {
rv += "normally";
if (verbosity>=1) {
if (verbosity==1) {
try {
rv += ", result "+get();
} catch (Exception e) {
rv += ", but error accessing result ["+e+"]"; //shouldn't happen
}
} else {
rv += " after "+duration;
try {
rv += "\n" + "Result: "+get();
} catch (Exception e) {
rv += " at first\n" +
"Error accessing result ["+e+"]"; //shouldn't happen
}
}
}
}
} else {
rv = getActiveTaskStatusString(verbosity);
}
return rv;
}
protected String getActiveTaskStatusString(int verbosity) {
String rv = "";
Thread t = getThread();
// Normally, it's not possible for thread==null as we were started and not ended
// However, there is a race where the task starts sand completes between the calls to getThread()
// at the start of the method and this call to getThread(), so both return null even though
// the intermediate checks returned started==true isDone()==false.
if (t == null) {
if (isDone()) {
return getStatusString(verbosity);
} else {
//should only happen for repeating task which is not active
return "Sleeping";
}
}
ThreadInfo ti = ManagementFactory.getThreadMXBean().getThreadInfo(t.getId(), (verbosity<=0 ? 0 : verbosity==1 ? 1 : Integer.MAX_VALUE));
if (getThread()==null)
//thread might have moved on to a new task; if so, recompute (it should now say "done")
return getStatusString(verbosity);
LockInfo lock = ti.getLockInfo();
if (!GroovyJavaMethods.truth(lock) && ti.getThreadState()==Thread.State.RUNNABLE) {
//not blocked
if (ti.isSuspended()) {
// when does this happen?
rv = "Waiting";
if (verbosity >= 1) rv += ", thread suspended";
} else {
rv = "Running";
if (verbosity >= 1) rv += " ("+ti.getThreadState()+")";
}
} else {
rv = "Waiting";
if (verbosity>=1) {
if (ti.getThreadState() == Thread.State.BLOCKED) {
rv += " (mutex) on "+lookup(lock);
//TODO could say who holds it
} else if (ti.getThreadState() == Thread.State.WAITING) {
rv += " (notify) on "+lookup(lock);
} else if (ti.getThreadState() == Thread.State.TIMED_WAITING) {
rv += " (timed) on "+lookup(lock);
} else {
rv = " ("+ti.getThreadState()+") on "+lookup(lock);
}
if (GroovyJavaMethods.truth(blockingDetails)) rv += " - "+blockingDetails;
}
}
if (verbosity>=2) {
StackTraceElement[] st = ti.getStackTrace();
st = StackTraceSimplifier.cleanStackTrace(st);
if (st!=null && st.length>0)
rv += "\n" +"At: "+st[0];
for (int ii=1; ii<st.length; ii++) {
rv += "\n" +" "+st[ii];
}
}
return rv;
}
protected String lookup(LockInfo info) {
return GroovyJavaMethods.truth(info) ? ""+info : "unknown (sleep)";
}
public String getDisplayName() {
return displayName;
}
public String getDescription() {
return description;
}
/** allows a task user to specify why a task is blocked; for use immediately before a blocking/wait,
* and typically cleared immediately afterwards; referenced by management api to inspect a task
* which is blocking
*/
public void setBlockingDetails(String blockingDetails) {
this.blockingDetails = blockingDetails;
}
public String getBlockingDetails() {
return blockingDetails;
}
}
| true | true | protected String getStatusString(int verbosity) {
// Thread t = getThread();
String rv;
if (submitTimeUtc <= 0) rv = "Not submitted";
else if (!isCancelled() && startTimeUtc <= 0) {
rv = "Submitted for execution";
if (verbosity>0) {
long elapsed = System.currentTimeMillis() - submitTimeUtc;
rv += " "+elapsed+" ms ago";
}
} else if (isDone()) {
long elapsed = endTimeUtc - submitTimeUtc;
String duration = ""+elapsed+" ms";
rv = "Ended ";
if (isCancelled()) {
rv += "by cancellation";
if (verbosity >= 1) rv+=" after "+duration;
} else if (isError()) {
rv += "by error";
if (verbosity >= 1) {
rv += " after "+duration;
Object error;
try { String rvx = ""+get(); error = "no error, return value "+rvx; /* shouldn't happen */ }
catch (Throwable tt) { error = tt; }
//remove outer ExecException which is reported by the get(), we want the exception the task threw
if (error instanceof ExecutionException) error = ((Throwable)error).getCause();
if (verbosity == 1) rv += " ("+error+")";
else {
StringWriter sw = new StringWriter();
if (error instanceof ExecutionException)
((Throwable)error).printStackTrace(new PrintWriter(sw));
rv += "\n"+sw.getBuffer();
}
}
} else {
rv += "normally";
if (verbosity>=1) {
if (verbosity==1) {
try {
rv += ", result "+get();
} catch (Exception e) {
rv += ", but error accessing result ["+e+"]"; //shouldn't happen
}
} else {
rv += " after "+duration;
try {
rv += "\n" + "Result: "+get();
} catch (Exception e) {
rv += " at first\n" +
"Error accessing result ["+e+"]"; //shouldn't happen
}
}
}
}
} else {
rv = getActiveTaskStatusString(verbosity);
}
return rv;
}
| protected String getStatusString(int verbosity) {
// Thread t = getThread();
String rv;
if (submitTimeUtc <= 0) rv = "Not submitted";
else if (!isCancelled() && startTimeUtc <= 0) {
rv = "Submitted for execution";
if (verbosity>0) {
long elapsed = System.currentTimeMillis() - submitTimeUtc;
rv += " "+elapsed+" ms ago";
}
} else if (isDone()) {
long elapsed = endTimeUtc - submitTimeUtc;
String duration = ""+elapsed+" ms";
rv = "Ended ";
if (isCancelled()) {
rv += "by cancellation";
if (verbosity >= 1) rv+=" after "+duration;
} else if (isError()) {
rv += "by error";
if (verbosity >= 1) {
rv += " after "+duration;
Object error;
try { String rvx = ""+get(); error = "no error, return value "+rvx; /* shouldn't happen */ }
catch (Throwable tt) { error = tt; }
//remove outer ExecException which is reported by the get(), we want the exception the task threw
if (error instanceof ExecutionException) error = ((Throwable)error).getCause();
if (verbosity == 1) rv += " ("+error+")";
else {
StringWriter sw = new StringWriter();
((Throwable)error).printStackTrace(new PrintWriter(sw));
rv += "\n"+sw.getBuffer();
}
}
} else {
rv += "normally";
if (verbosity>=1) {
if (verbosity==1) {
try {
rv += ", result "+get();
} catch (Exception e) {
rv += ", but error accessing result ["+e+"]"; //shouldn't happen
}
} else {
rv += " after "+duration;
try {
rv += "\n" + "Result: "+get();
} catch (Exception e) {
rv += " at first\n" +
"Error accessing result ["+e+"]"; //shouldn't happen
}
}
}
}
} else {
rv = getActiveTaskStatusString(verbosity);
}
return rv;
}
|
diff --git a/jmx-extractor/src/main/java/org/jmxdatamart/Extractor/Bean2DB.java b/jmx-extractor/src/main/java/org/jmxdatamart/Extractor/Bean2DB.java
index 5f89f06..479cbdc 100644
--- a/jmx-extractor/src/main/java/org/jmxdatamart/Extractor/Bean2DB.java
+++ b/jmx-extractor/src/main/java/org/jmxdatamart/Extractor/Bean2DB.java
@@ -1,194 +1,194 @@
package org.jmxdatamart.Extractor;
import org.jmxdatamart.JMXTestServer.TestBean;
import org.jmxdatamart.common.*;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import java.lang.management.ManagementFactory;
import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* Created with IntelliJ IDEA.
* User: Xiao Han
* To change this template use File | Settings | File Templates.
*/
public class Bean2DB {
public static void main(String[] args) throws Exception {
// TODO code application logic here
int expected = 42;
//Create new test MBean
TestBean tb = new TestBean();
tb.setA(new Integer(expected));
MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
String mbName = "org.jmxdatamart.JMXTestServer:type=TestBean";
ObjectName mbeanName = new ObjectName(mbName);
mbs.registerMBean(tb, mbeanName);
//Create test MBean's MBeanData
Attribute a = new Attribute("A", "Alpha", DataType.INT);
MBeanData mbd = new MBeanData(mbName, "testMBean", Collections.singletonList(a), true);
//Init MBeanExtract
MBeanExtract instance = new MBeanExtract(mbd, mbs);
Map result = instance.extract();
Settings s = new Settings();
s.setBeans(Collections.singletonList((BeanData)mbd));
s.setFolderLocation("HyperSQL/");
s.setPollingRate(2);
s.setUrl("service:jmx:rmi:///jndi/rmi://:9999/jmxrmi");
Properties props = new Properties();
props.put("username", "sa");
props.put("password", "whatever");
Bean2DB bd = new Bean2DB();
String dbname = bd.generateMBeanDB(s);
HypersqlHandler hsql = new HypersqlHandler();
Connection conn= hsql.connectDatabase(dbname, props);
bd.export2DB(conn,mbd,result);
ResultSet rs = conn.createStatement().executeQuery("select * from org_jmxdatamart_JMXTestServer__type___TestBean");
while(rs.next()){
System.out.println(rs.getObject(1) + "\t" + rs.getObject(2));
}
hsql.shutdownDatabase(conn);
DBHandler.disconnectDatabase(rs, null, null, conn);
}
//get rid of the . : =, which are illegal for a table name
public String convertIllegalTableName(String tablename){
return tablename.replaceAll("\\.","_").replaceAll(":","__").replaceAll("=","___");
}
public String recoverOriginalTableName(String tablename){
return tablename.replaceAll("___","=").replaceAll("__",":").replaceAll("_","\\.");
}
private void dealWithDynamicBean(Connection conn, String tableName , Map<Attribute, Object> result) throws SQLException,DBException{
if (!DBHandler.tableExists(tableName,conn)){
throw new DBException("Something wrong in the Dynamic Bean: bean table doesn't exists!");
}
String sql;
boolean bl = conn.getAutoCommit();
conn.setAutoCommit(false);
for (Map.Entry<Attribute, Object> m : result.entrySet()) {
if (!DBHandler.columnExists(m.getKey().getName(),tableName,conn)){
sql = "Alter table " + tableName +" add " +m.getKey().getName()+ " "+m.getKey().getDataType();
conn.createStatement().executeUpdate(sql);
}
}
conn.commit();
conn.setAutoCommit(bl);
}
- public void export2DB(Connection conn, MBeanData mbd, Map<Attribute, Object> result) throws SQLException,DBException{
+ public void export2DB(Connection conn, BeanData mbd, Map<Attribute, Object> result) throws SQLException,DBException{
String tablename = convertIllegalTableName(mbd.getName());
//deal with dynamic bean
dealWithDynamicBean(conn,tablename,result);
PreparedStatement ps = null;
StringBuilder insertstring = new StringBuilder() ;
insertstring.append("insert into ").append(tablename).append(" (");
StringBuilder insertvalue = new StringBuilder();
insertvalue.append(" values(");
for (Map.Entry<Attribute, Object> m : result.entrySet()) {
insertstring.append(((Attribute)m.getKey()).getName()).append(",");
insertvalue.append("?,");
}
String sql = insertstring.append("time)").toString();
sql += insertvalue.append("?)").toString();
//System.out.println(sql);
ps = conn.prepareStatement(sql);
//need to think about how to avoid retrieving the map twice
int i=0;
for (Map.Entry<Attribute, Object> m : result.entrySet()) {
switch (((Attribute)m.getKey()).getDataType())
{
case INT:
ps.setInt(++i,(Integer)m.getValue());
break;
case STRING:
ps.setString(++i,m.getValue().toString());
break;
case FLOAT:
ps.setFloat(++i,(Float)m.getValue());
break;
}
}
ps.setTimestamp(++i, new Timestamp((new java.util.Date()).getTime()));
boolean bl=false;
try{
bl = conn.getAutoCommit();
conn.setAutoCommit(false);
ps.executeUpdate();
conn.commit();
}
catch (SQLException e){
conn.rollback();
}
finally {
ps.close();
conn.setAutoCommit(bl);
}
}
public String generateMBeanDB(Settings s) throws SQLException{
Connection conn = null;
Statement st = null;
HypersqlHandler hypersql = new HypersqlHandler();
hypersql.loadDriver(hypersql.getDriver());
String dbName = s.getFolderLocation()+"Extrator" + new SimpleDateFormat("yyyyMMddHHmmss").format(new java.util.Date());
StringBuilder sb;
String tablename = null;
try{
Properties props = new Properties();
props.put("username", "sa");
props.put("password", "whatever");
conn = hypersql.connectDatabase(dbName, props);
System.out.println("Database " + dbName + " is created.");
st = conn.createStatement();
conn.setAutoCommit(false);
for (BeanData bean:s.getBeans()){
sb = new StringBuilder();
tablename = convertIllegalTableName(bean.getName());
//1.the bean names are unique, but alias not
//2.the field name of "time"(or whatever) should be reserved, can't be used as an attribute name
//3.the datatyype should be valid in embedded SQL (ie. HyperSQL)
//All above requirements must be set to a DTD for the setting xml file!!!
sb.append("create table " + tablename + "(");
for (Attribute ab: bean.getAttributes()){
sb.append(ab.getName() + " " + ab.getDataType() + ",");
}
sb.append("time TIMESTAMP)");
st.executeUpdate(sb.toString());
System.out.println("Table " + recoverOriginalTableName(tablename) + " is created.");
}
conn.commit();
}
catch (Exception e){
System.err.println(e.getMessage());
conn.rollback();
return null;
}
finally {
hypersql.shutdownDatabase(conn); //we should shut down a Hsql DB
DBHandler.disconnectDatabase(null, st, null, conn);
}
return dbName;
}
}
| true | true | public void export2DB(Connection conn, MBeanData mbd, Map<Attribute, Object> result) throws SQLException,DBException{
String tablename = convertIllegalTableName(mbd.getName());
//deal with dynamic bean
dealWithDynamicBean(conn,tablename,result);
PreparedStatement ps = null;
StringBuilder insertstring = new StringBuilder() ;
insertstring.append("insert into ").append(tablename).append(" (");
StringBuilder insertvalue = new StringBuilder();
insertvalue.append(" values(");
for (Map.Entry<Attribute, Object> m : result.entrySet()) {
insertstring.append(((Attribute)m.getKey()).getName()).append(",");
insertvalue.append("?,");
}
String sql = insertstring.append("time)").toString();
sql += insertvalue.append("?)").toString();
//System.out.println(sql);
ps = conn.prepareStatement(sql);
//need to think about how to avoid retrieving the map twice
int i=0;
for (Map.Entry<Attribute, Object> m : result.entrySet()) {
switch (((Attribute)m.getKey()).getDataType())
{
case INT:
ps.setInt(++i,(Integer)m.getValue());
break;
case STRING:
ps.setString(++i,m.getValue().toString());
break;
case FLOAT:
ps.setFloat(++i,(Float)m.getValue());
break;
}
}
ps.setTimestamp(++i, new Timestamp((new java.util.Date()).getTime()));
boolean bl=false;
try{
bl = conn.getAutoCommit();
conn.setAutoCommit(false);
ps.executeUpdate();
conn.commit();
}
catch (SQLException e){
conn.rollback();
}
finally {
ps.close();
conn.setAutoCommit(bl);
}
}
| public void export2DB(Connection conn, BeanData mbd, Map<Attribute, Object> result) throws SQLException,DBException{
String tablename = convertIllegalTableName(mbd.getName());
//deal with dynamic bean
dealWithDynamicBean(conn,tablename,result);
PreparedStatement ps = null;
StringBuilder insertstring = new StringBuilder() ;
insertstring.append("insert into ").append(tablename).append(" (");
StringBuilder insertvalue = new StringBuilder();
insertvalue.append(" values(");
for (Map.Entry<Attribute, Object> m : result.entrySet()) {
insertstring.append(((Attribute)m.getKey()).getName()).append(",");
insertvalue.append("?,");
}
String sql = insertstring.append("time)").toString();
sql += insertvalue.append("?)").toString();
//System.out.println(sql);
ps = conn.prepareStatement(sql);
//need to think about how to avoid retrieving the map twice
int i=0;
for (Map.Entry<Attribute, Object> m : result.entrySet()) {
switch (((Attribute)m.getKey()).getDataType())
{
case INT:
ps.setInt(++i,(Integer)m.getValue());
break;
case STRING:
ps.setString(++i,m.getValue().toString());
break;
case FLOAT:
ps.setFloat(++i,(Float)m.getValue());
break;
}
}
ps.setTimestamp(++i, new Timestamp((new java.util.Date()).getTime()));
boolean bl=false;
try{
bl = conn.getAutoCommit();
conn.setAutoCommit(false);
ps.executeUpdate();
conn.commit();
}
catch (SQLException e){
conn.rollback();
}
finally {
ps.close();
conn.setAutoCommit(bl);
}
}
|
diff --git a/src/com/suxsem/liquidnextparts/activities/settings.java b/src/com/suxsem/liquidnextparts/activities/settings.java
index b329524..0d4fc4d 100755
--- a/src/com/suxsem/liquidnextparts/activities/settings.java
+++ b/src/com/suxsem/liquidnextparts/activities/settings.java
@@ -1,650 +1,650 @@
package com.suxsem.liquidnextparts.activities;
import com.suxsem.liquidnextparts.components.StartSystem;
import com.suxsem.liquidnextparts.BatteryLED;
import com.suxsem.liquidnextparts.BottomLED;
import com.suxsem.liquidnextparts.DiskSpace;
import com.suxsem.liquidnextparts.LSystem;
import com.suxsem.liquidnextparts.LiquidSettings;
import com.suxsem.liquidnextparts.NetworkMode;
import com.suxsem.liquidnextparts.OTA_updates;
import com.suxsem.liquidnextparts.R;
import com.suxsem.liquidnextparts.SdCache;
import com.suxsem.liquidnextparts.Strings;
import com.suxsem.liquidnextparts.parsebuildprop;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.EditTextPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.Preference.OnPreferenceClickListener;
import android.widget.Toast;
import android.content.Intent;
import android.content.SharedPreferences.Editor;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
public class settings extends PreferenceActivity {
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.inflatedmenu, menu);
return true;
}
@Override
public void onStop() {
super.onStop();
this.finish();
return;
}
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.menu_help:
showhelp();
return true;
case R.id.menu_close:
this.finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public boolean ROOT = false;
public boolean isFirstTime = false;
public SharedPreferences prefs;
public String noiseValue, sensitivityValue, softsensValue, hftimeValue;
public int SDCacheSize;
private settings myactivity = this;
EditTextPreference editNoise, editSensitivity, editSoftsens, editHftime;
public String DownloadTaskInformations = "";
Boolean update = false;
Boolean connection = false;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (!LSystem.checkInitFolder()){
Toast.makeText(this, "Can't make init.d folder, your system must be rooted", 4000).show();
this.finish(); //Exit app
}
ROOT = LiquidSettings.isRoot();
prefs = PreferenceManager.getDefaultSharedPreferences(myactivity);
new StartSystem().startsystem(myactivity);
addPreferencesFromResource(R.xml.menu);
final Context context = getApplicationContext();
final CheckBoxPreference hf = (CheckBoxPreference)findPreference("hf");
final EditTextPreference sdcache = (EditTextPreference)findPreference("sdcache");
final CheckBoxPreference powerled = (CheckBoxPreference)findPreference("powerled");
final CheckBoxPreference noprox = (CheckBoxPreference)findPreference("noprox");
final CheckBoxPreference nobottom = (CheckBoxPreference)findPreference("nobottom");
final CheckBoxPreference updateonstart = (CheckBoxPreference)findPreference("updateonstart");
final CheckBoxPreference usemetalcamera = (CheckBoxPreference)findPreference("usemetalcamera");
final Preference menu_info = findPreference("menu_info");
final Preference mountsystem = findPreference("mountsystem");
final Preference diskspace = findPreference("diskspace");
final Preference hotreboot = findPreference("hotreboot");
final Preference forceupdate = findPreference("forceupdate");
final Preference donateclick = findPreference("donateclick");
final Preference v6scripttweaker = findPreference("v6scripttweaker");
final Preference sdmanscripttweaker = findPreference("sdmanscripttweaker");
final Preference sdmanscript = findPreference("sdmanscript");
final Preference reportissue = findPreference("reportissue");
final ListPreference networkmode = (ListPreference)findPreference("2g3gmode");
final Preference resetall = findPreference("resetall");
//noprox.setChecked((parsebuildprop.parseInt("hw.acer.psensor_calib_min_base")==32717));
editNoise = (EditTextPreference)findPreference("noise");
editSensitivity = (EditTextPreference)findPreference("sensitivity");
editSoftsens = (EditTextPreference)findPreference("softsens");
editHftime = (EditTextPreference)findPreference("hftime");
if (!LSystem.hapticAvailable())
hf.setEnabled(false);
else
hf.setChecked(LSystem.vibrStatus());
if (!SdCache.isCachePathAvailable())
sdcache.setEnabled(false);
if ((SDCacheSize=SdCache.getSdCacheSize()) >= 128){
sdcache.setText(Integer.toString(SDCacheSize));
}
noiseValue = editNoise.getText();
sensitivityValue = editSensitivity.getText();
softsensValue = editSoftsens.getText();
hftimeValue = editHftime.getText();
updateValues();
java.io.File file = new java.io.File("/system/app/Camera.stock_lock");
if (!file.exists()) {
usemetalcamera.setChecked(false);
}else{
usemetalcamera.setChecked(true);
}
editNoise.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
public boolean onPreferenceChange(Preference preference, Object newValue) {
if (!Strings.onlyNumber(newValue.toString())){
Toast.makeText(context, "You must enter a numeric value!", 4000).show();
return false;
} //Check if the value is numeric, THEN assign it to noiseValue
noiseValue = newValue.toString();
int noiseValueInt = Integer.parseInt(noiseValue);
if(noiseValueInt < 20)
noiseValue = "20";
else if(noiseValueInt > 75)
noiseValue = "75";
if(ROOT) {
if(ROOT && LSystem.RemountRW()) {
LiquidSettings.runRootCommand("echo "+Strings.getSens(sensitivityValue, noiseValue, softsensValue, hftimeValue)+" > /system/etc/init.d/06sensitivity");
LiquidSettings.runRootCommand("chmod +x /system/etc/init.d/06sensitivity");
LSystem.RemountROnly();
if (LiquidSettings.runRootCommand("./system/etc/init.d/06sensitivity"))
Toast.makeText(context, "Sensitivity set correctly", 4000).show();
else
Toast.makeText(context, "Error, unable to set noise", 4000).show();
}
updateValues();
} else {
Toast.makeText(context, "Sorry, you need ROOT permissions.", 4000).show();
}
return true;
}
});
editSensitivity.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
public boolean onPreferenceChange(Preference preference, Object newValue) {
if (!Strings.onlyNumber(newValue.toString())){
Toast.makeText(context, "You must enter a numeric value!", 4000).show();
return false;
} //Check if the value is numeric, THEN assign it to sensitivityValue
sensitivityValue = newValue.toString();
int sensitivityValueInt = Integer.parseInt(sensitivityValue);
if(sensitivityValueInt < (20))
sensitivityValue = ("20");
else if (sensitivityValueInt>(75))
sensitivityValue=("75");
if(ROOT) {
if(ROOT && LSystem.RemountRW()) {
LiquidSettings.runRootCommand("echo "+Strings.getSens(sensitivityValue, noiseValue, softsensValue, hftimeValue)+" > /system/etc/init.d/06sensitivity");
LiquidSettings.runRootCommand("chmod +x /system/etc/init.d/06sensitivity");
LSystem.RemountROnly();
if (LiquidSettings.runRootCommand("./system/etc/init.d/06sensitivity"))
Toast.makeText(context, "Sensitivity set correctly", 4000).show();
else
Toast.makeText(context, "Error, unable to set noise", 4000).show();
}
updateValues();
} else {
Toast.makeText(context, "Sorry, you need ROOT permissions.", 4000).show();
}
return true;
}
});
editSoftsens.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
public boolean onPreferenceChange(Preference preference, Object newValue) {
if (!Strings.onlyNumber(newValue.toString())){
Toast.makeText(context, "You must enter a numeric value!", 4000).show();
return false;
} //Check if the value is numeric, THEN assign it to sensitivityValue
softsensValue = newValue.toString();
int softsensValueInt = Integer.parseInt(softsensValue);
if(softsensValueInt < (15))
softsensValue = ("15");
else if (softsensValueInt>(30))
softsensValue=("30");
if(ROOT) {
if(ROOT && LSystem.RemountRW()) {
LiquidSettings.runRootCommand("echo "+Strings.getSens(sensitivityValue, noiseValue, softsensValue, hftimeValue)+" > /system/etc/init.d/06sensitivity");
LiquidSettings.runRootCommand("chmod +x /system/etc/init.d/06sensitivity");
LSystem.RemountROnly();
if (LiquidSettings.runRootCommand("./system/etc/init.d/06sensitivity"))
Toast.makeText(context, "Sensitivity set correctly", 4000).show();
else
Toast.makeText(context, "Error, unable to set noise", 4000).show();
}
updateValues();
} else {
Toast.makeText(context, "Sorry, you need ROOT permissions.", 4000).show();
}
return true;
}
});
powerled.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
if (ROOT){
if (powerled.isChecked()) {
LiquidSettings.runRootCommand("echo '0' > /sys/class/leds2/power");
LiquidSettings.runRootCommand("chmod 000 /sys/class/leds2/power");
}else{
LiquidSettings.runRootCommand("chmod 222 /sys/class/leds2/power");
}
if (BatteryLED.setdisable(powerled.isChecked())){
return true;
} else{
Toast.makeText(context, "Error while set Power LED disable", 4000).show();
return false;
}
}else {
Toast.makeText(context, "Sorry, you need ROOT permissions", 4000).show();
return false;
}
}
});
nobottom.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
if (ROOT){
if (nobottom.isChecked()) {
LiquidSettings.runRootCommand("echo '0' > /sys/class/leds2/bottom");
LiquidSettings.runRootCommand("chmod 000 /sys/class/leds2/bottom");
}else{
LiquidSettings.runRootCommand("chmod 222 /sys/class/leds2/bottom");
}
if (BottomLED.setdisable(nobottom.isChecked())){
return true;
} else{
Toast.makeText(context, "Error while set Bottom LED disable", 4000).show();
return false;
}
}else {
Toast.makeText(context, "Sorry, you need ROOT permissions", 4000).show();
return false;
}
}
});
hf.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
if(ROOT){
if(LSystem.RemountRW()) {
LiquidSettings.runRootCommand("echo " + ((hf.isChecked()) ? Strings.getvibr() : Strings.getnovibr()) + " > /system/etc/init.d/06vibrate");
LiquidSettings.runRootCommand("echo " + ((hf.isChecked()==true) ? "1": "0") +" > /sys/module/avr/parameters/vibr");
LiquidSettings.runRootCommand("chmod +x /system/etc/init.d/06vibrate");
LSystem.RemountROnly();
Toast.makeText(context, "Haptic set on " + Boolean.toString(hf.isChecked()), 4000).show();
} else {
Toast.makeText(context, "Error: unable to mount partition", 4000).show();
hf.setChecked(false);
}
} else {
Toast.makeText(context, "Sorry, you need ROOT permissions.", 4000).show();
hf.setChecked(false);
}
return true;
}
});
editHftime.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
public boolean onPreferenceChange(Preference preference, Object newValue) {
if (!Strings.onlyNumber(newValue.toString())){
Toast.makeText(context, "You must enter a numeric value!", 4000).show();
return false;
} //Check if the value is numeric, THEN assign it to sensitivityValue
hftimeValue = newValue.toString();
int hftimeValueInt = Integer.parseInt(hftimeValue);
if(hftimeValueInt < (10))
hftimeValue = ("10");
else if (hftimeValueInt>(2000))
hftimeValue=("2000");
if(ROOT) {
if(ROOT && LSystem.RemountRW()) {
LiquidSettings.runRootCommand("echo "+Strings.getSens(sensitivityValue, noiseValue, softsensValue, hftimeValue)+" > /system/etc/init.d/06sensitivity");
LiquidSettings.runRootCommand("chmod +x /system/etc/init.d/06sensitivity");
LSystem.RemountROnly();
if (LiquidSettings.runRootCommand("./system/etc/init.d/06sensitivity"))
Toast.makeText(context, "Sensitivity set correctly", 4000).show();
else
Toast.makeText(context, "Error, unable to set noise", 4000).show();
}
updateValues();
} else {
Toast.makeText(context, "Sorry, you need ROOT permissions.", 4000).show();
}
return true;
}
});
sdcache.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
public boolean onPreferenceChange(Preference preference, Object newValue) {
if (!Strings.onlyNumber(newValue.toString())){
Toast.makeText(context, "You must enter a numeric value!", 4000).show();
return false;
} //Check if the value is numeric, THEN assign it to sensitivityValue
String newValueString = newValue.toString();
int newValueInt = Integer.parseInt(newValueString);
if(newValueInt < 128)
newValueInt = 128;
else if (newValueInt > 4096)
newValueInt = 4096;
if (ROOT){
if (SdCache.setSDCache(newValueInt)){
Toast.makeText(context, "SD cache size set to " + newValueInt, 4000).show();
return true;
}else{
Toast.makeText(context, "Error while setting SD Cache", 4000).show();
return false;
}
} else
Toast.makeText(context, "Sorry you need root permissions", 4000).show();
return false;
}
});
networkmode.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference,
Object newValue) {
Editor editor = prefs.edit();
editor.putString("2g3gmode", newValue.toString());
editor.commit();
NetworkMode.switchnetworkmode(myactivity);
return true;
}
});
noprox.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
if (noprox.isChecked()) {
parsebuildprop.editString("hw.acer.psensor_calib_min_base", "32717");
}else{
parsebuildprop.editString("hw.acer.psensor_calib_min_base", "32716");
}
AlertDialog.Builder builder = new AlertDialog.Builder(myactivity);
builder.setTitle("Reboot required");
builder.setCancelable(true);
builder.setMessage("This option requires a reboot to be applied. Do you want to reboot now?");
builder.setPositiveButton("Reboot", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
LiquidSettings.runRootCommand("reboot");
}
});
builder.setNegativeButton("Close", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
builder.create().show();
return true;
}
});
v6scripttweaker.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
try {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.setComponent(new ComponentName("jackpal.androidterm2", "jackpal.androidterm2.Term"));
intent.putExtra("jackpal.androidterm.iInitialCommand", "su \r sh /system/xbin/V6SuperChargerLN.sh");
startActivity(intent);
} catch (Exception e) {
Toast.makeText(myactivity, "No terminal emulator app found", 4000).show();
}
return true;
}
});
sdmanscripttweaker.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
try {
Intent intent = new Intent(Intent.ACTION_MAIN);
- intent.setComponent(new ComponentName("jackpal.androidterm2", "jackpal.androidter2.Term"));
+ intent.setComponent(new ComponentName("jackpal.androidterm2", "jackpal.androidterm2.Term"));
intent.putExtra("jackpal.androidterm.iInitialCommand", "su \r sh /system/bin/sdman");
startActivity(intent);
} catch (Exception e) {
Toast.makeText(myactivity, "No terminal emulator app found", 4000).show();
}
return true;
}
});
sdmanscript.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
Intent myintent = new Intent (Intent.ACTION_VIEW);
myintent.setClassName(myactivity, SDMAN.class.getName());
startActivity(myintent);
return true;
}
});
usemetalcamera.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
LSystem.RemountRW();
if (usemetalcamera.isChecked()) {
LiquidSettings.runRootCommand("mv -f /system/app/Camera.apk /system/app/Camera.stock_lock");
LiquidSettings.runRootCommand("mv -f /system/app/Camera.metal_lock /system/app/Camera.apk");
LiquidSettings.runRootCommand("chmod 777 /system/app/Camera.apk");
LiquidSettings.runRootCommand("sync");
Toast.makeText(myactivity, "Choose 480p in camera settings!", 4000).show();
}else{
LiquidSettings.runRootCommand("mv -f /system/app/Camera.apk /system/app/Camera.metal_lock");
LiquidSettings.runRootCommand("mv -f /system/app/Camera.stock_lock /system/app/Camera.apk");
LiquidSettings.runRootCommand("chmod 777 /system/app/Camera.apk");
LiquidSettings.runRootCommand("sync");
}
LSystem.RemountROnly();
return true;
}
});
mountsystem.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
final AlertDialog.Builder builder = new AlertDialog.Builder(myactivity);
builder.setTitle("Mount system as...");
builder.setCancelable(true);
builder.setMessage("Choose RW if you want to write into system parition (read-write). Choose RO if you want to write-protect system partition (read-only). NOTICE: after a reboot system partition will be mounted as RO!");
builder.setPositiveButton("RW", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
LSystem.RemountRW();
Toast.makeText(myactivity, "Done", 4000).show();
}
});
builder.setNegativeButton("RO", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
LSystem.RemountROnly();
Toast.makeText(myactivity, "Done", 4000).show();
}
});
builder.create().show();
return true;
}
});
diskspace.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
final AlertDialog.Builder builder = new AlertDialog.Builder(myactivity);
builder.setTitle("DiskSpace");
builder.setCancelable(true);
builder.setMessage(DiskSpace.getdiskspace());
builder.setNegativeButton("Close", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
builder.create().show();
return true;
}
});
hotreboot.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
ProgressDialog.show(myactivity, "",
"Rebooting...", true);
LiquidSettings.runRootCommand("killall system_server");
return true;
}
});
donateclick.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
ConnectivityManager connManager = (ConnectivityManager)myactivity.getSystemService(Context.CONNECTIVITY_SERVICE);
android.net.NetworkInfo netInfo= connManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
android.net.NetworkInfo wifiInfo= connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (netInfo.getState() == android.net.NetworkInfo.State.CONNECTED ||
wifiInfo.getState() == android.net.NetworkInfo.State.CONNECTED ) {
Intent myintent = new Intent (Intent.ACTION_VIEW);
myintent.setClassName(context, Webview.class.getName());
startActivity(myintent);
}else{
Toast.makeText(myactivity, "ERROR: NO CONNECTIONS!", 4000).show();
}
return true;
}
});
forceupdate.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
//checkupdates();
new OTA_updates().checkupdates(myactivity, myactivity);
return true;
}
});
updateonstart.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
if (!updateonstart.isChecked()) {
parsebuildprop.editString("hw.acer.psensor_calib_min_base", "32717");
AlertDialog.Builder builder = new AlertDialog.Builder(myactivity);
builder.setTitle("Are you sure?");
builder.setCancelable(true);
builder.setMessage("It's very important to have the latest available updates! Please check this option only if you have problems launching app.");
builder.setPositiveButton("Undo", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Editor editor = prefs.edit();
editor.putBoolean("updateonstart",true);
updateonstart.setChecked(true);
editor.commit();
}
});
builder.setNegativeButton("Close", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
builder.create().show();
}
return true;
}
});
reportissue.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
ConnectivityManager connManager = (ConnectivityManager)myactivity.getSystemService(Context.CONNECTIVITY_SERVICE);
android.net.NetworkInfo netInfo= connManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
android.net.NetworkInfo wifiInfo= connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (netInfo.getState() == android.net.NetworkInfo.State.CONNECTED ||
wifiInfo.getState() == android.net.NetworkInfo.State.CONNECTED ) {
ProgressDialog.show(myactivity, "Report an issue",
"Loading issues list...", true);
Intent myintent = new Intent (Intent.ACTION_VIEW);
myintent.setClassName(myactivity, ReportIssue.class.getName());
startActivity(myintent);
}else{
Toast.makeText(myactivity, "ERROR: NO CONNECTIONS!", 4000).show();
}
return true;
}
});
menu_info.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
showhelp();
return true;
}
});
resetall.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
LSystem.RemountRW();
LiquidSettings.runRootCommand("rm -f /system/etc/init.d/06sensitivity");
LiquidSettings.runRootCommand("rm -f /system/etc/init.d/10batteryled");
LiquidSettings.runRootCommand("rm -f /system/etc/init.d/06vibrate");
LiquidSettings.runRootCommand("rm -f /system/etc/init.d/11bottomled");
LiquidSettings.runRootCommand("chmod 222 /sys/class/leds2/power");
LSystem.RemountROnly();
Editor editor = prefs.edit();
editor.putBoolean("firststart", true);
editor.commit();
new StartSystem().startsystem(myactivity);
return true;
}
});
// fixled.setOnPreferenceClickListener(new OnPreferenceClickListener() {
//
// public boolean onPreferenceClick(Preference preference) {
// return true;
// }
// });
if(prefs.getBoolean("updateonstart", true)){
//checkupdates();
new OTA_updates().checkupdates(myactivity,myactivity);
}
}
private void showhelp(){
Intent myintent = new Intent (Intent.ACTION_VIEW);
myintent.setClassName(myactivity, InfoPreferenceActivity.class.getName());
startActivity(myintent);
}
private void updateValues() {
editNoise.setSummary("Noise is set to " + noiseValue);
editSensitivity.setSummary("Sensitivity is set to " + sensitivityValue);
editSoftsens.setSummary("Softkey sensitivity is set to "+ softsensValue);
editHftime.setSummary("Softkey vibration time is set to "+ hftimeValue +"ms");
}
}
| true | true | public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (!LSystem.checkInitFolder()){
Toast.makeText(this, "Can't make init.d folder, your system must be rooted", 4000).show();
this.finish(); //Exit app
}
ROOT = LiquidSettings.isRoot();
prefs = PreferenceManager.getDefaultSharedPreferences(myactivity);
new StartSystem().startsystem(myactivity);
addPreferencesFromResource(R.xml.menu);
final Context context = getApplicationContext();
final CheckBoxPreference hf = (CheckBoxPreference)findPreference("hf");
final EditTextPreference sdcache = (EditTextPreference)findPreference("sdcache");
final CheckBoxPreference powerled = (CheckBoxPreference)findPreference("powerled");
final CheckBoxPreference noprox = (CheckBoxPreference)findPreference("noprox");
final CheckBoxPreference nobottom = (CheckBoxPreference)findPreference("nobottom");
final CheckBoxPreference updateonstart = (CheckBoxPreference)findPreference("updateonstart");
final CheckBoxPreference usemetalcamera = (CheckBoxPreference)findPreference("usemetalcamera");
final Preference menu_info = findPreference("menu_info");
final Preference mountsystem = findPreference("mountsystem");
final Preference diskspace = findPreference("diskspace");
final Preference hotreboot = findPreference("hotreboot");
final Preference forceupdate = findPreference("forceupdate");
final Preference donateclick = findPreference("donateclick");
final Preference v6scripttweaker = findPreference("v6scripttweaker");
final Preference sdmanscripttweaker = findPreference("sdmanscripttweaker");
final Preference sdmanscript = findPreference("sdmanscript");
final Preference reportissue = findPreference("reportissue");
final ListPreference networkmode = (ListPreference)findPreference("2g3gmode");
final Preference resetall = findPreference("resetall");
//noprox.setChecked((parsebuildprop.parseInt("hw.acer.psensor_calib_min_base")==32717));
editNoise = (EditTextPreference)findPreference("noise");
editSensitivity = (EditTextPreference)findPreference("sensitivity");
editSoftsens = (EditTextPreference)findPreference("softsens");
editHftime = (EditTextPreference)findPreference("hftime");
if (!LSystem.hapticAvailable())
hf.setEnabled(false);
else
hf.setChecked(LSystem.vibrStatus());
if (!SdCache.isCachePathAvailable())
sdcache.setEnabled(false);
if ((SDCacheSize=SdCache.getSdCacheSize()) >= 128){
sdcache.setText(Integer.toString(SDCacheSize));
}
noiseValue = editNoise.getText();
sensitivityValue = editSensitivity.getText();
softsensValue = editSoftsens.getText();
hftimeValue = editHftime.getText();
updateValues();
java.io.File file = new java.io.File("/system/app/Camera.stock_lock");
if (!file.exists()) {
usemetalcamera.setChecked(false);
}else{
usemetalcamera.setChecked(true);
}
editNoise.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
public boolean onPreferenceChange(Preference preference, Object newValue) {
if (!Strings.onlyNumber(newValue.toString())){
Toast.makeText(context, "You must enter a numeric value!", 4000).show();
return false;
} //Check if the value is numeric, THEN assign it to noiseValue
noiseValue = newValue.toString();
int noiseValueInt = Integer.parseInt(noiseValue);
if(noiseValueInt < 20)
noiseValue = "20";
else if(noiseValueInt > 75)
noiseValue = "75";
if(ROOT) {
if(ROOT && LSystem.RemountRW()) {
LiquidSettings.runRootCommand("echo "+Strings.getSens(sensitivityValue, noiseValue, softsensValue, hftimeValue)+" > /system/etc/init.d/06sensitivity");
LiquidSettings.runRootCommand("chmod +x /system/etc/init.d/06sensitivity");
LSystem.RemountROnly();
if (LiquidSettings.runRootCommand("./system/etc/init.d/06sensitivity"))
Toast.makeText(context, "Sensitivity set correctly", 4000).show();
else
Toast.makeText(context, "Error, unable to set noise", 4000).show();
}
updateValues();
} else {
Toast.makeText(context, "Sorry, you need ROOT permissions.", 4000).show();
}
return true;
}
});
editSensitivity.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
public boolean onPreferenceChange(Preference preference, Object newValue) {
if (!Strings.onlyNumber(newValue.toString())){
Toast.makeText(context, "You must enter a numeric value!", 4000).show();
return false;
} //Check if the value is numeric, THEN assign it to sensitivityValue
sensitivityValue = newValue.toString();
int sensitivityValueInt = Integer.parseInt(sensitivityValue);
if(sensitivityValueInt < (20))
sensitivityValue = ("20");
else if (sensitivityValueInt>(75))
sensitivityValue=("75");
if(ROOT) {
if(ROOT && LSystem.RemountRW()) {
LiquidSettings.runRootCommand("echo "+Strings.getSens(sensitivityValue, noiseValue, softsensValue, hftimeValue)+" > /system/etc/init.d/06sensitivity");
LiquidSettings.runRootCommand("chmod +x /system/etc/init.d/06sensitivity");
LSystem.RemountROnly();
if (LiquidSettings.runRootCommand("./system/etc/init.d/06sensitivity"))
Toast.makeText(context, "Sensitivity set correctly", 4000).show();
else
Toast.makeText(context, "Error, unable to set noise", 4000).show();
}
updateValues();
} else {
Toast.makeText(context, "Sorry, you need ROOT permissions.", 4000).show();
}
return true;
}
});
editSoftsens.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
public boolean onPreferenceChange(Preference preference, Object newValue) {
if (!Strings.onlyNumber(newValue.toString())){
Toast.makeText(context, "You must enter a numeric value!", 4000).show();
return false;
} //Check if the value is numeric, THEN assign it to sensitivityValue
softsensValue = newValue.toString();
int softsensValueInt = Integer.parseInt(softsensValue);
if(softsensValueInt < (15))
softsensValue = ("15");
else if (softsensValueInt>(30))
softsensValue=("30");
if(ROOT) {
if(ROOT && LSystem.RemountRW()) {
LiquidSettings.runRootCommand("echo "+Strings.getSens(sensitivityValue, noiseValue, softsensValue, hftimeValue)+" > /system/etc/init.d/06sensitivity");
LiquidSettings.runRootCommand("chmod +x /system/etc/init.d/06sensitivity");
LSystem.RemountROnly();
if (LiquidSettings.runRootCommand("./system/etc/init.d/06sensitivity"))
Toast.makeText(context, "Sensitivity set correctly", 4000).show();
else
Toast.makeText(context, "Error, unable to set noise", 4000).show();
}
updateValues();
} else {
Toast.makeText(context, "Sorry, you need ROOT permissions.", 4000).show();
}
return true;
}
});
powerled.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
if (ROOT){
if (powerled.isChecked()) {
LiquidSettings.runRootCommand("echo '0' > /sys/class/leds2/power");
LiquidSettings.runRootCommand("chmod 000 /sys/class/leds2/power");
}else{
LiquidSettings.runRootCommand("chmod 222 /sys/class/leds2/power");
}
if (BatteryLED.setdisable(powerled.isChecked())){
return true;
} else{
Toast.makeText(context, "Error while set Power LED disable", 4000).show();
return false;
}
}else {
Toast.makeText(context, "Sorry, you need ROOT permissions", 4000).show();
return false;
}
}
});
nobottom.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
if (ROOT){
if (nobottom.isChecked()) {
LiquidSettings.runRootCommand("echo '0' > /sys/class/leds2/bottom");
LiquidSettings.runRootCommand("chmod 000 /sys/class/leds2/bottom");
}else{
LiquidSettings.runRootCommand("chmod 222 /sys/class/leds2/bottom");
}
if (BottomLED.setdisable(nobottom.isChecked())){
return true;
} else{
Toast.makeText(context, "Error while set Bottom LED disable", 4000).show();
return false;
}
}else {
Toast.makeText(context, "Sorry, you need ROOT permissions", 4000).show();
return false;
}
}
});
hf.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
if(ROOT){
if(LSystem.RemountRW()) {
LiquidSettings.runRootCommand("echo " + ((hf.isChecked()) ? Strings.getvibr() : Strings.getnovibr()) + " > /system/etc/init.d/06vibrate");
LiquidSettings.runRootCommand("echo " + ((hf.isChecked()==true) ? "1": "0") +" > /sys/module/avr/parameters/vibr");
LiquidSettings.runRootCommand("chmod +x /system/etc/init.d/06vibrate");
LSystem.RemountROnly();
Toast.makeText(context, "Haptic set on " + Boolean.toString(hf.isChecked()), 4000).show();
} else {
Toast.makeText(context, "Error: unable to mount partition", 4000).show();
hf.setChecked(false);
}
} else {
Toast.makeText(context, "Sorry, you need ROOT permissions.", 4000).show();
hf.setChecked(false);
}
return true;
}
});
editHftime.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
public boolean onPreferenceChange(Preference preference, Object newValue) {
if (!Strings.onlyNumber(newValue.toString())){
Toast.makeText(context, "You must enter a numeric value!", 4000).show();
return false;
} //Check if the value is numeric, THEN assign it to sensitivityValue
hftimeValue = newValue.toString();
int hftimeValueInt = Integer.parseInt(hftimeValue);
if(hftimeValueInt < (10))
hftimeValue = ("10");
else if (hftimeValueInt>(2000))
hftimeValue=("2000");
if(ROOT) {
if(ROOT && LSystem.RemountRW()) {
LiquidSettings.runRootCommand("echo "+Strings.getSens(sensitivityValue, noiseValue, softsensValue, hftimeValue)+" > /system/etc/init.d/06sensitivity");
LiquidSettings.runRootCommand("chmod +x /system/etc/init.d/06sensitivity");
LSystem.RemountROnly();
if (LiquidSettings.runRootCommand("./system/etc/init.d/06sensitivity"))
Toast.makeText(context, "Sensitivity set correctly", 4000).show();
else
Toast.makeText(context, "Error, unable to set noise", 4000).show();
}
updateValues();
} else {
Toast.makeText(context, "Sorry, you need ROOT permissions.", 4000).show();
}
return true;
}
});
sdcache.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
public boolean onPreferenceChange(Preference preference, Object newValue) {
if (!Strings.onlyNumber(newValue.toString())){
Toast.makeText(context, "You must enter a numeric value!", 4000).show();
return false;
} //Check if the value is numeric, THEN assign it to sensitivityValue
String newValueString = newValue.toString();
int newValueInt = Integer.parseInt(newValueString);
if(newValueInt < 128)
newValueInt = 128;
else if (newValueInt > 4096)
newValueInt = 4096;
if (ROOT){
if (SdCache.setSDCache(newValueInt)){
Toast.makeText(context, "SD cache size set to " + newValueInt, 4000).show();
return true;
}else{
Toast.makeText(context, "Error while setting SD Cache", 4000).show();
return false;
}
} else
Toast.makeText(context, "Sorry you need root permissions", 4000).show();
return false;
}
});
networkmode.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference,
Object newValue) {
Editor editor = prefs.edit();
editor.putString("2g3gmode", newValue.toString());
editor.commit();
NetworkMode.switchnetworkmode(myactivity);
return true;
}
});
noprox.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
if (noprox.isChecked()) {
parsebuildprop.editString("hw.acer.psensor_calib_min_base", "32717");
}else{
parsebuildprop.editString("hw.acer.psensor_calib_min_base", "32716");
}
AlertDialog.Builder builder = new AlertDialog.Builder(myactivity);
builder.setTitle("Reboot required");
builder.setCancelable(true);
builder.setMessage("This option requires a reboot to be applied. Do you want to reboot now?");
builder.setPositiveButton("Reboot", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
LiquidSettings.runRootCommand("reboot");
}
});
builder.setNegativeButton("Close", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
builder.create().show();
return true;
}
});
v6scripttweaker.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
try {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.setComponent(new ComponentName("jackpal.androidterm2", "jackpal.androidterm2.Term"));
intent.putExtra("jackpal.androidterm.iInitialCommand", "su \r sh /system/xbin/V6SuperChargerLN.sh");
startActivity(intent);
} catch (Exception e) {
Toast.makeText(myactivity, "No terminal emulator app found", 4000).show();
}
return true;
}
});
sdmanscripttweaker.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
try {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.setComponent(new ComponentName("jackpal.androidterm2", "jackpal.androidter2.Term"));
intent.putExtra("jackpal.androidterm.iInitialCommand", "su \r sh /system/bin/sdman");
startActivity(intent);
} catch (Exception e) {
Toast.makeText(myactivity, "No terminal emulator app found", 4000).show();
}
return true;
}
});
sdmanscript.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
Intent myintent = new Intent (Intent.ACTION_VIEW);
myintent.setClassName(myactivity, SDMAN.class.getName());
startActivity(myintent);
return true;
}
});
usemetalcamera.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
LSystem.RemountRW();
if (usemetalcamera.isChecked()) {
LiquidSettings.runRootCommand("mv -f /system/app/Camera.apk /system/app/Camera.stock_lock");
LiquidSettings.runRootCommand("mv -f /system/app/Camera.metal_lock /system/app/Camera.apk");
LiquidSettings.runRootCommand("chmod 777 /system/app/Camera.apk");
LiquidSettings.runRootCommand("sync");
Toast.makeText(myactivity, "Choose 480p in camera settings!", 4000).show();
}else{
LiquidSettings.runRootCommand("mv -f /system/app/Camera.apk /system/app/Camera.metal_lock");
LiquidSettings.runRootCommand("mv -f /system/app/Camera.stock_lock /system/app/Camera.apk");
LiquidSettings.runRootCommand("chmod 777 /system/app/Camera.apk");
LiquidSettings.runRootCommand("sync");
}
LSystem.RemountROnly();
return true;
}
});
mountsystem.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
final AlertDialog.Builder builder = new AlertDialog.Builder(myactivity);
builder.setTitle("Mount system as...");
builder.setCancelable(true);
builder.setMessage("Choose RW if you want to write into system parition (read-write). Choose RO if you want to write-protect system partition (read-only). NOTICE: after a reboot system partition will be mounted as RO!");
builder.setPositiveButton("RW", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
LSystem.RemountRW();
Toast.makeText(myactivity, "Done", 4000).show();
}
});
builder.setNegativeButton("RO", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
LSystem.RemountROnly();
Toast.makeText(myactivity, "Done", 4000).show();
}
});
builder.create().show();
return true;
}
});
diskspace.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
final AlertDialog.Builder builder = new AlertDialog.Builder(myactivity);
builder.setTitle("DiskSpace");
builder.setCancelable(true);
builder.setMessage(DiskSpace.getdiskspace());
builder.setNegativeButton("Close", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
builder.create().show();
return true;
}
});
hotreboot.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
ProgressDialog.show(myactivity, "",
"Rebooting...", true);
LiquidSettings.runRootCommand("killall system_server");
return true;
}
});
donateclick.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
ConnectivityManager connManager = (ConnectivityManager)myactivity.getSystemService(Context.CONNECTIVITY_SERVICE);
android.net.NetworkInfo netInfo= connManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
android.net.NetworkInfo wifiInfo= connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (netInfo.getState() == android.net.NetworkInfo.State.CONNECTED ||
wifiInfo.getState() == android.net.NetworkInfo.State.CONNECTED ) {
Intent myintent = new Intent (Intent.ACTION_VIEW);
myintent.setClassName(context, Webview.class.getName());
startActivity(myintent);
}else{
Toast.makeText(myactivity, "ERROR: NO CONNECTIONS!", 4000).show();
}
return true;
}
});
forceupdate.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
//checkupdates();
new OTA_updates().checkupdates(myactivity, myactivity);
return true;
}
});
updateonstart.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
if (!updateonstart.isChecked()) {
parsebuildprop.editString("hw.acer.psensor_calib_min_base", "32717");
AlertDialog.Builder builder = new AlertDialog.Builder(myactivity);
builder.setTitle("Are you sure?");
builder.setCancelable(true);
builder.setMessage("It's very important to have the latest available updates! Please check this option only if you have problems launching app.");
builder.setPositiveButton("Undo", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Editor editor = prefs.edit();
editor.putBoolean("updateonstart",true);
updateonstart.setChecked(true);
editor.commit();
}
});
builder.setNegativeButton("Close", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
builder.create().show();
}
return true;
}
});
reportissue.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
ConnectivityManager connManager = (ConnectivityManager)myactivity.getSystemService(Context.CONNECTIVITY_SERVICE);
android.net.NetworkInfo netInfo= connManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
android.net.NetworkInfo wifiInfo= connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (netInfo.getState() == android.net.NetworkInfo.State.CONNECTED ||
wifiInfo.getState() == android.net.NetworkInfo.State.CONNECTED ) {
ProgressDialog.show(myactivity, "Report an issue",
"Loading issues list...", true);
Intent myintent = new Intent (Intent.ACTION_VIEW);
myintent.setClassName(myactivity, ReportIssue.class.getName());
startActivity(myintent);
}else{
Toast.makeText(myactivity, "ERROR: NO CONNECTIONS!", 4000).show();
}
return true;
}
});
menu_info.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
showhelp();
return true;
}
});
resetall.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
LSystem.RemountRW();
LiquidSettings.runRootCommand("rm -f /system/etc/init.d/06sensitivity");
LiquidSettings.runRootCommand("rm -f /system/etc/init.d/10batteryled");
LiquidSettings.runRootCommand("rm -f /system/etc/init.d/06vibrate");
LiquidSettings.runRootCommand("rm -f /system/etc/init.d/11bottomled");
LiquidSettings.runRootCommand("chmod 222 /sys/class/leds2/power");
LSystem.RemountROnly();
Editor editor = prefs.edit();
editor.putBoolean("firststart", true);
editor.commit();
new StartSystem().startsystem(myactivity);
return true;
}
});
// fixled.setOnPreferenceClickListener(new OnPreferenceClickListener() {
//
// public boolean onPreferenceClick(Preference preference) {
// return true;
// }
// });
if(prefs.getBoolean("updateonstart", true)){
//checkupdates();
new OTA_updates().checkupdates(myactivity,myactivity);
}
}
| public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (!LSystem.checkInitFolder()){
Toast.makeText(this, "Can't make init.d folder, your system must be rooted", 4000).show();
this.finish(); //Exit app
}
ROOT = LiquidSettings.isRoot();
prefs = PreferenceManager.getDefaultSharedPreferences(myactivity);
new StartSystem().startsystem(myactivity);
addPreferencesFromResource(R.xml.menu);
final Context context = getApplicationContext();
final CheckBoxPreference hf = (CheckBoxPreference)findPreference("hf");
final EditTextPreference sdcache = (EditTextPreference)findPreference("sdcache");
final CheckBoxPreference powerled = (CheckBoxPreference)findPreference("powerled");
final CheckBoxPreference noprox = (CheckBoxPreference)findPreference("noprox");
final CheckBoxPreference nobottom = (CheckBoxPreference)findPreference("nobottom");
final CheckBoxPreference updateonstart = (CheckBoxPreference)findPreference("updateonstart");
final CheckBoxPreference usemetalcamera = (CheckBoxPreference)findPreference("usemetalcamera");
final Preference menu_info = findPreference("menu_info");
final Preference mountsystem = findPreference("mountsystem");
final Preference diskspace = findPreference("diskspace");
final Preference hotreboot = findPreference("hotreboot");
final Preference forceupdate = findPreference("forceupdate");
final Preference donateclick = findPreference("donateclick");
final Preference v6scripttweaker = findPreference("v6scripttweaker");
final Preference sdmanscripttweaker = findPreference("sdmanscripttweaker");
final Preference sdmanscript = findPreference("sdmanscript");
final Preference reportissue = findPreference("reportissue");
final ListPreference networkmode = (ListPreference)findPreference("2g3gmode");
final Preference resetall = findPreference("resetall");
//noprox.setChecked((parsebuildprop.parseInt("hw.acer.psensor_calib_min_base")==32717));
editNoise = (EditTextPreference)findPreference("noise");
editSensitivity = (EditTextPreference)findPreference("sensitivity");
editSoftsens = (EditTextPreference)findPreference("softsens");
editHftime = (EditTextPreference)findPreference("hftime");
if (!LSystem.hapticAvailable())
hf.setEnabled(false);
else
hf.setChecked(LSystem.vibrStatus());
if (!SdCache.isCachePathAvailable())
sdcache.setEnabled(false);
if ((SDCacheSize=SdCache.getSdCacheSize()) >= 128){
sdcache.setText(Integer.toString(SDCacheSize));
}
noiseValue = editNoise.getText();
sensitivityValue = editSensitivity.getText();
softsensValue = editSoftsens.getText();
hftimeValue = editHftime.getText();
updateValues();
java.io.File file = new java.io.File("/system/app/Camera.stock_lock");
if (!file.exists()) {
usemetalcamera.setChecked(false);
}else{
usemetalcamera.setChecked(true);
}
editNoise.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
public boolean onPreferenceChange(Preference preference, Object newValue) {
if (!Strings.onlyNumber(newValue.toString())){
Toast.makeText(context, "You must enter a numeric value!", 4000).show();
return false;
} //Check if the value is numeric, THEN assign it to noiseValue
noiseValue = newValue.toString();
int noiseValueInt = Integer.parseInt(noiseValue);
if(noiseValueInt < 20)
noiseValue = "20";
else if(noiseValueInt > 75)
noiseValue = "75";
if(ROOT) {
if(ROOT && LSystem.RemountRW()) {
LiquidSettings.runRootCommand("echo "+Strings.getSens(sensitivityValue, noiseValue, softsensValue, hftimeValue)+" > /system/etc/init.d/06sensitivity");
LiquidSettings.runRootCommand("chmod +x /system/etc/init.d/06sensitivity");
LSystem.RemountROnly();
if (LiquidSettings.runRootCommand("./system/etc/init.d/06sensitivity"))
Toast.makeText(context, "Sensitivity set correctly", 4000).show();
else
Toast.makeText(context, "Error, unable to set noise", 4000).show();
}
updateValues();
} else {
Toast.makeText(context, "Sorry, you need ROOT permissions.", 4000).show();
}
return true;
}
});
editSensitivity.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
public boolean onPreferenceChange(Preference preference, Object newValue) {
if (!Strings.onlyNumber(newValue.toString())){
Toast.makeText(context, "You must enter a numeric value!", 4000).show();
return false;
} //Check if the value is numeric, THEN assign it to sensitivityValue
sensitivityValue = newValue.toString();
int sensitivityValueInt = Integer.parseInt(sensitivityValue);
if(sensitivityValueInt < (20))
sensitivityValue = ("20");
else if (sensitivityValueInt>(75))
sensitivityValue=("75");
if(ROOT) {
if(ROOT && LSystem.RemountRW()) {
LiquidSettings.runRootCommand("echo "+Strings.getSens(sensitivityValue, noiseValue, softsensValue, hftimeValue)+" > /system/etc/init.d/06sensitivity");
LiquidSettings.runRootCommand("chmod +x /system/etc/init.d/06sensitivity");
LSystem.RemountROnly();
if (LiquidSettings.runRootCommand("./system/etc/init.d/06sensitivity"))
Toast.makeText(context, "Sensitivity set correctly", 4000).show();
else
Toast.makeText(context, "Error, unable to set noise", 4000).show();
}
updateValues();
} else {
Toast.makeText(context, "Sorry, you need ROOT permissions.", 4000).show();
}
return true;
}
});
editSoftsens.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
public boolean onPreferenceChange(Preference preference, Object newValue) {
if (!Strings.onlyNumber(newValue.toString())){
Toast.makeText(context, "You must enter a numeric value!", 4000).show();
return false;
} //Check if the value is numeric, THEN assign it to sensitivityValue
softsensValue = newValue.toString();
int softsensValueInt = Integer.parseInt(softsensValue);
if(softsensValueInt < (15))
softsensValue = ("15");
else if (softsensValueInt>(30))
softsensValue=("30");
if(ROOT) {
if(ROOT && LSystem.RemountRW()) {
LiquidSettings.runRootCommand("echo "+Strings.getSens(sensitivityValue, noiseValue, softsensValue, hftimeValue)+" > /system/etc/init.d/06sensitivity");
LiquidSettings.runRootCommand("chmod +x /system/etc/init.d/06sensitivity");
LSystem.RemountROnly();
if (LiquidSettings.runRootCommand("./system/etc/init.d/06sensitivity"))
Toast.makeText(context, "Sensitivity set correctly", 4000).show();
else
Toast.makeText(context, "Error, unable to set noise", 4000).show();
}
updateValues();
} else {
Toast.makeText(context, "Sorry, you need ROOT permissions.", 4000).show();
}
return true;
}
});
powerled.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
if (ROOT){
if (powerled.isChecked()) {
LiquidSettings.runRootCommand("echo '0' > /sys/class/leds2/power");
LiquidSettings.runRootCommand("chmod 000 /sys/class/leds2/power");
}else{
LiquidSettings.runRootCommand("chmod 222 /sys/class/leds2/power");
}
if (BatteryLED.setdisable(powerled.isChecked())){
return true;
} else{
Toast.makeText(context, "Error while set Power LED disable", 4000).show();
return false;
}
}else {
Toast.makeText(context, "Sorry, you need ROOT permissions", 4000).show();
return false;
}
}
});
nobottom.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
if (ROOT){
if (nobottom.isChecked()) {
LiquidSettings.runRootCommand("echo '0' > /sys/class/leds2/bottom");
LiquidSettings.runRootCommand("chmod 000 /sys/class/leds2/bottom");
}else{
LiquidSettings.runRootCommand("chmod 222 /sys/class/leds2/bottom");
}
if (BottomLED.setdisable(nobottom.isChecked())){
return true;
} else{
Toast.makeText(context, "Error while set Bottom LED disable", 4000).show();
return false;
}
}else {
Toast.makeText(context, "Sorry, you need ROOT permissions", 4000).show();
return false;
}
}
});
hf.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
if(ROOT){
if(LSystem.RemountRW()) {
LiquidSettings.runRootCommand("echo " + ((hf.isChecked()) ? Strings.getvibr() : Strings.getnovibr()) + " > /system/etc/init.d/06vibrate");
LiquidSettings.runRootCommand("echo " + ((hf.isChecked()==true) ? "1": "0") +" > /sys/module/avr/parameters/vibr");
LiquidSettings.runRootCommand("chmod +x /system/etc/init.d/06vibrate");
LSystem.RemountROnly();
Toast.makeText(context, "Haptic set on " + Boolean.toString(hf.isChecked()), 4000).show();
} else {
Toast.makeText(context, "Error: unable to mount partition", 4000).show();
hf.setChecked(false);
}
} else {
Toast.makeText(context, "Sorry, you need ROOT permissions.", 4000).show();
hf.setChecked(false);
}
return true;
}
});
editHftime.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
public boolean onPreferenceChange(Preference preference, Object newValue) {
if (!Strings.onlyNumber(newValue.toString())){
Toast.makeText(context, "You must enter a numeric value!", 4000).show();
return false;
} //Check if the value is numeric, THEN assign it to sensitivityValue
hftimeValue = newValue.toString();
int hftimeValueInt = Integer.parseInt(hftimeValue);
if(hftimeValueInt < (10))
hftimeValue = ("10");
else if (hftimeValueInt>(2000))
hftimeValue=("2000");
if(ROOT) {
if(ROOT && LSystem.RemountRW()) {
LiquidSettings.runRootCommand("echo "+Strings.getSens(sensitivityValue, noiseValue, softsensValue, hftimeValue)+" > /system/etc/init.d/06sensitivity");
LiquidSettings.runRootCommand("chmod +x /system/etc/init.d/06sensitivity");
LSystem.RemountROnly();
if (LiquidSettings.runRootCommand("./system/etc/init.d/06sensitivity"))
Toast.makeText(context, "Sensitivity set correctly", 4000).show();
else
Toast.makeText(context, "Error, unable to set noise", 4000).show();
}
updateValues();
} else {
Toast.makeText(context, "Sorry, you need ROOT permissions.", 4000).show();
}
return true;
}
});
sdcache.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
public boolean onPreferenceChange(Preference preference, Object newValue) {
if (!Strings.onlyNumber(newValue.toString())){
Toast.makeText(context, "You must enter a numeric value!", 4000).show();
return false;
} //Check if the value is numeric, THEN assign it to sensitivityValue
String newValueString = newValue.toString();
int newValueInt = Integer.parseInt(newValueString);
if(newValueInt < 128)
newValueInt = 128;
else if (newValueInt > 4096)
newValueInt = 4096;
if (ROOT){
if (SdCache.setSDCache(newValueInt)){
Toast.makeText(context, "SD cache size set to " + newValueInt, 4000).show();
return true;
}else{
Toast.makeText(context, "Error while setting SD Cache", 4000).show();
return false;
}
} else
Toast.makeText(context, "Sorry you need root permissions", 4000).show();
return false;
}
});
networkmode.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference,
Object newValue) {
Editor editor = prefs.edit();
editor.putString("2g3gmode", newValue.toString());
editor.commit();
NetworkMode.switchnetworkmode(myactivity);
return true;
}
});
noprox.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
if (noprox.isChecked()) {
parsebuildprop.editString("hw.acer.psensor_calib_min_base", "32717");
}else{
parsebuildprop.editString("hw.acer.psensor_calib_min_base", "32716");
}
AlertDialog.Builder builder = new AlertDialog.Builder(myactivity);
builder.setTitle("Reboot required");
builder.setCancelable(true);
builder.setMessage("This option requires a reboot to be applied. Do you want to reboot now?");
builder.setPositiveButton("Reboot", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
LiquidSettings.runRootCommand("reboot");
}
});
builder.setNegativeButton("Close", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
builder.create().show();
return true;
}
});
v6scripttweaker.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
try {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.setComponent(new ComponentName("jackpal.androidterm2", "jackpal.androidterm2.Term"));
intent.putExtra("jackpal.androidterm.iInitialCommand", "su \r sh /system/xbin/V6SuperChargerLN.sh");
startActivity(intent);
} catch (Exception e) {
Toast.makeText(myactivity, "No terminal emulator app found", 4000).show();
}
return true;
}
});
sdmanscripttweaker.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
try {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.setComponent(new ComponentName("jackpal.androidterm2", "jackpal.androidterm2.Term"));
intent.putExtra("jackpal.androidterm.iInitialCommand", "su \r sh /system/bin/sdman");
startActivity(intent);
} catch (Exception e) {
Toast.makeText(myactivity, "No terminal emulator app found", 4000).show();
}
return true;
}
});
sdmanscript.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
Intent myintent = new Intent (Intent.ACTION_VIEW);
myintent.setClassName(myactivity, SDMAN.class.getName());
startActivity(myintent);
return true;
}
});
usemetalcamera.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
LSystem.RemountRW();
if (usemetalcamera.isChecked()) {
LiquidSettings.runRootCommand("mv -f /system/app/Camera.apk /system/app/Camera.stock_lock");
LiquidSettings.runRootCommand("mv -f /system/app/Camera.metal_lock /system/app/Camera.apk");
LiquidSettings.runRootCommand("chmod 777 /system/app/Camera.apk");
LiquidSettings.runRootCommand("sync");
Toast.makeText(myactivity, "Choose 480p in camera settings!", 4000).show();
}else{
LiquidSettings.runRootCommand("mv -f /system/app/Camera.apk /system/app/Camera.metal_lock");
LiquidSettings.runRootCommand("mv -f /system/app/Camera.stock_lock /system/app/Camera.apk");
LiquidSettings.runRootCommand("chmod 777 /system/app/Camera.apk");
LiquidSettings.runRootCommand("sync");
}
LSystem.RemountROnly();
return true;
}
});
mountsystem.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
final AlertDialog.Builder builder = new AlertDialog.Builder(myactivity);
builder.setTitle("Mount system as...");
builder.setCancelable(true);
builder.setMessage("Choose RW if you want to write into system parition (read-write). Choose RO if you want to write-protect system partition (read-only). NOTICE: after a reboot system partition will be mounted as RO!");
builder.setPositiveButton("RW", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
LSystem.RemountRW();
Toast.makeText(myactivity, "Done", 4000).show();
}
});
builder.setNegativeButton("RO", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
LSystem.RemountROnly();
Toast.makeText(myactivity, "Done", 4000).show();
}
});
builder.create().show();
return true;
}
});
diskspace.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
final AlertDialog.Builder builder = new AlertDialog.Builder(myactivity);
builder.setTitle("DiskSpace");
builder.setCancelable(true);
builder.setMessage(DiskSpace.getdiskspace());
builder.setNegativeButton("Close", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
builder.create().show();
return true;
}
});
hotreboot.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
ProgressDialog.show(myactivity, "",
"Rebooting...", true);
LiquidSettings.runRootCommand("killall system_server");
return true;
}
});
donateclick.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
ConnectivityManager connManager = (ConnectivityManager)myactivity.getSystemService(Context.CONNECTIVITY_SERVICE);
android.net.NetworkInfo netInfo= connManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
android.net.NetworkInfo wifiInfo= connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (netInfo.getState() == android.net.NetworkInfo.State.CONNECTED ||
wifiInfo.getState() == android.net.NetworkInfo.State.CONNECTED ) {
Intent myintent = new Intent (Intent.ACTION_VIEW);
myintent.setClassName(context, Webview.class.getName());
startActivity(myintent);
}else{
Toast.makeText(myactivity, "ERROR: NO CONNECTIONS!", 4000).show();
}
return true;
}
});
forceupdate.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
//checkupdates();
new OTA_updates().checkupdates(myactivity, myactivity);
return true;
}
});
updateonstart.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
if (!updateonstart.isChecked()) {
parsebuildprop.editString("hw.acer.psensor_calib_min_base", "32717");
AlertDialog.Builder builder = new AlertDialog.Builder(myactivity);
builder.setTitle("Are you sure?");
builder.setCancelable(true);
builder.setMessage("It's very important to have the latest available updates! Please check this option only if you have problems launching app.");
builder.setPositiveButton("Undo", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Editor editor = prefs.edit();
editor.putBoolean("updateonstart",true);
updateonstart.setChecked(true);
editor.commit();
}
});
builder.setNegativeButton("Close", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
builder.create().show();
}
return true;
}
});
reportissue.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
ConnectivityManager connManager = (ConnectivityManager)myactivity.getSystemService(Context.CONNECTIVITY_SERVICE);
android.net.NetworkInfo netInfo= connManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
android.net.NetworkInfo wifiInfo= connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (netInfo.getState() == android.net.NetworkInfo.State.CONNECTED ||
wifiInfo.getState() == android.net.NetworkInfo.State.CONNECTED ) {
ProgressDialog.show(myactivity, "Report an issue",
"Loading issues list...", true);
Intent myintent = new Intent (Intent.ACTION_VIEW);
myintent.setClassName(myactivity, ReportIssue.class.getName());
startActivity(myintent);
}else{
Toast.makeText(myactivity, "ERROR: NO CONNECTIONS!", 4000).show();
}
return true;
}
});
menu_info.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
showhelp();
return true;
}
});
resetall.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
LSystem.RemountRW();
LiquidSettings.runRootCommand("rm -f /system/etc/init.d/06sensitivity");
LiquidSettings.runRootCommand("rm -f /system/etc/init.d/10batteryled");
LiquidSettings.runRootCommand("rm -f /system/etc/init.d/06vibrate");
LiquidSettings.runRootCommand("rm -f /system/etc/init.d/11bottomled");
LiquidSettings.runRootCommand("chmod 222 /sys/class/leds2/power");
LSystem.RemountROnly();
Editor editor = prefs.edit();
editor.putBoolean("firststart", true);
editor.commit();
new StartSystem().startsystem(myactivity);
return true;
}
});
// fixled.setOnPreferenceClickListener(new OnPreferenceClickListener() {
//
// public boolean onPreferenceClick(Preference preference) {
// return true;
// }
// });
if(prefs.getBoolean("updateonstart", true)){
//checkupdates();
new OTA_updates().checkupdates(myactivity,myactivity);
}
}
|
diff --git a/src/codegen/Codegen.java b/src/codegen/Codegen.java
index e146ef7..49c93c6 100644
--- a/src/codegen/Codegen.java
+++ b/src/codegen/Codegen.java
@@ -1,520 +1,521 @@
package codegen;
import ast.*;
import java.util.*;
import java.io.*;
import visitor.*;
/* This is currently a total mess and should be farmed out a little bit, Should write IR nodes for every
* ast node but much more organized, but this is for a later time and not oh god behind schedule crunch time
*
* TODO: make this not embarassing
*/
public class Codegen implements AstVisitor
{
private Map<String,Type> typedefs;
private OutputStreamWriter writer;
public Codegen(OutputStreamWriter writer)
{
typedefs = new HashMap<String,Type>();
this.writer = writer;
}
public void accept(Program p)
{
//TODO: Print our shared library code, classes loaders etc
emit(CudaCode.helpers());
p.graph.visit(this);
for(Def d: p.defs)
d.visit(this);
}
public void accept(Graph g)
{
for(AttributeDef attdef : g.natts)
typedefs.put(attdef.id.id,attdef.type);
for(AttributeDef attdef : g.eatts)
typedefs.put(attdef.id.id,attdef.type);
}
public void accept(OpExp exp)
{
//should be handled from OpDef
}
public void accept(OpDef def)
{
List<Tuple> node_items = get_node_items(def.exp.tuples);
List<String> node_names = get_node_names(def.exp.tuples);
List<Tuple> edge_items = get_edge_items(def.exp.tuples);
List<Attribute> attributes = get_attributes(def.exp.tuples);
String params = get_param_string(node_names,edge_items);
//write our helper methods...
CheckShape(def);
CheckGuard(def);
Apply(def);
emit("__global__ void _kernel_"+def.id.id+"(bool *chaged, int unroll) \n{");
//Emit edge/node decls
int num_edges = 0;
for(Tuple t : def.exp.tuples) {
switch(t.type) {
case EDGES:
emit("Edge *e"+num_edges+++";\n");
break;
case NODES:
emit("Node *"+get_prop_type(t,Type.Types.NODE)+";\n");
break;
}
}
//default changed to false
emit("*changed = false;");
//TODO: Current supporting three types of ops, Global, 1 vertex, 2 verts with shared edge
//empty args, just call apply
if(def.exp.tuples.size() == 0) {
emit("*changed = _apply_"+def.id.id+"();");
} else if(node_items.size() == 1) {
emit("int _id = threadIdx.x;");
emit(node_names.get(0)+ " = _get_node(_id);");
emit("*changed = _apply_"+def.id.id+"("+params+");");
} else if(node_items.size() == 2 && edge_items.size() == 1) {
emit("int _id = threadIdx.x;");
emit(node_names.get(0)+ " = _get_node(_id);");
//choose which edges we are iterating over, in edges or out edges
//if the first node is the src then out_edges, otherwise first node is dest and go for in_edges
String edge_map = (node_names.get(0).equals(get_prop_name(edge_items.get(0),"src"))) ? "out_edges" : "in_edges";
+ String edge_side = (node_names.get(0).equals(get_prop_name(edge_items.get(0),"src"))) ? "dst" : "src";
//iterate over edges like a boss
- //emit("for( std::map<int,Edge*>::iterator _it="+node_names.get(0)+"->"+edge_map+".begin(); _it != " +node_names.get(0)+"->"+edge_map+".end(); ++it) {");
emit("for(int _i = 0; _i < "+node_names.get(0)+"->"+edge_map+"_size ; _i++) {");
- emit(node_names.get(1)+ " = "+node_names.get(0)+"->" + edge_map+"[_i];");
+ emit("e0 = "+node_names.get(0)+"->" + edge_map+"[_i];");
+ emit(node_names.get(1)+" = e0->"+edge_side+";");
emit("*changed |= _apply_"+def.id.id+"("+params+");");
emit("}");
} else {
System.err.println("Unsupported operation format");
}
emit("}\n");
}
public void Apply(OpDef def)
{
List<Tuple> node_items = get_node_items(def.exp.tuples);
List<String> node_names = get_node_names(def.exp.tuples);
List<Tuple> edge_items = get_edge_items(def.exp.tuples);
List<Attribute> attributes = get_attributes(def.exp.tuples);
//Generate the apply
String params = get_param_string(node_names,edge_items);
String args = get_arg_string(node_names,edge_items);
emit("__device__ inline bool _apply_"+def.id.id+"("+args+")\n{") ;
emit("bool _changed = false;");
emit("if(!_checkshape_"+def.id.id+"("+params+")) return;");
//Make the array of nodes for locking
StringBuilder nodebuilder = new StringBuilder();
for(String s : node_names)
nodebuilder.append(s+",");
emit("Node *_nodes[] = {"+nodebuilder+"};");
//sort them so we don't get in a deadlock
emit("_sort(nodes,"+node_names.size()+");");
//Lock
for(int i=0;i<node_names.size();i++)
emit("nodes["+i+"].lock();");
//now get all the needed attributes
emitGets(node_items,edge_items);
//guard check
emit("if(_checkguard_"+def.id.id+"("+params+")) {");
for(Assignment assignment : def.exp.assignments)
assignment.visit(this);
//TODO: Do we need to emit better code than this or is passing the guard enough to set changed to true?
emit("_changed=true;");
emit("}"); //close to if checkguard
//unlock
for(int i=0;i<node_names.size();i++)
emit("nodes["+i+"].unlock();");
emit("return _changed;");
emit("}\n");
}
public void CheckGuard(OpDef def)
{
/*TODO: This needs to go somewhere and be shared, probably in an OpDef IR node*/
List<Tuple> node_items = get_node_items(def.exp.tuples);
List<String> node_names = get_node_names(def.exp.tuples);
List<Tuple> edge_items = get_edge_items(def.exp.tuples);
List<Attribute> attributes = get_attributes(def.exp.tuples);
String args = get_arg_string(node_names,edge_items);
emit("__device__ inline bool _checkguard_"+def.id.id+"("+args+")\n{");
emitGets(node_items,edge_items);
emit("return ");
def.exp.bexp.visit(this);
emit(";\n}\n");
}
public void CheckShape(OpDef def)
{
/*
* Should emit something like __device__ int _checkshape_op([records])
* { return ...}
*
*
*/
//emit highly unoptimized code, let someone else handle that noise
//Categorize
List<Tuple> node_items = get_node_items(def.exp.tuples);
List<String> node_names = get_node_names(def.exp.tuples);
List<Tuple> edge_items = get_edge_items(def.exp.tuples);
List<Attribute> attributes = get_attributes(def.exp.tuples);
String args = get_arg_string(node_names,edge_items);
emit("__device__ inline bool _checkshape_"+def.id.id+"("+args+")\n{");
for (int i=0;i<node_items.size();i++) {
for (int j=0;j<i;j++) {
String ni = get_prop_type(node_items.get(i),Type.Types.NODE);
String nj = get_prop_type(node_items.get(j),Type.Types.NODE);
emit("if("+nj+"=="+ni+") return false;");
}
}
for (int i=0;i<edge_items.size();i++) {
//emit code checking Edge(src,dst). Assume all edges have a src and dst, if not W/E.
String src = get_prop_name(edge_items.get(i),"src");
String dst = get_prop_name(edge_items.get(i),"dst");
emit("if(!_edge("+src+","+dst+")) return false;");
}
emit("return true;\n}\n");
}
private void emit(String s)
{
try{
writer.write(s);
}catch (Exception e) {/*screw you java*/}
}
//Util methods for finding the src,dst of edges
private String get_prop_type(Tuple t,Type.Types prop)
{
for(Attribute at : t.attributes) {
if(this.typedefs.get(at.id.id).of == prop)
return at.var.id;
}
return "!!!!Error!!!!";
}
private String get_prop_name(Tuple t,String prop)
{
for(Attribute at : t.attributes) {
if(at.id.id.equals(prop))
return at.var.id;
}
return "!!!!Error!!!!";
}
public void accept(BoolAnd exp)
{
exp.lhs.visit(this);
emit(" && ");
exp.rhs.visit(this);
}
public void accept(BoolOr exp)
{
exp.lhs.visit(this);
emit(" || ");
exp.rhs.visit(this);
}
public void accept(BoolEq exp)
{
exp.lhs.visit(this);
emit(" == ");
exp.rhs.visit(this);
}
public void accept(BoolIn exp)
{
emit("("+exp.id.id+".count(");
exp.exp.visit(this);
emit(") > 0)");
}
public void accept(ast.Set exp)
{
//TODO
}
public void accept(Empty exp)
{
//TODO
}
public void accept(IntConst exp)
{
emit(""+exp.value);
}
public void accept(Var exp)
{
emit("*");
emit(exp.name.id);
}
public void accept(LessThan exp)
{
exp.lhs.visit(this);
emit(" < ");
exp.rhs.visit(this);
}
public void accept(True exp)
{
emit("true");
}
public void accept(False exp)
{
emit("false");
}
public void accept(Times exp)
{
exp.lhs.visit(this);
emit(" * ");
exp.rhs.visit(this);
}
public void accept(Plus exp)
{
exp.lhs.visit(this);
emit(" + ");
exp.rhs.visit(this);
}
public void accept(Minus exp)
{
exp.lhs.visit(this);
emit(" - ");
exp.rhs.visit(this);
}
public void accept(Div exp)
{
exp.lhs.visit(this);
emit(" / ");
exp.rhs.visit(this);
}
public void accept(Not exp)
{
emit("!");
exp.exp.visit(this);
}
public void accept(Intersection exp)
{
//TODO:Make sure out Set class supports & for intersection
exp.lhs.visit(this);
emit(" & ");
exp.rhs.visit(this);
}
public void accept(Union exp)
{
//TODO:Make sure out Set class supports | for union
exp.lhs.visit(this);
emit(" | ");
exp.rhs.visit(this);
}
public void accept(If exp)
{
emit("(");
exp.condition.visit(this);
emit("?");
exp.tcase.visit(this);
emit(":");
exp.fcase.visit(this);
emit(")");
}
public void accept(Tuple t)
{
//shouldn't happen
}
public void accept(SetType s)
{
emit(this.typeToString(s));
}
public void accept(BaseType b)
{
emit(this.typeToString(b));
}
public void accept(ForEach f)
{
//TODO
}
public void accept(Iterate f)
{
//TODO
}
public void accept(For f)
{
//TODO
}
public void accept(AcidStatement a)
{
//TODO
}
public void accept(Identifier id)
{
//TODO (might not be needed anywhere)
}
public void accept(AttributeDef def)
{
//TODO
}
public void accept(ActionDef def)
{
//TODO
}
public void accept(Attribute att)
{
//TODO
}
public void accept(Assignment assign)
{
emit("*"+assign.id.id +" = ");
assign.exp.visit(this);
emit(";");
}
public void accept(Global global)
{
global.type.visit(this);
emit(" "+global.name.id+";");
}
public void accept(SchedExp exp)
{
//TODO
}
public void accept(JoinStatement stm)
{
stm.s1.visit(this);
stm.s2.visit(this);
}
//Helper method for Type, move to a Type IR at some point
public String typeToString(Type t)
{
if(t instanceof SetType)
return "set<"+typesToString(t.of)+">";
else return typesToString(t.of);
}
public String typesToString(Type.Types t)
{
switch(t){
case FLOAT:
return "restrict float*";
case INT:
return "restrict int*";
case NODE:
return "Node*";
case EDGE:
return "Edge*";
default:
return "";
}
}
//Helper methods for opdef, TODO:move to a util class someday
private List<Tuple> get_node_items(List<Tuple> tuples)
{
List<Tuple> node_items = new ArrayList<Tuple>();
for(Tuple t: tuples){
switch(t.type) {
case NODES:
node_items.add(t);
break;
}
}
return node_items;
}
private List<Tuple> get_edge_items(List<Tuple> tuples)
{
List<Tuple> edge_items = new ArrayList<Tuple>();
for(Tuple t: tuples){
switch(t.type) {
case EDGES:
edge_items.add(t);
break;
}
}
return edge_items;
}
private List<Attribute> get_attributes(List<Tuple> tuples)
{
List<Attribute> attributes = new ArrayList<Attribute>();
for(Tuple t: tuples){
for(Attribute at : t.attributes)
attributes.add(at);
}
return attributes;
}
private List<String> get_node_names(List<Tuple> tuples)
{
List<String> names = new ArrayList<String>();
for(Tuple t: tuples){
switch(t.type) {
case NODES:
names.add(get_prop_type(t,Type.Types.NODE));
break;
}
}
return names;
}
public String get_param_string(List<String> node_names, List<Tuple> edge_items)
{
StringBuilder parambuilder = new StringBuilder("");
for (int i=0; i<node_names.size();i++) {
String s = node_names.get(i);
parambuilder.append(s + ((i < node_names.size()-1) ? "," : " "));
}
for (int i=0; i<edge_items.size();i++) {
parambuilder.append(",e"+i );
}
return parambuilder.toString();
}
public String get_arg_string(List<String> node_names, List<Tuple> edge_items)
{
StringBuilder argbuilder = new StringBuilder(""); //for the args coming in
for (int i=0; i<node_names.size();i++) {
String s = node_names.get(i);
argbuilder.append("Node* " + s + ((i < node_names.size()-1) ? "," : ""));
}
for (int i=0; i<edge_items.size();i++) {
argbuilder.append(", Edge *e" + i);
}
return argbuilder.toString();
}
public void emitGets(List<Tuple> node_items, List<Tuple> edge_items)
{
java.util.Set<String> declared = new HashSet<String>();
for(Tuple node : node_items) {
for(Attribute at : node.attributes) {
if(this.typedefs.get(at.id.id).of == Type.Types.NODE)
continue;
if(declared.contains(at.var.id))
continue;
declared.add(at.var.id);
emit(this.typeToString(typedefs.get(at.id.id))+" "+at.var.id);
emit(" = &"+ get_prop_type(node,Type.Types.NODE)+"->attribute_"+at.id.id+";\n");
}
}
int i=0;
for(Tuple edge : edge_items) {
String src = get_prop_name(edge,"src");
String dst = get_prop_name(edge,"dst");
for(Attribute at : edge.attributes) {
if(this.typedefs.get(at.id.id).of == Type.Types.NODE)
continue;
if(declared.contains(at.var.id))
continue;
declared.add(at.var.id);
emit(this.typeToString(typedefs.get(at.id.id))+" "+at.var.id);
emit(" = &e"+i+"->attribute_"+at.id.id+";\n");
}
i++;
}
}
}
| false | true | public void accept(OpDef def)
{
List<Tuple> node_items = get_node_items(def.exp.tuples);
List<String> node_names = get_node_names(def.exp.tuples);
List<Tuple> edge_items = get_edge_items(def.exp.tuples);
List<Attribute> attributes = get_attributes(def.exp.tuples);
String params = get_param_string(node_names,edge_items);
//write our helper methods...
CheckShape(def);
CheckGuard(def);
Apply(def);
emit("__global__ void _kernel_"+def.id.id+"(bool *chaged, int unroll) \n{");
//Emit edge/node decls
int num_edges = 0;
for(Tuple t : def.exp.tuples) {
switch(t.type) {
case EDGES:
emit("Edge *e"+num_edges+++";\n");
break;
case NODES:
emit("Node *"+get_prop_type(t,Type.Types.NODE)+";\n");
break;
}
}
//default changed to false
emit("*changed = false;");
//TODO: Current supporting three types of ops, Global, 1 vertex, 2 verts with shared edge
//empty args, just call apply
if(def.exp.tuples.size() == 0) {
emit("*changed = _apply_"+def.id.id+"();");
} else if(node_items.size() == 1) {
emit("int _id = threadIdx.x;");
emit(node_names.get(0)+ " = _get_node(_id);");
emit("*changed = _apply_"+def.id.id+"("+params+");");
} else if(node_items.size() == 2 && edge_items.size() == 1) {
emit("int _id = threadIdx.x;");
emit(node_names.get(0)+ " = _get_node(_id);");
//choose which edges we are iterating over, in edges or out edges
//if the first node is the src then out_edges, otherwise first node is dest and go for in_edges
String edge_map = (node_names.get(0).equals(get_prop_name(edge_items.get(0),"src"))) ? "out_edges" : "in_edges";
//iterate over edges like a boss
//emit("for( std::map<int,Edge*>::iterator _it="+node_names.get(0)+"->"+edge_map+".begin(); _it != " +node_names.get(0)+"->"+edge_map+".end(); ++it) {");
emit("for(int _i = 0; _i < "+node_names.get(0)+"->"+edge_map+"_size ; _i++) {");
emit(node_names.get(1)+ " = "+node_names.get(0)+"->" + edge_map+"[_i];");
emit("*changed |= _apply_"+def.id.id+"("+params+");");
emit("}");
} else {
System.err.println("Unsupported operation format");
}
emit("}\n");
}
| public void accept(OpDef def)
{
List<Tuple> node_items = get_node_items(def.exp.tuples);
List<String> node_names = get_node_names(def.exp.tuples);
List<Tuple> edge_items = get_edge_items(def.exp.tuples);
List<Attribute> attributes = get_attributes(def.exp.tuples);
String params = get_param_string(node_names,edge_items);
//write our helper methods...
CheckShape(def);
CheckGuard(def);
Apply(def);
emit("__global__ void _kernel_"+def.id.id+"(bool *chaged, int unroll) \n{");
//Emit edge/node decls
int num_edges = 0;
for(Tuple t : def.exp.tuples) {
switch(t.type) {
case EDGES:
emit("Edge *e"+num_edges+++";\n");
break;
case NODES:
emit("Node *"+get_prop_type(t,Type.Types.NODE)+";\n");
break;
}
}
//default changed to false
emit("*changed = false;");
//TODO: Current supporting three types of ops, Global, 1 vertex, 2 verts with shared edge
//empty args, just call apply
if(def.exp.tuples.size() == 0) {
emit("*changed = _apply_"+def.id.id+"();");
} else if(node_items.size() == 1) {
emit("int _id = threadIdx.x;");
emit(node_names.get(0)+ " = _get_node(_id);");
emit("*changed = _apply_"+def.id.id+"("+params+");");
} else if(node_items.size() == 2 && edge_items.size() == 1) {
emit("int _id = threadIdx.x;");
emit(node_names.get(0)+ " = _get_node(_id);");
//choose which edges we are iterating over, in edges or out edges
//if the first node is the src then out_edges, otherwise first node is dest and go for in_edges
String edge_map = (node_names.get(0).equals(get_prop_name(edge_items.get(0),"src"))) ? "out_edges" : "in_edges";
String edge_side = (node_names.get(0).equals(get_prop_name(edge_items.get(0),"src"))) ? "dst" : "src";
//iterate over edges like a boss
emit("for(int _i = 0; _i < "+node_names.get(0)+"->"+edge_map+"_size ; _i++) {");
emit("e0 = "+node_names.get(0)+"->" + edge_map+"[_i];");
emit(node_names.get(1)+" = e0->"+edge_side+";");
emit("*changed |= _apply_"+def.id.id+"("+params+");");
emit("}");
} else {
System.err.println("Unsupported operation format");
}
emit("}\n");
}
|
diff --git a/core/provider/src/main/java/net/oauth/v2/server/OAuth2Servlet.java b/core/provider/src/main/java/net/oauth/v2/server/OAuth2Servlet.java
index 6c73e57..6395412 100644
--- a/core/provider/src/main/java/net/oauth/v2/server/OAuth2Servlet.java
+++ b/core/provider/src/main/java/net/oauth/v2/server/OAuth2Servlet.java
@@ -1,238 +1,238 @@
/*
* Copyright 2010 Yutaka Obuchi
*
* 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.
*/
// Original is OAuth Java library(http://oauth.googlecode.com/svn/code/java/)
// and modified for OAuth 2.0 Provider
// Original's copyright and license terms
/*
* Copyright 2007 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.oauth.v2.server;
import java.io.IOException;
import java.util.Map;
import java.util.Set;
import java.util.List;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Collections;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.oauth.v2.OAuth2;
import net.oauth.v2.OAuth2Message;
import net.oauth.v2.OAuth2ProblemException;
/**
* Utility methods for servlets that implement OAuth2.0.
*
* @author Yutaka Obuchi
*/
public class OAuth2Servlet {
/**
* Extract the parts of the given request that are relevant to OAuth.
* Parameters include OAuth Authorization headers and the usual request
* parameters in the query string and/or form encoded body. The header
* parameters come first, followed by the rest in the order they came from
* request.getParameterMap().
*
* @param URL
* the official URL of this service; that is the URL a legitimate
* client would use to compute the digital signature. If this
* parameter is null, this method will try to reconstruct the URL
* from the HTTP request; which may be wrong in some cases.
*/
public static OAuth2Message getMessage(HttpServletRequest request, String URL) {
if (URL == null) {
URL = request.getRequestURL().toString();
}
int q = URL.indexOf('?');
if (q >= 0) {
URL = URL.substring(0, q);
// The query string parameters will be included in
// the result from getParameters(request).
}
return new HttpRequestMessage(request, URL);
}
/** Reconstruct the requested URL, complete with query string (if any). */
public static String getRequestURL(HttpServletRequest request) {
StringBuffer url = request.getRequestURL();
String queryString = request.getQueryString();
if (queryString != null) {
url.append("?").append(queryString);
}
return url.toString();
}
public static void handleException(HttpServletResponse response,
Exception e, String realm) throws IOException, ServletException {
handleException(null, response, e, realm, true,true);
}
public static final Set<String> SEND_BACK_ERROR_PARAMETERS = constructParameters();
private static Set<String> constructParameters() {
Set<String> s = new HashSet<String>();
for (String p : new String[] { OAuth2.ERROR, OAuth2.ERROR_DESCRIPTION, OAuth2.ERROR_URI,
OAuth2.STATE}) {
s.add(p);
}
return Collections.unmodifiableSet(s);
}
public static void handleException(HttpServletRequest request, HttpServletResponse response,
Exception e, String realm, boolean sendBodyInJson, boolean withAuthHeader)
throws IOException, ServletException {
if (e instanceof OAuth2ProblemException) {
OAuth2ProblemException problem = (OAuth2ProblemException) e;
Object httpCode = problem.getParameters().get(OAuth2ProblemException.HTTP_STATUS_CODE);
if (httpCode == null) {
httpCode = PROBLEM_TO_HTTP_CODE.get(problem.getProblem());
}
if (httpCode == null) {
httpCode = SC_FORBIDDEN;
}
Object errorCode = problem.getParameters().get(OAuth2.ERROR);
if (errorCode == null) {
errorCode = PROBLEM_TO_ERROR_CODE.get(problem.getProblem());
if(errorCode != null) problem.getParameters().put(OAuth2.ERROR,errorCode);
}
response.reset();
- //response.setStatus(Integer.parseInt(httpCode.toString()));
+ response.setStatus(Integer.parseInt(httpCode.toString()));
OAuth2Message message = new OAuth2Message(null, null, problem.getParameters().entrySet());
if(withAuthHeader){
response.addHeader("WWW-Authenticate", message.getAuthorizationHeader(realm));
}
if (sendBodyInJson) {
List<Map.Entry<String, String>> sendBackErrorParameters = new ArrayList<Map.Entry<String, String>>(SEND_BACK_ERROR_PARAMETERS.size());
for (Map.Entry parameter : message.getParameters()) {
if(SEND_BACK_ERROR_PARAMETERS.contains(parameter.getKey()))
{
sendBackErrorParameters.add(parameter);
}
}
sendFormInJson(response, sendBackErrorParameters);
}else{
//send back error info as parameters to the redirection URI query component
String redirect_uri = message.getParameter(OAuth2.REDIRECT_URI);
redirect_uri = OAuth2.addParameters(redirect_uri, OAuth2.ERROR, errorCode.toString());
if(problem.getParameters().get(OAuth2.ERROR_DESCRIPTION)!=null){
redirect_uri = OAuth2.addParameters(redirect_uri, OAuth2.ERROR_DESCRIPTION, problem.getParameters().get(OAuth2.ERROR_DESCRIPTION).toString());
}
if(problem.getParameters().get(OAuth2.ERROR_URI) != null){
redirect_uri = OAuth2.addParameters(redirect_uri, OAuth2.ERROR_URI, problem.getParameters().get(OAuth2.ERROR_URI).toString());
}
if(problem.getParameters().get(OAuth2.STATE) != null){
redirect_uri = OAuth2.addParameters(redirect_uri, OAuth2.STATE, problem.getParameters().get(OAuth2.STATE).toString());
}
response.addHeader(OAuth2ProblemException.HTTP_LOCATION,redirect_uri);
}
} else if (e instanceof IOException) {
throw (IOException) e;
} else if (e instanceof ServletException) {
throw (ServletException) e;
} else if (e instanceof RuntimeException) {
throw (RuntimeException) e;
} else {
throw new ServletException(e);
}
}
private static final Integer SC_FORBIDDEN = new Integer(HttpServletResponse.SC_FORBIDDEN);
private static final Map<String, Integer> PROBLEM_TO_HTTP_CODE = OAuth2.Problems.TO_HTTP_CODE;
private static final Map<String, String> PROBLEM_TO_ERROR_CODE = OAuth2.Problems.TO_ERROR_CODE;
/** Send the given parameters as a form-encoded response body. */
//public static void sendForm(HttpServletResponse response,
// Iterable<? extends Map.Entry> parameters) throws IOException {
// response.resetBuffer();
// response.setContentType(OAuth.FORM_ENCODED + ";charset="
// + OAuth.ENCODING);
// OAuth.formEncode(parameters, response.getOutputStream());
//}
/** Send the given parameters as a form-encoded response body. */
public static void sendFormInJson(HttpServletResponse response,
Iterable<? extends Map.Entry> parameters) throws IOException {
response.resetBuffer();
response.setContentType("application/json" + ";charset="
+ OAuth2.ENCODING);
//response.addHeader("X-YUTAKA", "OBUCHI");
//String res= "non";
//for (Map.Entry parameter : parameters) {
// res +=(String)parameter.getKey()+(String)parameter.getValue();
//}
//response.addHeader("X-OBUCHI", res);
OAuth2.formEncodeInJson(parameters, response.getOutputStream());
}
/**
* Return the HTML representation of the given plain text. Characters that
* would have special significance in HTML are replaced by <a
* href="http://www.w3.org/TR/html401/sgml/entities.html">character entity
* references</a>. Whitespace is not converted.
*/
public static String htmlEncode(String s) {
if (s == null) {
return null;
}
StringBuilder html = new StringBuilder(s.length());
for (char c : s.toCharArray()) {
switch (c) {
case '<':
html.append("<");
break;
case '>':
html.append(">");
break;
case '&':
html.append("&");
// This also takes care of numeric character references;
// for example © becomes &#169.
break;
case '"':
html.append(""");
break;
default:
html.append(c);
break;
}
}
return html.toString();
}
}
| true | true | public static void handleException(HttpServletRequest request, HttpServletResponse response,
Exception e, String realm, boolean sendBodyInJson, boolean withAuthHeader)
throws IOException, ServletException {
if (e instanceof OAuth2ProblemException) {
OAuth2ProblemException problem = (OAuth2ProblemException) e;
Object httpCode = problem.getParameters().get(OAuth2ProblemException.HTTP_STATUS_CODE);
if (httpCode == null) {
httpCode = PROBLEM_TO_HTTP_CODE.get(problem.getProblem());
}
if (httpCode == null) {
httpCode = SC_FORBIDDEN;
}
Object errorCode = problem.getParameters().get(OAuth2.ERROR);
if (errorCode == null) {
errorCode = PROBLEM_TO_ERROR_CODE.get(problem.getProblem());
if(errorCode != null) problem.getParameters().put(OAuth2.ERROR,errorCode);
}
response.reset();
//response.setStatus(Integer.parseInt(httpCode.toString()));
OAuth2Message message = new OAuth2Message(null, null, problem.getParameters().entrySet());
if(withAuthHeader){
response.addHeader("WWW-Authenticate", message.getAuthorizationHeader(realm));
}
if (sendBodyInJson) {
List<Map.Entry<String, String>> sendBackErrorParameters = new ArrayList<Map.Entry<String, String>>(SEND_BACK_ERROR_PARAMETERS.size());
for (Map.Entry parameter : message.getParameters()) {
if(SEND_BACK_ERROR_PARAMETERS.contains(parameter.getKey()))
{
sendBackErrorParameters.add(parameter);
}
}
sendFormInJson(response, sendBackErrorParameters);
}else{
//send back error info as parameters to the redirection URI query component
String redirect_uri = message.getParameter(OAuth2.REDIRECT_URI);
redirect_uri = OAuth2.addParameters(redirect_uri, OAuth2.ERROR, errorCode.toString());
if(problem.getParameters().get(OAuth2.ERROR_DESCRIPTION)!=null){
redirect_uri = OAuth2.addParameters(redirect_uri, OAuth2.ERROR_DESCRIPTION, problem.getParameters().get(OAuth2.ERROR_DESCRIPTION).toString());
}
if(problem.getParameters().get(OAuth2.ERROR_URI) != null){
redirect_uri = OAuth2.addParameters(redirect_uri, OAuth2.ERROR_URI, problem.getParameters().get(OAuth2.ERROR_URI).toString());
}
if(problem.getParameters().get(OAuth2.STATE) != null){
redirect_uri = OAuth2.addParameters(redirect_uri, OAuth2.STATE, problem.getParameters().get(OAuth2.STATE).toString());
}
response.addHeader(OAuth2ProblemException.HTTP_LOCATION,redirect_uri);
}
} else if (e instanceof IOException) {
throw (IOException) e;
} else if (e instanceof ServletException) {
throw (ServletException) e;
} else if (e instanceof RuntimeException) {
throw (RuntimeException) e;
} else {
throw new ServletException(e);
}
}
| public static void handleException(HttpServletRequest request, HttpServletResponse response,
Exception e, String realm, boolean sendBodyInJson, boolean withAuthHeader)
throws IOException, ServletException {
if (e instanceof OAuth2ProblemException) {
OAuth2ProblemException problem = (OAuth2ProblemException) e;
Object httpCode = problem.getParameters().get(OAuth2ProblemException.HTTP_STATUS_CODE);
if (httpCode == null) {
httpCode = PROBLEM_TO_HTTP_CODE.get(problem.getProblem());
}
if (httpCode == null) {
httpCode = SC_FORBIDDEN;
}
Object errorCode = problem.getParameters().get(OAuth2.ERROR);
if (errorCode == null) {
errorCode = PROBLEM_TO_ERROR_CODE.get(problem.getProblem());
if(errorCode != null) problem.getParameters().put(OAuth2.ERROR,errorCode);
}
response.reset();
response.setStatus(Integer.parseInt(httpCode.toString()));
OAuth2Message message = new OAuth2Message(null, null, problem.getParameters().entrySet());
if(withAuthHeader){
response.addHeader("WWW-Authenticate", message.getAuthorizationHeader(realm));
}
if (sendBodyInJson) {
List<Map.Entry<String, String>> sendBackErrorParameters = new ArrayList<Map.Entry<String, String>>(SEND_BACK_ERROR_PARAMETERS.size());
for (Map.Entry parameter : message.getParameters()) {
if(SEND_BACK_ERROR_PARAMETERS.contains(parameter.getKey()))
{
sendBackErrorParameters.add(parameter);
}
}
sendFormInJson(response, sendBackErrorParameters);
}else{
//send back error info as parameters to the redirection URI query component
String redirect_uri = message.getParameter(OAuth2.REDIRECT_URI);
redirect_uri = OAuth2.addParameters(redirect_uri, OAuth2.ERROR, errorCode.toString());
if(problem.getParameters().get(OAuth2.ERROR_DESCRIPTION)!=null){
redirect_uri = OAuth2.addParameters(redirect_uri, OAuth2.ERROR_DESCRIPTION, problem.getParameters().get(OAuth2.ERROR_DESCRIPTION).toString());
}
if(problem.getParameters().get(OAuth2.ERROR_URI) != null){
redirect_uri = OAuth2.addParameters(redirect_uri, OAuth2.ERROR_URI, problem.getParameters().get(OAuth2.ERROR_URI).toString());
}
if(problem.getParameters().get(OAuth2.STATE) != null){
redirect_uri = OAuth2.addParameters(redirect_uri, OAuth2.STATE, problem.getParameters().get(OAuth2.STATE).toString());
}
response.addHeader(OAuth2ProblemException.HTTP_LOCATION,redirect_uri);
}
} else if (e instanceof IOException) {
throw (IOException) e;
} else if (e instanceof ServletException) {
throw (ServletException) e;
} else if (e instanceof RuntimeException) {
throw (RuntimeException) e;
} else {
throw new ServletException(e);
}
}
|
diff --git a/net.sourceforge.vrapper.core/src/net/sourceforge/vrapper/vim/modes/InsertMode.java b/net.sourceforge.vrapper.core/src/net/sourceforge/vrapper/vim/modes/InsertMode.java
index f8d7258a..6ed46550 100644
--- a/net.sourceforge.vrapper.core/src/net/sourceforge/vrapper/vim/modes/InsertMode.java
+++ b/net.sourceforge.vrapper.core/src/net/sourceforge/vrapper/vim/modes/InsertMode.java
@@ -1,567 +1,567 @@
package net.sourceforge.vrapper.vim.modes;
import static net.sourceforge.vrapper.keymap.StateUtils.union;
import static net.sourceforge.vrapper.keymap.vim.ConstructorWrappers.ctrlKey;
import static net.sourceforge.vrapper.keymap.vim.ConstructorWrappers.key;
import static net.sourceforge.vrapper.keymap.vim.ConstructorWrappers.leafBind;
import static net.sourceforge.vrapper.keymap.vim.ConstructorWrappers.leafCtrlBind;
import static net.sourceforge.vrapper.keymap.vim.ConstructorWrappers.state;
import static net.sourceforge.vrapper.vim.commands.ConstructorWrappers.dontRepeat;
import static net.sourceforge.vrapper.vim.commands.ConstructorWrappers.seq;
import net.sourceforge.vrapper.keymap.EmptyState;
import net.sourceforge.vrapper.keymap.KeyStroke;
import net.sourceforge.vrapper.keymap.SpecialKey;
import net.sourceforge.vrapper.keymap.State;
import net.sourceforge.vrapper.keymap.Transition;
import net.sourceforge.vrapper.keymap.vim.RegisterState;
import net.sourceforge.vrapper.keymap.vim.SimpleKeyStroke;
import net.sourceforge.vrapper.log.VrapperLog;
import net.sourceforge.vrapper.platform.CursorService;
import net.sourceforge.vrapper.platform.TextContent;
import net.sourceforge.vrapper.utils.CaretType;
import net.sourceforge.vrapper.utils.ContentType;
import net.sourceforge.vrapper.utils.LineInformation;
import net.sourceforge.vrapper.utils.Position;
import net.sourceforge.vrapper.utils.StartEndTextRange;
import net.sourceforge.vrapper.utils.VimUtils;
import net.sourceforge.vrapper.vim.EditorAdaptor;
import net.sourceforge.vrapper.vim.Options;
import net.sourceforge.vrapper.vim.VimConstants;
import net.sourceforge.vrapper.vim.commands.ChangeModeCommand;
import net.sourceforge.vrapper.vim.commands.Command;
import net.sourceforge.vrapper.vim.commands.CommandExecutionException;
import net.sourceforge.vrapper.vim.commands.CountIgnoringNonRepeatableCommand;
import net.sourceforge.vrapper.vim.commands.InsertAdjacentCharacter;
import net.sourceforge.vrapper.vim.commands.InsertLineCommand;
import net.sourceforge.vrapper.vim.commands.InsertShiftWidth;
import net.sourceforge.vrapper.vim.commands.MotionCommand;
import net.sourceforge.vrapper.vim.commands.PasteAfterCommand;
import net.sourceforge.vrapper.vim.commands.PasteBeforeCommand;
import net.sourceforge.vrapper.vim.commands.PasteRegisterCommand;
import net.sourceforge.vrapper.vim.commands.SimpleSelection;
import net.sourceforge.vrapper.vim.commands.SwitchRegisterCommand;
import net.sourceforge.vrapper.vim.commands.TextOperationTextObjectCommand;
import net.sourceforge.vrapper.vim.commands.VimCommandSequence;
import net.sourceforge.vrapper.vim.commands.motions.LineStartMotion;
import net.sourceforge.vrapper.vim.commands.motions.Motion;
import net.sourceforge.vrapper.vim.commands.motions.MoveDown;
import net.sourceforge.vrapper.vim.commands.motions.MoveLeft;
import net.sourceforge.vrapper.vim.commands.motions.MoveLeftAcrossLines;
import net.sourceforge.vrapper.vim.commands.motions.MoveRightAcrossLines;
import net.sourceforge.vrapper.vim.commands.motions.MoveUp;
import net.sourceforge.vrapper.vim.commands.motions.MoveWordLeft;
import net.sourceforge.vrapper.vim.commands.motions.StickyColumnPolicy;
import net.sourceforge.vrapper.vim.modes.commandline.CommandLineMode;
import net.sourceforge.vrapper.vim.modes.commandline.PasteRegisterMode;
import net.sourceforge.vrapper.vim.register.Register;
import net.sourceforge.vrapper.vim.register.RegisterContent;
import net.sourceforge.vrapper.vim.register.StringRegisterContent;
public class InsertMode extends AbstractMode {
public static final String NAME = "insert mode";
public static final String DISPLAY_NAME = "INSERT";
public static final String KEYMAP_NAME = "Insert Mode Keymap";
public static final ModeSwitchHint DONT_MOVE_CURSOR = new ModeSwitchHint() {};
public static final ModeSwitchHint DONT_LOCK_HISTORY = new ModeSwitchHint() {};
public static final ModeSwitchHint RESUME_ON_MODE_ENTER = new ModeSwitchHint() {};
public static final KeyStroke ESC = key(SpecialKey.ESC);
public static final KeyStroke BACKSPACE = key(SpecialKey.BACKSPACE);
public static final KeyStroke CTRL_R = ctrlKey('r');
public static final KeyStroke CTRL_O = ctrlKey('o');
public static final KeyStroke CTRL_U = ctrlKey('u');
public static final KeyStroke CTRL_W = ctrlKey('w');
public static final KeyStroke CTRL_X = ctrlKey('x');
protected State<Command> currentState = buildState();
private Position startEditPosition;
private boolean cleanupIndent = false;
private boolean resumeOnEnter = false;
/**
* Command to be used before insertion
*/
private Command command;
private int count;
private ExecuteCommandHint mOnLeaveHint;
public InsertMode(final EditorAdaptor editorAdaptor) {
super(editorAdaptor);
}
@Override
public String getName() {
return NAME;
}
@Override
public String getDisplayName() {
return DISPLAY_NAME;
}
/**
* @param args
* command to perform on entering insert mode
* @throws CommandExecutionException
*/
@Override
public void enterMode(final ModeSwitchHint... args) throws CommandExecutionException {
boolean initMode = !resumeOnEnter;
resumeOnEnter = false;
boolean lockHistory = true;
for (final ModeSwitchHint hint: args) {
if(hint == DONT_LOCK_HISTORY) {
lockHistory = false;
}
}
if (initMode && lockHistory && editorAdaptor.getConfiguration().get(Options.ATOMIC_INSERT)) {
editorAdaptor.getHistory().beginCompoundChange();
editorAdaptor.getHistory().lock("insertmode");
}
count = 1;
command = null;
mOnLeaveHint = null;
try {
editorAdaptor.getViewportService().setRepaint(false);
for (final ModeSwitchHint hint : args) {
if (hint instanceof WithCountHint) {
final WithCountHint cast = (WithCountHint) hint;
count = cast.getCount();
}
if (hint instanceof ExecuteCommandHint) {
if (hint instanceof ExecuteCommandHint.OnLeave) {
mOnLeaveHint = (ExecuteCommandHint) hint;
}
else { //onEnter, execute command now
Command command = ((ExecuteCommandHint) hint).getCommand();
command.execute(editorAdaptor);
if(command instanceof InsertLineCommand && editorAdaptor.getConfiguration().get(Options.CLEAN_INDENT)) {
//entered insert mode via 'o' or 'O'
//cleanup auto-indent if nothing is entered
cleanupIndent = true;
}
}
}
}
} catch (final CommandExecutionException e) {
if (editorAdaptor.getConfiguration().get(Options.ATOMIC_INSERT)) {
editorAdaptor.getHistory().unlock("insertmode");
editorAdaptor.getHistory().endCompoundChange();
}
throw e;
} finally {
editorAdaptor.getViewportService().setRepaint(true);
}
editorAdaptor.getCursorService().setCaret(CaretType.VERTICAL_BAR);
if(initMode) {
startEditPosition = editorAdaptor.getCursorService().getPosition();
}
super.enterMode(args);
}
@Override
public void leaveMode(final ModeSwitchHint... hints) {
boolean moveCursor = true;
for (final ModeSwitchHint hint: hints) {
if (hint == InsertMode.DONT_MOVE_CURSOR) {
moveCursor = false;
}
if (hint == InsertMode.RESUME_ON_MODE_ENTER) {
resumeOnEnter = true;
//Leave insert mode without performing any of our "leave" operations.
//This is because we'll be returning to InsertMode soon and we want
//everything to be considered a single "insert" operation.
return;
}
}
try {
saveTypedText();
try {
if (moveCursor)
MotionCommand.doIt(editorAdaptor, MoveLeft.INSTANCE);
} catch (final CommandExecutionException e) {
editorAdaptor.getUserInterfaceService().setErrorMessage(
e.getMessage());
}
repeatInsert();
} finally {
if (editorAdaptor.getConfiguration().get(Options.ATOMIC_INSERT)) {
editorAdaptor.getHistory().unlock("insertmode");
editorAdaptor.getHistory().endCompoundChange();
}
}
Position lastInsertOffset = editorAdaptor.getPosition();
if (lastInsertOffset.getModelOffset() < editorAdaptor.getModelContent().getTextLength()) {
//Mark is placed one to the right to resume editing where we exited, except for file end
lastInsertOffset = lastInsertOffset.addModelOffset(1);
}
editorAdaptor.getCursorService().setMark(CursorService.LAST_INSERT_MARK, lastInsertOffset);
}
private void repeatInsert() {
if (count > 1) {
try {
editorAdaptor.getRegisterManager().getLastEdit().withCount(
count - 1).execute(editorAdaptor);
} catch (final CommandExecutionException e) {
editorAdaptor.getUserInterfaceService().setErrorMessage(
e.getMessage());
}
}
}
private void saveTypedText() {
final Register lastEditRegister = editorAdaptor.getRegisterManager().getLastEditRegister();
final TextContent content = editorAdaptor.getModelContent();
final Position position = editorAdaptor.getCursorService().getPosition();
if(startEditPosition.getModelOffset() > editorAdaptor.getModelContent().getTextLength()) {
//if the file is shorter than where we started,
//update so we aren't at an invalid position
startEditPosition = editorAdaptor.getCursorService().newPositionForModelOffset(
editorAdaptor.getModelContent().getTextLength()
);
}
else if(cleanupIndent && position.getModelOffset() == startEditPosition.getModelOffset()) {
//if we entered InsertMode via 'o' or 'O' but didn't enter any text,
//remove any auto-inserted indentation
final int startOfLine = content.getLineInformationOfOffset(position.getModelOffset()).getBeginOffset();
final String indent = content.getText(startOfLine, position.getModelOffset() - startOfLine);
if(indent.length() > 0 && VimUtils.isBlank(indent)) {
content.replace(startOfLine, indent.length(), "");
}
}
//reset value in case we re-enter InsertMode
cleanupIndent = false;
CursorService cur = editorAdaptor.getCursorService();
cur.setMark(CursorService.LAST_CHANGE_START, startEditPosition);
cur.setMark(CursorService.LAST_CHANGE_END, position);
final String text = content.getText(new StartEndTextRange(startEditPosition, position));
final RegisterContent registerContent = new StringRegisterContent(ContentType.TEXT, text);
lastEditRegister.setContent(registerContent);
final Command repetition = createRepetition(lastEditRegister, text);
editorAdaptor.getRegisterManager().setLastInsertion(
count > 1 ? repetition.withCount(count) : repetition);
}
protected Command createRepetition(final Register lastEditRegister, final String text) {
Command repetition = null;
if (command != null)
repetition = command.repetition();
Command paste;
if(count > 1) {
//insert mode with count
paste = PasteAfterCommand.CURSOR_ON_TEXT;
}
else {
//'.' command after insert
paste = PasteBeforeCommand.CURSOR_ON_TEXT;
}
return dontRepeat(seq(
repetition,
new SwitchRegisterCommand(lastEditRegister),
paste
));
}
@Override
public boolean handleKey(final KeyStroke stroke) {
final Transition<Command> transition = currentState.press(stroke);
if (transition != null && transition.getValue() != null) {
try {
transition.getValue().execute(editorAdaptor);
} catch (final CommandExecutionException e) {
editorAdaptor.getUserInterfaceService().setErrorMessage(e.getMessage());
}
return true;
} else if (stroke.equals(ESC)) {
editorAdaptor.changeModeSafely(NormalMode.NAME);
if (editorAdaptor.getConfiguration().get(Options.IM_DISABLE)) {
editorAdaptor.getEditorSettings().disableInputMethod();
}
if (mOnLeaveHint != null && stroke.equals(ESC)) {
try {
mOnLeaveHint.getCommand().execute(editorAdaptor);
} catch (final CommandExecutionException e) {
editorAdaptor.getUserInterfaceService().setErrorMessage(e.getMessage());
}
}
return true;
} else if (stroke.equals(CTRL_R)) {
// move to "paste register" mode, but don't actually perform the
// "leave insert mode" operations
editorAdaptor.changeModeSafely(PasteRegisterMode.NAME, RESUME_ON_MODE_ENTER);
return true;
} else if (stroke.equals(CTRL_X)) {
editorAdaptor.changeModeSafely(InsertExpandMode.NAME, RESUME_ON_MODE_ENTER);
return true;
} else if (stroke.equals(CTRL_O)) {
// perform a single NormalMode command then return to InsertMode
editorAdaptor.changeModeSafely(TempNormalMode.NAME);
return true;
} else if (stroke.equals(CTRL_U) || stroke.equals(CTRL_W)) {
Motion motion;
Position pos;
try {
CursorService cur = editorAdaptor.getCursorService();
int cursorPos = cur.getPosition().getModelOffset();
TextContent txt = editorAdaptor.getModelContent();
int startEditPos = startEditPosition.getModelOffset();
LineInformation line = txt.getLineInformationOfOffset(cursorPos);
if (stroke.equals(CTRL_U)) {
motion = LineStartMotion.NON_WHITESPACE;
} else {
motion = MoveWordLeft.INSTANCE;
}
pos = motion.destination(editorAdaptor);
if (pos.getModelOffset() < line.getBeginOffset()
|| pos.getModelOffset() == cursorPos) {
motion = LineStartMotion.COLUMN0;
pos = motion.destination(editorAdaptor);
}
int position = pos.getModelOffset();
if (cursorPos == line.getBeginOffset()) {
position = txt.getLineInformation(line.getNumber() - 1)
.getEndOffset();
} else {
if (cursorPos > startEditPos && position < startEditPos) {
position = startEditPos;
}
}
int length = cursorPos - position;
txt.replace(position, length, "");
if (position < startEditPos) {
startEditPosition = startEditPosition.setModelOffset(position);
}
} catch (CommandExecutionException e) {
}
return true;
// Check if editor is unmodifiable.
} else if (Boolean.FALSE.equals(editorAdaptor.getConfiguration().get(Options.MODIFIABLE))
&& (stroke.getSpecialKey() == null
|| ! VimConstants.SPECIAL_KEYS_ALLOWED_FOR_UNMODIFIABLE_INSERT
.contains(stroke.getSpecialKey()))) {
editorAdaptor.getUserInterfaceService().setErrorMessage("Cannot modify contents, " +
"'modifiable' is off!");
// Mark as handled (= ignored)
return true;
} else if (!allowed(stroke)) {
startEditPosition = editorAdaptor.getCursorService().getPosition();
count = 1;
if (editorAdaptor.getConfiguration().get(Options.ATOMIC_INSERT)) {
editorAdaptor.getHistory().unlock("insertmode");
editorAdaptor.getHistory().endCompoundChange();
editorAdaptor.getHistory().beginCompoundChange();
editorAdaptor.getHistory().lock("insertmode");
}
- } else if (stroke.equals(BACKSPACE)
- && editorAdaptor.getConfiguration().get(Options.SOFT_TAB) > 1) {
- // soft tab stop is enabled, check to see if there are spaces
- return softTabDelete();
} else if (stroke.isVirtual()) {
// stroke was generated by Vrapper, it will not be passed to the
// editor
handleVirtualStroke(stroke);
return true;
+ } else if (stroke.equals(BACKSPACE)
+ && editorAdaptor.getConfiguration().get(Options.SOFT_TAB) > 1) {
+ // soft tab stop is enabled, check to see if there are spaces
+ return softTabDelete();
}
return false;
}
/**
* If there are <softTabStop> number of spaces before the cursor
* delete that many spaces as if it was a single tab character.
*/
private boolean softTabDelete() {
final TextContent model = editorAdaptor.getModelContent();
final int softTabStop = editorAdaptor.getConfiguration().get(Options.SOFT_TAB);
final int pos = editorAdaptor.getPosition().getModelOffset();
final int start = model.getLineInformationOfOffset(pos).getBeginOffset();
//text before cursor
final String text = model.getText(start, pos - start);
//get number of consecutive spaces
int spaceCount = 0;
for(int i = text.length() -1; i >= 0; i--) {
if(text.charAt(i) != ' ') {
break;
}
spaceCount++;
}
if(spaceCount < softTabStop) {
//backspace key behaves as normal
return false;
}
int toDelete = 0;
if(spaceCount % softTabStop == 0) {
//exactly <softTabStop> space characters
//delete them as if they were a single tab character
toDelete = softTabStop;
}
else {
//not a <softTabStop> divisible number of spaces
//delete up to the closest soft tab stop
toDelete = spaceCount % softTabStop;
}
model.replace(pos - toDelete, toDelete, "");
editorAdaptor.setPosition(editorAdaptor.getCursorService()
.newPositionForModelOffset(pos - toDelete), StickyColumnPolicy.NEVER);
return true;
}
private void handleVirtualStroke(final KeyStroke stroke) {
final TextContent c = editorAdaptor.getModelContent();
if (SpecialKey.BACKSPACE.equals(stroke.getSpecialKey())) {
final int pos = editorAdaptor.getPosition().getModelOffset();
int pos2;
final LineInformation line = c.getLineInformationOfOffset(pos);
if (pos > 0) {
if (pos > line.getBeginOffset()) {
pos2 = pos - 1;
} else {
pos2 = c.getLineInformation(line.getNumber() - 1)
.getEndOffset();
}
c.replace(pos2, pos - pos2, "");
editorAdaptor.setPosition(editorAdaptor.getCursorService()
.newPositionForModelOffset(pos2), StickyColumnPolicy.NEVER);
}
} else if (SpecialKey.ARROW_LEFT.equals(stroke.getSpecialKey())
|| SpecialKey.ARROW_RIGHT.equals(stroke.getSpecialKey())
|| SpecialKey.ARROW_UP.equals(stroke.getSpecialKey())
|| SpecialKey.ARROW_DOWN.equals(stroke.getSpecialKey())) {
Motion direction;
switch (stroke.getSpecialKey()) {
case ARROW_LEFT:
direction = MoveLeftAcrossLines.INSTANCE; break;
case ARROW_RIGHT:
direction = MoveRightAcrossLines.INSTANCE_INSERT; break;
case ARROW_UP:
direction = MoveUp.INSTANCE; break;
case ARROW_DOWN:
direction = MoveDown.INSTANCE; break;
default:
throw new RuntimeException("No matching direction!");
}
try {
Position destination = direction.destination(editorAdaptor);
editorAdaptor.setPosition(destination, direction.stickyColumnPolicy());
} catch (CommandExecutionException e) {
VrapperLog.error("Failed to navigate in editor", e);
}
} else {
String s;
if (SpecialKey.RETURN.equals(stroke.getSpecialKey())) {
s = editorAdaptor.getConfiguration().getNewLine();
} else if (SpecialKey.TAB.equals(stroke.getSpecialKey())) {
s = "\t";
} else {
s = String.valueOf(stroke.getCharacter());
}
handleVirtualInsert(c, s);
}
}
/**
* This method only exists for ReplaceMode to override it. I know, I know,
* it's a horrible hack. I couldn't find a way for smartInsert to know when
* Eclipse is in overwrite mode though. So, if we're in InsertMode, perform
* the virtual insert. If we're in ReplaceMode, the ReplaceMode class will
* handle the insert (by actually performing a replace).
*/
protected void handleVirtualInsert(TextContent content, String str) {
content.smartInsert(str);
}
/**
* Check if a ' special key' should be handled by {@link #handleVirtualStroke(KeyStroke)}.
* <p>
* This code could be rolled into {@link #handleVirtualStroke(KeyStroke)} if really wanted,
* though in that case it should return a boolean.
*/
private boolean allowed(final KeyStroke stroke) {
final SpecialKey specialKey = stroke.getSpecialKey();
if (specialKey != null) {
return VimConstants.SPECIAL_KEYS_ALLOWED_FOR_INSERT.contains(specialKey);
}
return true;
}
@SuppressWarnings("unchecked")
protected State<Command> buildState() {
State<Command> platformSpecificState = editorAdaptor.getPlatformSpecificStateProvider().getState(NAME);
if(platformSpecificState == null) {
platformSpecificState = EmptyState.getInstance();
}
return RegisterState.wrap(union(
platformSpecificState,
state(
// Alt+O - temporary go into command mode
leafBind(new SimpleKeyStroke('o', false, true, false),
(Command)new ChangeModeCommand(CommandLineMode.NAME, RESUME_ON_MODE_ENTER)),
leafCtrlBind('a', (Command)PasteRegisterCommand.PASTE_LAST_INSERT),
leafCtrlBind('e', (Command)InsertAdjacentCharacter.LINE_BELOW),
leafCtrlBind('y', (Command)InsertAdjacentCharacter.LINE_ABOVE),
leafCtrlBind('t', (Command)new TextOperationTextObjectCommand(InsertShiftWidth.INSERT, new SimpleSelection(null))),
leafCtrlBind('d', (Command)new TextOperationTextObjectCommand(InsertShiftWidth.REMOVE, new SimpleSelection(null)))
)
));
}
@Override
public String resolveKeyMap(KeyStroke stroke) {
return KEYMAP_NAME;
}
public static class MoveRightOverLineBreak extends
CountIgnoringNonRepeatableCommand {
private final int offset;
public MoveRightOverLineBreak(final int offset) {
this.offset = offset;
}
@Override
public void execute(final EditorAdaptor editorAdaptor)
throws CommandExecutionException {
editorAdaptor.setPosition(editorAdaptor.getPosition().addModelOffset(offset),
StickyColumnPolicy.ON_CHANGE);
}
}
public static class SimpleInsertCommandSequence extends VimCommandSequence {
public SimpleInsertCommandSequence(final Command... commands) {
super(commands);
}
@Override
public Command withCount(final int count) {
return new CountIgnoringNonRepeatableCommand() {
@Override
public void execute(final EditorAdaptor editorAdaptor)
throws CommandExecutionException {
SimpleInsertCommandSequence.this.execute(editorAdaptor);
for (int i = 1; i < count; i++) {
final Position pos = editorAdaptor.getPosition();
editorAdaptor.setPosition(pos.addModelOffset(1), StickyColumnPolicy.NEVER);
SimpleInsertCommandSequence.this.execute(editorAdaptor);
}
}
};
}
}
}
| false | true | public boolean handleKey(final KeyStroke stroke) {
final Transition<Command> transition = currentState.press(stroke);
if (transition != null && transition.getValue() != null) {
try {
transition.getValue().execute(editorAdaptor);
} catch (final CommandExecutionException e) {
editorAdaptor.getUserInterfaceService().setErrorMessage(e.getMessage());
}
return true;
} else if (stroke.equals(ESC)) {
editorAdaptor.changeModeSafely(NormalMode.NAME);
if (editorAdaptor.getConfiguration().get(Options.IM_DISABLE)) {
editorAdaptor.getEditorSettings().disableInputMethod();
}
if (mOnLeaveHint != null && stroke.equals(ESC)) {
try {
mOnLeaveHint.getCommand().execute(editorAdaptor);
} catch (final CommandExecutionException e) {
editorAdaptor.getUserInterfaceService().setErrorMessage(e.getMessage());
}
}
return true;
} else if (stroke.equals(CTRL_R)) {
// move to "paste register" mode, but don't actually perform the
// "leave insert mode" operations
editorAdaptor.changeModeSafely(PasteRegisterMode.NAME, RESUME_ON_MODE_ENTER);
return true;
} else if (stroke.equals(CTRL_X)) {
editorAdaptor.changeModeSafely(InsertExpandMode.NAME, RESUME_ON_MODE_ENTER);
return true;
} else if (stroke.equals(CTRL_O)) {
// perform a single NormalMode command then return to InsertMode
editorAdaptor.changeModeSafely(TempNormalMode.NAME);
return true;
} else if (stroke.equals(CTRL_U) || stroke.equals(CTRL_W)) {
Motion motion;
Position pos;
try {
CursorService cur = editorAdaptor.getCursorService();
int cursorPos = cur.getPosition().getModelOffset();
TextContent txt = editorAdaptor.getModelContent();
int startEditPos = startEditPosition.getModelOffset();
LineInformation line = txt.getLineInformationOfOffset(cursorPos);
if (stroke.equals(CTRL_U)) {
motion = LineStartMotion.NON_WHITESPACE;
} else {
motion = MoveWordLeft.INSTANCE;
}
pos = motion.destination(editorAdaptor);
if (pos.getModelOffset() < line.getBeginOffset()
|| pos.getModelOffset() == cursorPos) {
motion = LineStartMotion.COLUMN0;
pos = motion.destination(editorAdaptor);
}
int position = pos.getModelOffset();
if (cursorPos == line.getBeginOffset()) {
position = txt.getLineInformation(line.getNumber() - 1)
.getEndOffset();
} else {
if (cursorPos > startEditPos && position < startEditPos) {
position = startEditPos;
}
}
int length = cursorPos - position;
txt.replace(position, length, "");
if (position < startEditPos) {
startEditPosition = startEditPosition.setModelOffset(position);
}
} catch (CommandExecutionException e) {
}
return true;
// Check if editor is unmodifiable.
} else if (Boolean.FALSE.equals(editorAdaptor.getConfiguration().get(Options.MODIFIABLE))
&& (stroke.getSpecialKey() == null
|| ! VimConstants.SPECIAL_KEYS_ALLOWED_FOR_UNMODIFIABLE_INSERT
.contains(stroke.getSpecialKey()))) {
editorAdaptor.getUserInterfaceService().setErrorMessage("Cannot modify contents, " +
"'modifiable' is off!");
// Mark as handled (= ignored)
return true;
} else if (!allowed(stroke)) {
startEditPosition = editorAdaptor.getCursorService().getPosition();
count = 1;
if (editorAdaptor.getConfiguration().get(Options.ATOMIC_INSERT)) {
editorAdaptor.getHistory().unlock("insertmode");
editorAdaptor.getHistory().endCompoundChange();
editorAdaptor.getHistory().beginCompoundChange();
editorAdaptor.getHistory().lock("insertmode");
}
} else if (stroke.equals(BACKSPACE)
&& editorAdaptor.getConfiguration().get(Options.SOFT_TAB) > 1) {
// soft tab stop is enabled, check to see if there are spaces
return softTabDelete();
} else if (stroke.isVirtual()) {
// stroke was generated by Vrapper, it will not be passed to the
// editor
handleVirtualStroke(stroke);
return true;
}
return false;
}
| public boolean handleKey(final KeyStroke stroke) {
final Transition<Command> transition = currentState.press(stroke);
if (transition != null && transition.getValue() != null) {
try {
transition.getValue().execute(editorAdaptor);
} catch (final CommandExecutionException e) {
editorAdaptor.getUserInterfaceService().setErrorMessage(e.getMessage());
}
return true;
} else if (stroke.equals(ESC)) {
editorAdaptor.changeModeSafely(NormalMode.NAME);
if (editorAdaptor.getConfiguration().get(Options.IM_DISABLE)) {
editorAdaptor.getEditorSettings().disableInputMethod();
}
if (mOnLeaveHint != null && stroke.equals(ESC)) {
try {
mOnLeaveHint.getCommand().execute(editorAdaptor);
} catch (final CommandExecutionException e) {
editorAdaptor.getUserInterfaceService().setErrorMessage(e.getMessage());
}
}
return true;
} else if (stroke.equals(CTRL_R)) {
// move to "paste register" mode, but don't actually perform the
// "leave insert mode" operations
editorAdaptor.changeModeSafely(PasteRegisterMode.NAME, RESUME_ON_MODE_ENTER);
return true;
} else if (stroke.equals(CTRL_X)) {
editorAdaptor.changeModeSafely(InsertExpandMode.NAME, RESUME_ON_MODE_ENTER);
return true;
} else if (stroke.equals(CTRL_O)) {
// perform a single NormalMode command then return to InsertMode
editorAdaptor.changeModeSafely(TempNormalMode.NAME);
return true;
} else if (stroke.equals(CTRL_U) || stroke.equals(CTRL_W)) {
Motion motion;
Position pos;
try {
CursorService cur = editorAdaptor.getCursorService();
int cursorPos = cur.getPosition().getModelOffset();
TextContent txt = editorAdaptor.getModelContent();
int startEditPos = startEditPosition.getModelOffset();
LineInformation line = txt.getLineInformationOfOffset(cursorPos);
if (stroke.equals(CTRL_U)) {
motion = LineStartMotion.NON_WHITESPACE;
} else {
motion = MoveWordLeft.INSTANCE;
}
pos = motion.destination(editorAdaptor);
if (pos.getModelOffset() < line.getBeginOffset()
|| pos.getModelOffset() == cursorPos) {
motion = LineStartMotion.COLUMN0;
pos = motion.destination(editorAdaptor);
}
int position = pos.getModelOffset();
if (cursorPos == line.getBeginOffset()) {
position = txt.getLineInformation(line.getNumber() - 1)
.getEndOffset();
} else {
if (cursorPos > startEditPos && position < startEditPos) {
position = startEditPos;
}
}
int length = cursorPos - position;
txt.replace(position, length, "");
if (position < startEditPos) {
startEditPosition = startEditPosition.setModelOffset(position);
}
} catch (CommandExecutionException e) {
}
return true;
// Check if editor is unmodifiable.
} else if (Boolean.FALSE.equals(editorAdaptor.getConfiguration().get(Options.MODIFIABLE))
&& (stroke.getSpecialKey() == null
|| ! VimConstants.SPECIAL_KEYS_ALLOWED_FOR_UNMODIFIABLE_INSERT
.contains(stroke.getSpecialKey()))) {
editorAdaptor.getUserInterfaceService().setErrorMessage("Cannot modify contents, " +
"'modifiable' is off!");
// Mark as handled (= ignored)
return true;
} else if (!allowed(stroke)) {
startEditPosition = editorAdaptor.getCursorService().getPosition();
count = 1;
if (editorAdaptor.getConfiguration().get(Options.ATOMIC_INSERT)) {
editorAdaptor.getHistory().unlock("insertmode");
editorAdaptor.getHistory().endCompoundChange();
editorAdaptor.getHistory().beginCompoundChange();
editorAdaptor.getHistory().lock("insertmode");
}
} else if (stroke.isVirtual()) {
// stroke was generated by Vrapper, it will not be passed to the
// editor
handleVirtualStroke(stroke);
return true;
} else if (stroke.equals(BACKSPACE)
&& editorAdaptor.getConfiguration().get(Options.SOFT_TAB) > 1) {
// soft tab stop is enabled, check to see if there are spaces
return softTabDelete();
}
return false;
}
|
diff --git a/src/info/sholes/camel/updater/DownloadHelper.java b/src/info/sholes/camel/updater/DownloadHelper.java
index 63e4ca0..a28bf40 100644
--- a/src/info/sholes/camel/updater/DownloadHelper.java
+++ b/src/info/sholes/camel/updater/DownloadHelper.java
@@ -1,174 +1,175 @@
package info.sholes.camel.updater;
import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.content.pm.PackageInfo;
import android.net.Uri;
public class DownloadHelper {
private static XMLElementDecorator xed = null;
private static void init(Context ctx) throws Exception {
if(xed == null)
xed = XMLElementDecorator.parse(ctx.getString(R.string.url_update)).getChild("smupdater");
}
private static XMLElementDecorator getFileXml(String type) throws Exception {
for(XMLElementDecorator file : xed.getChild("files").getChildren("file")) {
if(!type.equals(file.getAttribute("type")))
continue;
return file;
}
return null;
}
enum Downloadable {
ROOT("root"),
FLASH_IMAGE("flash_image"),
RECOVERY_IMAGE("recovery");
private final String type;
private String url = null;
private String md5 = null;
private XMLElementDecorator xed = null;
Downloadable(String type) {
this.type = type;
}
public String getUrl() throws Exception {
if(url != null)
return url;
if(xed == null)
xed = getFileXml(type);
url = xed.getChild("url").getString();
return url;
}
public String getMd5() throws Exception {
if(md5 != null)
return md5;
if(xed == null)
xed = getFileXml(type);
md5 = xed.getChild("md5").getString();
return md5;
}
}
class RomDescriptor {
public final String name;
public final String dispid;
public final String url;
public final String md5;
private RomDescriptor(String name, String dispid, String url, String md5) {
this.name = name;
this.dispid = dispid;
this.url = url;
this.md5 = md5;
}
}
private final Updater u;
private final DownloadUtil du;
private int download_attempts = 0;
public DownloadHelper(Updater u) throws Exception {
init(u);
this.u = u;
du = new DownloadUtil(u);
}
public void resetDownloadAttempts() {
download_attempts = 0;
}
public File downloadFile(Downloadable which, File where, Callback cb) throws Exception {
return downloadFile(which.getUrl(), which.getMd5(), where, cb);
}
private File downloadFile(String url, String expect_md5, File where, Callback cb) throws Exception {
while(where.exists()) {
String actual_md5;
try {
actual_md5 = DownloadUtil.md5(where);
} catch (Exception e) {
// Re-download
break;
}
if(expect_md5.equals(actual_md5)) {
// Got the file
return where;
} else {
u.addText("Unknown MD5: " + actual_md5);
// Fall-through to re-download
break;
}
}
download_attempts++;
if(download_attempts >= 3)
throw new Exception("It's hopeless; giving up");
du.downloadFile(where, new URL(url), cb);
return null;
}
public List<RomDescriptor> getRoms() {
List<RomDescriptor> roms = new ArrayList<RomDescriptor>();
for(XMLElementDecorator rom : xed.getChild("roms").getChildren("rom")) {
String name = rom.getAttribute("name");
String dispid = rom.getAttribute("dispid");
String url = rom.getChild("url").getString();
String md5 = rom.getChild("md5").getString();
roms.add(new RomDescriptor(name, dispid, url, md5));
}
return roms;
}
public File downloadRom(RomDescriptor rd, File rom_tgz) throws Exception {
return downloadFile(rd.url, rd.md5, rom_tgz, Callback.ROM_DOWNLOAD);
}
public boolean checkVersion(PackageInfo pi) {
XMLElementDecorator vc = xed.getChild("version_check");
int code = vc.getChild("code").getInt().intValue();
if(code <= pi.versionCode)
return false;
// Update available!
final String name = vc.getChild("name").getString();
- final String url = vc.getChild("url").getString();
+ final String uri = vc.getChild("uri").getString();
new AlertDialog.Builder(u)
.setTitle("Update available")
.setMessage("Version " + name + " of " + u.getString(R.string.app_label) + " is available")
.setPositiveButton(
"Install",
new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
- u.sendBroadcast(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
+ u.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(uri)));
+ System.exit(1);
}
}
)
.setNegativeButton(
"Quit",
new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
System.exit(1);
}
}
)
.show();
return true;
}
}
| false | true | public boolean checkVersion(PackageInfo pi) {
XMLElementDecorator vc = xed.getChild("version_check");
int code = vc.getChild("code").getInt().intValue();
if(code <= pi.versionCode)
return false;
// Update available!
final String name = vc.getChild("name").getString();
final String url = vc.getChild("url").getString();
new AlertDialog.Builder(u)
.setTitle("Update available")
.setMessage("Version " + name + " of " + u.getString(R.string.app_label) + " is available")
.setPositiveButton(
"Install",
new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
u.sendBroadcast(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
}
}
)
.setNegativeButton(
"Quit",
new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
System.exit(1);
}
}
)
.show();
return true;
}
| public boolean checkVersion(PackageInfo pi) {
XMLElementDecorator vc = xed.getChild("version_check");
int code = vc.getChild("code").getInt().intValue();
if(code <= pi.versionCode)
return false;
// Update available!
final String name = vc.getChild("name").getString();
final String uri = vc.getChild("uri").getString();
new AlertDialog.Builder(u)
.setTitle("Update available")
.setMessage("Version " + name + " of " + u.getString(R.string.app_label) + " is available")
.setPositiveButton(
"Install",
new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
u.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(uri)));
System.exit(1);
}
}
)
.setNegativeButton(
"Quit",
new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
System.exit(1);
}
}
)
.show();
return true;
}
|
diff --git a/src/minecraft/co/uk/flansmods/client/FlansModClient.java b/src/minecraft/co/uk/flansmods/client/FlansModClient.java
index 998242c3..06992fb5 100644
--- a/src/minecraft/co/uk/flansmods/client/FlansModClient.java
+++ b/src/minecraft/co/uk/flansmods/client/FlansModClient.java
@@ -1,370 +1,381 @@
package co.uk.flansmods.client;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.EntityRenderer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.CompressedStreamTools;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.server.MinecraftServer;
import net.minecraft.world.World;
import net.minecraftforge.client.event.ClientChatReceivedEvent;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.Event;
import net.minecraftforge.event.ForgeSubscribe;
import net.minecraftforge.event.world.WorldEvent;
import co.uk.flansmods.common.BlockGunBox;
import co.uk.flansmods.common.DriveableType;
import co.uk.flansmods.common.EntityDriveable;
import co.uk.flansmods.common.EntityPlane;
import co.uk.flansmods.common.EntityVehicle;
import co.uk.flansmods.common.FlansMod;
import co.uk.flansmods.common.GunBoxType;
import co.uk.flansmods.common.InfoType;
import co.uk.flansmods.common.ItemGun;
import co.uk.flansmods.common.PlaneType;
import co.uk.flansmods.common.VehicleType;
import co.uk.flansmods.common.network.PacketBuyWeapon;
import co.uk.flansmods.common.teams.Gametype;
import co.uk.flansmods.common.teams.Team;
import cpw.mods.fml.client.FMLClientHandler;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.ObfuscationReflectionHelper;
public class FlansModClient extends FlansMod
{
public static boolean doneTutorial = false;
public static boolean controlModeMouse = false; // 0 = Standard controls, 1 = Mouse
public static int controlModeSwitchTimer = 20;
public static int shootTime;
public static String zoomOverlay;
public static float playerRecoil;
public static float antiRecoil;
public static float playerZoom = 1.0F;
public static float newZoom = 1.0F;
public static float lastPlayerZoom;
public static boolean planeGUI = false;
public static int planeHeight;
public static double planeSpeed;
public static double planeYSpeed = 0D;
public static double planeHeading = 0F;
public static float originalMouseSensitivity = 0.5F;
public static boolean originalHideGUI = false;
public static int originalThirdPerson = 0;
public static boolean inPlane = false;
public static List<DriveableType> blueprintsUnlocked = new ArrayList<DriveableType>();
public static List<DriveableType> vehicleBlueprintsUnlocked = new ArrayList<DriveableType>();
public void load()
{
if (ABORT)
{
log("Failed to load dependencies! Not loading Flan's Mod.");
return;
}
log("Loading Flan's mod.");
MinecraftForge.EVENT_BUS.register(this);
// Properties
// TODO: move to common and proxy-ify
try
{
File file = new File(FMLClientHandler.instance().getClient().getMinecraftDir() + "/Flan/properties.txt");
if (file != null)
{
BufferedReader properties = new BufferedReader(new FileReader(file));
do
{
String line = null;
try
{
line = properties.readLine();
} catch (Exception e)
{
break;
}
if (line == null)
{
break;
}
if (line.startsWith("//"))
continue;
String[] split = line.split(" ");
if (split.length < 2)
continue;
readProperties(split, properties);
} while (true);
log("Loaded properties.");
}
} catch (Exception e)
{
log("No properties file found. Using defaults.");
createNewProperties();
}
}
public static void tick()
{
if (minecraft.thePlayer == null)
return;
// Guns
if (shootTime > 0)
shootTime--;
if (playerRecoil > 0)
playerRecoil *= 0.8F;
minecraft.thePlayer.rotationPitch -= playerRecoil;
antiRecoil += playerRecoil;
minecraft.thePlayer.rotationPitch += antiRecoil * 0.2F;
antiRecoil *= 0.8F;
Item itemInHand = null;
ItemStack itemstackInHand = minecraft.thePlayer.inventory.getCurrentItem();
if (itemstackInHand != null)
itemInHand = itemstackInHand.getItem();
if (itemInHand != null)
{
if (!(itemInHand instanceof ItemGun && ((ItemGun) itemInHand).type.hasScope))
{
newZoom = 1.0F;
}
}
float dZoom = newZoom - playerZoom;
playerZoom += dZoom / 3F;
if (playerZoom < 1.1F && zoomOverlay != null)
{
minecraft.gameSettings.mouseSensitivity = originalMouseSensitivity;
playerZoom = 1.0F;
zoomOverlay = null;
minecraft.gameSettings.hideGUI = originalHideGUI;
minecraft.gameSettings.thirdPersonView = originalThirdPerson;
}
String field = inMCP ? "cameraZoom" : "V";
if (Math.abs(playerZoom - lastPlayerZoom) > 1F / 64F)
{
try
{
ObfuscationReflectionHelper.setPrivateValue(EntityRenderer.class, minecraft.entityRenderer, playerZoom, "cameraZoom", "X");
} catch (Exception e)
{
log("I forgot to update obfuscated reflection D:");
throw new RuntimeException(e);
}
}
lastPlayerZoom = playerZoom;
field = inMCP ? "camRoll" : "O";
if (minecraft.thePlayer.ridingEntity instanceof EntityDriveable)
{
inPlane = true;
try
{
ObfuscationReflectionHelper.setPrivateValue(EntityRenderer.class, minecraft.entityRenderer, ((EntityDriveable)minecraft.thePlayer.ridingEntity).axes.getRoll() * (minecraft.thePlayer.ridingEntity instanceof EntityVehicle ? -1 : 1), "camRoll", "O");
} catch (Exception e)
{
log("I forgot to update obfuscated reflection D:");
throw new RuntimeException(e);
}
if(minecraft.thePlayer.ridingEntity instanceof EntityPlane)
{
try
{
ObfuscationReflectionHelper.setPrivateValue(EntityRenderer.class, minecraft.entityRenderer, ((EntityPlane)minecraft.thePlayer.ridingEntity).getPlaneType().cameraDistance, "thirdPersonDistance", "B");
} catch (Exception e)
{
log("I forgot to update obfuscated reflection D:");
throw new RuntimeException(e);
}
}
}
+ if(minecraft.thePlayer.ridingEntity instanceof EntityVehicle) // Add CameraDistance for Vehicles
+ {
+ try
+ {
+ ObfuscationReflectionHelper.setPrivateValue(EntityRenderer.class, minecraft.entityRenderer, ((EntityVehicle)minecraft.thePlayer.ridingEntity).getVehicleType().cameraDistance, "thirdPersonDistance", "B");
+ } catch (Exception e)
+ {
+ log("I forgot to update obfuscated reflection D:");
+ throw new RuntimeException(e);
+ }
+ }
else if(inPlane)
{
try
{
ObfuscationReflectionHelper.setPrivateValue(EntityRenderer.class, minecraft.entityRenderer, 0F, "camRoll", "O");
} catch (Exception e)
{
log("I forgot to update obfuscated reflection D:");
throw new RuntimeException(e);
}
try
{
ObfuscationReflectionHelper.setPrivateValue(EntityRenderer.class, minecraft.entityRenderer, 4.0F, "thirdPersonDistance", "B");
} catch (Exception e)
{
log("I forgot to update obfuscated reflection D:");
throw new RuntimeException(e);
}
inPlane = false;
}
if (controlModeSwitchTimer > 0)
controlModeSwitchTimer--;
if (errorStringTimer > 0)
errorStringTimer--;
}
@ForgeSubscribe
public void chatMessage(ClientChatReceivedEvent event)
{
if(event.message.startsWith("flanDeath."))
{
String[] split = event.message.split("\\.");
event.setCanceled(true);
TickHandlerClient.addKillMessage(split);
//FMLClientHandler.instance().getClient().thePlayer.sendChatToPlayer(split[3] + " killed " + split[2] + " with a " + InfoType.getType(split[1]).name);
}
}
@ForgeSubscribe
public void worldData(WorldEvent event)
{
if(!event.world.isRemote)
return;
if(event instanceof WorldEvent.Load)
{
loadPerWorldData(event, event.world);
savePerWorldData(event, event.world);
}
if(event instanceof WorldEvent.Save)
{
savePerWorldData(event, event.world);
}
}
private void loadPerWorldData(Event event, World world)
{
File file = new File("teams.dat");
checkFileExists(file);
try
{
blueprintsUnlocked = new ArrayList<DriveableType>();
vehicleBlueprintsUnlocked = new ArrayList<DriveableType>();
NBTTagCompound tags = CompressedStreamTools.read(new DataInputStream(new FileInputStream(file)));
int numPlaneBlues = tags.getInteger("NumPlaneBlues");
for(int i = 0; i < numPlaneBlues; i++)
{
blueprintsUnlocked.add(PlaneType.getPlane(tags.getString("PlaneBlue" + i)));
}
int numVehicleBlues = tags.getInteger("NumVehicleBlues");
for(int i = 0; i < numVehicleBlues; i++)
{
vehicleBlueprintsUnlocked.add(VehicleType.getVehicle(tags.getString("VehicleBlue" + i)));
}
}
catch(Exception e)
{
FlansMod.log("Failed to load from teams.dat");
e.printStackTrace();
}
}
private void savePerWorldData(Event event, World world)
{
File file = new File("teams.dat");
checkFileExists(file);
try
{
NBTTagCompound tags = new NBTTagCompound();
tags.setInteger("NumPlaneBlues", blueprintsUnlocked.size());
for(int i = 0; i < blueprintsUnlocked.size(); i++)
{
tags.setString("PlaneBlue" + i, blueprintsUnlocked.get(i).shortName);
}
tags.setInteger("NumVehicleBlues", vehicleBlueprintsUnlocked.size());
for(int i = 0; i < vehicleBlueprintsUnlocked.size(); i++)
{
tags.setString("VehicleBlue" + i, vehicleBlueprintsUnlocked.get(i).shortName);
}
CompressedStreamTools.write(tags, new DataOutputStream(new FileOutputStream(file)));
}
catch(Exception e)
{
FlansMod.log("Failed to save to teams.dat");
}
}
private void checkFileExists(File file)
{
if(!file.exists())
{
try
{
file.createNewFile();
}
catch(Exception e)
{
FlansMod.log("Failed to create file");
FlansMod.log(file.getAbsolutePath());
}
}
}
public static void flipControlMode()
{
if (controlModeSwitchTimer > 0)
return;
controlModeMouse = !controlModeMouse;
controlModeSwitchTimer = 40;
}
public static void shoot()
{
// TODO : SMP guns
}
private void doPropertyStuff(File file)
{
}
private void readProperties(String[] split, BufferedReader file)
{
try
{
if (split[0].equals("Explosions"))
explosions = split[1].equals("True");
if (split[0].equals("Bombs"))
bombsEnabled = split[1].equals("True");
if (split[0].equals("Bullets"))
bulletsEnabled = split[1].equals("True");
} catch (Exception e)
{
e.printStackTrace();
}
}
private void createNewProperties()
{
try
{
FileOutputStream propsOut = new FileOutputStream(new File(FMLClientHandler.instance().getClient().getMinecraftDir() + "/Flan/properties.txt"));
propsOut.write(("Explosions True\r\nBombs True\r\nBullets True").getBytes());
propsOut.close();
} catch (Exception e)
{
log("Failed to write default properties");
e.printStackTrace();
}
}
public static Minecraft minecraft = FMLClientHandler.instance().getClient();
}
| true | true | public static void tick()
{
if (minecraft.thePlayer == null)
return;
// Guns
if (shootTime > 0)
shootTime--;
if (playerRecoil > 0)
playerRecoil *= 0.8F;
minecraft.thePlayer.rotationPitch -= playerRecoil;
antiRecoil += playerRecoil;
minecraft.thePlayer.rotationPitch += antiRecoil * 0.2F;
antiRecoil *= 0.8F;
Item itemInHand = null;
ItemStack itemstackInHand = minecraft.thePlayer.inventory.getCurrentItem();
if (itemstackInHand != null)
itemInHand = itemstackInHand.getItem();
if (itemInHand != null)
{
if (!(itemInHand instanceof ItemGun && ((ItemGun) itemInHand).type.hasScope))
{
newZoom = 1.0F;
}
}
float dZoom = newZoom - playerZoom;
playerZoom += dZoom / 3F;
if (playerZoom < 1.1F && zoomOverlay != null)
{
minecraft.gameSettings.mouseSensitivity = originalMouseSensitivity;
playerZoom = 1.0F;
zoomOverlay = null;
minecraft.gameSettings.hideGUI = originalHideGUI;
minecraft.gameSettings.thirdPersonView = originalThirdPerson;
}
String field = inMCP ? "cameraZoom" : "V";
if (Math.abs(playerZoom - lastPlayerZoom) > 1F / 64F)
{
try
{
ObfuscationReflectionHelper.setPrivateValue(EntityRenderer.class, minecraft.entityRenderer, playerZoom, "cameraZoom", "X");
} catch (Exception e)
{
log("I forgot to update obfuscated reflection D:");
throw new RuntimeException(e);
}
}
lastPlayerZoom = playerZoom;
field = inMCP ? "camRoll" : "O";
if (minecraft.thePlayer.ridingEntity instanceof EntityDriveable)
{
inPlane = true;
try
{
ObfuscationReflectionHelper.setPrivateValue(EntityRenderer.class, minecraft.entityRenderer, ((EntityDriveable)minecraft.thePlayer.ridingEntity).axes.getRoll() * (minecraft.thePlayer.ridingEntity instanceof EntityVehicle ? -1 : 1), "camRoll", "O");
} catch (Exception e)
{
log("I forgot to update obfuscated reflection D:");
throw new RuntimeException(e);
}
if(minecraft.thePlayer.ridingEntity instanceof EntityPlane)
{
try
{
ObfuscationReflectionHelper.setPrivateValue(EntityRenderer.class, minecraft.entityRenderer, ((EntityPlane)minecraft.thePlayer.ridingEntity).getPlaneType().cameraDistance, "thirdPersonDistance", "B");
} catch (Exception e)
{
log("I forgot to update obfuscated reflection D:");
throw new RuntimeException(e);
}
}
}
else if(inPlane)
{
try
{
ObfuscationReflectionHelper.setPrivateValue(EntityRenderer.class, minecraft.entityRenderer, 0F, "camRoll", "O");
} catch (Exception e)
{
log("I forgot to update obfuscated reflection D:");
throw new RuntimeException(e);
}
try
{
ObfuscationReflectionHelper.setPrivateValue(EntityRenderer.class, minecraft.entityRenderer, 4.0F, "thirdPersonDistance", "B");
} catch (Exception e)
{
log("I forgot to update obfuscated reflection D:");
throw new RuntimeException(e);
}
inPlane = false;
}
if (controlModeSwitchTimer > 0)
controlModeSwitchTimer--;
if (errorStringTimer > 0)
errorStringTimer--;
}
| public static void tick()
{
if (minecraft.thePlayer == null)
return;
// Guns
if (shootTime > 0)
shootTime--;
if (playerRecoil > 0)
playerRecoil *= 0.8F;
minecraft.thePlayer.rotationPitch -= playerRecoil;
antiRecoil += playerRecoil;
minecraft.thePlayer.rotationPitch += antiRecoil * 0.2F;
antiRecoil *= 0.8F;
Item itemInHand = null;
ItemStack itemstackInHand = minecraft.thePlayer.inventory.getCurrentItem();
if (itemstackInHand != null)
itemInHand = itemstackInHand.getItem();
if (itemInHand != null)
{
if (!(itemInHand instanceof ItemGun && ((ItemGun) itemInHand).type.hasScope))
{
newZoom = 1.0F;
}
}
float dZoom = newZoom - playerZoom;
playerZoom += dZoom / 3F;
if (playerZoom < 1.1F && zoomOverlay != null)
{
minecraft.gameSettings.mouseSensitivity = originalMouseSensitivity;
playerZoom = 1.0F;
zoomOverlay = null;
minecraft.gameSettings.hideGUI = originalHideGUI;
minecraft.gameSettings.thirdPersonView = originalThirdPerson;
}
String field = inMCP ? "cameraZoom" : "V";
if (Math.abs(playerZoom - lastPlayerZoom) > 1F / 64F)
{
try
{
ObfuscationReflectionHelper.setPrivateValue(EntityRenderer.class, minecraft.entityRenderer, playerZoom, "cameraZoom", "X");
} catch (Exception e)
{
log("I forgot to update obfuscated reflection D:");
throw new RuntimeException(e);
}
}
lastPlayerZoom = playerZoom;
field = inMCP ? "camRoll" : "O";
if (minecraft.thePlayer.ridingEntity instanceof EntityDriveable)
{
inPlane = true;
try
{
ObfuscationReflectionHelper.setPrivateValue(EntityRenderer.class, minecraft.entityRenderer, ((EntityDriveable)minecraft.thePlayer.ridingEntity).axes.getRoll() * (minecraft.thePlayer.ridingEntity instanceof EntityVehicle ? -1 : 1), "camRoll", "O");
} catch (Exception e)
{
log("I forgot to update obfuscated reflection D:");
throw new RuntimeException(e);
}
if(minecraft.thePlayer.ridingEntity instanceof EntityPlane)
{
try
{
ObfuscationReflectionHelper.setPrivateValue(EntityRenderer.class, minecraft.entityRenderer, ((EntityPlane)minecraft.thePlayer.ridingEntity).getPlaneType().cameraDistance, "thirdPersonDistance", "B");
} catch (Exception e)
{
log("I forgot to update obfuscated reflection D:");
throw new RuntimeException(e);
}
}
}
if(minecraft.thePlayer.ridingEntity instanceof EntityVehicle) // Add CameraDistance for Vehicles
{
try
{
ObfuscationReflectionHelper.setPrivateValue(EntityRenderer.class, minecraft.entityRenderer, ((EntityVehicle)minecraft.thePlayer.ridingEntity).getVehicleType().cameraDistance, "thirdPersonDistance", "B");
} catch (Exception e)
{
log("I forgot to update obfuscated reflection D:");
throw new RuntimeException(e);
}
}
else if(inPlane)
{
try
{
ObfuscationReflectionHelper.setPrivateValue(EntityRenderer.class, minecraft.entityRenderer, 0F, "camRoll", "O");
} catch (Exception e)
{
log("I forgot to update obfuscated reflection D:");
throw new RuntimeException(e);
}
try
{
ObfuscationReflectionHelper.setPrivateValue(EntityRenderer.class, minecraft.entityRenderer, 4.0F, "thirdPersonDistance", "B");
} catch (Exception e)
{
log("I forgot to update obfuscated reflection D:");
throw new RuntimeException(e);
}
inPlane = false;
}
if (controlModeSwitchTimer > 0)
controlModeSwitchTimer--;
if (errorStringTimer > 0)
errorStringTimer--;
}
|
diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/handler/HotSwapHandler.java b/jetty-server/src/main/java/org/eclipse/jetty/server/handler/HotSwapHandler.java
index dbc1dac1b..0b02b237f 100644
--- a/jetty-server/src/main/java/org/eclipse/jetty/server/handler/HotSwapHandler.java
+++ b/jetty-server/src/main/java/org/eclipse/jetty/server/handler/HotSwapHandler.java
@@ -1,164 +1,167 @@
// ========================================================================
// Copyright (c) 2004-2009 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
package org.eclipse.jetty.server.handler;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.Server;
/* ------------------------------------------------------------ */
/** A <code>HandlerContainer</code> that allows a hot swap
* of a wrapped handler.
*
*/
public class HotSwapHandler extends AbstractHandlerContainer
{
private volatile Handler _handler;
/* ------------------------------------------------------------ */
/**
*
*/
public HotSwapHandler()
{
}
/* ------------------------------------------------------------ */
/**
* @return Returns the handlers.
*/
public Handler getHandler()
{
return _handler;
}
/* ------------------------------------------------------------ */
/**
* @return Returns the handlers.
*/
public Handler[] getHandlers()
{
return new Handler[] {_handler};
}
/* ------------------------------------------------------------ */
/**
* @param handler Set the {@link Handler} which should be wrapped.
*/
public void setHandler(Handler handler)
{
try
{
Handler old_handler = _handler;
if (getServer()!=null)
getServer().getContainer().update(this, old_handler, handler, "handler");
if (handler!=null)
{
handler.setServer(getServer());
if (isStarted())
handler.start();
}
_handler = handler;
- if (isStarted())
+ // if there is an old handler and it was started, stop it
+ if (old_handler != null && isStarted())
+ {
old_handler.stop();
+ }
}
catch(RuntimeException e)
{
throw e;
}
catch(Exception e)
{
throw new RuntimeException(e);
}
}
/* ------------------------------------------------------------ */
/*
* @see org.eclipse.thread.AbstractLifeCycle#doStart()
*/
@Override
protected void doStart() throws Exception
{
if (_handler!=null)
_handler.start();
super.doStart();
}
/* ------------------------------------------------------------ */
/*
* @see org.eclipse.thread.AbstractLifeCycle#doStop()
*/
@Override
protected void doStop() throws Exception
{
super.doStop();
if (_handler!=null)
_handler.stop();
}
/* ------------------------------------------------------------ */
/*
* @see org.eclipse.jetty.server.server.EventHandler#handle(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
*/
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{
if (_handler!=null && isStarted())
{
_handler.handle(target,baseRequest, request, response);
}
}
/* ------------------------------------------------------------ */
@Override
public void setServer(Server server)
{
Server old_server=getServer();
if (server==old_server)
return;
if (isRunning())
throw new IllegalStateException(RUNNING);
super.setServer(server);
Handler h=getHandler();
if (h!=null)
h.setServer(server);
if (server!=null && server!=old_server)
server.getContainer().update(this, null,_handler, "handler");
}
/* ------------------------------------------------------------ */
@Override
protected Object expandChildren(Object list, Class byClass)
{
return expandHandler(_handler,list,byClass);
}
}
| false | true | public void setHandler(Handler handler)
{
try
{
Handler old_handler = _handler;
if (getServer()!=null)
getServer().getContainer().update(this, old_handler, handler, "handler");
if (handler!=null)
{
handler.setServer(getServer());
if (isStarted())
handler.start();
}
_handler = handler;
if (isStarted())
old_handler.stop();
}
catch(RuntimeException e)
{
throw e;
}
catch(Exception e)
{
throw new RuntimeException(e);
}
}
| public void setHandler(Handler handler)
{
try
{
Handler old_handler = _handler;
if (getServer()!=null)
getServer().getContainer().update(this, old_handler, handler, "handler");
if (handler!=null)
{
handler.setServer(getServer());
if (isStarted())
handler.start();
}
_handler = handler;
// if there is an old handler and it was started, stop it
if (old_handler != null && isStarted())
{
old_handler.stop();
}
}
catch(RuntimeException e)
{
throw e;
}
catch(Exception e)
{
throw new RuntimeException(e);
}
}
|
diff --git a/src/de/_13ducks/cor/game/server/movement/ServerBehaviourMove.java b/src/de/_13ducks/cor/game/server/movement/ServerBehaviourMove.java
index 8c8d5b8..b71533a 100644
--- a/src/de/_13ducks/cor/game/server/movement/ServerBehaviourMove.java
+++ b/src/de/_13ducks/cor/game/server/movement/ServerBehaviourMove.java
@@ -1,497 +1,498 @@
/*
* Copyright 2008, 2009, 2010, 2011:
* Tobias Fleig (tfg[AT]online[DOT]de),
* Michael Haas (mekhar[AT]gmx[DOT]de),
* Johannes Kattinger (johanneskattinger[AT]gmx[DOT]de)
*
* - All rights reserved -
*
*
* This file is part of Centuries of Rage.
*
* Centuries of Rage 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.
*
* Centuries of Rage 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 Centuries of Rage. If not, see <http://www.gnu.org/licenses/>.
*
*/
package de._13ducks.cor.game.server.movement;
import de._13ducks.cor.game.FloatingPointPosition;
import de._13ducks.cor.game.GameObject;
import de._13ducks.cor.game.Moveable;
import de._13ducks.cor.game.SimplePosition;
import de._13ducks.cor.game.server.Server;
import de._13ducks.cor.networks.server.behaviour.ServerBehaviour;
import de._13ducks.cor.game.server.ServerCore;
import de._13ducks.cor.map.fastfindgrid.Traceable;
import java.util.List;
import org.newdawn.slick.geom.Circle;
import org.newdawn.slick.geom.Polygon;
/**
* Lowlevel-Movemanagement
*
* Verwaltet die reine Bewegung einer einzelnen Einheit.
* Kümmert sich nicht weiter um Formationen/Kampf oder ähnliches.
* Erhält vom übergeordneten MidLevelManager einen Richtungsvektor und eine Zielkoordinate.
* Läuft dann dort hin. Tut sonst nichts.
* Hat exklusive Kontrolle über die Einheitenposition.
* Weigert sich, sich schneller als die maximale Einheitengeschwindigkeit zu bewegen.
* Dadurch werden Sprünge verhindert.
*
* Wenn eine Kollision festgestellt wird, wird der überliegende GroupManager gefragt was zu tun ist.
* Der GroupManager entscheidet dann über die Ausweichroute oder lässt uns warten.
*/
public class ServerBehaviourMove extends ServerBehaviour {
private Moveable caster2;
private Traceable caster3;
private SimplePosition target;
/**
* Mittelpunkt für arc-Bewegungen
*/
private SimplePosition around;
/**
* Aktuelle Bewegung eine Kurve?
*/
private boolean arc;
/**
* Richtung der Kurve (true = Plus)
*/
private boolean arcDirection;
private double speed;
private boolean stopUnit = false;
private long lastTick;
private SimplePosition clientTarget;
private MovementMap moveMap;
private GroupMember pathManager;
/**
* Die Systemzeit zu dem Zeitpunkt, an dem mit dem Warten begonnen wurde
*/
private long waitStartTime;
/**
* Gibt an, ob gerade gewartet wird
* (z.B. wenn etwas im Weg steht und man wartet bis es den Weg freimacht)
*/
private boolean wait;
/**
* Die Zeit, die gewartet wird (in Nanosekunden) (eine milliarde ist eine sekunde)
*/
private static final long waitTime = 3000000000l;
/**
* Eine minimale Distanz, die Einheiten beim Aufstellen wegen einer Kollision berücksichtigen.
* Damit wird verhindert, dass aufgrund von Rundungsfehlern Kolision auf ursprünlich als frei
* eingestuften Flächen berechnet wird.
*/
public static final double MIN_DISTANCE = 0.1;
/**
* Ein simples Flag, das nach dem Kollisionstest gesetzt ist.
*/
private boolean colliding = false;
/**
* Zeigt nach dem Kollisionstest auf das letzte (kollidierende) Objekt.
*/
private Moveable lastObstacle;
public ServerBehaviourMove(ServerCore.InnerServer newinner, GameObject caster1, Moveable caster2, Traceable caster3, MovementMap moveMap) {
super(newinner, caster1, 1, 20, true);
this.caster2 = caster2;
this.caster3 = caster3;
this.moveMap = moveMap;
}
@Override
public void activate() {
active = true;
trigger();
}
@Override
public void deactivate() {
active = false;
}
@Override
public synchronized void execute() {
// Auto-Ende:
if (target == null || speed <= 0) {
deactivate();
return;
}
// Wir laufen also.
// Aktuelle Position berechnen:
// Erstmal default-Berechnung für gerades laufen
FloatingPointPosition oldPos = caster2.getPrecisePosition();
long ticktime = System.nanoTime();
Vector vec = target.toFPP().subtract(oldPos).toVector();
vec.normalizeMe();
vec.multiplyMe((ticktime - lastTick) / 1000000000.0 * speed);
FloatingPointPosition newpos = vec.toFPP().add(oldPos);
if (arc) {
// Kreisbewegung berechnen:
double rad = Math.sqrt((oldPos.x() - around.x()) * (oldPos.x() - around.x()) + (oldPos.y() - around.y()) * (oldPos.y() - around.y()));
double tetha = Math.atan2(oldPos.y() - around.y(), oldPos.x() - around.x());
double delta = vec.length(); // Wie weit wir auf diesem Kreis laufen
if (!arcDirection) { // Falls Richtung negativ delta invertieren
delta *= -1;
}
double newTetha = ((tetha * rad) + delta) / rad; // Strahlensatz, u = 2*PI*r
// Über-/Unterläufe behandeln:
if (newTetha > Math.PI) {
- newTetha = -2 * Math.PI + tetha;
+ newTetha = -2 * Math.PI + newTetha;
} else if (newTetha < -Math.PI) {
- newTetha = 2 * Math.PI + tetha;
+ newTetha = 2 * Math.PI + newTetha;
}
+ System.out.println("rad " + rad + " tetha " + tetha + " delta " + delta + " nt " + newTetha);
Vector newPvec = new Vector(Math.cos(newTetha), Math.sin(newTetha));
newPvec = newPvec.multiply(rad);
newpos = around.toVector().add(newPvec).toFPP();
}
// Ob die Kollision später noch geprüft werden muss. Kann durch ein Weiterlaufen nach warten überschrieben werden.
boolean checkCollision = true;
// Wir sind im Warten-Modus. Jetzt also testen, ob wir zur nächsten Position können
if (wait) {
// Testen, ob wir schon weiterlaufen können:
// Echtzeitkollision:
newpos = checkAndMaxMove(oldPos, newpos);
if (colliding) {
// Immer noch Kollision
if (System.nanoTime() - waitStartTime < waitTime) {
// Das ist ok, einfach weiter warten
lastTick = System.nanoTime();
return;
} else {
// Wartezeit abgelaufen
wait = false;
// Wir stehen schon, der Client auch --> nichts weiter zu tun.
target = null;
deactivate();
System.out.println("STOP waiting: " + caster2);
return;
}
} else {
// Nichtmehr weiter warten - Bewegung wieder starten
System.out.println("GO! Weiter mit " + caster2 + " " + newpos + " nach " + target);
wait = false;
checkCollision = false;
}
}
if (!target.equals(clientTarget) && !stopUnit) {
// An Client senden
rgi.netctrl.broadcastMoveVec(caster2.getNetID(), target.toFPP(), speed);
clientTarget = target.toFPP();
}
if (checkCollision) {
// Zu laufenden Weg auf Kollision prüfen
newpos = checkAndMaxMove(oldPos, newpos);
if (!stopUnit && colliding) {
// Kollision. Gruppenmanager muss entscheiden, ob wir warten oder ne Alternativroute suchen.
wait = this.caster2.getMidLevelManager().collisionDetected(this.caster2, lastObstacle, target);
if (wait) {
waitStartTime = System.nanoTime();
// Spezielle Stopfunktion: (hält den Client in einem Pseudozustand)
// Der Client muss das auch mitbekommen
rgi.netctrl.broadcastDATA(rgi.packetFactory((byte) 24, caster2.getNetID(), 0, Float.floatToIntBits((float) newpos.getfX()), Float.floatToIntBits((float) newpos.getfY())));
setMoveable(oldPos, newpos);
clientTarget = null;
System.out.println("WAIT-COLLISION " + caster2 + " with " + lastObstacle + " stop at " + newpos);
return; // Nicht weiter ausführen!
} else {
// Nochmal laufen, wir haben ein neues Ziel!
trigger();
return;
}
}
}
// Ziel schon erreicht?
Vector nextVec = target.toFPP().subtract(newpos).toVector();
if ((vec.isOpposite(nextVec) || newpos.equals(target)) && !stopUnit) {
// Zielvektor erreicht
// Wir sind warscheinlich drüber - egal einfach auf dem Ziel halten.
setMoveable(oldPos, target.toFPP());
// Neuen Wegpunkt anfordern:
if (!pathManager.reachedTarget(caster2)) {
// Wenn das false gibt, gibts keine weiteren, dann hier halten.
target = null;
stopUnit = false; // Es ist wohl besser auf dem Ziel zu stoppen als kurz dahinter!
deactivate();
}
} else {
// Sofort stoppen?
if (stopUnit) {
// Der Client muss das auch mitbekommen
rgi.netctrl.broadcastDATA(rgi.packetFactory((byte) 24, caster2.getNetID(), 0, Float.floatToIntBits((float) newpos.getfX()), Float.floatToIntBits((float) newpos.getfY())));
System.out.println("MANUSTOP: " + caster2 + " at " + newpos);
setMoveable(oldPos, newpos);
target = null;
stopUnit = false;
deactivate();
} else {
// Weiterlaufen
setMoveable(oldPos, newpos);
lastTick = System.nanoTime();
}
}
}
private void setMoveable(FloatingPointPosition from, FloatingPointPosition to) {
caster2.setMainPosition(to);
// Neuer Sektor?
while (pathManager.nextSectorBorder() != null && pathManager.nextSectorBorder().sidesDiffer(from, to)) {
// Ja, alten löschen und neuen setzen!
SectorChangingEdge edge = pathManager.borderCrossed();
caster2.setMyPoly(edge.getNext(caster2.getMyPoly()));
}
// Schnellsuchraster aktualisieren:
caster3.setCell(Server.getInnerServer().netmap.getFastFindGrid().getNewCell(caster3));
}
@Override
public void gotSignal(byte[] packet) {
}
@Override
public void pause() {
caster2.pause();
}
@Override
public void unpause() {
caster2.unpause();
}
/**
* Setzt den Zielvektor für diese Einheit.
* Es wird nicht untersucht, ob das Ziel in irgendeiner Weise ok ist, die Einheit beginnt sofort loszulaufen.
* In der Regel sollte noch eine Geschwindigkeit angegeben werden.
* Wehrt sich gegen nicht existente Ziele.
* Falls arc true ist, werden arcDirection und arcCenter ausgewertet, sonst nicht.
* @param pos die Zielposition
* @param arc ob das Ziel auf einer Kurve angesteuert werden soll (true)
* @param arcDirection Richtung der Kurve (true - Bogenmaß-Plusrichtung)
* @param arcCenter um welchen Punkt gedreht werden soll.
*/
public synchronized void setTargetVector(SimplePosition pos, boolean arc, boolean arcDirection, SimplePosition arcCenter) {
if (pos == null) {
throw new IllegalArgumentException("Cannot send " + caster2 + " to null (" + arc + ")");
}
if (!pos.toVector().isValid()) {
throw new IllegalArgumentException("Cannot send " + caster2 + " to invalid position (" + arc + ")");
}
target = pos;
lastTick = System.nanoTime();
clientTarget = Vector.ZERO;
this.arc = arc;
this.arcDirection = arcDirection;
this.around = arcCenter;
activate();
}
/**
* Setzt den Zielvektor und die Geschwindigkeit und startet die Bewegung sofort.
* @param pos die Zielposition
* @param speed die Geschwindigkeit
*/
public synchronized void setTargetVector(SimplePosition pos, double speed, boolean arc, boolean arcDirection, SimplePosition arcCenter) {
changeSpeed(speed);
setTargetVector(pos, arc, arcDirection, arcCenter);
}
/**
* Ändert die Geschwindigkeit während des Laufens.
* Speed wird verkleinert, wenn der Wert über dem Einheiten-Maximum liegen würde
* @param speed Die Einheitengeschwindigkeit
*/
public synchronized void changeSpeed(double speed) {
if (speed > 0 && speed <= caster2.getSpeed()) {
this.speed = speed;
}
trigger();
}
public boolean isMoving() {
return target != null;
}
/**
* Stoppt die Einheit innerhalb eines Ticks.
*/
public synchronized void stopImmediately() {
stopUnit = true;
trigger();
}
/**
* Findet einen Sektor, den beide Knoten gemeinsam haben
* @param n1 Knoten 1
* @param n2 Knoten 2
*/
private FreePolygon commonSector(Node n1, Node n2) {
for (FreePolygon poly : n1.getPolygons()) {
if (n2.getPolygons().contains(poly)) {
return poly;
}
}
return null;
}
/**
* Berechnet den Winkel zwischen zwei Vektoren
* @param vector_1
* @param vector_2
* @return
*/
public double getAngle(FloatingPointPosition vector_1, FloatingPointPosition vector_2) {
double scalar = ((vector_1.getfX() * vector_2.getfX()) + (vector_1.getfY() * vector_2.getfY()));
double vector_1_lenght = Math.sqrt((vector_1.getfX() * vector_1.getfX()) + vector_2.getfY() * vector_1.getfY());
double vector_2_lenght = Math.sqrt((vector_2.getfX() * vector_2.getfX()) + vector_2.getfY() * vector_2.getfY());
double lenght = vector_1_lenght * vector_2_lenght;
double angle = Math.acos((scalar / lenght));
return angle;
}
/**
* Untersucht die gegebene Route auf Echtzeitkollision.
* Sollte alles frei sein, wird to zurückgegeben.
* Ansonsten gibts eine neue Position, bis zu der problemlos gelaufen werden kann.
* Im schlimmsten Fall ist dies die from-Position, die frei sein MUSS!
* @param from von wo wir uns losbewegen
* @param to wohin wir laufen
* @return FloatingPointPosition bis wohin man laufen kann.
*/
private FloatingPointPosition checkAndMaxMove(FloatingPointPosition from, FloatingPointPosition to) {
// Zuallererst: Wir dürfen nicht über das Ziel hinaus laufen:
Vector oldtargetVec = new Vector(target.x() - from.x(), target.y() - from.y());
Vector newtargetVec = new Vector(target.x() - to.x(), target.y() - to.y());
if (oldtargetVec.isOpposite(newtargetVec)) {
// Achtung, zu weit!
to = target.toFPP();
}
// Zurücksetzen
lastObstacle = null;
colliding = false;
List<Moveable> possibleCollisions = moveMap.moversAroundPoint(caster2.getPrecisePosition(), caster2.getRadius() + 10, caster2.getMyPoly());
// Uns selber ignorieren
possibleCollisions.remove(caster2);
// Freies Gebiet markieren:
Vector ortho = new Vector(to.getfY() - from.getfY(), from.getfX() - to.getfX()); // 90 Grad verdreht (y, -x)
ortho.normalizeMe();
ortho.multiplyMe(caster2.getRadius());
Vector fromv = from.toVector();
Vector tov = to.toVector();
Polygon poly = new Polygon();
poly.addPoint((float) fromv.add(ortho).x(), (float) fromv.add(ortho).y());
poly.addPoint((float) fromv.add(ortho.getInverted()).x(), (float) fromv.add(ortho.getInverted()).y());
poly.addPoint((float) tov.add(ortho.getInverted()).x(), (float) tov.add(ortho.getInverted()).y());
poly.addPoint((float) tov.add(ortho).x(), (float) tov.add(ortho).y());
poly.addPoint((float) fromv.add(ortho).x(), (float) fromv.add(ortho).y());
for (Moveable t : possibleCollisions) {
float radius = (float) (t.getRadius() + MIN_DISTANCE / 2);
Circle c = new Circle((float) t.getPrecisePosition().x(), (float) t.getPrecisePosition().y(), radius); //Das getUnit ist ugly!
// Die drei Kollisionsbedingungen: Schnitt mit Begrenzungslinien, liegt innerhalb des Testpolygons, liegt zu nah am Ziel
// Die ersten beiden Bedingungen gelten nur für nicht-arc-Bewegungen!
if (!arc && (poly.intersects(c)) || (!arc && poly.includes(c.getCenterX(), c.getCenterY())) || to.getDistance(t.getPrecisePosition()) < caster2.getRadius() + radius) {
// Kollision!
// Jetzt muss poly verkleinert werden.
// Dazu muss die Zielposition to auf der Strecke von from nach to so weit wie notwendig nach hinten verschoben werden.
// Notwendiger Abstand zur gefundenen Kollision t
float distanceToObstacle = (float) (this.caster2.getRadius() + radius + MIN_DISTANCE / 2);
// Vector, der vom start zum Ziel der Bewegung zeigt.
Vector dirVec = new Vector(to.getfX() - from.getfX(), to.getfY() - from.getfY());
// 90 Grad dazu
Vector origin = new Vector(-dirVec.getY(), dirVec.getX());
// Strecke vom Hinderniss in 90-Grad-Richtung
Edge edge = new Edge(t.getPrecisePosition().toNode(), t.getPrecisePosition().add(origin.toFPP()).toNode());
// Strecke zwischen start und ziel
Edge edge2 = new Edge(caster2.getPrecisePosition().toNode(), caster2.getPrecisePosition().add(dirVec.toFPP()).toNode());
// Schnittpunkt
SimplePosition p = edge.endlessIntersection(edge2);
if (p == null) {
System.out.println("ERROR: " + caster2 + " " + edge + " " + edge2 + " " + t.getPrecisePosition() + " " + origin + " " + dirVec + " " + distanceToObstacle);
}
// Abstand vom Hinderniss zur Strecke edge2
double distance = t.getPrecisePosition().getDistance(p.toFPP());
// Abstand vom Punkt auf edge2 zu freigegebenem Punkt
double b = Math.sqrt((distanceToObstacle * distanceToObstacle) - (distance * distance));
// Auf der Strecke weit genug zurück gehen:
FloatingPointPosition nextnewpos = p.toVector().add(dirVec.getInverted().normalize().multiply(b)).toFPP();
// Zurückgegangenes Stück analysieren
if (new Vector(nextnewpos.getfX() - fromv.x(), nextnewpos.getfY() - fromv.y()).isOpposite(dirVec)) {
// Ganz zurück setzen. Dann muss man nicht weiter suchen, die ganze Route ist hoffnungslos blockiert
colliding = true;
lastObstacle = t;
return from;
}
// Hier gibt es keine Kollision mehr.
// poly neu bauen:
to = nextnewpos;
tov = nextnewpos.toVector();
poly = new Polygon();
poly.addPoint((float) fromv.add(ortho).x(), (float) fromv.add(ortho).y());
poly.addPoint((float) fromv.add(ortho.getInverted()).x(), (float) fromv.add(ortho.getInverted()).y());
poly.addPoint((float) tov.add(ortho.getInverted()).x(), (float) tov.add(ortho.getInverted()).y());
poly.addPoint((float) tov.add(ortho).x(), (float) tov.add(ortho).y());
poly.addPoint((float) fromv.add(ortho).x(), (float) fromv.add(ortho).y());
colliding = true;
lastObstacle = t;
// Falls wir so weit zurück mussten, dass es gar netmehr weiter geht:
if (from.equals(to)) {
return from;
}
}
}
// Jetzt wurde alles oft genug verschoben um definitiv keine Kollision mehr zu haben.
// Bis hierhin die Route also freigeben:
return to;
}
/**
* Hiermit lässt sich herausfinden, ob dieser mover gerade wartet, weil jemand im Weg steht.
* @return
*/
boolean isWaiting() {
return wait;
}
/**
* @return the pathManager
*/
GroupMember getPathManager() {
return pathManager;
}
/**
* @param pathManager the pathManager to set
*/
void setPathManager(GroupMember pathManager) {
this.pathManager = pathManager;
}
}
| false | true | public synchronized void execute() {
// Auto-Ende:
if (target == null || speed <= 0) {
deactivate();
return;
}
// Wir laufen also.
// Aktuelle Position berechnen:
// Erstmal default-Berechnung für gerades laufen
FloatingPointPosition oldPos = caster2.getPrecisePosition();
long ticktime = System.nanoTime();
Vector vec = target.toFPP().subtract(oldPos).toVector();
vec.normalizeMe();
vec.multiplyMe((ticktime - lastTick) / 1000000000.0 * speed);
FloatingPointPosition newpos = vec.toFPP().add(oldPos);
if (arc) {
// Kreisbewegung berechnen:
double rad = Math.sqrt((oldPos.x() - around.x()) * (oldPos.x() - around.x()) + (oldPos.y() - around.y()) * (oldPos.y() - around.y()));
double tetha = Math.atan2(oldPos.y() - around.y(), oldPos.x() - around.x());
double delta = vec.length(); // Wie weit wir auf diesem Kreis laufen
if (!arcDirection) { // Falls Richtung negativ delta invertieren
delta *= -1;
}
double newTetha = ((tetha * rad) + delta) / rad; // Strahlensatz, u = 2*PI*r
// Über-/Unterläufe behandeln:
if (newTetha > Math.PI) {
newTetha = -2 * Math.PI + tetha;
} else if (newTetha < -Math.PI) {
newTetha = 2 * Math.PI + tetha;
}
Vector newPvec = new Vector(Math.cos(newTetha), Math.sin(newTetha));
newPvec = newPvec.multiply(rad);
newpos = around.toVector().add(newPvec).toFPP();
}
// Ob die Kollision später noch geprüft werden muss. Kann durch ein Weiterlaufen nach warten überschrieben werden.
boolean checkCollision = true;
// Wir sind im Warten-Modus. Jetzt also testen, ob wir zur nächsten Position können
if (wait) {
// Testen, ob wir schon weiterlaufen können:
// Echtzeitkollision:
newpos = checkAndMaxMove(oldPos, newpos);
if (colliding) {
// Immer noch Kollision
if (System.nanoTime() - waitStartTime < waitTime) {
// Das ist ok, einfach weiter warten
lastTick = System.nanoTime();
return;
} else {
// Wartezeit abgelaufen
wait = false;
// Wir stehen schon, der Client auch --> nichts weiter zu tun.
target = null;
deactivate();
System.out.println("STOP waiting: " + caster2);
return;
}
} else {
// Nichtmehr weiter warten - Bewegung wieder starten
System.out.println("GO! Weiter mit " + caster2 + " " + newpos + " nach " + target);
wait = false;
checkCollision = false;
}
}
if (!target.equals(clientTarget) && !stopUnit) {
// An Client senden
rgi.netctrl.broadcastMoveVec(caster2.getNetID(), target.toFPP(), speed);
clientTarget = target.toFPP();
}
if (checkCollision) {
// Zu laufenden Weg auf Kollision prüfen
newpos = checkAndMaxMove(oldPos, newpos);
if (!stopUnit && colliding) {
// Kollision. Gruppenmanager muss entscheiden, ob wir warten oder ne Alternativroute suchen.
wait = this.caster2.getMidLevelManager().collisionDetected(this.caster2, lastObstacle, target);
if (wait) {
waitStartTime = System.nanoTime();
// Spezielle Stopfunktion: (hält den Client in einem Pseudozustand)
// Der Client muss das auch mitbekommen
rgi.netctrl.broadcastDATA(rgi.packetFactory((byte) 24, caster2.getNetID(), 0, Float.floatToIntBits((float) newpos.getfX()), Float.floatToIntBits((float) newpos.getfY())));
setMoveable(oldPos, newpos);
clientTarget = null;
System.out.println("WAIT-COLLISION " + caster2 + " with " + lastObstacle + " stop at " + newpos);
return; // Nicht weiter ausführen!
} else {
// Nochmal laufen, wir haben ein neues Ziel!
trigger();
return;
}
}
}
// Ziel schon erreicht?
Vector nextVec = target.toFPP().subtract(newpos).toVector();
if ((vec.isOpposite(nextVec) || newpos.equals(target)) && !stopUnit) {
// Zielvektor erreicht
// Wir sind warscheinlich drüber - egal einfach auf dem Ziel halten.
setMoveable(oldPos, target.toFPP());
// Neuen Wegpunkt anfordern:
if (!pathManager.reachedTarget(caster2)) {
// Wenn das false gibt, gibts keine weiteren, dann hier halten.
target = null;
stopUnit = false; // Es ist wohl besser auf dem Ziel zu stoppen als kurz dahinter!
deactivate();
}
} else {
// Sofort stoppen?
if (stopUnit) {
// Der Client muss das auch mitbekommen
rgi.netctrl.broadcastDATA(rgi.packetFactory((byte) 24, caster2.getNetID(), 0, Float.floatToIntBits((float) newpos.getfX()), Float.floatToIntBits((float) newpos.getfY())));
System.out.println("MANUSTOP: " + caster2 + " at " + newpos);
setMoveable(oldPos, newpos);
target = null;
stopUnit = false;
deactivate();
} else {
// Weiterlaufen
setMoveable(oldPos, newpos);
lastTick = System.nanoTime();
}
}
}
| public synchronized void execute() {
// Auto-Ende:
if (target == null || speed <= 0) {
deactivate();
return;
}
// Wir laufen also.
// Aktuelle Position berechnen:
// Erstmal default-Berechnung für gerades laufen
FloatingPointPosition oldPos = caster2.getPrecisePosition();
long ticktime = System.nanoTime();
Vector vec = target.toFPP().subtract(oldPos).toVector();
vec.normalizeMe();
vec.multiplyMe((ticktime - lastTick) / 1000000000.0 * speed);
FloatingPointPosition newpos = vec.toFPP().add(oldPos);
if (arc) {
// Kreisbewegung berechnen:
double rad = Math.sqrt((oldPos.x() - around.x()) * (oldPos.x() - around.x()) + (oldPos.y() - around.y()) * (oldPos.y() - around.y()));
double tetha = Math.atan2(oldPos.y() - around.y(), oldPos.x() - around.x());
double delta = vec.length(); // Wie weit wir auf diesem Kreis laufen
if (!arcDirection) { // Falls Richtung negativ delta invertieren
delta *= -1;
}
double newTetha = ((tetha * rad) + delta) / rad; // Strahlensatz, u = 2*PI*r
// Über-/Unterläufe behandeln:
if (newTetha > Math.PI) {
newTetha = -2 * Math.PI + newTetha;
} else if (newTetha < -Math.PI) {
newTetha = 2 * Math.PI + newTetha;
}
System.out.println("rad " + rad + " tetha " + tetha + " delta " + delta + " nt " + newTetha);
Vector newPvec = new Vector(Math.cos(newTetha), Math.sin(newTetha));
newPvec = newPvec.multiply(rad);
newpos = around.toVector().add(newPvec).toFPP();
}
// Ob die Kollision später noch geprüft werden muss. Kann durch ein Weiterlaufen nach warten überschrieben werden.
boolean checkCollision = true;
// Wir sind im Warten-Modus. Jetzt also testen, ob wir zur nächsten Position können
if (wait) {
// Testen, ob wir schon weiterlaufen können:
// Echtzeitkollision:
newpos = checkAndMaxMove(oldPos, newpos);
if (colliding) {
// Immer noch Kollision
if (System.nanoTime() - waitStartTime < waitTime) {
// Das ist ok, einfach weiter warten
lastTick = System.nanoTime();
return;
} else {
// Wartezeit abgelaufen
wait = false;
// Wir stehen schon, der Client auch --> nichts weiter zu tun.
target = null;
deactivate();
System.out.println("STOP waiting: " + caster2);
return;
}
} else {
// Nichtmehr weiter warten - Bewegung wieder starten
System.out.println("GO! Weiter mit " + caster2 + " " + newpos + " nach " + target);
wait = false;
checkCollision = false;
}
}
if (!target.equals(clientTarget) && !stopUnit) {
// An Client senden
rgi.netctrl.broadcastMoveVec(caster2.getNetID(), target.toFPP(), speed);
clientTarget = target.toFPP();
}
if (checkCollision) {
// Zu laufenden Weg auf Kollision prüfen
newpos = checkAndMaxMove(oldPos, newpos);
if (!stopUnit && colliding) {
// Kollision. Gruppenmanager muss entscheiden, ob wir warten oder ne Alternativroute suchen.
wait = this.caster2.getMidLevelManager().collisionDetected(this.caster2, lastObstacle, target);
if (wait) {
waitStartTime = System.nanoTime();
// Spezielle Stopfunktion: (hält den Client in einem Pseudozustand)
// Der Client muss das auch mitbekommen
rgi.netctrl.broadcastDATA(rgi.packetFactory((byte) 24, caster2.getNetID(), 0, Float.floatToIntBits((float) newpos.getfX()), Float.floatToIntBits((float) newpos.getfY())));
setMoveable(oldPos, newpos);
clientTarget = null;
System.out.println("WAIT-COLLISION " + caster2 + " with " + lastObstacle + " stop at " + newpos);
return; // Nicht weiter ausführen!
} else {
// Nochmal laufen, wir haben ein neues Ziel!
trigger();
return;
}
}
}
// Ziel schon erreicht?
Vector nextVec = target.toFPP().subtract(newpos).toVector();
if ((vec.isOpposite(nextVec) || newpos.equals(target)) && !stopUnit) {
// Zielvektor erreicht
// Wir sind warscheinlich drüber - egal einfach auf dem Ziel halten.
setMoveable(oldPos, target.toFPP());
// Neuen Wegpunkt anfordern:
if (!pathManager.reachedTarget(caster2)) {
// Wenn das false gibt, gibts keine weiteren, dann hier halten.
target = null;
stopUnit = false; // Es ist wohl besser auf dem Ziel zu stoppen als kurz dahinter!
deactivate();
}
} else {
// Sofort stoppen?
if (stopUnit) {
// Der Client muss das auch mitbekommen
rgi.netctrl.broadcastDATA(rgi.packetFactory((byte) 24, caster2.getNetID(), 0, Float.floatToIntBits((float) newpos.getfX()), Float.floatToIntBits((float) newpos.getfY())));
System.out.println("MANUSTOP: " + caster2 + " at " + newpos);
setMoveable(oldPos, newpos);
target = null;
stopUnit = false;
deactivate();
} else {
// Weiterlaufen
setMoveable(oldPos, newpos);
lastTick = System.nanoTime();
}
}
}
|
diff --git a/dtgov-war/src/main/java/org/overlord/sramp/governance/services/NotificationResource.java b/dtgov-war/src/main/java/org/overlord/sramp/governance/services/NotificationResource.java
index 43352f2..cf97e8d 100644
--- a/dtgov-war/src/main/java/org/overlord/sramp/governance/services/NotificationResource.java
+++ b/dtgov-war/src/main/java/org/overlord/sramp/governance/services/NotificationResource.java
@@ -1,163 +1,164 @@
/*
* Copyright 2013 JBoss Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.overlord.sramp.governance.services;
import java.io.InputStream;
import java.net.URL;
import javax.mail.Address;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import org.apache.commons.io.IOUtils;
import org.overlord.dtgov.server.i18n.Messages;
import org.overlord.sramp.atom.MediaType;
import org.overlord.sramp.atom.err.SrampAtomException;
import org.overlord.sramp.client.SrampAtomApiClient;
import org.overlord.sramp.client.query.ArtifactSummary;
import org.overlord.sramp.client.query.QueryResultSet;
import org.overlord.sramp.governance.Governance;
import org.overlord.sramp.governance.NotificationDestinations;
import org.overlord.sramp.governance.SlashDecoder;
import org.overlord.sramp.governance.SrampAtomApiClientFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* The JAX-RS resource that handles notification specific tasks.
*
*/
@Path("/notify")
public class NotificationResource {
private Session mailSession;
private static Logger logger = LoggerFactory.getLogger(NotificationResource.class);
private Governance governance = new Governance();
/**
* Constructor.
* @throws NamingException
*/
public NotificationResource() {
InitialContext context;
try {
String jndiEmailRef = governance.getJNDIEmailName();
context = new InitialContext();
mailSession = (Session) context.lookup(jndiEmailRef);
if (mailSession==null) {
logger.error(Messages.i18n.format("NotificationResource.JndiLookupFailed", jndiEmailRef)); //$NON-NLS-1$
}
} catch (NamingException e) {
logger.error(e.getMessage(),e);
}
}
/**
* POST to email a notification about an artifact.
*
* @param environment
* @param uuid
* @throws SrampAtomException
*/
@POST
@Path("email/{group}/{template}/{target}/{uuid}")
@Produces(MediaType.APPLICATION_XML)
public Response emailNotification(@Context HttpServletRequest request,
@PathParam("group") String group,
@PathParam("template") String template,
@PathParam("target") String target,
@PathParam("uuid") String uuid) throws Exception {
try {
// 0. run the decoder on the arguments, after replacing * by % (this so parameters can
// contain slashes (%2F)
group = SlashDecoder.decode(group);
template = SlashDecoder.decode(template);
target = SlashDecoder.decode(target);
uuid = SlashDecoder.decode(uuid);
// 1. get the artifact from the repo
SrampAtomApiClient client = SrampAtomApiClientFactory.createAtomApiClient();
String query = String.format("/s-ramp[@uuid='%s']", uuid); //$NON-NLS-1$
QueryResultSet queryResultSet = client.query(query);
if (queryResultSet.size() == 0) {
return Response.serverError().status(0).build();
}
ArtifactSummary artifactSummary = queryResultSet.iterator().next();
// 2. get the destinations for this group
NotificationDestinations destinations = governance.getNotificationDestinations("email").get(group); //$NON-NLS-1$
if (destinations==null) {
destinations = new NotificationDestinations(group,
governance.getDefaultEmailFromAddress(),
group + "@" + governance.getDefaultEmailDomain()); //$NON-NLS-1$
}
// 3. send the email notification
try {
MimeMessage m = new MimeMessage(mailSession);
Address from = new InternetAddress(destinations.getFromAddress());
Address[] to = new InternetAddress[destinations.getToAddresses().length];
for (int i=0; i<destinations.getToAddresses().length;i++) {
to[i] = new InternetAddress(destinations.getToAddresses()[i]);
}
m.setFrom(from);
m.setRecipients(Message.RecipientType.TO, to);
String subject = "/governance-email-templates/" + template + ".subject.tmpl"; //$NON-NLS-1$ //$NON-NLS-2$
URL subjectUrl = Governance.class.getClassLoader().getResource(subject);
if (subjectUrl!=null) subject=IOUtils.toString(subjectUrl);
subject = subject.replaceAll("\\$\\{uuid}", uuid); //$NON-NLS-1$
subject = subject.replaceAll("\\$\\{name}", artifactSummary.getName()); //$NON-NLS-1$
subject = subject.replaceAll("\\$\\{target}", target); //$NON-NLS-1$
m.setSubject(subject);
m.setSentDate(new java.util.Date());
String content = "/governance-email-templates/" + template + ".body.tmpl"; //$NON-NLS-1$ //$NON-NLS-2$
URL contentUrl = Governance.class.getClassLoader().getResource(content);
if (contentUrl!=null) content=IOUtils.toString(contentUrl);
content = content.replaceAll("\\$\\{uuid}", uuid); //$NON-NLS-1$
content = content.replaceAll("\\$\\{name}", artifactSummary.getName()); //$NON-NLS-1$
content = content.replaceAll("\\$\\{target}", target); //$NON-NLS-1$
+ content = content.replaceAll("\\$\\{dtgovurl}", governance.getDTGovUiUrl()); //$NON-NLS-1$
m.setContent(content,"text/plain"); //$NON-NLS-1$
Transport.send(m);
} catch (javax.mail.MessagingException e) {
logger.error(e.getMessage(),e);
}
// 4. build the response
InputStream reply = IOUtils.toInputStream("success"); //$NON-NLS-1$
return Response.ok(reply, MediaType.APPLICATION_OCTET_STREAM).build();
} catch (Exception e) {
logger.error(Messages.i18n.format("NotificationResource.EmailError", e.getMessage(), e)); //$NON-NLS-1$
throw new SrampAtomException(e);
}
}
}
| true | true | public Response emailNotification(@Context HttpServletRequest request,
@PathParam("group") String group,
@PathParam("template") String template,
@PathParam("target") String target,
@PathParam("uuid") String uuid) throws Exception {
try {
// 0. run the decoder on the arguments, after replacing * by % (this so parameters can
// contain slashes (%2F)
group = SlashDecoder.decode(group);
template = SlashDecoder.decode(template);
target = SlashDecoder.decode(target);
uuid = SlashDecoder.decode(uuid);
// 1. get the artifact from the repo
SrampAtomApiClient client = SrampAtomApiClientFactory.createAtomApiClient();
String query = String.format("/s-ramp[@uuid='%s']", uuid); //$NON-NLS-1$
QueryResultSet queryResultSet = client.query(query);
if (queryResultSet.size() == 0) {
return Response.serverError().status(0).build();
}
ArtifactSummary artifactSummary = queryResultSet.iterator().next();
// 2. get the destinations for this group
NotificationDestinations destinations = governance.getNotificationDestinations("email").get(group); //$NON-NLS-1$
if (destinations==null) {
destinations = new NotificationDestinations(group,
governance.getDefaultEmailFromAddress(),
group + "@" + governance.getDefaultEmailDomain()); //$NON-NLS-1$
}
// 3. send the email notification
try {
MimeMessage m = new MimeMessage(mailSession);
Address from = new InternetAddress(destinations.getFromAddress());
Address[] to = new InternetAddress[destinations.getToAddresses().length];
for (int i=0; i<destinations.getToAddresses().length;i++) {
to[i] = new InternetAddress(destinations.getToAddresses()[i]);
}
m.setFrom(from);
m.setRecipients(Message.RecipientType.TO, to);
String subject = "/governance-email-templates/" + template + ".subject.tmpl"; //$NON-NLS-1$ //$NON-NLS-2$
URL subjectUrl = Governance.class.getClassLoader().getResource(subject);
if (subjectUrl!=null) subject=IOUtils.toString(subjectUrl);
subject = subject.replaceAll("\\$\\{uuid}", uuid); //$NON-NLS-1$
subject = subject.replaceAll("\\$\\{name}", artifactSummary.getName()); //$NON-NLS-1$
subject = subject.replaceAll("\\$\\{target}", target); //$NON-NLS-1$
m.setSubject(subject);
m.setSentDate(new java.util.Date());
String content = "/governance-email-templates/" + template + ".body.tmpl"; //$NON-NLS-1$ //$NON-NLS-2$
URL contentUrl = Governance.class.getClassLoader().getResource(content);
if (contentUrl!=null) content=IOUtils.toString(contentUrl);
content = content.replaceAll("\\$\\{uuid}", uuid); //$NON-NLS-1$
content = content.replaceAll("\\$\\{name}", artifactSummary.getName()); //$NON-NLS-1$
content = content.replaceAll("\\$\\{target}", target); //$NON-NLS-1$
m.setContent(content,"text/plain"); //$NON-NLS-1$
Transport.send(m);
} catch (javax.mail.MessagingException e) {
logger.error(e.getMessage(),e);
}
// 4. build the response
InputStream reply = IOUtils.toInputStream("success"); //$NON-NLS-1$
return Response.ok(reply, MediaType.APPLICATION_OCTET_STREAM).build();
} catch (Exception e) {
logger.error(Messages.i18n.format("NotificationResource.EmailError", e.getMessage(), e)); //$NON-NLS-1$
throw new SrampAtomException(e);
}
}
| public Response emailNotification(@Context HttpServletRequest request,
@PathParam("group") String group,
@PathParam("template") String template,
@PathParam("target") String target,
@PathParam("uuid") String uuid) throws Exception {
try {
// 0. run the decoder on the arguments, after replacing * by % (this so parameters can
// contain slashes (%2F)
group = SlashDecoder.decode(group);
template = SlashDecoder.decode(template);
target = SlashDecoder.decode(target);
uuid = SlashDecoder.decode(uuid);
// 1. get the artifact from the repo
SrampAtomApiClient client = SrampAtomApiClientFactory.createAtomApiClient();
String query = String.format("/s-ramp[@uuid='%s']", uuid); //$NON-NLS-1$
QueryResultSet queryResultSet = client.query(query);
if (queryResultSet.size() == 0) {
return Response.serverError().status(0).build();
}
ArtifactSummary artifactSummary = queryResultSet.iterator().next();
// 2. get the destinations for this group
NotificationDestinations destinations = governance.getNotificationDestinations("email").get(group); //$NON-NLS-1$
if (destinations==null) {
destinations = new NotificationDestinations(group,
governance.getDefaultEmailFromAddress(),
group + "@" + governance.getDefaultEmailDomain()); //$NON-NLS-1$
}
// 3. send the email notification
try {
MimeMessage m = new MimeMessage(mailSession);
Address from = new InternetAddress(destinations.getFromAddress());
Address[] to = new InternetAddress[destinations.getToAddresses().length];
for (int i=0; i<destinations.getToAddresses().length;i++) {
to[i] = new InternetAddress(destinations.getToAddresses()[i]);
}
m.setFrom(from);
m.setRecipients(Message.RecipientType.TO, to);
String subject = "/governance-email-templates/" + template + ".subject.tmpl"; //$NON-NLS-1$ //$NON-NLS-2$
URL subjectUrl = Governance.class.getClassLoader().getResource(subject);
if (subjectUrl!=null) subject=IOUtils.toString(subjectUrl);
subject = subject.replaceAll("\\$\\{uuid}", uuid); //$NON-NLS-1$
subject = subject.replaceAll("\\$\\{name}", artifactSummary.getName()); //$NON-NLS-1$
subject = subject.replaceAll("\\$\\{target}", target); //$NON-NLS-1$
m.setSubject(subject);
m.setSentDate(new java.util.Date());
String content = "/governance-email-templates/" + template + ".body.tmpl"; //$NON-NLS-1$ //$NON-NLS-2$
URL contentUrl = Governance.class.getClassLoader().getResource(content);
if (contentUrl!=null) content=IOUtils.toString(contentUrl);
content = content.replaceAll("\\$\\{uuid}", uuid); //$NON-NLS-1$
content = content.replaceAll("\\$\\{name}", artifactSummary.getName()); //$NON-NLS-1$
content = content.replaceAll("\\$\\{target}", target); //$NON-NLS-1$
content = content.replaceAll("\\$\\{dtgovurl}", governance.getDTGovUiUrl()); //$NON-NLS-1$
m.setContent(content,"text/plain"); //$NON-NLS-1$
Transport.send(m);
} catch (javax.mail.MessagingException e) {
logger.error(e.getMessage(),e);
}
// 4. build the response
InputStream reply = IOUtils.toInputStream("success"); //$NON-NLS-1$
return Response.ok(reply, MediaType.APPLICATION_OCTET_STREAM).build();
} catch (Exception e) {
logger.error(Messages.i18n.format("NotificationResource.EmailError", e.getMessage(), e)); //$NON-NLS-1$
throw new SrampAtomException(e);
}
}
|
diff --git a/src/com/daneel87/AneCMS/Blog/BlogNewPost.java b/src/com/daneel87/AneCMS/Blog/BlogNewPost.java
index a13ad81..6033ab1 100644
--- a/src/com/daneel87/AneCMS/Blog/BlogNewPost.java
+++ b/src/com/daneel87/AneCMS/Blog/BlogNewPost.java
@@ -1,54 +1,54 @@
package com.daneel87.AneCMS.Blog;
import org.xmlrpc.android.XMLRPCClient;
import org.xmlrpc.android.XMLRPCException;
import com.daneel87.AneCMS.R;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class BlogNewPost extends Activity {
private String server;
private String sessionid;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.blog_new_post);
Bundle b = getIntent().getExtras();
server = b.getString("server");
sessionid = b.getString("sessionid");
// TODO Auto-generated method stub
}
public void Post(View v) {
EditText titolo = (EditText)findViewById(R.id.NewPostTitle);
EditText contenuto = (EditText)findViewById(R.id.NewPostContent);
- String[] parameters = new String[] {sessionid,titolo.getText().toString(), contenuto.getText().toString(), ""};
+ String[] parameters = new String[] {sessionid,titolo.getText().toString(), contenuto.getText().toString().replace("\n", "<br />"), ""};
XMLRPCClient client = new XMLRPCClient(server + "/xmlrpc.php");
try {
Boolean result = (Boolean) client.call("AneCMSBlog.addPost", parameters);
if (result){
CharSequence text = this.getString(R.string.posted);
int duration = Toast.LENGTH_LONG;
Toast.makeText(getApplicationContext(), text, duration).show();
finish();
return;
}
} catch (Exception e) {
// TODO Auto-generated catch block
}
CharSequence text = this.getString(R.string.not_posted);
int duration = Toast.LENGTH_LONG;
Toast.makeText(getApplicationContext(), text, duration).show();
}
}
| true | true | public void Post(View v) {
EditText titolo = (EditText)findViewById(R.id.NewPostTitle);
EditText contenuto = (EditText)findViewById(R.id.NewPostContent);
String[] parameters = new String[] {sessionid,titolo.getText().toString(), contenuto.getText().toString(), ""};
XMLRPCClient client = new XMLRPCClient(server + "/xmlrpc.php");
try {
Boolean result = (Boolean) client.call("AneCMSBlog.addPost", parameters);
if (result){
CharSequence text = this.getString(R.string.posted);
int duration = Toast.LENGTH_LONG;
Toast.makeText(getApplicationContext(), text, duration).show();
finish();
return;
}
} catch (Exception e) {
// TODO Auto-generated catch block
}
CharSequence text = this.getString(R.string.not_posted);
int duration = Toast.LENGTH_LONG;
Toast.makeText(getApplicationContext(), text, duration).show();
}
| public void Post(View v) {
EditText titolo = (EditText)findViewById(R.id.NewPostTitle);
EditText contenuto = (EditText)findViewById(R.id.NewPostContent);
String[] parameters = new String[] {sessionid,titolo.getText().toString(), contenuto.getText().toString().replace("\n", "<br />"), ""};
XMLRPCClient client = new XMLRPCClient(server + "/xmlrpc.php");
try {
Boolean result = (Boolean) client.call("AneCMSBlog.addPost", parameters);
if (result){
CharSequence text = this.getString(R.string.posted);
int duration = Toast.LENGTH_LONG;
Toast.makeText(getApplicationContext(), text, duration).show();
finish();
return;
}
} catch (Exception e) {
// TODO Auto-generated catch block
}
CharSequence text = this.getString(R.string.not_posted);
int duration = Toast.LENGTH_LONG;
Toast.makeText(getApplicationContext(), text, duration).show();
}
|
diff --git a/core/src/test/java/org/mule/galaxy/impl/ArtifactTest.java b/core/src/test/java/org/mule/galaxy/impl/ArtifactTest.java
index 86073145..d7bcf1a4 100755
--- a/core/src/test/java/org/mule/galaxy/impl/ArtifactTest.java
+++ b/core/src/test/java/org/mule/galaxy/impl/ArtifactTest.java
@@ -1,340 +1,341 @@
package org.mule.galaxy.impl;
import java.io.InputStream;
import java.util.Calendar;
import java.util.List;
import java.util.Set;
import org.mule.galaxy.Item;
import org.mule.galaxy.PropertyInfo;
import org.mule.galaxy.Registry;
import org.mule.galaxy.artifact.Artifact;
import org.mule.galaxy.lifecycle.Phase;
import org.mule.galaxy.query.Query;
import org.mule.galaxy.test.AbstractGalaxyTest;
import org.mule.galaxy.type.TypeManager;
import org.w3c.dom.Document;
public class ArtifactTest extends AbstractGalaxyTest {
public void testMove() throws Exception {
Item a = importHelloWsdl();
Item w = registry.newItem("test", typeManager.getTypeByName(TypeManager.WORKSPACE)).getItem();
registry.move(a, w.getPath(), a.getName());
assertEquals(w.getId(), a.getParent().getId());
Set<Item> results = registry.search(new Query().fromId(w.getId())).getResults();
assertEquals(1, results.size());
// test moving it into the workspace its already in.
registry.move(a, w.getPath(), a.getName());
}
public void testRename() throws Exception {
Item a = importHelloWsdl();
a.setName("2.0");
List<Item> artifacts = a.getParent().getItems();
assertEquals(1, artifacts.size());
Item a2 = (Item) artifacts.iterator().next();
assertEquals("2.0", a2.getName());
}
//
// public void testWorkspaces() throws Exception {
// Collection<Item> workspaces = registry.getItems();
// assertEquals(1, workspaces.size());
//
// Item newWork = registry.newItem("New Workspace", type);
// assertEquals("New Workspace", newWork.getName());
// assertNotNull(newWork.getId());
//
// try {
// registry.newItem("New Workspace", type);
// fail("Two workspaces with the same name");
// } catch (DuplicateItemException e) {
// }
//
// Item child = newWork.newItem("Child", type);
// assertEquals("Child", child.getName());
// assertNotNull(child.getId());
// assertNotNull(child.getUpdated());
//
// assertEquals(1, newWork.getChildren().size());
//
// newWork.delete();
//
// assertEquals(1, registry.getItems().size());
//
// Item root = workspaces.iterator().next();
// child = root.newItem("child", type);
//
// Item newRoot = registry.newItem("newroot", type);
// registry.save(child, newRoot.getId());
//
// Collection<Item> children = newRoot.getChildren();
// assertEquals(1, children.size());
//
// child = children.iterator().next();
// assertNotNull(child.getParent());
//
// registry.save(newRoot, "root");
//
// Item newWorkspace = newRoot.newItem("child2", type);
//
// registry.save(newWorkspace, "root");
//
// assertNull(newWorkspace.getParent());
// }
//
// public void testAddDuplicate() throws Exception {
// InputStream helloWsdl = getResourceAsStream("/wsdl/hello.wsdl");
//
// Collection<Item> workspaces = registry.getItems();
// assertEquals(1, workspaces.size());
// Item workspace = workspaces.iterator().next();
//
// workspace.createArtifact("application/wsdl+xml", "hello_world.wsdl", "0.1", helloWsdl);
//
// helloWsdl = getResourceAsStream("/wsdl/hello.wsdl");
// try {
// workspace.createArtifact("application/wsdl+xml", "hello_world.wsdl", "0.1", helloWsdl);
// fail("Expected a duplicate item exception");
// } catch (DuplicateItemException e) {
// // great! expected
// }
//
// Collection<Item> artifacts = workspace.getItems();
// assertEquals(1, artifacts.size());
// }
//
// public void testAddWsdlWithApplicationOctetStream() throws Exception {
// InputStream helloWsdl = getResourceAsStream("/wsdl/hello.wsdl");
//
// Collection<Item> workspaces = registry.getItems();
// assertEquals(1, workspaces.size());
// Item workspace = workspaces.iterator().next();
//
// NewItemResult ar = workspace.createArtifact("application/octet-stream",
// "hello_world.wsdl", "0.1", helloWsdl);
//
// ArtifactImpl artifact = (ArtifactImpl) ar.getItem();
//
// assertEquals("application/wsdl+xml", artifact.getContentType().toString());
// }
//
// public void testAddMuleConfig() throws Exception {
// InputStream helloMule = getResourceAsStream("/mule/hello-config.xml");
//
// Collection<Item> workspaces = registry.getItems();
// assertEquals(1, workspaces.size());
// Item workspace = workspaces.iterator().next();
//
// // Try application/xml
// NewItemResult ar = workspace.createArtifact("application/xml",
// "hello_world.xml", "0.1", helloMule);
//
// ArtifactImpl artifact = (ArtifactImpl) ar.getItem();
//
// assertEquals("application/xml", artifact.getContentType().toString());
// assertEquals("mule-configuration", artifact.getDocumentType().getLocalPart());
//
//
// // Try application/octent-stream
// helloMule = getResourceAsStream("/mule/hello-config.xml");
// ar = workspace.createArtifact("application/octet-stream", "hello_world2.xml", "0.1",
// helloMule);
//
// artifact = (ArtifactImpl) ar.getItem();
//
// assertEquals("application/xml", artifact.getContentType().toString());
// assertEquals("mule-configuration", artifact.getDocumentType().getLocalPart());
// }
public void testAddWsdl() throws Exception {
Item av = importHelloWsdl();
assertNotNull(av.getId());
Phase p = av.getProperty(Registry.PRIMARY_LIFECYCLE);
assertNotNull(p);
p = av.getParent().getProperty(Registry.PRIMARY_LIFECYCLE);
assertNull(p);
Artifact artifact = av.getProperty("artifact");
assertNotNull(artifact);
assertEquals("application/xml", artifact.getContentType().toString());
assertNotNull(artifact.getDocumentType());
assertEquals("definitions", artifact.getDocumentType().getLocalPart());
// test properties
boolean testedTNS = false;
for (PropertyInfo next : av.getProperties()) {
if (next.getName().equals("wsdl.targetNamespace")) {
assertEquals("wsdl.targetNamespace", next.getName());
assertNotNull(next.getValue());
assertTrue(next.isLocked());
assertTrue(next.isVisible());
assertEquals("WSDL Target Namespace", next.getDescription());
testedTNS = true;
}
}
Calendar origUpdated = av.getUpdated();
assertNotNull(origUpdated);
assertTrue(testedTNS);
// This is odd, but otherwise the updates happen too fast, and the lastUpdated tstamp isn't changed
Thread.sleep(500);
av.setLocked("wsdl.targetNamespace", true);
av.setVisible("wsdl.targetNamespace", false);
PropertyInfo pi = av.getPropertyInfo("wsdl.targetNamespace");
assertTrue(pi.isLocked());
assertFalse(pi.isVisible());
Calendar update = av.getUpdated();
assertTrue(update.after(origUpdated));
av.setProperty("foo", "bar");
assertEquals("bar", av.getProperty("foo"));
// Test the version history
- assertTrue(artifact.getData() instanceof Document);
+ final Object data = artifact.getData();
+ assertTrue(data instanceof Document);
assertNotNull(av.getAuthor());
assertEquals("Created", getPhase(av).getName());
Calendar created = av.getCreated();
assertTrue(created.getTime().getTime() > 0);
av.setProperty("foo", "bar");
assertEquals("bar", av.getProperty("foo"));
// Create another version
InputStream stream = artifact.getInputStream();
assertNotNull(stream);
stream.close();
// InputStream helloWsdl2 = getResourceAsStream("/wsdl/hello.wsdl");
//
// ar = artifact.newVersion(helloWsdl2, "0.2");
// assertTrue(waitForIndexing((ArtifactVersion)ar.getEntryVersion()));
// JcrVersion newVersion = (JcrVersion) ar.getEntryVersion();
// assertTrue(newVersion.isLatest());
// assertFalse(version.isLatest());
//
// assertSame(newVersion, ar.getItem().getDefaultOrLastVersion());
//
// versions = artifact.getVersions();
// assertEquals(2, versions.size());
//
// assertEquals("0.2", newVersion.getVersionLabel());
// assertEquals("Created", getPhase(newVersion).getName());
//
// stream = newVersion.getStream();
// assertNotNull(stream);
// assertTrue(stream.available() > 0);
// stream.close();
//
// assertNotNull(newVersion.getAuthor());
//
// newVersion.setProperty("foo2", "bar");
// assertEquals("bar", newVersion.getProperty("foo2"));
// assertNull(version.getProperty("foo2"));
//
// ArtifactImpl a2 = (ArtifactImpl) registry.resolve(workspace, artifact.getName());
// assertNotNull(a2);
//
// version.setAsDefaultVersion();
//
// assertEquals(2, a2.getVersions().size());
// EntryVersion activeVersion = a2.getDefaultOrLastVersion();
// assertEquals("0.1", activeVersion.getVersionLabel());
//
// activeVersion.delete();
//
// assertEquals(1, a2.getVersions().size());
//
// activeVersion = a2.getDefaultOrLastVersion();
// assertNotNull(activeVersion);
//
// assertTrue(((JcrVersion)activeVersion).isLatest());
//
// Collection<Item> artifacts = a2.getParent().getItems();
// boolean found = false;
// for (Item a : artifacts) {
// if (a.getId().equals(a2.getId())) {
// found = true;
// break;
// }
// }
// assertTrue(found);
// a2.delete();
}
//
// /**
// * Test for http://mule.mulesource.org/jira/browse/GALAXY-54 .
// */
// public void testActiveVersion() throws Exception
// {
// Collection<Item> workspaces = registry.getItems();
// assertEquals(1, workspaces.size());
//
// Item workspace = workspaces.iterator().next();
//
// String version1 = "This is version 1";
// String version2 = "This is version 2";
//
// ByteArrayInputStream bais = new ByteArrayInputStream(version1.getBytes("UTF-8"));
//
// NewItemResult ar = workspace.createArtifact("text/plain",
// "test.txt",
// "1",
// bais);
// assertNotNull(ar);
// assertTrue(ar.isApproved());
//
// bais = new ByteArrayInputStream(version2.getBytes());
//
// final ArtifactImpl artifact = (ArtifactImpl) ar.getItem();
//
// ar = artifact.newVersion(bais, "2");
// assertNotNull(ar);
// assertTrue(ar.isApproved());
//
// assertNotNull(ar.getEntryVersion().getPrevious());
//
// artifact.getVersion("1").setAsDefaultVersion();
//
// ArtifactImpl a = (ArtifactImpl) registry.resolve(workspace, "test.txt");
// assertNotNull(a);
// assertEquals("1", a.getDefaultOrLastVersion().getVersionLabel());
// assertEquals(version1, IOUtils.readStringFromStream(((ArtifactVersion)a.getDefaultOrLastVersion()).getStream()));
//
// ArtifactVersion artifactVersion = (ArtifactVersion) a.getVersion("2");
// assertEquals(version2, IOUtils.readStringFromStream(artifactVersion.getStream()));
// }
//
//
// public void testAddNonUnderstood() throws Exception {
// InputStream logProps = getResourceAsStream("/log4j.properties");
//
// Collection<Item> workspaces = registry.getItems();
// assertEquals(1, workspaces.size());
// Item workspace = workspaces.iterator().next();
//
// NewItemResult ar = workspace.createArtifact("text/plain",
// "log4j.properties",
// "0.1",
// logProps);
//
// assertNotNull(ar);
// }
}
| true | true | public void testAddWsdl() throws Exception {
Item av = importHelloWsdl();
assertNotNull(av.getId());
Phase p = av.getProperty(Registry.PRIMARY_LIFECYCLE);
assertNotNull(p);
p = av.getParent().getProperty(Registry.PRIMARY_LIFECYCLE);
assertNull(p);
Artifact artifact = av.getProperty("artifact");
assertNotNull(artifact);
assertEquals("application/xml", artifact.getContentType().toString());
assertNotNull(artifact.getDocumentType());
assertEquals("definitions", artifact.getDocumentType().getLocalPart());
// test properties
boolean testedTNS = false;
for (PropertyInfo next : av.getProperties()) {
if (next.getName().equals("wsdl.targetNamespace")) {
assertEquals("wsdl.targetNamespace", next.getName());
assertNotNull(next.getValue());
assertTrue(next.isLocked());
assertTrue(next.isVisible());
assertEquals("WSDL Target Namespace", next.getDescription());
testedTNS = true;
}
}
Calendar origUpdated = av.getUpdated();
assertNotNull(origUpdated);
assertTrue(testedTNS);
// This is odd, but otherwise the updates happen too fast, and the lastUpdated tstamp isn't changed
Thread.sleep(500);
av.setLocked("wsdl.targetNamespace", true);
av.setVisible("wsdl.targetNamespace", false);
PropertyInfo pi = av.getPropertyInfo("wsdl.targetNamespace");
assertTrue(pi.isLocked());
assertFalse(pi.isVisible());
Calendar update = av.getUpdated();
assertTrue(update.after(origUpdated));
av.setProperty("foo", "bar");
assertEquals("bar", av.getProperty("foo"));
// Test the version history
assertTrue(artifact.getData() instanceof Document);
assertNotNull(av.getAuthor());
assertEquals("Created", getPhase(av).getName());
Calendar created = av.getCreated();
assertTrue(created.getTime().getTime() > 0);
av.setProperty("foo", "bar");
assertEquals("bar", av.getProperty("foo"));
// Create another version
InputStream stream = artifact.getInputStream();
assertNotNull(stream);
stream.close();
// InputStream helloWsdl2 = getResourceAsStream("/wsdl/hello.wsdl");
//
// ar = artifact.newVersion(helloWsdl2, "0.2");
// assertTrue(waitForIndexing((ArtifactVersion)ar.getEntryVersion()));
// JcrVersion newVersion = (JcrVersion) ar.getEntryVersion();
// assertTrue(newVersion.isLatest());
// assertFalse(version.isLatest());
//
// assertSame(newVersion, ar.getItem().getDefaultOrLastVersion());
//
// versions = artifact.getVersions();
// assertEquals(2, versions.size());
//
// assertEquals("0.2", newVersion.getVersionLabel());
// assertEquals("Created", getPhase(newVersion).getName());
//
// stream = newVersion.getStream();
// assertNotNull(stream);
// assertTrue(stream.available() > 0);
// stream.close();
//
// assertNotNull(newVersion.getAuthor());
//
// newVersion.setProperty("foo2", "bar");
// assertEquals("bar", newVersion.getProperty("foo2"));
// assertNull(version.getProperty("foo2"));
//
// ArtifactImpl a2 = (ArtifactImpl) registry.resolve(workspace, artifact.getName());
// assertNotNull(a2);
//
// version.setAsDefaultVersion();
//
// assertEquals(2, a2.getVersions().size());
// EntryVersion activeVersion = a2.getDefaultOrLastVersion();
// assertEquals("0.1", activeVersion.getVersionLabel());
//
// activeVersion.delete();
//
// assertEquals(1, a2.getVersions().size());
//
// activeVersion = a2.getDefaultOrLastVersion();
// assertNotNull(activeVersion);
//
// assertTrue(((JcrVersion)activeVersion).isLatest());
//
// Collection<Item> artifacts = a2.getParent().getItems();
// boolean found = false;
// for (Item a : artifacts) {
// if (a.getId().equals(a2.getId())) {
// found = true;
// break;
// }
// }
// assertTrue(found);
// a2.delete();
}
| public void testAddWsdl() throws Exception {
Item av = importHelloWsdl();
assertNotNull(av.getId());
Phase p = av.getProperty(Registry.PRIMARY_LIFECYCLE);
assertNotNull(p);
p = av.getParent().getProperty(Registry.PRIMARY_LIFECYCLE);
assertNull(p);
Artifact artifact = av.getProperty("artifact");
assertNotNull(artifact);
assertEquals("application/xml", artifact.getContentType().toString());
assertNotNull(artifact.getDocumentType());
assertEquals("definitions", artifact.getDocumentType().getLocalPart());
// test properties
boolean testedTNS = false;
for (PropertyInfo next : av.getProperties()) {
if (next.getName().equals("wsdl.targetNamespace")) {
assertEquals("wsdl.targetNamespace", next.getName());
assertNotNull(next.getValue());
assertTrue(next.isLocked());
assertTrue(next.isVisible());
assertEquals("WSDL Target Namespace", next.getDescription());
testedTNS = true;
}
}
Calendar origUpdated = av.getUpdated();
assertNotNull(origUpdated);
assertTrue(testedTNS);
// This is odd, but otherwise the updates happen too fast, and the lastUpdated tstamp isn't changed
Thread.sleep(500);
av.setLocked("wsdl.targetNamespace", true);
av.setVisible("wsdl.targetNamespace", false);
PropertyInfo pi = av.getPropertyInfo("wsdl.targetNamespace");
assertTrue(pi.isLocked());
assertFalse(pi.isVisible());
Calendar update = av.getUpdated();
assertTrue(update.after(origUpdated));
av.setProperty("foo", "bar");
assertEquals("bar", av.getProperty("foo"));
// Test the version history
final Object data = artifact.getData();
assertTrue(data instanceof Document);
assertNotNull(av.getAuthor());
assertEquals("Created", getPhase(av).getName());
Calendar created = av.getCreated();
assertTrue(created.getTime().getTime() > 0);
av.setProperty("foo", "bar");
assertEquals("bar", av.getProperty("foo"));
// Create another version
InputStream stream = artifact.getInputStream();
assertNotNull(stream);
stream.close();
// InputStream helloWsdl2 = getResourceAsStream("/wsdl/hello.wsdl");
//
// ar = artifact.newVersion(helloWsdl2, "0.2");
// assertTrue(waitForIndexing((ArtifactVersion)ar.getEntryVersion()));
// JcrVersion newVersion = (JcrVersion) ar.getEntryVersion();
// assertTrue(newVersion.isLatest());
// assertFalse(version.isLatest());
//
// assertSame(newVersion, ar.getItem().getDefaultOrLastVersion());
//
// versions = artifact.getVersions();
// assertEquals(2, versions.size());
//
// assertEquals("0.2", newVersion.getVersionLabel());
// assertEquals("Created", getPhase(newVersion).getName());
//
// stream = newVersion.getStream();
// assertNotNull(stream);
// assertTrue(stream.available() > 0);
// stream.close();
//
// assertNotNull(newVersion.getAuthor());
//
// newVersion.setProperty("foo2", "bar");
// assertEquals("bar", newVersion.getProperty("foo2"));
// assertNull(version.getProperty("foo2"));
//
// ArtifactImpl a2 = (ArtifactImpl) registry.resolve(workspace, artifact.getName());
// assertNotNull(a2);
//
// version.setAsDefaultVersion();
//
// assertEquals(2, a2.getVersions().size());
// EntryVersion activeVersion = a2.getDefaultOrLastVersion();
// assertEquals("0.1", activeVersion.getVersionLabel());
//
// activeVersion.delete();
//
// assertEquals(1, a2.getVersions().size());
//
// activeVersion = a2.getDefaultOrLastVersion();
// assertNotNull(activeVersion);
//
// assertTrue(((JcrVersion)activeVersion).isLatest());
//
// Collection<Item> artifacts = a2.getParent().getItems();
// boolean found = false;
// for (Item a : artifacts) {
// if (a.getId().equals(a2.getId())) {
// found = true;
// break;
// }
// }
// assertTrue(found);
// a2.delete();
}
|
diff --git a/Frontend/src/main/com/sk/frontend/web/controller/BonusPaymentController.java b/Frontend/src/main/com/sk/frontend/web/controller/BonusPaymentController.java
index c448495..fe14b81 100644
--- a/Frontend/src/main/com/sk/frontend/web/controller/BonusPaymentController.java
+++ b/Frontend/src/main/com/sk/frontend/web/controller/BonusPaymentController.java
@@ -1,34 +1,34 @@
package com.sk.frontend.web.controller;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import com.sk.service.payment.VPOSResponse;
import com.sk.service.payment.garanti.GarantiVPOSService;
@Controller
@RequestMapping("/queryBonus")
public class BonusPaymentController {
private GarantiVPOSService garantiVPOSService;
@Autowired
public BonusPaymentController(GarantiVPOSService garantiVPOSService) {
this.garantiVPOSService = garantiVPOSService;
}
@RequestMapping(method = RequestMethod.POST)
public ModelAndView query(@RequestParam("creditCardNumber") String creditCardNumber,HttpServletRequest request) {
ModelAndView mav = new ModelAndView("bonusQuery");
VPOSResponse vposResponse = garantiVPOSService.queryBonus(creditCardNumber);
- mav.addObject("abonus",vposResponse.getDetailMessage());
+ mav.addObject("bonus",vposResponse.getDetailMessage());
return mav;
}
}
| true | true | public ModelAndView query(@RequestParam("creditCardNumber") String creditCardNumber,HttpServletRequest request) {
ModelAndView mav = new ModelAndView("bonusQuery");
VPOSResponse vposResponse = garantiVPOSService.queryBonus(creditCardNumber);
mav.addObject("abonus",vposResponse.getDetailMessage());
return mav;
}
| public ModelAndView query(@RequestParam("creditCardNumber") String creditCardNumber,HttpServletRequest request) {
ModelAndView mav = new ModelAndView("bonusQuery");
VPOSResponse vposResponse = garantiVPOSService.queryBonus(creditCardNumber);
mav.addObject("bonus",vposResponse.getDetailMessage());
return mav;
}
|
diff --git a/src/pl/poznan/put/cs/bioserver/gui/MainWindow.java b/src/pl/poznan/put/cs/bioserver/gui/MainWindow.java
index 98ed7a8..aeb923f 100644
--- a/src/pl/poznan/put/cs/bioserver/gui/MainWindow.java
+++ b/src/pl/poznan/put/cs/bioserver/gui/MainWindow.java
@@ -1,1100 +1,1100 @@
package pl.poznan.put.cs.bioserver.gui;
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.ImageIcon;
import javax.swing.JCheckBoxMenuItem;
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 javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
import org.apache.commons.lang3.StringUtils;
import org.biojava.bio.structure.Chain;
import org.biojava.bio.structure.ResidueNumber;
import org.biojava.bio.structure.Structure;
import org.biojava.bio.structure.StructureException;
import org.biojava.bio.structure.StructureImpl;
import org.biojava.bio.structure.align.gui.jmol.JmolPanel;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.DefaultXYItemRenderer;
import org.jfree.data.xy.DefaultXYDataset;
import org.jmol.api.JmolViewer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import pl.poznan.put.cs.bioserver.alignment.AlignmentOutput;
import pl.poznan.put.cs.bioserver.alignment.OutputAlignSeq;
import pl.poznan.put.cs.bioserver.alignment.SequenceAligner;
import pl.poznan.put.cs.bioserver.alignment.StructureAligner;
import pl.poznan.put.cs.bioserver.comparison.ComparisonListener;
import pl.poznan.put.cs.bioserver.comparison.GlobalComparison;
import pl.poznan.put.cs.bioserver.comparison.MCQ;
import pl.poznan.put.cs.bioserver.comparison.RMSD;
import pl.poznan.put.cs.bioserver.comparison.TorsionLocalComparison;
import pl.poznan.put.cs.bioserver.helper.Helper;
import pl.poznan.put.cs.bioserver.helper.PdbManager;
import pl.poznan.put.cs.bioserver.torsion.AngleDifference;
import pl.poznan.put.cs.bioserver.visualisation.MDS;
import pl.poznan.put.cs.bioserver.visualisation.MDSPlot;
import com.csvreader.CsvWriter;
class MainWindow extends JFrame {
private static final String TITLE = "MCQ4Structures: computing similarity of 3D RNA / protein structures";
private static final long serialVersionUID = 1L;
private static final Logger LOGGER = LoggerFactory
.getLogger(MainWindow.class);
private static final char CSV_DELIMITER = ';';
private static final String CARD_GLOBAL = "CARD_GLOBAL";
private static final String CARD_LOCAL = "CARD_LOCAL";
private static final String CARD_ALIGN_SEQ = "CARD_ALIGN_SEQ";
private static final String CARD_ALIGN_STRUC = "CARD_ALIGN_STRUC";
private static Component getCurrentCard(JPanel panel) {
for (Component component : panel.getComponents()) {
if (component.isVisible()) {
return component;
}
}
return null;
}
private JFileChooser chooserSaveFile;
private PdbManagerDialog managerDialog;
private StructureSelectionDialog structureDialog;
private ChainSelectionDialog chainDialog;
private TorsionAnglesSelectionDialog torsionDialog;
private String[] resultGlobalNames;
private double[][] resultGlobalMatrix;
private Map<String, List<AngleDifference>> resultLocal;
private String resultAlignStruc;
private String resultAlignSeq;
public MainWindow() {
super();
chooserSaveFile = new JFileChooser();
managerDialog = PdbManagerDialog.getInstance(this);
managerDialog.setVisible(true);
structureDialog = StructureSelectionDialog.getInstance(this);
chainDialog = ChainSelectionDialog.getInstance(this);
torsionDialog = TorsionAnglesSelectionDialog.getInstance(this);
/*
* Create menu
*/
JMenuBar menuBar = new JMenuBar();
final JMenuItem itemOpen = new JMenuItem("Open structure(s)",
loadIcon("/toolbarButtonGraphics/general/Open16.gif"));
final JMenuItem itemSave = new JMenuItem("Save results",
loadIcon("/toolbarButtonGraphics/general/Save16.gif"));
itemSave.setEnabled(false);
final JCheckBoxMenuItem checkBoxManager = new JCheckBoxMenuItem(
"View structure manager", true);
final JMenuItem itemExit = new JMenuItem("Exit");
JMenu menu = new JMenu("File");
menu.setMnemonic(KeyEvent.VK_F);
menu.add(itemOpen);
menu.add(itemSave);
menu.addSeparator();
menu.add(checkBoxManager);
menu.addSeparator();
menu.add(itemExit);
menuBar.add(menu);
final JRadioButtonMenuItem radioGlobalMcq = new JRadioButtonMenuItem(
"Global MCQ", true);
final JRadioButtonMenuItem radioGlobalRmsd = new JRadioButtonMenuItem(
"Global RMSD", false);
final JRadioButtonMenuItem radioLocal = new JRadioButtonMenuItem(
"Local distances", false);
ButtonGroup group = new ButtonGroup();
group.add(radioGlobalMcq);
group.add(radioGlobalRmsd);
group.add(radioLocal);
final JMenuItem itemSelectTorsion = new JMenuItem(
"Select torsion angles");
itemSelectTorsion.setEnabled(false);
final JMenuItem itemSelectStructuresCompare = new JMenuItem(
"Select structures to compare");
final JMenuItem itemComputeDistances = new JMenuItem(
"Compute distance(s)");
itemComputeDistances.setEnabled(false);
final JMenuItem itemVisualise = new JMenuItem("Visualise results");
itemVisualise.setEnabled(false);
final JMenuItem itemCluster = new JMenuItem("Cluster results");
itemCluster.setEnabled(false);
menu = new JMenu("Distance measure");
menu.setMnemonic(KeyEvent.VK_D);
menu.add(new JLabel(" Select distance type:"));
menu.add(radioGlobalMcq);
menu.add(radioGlobalRmsd);
menu.add(radioLocal);
menu.addSeparator();
menu.add(itemSelectTorsion);
menu.add(itemSelectStructuresCompare);
menu.addSeparator();
menu.add(itemComputeDistances);
menu.add(itemVisualise);
menu.add(itemCluster);
menuBar.add(menu);
final JRadioButtonMenuItem radioAlignSeqGlobal = new JRadioButtonMenuItem(
"Global sequence alignment", true);
final JRadioButtonMenuItem radioAlignSeqLocal = new JRadioButtonMenuItem(
"Local sequence alignment", false);
final JRadioButtonMenuItem radioAlignStruc = new JRadioButtonMenuItem(
"3D structure alignment", false);
ButtonGroup groupAlign = new ButtonGroup();
groupAlign.add(radioAlignSeqGlobal);
groupAlign.add(radioAlignSeqLocal);
groupAlign.add(radioAlignStruc);
final JMenuItem itemSelectStructuresAlign = new JMenuItem(
"Select structures to align");
final JMenuItem itemComputeAlign = new JMenuItem("Compute alignment");
itemComputeAlign.setEnabled(false);
menu = new JMenu("Alignment");
menu.setMnemonic(KeyEvent.VK_A);
menu.add(new JLabel(" Select alignment type:"));
menu.add(radioAlignSeqGlobal);
menu.add(radioAlignSeqLocal);
menu.add(radioAlignStruc);
menu.addSeparator();
menu.add(itemSelectStructuresAlign);
menu.add(itemComputeAlign);
menuBar.add(menu);
JMenuItem itemGuide = new JMenuItem("Quick guide");
JMenuItem itemAbout = new JMenuItem("About");
menu = new JMenu("Help");
menu.setMnemonic(KeyEvent.VK_H);
menu.add(itemGuide);
menu.add(itemAbout);
menuBar.add(menu);
setJMenuBar(menuBar);
/*
* Create panel with global comparison results
*/
JPanel panel;
final JLabel labelInfoGlobal = new JLabel(
"Global comparison results: distance matrix");
final JTable tableMatrix = new JTable();
final JProgressBar progressBar = new JProgressBar();
progressBar.setStringPainted(true);
final JPanel panelResultsGlobal = new JPanel(new BorderLayout());
panel = new JPanel(new BorderLayout());
panel.add(labelInfoGlobal, BorderLayout.WEST);
panelResultsGlobal.add(panel, BorderLayout.NORTH);
panelResultsGlobal.add(new JScrollPane(tableMatrix),
BorderLayout.CENTER);
panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
panel.add(new JLabel("Progress in computing:"));
panel.add(progressBar);
/*
* Create panel with local comparison results
*/
final JLabel labelInfoLocal = new JLabel(
"Local comparison results: distance plot");
final JPanel panelLocalPlot = new JPanel(new GridLayout(1, 1));
final JPanel panelResultsLocal = new JPanel(new BorderLayout());
panel = new JPanel(new BorderLayout());
panel.add(labelInfoLocal, BorderLayout.WEST);
panelResultsLocal.add(panel, BorderLayout.NORTH);
panelResultsLocal.add(panelLocalPlot, BorderLayout.CENTER);
/*
* Create panel with sequence alignment
*/
final JLabel labelInfoAlignSeq = new JLabel(
"Sequence alignment results");
final JTextArea textAreaAlignSeq = new JTextArea();
textAreaAlignSeq.setEditable(false);
textAreaAlignSeq.setFont(new Font("Monospaced", Font.PLAIN, 20));
final JPanel panelResultsAlignSeq = new JPanel(new BorderLayout());
panel = new JPanel(new BorderLayout());
panel.add(labelInfoAlignSeq, BorderLayout.WEST);
panelResultsAlignSeq.add(panel, BorderLayout.NORTH);
panelResultsAlignSeq.add(new JScrollPane(textAreaAlignSeq),
BorderLayout.CENTER);
/*
* Create panel with structure alignment
*/
JPanel panelAlignStrucInfo = new JPanel(new GridBagLayout());
GridBagConstraints constraints = new GridBagConstraints();
constraints.gridx = 0;
constraints.gridy = 0;
constraints.weightx = 0.5;
panelAlignStrucInfo.add(new JLabel("Whole structures (Jmol view)"),
constraints);
constraints.gridx++;
constraints.weightx = 0;
final JLabel labelInfoAlignStruc = new JLabel(
"3D structure alignment results");
panelAlignStrucInfo.add(labelInfoAlignStruc, constraints);
constraints.gridx++;
constraints.weightx = 0.5;
panelAlignStrucInfo.add(new JLabel("Aligned fragments (Jmol view)"),
constraints);
final JmolPanel panelJmolLeft = new JmolPanel();
panelJmolLeft.executeCmd("background lightgrey; save state state_init");
final JmolPanel panelJmolRight = new JmolPanel();
panelJmolRight.executeCmd("background darkgray; save state state_init");
final JPanel panelResultsAlignStruc = new JPanel(new BorderLayout());
panelResultsAlignStruc.add(panelAlignStrucInfo, BorderLayout.NORTH);
panel = new JPanel(new GridLayout(1, 2));
panel.add(panelJmolLeft);
panel.add(panelJmolRight);
panelResultsAlignStruc.add(panel, BorderLayout.CENTER);
/*
* Create card layout
*/
final CardLayout layoutCards = new CardLayout();
final JPanel panelCards = new JPanel();
panelCards.setLayout(layoutCards);
panelCards.add(new JPanel());
panelCards.add(panelResultsGlobal, MainWindow.CARD_GLOBAL);
panelCards.add(panelResultsLocal, MainWindow.CARD_LOCAL);
panelCards.add(panelResultsAlignSeq, MainWindow.CARD_ALIGN_SEQ);
panelCards.add(panelResultsAlignStruc, MainWindow.CARD_ALIGN_STRUC);
setLayout(new BorderLayout());
add(panelCards, BorderLayout.CENTER);
/*
* Set window properties
*/
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle(MainWindow.TITLE);
Toolkit toolkit = Toolkit.getDefaultToolkit();
Dimension size = toolkit.getScreenSize();
setSize(size.width * 3 / 4, size.height * 3 / 4);
setLocation(size.width / 8, size.height / 8);
/*
* Set action listeners
*/
managerDialog.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
super.windowClosing(e);
checkBoxManager.setSelected(false);
}
});
itemOpen.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
File[] files = PdbFileChooser.getSelectedFiles(MainWindow.this);
for (File f : files) {
if (PdbManager.loadStructure(f) != null) {
PdbManagerDialog.MODEL.addElement(f);
}
}
}
});
itemSave.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Component current = MainWindow.getCurrentCard(panelCards);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-DD-HH-mm");
Date now = new Date();
File proposedName = null;
if (current.equals(panelResultsGlobal)) {
proposedName = new File(sdf.format(now) + "-global.csv");
} else {
StringBuilder builder = new StringBuilder();
builder.append(PdbManager
.getStructureName(chainDialog.selectedStructures[0]));
builder.append('-');
builder.append(PdbManager
.getStructureName(chainDialog.selectedStructures[1]));
if (current.equals(panelResultsLocal)) {
proposedName = new File(sdf.format(now) + "-local-"
+ builder.toString() + ".csv");
} else if (current.equals(panelResultsAlignSeq)) {
proposedName = new File(sdf.format(now) + "-alignseq-"
+ builder.toString() + ".txt");
} else { // current.equals(panelResultsAlignStruc)
proposedName = new File(sdf.format(now)
+ "-alignstruc-" + builder.toString() + ".pdb");
}
}
chooserSaveFile.setSelectedFile(proposedName);
int chosenOption = chooserSaveFile
.showSaveDialog(MainWindow.this);
if (chosenOption != JFileChooser.APPROVE_OPTION) {
return;
}
if (current.equals(panelResultsGlobal)) {
saveResultsGlobalComparison(chooserSaveFile
.getSelectedFile());
} else if (current.equals(panelResultsLocal)) {
saveResultsLocalComparison(chooserSaveFile
.getSelectedFile());
} else if (current.equals(panelResultsAlignSeq)) {
try (FileOutputStream stream = new FileOutputStream(
chooserSaveFile.getSelectedFile())) {
// TODO: output structure names
stream.write(resultAlignSeq.getBytes("UTF-8"));
} catch (IOException e1) {
MainWindow.LOGGER.error(
"Failed to save aligned sequences", e1);
JOptionPane.showMessageDialog(MainWindow.this,
e1.getMessage(), "Error",
JOptionPane.ERROR_MESSAGE);
}
} else { // current.equals(panelResultsAlignStruc)
try (FileOutputStream stream = new FileOutputStream(
chooserSaveFile.getSelectedFile())) {
stream.write(resultAlignStruc.getBytes("UTF-8"));
} catch (IOException e1) {
MainWindow.LOGGER.error(
"Failed to save PDB of aligned structures", e1);
JOptionPane.showMessageDialog(MainWindow.this,
e1.getMessage(), "Error",
JOptionPane.ERROR_MESSAGE);
}
}
}
});
checkBoxManager.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
managerDialog.setVisible(checkBoxManager.isSelected());
}
});
itemExit.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
dispatchEvent(new WindowEvent(MainWindow.this,
WindowEvent.WINDOW_CLOSING));
}
});
ActionListener radioActionListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
Object source = arg0.getSource();
itemSelectTorsion.setEnabled(source.equals(radioLocal));
}
};
radioGlobalMcq.addActionListener(radioActionListener);
radioGlobalRmsd.addActionListener(radioActionListener);
radioLocal.addActionListener(radioActionListener);
itemSelectTorsion.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
torsionDialog.setVisible(true);
}
});
ActionListener selectActionListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
- if (source.equals(itemComputeDistances)
+ if (source.equals(itemSelectStructuresCompare)
&& (radioGlobalMcq.isSelected() || radioGlobalRmsd
.isSelected())) {
/*
* Add new structures to the "all" section of structures
* selection dialog
*/
Enumeration<File> elements = PdbManagerDialog.MODEL
.elements();
while (elements.hasMoreElements()) {
File path = elements.nextElement();
if (!structureDialog.modelAll.contains(path)
&& !structureDialog.modelSelected
.contains(path)) {
structureDialog.modelAll.addElement(path);
}
}
/*
* Remove from "all" section these structures, that were
* removed in PDB manager dialog
*/
elements = structureDialog.modelAll.elements();
while (elements.hasMoreElements()) {
File path = elements.nextElement();
if (PdbManager.getStructure(path) == null) {
structureDialog.modelAll.removeElement(path);
}
}
/*
* Remove from "selected" section these structures, that
* were removed in PDB manager dialog
*/
elements = structureDialog.modelSelected.elements();
while (elements.hasMoreElements()) {
File path = elements.nextElement();
if (PdbManager.getStructure(path) == null) {
structureDialog.modelSelected.removeElement(path);
}
}
/*
* Show dialog
*/
structureDialog.setVisible(true);
if (structureDialog.chosenOption == StructureSelectionDialog.OK
&& structureDialog.selectedStructures != null) {
if (structureDialog.selectedStructures.size() < 2) {
JOptionPane
.showMessageDialog(
MainWindow.this,
"At "
+ "least two structures must be selected to "
+ "compute global distance",
"Information",
JOptionPane.INFORMATION_MESSAGE);
return;
}
tableMatrix.setModel(new MatrixTableModel(
new String[0], new double[0][]));
layoutCards.show(panelCards, MainWindow.CARD_GLOBAL);
itemSave.setEnabled(false);
radioGlobalMcq.setEnabled(true);
radioGlobalRmsd.setEnabled(true);
itemComputeDistances.setEnabled(true);
}
} else {
chainDialog.modelLeft.removeAllElements();
chainDialog.modelRight.removeAllElements();
Enumeration<File> elements = PdbManagerDialog.MODEL
.elements();
while (elements.hasMoreElements()) {
File path = elements.nextElement();
chainDialog.modelLeft.addElement(path);
chainDialog.modelRight.addElement(path);
}
chainDialog.setVisible(true);
if (chainDialog.chosenOption == ChainSelectionDialog.OK
&& chainDialog.selectedStructures != null
&& chainDialog.selectedChains != null) {
for (int i = 0; i < 2; i++) {
if (chainDialog.selectedChains[i].length == 0) {
String message = "No chains specified for structure: "
+ chainDialog.selectedStructures[i];
JOptionPane.showMessageDialog(MainWindow.this,
message, "Information",
JOptionPane.INFORMATION_MESSAGE);
chainDialog.selectedStructures = null;
chainDialog.selectedChains = null;
return;
}
}
if (source.equals(itemSelectStructuresCompare)) {
panelLocalPlot.removeAll();
panelLocalPlot.revalidate();
layoutCards.show(panelCards, MainWindow.CARD_LOCAL);
itemSelectTorsion.setEnabled(true);
itemComputeAlign.setEnabled(false);
} else if (radioAlignSeqGlobal.isSelected()
|| radioAlignSeqLocal.isSelected()) {
if (chainDialog.selectedChains[0].length != 1
|| chainDialog.selectedChains[1].length != 1) {
JOptionPane.showMessageDialog(MainWindow.this,
"A single chain should be "
+ "selected from each "
+ "structure in "
+ "sequence alignment.",
"Information",
JOptionPane.INFORMATION_MESSAGE);
chainDialog.selectedStructures = null;
chainDialog.selectedChains = null;
return;
}
textAreaAlignSeq.setText("");
layoutCards.show(panelCards,
MainWindow.CARD_ALIGN_SEQ);
itemSelectTorsion.setEnabled(false);
itemComputeAlign.setEnabled(true);
} else { // source.equals(itemSelectChainsAlignStruc)
panelJmolLeft.executeCmd("restore state "
+ "state_init");
panelJmolRight.executeCmd("restore state "
+ "state_init");
layoutCards.show(panelCards,
MainWindow.CARD_ALIGN_STRUC);
itemSelectTorsion.setEnabled(false);
itemComputeAlign.setEnabled(true);
}
}
}
}
};
itemSelectStructuresCompare.addActionListener(selectActionListener);
itemSelectStructuresAlign.addActionListener(selectActionListener);
itemComputeDistances.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (radioGlobalMcq.isSelected() || radioGlobalRmsd.isSelected()) {
final GlobalComparison comparison;
if (radioGlobalMcq.isSelected()) {
comparison = new MCQ();
} else { // radioRmsd.isSelected() == true
comparison = new RMSD();
}
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
Structure[] structures = PdbManager
.getSelectedStructures(structureDialog.selectedStructures);
resultGlobalNames = PdbManager
.getSelectedStructuresNames(structureDialog.selectedStructures);
resultGlobalMatrix = comparison.compare(structures,
new ComparisonListener() {
@Override
public void stateChanged(long all,
long completed) {
progressBar.setMaximum((int) all);
progressBar
.setValue((int) completed);
}
});
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
MatrixTableModel model = new MatrixTableModel(
resultGlobalNames,
resultGlobalMatrix);
tableMatrix.setModel(model);
itemSave.setEnabled(true);
itemSave.setText("Save results (CSV)");
itemCluster.setEnabled(true);
itemVisualise.setEnabled(true);
labelInfoGlobal.setText("Global comparison "
+ "results: distance matrix for "
+ (radioGlobalMcq.isSelected() ? "MCQ"
: "RMSD"));
}
});
}
});
thread.start();
} else {
layoutCards.show(panelCards, MainWindow.CARD_LOCAL);
final Structure[] structures = new Structure[2];
for (int i = 0; i < 2; i++) {
structures[i] = new StructureImpl();
// FIXME: NPE after hitting Cancel on chain selection
structures[i].setChains(Arrays
.asList(chainDialog.selectedChains[i]));
}
try {
resultLocal = TorsionLocalComparison.compare(
structures[0], structures[1], false);
} catch (StructureException e1) {
JOptionPane.showMessageDialog(MainWindow.this,
e1.getMessage(), "Error",
JOptionPane.ERROR_MESSAGE);
return;
}
Set<ResidueNumber> set = new HashSet<>();
for (String angle : torsionDialog.selectedNames) {
if (!resultLocal.containsKey(angle)) {
continue;
}
for (AngleDifference ad : resultLocal.get(angle)) {
set.add(ad.getResidue());
}
}
List<ResidueNumber> list = new ArrayList<>(set);
Collections.sort(list);
DefaultXYDataset dataset = new DefaultXYDataset();
for (String angle : torsionDialog.selectedNames) {
if (!resultLocal.containsKey(angle)) {
continue;
}
List<AngleDifference> diffs = resultLocal.get(angle);
Collections.sort(diffs);
double[] x = new double[diffs.size()];
double[] y = new double[diffs.size()];
for (int i = 0; i < diffs.size(); i++) {
AngleDifference ad = diffs.get(i);
x[i] = list.indexOf(ad.getResidue());
y[i] = ad.getDifference();
}
dataset.addSeries(angle, new double[][] { x, y });
}
NumberAxis xAxis = new TorsionAxis(resultLocal);
xAxis.setLabel("Residue");
NumberAxis yAxis = new NumberAxis();
yAxis.setAutoRange(false);
yAxis.setRange(0, Math.PI);
yAxis.setLabel("Distance [rad]");
XYPlot plot = new XYPlot(dataset, xAxis, yAxis,
new DefaultXYItemRenderer());
panelLocalPlot.removeAll();
panelLocalPlot.add(new ChartPanel(new JFreeChart(plot)));
panelLocalPlot.revalidate();
itemSave.setEnabled(true);
itemSave.setText("Save results (CSV)");
File[] pdbs = new File[] {
chainDialog.selectedStructures[0],
chainDialog.selectedStructures[1] };
String[] names = new String[] {
PdbManager.getStructureName(pdbs[0]),
PdbManager.getStructureName(pdbs[1]) };
labelInfoLocal
.setText("Local comparison results: distance "
+ "plot for " + names[0] + " and "
+ names[1]);
}
}
});
itemVisualise.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
MatrixTableModel model = (MatrixTableModel) tableMatrix
.getModel();
String[] names = model.getNames();
double[][] values = model.getValues();
for (double[] value : values) {
for (double element : value) {
if (Double.isNaN(element)) {
JOptionPane.showMessageDialog(MainWindow.this, ""
+ "Results cannot be visualized. Some "
+ "structures could not be compared.",
"Error", JOptionPane.ERROR_MESSAGE);
return;
}
}
}
double[][] mds = MDS.multidimensionalScaling(values, 2);
if (mds == null) {
JOptionPane.showMessageDialog(MainWindow.this, "Cannot "
+ "visualise specified structures in 2D space",
"Warning", JOptionPane.WARNING_MESSAGE);
return;
}
MDSPlot plot = new MDSPlot(mds, names);
plot.setVisible(true);
}
});
itemCluster.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
MatrixTableModel model = (MatrixTableModel) tableMatrix
.getModel();
String[] names = model.getNames();
double[][] values = model.getValues();
for (double[] value : values) {
for (double element : value) {
if (Double.isNaN(element)) {
JOptionPane.showMessageDialog(MainWindow.this, ""
+ "Results cannot be visualized. Some "
+ "structures could not be compared.",
"Error", JOptionPane.ERROR_MESSAGE);
return;
}
}
}
ClusteringDialog dialogClustering = new ClusteringDialog(names,
values);
dialogClustering.setVisible(true);
}
});
itemComputeAlign.addActionListener(new ActionListener() {
private Thread thread;
@Override
public void actionPerformed(ActionEvent e) {
if (radioAlignSeqGlobal.isSelected()
|| radioAlignSeqLocal.isSelected()) {
layoutCards.show(panelCards, MainWindow.CARD_ALIGN_SEQ);
Chain chains[] = new Chain[] {
chainDialog.selectedChains[0][0],
chainDialog.selectedChains[1][0] };
boolean isRNA = Helper.isNucleicAcid(chains[0]);
if (isRNA != Helper.isNucleicAcid(chains[1])) {
String message = "Cannot align structures: different molecular types";
MainWindow.LOGGER.error(message);
JOptionPane.showMessageDialog(null, message, "Error",
JOptionPane.ERROR_MESSAGE);
return;
}
OutputAlignSeq alignment = SequenceAligner.align(chains[0],
chains[1], radioAlignSeqGlobal.isSelected());
resultAlignSeq = alignment.toString();
textAreaAlignSeq.setText(resultAlignSeq);
itemSave.setEnabled(true);
itemSave.setText("Save results (TXT)");
File[] pdbs = new File[] {
chainDialog.selectedStructures[0],
chainDialog.selectedStructures[1] };
String[] names = new String[] {
PdbManager.getStructureName(pdbs[0]),
PdbManager.getStructureName(pdbs[1]) };
labelInfoAlignSeq.setText("Sequence alignment results for "
+ names[0] + " and " + names[1]);
} else {
if (thread != null && thread.isAlive()) {
JOptionPane.showMessageDialog(null,
"3D structure alignment computation has not "
+ "finished yet!", "Information",
JOptionPane.INFORMATION_MESSAGE);
return;
}
layoutCards.show(panelCards, MainWindow.CARD_ALIGN_STRUC);
final Structure[] structures = new Structure[2];
for (int i = 0; i < 2; i++) {
structures[i] = new StructureImpl();
structures[i].setChains(Arrays
.asList(chainDialog.selectedChains[i]));
}
boolean isRNA = Helper.isNucleicAcid(structures[0]);
if (isRNA != Helper.isNucleicAcid(structures[1])) {
String message = "Cannot align structures: different molecular types";
MainWindow.LOGGER.error(message);
JOptionPane.showMessageDialog(null, message, "Error",
JOptionPane.ERROR_MESSAGE);
return;
}
labelInfoAlignStruc.setText("Processing");
final Timer timer = new Timer(250, new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
String text = labelInfoAlignStruc.getText();
int count = StringUtils.countMatches(text, ".");
if (count < 5) {
labelInfoAlignStruc.setText(text + ".");
} else {
labelInfoAlignStruc.setText("Processing");
}
}
});
timer.start();
thread = new Thread(new Runnable() {
@Override
public void run() {
try {
Helper.normalizeAtomNames(structures[0]);
Helper.normalizeAtomNames(structures[1]);
AlignmentOutput output = StructureAligner
.align(structures[0], structures[1]);
final Structure[] aligned = output
.getStructures();
SwingUtilities.invokeLater(new Runnable() {
private static final String JMOL_SCRIPT = "frame 0.0; "
+ "cartoon only; "
+ "select model=1.1; color green; "
+ "select model=1.2; color red; ";
@Override
public void run() {
StringBuilder builder = new StringBuilder();
builder.append("MODEL 1 \n");
builder.append(aligned[0].toPDB());
builder.append("ENDMDL \n");
builder.append("MODEL 2 \n");
builder.append(aligned[1].toPDB());
builder.append("ENDMDL \n");
resultAlignStruc = builder.toString();
JmolViewer viewer = panelJmolLeft
.getViewer();
viewer.openStringInline(builder
.toString());
panelJmolLeft.executeCmd(JMOL_SCRIPT);
builder = new StringBuilder();
builder.append("MODEL 1 \n");
builder.append(aligned[2].toPDB());
builder.append("ENDMDL \n");
builder.append("MODEL 2 \n");
builder.append(aligned[3].toPDB());
builder.append("ENDMDL \n");
viewer = panelJmolRight.getViewer();
viewer.openStringInline(builder
.toString());
panelJmolRight.executeCmd(JMOL_SCRIPT);
itemSave.setEnabled(true);
itemSave.setText("Save results (PDB)");
}
});
} catch (StructureException e1) {
MainWindow.LOGGER.error(
"Failed to align structures", e1);
JOptionPane.showMessageDialog(getParent(),
e1.getMessage(), "Error",
JOptionPane.ERROR_MESSAGE);
} finally {
timer.stop();
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
File[] pdbs = new File[] {
chainDialog.selectedStructures[0],
chainDialog.selectedStructures[1] };
String[] names = new String[] {
PdbManager
.getStructureName(pdbs[0]),
PdbManager
.getStructureName(pdbs[1]) };
labelInfoAlignStruc
.setText("3D structure "
+ "alignments results for "
+ names[0] + " and "
+ names[1]);
}
});
}
}
});
thread.start();
}
}
});
itemGuide.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
QuickGuideDialog dialog = new QuickGuideDialog(MainWindow.this);
dialog.setVisible(true);
}
});
itemAbout.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
AboutDialog dialog = new AboutDialog(MainWindow.this);
dialog.setVisible(true);
}
});
}
private ImageIcon loadIcon(String name) {
URL resource = getClass().getResource(name);
if (resource == null) {
MainWindow.LOGGER.error("Failed to load icon: " + name);
return null;
}
return new ImageIcon(resource);
}
private void saveResultsGlobalComparison(File outputFile) {
try (FileOutputStream stream = new FileOutputStream(outputFile)) {
CsvWriter writer = new CsvWriter(stream, MainWindow.CSV_DELIMITER,
Charset.forName("UTF-8"));
/*
* Print header
*/
int length = resultGlobalNames.length;
writer.write("");
for (int i = 0; i < length; i++) {
writer.write(resultGlobalNames[i]);
}
writer.endRecord();
/*
* Print each value in the matrix
*/
for (int i = 0; i < length; i++) {
writer.write(resultGlobalNames[i]);
for (int j = 0; j < length; j++) {
writer.write(Double.toString(resultGlobalMatrix[i][j]));
}
writer.endRecord();
}
writer.close();
} catch (IOException e) {
MainWindow.LOGGER.error(
"Failed to save results from global comparison", e);
JOptionPane.showMessageDialog(this, e.getMessage(), "Error",
JOptionPane.ERROR_MESSAGE);
}
}
private void saveResultsLocalComparison(File outputFile) {
/*
* Reverse information: [angleName -> angleValue(residue)] into:
* [residue -> angleValue(angleName)]
*/
SortedMap<String, Map<String, Double>> map = new TreeMap<>();
Set<String> setAngleNames = new LinkedHashSet<>();
for (Entry<String, List<AngleDifference>> pair : resultLocal.entrySet()) {
String angleName = pair.getKey();
boolean isAnyNotNaN = false;
for (AngleDifference ad : pair.getValue()) {
ResidueNumber residue = ad.getResidue();
String residueName = String.format("%s:%03d",
residue.getChainId(), residue.getSeqNum());
if (!map.containsKey(residueName)) {
map.put(residueName, new LinkedHashMap<String, Double>());
}
Map<String, Double> angleValues = map.get(residueName);
double difference = ad.getDifference();
angleValues.put(angleName, difference);
if (!Double.isNaN(difference)) {
isAnyNotNaN = true;
}
}
if (isAnyNotNaN) {
setAngleNames.add(angleName);
}
}
try (FileOutputStream stream = new FileOutputStream(outputFile)) {
CsvWriter writer = new CsvWriter(stream, MainWindow.CSV_DELIMITER,
Charset.forName("UTF-8"));
/*
* Write header
*/
writer.write("");
for (String angleName : setAngleNames) {
writer.write(angleName);
}
writer.endRecord();
/*
* Write a record for each residue
*/
for (String residueName : map.keySet()) {
writer.write(residueName);
Map<String, Double> mapAngles = map.get(residueName);
for (String angleName : setAngleNames) {
if (mapAngles.containsKey(angleName)) {
String angleValue = Double.toString(mapAngles
.get(angleName));
writer.write(angleValue);
} else {
writer.write("");
}
}
writer.endRecord();
}
writer.close();
} catch (IOException e) {
MainWindow.LOGGER.error(
"Failed to save results from local comparison", e);
JOptionPane.showMessageDialog(this, e.getMessage(), "Error",
JOptionPane.ERROR_MESSAGE);
}
}
}
| true | true | public MainWindow() {
super();
chooserSaveFile = new JFileChooser();
managerDialog = PdbManagerDialog.getInstance(this);
managerDialog.setVisible(true);
structureDialog = StructureSelectionDialog.getInstance(this);
chainDialog = ChainSelectionDialog.getInstance(this);
torsionDialog = TorsionAnglesSelectionDialog.getInstance(this);
/*
* Create menu
*/
JMenuBar menuBar = new JMenuBar();
final JMenuItem itemOpen = new JMenuItem("Open structure(s)",
loadIcon("/toolbarButtonGraphics/general/Open16.gif"));
final JMenuItem itemSave = new JMenuItem("Save results",
loadIcon("/toolbarButtonGraphics/general/Save16.gif"));
itemSave.setEnabled(false);
final JCheckBoxMenuItem checkBoxManager = new JCheckBoxMenuItem(
"View structure manager", true);
final JMenuItem itemExit = new JMenuItem("Exit");
JMenu menu = new JMenu("File");
menu.setMnemonic(KeyEvent.VK_F);
menu.add(itemOpen);
menu.add(itemSave);
menu.addSeparator();
menu.add(checkBoxManager);
menu.addSeparator();
menu.add(itemExit);
menuBar.add(menu);
final JRadioButtonMenuItem radioGlobalMcq = new JRadioButtonMenuItem(
"Global MCQ", true);
final JRadioButtonMenuItem radioGlobalRmsd = new JRadioButtonMenuItem(
"Global RMSD", false);
final JRadioButtonMenuItem radioLocal = new JRadioButtonMenuItem(
"Local distances", false);
ButtonGroup group = new ButtonGroup();
group.add(radioGlobalMcq);
group.add(radioGlobalRmsd);
group.add(radioLocal);
final JMenuItem itemSelectTorsion = new JMenuItem(
"Select torsion angles");
itemSelectTorsion.setEnabled(false);
final JMenuItem itemSelectStructuresCompare = new JMenuItem(
"Select structures to compare");
final JMenuItem itemComputeDistances = new JMenuItem(
"Compute distance(s)");
itemComputeDistances.setEnabled(false);
final JMenuItem itemVisualise = new JMenuItem("Visualise results");
itemVisualise.setEnabled(false);
final JMenuItem itemCluster = new JMenuItem("Cluster results");
itemCluster.setEnabled(false);
menu = new JMenu("Distance measure");
menu.setMnemonic(KeyEvent.VK_D);
menu.add(new JLabel(" Select distance type:"));
menu.add(radioGlobalMcq);
menu.add(radioGlobalRmsd);
menu.add(radioLocal);
menu.addSeparator();
menu.add(itemSelectTorsion);
menu.add(itemSelectStructuresCompare);
menu.addSeparator();
menu.add(itemComputeDistances);
menu.add(itemVisualise);
menu.add(itemCluster);
menuBar.add(menu);
final JRadioButtonMenuItem radioAlignSeqGlobal = new JRadioButtonMenuItem(
"Global sequence alignment", true);
final JRadioButtonMenuItem radioAlignSeqLocal = new JRadioButtonMenuItem(
"Local sequence alignment", false);
final JRadioButtonMenuItem radioAlignStruc = new JRadioButtonMenuItem(
"3D structure alignment", false);
ButtonGroup groupAlign = new ButtonGroup();
groupAlign.add(radioAlignSeqGlobal);
groupAlign.add(radioAlignSeqLocal);
groupAlign.add(radioAlignStruc);
final JMenuItem itemSelectStructuresAlign = new JMenuItem(
"Select structures to align");
final JMenuItem itemComputeAlign = new JMenuItem("Compute alignment");
itemComputeAlign.setEnabled(false);
menu = new JMenu("Alignment");
menu.setMnemonic(KeyEvent.VK_A);
menu.add(new JLabel(" Select alignment type:"));
menu.add(radioAlignSeqGlobal);
menu.add(radioAlignSeqLocal);
menu.add(radioAlignStruc);
menu.addSeparator();
menu.add(itemSelectStructuresAlign);
menu.add(itemComputeAlign);
menuBar.add(menu);
JMenuItem itemGuide = new JMenuItem("Quick guide");
JMenuItem itemAbout = new JMenuItem("About");
menu = new JMenu("Help");
menu.setMnemonic(KeyEvent.VK_H);
menu.add(itemGuide);
menu.add(itemAbout);
menuBar.add(menu);
setJMenuBar(menuBar);
/*
* Create panel with global comparison results
*/
JPanel panel;
final JLabel labelInfoGlobal = new JLabel(
"Global comparison results: distance matrix");
final JTable tableMatrix = new JTable();
final JProgressBar progressBar = new JProgressBar();
progressBar.setStringPainted(true);
final JPanel panelResultsGlobal = new JPanel(new BorderLayout());
panel = new JPanel(new BorderLayout());
panel.add(labelInfoGlobal, BorderLayout.WEST);
panelResultsGlobal.add(panel, BorderLayout.NORTH);
panelResultsGlobal.add(new JScrollPane(tableMatrix),
BorderLayout.CENTER);
panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
panel.add(new JLabel("Progress in computing:"));
panel.add(progressBar);
/*
* Create panel with local comparison results
*/
final JLabel labelInfoLocal = new JLabel(
"Local comparison results: distance plot");
final JPanel panelLocalPlot = new JPanel(new GridLayout(1, 1));
final JPanel panelResultsLocal = new JPanel(new BorderLayout());
panel = new JPanel(new BorderLayout());
panel.add(labelInfoLocal, BorderLayout.WEST);
panelResultsLocal.add(panel, BorderLayout.NORTH);
panelResultsLocal.add(panelLocalPlot, BorderLayout.CENTER);
/*
* Create panel with sequence alignment
*/
final JLabel labelInfoAlignSeq = new JLabel(
"Sequence alignment results");
final JTextArea textAreaAlignSeq = new JTextArea();
textAreaAlignSeq.setEditable(false);
textAreaAlignSeq.setFont(new Font("Monospaced", Font.PLAIN, 20));
final JPanel panelResultsAlignSeq = new JPanel(new BorderLayout());
panel = new JPanel(new BorderLayout());
panel.add(labelInfoAlignSeq, BorderLayout.WEST);
panelResultsAlignSeq.add(panel, BorderLayout.NORTH);
panelResultsAlignSeq.add(new JScrollPane(textAreaAlignSeq),
BorderLayout.CENTER);
/*
* Create panel with structure alignment
*/
JPanel panelAlignStrucInfo = new JPanel(new GridBagLayout());
GridBagConstraints constraints = new GridBagConstraints();
constraints.gridx = 0;
constraints.gridy = 0;
constraints.weightx = 0.5;
panelAlignStrucInfo.add(new JLabel("Whole structures (Jmol view)"),
constraints);
constraints.gridx++;
constraints.weightx = 0;
final JLabel labelInfoAlignStruc = new JLabel(
"3D structure alignment results");
panelAlignStrucInfo.add(labelInfoAlignStruc, constraints);
constraints.gridx++;
constraints.weightx = 0.5;
panelAlignStrucInfo.add(new JLabel("Aligned fragments (Jmol view)"),
constraints);
final JmolPanel panelJmolLeft = new JmolPanel();
panelJmolLeft.executeCmd("background lightgrey; save state state_init");
final JmolPanel panelJmolRight = new JmolPanel();
panelJmolRight.executeCmd("background darkgray; save state state_init");
final JPanel panelResultsAlignStruc = new JPanel(new BorderLayout());
panelResultsAlignStruc.add(panelAlignStrucInfo, BorderLayout.NORTH);
panel = new JPanel(new GridLayout(1, 2));
panel.add(panelJmolLeft);
panel.add(panelJmolRight);
panelResultsAlignStruc.add(panel, BorderLayout.CENTER);
/*
* Create card layout
*/
final CardLayout layoutCards = new CardLayout();
final JPanel panelCards = new JPanel();
panelCards.setLayout(layoutCards);
panelCards.add(new JPanel());
panelCards.add(panelResultsGlobal, MainWindow.CARD_GLOBAL);
panelCards.add(panelResultsLocal, MainWindow.CARD_LOCAL);
panelCards.add(panelResultsAlignSeq, MainWindow.CARD_ALIGN_SEQ);
panelCards.add(panelResultsAlignStruc, MainWindow.CARD_ALIGN_STRUC);
setLayout(new BorderLayout());
add(panelCards, BorderLayout.CENTER);
/*
* Set window properties
*/
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle(MainWindow.TITLE);
Toolkit toolkit = Toolkit.getDefaultToolkit();
Dimension size = toolkit.getScreenSize();
setSize(size.width * 3 / 4, size.height * 3 / 4);
setLocation(size.width / 8, size.height / 8);
/*
* Set action listeners
*/
managerDialog.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
super.windowClosing(e);
checkBoxManager.setSelected(false);
}
});
itemOpen.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
File[] files = PdbFileChooser.getSelectedFiles(MainWindow.this);
for (File f : files) {
if (PdbManager.loadStructure(f) != null) {
PdbManagerDialog.MODEL.addElement(f);
}
}
}
});
itemSave.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Component current = MainWindow.getCurrentCard(panelCards);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-DD-HH-mm");
Date now = new Date();
File proposedName = null;
if (current.equals(panelResultsGlobal)) {
proposedName = new File(sdf.format(now) + "-global.csv");
} else {
StringBuilder builder = new StringBuilder();
builder.append(PdbManager
.getStructureName(chainDialog.selectedStructures[0]));
builder.append('-');
builder.append(PdbManager
.getStructureName(chainDialog.selectedStructures[1]));
if (current.equals(panelResultsLocal)) {
proposedName = new File(sdf.format(now) + "-local-"
+ builder.toString() + ".csv");
} else if (current.equals(panelResultsAlignSeq)) {
proposedName = new File(sdf.format(now) + "-alignseq-"
+ builder.toString() + ".txt");
} else { // current.equals(panelResultsAlignStruc)
proposedName = new File(sdf.format(now)
+ "-alignstruc-" + builder.toString() + ".pdb");
}
}
chooserSaveFile.setSelectedFile(proposedName);
int chosenOption = chooserSaveFile
.showSaveDialog(MainWindow.this);
if (chosenOption != JFileChooser.APPROVE_OPTION) {
return;
}
if (current.equals(panelResultsGlobal)) {
saveResultsGlobalComparison(chooserSaveFile
.getSelectedFile());
} else if (current.equals(panelResultsLocal)) {
saveResultsLocalComparison(chooserSaveFile
.getSelectedFile());
} else if (current.equals(panelResultsAlignSeq)) {
try (FileOutputStream stream = new FileOutputStream(
chooserSaveFile.getSelectedFile())) {
// TODO: output structure names
stream.write(resultAlignSeq.getBytes("UTF-8"));
} catch (IOException e1) {
MainWindow.LOGGER.error(
"Failed to save aligned sequences", e1);
JOptionPane.showMessageDialog(MainWindow.this,
e1.getMessage(), "Error",
JOptionPane.ERROR_MESSAGE);
}
} else { // current.equals(panelResultsAlignStruc)
try (FileOutputStream stream = new FileOutputStream(
chooserSaveFile.getSelectedFile())) {
stream.write(resultAlignStruc.getBytes("UTF-8"));
} catch (IOException e1) {
MainWindow.LOGGER.error(
"Failed to save PDB of aligned structures", e1);
JOptionPane.showMessageDialog(MainWindow.this,
e1.getMessage(), "Error",
JOptionPane.ERROR_MESSAGE);
}
}
}
});
checkBoxManager.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
managerDialog.setVisible(checkBoxManager.isSelected());
}
});
itemExit.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
dispatchEvent(new WindowEvent(MainWindow.this,
WindowEvent.WINDOW_CLOSING));
}
});
ActionListener radioActionListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
Object source = arg0.getSource();
itemSelectTorsion.setEnabled(source.equals(radioLocal));
}
};
radioGlobalMcq.addActionListener(radioActionListener);
radioGlobalRmsd.addActionListener(radioActionListener);
radioLocal.addActionListener(radioActionListener);
itemSelectTorsion.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
torsionDialog.setVisible(true);
}
});
ActionListener selectActionListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
if (source.equals(itemComputeDistances)
&& (radioGlobalMcq.isSelected() || radioGlobalRmsd
.isSelected())) {
/*
* Add new structures to the "all" section of structures
* selection dialog
*/
Enumeration<File> elements = PdbManagerDialog.MODEL
.elements();
while (elements.hasMoreElements()) {
File path = elements.nextElement();
if (!structureDialog.modelAll.contains(path)
&& !structureDialog.modelSelected
.contains(path)) {
structureDialog.modelAll.addElement(path);
}
}
/*
* Remove from "all" section these structures, that were
* removed in PDB manager dialog
*/
elements = structureDialog.modelAll.elements();
while (elements.hasMoreElements()) {
File path = elements.nextElement();
if (PdbManager.getStructure(path) == null) {
structureDialog.modelAll.removeElement(path);
}
}
/*
* Remove from "selected" section these structures, that
* were removed in PDB manager dialog
*/
elements = structureDialog.modelSelected.elements();
while (elements.hasMoreElements()) {
File path = elements.nextElement();
if (PdbManager.getStructure(path) == null) {
structureDialog.modelSelected.removeElement(path);
}
}
/*
* Show dialog
*/
structureDialog.setVisible(true);
if (structureDialog.chosenOption == StructureSelectionDialog.OK
&& structureDialog.selectedStructures != null) {
if (structureDialog.selectedStructures.size() < 2) {
JOptionPane
.showMessageDialog(
MainWindow.this,
"At "
+ "least two structures must be selected to "
+ "compute global distance",
"Information",
JOptionPane.INFORMATION_MESSAGE);
return;
}
tableMatrix.setModel(new MatrixTableModel(
new String[0], new double[0][]));
layoutCards.show(panelCards, MainWindow.CARD_GLOBAL);
itemSave.setEnabled(false);
radioGlobalMcq.setEnabled(true);
radioGlobalRmsd.setEnabled(true);
itemComputeDistances.setEnabled(true);
}
} else {
chainDialog.modelLeft.removeAllElements();
chainDialog.modelRight.removeAllElements();
Enumeration<File> elements = PdbManagerDialog.MODEL
.elements();
while (elements.hasMoreElements()) {
File path = elements.nextElement();
chainDialog.modelLeft.addElement(path);
chainDialog.modelRight.addElement(path);
}
chainDialog.setVisible(true);
if (chainDialog.chosenOption == ChainSelectionDialog.OK
&& chainDialog.selectedStructures != null
&& chainDialog.selectedChains != null) {
for (int i = 0; i < 2; i++) {
if (chainDialog.selectedChains[i].length == 0) {
String message = "No chains specified for structure: "
+ chainDialog.selectedStructures[i];
JOptionPane.showMessageDialog(MainWindow.this,
message, "Information",
JOptionPane.INFORMATION_MESSAGE);
chainDialog.selectedStructures = null;
chainDialog.selectedChains = null;
return;
}
}
if (source.equals(itemSelectStructuresCompare)) {
panelLocalPlot.removeAll();
panelLocalPlot.revalidate();
layoutCards.show(panelCards, MainWindow.CARD_LOCAL);
itemSelectTorsion.setEnabled(true);
itemComputeAlign.setEnabled(false);
} else if (radioAlignSeqGlobal.isSelected()
|| radioAlignSeqLocal.isSelected()) {
if (chainDialog.selectedChains[0].length != 1
|| chainDialog.selectedChains[1].length != 1) {
JOptionPane.showMessageDialog(MainWindow.this,
"A single chain should be "
+ "selected from each "
+ "structure in "
+ "sequence alignment.",
"Information",
JOptionPane.INFORMATION_MESSAGE);
chainDialog.selectedStructures = null;
chainDialog.selectedChains = null;
return;
}
textAreaAlignSeq.setText("");
layoutCards.show(panelCards,
MainWindow.CARD_ALIGN_SEQ);
itemSelectTorsion.setEnabled(false);
itemComputeAlign.setEnabled(true);
} else { // source.equals(itemSelectChainsAlignStruc)
panelJmolLeft.executeCmd("restore state "
+ "state_init");
panelJmolRight.executeCmd("restore state "
+ "state_init");
layoutCards.show(panelCards,
MainWindow.CARD_ALIGN_STRUC);
itemSelectTorsion.setEnabled(false);
itemComputeAlign.setEnabled(true);
}
}
}
}
};
itemSelectStructuresCompare.addActionListener(selectActionListener);
itemSelectStructuresAlign.addActionListener(selectActionListener);
itemComputeDistances.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (radioGlobalMcq.isSelected() || radioGlobalRmsd.isSelected()) {
final GlobalComparison comparison;
if (radioGlobalMcq.isSelected()) {
comparison = new MCQ();
} else { // radioRmsd.isSelected() == true
comparison = new RMSD();
}
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
Structure[] structures = PdbManager
.getSelectedStructures(structureDialog.selectedStructures);
resultGlobalNames = PdbManager
.getSelectedStructuresNames(structureDialog.selectedStructures);
resultGlobalMatrix = comparison.compare(structures,
new ComparisonListener() {
@Override
public void stateChanged(long all,
long completed) {
progressBar.setMaximum((int) all);
progressBar
.setValue((int) completed);
}
});
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
MatrixTableModel model = new MatrixTableModel(
resultGlobalNames,
resultGlobalMatrix);
tableMatrix.setModel(model);
itemSave.setEnabled(true);
itemSave.setText("Save results (CSV)");
itemCluster.setEnabled(true);
itemVisualise.setEnabled(true);
labelInfoGlobal.setText("Global comparison "
+ "results: distance matrix for "
+ (radioGlobalMcq.isSelected() ? "MCQ"
: "RMSD"));
}
});
}
});
thread.start();
} else {
layoutCards.show(panelCards, MainWindow.CARD_LOCAL);
final Structure[] structures = new Structure[2];
for (int i = 0; i < 2; i++) {
structures[i] = new StructureImpl();
// FIXME: NPE after hitting Cancel on chain selection
structures[i].setChains(Arrays
.asList(chainDialog.selectedChains[i]));
}
try {
resultLocal = TorsionLocalComparison.compare(
structures[0], structures[1], false);
} catch (StructureException e1) {
JOptionPane.showMessageDialog(MainWindow.this,
e1.getMessage(), "Error",
JOptionPane.ERROR_MESSAGE);
return;
}
Set<ResidueNumber> set = new HashSet<>();
for (String angle : torsionDialog.selectedNames) {
if (!resultLocal.containsKey(angle)) {
continue;
}
for (AngleDifference ad : resultLocal.get(angle)) {
set.add(ad.getResidue());
}
}
List<ResidueNumber> list = new ArrayList<>(set);
Collections.sort(list);
DefaultXYDataset dataset = new DefaultXYDataset();
for (String angle : torsionDialog.selectedNames) {
if (!resultLocal.containsKey(angle)) {
continue;
}
List<AngleDifference> diffs = resultLocal.get(angle);
Collections.sort(diffs);
double[] x = new double[diffs.size()];
double[] y = new double[diffs.size()];
for (int i = 0; i < diffs.size(); i++) {
AngleDifference ad = diffs.get(i);
x[i] = list.indexOf(ad.getResidue());
y[i] = ad.getDifference();
}
dataset.addSeries(angle, new double[][] { x, y });
}
NumberAxis xAxis = new TorsionAxis(resultLocal);
xAxis.setLabel("Residue");
NumberAxis yAxis = new NumberAxis();
yAxis.setAutoRange(false);
yAxis.setRange(0, Math.PI);
yAxis.setLabel("Distance [rad]");
XYPlot plot = new XYPlot(dataset, xAxis, yAxis,
new DefaultXYItemRenderer());
panelLocalPlot.removeAll();
panelLocalPlot.add(new ChartPanel(new JFreeChart(plot)));
panelLocalPlot.revalidate();
itemSave.setEnabled(true);
itemSave.setText("Save results (CSV)");
File[] pdbs = new File[] {
chainDialog.selectedStructures[0],
chainDialog.selectedStructures[1] };
String[] names = new String[] {
PdbManager.getStructureName(pdbs[0]),
PdbManager.getStructureName(pdbs[1]) };
labelInfoLocal
.setText("Local comparison results: distance "
+ "plot for " + names[0] + " and "
+ names[1]);
}
}
});
itemVisualise.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
MatrixTableModel model = (MatrixTableModel) tableMatrix
.getModel();
String[] names = model.getNames();
double[][] values = model.getValues();
for (double[] value : values) {
for (double element : value) {
if (Double.isNaN(element)) {
JOptionPane.showMessageDialog(MainWindow.this, ""
+ "Results cannot be visualized. Some "
+ "structures could not be compared.",
"Error", JOptionPane.ERROR_MESSAGE);
return;
}
}
}
double[][] mds = MDS.multidimensionalScaling(values, 2);
if (mds == null) {
JOptionPane.showMessageDialog(MainWindow.this, "Cannot "
+ "visualise specified structures in 2D space",
"Warning", JOptionPane.WARNING_MESSAGE);
return;
}
MDSPlot plot = new MDSPlot(mds, names);
plot.setVisible(true);
}
});
itemCluster.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
MatrixTableModel model = (MatrixTableModel) tableMatrix
.getModel();
String[] names = model.getNames();
double[][] values = model.getValues();
for (double[] value : values) {
for (double element : value) {
if (Double.isNaN(element)) {
JOptionPane.showMessageDialog(MainWindow.this, ""
+ "Results cannot be visualized. Some "
+ "structures could not be compared.",
"Error", JOptionPane.ERROR_MESSAGE);
return;
}
}
}
ClusteringDialog dialogClustering = new ClusteringDialog(names,
values);
dialogClustering.setVisible(true);
}
});
itemComputeAlign.addActionListener(new ActionListener() {
private Thread thread;
@Override
public void actionPerformed(ActionEvent e) {
if (radioAlignSeqGlobal.isSelected()
|| radioAlignSeqLocal.isSelected()) {
layoutCards.show(panelCards, MainWindow.CARD_ALIGN_SEQ);
Chain chains[] = new Chain[] {
chainDialog.selectedChains[0][0],
chainDialog.selectedChains[1][0] };
boolean isRNA = Helper.isNucleicAcid(chains[0]);
if (isRNA != Helper.isNucleicAcid(chains[1])) {
String message = "Cannot align structures: different molecular types";
MainWindow.LOGGER.error(message);
JOptionPane.showMessageDialog(null, message, "Error",
JOptionPane.ERROR_MESSAGE);
return;
}
OutputAlignSeq alignment = SequenceAligner.align(chains[0],
chains[1], radioAlignSeqGlobal.isSelected());
resultAlignSeq = alignment.toString();
textAreaAlignSeq.setText(resultAlignSeq);
itemSave.setEnabled(true);
itemSave.setText("Save results (TXT)");
File[] pdbs = new File[] {
chainDialog.selectedStructures[0],
chainDialog.selectedStructures[1] };
String[] names = new String[] {
PdbManager.getStructureName(pdbs[0]),
PdbManager.getStructureName(pdbs[1]) };
labelInfoAlignSeq.setText("Sequence alignment results for "
+ names[0] + " and " + names[1]);
} else {
if (thread != null && thread.isAlive()) {
JOptionPane.showMessageDialog(null,
"3D structure alignment computation has not "
+ "finished yet!", "Information",
JOptionPane.INFORMATION_MESSAGE);
return;
}
layoutCards.show(panelCards, MainWindow.CARD_ALIGN_STRUC);
final Structure[] structures = new Structure[2];
for (int i = 0; i < 2; i++) {
structures[i] = new StructureImpl();
structures[i].setChains(Arrays
.asList(chainDialog.selectedChains[i]));
}
boolean isRNA = Helper.isNucleicAcid(structures[0]);
if (isRNA != Helper.isNucleicAcid(structures[1])) {
String message = "Cannot align structures: different molecular types";
MainWindow.LOGGER.error(message);
JOptionPane.showMessageDialog(null, message, "Error",
JOptionPane.ERROR_MESSAGE);
return;
}
labelInfoAlignStruc.setText("Processing");
final Timer timer = new Timer(250, new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
String text = labelInfoAlignStruc.getText();
int count = StringUtils.countMatches(text, ".");
if (count < 5) {
labelInfoAlignStruc.setText(text + ".");
} else {
labelInfoAlignStruc.setText("Processing");
}
}
});
timer.start();
thread = new Thread(new Runnable() {
@Override
public void run() {
try {
Helper.normalizeAtomNames(structures[0]);
Helper.normalizeAtomNames(structures[1]);
AlignmentOutput output = StructureAligner
.align(structures[0], structures[1]);
final Structure[] aligned = output
.getStructures();
SwingUtilities.invokeLater(new Runnable() {
private static final String JMOL_SCRIPT = "frame 0.0; "
+ "cartoon only; "
+ "select model=1.1; color green; "
+ "select model=1.2; color red; ";
@Override
public void run() {
StringBuilder builder = new StringBuilder();
builder.append("MODEL 1 \n");
builder.append(aligned[0].toPDB());
builder.append("ENDMDL \n");
builder.append("MODEL 2 \n");
builder.append(aligned[1].toPDB());
builder.append("ENDMDL \n");
resultAlignStruc = builder.toString();
JmolViewer viewer = panelJmolLeft
.getViewer();
viewer.openStringInline(builder
.toString());
panelJmolLeft.executeCmd(JMOL_SCRIPT);
builder = new StringBuilder();
builder.append("MODEL 1 \n");
builder.append(aligned[2].toPDB());
builder.append("ENDMDL \n");
builder.append("MODEL 2 \n");
builder.append(aligned[3].toPDB());
builder.append("ENDMDL \n");
viewer = panelJmolRight.getViewer();
viewer.openStringInline(builder
.toString());
panelJmolRight.executeCmd(JMOL_SCRIPT);
itemSave.setEnabled(true);
itemSave.setText("Save results (PDB)");
}
});
} catch (StructureException e1) {
MainWindow.LOGGER.error(
"Failed to align structures", e1);
JOptionPane.showMessageDialog(getParent(),
e1.getMessage(), "Error",
JOptionPane.ERROR_MESSAGE);
} finally {
timer.stop();
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
File[] pdbs = new File[] {
chainDialog.selectedStructures[0],
chainDialog.selectedStructures[1] };
String[] names = new String[] {
PdbManager
.getStructureName(pdbs[0]),
PdbManager
.getStructureName(pdbs[1]) };
labelInfoAlignStruc
.setText("3D structure "
+ "alignments results for "
+ names[0] + " and "
+ names[1]);
}
});
}
}
});
thread.start();
}
}
});
itemGuide.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
QuickGuideDialog dialog = new QuickGuideDialog(MainWindow.this);
dialog.setVisible(true);
}
});
itemAbout.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
AboutDialog dialog = new AboutDialog(MainWindow.this);
dialog.setVisible(true);
}
});
}
| public MainWindow() {
super();
chooserSaveFile = new JFileChooser();
managerDialog = PdbManagerDialog.getInstance(this);
managerDialog.setVisible(true);
structureDialog = StructureSelectionDialog.getInstance(this);
chainDialog = ChainSelectionDialog.getInstance(this);
torsionDialog = TorsionAnglesSelectionDialog.getInstance(this);
/*
* Create menu
*/
JMenuBar menuBar = new JMenuBar();
final JMenuItem itemOpen = new JMenuItem("Open structure(s)",
loadIcon("/toolbarButtonGraphics/general/Open16.gif"));
final JMenuItem itemSave = new JMenuItem("Save results",
loadIcon("/toolbarButtonGraphics/general/Save16.gif"));
itemSave.setEnabled(false);
final JCheckBoxMenuItem checkBoxManager = new JCheckBoxMenuItem(
"View structure manager", true);
final JMenuItem itemExit = new JMenuItem("Exit");
JMenu menu = new JMenu("File");
menu.setMnemonic(KeyEvent.VK_F);
menu.add(itemOpen);
menu.add(itemSave);
menu.addSeparator();
menu.add(checkBoxManager);
menu.addSeparator();
menu.add(itemExit);
menuBar.add(menu);
final JRadioButtonMenuItem radioGlobalMcq = new JRadioButtonMenuItem(
"Global MCQ", true);
final JRadioButtonMenuItem radioGlobalRmsd = new JRadioButtonMenuItem(
"Global RMSD", false);
final JRadioButtonMenuItem radioLocal = new JRadioButtonMenuItem(
"Local distances", false);
ButtonGroup group = new ButtonGroup();
group.add(radioGlobalMcq);
group.add(radioGlobalRmsd);
group.add(radioLocal);
final JMenuItem itemSelectTorsion = new JMenuItem(
"Select torsion angles");
itemSelectTorsion.setEnabled(false);
final JMenuItem itemSelectStructuresCompare = new JMenuItem(
"Select structures to compare");
final JMenuItem itemComputeDistances = new JMenuItem(
"Compute distance(s)");
itemComputeDistances.setEnabled(false);
final JMenuItem itemVisualise = new JMenuItem("Visualise results");
itemVisualise.setEnabled(false);
final JMenuItem itemCluster = new JMenuItem("Cluster results");
itemCluster.setEnabled(false);
menu = new JMenu("Distance measure");
menu.setMnemonic(KeyEvent.VK_D);
menu.add(new JLabel(" Select distance type:"));
menu.add(radioGlobalMcq);
menu.add(radioGlobalRmsd);
menu.add(radioLocal);
menu.addSeparator();
menu.add(itemSelectTorsion);
menu.add(itemSelectStructuresCompare);
menu.addSeparator();
menu.add(itemComputeDistances);
menu.add(itemVisualise);
menu.add(itemCluster);
menuBar.add(menu);
final JRadioButtonMenuItem radioAlignSeqGlobal = new JRadioButtonMenuItem(
"Global sequence alignment", true);
final JRadioButtonMenuItem radioAlignSeqLocal = new JRadioButtonMenuItem(
"Local sequence alignment", false);
final JRadioButtonMenuItem radioAlignStruc = new JRadioButtonMenuItem(
"3D structure alignment", false);
ButtonGroup groupAlign = new ButtonGroup();
groupAlign.add(radioAlignSeqGlobal);
groupAlign.add(radioAlignSeqLocal);
groupAlign.add(radioAlignStruc);
final JMenuItem itemSelectStructuresAlign = new JMenuItem(
"Select structures to align");
final JMenuItem itemComputeAlign = new JMenuItem("Compute alignment");
itemComputeAlign.setEnabled(false);
menu = new JMenu("Alignment");
menu.setMnemonic(KeyEvent.VK_A);
menu.add(new JLabel(" Select alignment type:"));
menu.add(radioAlignSeqGlobal);
menu.add(radioAlignSeqLocal);
menu.add(radioAlignStruc);
menu.addSeparator();
menu.add(itemSelectStructuresAlign);
menu.add(itemComputeAlign);
menuBar.add(menu);
JMenuItem itemGuide = new JMenuItem("Quick guide");
JMenuItem itemAbout = new JMenuItem("About");
menu = new JMenu("Help");
menu.setMnemonic(KeyEvent.VK_H);
menu.add(itemGuide);
menu.add(itemAbout);
menuBar.add(menu);
setJMenuBar(menuBar);
/*
* Create panel with global comparison results
*/
JPanel panel;
final JLabel labelInfoGlobal = new JLabel(
"Global comparison results: distance matrix");
final JTable tableMatrix = new JTable();
final JProgressBar progressBar = new JProgressBar();
progressBar.setStringPainted(true);
final JPanel panelResultsGlobal = new JPanel(new BorderLayout());
panel = new JPanel(new BorderLayout());
panel.add(labelInfoGlobal, BorderLayout.WEST);
panelResultsGlobal.add(panel, BorderLayout.NORTH);
panelResultsGlobal.add(new JScrollPane(tableMatrix),
BorderLayout.CENTER);
panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
panel.add(new JLabel("Progress in computing:"));
panel.add(progressBar);
/*
* Create panel with local comparison results
*/
final JLabel labelInfoLocal = new JLabel(
"Local comparison results: distance plot");
final JPanel panelLocalPlot = new JPanel(new GridLayout(1, 1));
final JPanel panelResultsLocal = new JPanel(new BorderLayout());
panel = new JPanel(new BorderLayout());
panel.add(labelInfoLocal, BorderLayout.WEST);
panelResultsLocal.add(panel, BorderLayout.NORTH);
panelResultsLocal.add(panelLocalPlot, BorderLayout.CENTER);
/*
* Create panel with sequence alignment
*/
final JLabel labelInfoAlignSeq = new JLabel(
"Sequence alignment results");
final JTextArea textAreaAlignSeq = new JTextArea();
textAreaAlignSeq.setEditable(false);
textAreaAlignSeq.setFont(new Font("Monospaced", Font.PLAIN, 20));
final JPanel panelResultsAlignSeq = new JPanel(new BorderLayout());
panel = new JPanel(new BorderLayout());
panel.add(labelInfoAlignSeq, BorderLayout.WEST);
panelResultsAlignSeq.add(panel, BorderLayout.NORTH);
panelResultsAlignSeq.add(new JScrollPane(textAreaAlignSeq),
BorderLayout.CENTER);
/*
* Create panel with structure alignment
*/
JPanel panelAlignStrucInfo = new JPanel(new GridBagLayout());
GridBagConstraints constraints = new GridBagConstraints();
constraints.gridx = 0;
constraints.gridy = 0;
constraints.weightx = 0.5;
panelAlignStrucInfo.add(new JLabel("Whole structures (Jmol view)"),
constraints);
constraints.gridx++;
constraints.weightx = 0;
final JLabel labelInfoAlignStruc = new JLabel(
"3D structure alignment results");
panelAlignStrucInfo.add(labelInfoAlignStruc, constraints);
constraints.gridx++;
constraints.weightx = 0.5;
panelAlignStrucInfo.add(new JLabel("Aligned fragments (Jmol view)"),
constraints);
final JmolPanel panelJmolLeft = new JmolPanel();
panelJmolLeft.executeCmd("background lightgrey; save state state_init");
final JmolPanel panelJmolRight = new JmolPanel();
panelJmolRight.executeCmd("background darkgray; save state state_init");
final JPanel panelResultsAlignStruc = new JPanel(new BorderLayout());
panelResultsAlignStruc.add(panelAlignStrucInfo, BorderLayout.NORTH);
panel = new JPanel(new GridLayout(1, 2));
panel.add(panelJmolLeft);
panel.add(panelJmolRight);
panelResultsAlignStruc.add(panel, BorderLayout.CENTER);
/*
* Create card layout
*/
final CardLayout layoutCards = new CardLayout();
final JPanel panelCards = new JPanel();
panelCards.setLayout(layoutCards);
panelCards.add(new JPanel());
panelCards.add(panelResultsGlobal, MainWindow.CARD_GLOBAL);
panelCards.add(panelResultsLocal, MainWindow.CARD_LOCAL);
panelCards.add(panelResultsAlignSeq, MainWindow.CARD_ALIGN_SEQ);
panelCards.add(panelResultsAlignStruc, MainWindow.CARD_ALIGN_STRUC);
setLayout(new BorderLayout());
add(panelCards, BorderLayout.CENTER);
/*
* Set window properties
*/
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle(MainWindow.TITLE);
Toolkit toolkit = Toolkit.getDefaultToolkit();
Dimension size = toolkit.getScreenSize();
setSize(size.width * 3 / 4, size.height * 3 / 4);
setLocation(size.width / 8, size.height / 8);
/*
* Set action listeners
*/
managerDialog.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
super.windowClosing(e);
checkBoxManager.setSelected(false);
}
});
itemOpen.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
File[] files = PdbFileChooser.getSelectedFiles(MainWindow.this);
for (File f : files) {
if (PdbManager.loadStructure(f) != null) {
PdbManagerDialog.MODEL.addElement(f);
}
}
}
});
itemSave.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Component current = MainWindow.getCurrentCard(panelCards);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-DD-HH-mm");
Date now = new Date();
File proposedName = null;
if (current.equals(panelResultsGlobal)) {
proposedName = new File(sdf.format(now) + "-global.csv");
} else {
StringBuilder builder = new StringBuilder();
builder.append(PdbManager
.getStructureName(chainDialog.selectedStructures[0]));
builder.append('-');
builder.append(PdbManager
.getStructureName(chainDialog.selectedStructures[1]));
if (current.equals(panelResultsLocal)) {
proposedName = new File(sdf.format(now) + "-local-"
+ builder.toString() + ".csv");
} else if (current.equals(panelResultsAlignSeq)) {
proposedName = new File(sdf.format(now) + "-alignseq-"
+ builder.toString() + ".txt");
} else { // current.equals(panelResultsAlignStruc)
proposedName = new File(sdf.format(now)
+ "-alignstruc-" + builder.toString() + ".pdb");
}
}
chooserSaveFile.setSelectedFile(proposedName);
int chosenOption = chooserSaveFile
.showSaveDialog(MainWindow.this);
if (chosenOption != JFileChooser.APPROVE_OPTION) {
return;
}
if (current.equals(panelResultsGlobal)) {
saveResultsGlobalComparison(chooserSaveFile
.getSelectedFile());
} else if (current.equals(panelResultsLocal)) {
saveResultsLocalComparison(chooserSaveFile
.getSelectedFile());
} else if (current.equals(panelResultsAlignSeq)) {
try (FileOutputStream stream = new FileOutputStream(
chooserSaveFile.getSelectedFile())) {
// TODO: output structure names
stream.write(resultAlignSeq.getBytes("UTF-8"));
} catch (IOException e1) {
MainWindow.LOGGER.error(
"Failed to save aligned sequences", e1);
JOptionPane.showMessageDialog(MainWindow.this,
e1.getMessage(), "Error",
JOptionPane.ERROR_MESSAGE);
}
} else { // current.equals(panelResultsAlignStruc)
try (FileOutputStream stream = new FileOutputStream(
chooserSaveFile.getSelectedFile())) {
stream.write(resultAlignStruc.getBytes("UTF-8"));
} catch (IOException e1) {
MainWindow.LOGGER.error(
"Failed to save PDB of aligned structures", e1);
JOptionPane.showMessageDialog(MainWindow.this,
e1.getMessage(), "Error",
JOptionPane.ERROR_MESSAGE);
}
}
}
});
checkBoxManager.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
managerDialog.setVisible(checkBoxManager.isSelected());
}
});
itemExit.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
dispatchEvent(new WindowEvent(MainWindow.this,
WindowEvent.WINDOW_CLOSING));
}
});
ActionListener radioActionListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
Object source = arg0.getSource();
itemSelectTorsion.setEnabled(source.equals(radioLocal));
}
};
radioGlobalMcq.addActionListener(radioActionListener);
radioGlobalRmsd.addActionListener(radioActionListener);
radioLocal.addActionListener(radioActionListener);
itemSelectTorsion.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
torsionDialog.setVisible(true);
}
});
ActionListener selectActionListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
if (source.equals(itemSelectStructuresCompare)
&& (radioGlobalMcq.isSelected() || radioGlobalRmsd
.isSelected())) {
/*
* Add new structures to the "all" section of structures
* selection dialog
*/
Enumeration<File> elements = PdbManagerDialog.MODEL
.elements();
while (elements.hasMoreElements()) {
File path = elements.nextElement();
if (!structureDialog.modelAll.contains(path)
&& !structureDialog.modelSelected
.contains(path)) {
structureDialog.modelAll.addElement(path);
}
}
/*
* Remove from "all" section these structures, that were
* removed in PDB manager dialog
*/
elements = structureDialog.modelAll.elements();
while (elements.hasMoreElements()) {
File path = elements.nextElement();
if (PdbManager.getStructure(path) == null) {
structureDialog.modelAll.removeElement(path);
}
}
/*
* Remove from "selected" section these structures, that
* were removed in PDB manager dialog
*/
elements = structureDialog.modelSelected.elements();
while (elements.hasMoreElements()) {
File path = elements.nextElement();
if (PdbManager.getStructure(path) == null) {
structureDialog.modelSelected.removeElement(path);
}
}
/*
* Show dialog
*/
structureDialog.setVisible(true);
if (structureDialog.chosenOption == StructureSelectionDialog.OK
&& structureDialog.selectedStructures != null) {
if (structureDialog.selectedStructures.size() < 2) {
JOptionPane
.showMessageDialog(
MainWindow.this,
"At "
+ "least two structures must be selected to "
+ "compute global distance",
"Information",
JOptionPane.INFORMATION_MESSAGE);
return;
}
tableMatrix.setModel(new MatrixTableModel(
new String[0], new double[0][]));
layoutCards.show(panelCards, MainWindow.CARD_GLOBAL);
itemSave.setEnabled(false);
radioGlobalMcq.setEnabled(true);
radioGlobalRmsd.setEnabled(true);
itemComputeDistances.setEnabled(true);
}
} else {
chainDialog.modelLeft.removeAllElements();
chainDialog.modelRight.removeAllElements();
Enumeration<File> elements = PdbManagerDialog.MODEL
.elements();
while (elements.hasMoreElements()) {
File path = elements.nextElement();
chainDialog.modelLeft.addElement(path);
chainDialog.modelRight.addElement(path);
}
chainDialog.setVisible(true);
if (chainDialog.chosenOption == ChainSelectionDialog.OK
&& chainDialog.selectedStructures != null
&& chainDialog.selectedChains != null) {
for (int i = 0; i < 2; i++) {
if (chainDialog.selectedChains[i].length == 0) {
String message = "No chains specified for structure: "
+ chainDialog.selectedStructures[i];
JOptionPane.showMessageDialog(MainWindow.this,
message, "Information",
JOptionPane.INFORMATION_MESSAGE);
chainDialog.selectedStructures = null;
chainDialog.selectedChains = null;
return;
}
}
if (source.equals(itemSelectStructuresCompare)) {
panelLocalPlot.removeAll();
panelLocalPlot.revalidate();
layoutCards.show(panelCards, MainWindow.CARD_LOCAL);
itemSelectTorsion.setEnabled(true);
itemComputeAlign.setEnabled(false);
} else if (radioAlignSeqGlobal.isSelected()
|| radioAlignSeqLocal.isSelected()) {
if (chainDialog.selectedChains[0].length != 1
|| chainDialog.selectedChains[1].length != 1) {
JOptionPane.showMessageDialog(MainWindow.this,
"A single chain should be "
+ "selected from each "
+ "structure in "
+ "sequence alignment.",
"Information",
JOptionPane.INFORMATION_MESSAGE);
chainDialog.selectedStructures = null;
chainDialog.selectedChains = null;
return;
}
textAreaAlignSeq.setText("");
layoutCards.show(panelCards,
MainWindow.CARD_ALIGN_SEQ);
itemSelectTorsion.setEnabled(false);
itemComputeAlign.setEnabled(true);
} else { // source.equals(itemSelectChainsAlignStruc)
panelJmolLeft.executeCmd("restore state "
+ "state_init");
panelJmolRight.executeCmd("restore state "
+ "state_init");
layoutCards.show(panelCards,
MainWindow.CARD_ALIGN_STRUC);
itemSelectTorsion.setEnabled(false);
itemComputeAlign.setEnabled(true);
}
}
}
}
};
itemSelectStructuresCompare.addActionListener(selectActionListener);
itemSelectStructuresAlign.addActionListener(selectActionListener);
itemComputeDistances.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (radioGlobalMcq.isSelected() || radioGlobalRmsd.isSelected()) {
final GlobalComparison comparison;
if (radioGlobalMcq.isSelected()) {
comparison = new MCQ();
} else { // radioRmsd.isSelected() == true
comparison = new RMSD();
}
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
Structure[] structures = PdbManager
.getSelectedStructures(structureDialog.selectedStructures);
resultGlobalNames = PdbManager
.getSelectedStructuresNames(structureDialog.selectedStructures);
resultGlobalMatrix = comparison.compare(structures,
new ComparisonListener() {
@Override
public void stateChanged(long all,
long completed) {
progressBar.setMaximum((int) all);
progressBar
.setValue((int) completed);
}
});
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
MatrixTableModel model = new MatrixTableModel(
resultGlobalNames,
resultGlobalMatrix);
tableMatrix.setModel(model);
itemSave.setEnabled(true);
itemSave.setText("Save results (CSV)");
itemCluster.setEnabled(true);
itemVisualise.setEnabled(true);
labelInfoGlobal.setText("Global comparison "
+ "results: distance matrix for "
+ (radioGlobalMcq.isSelected() ? "MCQ"
: "RMSD"));
}
});
}
});
thread.start();
} else {
layoutCards.show(panelCards, MainWindow.CARD_LOCAL);
final Structure[] structures = new Structure[2];
for (int i = 0; i < 2; i++) {
structures[i] = new StructureImpl();
// FIXME: NPE after hitting Cancel on chain selection
structures[i].setChains(Arrays
.asList(chainDialog.selectedChains[i]));
}
try {
resultLocal = TorsionLocalComparison.compare(
structures[0], structures[1], false);
} catch (StructureException e1) {
JOptionPane.showMessageDialog(MainWindow.this,
e1.getMessage(), "Error",
JOptionPane.ERROR_MESSAGE);
return;
}
Set<ResidueNumber> set = new HashSet<>();
for (String angle : torsionDialog.selectedNames) {
if (!resultLocal.containsKey(angle)) {
continue;
}
for (AngleDifference ad : resultLocal.get(angle)) {
set.add(ad.getResidue());
}
}
List<ResidueNumber> list = new ArrayList<>(set);
Collections.sort(list);
DefaultXYDataset dataset = new DefaultXYDataset();
for (String angle : torsionDialog.selectedNames) {
if (!resultLocal.containsKey(angle)) {
continue;
}
List<AngleDifference> diffs = resultLocal.get(angle);
Collections.sort(diffs);
double[] x = new double[diffs.size()];
double[] y = new double[diffs.size()];
for (int i = 0; i < diffs.size(); i++) {
AngleDifference ad = diffs.get(i);
x[i] = list.indexOf(ad.getResidue());
y[i] = ad.getDifference();
}
dataset.addSeries(angle, new double[][] { x, y });
}
NumberAxis xAxis = new TorsionAxis(resultLocal);
xAxis.setLabel("Residue");
NumberAxis yAxis = new NumberAxis();
yAxis.setAutoRange(false);
yAxis.setRange(0, Math.PI);
yAxis.setLabel("Distance [rad]");
XYPlot plot = new XYPlot(dataset, xAxis, yAxis,
new DefaultXYItemRenderer());
panelLocalPlot.removeAll();
panelLocalPlot.add(new ChartPanel(new JFreeChart(plot)));
panelLocalPlot.revalidate();
itemSave.setEnabled(true);
itemSave.setText("Save results (CSV)");
File[] pdbs = new File[] {
chainDialog.selectedStructures[0],
chainDialog.selectedStructures[1] };
String[] names = new String[] {
PdbManager.getStructureName(pdbs[0]),
PdbManager.getStructureName(pdbs[1]) };
labelInfoLocal
.setText("Local comparison results: distance "
+ "plot for " + names[0] + " and "
+ names[1]);
}
}
});
itemVisualise.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
MatrixTableModel model = (MatrixTableModel) tableMatrix
.getModel();
String[] names = model.getNames();
double[][] values = model.getValues();
for (double[] value : values) {
for (double element : value) {
if (Double.isNaN(element)) {
JOptionPane.showMessageDialog(MainWindow.this, ""
+ "Results cannot be visualized. Some "
+ "structures could not be compared.",
"Error", JOptionPane.ERROR_MESSAGE);
return;
}
}
}
double[][] mds = MDS.multidimensionalScaling(values, 2);
if (mds == null) {
JOptionPane.showMessageDialog(MainWindow.this, "Cannot "
+ "visualise specified structures in 2D space",
"Warning", JOptionPane.WARNING_MESSAGE);
return;
}
MDSPlot plot = new MDSPlot(mds, names);
plot.setVisible(true);
}
});
itemCluster.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
MatrixTableModel model = (MatrixTableModel) tableMatrix
.getModel();
String[] names = model.getNames();
double[][] values = model.getValues();
for (double[] value : values) {
for (double element : value) {
if (Double.isNaN(element)) {
JOptionPane.showMessageDialog(MainWindow.this, ""
+ "Results cannot be visualized. Some "
+ "structures could not be compared.",
"Error", JOptionPane.ERROR_MESSAGE);
return;
}
}
}
ClusteringDialog dialogClustering = new ClusteringDialog(names,
values);
dialogClustering.setVisible(true);
}
});
itemComputeAlign.addActionListener(new ActionListener() {
private Thread thread;
@Override
public void actionPerformed(ActionEvent e) {
if (radioAlignSeqGlobal.isSelected()
|| radioAlignSeqLocal.isSelected()) {
layoutCards.show(panelCards, MainWindow.CARD_ALIGN_SEQ);
Chain chains[] = new Chain[] {
chainDialog.selectedChains[0][0],
chainDialog.selectedChains[1][0] };
boolean isRNA = Helper.isNucleicAcid(chains[0]);
if (isRNA != Helper.isNucleicAcid(chains[1])) {
String message = "Cannot align structures: different molecular types";
MainWindow.LOGGER.error(message);
JOptionPane.showMessageDialog(null, message, "Error",
JOptionPane.ERROR_MESSAGE);
return;
}
OutputAlignSeq alignment = SequenceAligner.align(chains[0],
chains[1], radioAlignSeqGlobal.isSelected());
resultAlignSeq = alignment.toString();
textAreaAlignSeq.setText(resultAlignSeq);
itemSave.setEnabled(true);
itemSave.setText("Save results (TXT)");
File[] pdbs = new File[] {
chainDialog.selectedStructures[0],
chainDialog.selectedStructures[1] };
String[] names = new String[] {
PdbManager.getStructureName(pdbs[0]),
PdbManager.getStructureName(pdbs[1]) };
labelInfoAlignSeq.setText("Sequence alignment results for "
+ names[0] + " and " + names[1]);
} else {
if (thread != null && thread.isAlive()) {
JOptionPane.showMessageDialog(null,
"3D structure alignment computation has not "
+ "finished yet!", "Information",
JOptionPane.INFORMATION_MESSAGE);
return;
}
layoutCards.show(panelCards, MainWindow.CARD_ALIGN_STRUC);
final Structure[] structures = new Structure[2];
for (int i = 0; i < 2; i++) {
structures[i] = new StructureImpl();
structures[i].setChains(Arrays
.asList(chainDialog.selectedChains[i]));
}
boolean isRNA = Helper.isNucleicAcid(structures[0]);
if (isRNA != Helper.isNucleicAcid(structures[1])) {
String message = "Cannot align structures: different molecular types";
MainWindow.LOGGER.error(message);
JOptionPane.showMessageDialog(null, message, "Error",
JOptionPane.ERROR_MESSAGE);
return;
}
labelInfoAlignStruc.setText("Processing");
final Timer timer = new Timer(250, new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
String text = labelInfoAlignStruc.getText();
int count = StringUtils.countMatches(text, ".");
if (count < 5) {
labelInfoAlignStruc.setText(text + ".");
} else {
labelInfoAlignStruc.setText("Processing");
}
}
});
timer.start();
thread = new Thread(new Runnable() {
@Override
public void run() {
try {
Helper.normalizeAtomNames(structures[0]);
Helper.normalizeAtomNames(structures[1]);
AlignmentOutput output = StructureAligner
.align(structures[0], structures[1]);
final Structure[] aligned = output
.getStructures();
SwingUtilities.invokeLater(new Runnable() {
private static final String JMOL_SCRIPT = "frame 0.0; "
+ "cartoon only; "
+ "select model=1.1; color green; "
+ "select model=1.2; color red; ";
@Override
public void run() {
StringBuilder builder = new StringBuilder();
builder.append("MODEL 1 \n");
builder.append(aligned[0].toPDB());
builder.append("ENDMDL \n");
builder.append("MODEL 2 \n");
builder.append(aligned[1].toPDB());
builder.append("ENDMDL \n");
resultAlignStruc = builder.toString();
JmolViewer viewer = panelJmolLeft
.getViewer();
viewer.openStringInline(builder
.toString());
panelJmolLeft.executeCmd(JMOL_SCRIPT);
builder = new StringBuilder();
builder.append("MODEL 1 \n");
builder.append(aligned[2].toPDB());
builder.append("ENDMDL \n");
builder.append("MODEL 2 \n");
builder.append(aligned[3].toPDB());
builder.append("ENDMDL \n");
viewer = panelJmolRight.getViewer();
viewer.openStringInline(builder
.toString());
panelJmolRight.executeCmd(JMOL_SCRIPT);
itemSave.setEnabled(true);
itemSave.setText("Save results (PDB)");
}
});
} catch (StructureException e1) {
MainWindow.LOGGER.error(
"Failed to align structures", e1);
JOptionPane.showMessageDialog(getParent(),
e1.getMessage(), "Error",
JOptionPane.ERROR_MESSAGE);
} finally {
timer.stop();
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
File[] pdbs = new File[] {
chainDialog.selectedStructures[0],
chainDialog.selectedStructures[1] };
String[] names = new String[] {
PdbManager
.getStructureName(pdbs[0]),
PdbManager
.getStructureName(pdbs[1]) };
labelInfoAlignStruc
.setText("3D structure "
+ "alignments results for "
+ names[0] + " and "
+ names[1]);
}
});
}
}
});
thread.start();
}
}
});
itemGuide.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
QuickGuideDialog dialog = new QuickGuideDialog(MainWindow.this);
dialog.setVisible(true);
}
});
itemAbout.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
AboutDialog dialog = new AboutDialog(MainWindow.this);
dialog.setVisible(true);
}
});
}
|
diff --git a/src/kg/apc/jmeter/threads/SteppingThreadGroup.java b/src/kg/apc/jmeter/threads/SteppingThreadGroup.java
index 28e8b169..f3ded81b 100644
--- a/src/kg/apc/jmeter/threads/SteppingThreadGroup.java
+++ b/src/kg/apc/jmeter/threads/SteppingThreadGroup.java
@@ -1,228 +1,228 @@
package kg.apc.jmeter.threads;
import org.apache.jmeter.engine.event.LoopIterationEvent;
import org.apache.jmeter.testelement.TestListener;
import org.apache.log.Logger;
import org.apache.jmeter.threads.AbstractThreadGroup;
import org.apache.jmeter.threads.JMeterThread;
import org.apache.jorphan.logging.LoggingManager;
/**
*
* @author apc
*/
public class SteppingThreadGroup
extends AbstractThreadGroup implements TestListener {
private static final Logger log = LoggingManager.getLoggerForClass();
/**
*
*/
private static final String THREAD_GROUP_DELAY = "Threads initial delay";
/**
*
*/
private static final String INC_USER_PERIOD = "Start users period";
/**
*
*/
private static final String INC_USER_COUNT = "Start users count";
/**
*
*/
private static final String DEC_USER_PERIOD = "Stop users period";
/**
*
*/
private static final String DEC_USER_COUNT = "Stop users count";
/**
*
*/
private static final String FLIGHT_TIME = "flighttime";
private static final String RAMPUP = "rampUp";
private long testStartTime;
/**
*
*/
public SteppingThreadGroup() {
super();
}
/**
*
* @param thread
*/
@Override
public void scheduleThread(JMeterThread thread) {
int inUserCount = getInUserCountAsInt();
int outUserCount = getOutUserCountAsInt();
if(inUserCount == 0) inUserCount = getNumThreads();
if(outUserCount == 0) outUserCount = getNumThreads();
int threadGroupDelay = 1000 * getThreadGroupDelayAsInt();
long ascentPoint = testStartTime + threadGroupDelay;
int inUserPeriod = 1000 * getInUserPeriodAsInt();
int additionalRampUp = 1000 * getRampUpAsInt() / inUserCount;
int flightTime = 1000 * getFlightTimeAsInt();
int outUserPeriod = 1000 * getOutUserPeriodAsInt();
long rampUpDuration = 1000 * getRampUpAsInt();
long iterationDuration = inUserPeriod + rampUpDuration;
int iterationCountTotal = (int) Math.ceil((double) getNumThreads() / inUserCount) - 1;
int iterationCountBeforeMe = (int) Math.floor((double) thread.getThreadNum() / inUserCount);
- long descentPoint = ascentPoint + iterationCountTotal * (iterationDuration+additionalRampUp) + additionalRampUp + flightTime;
+ long descentPoint = ascentPoint + iterationCountTotal * (iterationDuration+additionalRampUp) + rampUpDuration + flightTime;
long startTime = ascentPoint + iterationCountBeforeMe * iterationDuration + (thread.getThreadNum() % inUserCount) * additionalRampUp;
long endTime = descentPoint + outUserPeriod * (int) Math.floor((double) thread.getThreadNum() / outUserCount);
log.debug(String.format("threadNum=%d, rampUpDuration=%d, iterationDuration=%d, iterationCountTotal=%d, iterationCountBeforeMe=%d, ascentPoint=%d, descentPoint=%d, startTime=%d, endTime=%d",
thread.getThreadNum(), rampUpDuration, iterationDuration, iterationCountTotal, iterationCountBeforeMe, ascentPoint, descentPoint, startTime, endTime));
thread.setStartTime(startTime);
thread.setEndTime(endTime);
thread.setScheduled(true);
}
/**
*
* @return
*/
public String getThreadGroupDelay() {
return getPropertyAsString(THREAD_GROUP_DELAY);
}
public void setThreadGroupDelay(String delay) {
setProperty(THREAD_GROUP_DELAY, delay);
}
/**
*
* @return
*/
public String getInUserPeriod() {
return getPropertyAsString(INC_USER_PERIOD);
}
public void setInUserPeriod(String value) {
setProperty(INC_USER_PERIOD, value);
}
/**
*
* @return
*/
public String getInUserCount() {
return getPropertyAsString(INC_USER_COUNT);
}
public void setInUserCount(String delay) {
setProperty(INC_USER_COUNT, delay);
}
/**
*
* @return
*/
public String getFlightTime() {
return getPropertyAsString(FLIGHT_TIME);
}
public void setFlightTime(String delay) {
setProperty(FLIGHT_TIME, delay);
}
/**
*
* @return
*/
public String getOutUserPeriod() {
return getPropertyAsString(DEC_USER_PERIOD);
}
public void setOutUserPeriod(String delay) {
setProperty(DEC_USER_PERIOD, delay);
}
/**
*
* @return
*/
public String getOutUserCount() {
return getPropertyAsString(DEC_USER_COUNT);
}
public void setOutUserCount(String delay) {
setProperty(DEC_USER_COUNT, delay);
}
public String getRampUp() {
return getPropertyAsString(RAMPUP);
}
public void setRampUp(String delay) {
setProperty(RAMPUP, delay);
}
public int getThreadGroupDelayAsInt() {
return getPropertyAsInt(THREAD_GROUP_DELAY);
}
public int getInUserPeriodAsInt() {
return getPropertyAsInt(INC_USER_PERIOD);
}
public int getInUserCountAsInt() {
return getPropertyAsInt(INC_USER_COUNT);
}
public int getRampUpAsInt() {
return getPropertyAsInt(RAMPUP);
}
public int getFlightTimeAsInt() {
return getPropertyAsInt(FLIGHT_TIME);
}
public int getOutUserPeriodAsInt() {
return getPropertyAsInt(DEC_USER_PERIOD);
}
public int getOutUserCountAsInt() {
return getPropertyAsInt(DEC_USER_COUNT);
}
public void setNumThreads(String execute) {
setProperty(NUM_THREADS, execute);
}
public String getNumThreadsAsString() {
return getPropertyAsString(NUM_THREADS);
}
@Override
public void testStarted() {
testStartTime = System.currentTimeMillis();
}
@Override
public void testStarted(String string) {
testStarted();
}
@Override
public void testEnded() {
}
@Override
public void testEnded(String string) {
testEnded();
}
@Override
public void testIterationStart(LoopIterationEvent lie) {
}
}
| true | true | public void scheduleThread(JMeterThread thread) {
int inUserCount = getInUserCountAsInt();
int outUserCount = getOutUserCountAsInt();
if(inUserCount == 0) inUserCount = getNumThreads();
if(outUserCount == 0) outUserCount = getNumThreads();
int threadGroupDelay = 1000 * getThreadGroupDelayAsInt();
long ascentPoint = testStartTime + threadGroupDelay;
int inUserPeriod = 1000 * getInUserPeriodAsInt();
int additionalRampUp = 1000 * getRampUpAsInt() / inUserCount;
int flightTime = 1000 * getFlightTimeAsInt();
int outUserPeriod = 1000 * getOutUserPeriodAsInt();
long rampUpDuration = 1000 * getRampUpAsInt();
long iterationDuration = inUserPeriod + rampUpDuration;
int iterationCountTotal = (int) Math.ceil((double) getNumThreads() / inUserCount) - 1;
int iterationCountBeforeMe = (int) Math.floor((double) thread.getThreadNum() / inUserCount);
long descentPoint = ascentPoint + iterationCountTotal * (iterationDuration+additionalRampUp) + additionalRampUp + flightTime;
long startTime = ascentPoint + iterationCountBeforeMe * iterationDuration + (thread.getThreadNum() % inUserCount) * additionalRampUp;
long endTime = descentPoint + outUserPeriod * (int) Math.floor((double) thread.getThreadNum() / outUserCount);
log.debug(String.format("threadNum=%d, rampUpDuration=%d, iterationDuration=%d, iterationCountTotal=%d, iterationCountBeforeMe=%d, ascentPoint=%d, descentPoint=%d, startTime=%d, endTime=%d",
thread.getThreadNum(), rampUpDuration, iterationDuration, iterationCountTotal, iterationCountBeforeMe, ascentPoint, descentPoint, startTime, endTime));
thread.setStartTime(startTime);
thread.setEndTime(endTime);
thread.setScheduled(true);
}
| public void scheduleThread(JMeterThread thread) {
int inUserCount = getInUserCountAsInt();
int outUserCount = getOutUserCountAsInt();
if(inUserCount == 0) inUserCount = getNumThreads();
if(outUserCount == 0) outUserCount = getNumThreads();
int threadGroupDelay = 1000 * getThreadGroupDelayAsInt();
long ascentPoint = testStartTime + threadGroupDelay;
int inUserPeriod = 1000 * getInUserPeriodAsInt();
int additionalRampUp = 1000 * getRampUpAsInt() / inUserCount;
int flightTime = 1000 * getFlightTimeAsInt();
int outUserPeriod = 1000 * getOutUserPeriodAsInt();
long rampUpDuration = 1000 * getRampUpAsInt();
long iterationDuration = inUserPeriod + rampUpDuration;
int iterationCountTotal = (int) Math.ceil((double) getNumThreads() / inUserCount) - 1;
int iterationCountBeforeMe = (int) Math.floor((double) thread.getThreadNum() / inUserCount);
long descentPoint = ascentPoint + iterationCountTotal * (iterationDuration+additionalRampUp) + rampUpDuration + flightTime;
long startTime = ascentPoint + iterationCountBeforeMe * iterationDuration + (thread.getThreadNum() % inUserCount) * additionalRampUp;
long endTime = descentPoint + outUserPeriod * (int) Math.floor((double) thread.getThreadNum() / outUserCount);
log.debug(String.format("threadNum=%d, rampUpDuration=%d, iterationDuration=%d, iterationCountTotal=%d, iterationCountBeforeMe=%d, ascentPoint=%d, descentPoint=%d, startTime=%d, endTime=%d",
thread.getThreadNum(), rampUpDuration, iterationDuration, iterationCountTotal, iterationCountBeforeMe, ascentPoint, descentPoint, startTime, endTime));
thread.setStartTime(startTime);
thread.setEndTime(endTime);
thread.setScheduled(true);
}
|
diff --git a/src/main/java/de/cismet/cids/custom/objecteditors/wunda_blau/NivellementPunktEditor.java b/src/main/java/de/cismet/cids/custom/objecteditors/wunda_blau/NivellementPunktEditor.java
index c41b60d0..b1752846 100644
--- a/src/main/java/de/cismet/cids/custom/objecteditors/wunda_blau/NivellementPunktEditor.java
+++ b/src/main/java/de/cismet/cids/custom/objecteditors/wunda_blau/NivellementPunktEditor.java
@@ -1,1492 +1,1495 @@
/***************************************************
*
* cismet GmbH, Saarbruecken, Germany
*
* ... and it just works.
*
****************************************************/
package de.cismet.cids.custom.objecteditors.wunda_blau;
import Sirius.navigator.ui.RequestsFullSizeComponent;
import Sirius.server.middleware.types.MetaObject;
import com.vividsolutions.jts.geom.Geometry;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.engine.util.JRLoader;
import org.apache.log4j.Logger;
import org.jdesktop.beansbinding.Converter;
import org.jdesktop.swingx.JXErrorPane;
import org.jdesktop.swingx.error.ErrorInfo;
import org.openide.util.NbBundle;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.concurrent.ExecutionException;
import java.util.logging.Level;
import javax.imageio.ImageIO;
import javax.swing.JComponent;
import javax.swing.JOptionPane;
import javax.swing.SwingWorker;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;
import de.cismet.cids.client.tools.DevelopmentTools;
import de.cismet.cids.custom.objectrenderer.utils.billing.BillingPopup;
import de.cismet.cids.custom.objectrenderer.utils.billing.ProductGroupAmount;
import de.cismet.cids.custom.objectrenderer.wunda_blau.NivellementPunktAggregationRenderer;
import de.cismet.cids.custom.utils.alkis.AlkisConstants;
import de.cismet.cids.dynamics.CidsBean;
import de.cismet.cids.dynamics.DisposableCidsBeanStore;
import de.cismet.cids.editors.DefaultBindableReferenceCombo;
import de.cismet.cids.editors.DefaultCustomObjectEditor;
import de.cismet.cids.editors.EditorClosedEvent;
import de.cismet.cids.editors.EditorSaveListener;
import de.cismet.cids.editors.converters.DoubleToStringConverter;
import de.cismet.cismap.cids.geometryeditor.DefaultCismapGeometryComboBoxEditor;
import de.cismet.cismap.commons.Crs;
import de.cismet.cismap.commons.XBoundingBox;
import de.cismet.cismap.commons.gui.measuring.MeasuringComponent;
import de.cismet.cismap.commons.gui.printing.JasperDownload;
import de.cismet.security.WebAccessManager;
import de.cismet.security.exceptions.AccessMethodIsNotSupportedException;
import de.cismet.security.exceptions.MissingArgumentException;
import de.cismet.security.exceptions.NoHandlerForURLException;
import de.cismet.security.exceptions.RequestFailedException;
import de.cismet.tools.CismetThreadPool;
import de.cismet.tools.gui.BorderProvider;
import de.cismet.tools.gui.FooterComponentProvider;
import de.cismet.tools.gui.StaticSwingTools;
import de.cismet.tools.gui.TitleComponentProvider;
import de.cismet.tools.gui.downloadmanager.DownloadManager;
import de.cismet.tools.gui.downloadmanager.DownloadManagerDialog;
import de.cismet.tools.gui.downloadmanager.HttpDownload;
/**
* DOCUMENT ME!
*
* @author jweintraut
* @version $Revision$, $Date$
*/
public class NivellementPunktEditor extends javax.swing.JPanel implements DisposableCidsBeanStore,
TitleComponentProvider,
FooterComponentProvider,
BorderProvider,
RequestsFullSizeComponent,
EditorSaveListener {
//~ Static fields/initializers ---------------------------------------------
private static final Logger LOG = Logger.getLogger(NivellementPunktEditor.class);
public static final String[] SUFFIXES = new String[] { "tif", "jpg", "tiff", "jpeg" };
protected static XBoundingBox INITIAL_BOUNDINGBOX = new XBoundingBox(
2583621.251964098d,
5682507.032498134d,
2584022.9413952776d,
5682742.852810634d,
AlkisConstants.COMMONS.SRS_SERVICE,
true);
protected static Crs CRS = new Crs(
AlkisConstants.COMMONS.SRS_SERVICE,
AlkisConstants.COMMONS.SRS_SERVICE,
AlkisConstants.COMMONS.SRS_SERVICE,
true,
true);
protected static final Converter<Double, String> CONVERTER_HOEHE = new DoubleToStringConverter();
//~ Instance fields --------------------------------------------------------
protected CidsBean cidsBean;
protected boolean readOnly;
protected String oldDgkBlattnummer;
protected String oldLaufendeNummer;
protected String urlOfDocument;
protected RefreshDocumentWorker currentRefreshDocumentWorker;
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.ButtonGroup bgrControls;
private javax.swing.JButton btnHome;
private javax.swing.JButton btnOpen;
private javax.swing.JButton btnReport;
private javax.swing.JCheckBox chkHistorisch;
private javax.swing.JComboBox cmbFestlegungsart;
private javax.swing.JComboBox cmbGeometrie;
private javax.swing.JComboBox cmbLagegenauigkeit;
private javax.swing.Box.Filler gluFillDescription;
private javax.swing.Box.Filler gluFiller;
private javax.swing.Box.Filler gluFillerControls;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel lblBemerkung;
private javax.swing.JLabel lblFestlegungsart;
private javax.swing.JLabel lblGeometrie;
private javax.swing.JLabel lblHeaderDocument;
private javax.swing.JLabel lblHistorisch;
private javax.swing.JLabel lblHoeheUeberNN;
private javax.swing.JLabel lblLagebezeichnung;
private javax.swing.JLabel lblLagegenauigkeit;
private javax.swing.JLabel lblMessungsjahr;
private javax.swing.JLabel lblMissingRasterdocument;
private javax.swing.JLabel lblPunktnummerNRW;
private javax.swing.JLabel lblPunktnummerWUP;
private javax.swing.JLabel lblPunktnummerWUPSeparator;
private javax.swing.JLabel lblTitle;
private de.cismet.cismap.commons.gui.measuring.MeasuringComponent measuringComponent;
private de.cismet.tools.gui.RoundedPanel pnlControls;
private de.cismet.tools.gui.RoundedPanel pnlDocument;
private de.cismet.tools.gui.SemiRoundedPanel pnlHeaderDocument;
private de.cismet.tools.gui.RoundedPanel pnlSimpleAttributes;
private javax.swing.JPanel pnlTitle;
private javax.swing.JScrollPane scpBemerkung;
private de.cismet.tools.gui.SemiRoundedPanel semiRoundedPanel4;
private javax.swing.Box.Filler strFooter;
private javax.swing.JToggleButton togPan;
private javax.swing.JToggleButton togZoom;
private javax.swing.JTextArea txaBemerkung;
private javax.swing.JTextField txtDGKBlattnummer;
private javax.swing.JTextField txtHoeheUeberNN;
private javax.swing.JTextField txtLagebezeichnung;
private javax.swing.JTextField txtLaufendeNummer;
private javax.swing.JTextField txtMessungsjahr;
private javax.swing.JTextField txtPunktnummerNRW;
private org.jdesktop.beansbinding.BindingGroup bindingGroup;
// End of variables declaration//GEN-END:variables
//~ Constructors -----------------------------------------------------------
/**
* Creates a new NivellementPunktEditor object.
*/
public NivellementPunktEditor() {
this(false);
}
/**
* Creates new form NivellementPunktEditor.
*
* @param readOnly DOCUMENT ME!
*/
public NivellementPunktEditor(final boolean readOnly) {
this.readOnly = readOnly;
initComponents();
setOpaque(false);
lblMissingRasterdocument.setVisible(false);
if (readOnly) {
txtDGKBlattnummer.setEditable(false);
txtLaufendeNummer.setEditable(false);
txtPunktnummerNRW.setEditable(false);
txtLagebezeichnung.setEditable(false);
cmbLagegenauigkeit.setEditable(false);
cmbLagegenauigkeit.setEnabled(false);
txtHoeheUeberNN.setEditable(false);
txtMessungsjahr.setEditable(false);
txaBemerkung.setEditable(false);
cmbFestlegungsart.setEditable(false);
cmbFestlegungsart.setEnabled(false);
lblGeometrie.setVisible(false);
chkHistorisch.setEnabled(false);
}
}
//~ Methods ----------------------------------------------------------------
/**
* 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">//GEN-BEGIN:initComponents
private void initComponents() {
java.awt.GridBagConstraints gridBagConstraints;
bindingGroup = new org.jdesktop.beansbinding.BindingGroup();
pnlTitle = new javax.swing.JPanel();
lblTitle = new javax.swing.JLabel();
bgrControls = new javax.swing.ButtonGroup();
strFooter = new javax.swing.Box.Filler(new java.awt.Dimension(0, 22),
new java.awt.Dimension(0, 22),
new java.awt.Dimension(32767, 22));
pnlSimpleAttributes = new de.cismet.tools.gui.RoundedPanel();
txtDGKBlattnummer = new javax.swing.JTextField();
lblHoeheUeberNN = new javax.swing.JLabel();
txtHoeheUeberNN = new javax.swing.JTextField();
lblFestlegungsart = new javax.swing.JLabel();
cmbFestlegungsart = new DefaultBindableReferenceCombo();
lblLagebezeichnung = new javax.swing.JLabel();
txtLagebezeichnung = new javax.swing.JTextField();
lblLagegenauigkeit = new javax.swing.JLabel();
cmbLagegenauigkeit = new DefaultBindableReferenceCombo();
lblMessungsjahr = new javax.swing.JLabel();
txtMessungsjahr = new javax.swing.JTextField();
lblPunktnummerNRW = new javax.swing.JLabel();
txtPunktnummerNRW = new javax.swing.JTextField();
lblBemerkung = new javax.swing.JLabel();
scpBemerkung = new javax.swing.JScrollPane();
txaBemerkung = new javax.swing.JTextArea();
lblGeometrie = new javax.swing.JLabel();
if (!readOnly) {
cmbGeometrie = new DefaultCismapGeometryComboBoxEditor();
}
lblPunktnummerWUP = new javax.swing.JLabel();
lblPunktnummerWUPSeparator = new javax.swing.JLabel();
gluFiller = new javax.swing.Box.Filler(new java.awt.Dimension(0, 0),
new java.awt.Dimension(0, 0),
new java.awt.Dimension(0, 32767));
txtLaufendeNummer = new javax.swing.JTextField();
lblHistorisch = new javax.swing.JLabel();
chkHistorisch = new javax.swing.JCheckBox();
gluFillDescription = new javax.swing.Box.Filler(new java.awt.Dimension(0, 0),
new java.awt.Dimension(0, 0),
new java.awt.Dimension(0, 32767));
pnlDocument = new de.cismet.tools.gui.RoundedPanel();
pnlHeaderDocument = new de.cismet.tools.gui.SemiRoundedPanel();
lblHeaderDocument = new javax.swing.JLabel();
measuringComponent = new MeasuringComponent(INITIAL_BOUNDINGBOX, CRS);
lblMissingRasterdocument = new javax.swing.JLabel();
pnlControls = new de.cismet.tools.gui.RoundedPanel();
togPan = new javax.swing.JToggleButton();
togZoom = new javax.swing.JToggleButton();
btnHome = new javax.swing.JButton();
semiRoundedPanel4 = new de.cismet.tools.gui.SemiRoundedPanel();
jLabel3 = new javax.swing.JLabel();
btnOpen = new javax.swing.JButton();
btnReport = new javax.swing.JButton();
gluFillerControls = new javax.swing.Box.Filler(new java.awt.Dimension(0, 0),
new java.awt.Dimension(0, 0),
new java.awt.Dimension(0, 32767));
pnlTitle.setOpaque(false);
pnlTitle.setLayout(new java.awt.GridBagLayout());
lblTitle.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
lblTitle.setForeground(java.awt.Color.white);
lblTitle.setText(org.openide.util.NbBundle.getMessage(
NivellementPunktEditor.class,
"NivellementPunktEditor.lblTitle.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.weightx = 0.1;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
pnlTitle.add(lblTitle, gridBagConstraints);
setOpaque(false);
setLayout(new java.awt.GridBagLayout());
pnlSimpleAttributes.setAlpha(0);
pnlSimpleAttributes.setLayout(new java.awt.GridBagLayout());
txtDGKBlattnummer.setMinimumSize(new java.awt.Dimension(100, 20));
txtDGKBlattnummer.setPreferredSize(new java.awt.Dimension(100, 20));
org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(
org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE,
this,
org.jdesktop.beansbinding.ELProperty.create("${cidsBean.dgk_blattnummer}"),
txtDGKBlattnummer,
org.jdesktop.beansbinding.BeanProperty.create("text"));
bindingGroup.addBinding(binding);
txtDGKBlattnummer.addFocusListener(new java.awt.event.FocusAdapter() {
@Override
public void focusGained(final java.awt.event.FocusEvent evt) {
txtDGKBlattnummerFocusGained(evt);
}
@Override
public void focusLost(final java.awt.event.FocusEvent evt) {
txtDGKBlattnummerFocusLost(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.weightx = 0.25;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
pnlSimpleAttributes.add(txtDGKBlattnummer, gridBagConstraints);
lblHoeheUeberNN.setText(org.openide.util.NbBundle.getMessage(
NivellementPunktEditor.class,
"NivellementPunktEditor.lblHoeheUeberNN.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
pnlSimpleAttributes.add(lblHoeheUeberNN, gridBagConstraints);
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(
org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE,
this,
org.jdesktop.beansbinding.ELProperty.create("${cidsBean.hoehe_ueber_nn}"),
txtHoeheUeberNN,
org.jdesktop.beansbinding.BeanProperty.create("text"));
binding.setConverter(CONVERTER_HOEHE);
bindingGroup.addBinding(binding);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 4;
gridBagConstraints.gridwidth = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
pnlSimpleAttributes.add(txtHoeheUeberNN, gridBagConstraints);
lblFestlegungsart.setText(org.openide.util.NbBundle.getMessage(
NivellementPunktEditor.class,
"NivellementPunktEditor.lblFestlegungsart.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 4;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
pnlSimpleAttributes.add(lblFestlegungsart, gridBagConstraints);
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(
org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE,
this,
org.jdesktop.beansbinding.ELProperty.create("${cidsBean.festlegungsart}"),
cmbFestlegungsart,
org.jdesktop.beansbinding.BeanProperty.create("selectedItem"));
bindingGroup.addBinding(binding);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 5;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.weightx = 0.5;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
pnlSimpleAttributes.add(cmbFestlegungsart, gridBagConstraints);
lblLagebezeichnung.setText(org.openide.util.NbBundle.getMessage(
NivellementPunktEditor.class,
"NivellementPunktEditor.lblLagebezeichnung.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(10, 5, 5, 5);
pnlSimpleAttributes.add(lblLagebezeichnung, gridBagConstraints);
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(
org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE,
this,
org.jdesktop.beansbinding.ELProperty.create("${cidsBean.lagebezeichnung}"),
txtLagebezeichnung,
org.jdesktop.beansbinding.BeanProperty.create("text"));
bindingGroup.addBinding(binding);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
gridBagConstraints.gridwidth = 5;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(10, 5, 5, 5);
pnlSimpleAttributes.add(txtLagebezeichnung, gridBagConstraints);
lblLagegenauigkeit.setText(org.openide.util.NbBundle.getMessage(
NivellementPunktEditor.class,
"NivellementPunktEditor.lblLagegenauigkeit.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 5;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
pnlSimpleAttributes.add(lblLagegenauigkeit, gridBagConstraints);
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(
org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE,
this,
org.jdesktop.beansbinding.ELProperty.create("${cidsBean.lagegenauigkeit}"),
cmbLagegenauigkeit,
org.jdesktop.beansbinding.BeanProperty.create("selectedItem"));
bindingGroup.addBinding(binding);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 5;
gridBagConstraints.gridwidth = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
pnlSimpleAttributes.add(cmbLagegenauigkeit, gridBagConstraints);
lblMessungsjahr.setText(org.openide.util.NbBundle.getMessage(
NivellementPunktEditor.class,
"NivellementPunktEditor.lblMessungsjahr.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
pnlSimpleAttributes.add(lblMessungsjahr, gridBagConstraints);
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(
org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE,
this,
org.jdesktop.beansbinding.ELProperty.create("${cidsBean.messungsjahr}"),
txtMessungsjahr,
org.jdesktop.beansbinding.BeanProperty.create("text"));
bindingGroup.addBinding(binding);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 3;
gridBagConstraints.gridwidth = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
pnlSimpleAttributes.add(txtMessungsjahr, gridBagConstraints);
lblPunktnummerNRW.setText(org.openide.util.NbBundle.getMessage(
NivellementPunktEditor.class,
"NivellementPunktEditor.lblPunktnummerNRW.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
pnlSimpleAttributes.add(lblPunktnummerNRW, gridBagConstraints);
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(
org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE,
this,
org.jdesktop.beansbinding.ELProperty.create("${cidsBean.punktnummer_nrw}"),
txtPunktnummerNRW,
org.jdesktop.beansbinding.BeanProperty.create("text"));
bindingGroup.addBinding(binding);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 2;
gridBagConstraints.gridwidth = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
pnlSimpleAttributes.add(txtPunktnummerNRW, gridBagConstraints);
lblBemerkung.setText(org.openide.util.NbBundle.getMessage(
NivellementPunktEditor.class,
"NivellementPunktEditor.lblBemerkung.text")); // NOI18N
lblBemerkung.setVerticalAlignment(javax.swing.SwingConstants.TOP);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 4;
gridBagConstraints.gridy = 3;
gridBagConstraints.gridheight = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
pnlSimpleAttributes.add(lblBemerkung, gridBagConstraints);
txaBemerkung.setColumns(20);
txaBemerkung.setRows(5);
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(
org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE,
this,
org.jdesktop.beansbinding.ELProperty.create("${cidsBean.bemerkung}"),
txaBemerkung,
org.jdesktop.beansbinding.BeanProperty.create("text"));
bindingGroup.addBinding(binding);
scpBemerkung.setViewportView(txaBemerkung);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 5;
gridBagConstraints.gridy = 3;
gridBagConstraints.gridheight = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
pnlSimpleAttributes.add(scpBemerkung, gridBagConstraints);
lblGeometrie.setText(org.openide.util.NbBundle.getMessage(
NivellementPunktEditor.class,
"NivellementPunktEditor.lblGeometrie.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 4;
gridBagConstraints.gridy = 7;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
pnlSimpleAttributes.add(lblGeometrie, gridBagConstraints);
if (!readOnly) {
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(
org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE,
this,
org.jdesktop.beansbinding.ELProperty.create("${cidsBean.geometrie}"),
cmbGeometrie,
org.jdesktop.beansbinding.BeanProperty.create("selectedItem"));
binding.setConverter(((DefaultCismapGeometryComboBoxEditor)cmbGeometrie).getConverter());
bindingGroup.addBinding(binding);
}
if (!readOnly) {
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 5;
gridBagConstraints.gridy = 7;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
pnlSimpleAttributes.add(cmbGeometrie, gridBagConstraints);
}
lblPunktnummerWUP.setText(org.openide.util.NbBundle.getMessage(
NivellementPunktEditor.class,
"NivellementPunktEditor.lblPunktnummerWUP.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
pnlSimpleAttributes.add(lblPunktnummerWUP, gridBagConstraints);
lblPunktnummerWUPSeparator.setText(org.openide.util.NbBundle.getMessage(
NivellementPunktEditor.class,
"NivellementPunktEditor.lblPunktnummerWUPSeparator.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 1;
pnlSimpleAttributes.add(lblPunktnummerWUPSeparator, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 8;
gridBagConstraints.gridwidth = 6;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
pnlSimpleAttributes.add(gluFiller, gridBagConstraints);
txtLaufendeNummer.setColumns(3);
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(
org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE,
this,
org.jdesktop.beansbinding.ELProperty.create("${cidsBean.laufende_nummer}"),
txtLaufendeNummer,
org.jdesktop.beansbinding.BeanProperty.create("text"));
bindingGroup.addBinding(binding);
txtLaufendeNummer.addFocusListener(new java.awt.event.FocusAdapter() {
@Override
public void focusGained(final java.awt.event.FocusEvent evt) {
txtLaufendeNummerFocusGained(evt);
}
@Override
public void focusLost(final java.awt.event.FocusEvent evt) {
txtLaufendeNummerFocusLost(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 3;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.weightx = 0.25;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
pnlSimpleAttributes.add(txtLaufendeNummer, gridBagConstraints);
lblHistorisch.setText(org.openide.util.NbBundle.getMessage(
NivellementPunktEditor.class,
"NivellementPunktEditor.lblHistorisch.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 4;
gridBagConstraints.gridy = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
pnlSimpleAttributes.add(lblHistorisch, gridBagConstraints);
chkHistorisch.setText(org.openide.util.NbBundle.getMessage(
NivellementPunktEditor.class,
"NivellementPunktEditor.chkHistorisch.text")); // NOI18N
chkHistorisch.setContentAreaFilled(false);
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(
org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE,
this,
org.jdesktop.beansbinding.ELProperty.create("${cidsBean.historisch}"),
chkHistorisch,
- org.jdesktop.beansbinding.BeanProperty.create("selected"));
+ org.jdesktop.beansbinding.BeanProperty.create("selected"),
+ "");
+ binding.setSourceNullValue(false);
+ binding.setSourceUnreadableValue(false);
bindingGroup.addBinding(binding);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 5;
gridBagConstraints.gridy = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
pnlSimpleAttributes.add(chkHistorisch, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 6;
gridBagConstraints.gridwidth = 4;
gridBagConstraints.gridheight = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
pnlSimpleAttributes.add(gluFillDescription, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(8, 0, 10, 0);
add(pnlSimpleAttributes, gridBagConstraints);
pnlDocument.setLayout(new java.awt.GridBagLayout());
pnlHeaderDocument.setBackground(java.awt.Color.darkGray);
pnlHeaderDocument.setLayout(new java.awt.GridBagLayout());
lblHeaderDocument.setForeground(java.awt.Color.white);
lblHeaderDocument.setText(org.openide.util.NbBundle.getMessage(
NivellementPunktEditor.class,
"NivellementPunktEditor.lblHeaderDocument.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
pnlHeaderDocument.add(lblHeaderDocument, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.weightx = 0.1;
pnlDocument.add(pnlHeaderDocument, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weighty = 0.1;
pnlDocument.add(measuringComponent, gridBagConstraints);
lblMissingRasterdocument.setBackground(java.awt.Color.white);
lblMissingRasterdocument.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
lblMissingRasterdocument.setIcon(new javax.swing.ImageIcon(
getClass().getResource("/de/cismet/cids/custom/objecteditors/wunda_blau/missingRasterdocument.png"))); // NOI18N
lblMissingRasterdocument.setText(org.openide.util.NbBundle.getMessage(
NivellementPunktEditor.class,
"NivellementPunktEditor.lblMissingRasterdocument.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weighty = 0.1;
pnlDocument.add(lblMissingRasterdocument, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.gridheight = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.weightx = 0.1;
gridBagConstraints.weighty = 0.1;
gridBagConstraints.insets = new java.awt.Insets(10, 0, 0, 5);
add(pnlDocument, gridBagConstraints);
pnlControls.setLayout(new java.awt.GridBagLayout());
bgrControls.add(togPan);
togPan.setIcon(new javax.swing.ImageIcon(
getClass().getResource("/de/cismet/cids/custom/wunda_blau/res/pan.gif"))); // NOI18N
togPan.setSelected(true);
togPan.setText(org.openide.util.NbBundle.getMessage(
NivellementPunktEditor.class,
"NivellementPunktEditor.togPan.text")); // NOI18N
togPan.setToolTipText(org.openide.util.NbBundle.getMessage(
NivellementPunktEditor.class,
"NivellementPunktEditor.togPan.toolTipText")); // NOI18N
togPan.setEnabled(false);
togPan.setFocusPainted(false);
togPan.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
togPan.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
togPanActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.insets = new java.awt.Insets(2, 5, 3, 5);
pnlControls.add(togPan, gridBagConstraints);
bgrControls.add(togZoom);
togZoom.setIcon(new javax.swing.ImageIcon(
getClass().getResource("/de/cismet/cids/custom/wunda_blau/res/zoom.gif"))); // NOI18N
togZoom.setText(org.openide.util.NbBundle.getMessage(
NivellementPunktEditor.class,
"NivellementPunktEditor.togZoom.text")); // NOI18N
togZoom.setToolTipText(org.openide.util.NbBundle.getMessage(
NivellementPunktEditor.class,
"NivellementPunktEditor.togZoom.toolTipText")); // NOI18N
togZoom.setEnabled(false);
togZoom.setFocusPainted(false);
togZoom.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
togZoom.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
togZoomActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.insets = new java.awt.Insets(2, 5, 3, 5);
pnlControls.add(togZoom, gridBagConstraints);
btnHome.setIcon(new javax.swing.ImageIcon(
getClass().getResource("/de/cismet/cids/custom/wunda_blau/res/home.gif"))); // NOI18N
btnHome.setText(org.openide.util.NbBundle.getMessage(
NivellementPunktEditor.class,
"NivellementPunktEditor.btnHome.text")); // NOI18N
btnHome.setToolTipText(org.openide.util.NbBundle.getMessage(
NivellementPunktEditor.class,
"NivellementPunktEditor.btnHome.toolTipText")); // NOI18N
btnHome.setEnabled(false);
btnHome.setFocusPainted(false);
btnHome.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
btnHome.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
btnHomeActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 3, 5);
pnlControls.add(btnHome, gridBagConstraints);
semiRoundedPanel4.setBackground(new java.awt.Color(51, 51, 51));
semiRoundedPanel4.setLayout(new java.awt.FlowLayout());
jLabel3.setForeground(new java.awt.Color(255, 255, 255));
jLabel3.setText(org.openide.util.NbBundle.getMessage(
NivellementPunktEditor.class,
"NivellementPunktEditor.jLabel3.text")); // NOI18N
semiRoundedPanel4.add(jLabel3);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
pnlControls.add(semiRoundedPanel4, gridBagConstraints);
btnOpen.setIcon(new javax.swing.ImageIcon(
getClass().getResource("/de/cismet/cids/custom/wunda_blau/res/folder-image.png"))); // NOI18N
btnOpen.setText(org.openide.util.NbBundle.getMessage(
NivellementPunktEditor.class,
"NivellementPunktEditor.btnOpen.text")); // NOI18N
btnOpen.setToolTipText(org.openide.util.NbBundle.getMessage(
NivellementPunktEditor.class,
"NivellementPunktEditor.btnOpen.toolTipText")); // NOI18N
btnOpen.setEnabled(false);
btnOpen.setFocusPainted(false);
btnOpen.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
btnOpen.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
btnOpenActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 7;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.insets = new java.awt.Insets(2, 5, 3, 5);
pnlControls.add(btnOpen, gridBagConstraints);
btnReport.setIcon(new javax.swing.ImageIcon(
getClass().getResource("/de/cismet/cids/custom/objecteditors/wunda_blau/printer.png"))); // NOI18N
btnReport.setText(org.openide.util.NbBundle.getMessage(
NivellementPunktEditor.class,
"NivellementPunktEditor.btnReport.text")); // NOI18N
btnReport.setFocusPainted(false);
btnReport.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
btnReportActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 8;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.insets = new java.awt.Insets(2, 5, 5, 5);
pnlControls.add(btnReport, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(10, 5, 0, 0);
add(pnlControls, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
add(gluFillerControls, gridBagConstraints);
bindingGroup.bind();
} // </editor-fold>//GEN-END:initComponents
/**
* DOCUMENT ME!
*
* @param evt DOCUMENT ME!
*/
private void togPanActionPerformed(final java.awt.event.ActionEvent evt) { //GEN-FIRST:event_togPanActionPerformed
measuringComponent.actionPan();
} //GEN-LAST:event_togPanActionPerformed
/**
* DOCUMENT ME!
*
* @param evt DOCUMENT ME!
*/
private void togZoomActionPerformed(final java.awt.event.ActionEvent evt) { //GEN-FIRST:event_togZoomActionPerformed
measuringComponent.actionZoom();
} //GEN-LAST:event_togZoomActionPerformed
/**
* DOCUMENT ME!
*
* @param evt DOCUMENT ME!
*/
private void btnHomeActionPerformed(final java.awt.event.ActionEvent evt) { //GEN-FIRST:event_btnHomeActionPerformed
measuringComponent.actionOverview();
} //GEN-LAST:event_btnHomeActionPerformed
/**
* DOCUMENT ME!
*
* @param evt DOCUMENT ME!
*/
private void btnOpenActionPerformed(final java.awt.event.ActionEvent evt) { //GEN-FIRST:event_btnOpenActionPerformed
try {
if (BillingPopup.doBilling(
"nivppdf",
urlOfDocument,
(Geometry)null,
new ProductGroupAmount("ea", 1))) {
openDoc(urlOfDocument);
}
} catch (Exception e) {
LOG.error("Error when trying to produce a alkis product", e);
// Hier noch ein Fehlerdialog
}
} //GEN-LAST:event_btnOpenActionPerformed
/**
* DOCUMENT ME!
*
* @param urlOfDocument DOCUMENT ME!
*/
private void openDoc(final String urlOfDocument) {
if (urlOfDocument != null) {
final URL url;
try {
url = new URL(urlOfDocument);
} catch (MalformedURLException ex) {
LOG.info("Couldn't download nivellement point from '" + urlOfDocument + "'.", ex);
return;
}
CismetThreadPool.execute(new Runnable() {
@Override
public void run() {
if (DownloadManagerDialog.showAskingForUserTitle(NivellementPunktEditor.this)) {
final String filename = urlOfDocument.substring(urlOfDocument.lastIndexOf("/") + 1);
DownloadManager.instance()
.add(
new HttpDownload(
url,
"",
DownloadManagerDialog.getJobname(),
"NivP-Beschreibung",
filename.substring(0, filename.lastIndexOf(".")),
filename.substring(filename.lastIndexOf("."))));
}
}
});
}
}
/**
* DOCUMENT ME!
*
* @param evt DOCUMENT ME!
*/
private void txtDGKBlattnummerFocusLost(final java.awt.event.FocusEvent evt) { //GEN-FIRST:event_txtDGKBlattnummerFocusLost
if ((oldDgkBlattnummer != null) && !oldDgkBlattnummer.equals(txtDGKBlattnummer.getText())) {
refreshImage();
}
} //GEN-LAST:event_txtDGKBlattnummerFocusLost
/**
* DOCUMENT ME!
*
* @param evt DOCUMENT ME!
*/
private void txtLaufendeNummerFocusLost(final java.awt.event.FocusEvent evt) { //GEN-FIRST:event_txtLaufendeNummerFocusLost
if ((oldLaufendeNummer != null) && !oldLaufendeNummer.equals(txtLaufendeNummer.getText())) {
refreshImage();
}
} //GEN-LAST:event_txtLaufendeNummerFocusLost
/**
* DOCUMENT ME!
*
* @param evt DOCUMENT ME!
*/
private void txtDGKBlattnummerFocusGained(final java.awt.event.FocusEvent evt) { //GEN-FIRST:event_txtDGKBlattnummerFocusGained
oldDgkBlattnummer = txtDGKBlattnummer.getText();
} //GEN-LAST:event_txtDGKBlattnummerFocusGained
/**
* DOCUMENT ME!
*
* @param evt DOCUMENT ME!
*/
private void txtLaufendeNummerFocusGained(final java.awt.event.FocusEvent evt) { //GEN-FIRST:event_txtLaufendeNummerFocusGained
oldLaufendeNummer = txtLaufendeNummer.getText();
} //GEN-LAST:event_txtLaufendeNummerFocusGained
/**
* DOCUMENT ME!
*
* @param evt DOCUMENT ME!
*/
private void btnReportActionPerformed(final java.awt.event.ActionEvent evt) { //GEN-FIRST:event_btnReportActionPerformed
try {
if (BillingPopup.doBilling(
"nivppdf",
"no.yet",
(Geometry)null,
new ProductGroupAmount("ea", 1))) {
downloadReport();
}
} catch (Exception e) {
LOG.error("Error when trying to produce a alkis product", e);
// Hier noch ein Fehlerdialog
}
} //GEN-LAST:event_btnReportActionPerformed
/**
* DOCUMENT ME!
*/
private void downloadReport() {
final Runnable runnable = new Runnable() {
@Override
public void run() {
final Collection<CidsBean> nivellementPunkte = new LinkedList<CidsBean>();
nivellementPunkte.add(cidsBean);
final Collection<NivellementPunktAggregationRenderer.NivellementPunktReportBean> reportBeans =
new LinkedList<NivellementPunktAggregationRenderer.NivellementPunktReportBean>();
reportBeans.add(new NivellementPunktAggregationRenderer.NivellementPunktReportBean(
nivellementPunkte));
final JRBeanCollectionDataSource dataSource = new JRBeanCollectionDataSource(reportBeans);
final HashMap parameters = new HashMap();
final JasperReport jasperReport;
final JasperPrint jasperPrint;
try {
jasperReport = (JasperReport)JRLoader.loadObject(getClass().getResourceAsStream(
"/de/cismet/cids/custom/wunda_blau/res/nivp.jasper"));
jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, dataSource);
} catch (JRException ex) {
LOG.error("Could not generate report for nivellement points.", ex);
final ErrorInfo ei = new ErrorInfo(NbBundle.getMessage(
NivellementPunktEditor.class,
"NivellementPunktEditor.btnReportActionPerformed(ActionEvent).ErrorInfo.title"), // NOI18N
NbBundle.getMessage(
NivellementPunktEditor.class,
"NivellementPunktEditor.btnReportActionPerformed(ActionEvent).ErrorInfo.message"), // NOI18N
null,
null,
ex,
Level.ALL,
null);
JXErrorPane.showDialog(NivellementPunktEditor.this, ei);
return;
}
if (DownloadManagerDialog.showAskingForUserTitle(NivellementPunktEditor.this)) {
final String jobname = DownloadManagerDialog.getJobname();
DownloadManager.instance()
.add(new JasperDownload(jasperPrint, jobname, "Nivellement-Punkt", "nivp"));
}
}
};
CismetThreadPool.execute(runnable);
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public static Crs getCrs() {
return CRS;
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public static XBoundingBox getInitialBoundingBox() {
return INITIAL_BOUNDINGBOX;
}
/**
* DOCUMENT ME!
*/
protected void refreshImage() {
if ((currentRefreshDocumentWorker != null) && !currentRefreshDocumentWorker.isDone()) {
currentRefreshDocumentWorker.cancel(true);
}
currentRefreshDocumentWorker = new RefreshDocumentWorker();
CismetThreadPool.execute(currentRefreshDocumentWorker);
}
/**
* DOCUMENT ME!
*
* @param dgkBlattnummer the value of dgkBlattnummer
* @param laufendeNummer the value of laufendeNummer
*
* @return DOCUMENT ME!
*/
public static Collection<URL> getCorrespondingURLs(final java.lang.String dgkBlattnummer,
final String laufendeNummer) {
final Collection<URL> validURLs = new LinkedList<URL>();
final StringBuilder urlBuilder = new StringBuilder(AlkisConstants.COMMONS.NIVP_HOST);
urlBuilder.append('/');
urlBuilder.append(dgkBlattnummer);
urlBuilder.append('/');
urlBuilder.append(AlkisConstants.COMMONS.NIVP_PREFIX);
urlBuilder.append(dgkBlattnummer);
urlBuilder.append(getFormattedLaufendeNummer(laufendeNummer));
urlBuilder.append('.');
for (final String suffix : SUFFIXES) {
URL urlToTry = null;
try {
urlToTry = new URL(urlBuilder.toString() + suffix);
} catch (MalformedURLException ex) {
LOG.warn("The URL '" + urlBuilder.toString() + suffix
+ "' is malformed. Can't load the corresponding picture.",
ex);
}
if (urlToTry != null) {
if (LOG.isDebugEnabled()) {
LOG.debug("Valid URL: " + urlToTry.toExternalForm());
}
validURLs.add(urlToTry);
}
}
return validURLs;
}
/**
* DOCUMENT ME!
*
* @param laufendeNummer DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
protected static String getFormattedLaufendeNummer(final String laufendeNummer) {
final StringBuilder result;
if (laufendeNummer == null) {
result = new StringBuilder("000");
} else {
result = new StringBuilder(laufendeNummer);
}
while (result.length() < 3) {
result.insert(0, "0");
}
return result.toString();
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
@Override
public CidsBean getCidsBean() {
return cidsBean;
}
/**
* DOCUMENT ME!
*
* @param cidsBean DOCUMENT ME!
*/
@Override
public void setCidsBean(final CidsBean cidsBean) {
bindingGroup.unbind();
if (cidsBean != null) {
this.cidsBean = cidsBean;
if (MetaObject.NEW == this.cidsBean.getMetaObject().getStatus()) {
try {
this.cidsBean.setProperty("dgk_blattnummer", "0000");
this.cidsBean.setProperty("laufende_nummer", "000");
this.cidsBean.setProperty("historisch", "false");
this.cidsBean.setProperty("hoehe_ueber_nn", Double.valueOf(0D));
} catch (Exception ex) {
LOG.warn("Could not set initial properties to new NivellementPunkt", ex);
}
}
DefaultCustomObjectEditor.setMetaClassInformationToMetaClassStoreComponentsInBindingGroup(
bindingGroup,
this.cidsBean);
bindingGroup.bind();
final String dgkBlattnummer = (String)cidsBean.getProperty("dgk_blattnummer");
final String laufendeNummer = (String)cidsBean.getProperty("laufende_nummer");
lblTitle.setText(NbBundle.getMessage(NivellementPunktEditor.class, "NivellementPunktEditor.lblTitle.text")
+ " " + dgkBlattnummer + getFormattedLaufendeNummer(laufendeNummer));
refreshImage();
}
}
/**
* DOCUMENT ME!
*/
@Override
public void dispose() {
bindingGroup.unbind();
// dispose panels here if necessary
measuringComponent.dispose();
if (!readOnly) {
((DefaultCismapGeometryComboBoxEditor)cmbGeometrie).dispose();
}
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
@Override
public JComponent getTitleComponent() {
return pnlTitle;
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
@Override
public Border getTitleBorder() {
return new EmptyBorder(10, 10, 10, 10);
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
@Override
public Border getFooterBorder() {
return new EmptyBorder(5, 5, 5, 5);
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
@Override
public Border getCenterrBorder() {
return new EmptyBorder(0, 5, 0, 5);
}
/**
* DOCUMENT ME!
*
* @param event DOCUMENT ME!
*/
@Override
public void editorClosed(final EditorClosedEvent event) {
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
@Override
public boolean prepareForSave() {
boolean save = true;
Float hoehe = null;
try {
hoehe = Float.valueOf(txtHoeheUeberNN.getText().replace(',', '.'));
} catch (NumberFormatException e) {
}
if (hoehe == null) {
save = false;
JOptionPane.showMessageDialog(
StaticSwingTools.getParentFrame(this),
"Die angegebene Höhe ist ungültig.",
"Fehler aufgetreten",
JOptionPane.WARNING_MESSAGE);
}
if ((txtDGKBlattnummer.getText() == null) || (txtDGKBlattnummer.getText().trim().length() <= 0)) {
save = false;
JOptionPane.showMessageDialog(
StaticSwingTools.getParentFrame(this),
"Die angegebene DGK-Blattnummer ist ungültig.",
"Fehler aufgetreten",
JOptionPane.WARNING_MESSAGE);
}
if ((txtLaufendeNummer.getText() == null) || (txtLaufendeNummer.getText().trim().length() <= 0)) {
save = false;
JOptionPane.showMessageDialog(
StaticSwingTools.getParentFrame(this),
"Die angegebene laufende Nummer ist ungültig.",
"Fehler aufgetreten",
JOptionPane.WARNING_MESSAGE);
}
return save;
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
@Override
public JComponent getFooterComponent() {
return strFooter;
}
/**
* DOCUMENT ME!
*
* @param args DOCUMENT ME!
*
* @throws Exception DOCUMENT ME!
*/
public static void main(final String[] args) throws Exception {
// final CidsBean cb = DevelopmentTools.createCidsBeanFromRMIConnectionOnLocalhost(
// "WUNDA_BLAU",
// "Administratoren",
// "admin",
// "sb",
// "GEOM",
// 83318655);
//
// System.out.println(cb.getProperty("geo_field"));
// cb.setProperty("geo_field", null);
// System.out.println("fertich");
// System.exit(0);
DevelopmentTools.createEditorInFrameFromRMIConnectionOnLocalhost(
"WUNDA_BLAU",
"Administratoren",
"admin",
"sb",
"nivellement_punkt",
6818,
// 6833,
1024,
768);
// DevelopmentTools.createRendererInFrameFromRMIConnectionOnLocalhost(
// "WUNDA_BLAU",
// "Administratoren",
// "admin",
// "sb",
// "nivellement_punkt",
// 4349,
// "Renderer",
// 1024,
// 768);
}
//~ Inner Classes ----------------------------------------------------------
/**
* DOCUMENT ME!
*
* @version $Revision$, $Date$
*/
class RefreshDocumentWorker extends SwingWorker<BufferedImage, Object> {
//~ Methods ------------------------------------------------------------
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*
* @throws Exception DOCUMENT ME!
*/
@Override
protected BufferedImage doInBackground() throws Exception {
final Collection<URL> validURLs = getCorrespondingURLs(txtDGKBlattnummer.getText(),
txtLaufendeNummer.getText());
InputStream streamToReadFrom = null;
for (final URL url : validURLs) {
try {
streamToReadFrom = WebAccessManager.getInstance().doRequest(url);
urlOfDocument = url.toExternalForm();
break;
} catch (MissingArgumentException ex) {
LOG.warn("Could not read document from URL '" + url.toExternalForm() + "'. Skipping this url.", ex);
} catch (AccessMethodIsNotSupportedException ex) {
LOG.warn("Can't access document URL '" + url.toExternalForm()
+ "' with default access method. Skipping this url.",
ex);
} catch (RequestFailedException ex) {
LOG.warn("Requesting document from URL '" + url.toExternalForm() + "' failed. Skipping this url.",
ex);
} catch (NoHandlerForURLException ex) {
LOG.warn("Can't handle URL '" + url.toExternalForm() + "'. Skipping this url.", ex);
} catch (Exception ex) {
LOG.warn("An exception occurred while opening URL '" + url.toExternalForm()
+ "'. Skipping this url.",
ex);
}
}
BufferedImage result = null;
if (streamToReadFrom == null) {
LOG.error("Couldn't get a connection to associated document.");
urlOfDocument = null;
} else if (LOG.isDebugEnabled()) {
LOG.debug("Loading '" + urlOfDocument + "'.");
}
try {
result = ImageIO.read(streamToReadFrom);
} catch (IOException ex) {
LOG.warn("Could not read image.", ex);
urlOfDocument = null;
} finally {
try {
if (streamToReadFrom != null) {
streamToReadFrom.close();
}
} catch (IOException ex) {
LOG.warn("Couldn't close the stream.", ex);
}
}
return result;
}
/**
* DOCUMENT ME!
*/
@Override
protected void done() {
BufferedImage document = null;
try {
if (!isCancelled()) {
document = get();
}
} catch (InterruptedException ex) {
LOG.warn("Was interrupted while refreshing document.", ex);
} catch (ExecutionException ex) {
LOG.warn("There was an exception while refreshing document.", ex);
}
measuringComponent.reset();
if ((document != null) && !isCancelled()) {
measuringComponent.setVisible(true);
lblMissingRasterdocument.setVisible(false);
measuringComponent.addImage(document);
measuringComponent.zoomToFeatureCollection();
btnHome.setEnabled(true);
btnOpen.setEnabled(BillingPopup.isBillingAllowed());
btnReport.setEnabled(BillingPopup.isBillingAllowed());
togPan.setEnabled(true);
togZoom.setEnabled(true);
} else {
measuringComponent.setVisible(false);
lblMissingRasterdocument.setVisible(true);
btnHome.setEnabled(false);
btnOpen.setEnabled(false);
btnReport.setEnabled(false);
togPan.setEnabled(false);
togZoom.setEnabled(false);
}
}
}
}
| true | true | private void initComponents() {
java.awt.GridBagConstraints gridBagConstraints;
bindingGroup = new org.jdesktop.beansbinding.BindingGroup();
pnlTitle = new javax.swing.JPanel();
lblTitle = new javax.swing.JLabel();
bgrControls = new javax.swing.ButtonGroup();
strFooter = new javax.swing.Box.Filler(new java.awt.Dimension(0, 22),
new java.awt.Dimension(0, 22),
new java.awt.Dimension(32767, 22));
pnlSimpleAttributes = new de.cismet.tools.gui.RoundedPanel();
txtDGKBlattnummer = new javax.swing.JTextField();
lblHoeheUeberNN = new javax.swing.JLabel();
txtHoeheUeberNN = new javax.swing.JTextField();
lblFestlegungsart = new javax.swing.JLabel();
cmbFestlegungsart = new DefaultBindableReferenceCombo();
lblLagebezeichnung = new javax.swing.JLabel();
txtLagebezeichnung = new javax.swing.JTextField();
lblLagegenauigkeit = new javax.swing.JLabel();
cmbLagegenauigkeit = new DefaultBindableReferenceCombo();
lblMessungsjahr = new javax.swing.JLabel();
txtMessungsjahr = new javax.swing.JTextField();
lblPunktnummerNRW = new javax.swing.JLabel();
txtPunktnummerNRW = new javax.swing.JTextField();
lblBemerkung = new javax.swing.JLabel();
scpBemerkung = new javax.swing.JScrollPane();
txaBemerkung = new javax.swing.JTextArea();
lblGeometrie = new javax.swing.JLabel();
if (!readOnly) {
cmbGeometrie = new DefaultCismapGeometryComboBoxEditor();
}
lblPunktnummerWUP = new javax.swing.JLabel();
lblPunktnummerWUPSeparator = new javax.swing.JLabel();
gluFiller = new javax.swing.Box.Filler(new java.awt.Dimension(0, 0),
new java.awt.Dimension(0, 0),
new java.awt.Dimension(0, 32767));
txtLaufendeNummer = new javax.swing.JTextField();
lblHistorisch = new javax.swing.JLabel();
chkHistorisch = new javax.swing.JCheckBox();
gluFillDescription = new javax.swing.Box.Filler(new java.awt.Dimension(0, 0),
new java.awt.Dimension(0, 0),
new java.awt.Dimension(0, 32767));
pnlDocument = new de.cismet.tools.gui.RoundedPanel();
pnlHeaderDocument = new de.cismet.tools.gui.SemiRoundedPanel();
lblHeaderDocument = new javax.swing.JLabel();
measuringComponent = new MeasuringComponent(INITIAL_BOUNDINGBOX, CRS);
lblMissingRasterdocument = new javax.swing.JLabel();
pnlControls = new de.cismet.tools.gui.RoundedPanel();
togPan = new javax.swing.JToggleButton();
togZoom = new javax.swing.JToggleButton();
btnHome = new javax.swing.JButton();
semiRoundedPanel4 = new de.cismet.tools.gui.SemiRoundedPanel();
jLabel3 = new javax.swing.JLabel();
btnOpen = new javax.swing.JButton();
btnReport = new javax.swing.JButton();
gluFillerControls = new javax.swing.Box.Filler(new java.awt.Dimension(0, 0),
new java.awt.Dimension(0, 0),
new java.awt.Dimension(0, 32767));
pnlTitle.setOpaque(false);
pnlTitle.setLayout(new java.awt.GridBagLayout());
lblTitle.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
lblTitle.setForeground(java.awt.Color.white);
lblTitle.setText(org.openide.util.NbBundle.getMessage(
NivellementPunktEditor.class,
"NivellementPunktEditor.lblTitle.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.weightx = 0.1;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
pnlTitle.add(lblTitle, gridBagConstraints);
setOpaque(false);
setLayout(new java.awt.GridBagLayout());
pnlSimpleAttributes.setAlpha(0);
pnlSimpleAttributes.setLayout(new java.awt.GridBagLayout());
txtDGKBlattnummer.setMinimumSize(new java.awt.Dimension(100, 20));
txtDGKBlattnummer.setPreferredSize(new java.awt.Dimension(100, 20));
org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(
org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE,
this,
org.jdesktop.beansbinding.ELProperty.create("${cidsBean.dgk_blattnummer}"),
txtDGKBlattnummer,
org.jdesktop.beansbinding.BeanProperty.create("text"));
bindingGroup.addBinding(binding);
txtDGKBlattnummer.addFocusListener(new java.awt.event.FocusAdapter() {
@Override
public void focusGained(final java.awt.event.FocusEvent evt) {
txtDGKBlattnummerFocusGained(evt);
}
@Override
public void focusLost(final java.awt.event.FocusEvent evt) {
txtDGKBlattnummerFocusLost(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.weightx = 0.25;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
pnlSimpleAttributes.add(txtDGKBlattnummer, gridBagConstraints);
lblHoeheUeberNN.setText(org.openide.util.NbBundle.getMessage(
NivellementPunktEditor.class,
"NivellementPunktEditor.lblHoeheUeberNN.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
pnlSimpleAttributes.add(lblHoeheUeberNN, gridBagConstraints);
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(
org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE,
this,
org.jdesktop.beansbinding.ELProperty.create("${cidsBean.hoehe_ueber_nn}"),
txtHoeheUeberNN,
org.jdesktop.beansbinding.BeanProperty.create("text"));
binding.setConverter(CONVERTER_HOEHE);
bindingGroup.addBinding(binding);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 4;
gridBagConstraints.gridwidth = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
pnlSimpleAttributes.add(txtHoeheUeberNN, gridBagConstraints);
lblFestlegungsart.setText(org.openide.util.NbBundle.getMessage(
NivellementPunktEditor.class,
"NivellementPunktEditor.lblFestlegungsart.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 4;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
pnlSimpleAttributes.add(lblFestlegungsart, gridBagConstraints);
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(
org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE,
this,
org.jdesktop.beansbinding.ELProperty.create("${cidsBean.festlegungsart}"),
cmbFestlegungsart,
org.jdesktop.beansbinding.BeanProperty.create("selectedItem"));
bindingGroup.addBinding(binding);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 5;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.weightx = 0.5;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
pnlSimpleAttributes.add(cmbFestlegungsart, gridBagConstraints);
lblLagebezeichnung.setText(org.openide.util.NbBundle.getMessage(
NivellementPunktEditor.class,
"NivellementPunktEditor.lblLagebezeichnung.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(10, 5, 5, 5);
pnlSimpleAttributes.add(lblLagebezeichnung, gridBagConstraints);
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(
org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE,
this,
org.jdesktop.beansbinding.ELProperty.create("${cidsBean.lagebezeichnung}"),
txtLagebezeichnung,
org.jdesktop.beansbinding.BeanProperty.create("text"));
bindingGroup.addBinding(binding);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
gridBagConstraints.gridwidth = 5;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(10, 5, 5, 5);
pnlSimpleAttributes.add(txtLagebezeichnung, gridBagConstraints);
lblLagegenauigkeit.setText(org.openide.util.NbBundle.getMessage(
NivellementPunktEditor.class,
"NivellementPunktEditor.lblLagegenauigkeit.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 5;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
pnlSimpleAttributes.add(lblLagegenauigkeit, gridBagConstraints);
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(
org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE,
this,
org.jdesktop.beansbinding.ELProperty.create("${cidsBean.lagegenauigkeit}"),
cmbLagegenauigkeit,
org.jdesktop.beansbinding.BeanProperty.create("selectedItem"));
bindingGroup.addBinding(binding);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 5;
gridBagConstraints.gridwidth = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
pnlSimpleAttributes.add(cmbLagegenauigkeit, gridBagConstraints);
lblMessungsjahr.setText(org.openide.util.NbBundle.getMessage(
NivellementPunktEditor.class,
"NivellementPunktEditor.lblMessungsjahr.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
pnlSimpleAttributes.add(lblMessungsjahr, gridBagConstraints);
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(
org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE,
this,
org.jdesktop.beansbinding.ELProperty.create("${cidsBean.messungsjahr}"),
txtMessungsjahr,
org.jdesktop.beansbinding.BeanProperty.create("text"));
bindingGroup.addBinding(binding);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 3;
gridBagConstraints.gridwidth = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
pnlSimpleAttributes.add(txtMessungsjahr, gridBagConstraints);
lblPunktnummerNRW.setText(org.openide.util.NbBundle.getMessage(
NivellementPunktEditor.class,
"NivellementPunktEditor.lblPunktnummerNRW.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
pnlSimpleAttributes.add(lblPunktnummerNRW, gridBagConstraints);
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(
org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE,
this,
org.jdesktop.beansbinding.ELProperty.create("${cidsBean.punktnummer_nrw}"),
txtPunktnummerNRW,
org.jdesktop.beansbinding.BeanProperty.create("text"));
bindingGroup.addBinding(binding);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 2;
gridBagConstraints.gridwidth = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
pnlSimpleAttributes.add(txtPunktnummerNRW, gridBagConstraints);
lblBemerkung.setText(org.openide.util.NbBundle.getMessage(
NivellementPunktEditor.class,
"NivellementPunktEditor.lblBemerkung.text")); // NOI18N
lblBemerkung.setVerticalAlignment(javax.swing.SwingConstants.TOP);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 4;
gridBagConstraints.gridy = 3;
gridBagConstraints.gridheight = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
pnlSimpleAttributes.add(lblBemerkung, gridBagConstraints);
txaBemerkung.setColumns(20);
txaBemerkung.setRows(5);
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(
org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE,
this,
org.jdesktop.beansbinding.ELProperty.create("${cidsBean.bemerkung}"),
txaBemerkung,
org.jdesktop.beansbinding.BeanProperty.create("text"));
bindingGroup.addBinding(binding);
scpBemerkung.setViewportView(txaBemerkung);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 5;
gridBagConstraints.gridy = 3;
gridBagConstraints.gridheight = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
pnlSimpleAttributes.add(scpBemerkung, gridBagConstraints);
lblGeometrie.setText(org.openide.util.NbBundle.getMessage(
NivellementPunktEditor.class,
"NivellementPunktEditor.lblGeometrie.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 4;
gridBagConstraints.gridy = 7;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
pnlSimpleAttributes.add(lblGeometrie, gridBagConstraints);
if (!readOnly) {
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(
org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE,
this,
org.jdesktop.beansbinding.ELProperty.create("${cidsBean.geometrie}"),
cmbGeometrie,
org.jdesktop.beansbinding.BeanProperty.create("selectedItem"));
binding.setConverter(((DefaultCismapGeometryComboBoxEditor)cmbGeometrie).getConverter());
bindingGroup.addBinding(binding);
}
if (!readOnly) {
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 5;
gridBagConstraints.gridy = 7;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
pnlSimpleAttributes.add(cmbGeometrie, gridBagConstraints);
}
lblPunktnummerWUP.setText(org.openide.util.NbBundle.getMessage(
NivellementPunktEditor.class,
"NivellementPunktEditor.lblPunktnummerWUP.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
pnlSimpleAttributes.add(lblPunktnummerWUP, gridBagConstraints);
lblPunktnummerWUPSeparator.setText(org.openide.util.NbBundle.getMessage(
NivellementPunktEditor.class,
"NivellementPunktEditor.lblPunktnummerWUPSeparator.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 1;
pnlSimpleAttributes.add(lblPunktnummerWUPSeparator, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 8;
gridBagConstraints.gridwidth = 6;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
pnlSimpleAttributes.add(gluFiller, gridBagConstraints);
txtLaufendeNummer.setColumns(3);
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(
org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE,
this,
org.jdesktop.beansbinding.ELProperty.create("${cidsBean.laufende_nummer}"),
txtLaufendeNummer,
org.jdesktop.beansbinding.BeanProperty.create("text"));
bindingGroup.addBinding(binding);
txtLaufendeNummer.addFocusListener(new java.awt.event.FocusAdapter() {
@Override
public void focusGained(final java.awt.event.FocusEvent evt) {
txtLaufendeNummerFocusGained(evt);
}
@Override
public void focusLost(final java.awt.event.FocusEvent evt) {
txtLaufendeNummerFocusLost(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 3;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.weightx = 0.25;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
pnlSimpleAttributes.add(txtLaufendeNummer, gridBagConstraints);
lblHistorisch.setText(org.openide.util.NbBundle.getMessage(
NivellementPunktEditor.class,
"NivellementPunktEditor.lblHistorisch.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 4;
gridBagConstraints.gridy = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
pnlSimpleAttributes.add(lblHistorisch, gridBagConstraints);
chkHistorisch.setText(org.openide.util.NbBundle.getMessage(
NivellementPunktEditor.class,
"NivellementPunktEditor.chkHistorisch.text")); // NOI18N
chkHistorisch.setContentAreaFilled(false);
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(
org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE,
this,
org.jdesktop.beansbinding.ELProperty.create("${cidsBean.historisch}"),
chkHistorisch,
org.jdesktop.beansbinding.BeanProperty.create("selected"));
bindingGroup.addBinding(binding);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 5;
gridBagConstraints.gridy = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
pnlSimpleAttributes.add(chkHistorisch, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 6;
gridBagConstraints.gridwidth = 4;
gridBagConstraints.gridheight = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
pnlSimpleAttributes.add(gluFillDescription, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(8, 0, 10, 0);
add(pnlSimpleAttributes, gridBagConstraints);
pnlDocument.setLayout(new java.awt.GridBagLayout());
pnlHeaderDocument.setBackground(java.awt.Color.darkGray);
pnlHeaderDocument.setLayout(new java.awt.GridBagLayout());
lblHeaderDocument.setForeground(java.awt.Color.white);
lblHeaderDocument.setText(org.openide.util.NbBundle.getMessage(
NivellementPunktEditor.class,
"NivellementPunktEditor.lblHeaderDocument.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
pnlHeaderDocument.add(lblHeaderDocument, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.weightx = 0.1;
pnlDocument.add(pnlHeaderDocument, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weighty = 0.1;
pnlDocument.add(measuringComponent, gridBagConstraints);
lblMissingRasterdocument.setBackground(java.awt.Color.white);
lblMissingRasterdocument.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
lblMissingRasterdocument.setIcon(new javax.swing.ImageIcon(
getClass().getResource("/de/cismet/cids/custom/objecteditors/wunda_blau/missingRasterdocument.png"))); // NOI18N
lblMissingRasterdocument.setText(org.openide.util.NbBundle.getMessage(
NivellementPunktEditor.class,
"NivellementPunktEditor.lblMissingRasterdocument.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weighty = 0.1;
pnlDocument.add(lblMissingRasterdocument, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.gridheight = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.weightx = 0.1;
gridBagConstraints.weighty = 0.1;
gridBagConstraints.insets = new java.awt.Insets(10, 0, 0, 5);
add(pnlDocument, gridBagConstraints);
pnlControls.setLayout(new java.awt.GridBagLayout());
bgrControls.add(togPan);
togPan.setIcon(new javax.swing.ImageIcon(
getClass().getResource("/de/cismet/cids/custom/wunda_blau/res/pan.gif"))); // NOI18N
togPan.setSelected(true);
togPan.setText(org.openide.util.NbBundle.getMessage(
NivellementPunktEditor.class,
"NivellementPunktEditor.togPan.text")); // NOI18N
togPan.setToolTipText(org.openide.util.NbBundle.getMessage(
NivellementPunktEditor.class,
"NivellementPunktEditor.togPan.toolTipText")); // NOI18N
togPan.setEnabled(false);
togPan.setFocusPainted(false);
togPan.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
togPan.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
togPanActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.insets = new java.awt.Insets(2, 5, 3, 5);
pnlControls.add(togPan, gridBagConstraints);
bgrControls.add(togZoom);
togZoom.setIcon(new javax.swing.ImageIcon(
getClass().getResource("/de/cismet/cids/custom/wunda_blau/res/zoom.gif"))); // NOI18N
togZoom.setText(org.openide.util.NbBundle.getMessage(
NivellementPunktEditor.class,
"NivellementPunktEditor.togZoom.text")); // NOI18N
togZoom.setToolTipText(org.openide.util.NbBundle.getMessage(
NivellementPunktEditor.class,
"NivellementPunktEditor.togZoom.toolTipText")); // NOI18N
togZoom.setEnabled(false);
togZoom.setFocusPainted(false);
togZoom.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
togZoom.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
togZoomActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.insets = new java.awt.Insets(2, 5, 3, 5);
pnlControls.add(togZoom, gridBagConstraints);
btnHome.setIcon(new javax.swing.ImageIcon(
getClass().getResource("/de/cismet/cids/custom/wunda_blau/res/home.gif"))); // NOI18N
btnHome.setText(org.openide.util.NbBundle.getMessage(
NivellementPunktEditor.class,
"NivellementPunktEditor.btnHome.text")); // NOI18N
btnHome.setToolTipText(org.openide.util.NbBundle.getMessage(
NivellementPunktEditor.class,
"NivellementPunktEditor.btnHome.toolTipText")); // NOI18N
btnHome.setEnabled(false);
btnHome.setFocusPainted(false);
btnHome.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
btnHome.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
btnHomeActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 3, 5);
pnlControls.add(btnHome, gridBagConstraints);
semiRoundedPanel4.setBackground(new java.awt.Color(51, 51, 51));
semiRoundedPanel4.setLayout(new java.awt.FlowLayout());
jLabel3.setForeground(new java.awt.Color(255, 255, 255));
jLabel3.setText(org.openide.util.NbBundle.getMessage(
NivellementPunktEditor.class,
"NivellementPunktEditor.jLabel3.text")); // NOI18N
semiRoundedPanel4.add(jLabel3);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
pnlControls.add(semiRoundedPanel4, gridBagConstraints);
btnOpen.setIcon(new javax.swing.ImageIcon(
getClass().getResource("/de/cismet/cids/custom/wunda_blau/res/folder-image.png"))); // NOI18N
btnOpen.setText(org.openide.util.NbBundle.getMessage(
NivellementPunktEditor.class,
"NivellementPunktEditor.btnOpen.text")); // NOI18N
btnOpen.setToolTipText(org.openide.util.NbBundle.getMessage(
NivellementPunktEditor.class,
"NivellementPunktEditor.btnOpen.toolTipText")); // NOI18N
btnOpen.setEnabled(false);
btnOpen.setFocusPainted(false);
btnOpen.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
btnOpen.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
btnOpenActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 7;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.insets = new java.awt.Insets(2, 5, 3, 5);
pnlControls.add(btnOpen, gridBagConstraints);
btnReport.setIcon(new javax.swing.ImageIcon(
getClass().getResource("/de/cismet/cids/custom/objecteditors/wunda_blau/printer.png"))); // NOI18N
btnReport.setText(org.openide.util.NbBundle.getMessage(
NivellementPunktEditor.class,
"NivellementPunktEditor.btnReport.text")); // NOI18N
btnReport.setFocusPainted(false);
btnReport.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
btnReportActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 8;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.insets = new java.awt.Insets(2, 5, 5, 5);
pnlControls.add(btnReport, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(10, 5, 0, 0);
add(pnlControls, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
add(gluFillerControls, gridBagConstraints);
bindingGroup.bind();
} // </editor-fold>//GEN-END:initComponents
| private void initComponents() {
java.awt.GridBagConstraints gridBagConstraints;
bindingGroup = new org.jdesktop.beansbinding.BindingGroup();
pnlTitle = new javax.swing.JPanel();
lblTitle = new javax.swing.JLabel();
bgrControls = new javax.swing.ButtonGroup();
strFooter = new javax.swing.Box.Filler(new java.awt.Dimension(0, 22),
new java.awt.Dimension(0, 22),
new java.awt.Dimension(32767, 22));
pnlSimpleAttributes = new de.cismet.tools.gui.RoundedPanel();
txtDGKBlattnummer = new javax.swing.JTextField();
lblHoeheUeberNN = new javax.swing.JLabel();
txtHoeheUeberNN = new javax.swing.JTextField();
lblFestlegungsart = new javax.swing.JLabel();
cmbFestlegungsart = new DefaultBindableReferenceCombo();
lblLagebezeichnung = new javax.swing.JLabel();
txtLagebezeichnung = new javax.swing.JTextField();
lblLagegenauigkeit = new javax.swing.JLabel();
cmbLagegenauigkeit = new DefaultBindableReferenceCombo();
lblMessungsjahr = new javax.swing.JLabel();
txtMessungsjahr = new javax.swing.JTextField();
lblPunktnummerNRW = new javax.swing.JLabel();
txtPunktnummerNRW = new javax.swing.JTextField();
lblBemerkung = new javax.swing.JLabel();
scpBemerkung = new javax.swing.JScrollPane();
txaBemerkung = new javax.swing.JTextArea();
lblGeometrie = new javax.swing.JLabel();
if (!readOnly) {
cmbGeometrie = new DefaultCismapGeometryComboBoxEditor();
}
lblPunktnummerWUP = new javax.swing.JLabel();
lblPunktnummerWUPSeparator = new javax.swing.JLabel();
gluFiller = new javax.swing.Box.Filler(new java.awt.Dimension(0, 0),
new java.awt.Dimension(0, 0),
new java.awt.Dimension(0, 32767));
txtLaufendeNummer = new javax.swing.JTextField();
lblHistorisch = new javax.swing.JLabel();
chkHistorisch = new javax.swing.JCheckBox();
gluFillDescription = new javax.swing.Box.Filler(new java.awt.Dimension(0, 0),
new java.awt.Dimension(0, 0),
new java.awt.Dimension(0, 32767));
pnlDocument = new de.cismet.tools.gui.RoundedPanel();
pnlHeaderDocument = new de.cismet.tools.gui.SemiRoundedPanel();
lblHeaderDocument = new javax.swing.JLabel();
measuringComponent = new MeasuringComponent(INITIAL_BOUNDINGBOX, CRS);
lblMissingRasterdocument = new javax.swing.JLabel();
pnlControls = new de.cismet.tools.gui.RoundedPanel();
togPan = new javax.swing.JToggleButton();
togZoom = new javax.swing.JToggleButton();
btnHome = new javax.swing.JButton();
semiRoundedPanel4 = new de.cismet.tools.gui.SemiRoundedPanel();
jLabel3 = new javax.swing.JLabel();
btnOpen = new javax.swing.JButton();
btnReport = new javax.swing.JButton();
gluFillerControls = new javax.swing.Box.Filler(new java.awt.Dimension(0, 0),
new java.awt.Dimension(0, 0),
new java.awt.Dimension(0, 32767));
pnlTitle.setOpaque(false);
pnlTitle.setLayout(new java.awt.GridBagLayout());
lblTitle.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
lblTitle.setForeground(java.awt.Color.white);
lblTitle.setText(org.openide.util.NbBundle.getMessage(
NivellementPunktEditor.class,
"NivellementPunktEditor.lblTitle.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.weightx = 0.1;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
pnlTitle.add(lblTitle, gridBagConstraints);
setOpaque(false);
setLayout(new java.awt.GridBagLayout());
pnlSimpleAttributes.setAlpha(0);
pnlSimpleAttributes.setLayout(new java.awt.GridBagLayout());
txtDGKBlattnummer.setMinimumSize(new java.awt.Dimension(100, 20));
txtDGKBlattnummer.setPreferredSize(new java.awt.Dimension(100, 20));
org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(
org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE,
this,
org.jdesktop.beansbinding.ELProperty.create("${cidsBean.dgk_blattnummer}"),
txtDGKBlattnummer,
org.jdesktop.beansbinding.BeanProperty.create("text"));
bindingGroup.addBinding(binding);
txtDGKBlattnummer.addFocusListener(new java.awt.event.FocusAdapter() {
@Override
public void focusGained(final java.awt.event.FocusEvent evt) {
txtDGKBlattnummerFocusGained(evt);
}
@Override
public void focusLost(final java.awt.event.FocusEvent evt) {
txtDGKBlattnummerFocusLost(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.weightx = 0.25;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
pnlSimpleAttributes.add(txtDGKBlattnummer, gridBagConstraints);
lblHoeheUeberNN.setText(org.openide.util.NbBundle.getMessage(
NivellementPunktEditor.class,
"NivellementPunktEditor.lblHoeheUeberNN.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
pnlSimpleAttributes.add(lblHoeheUeberNN, gridBagConstraints);
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(
org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE,
this,
org.jdesktop.beansbinding.ELProperty.create("${cidsBean.hoehe_ueber_nn}"),
txtHoeheUeberNN,
org.jdesktop.beansbinding.BeanProperty.create("text"));
binding.setConverter(CONVERTER_HOEHE);
bindingGroup.addBinding(binding);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 4;
gridBagConstraints.gridwidth = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
pnlSimpleAttributes.add(txtHoeheUeberNN, gridBagConstraints);
lblFestlegungsart.setText(org.openide.util.NbBundle.getMessage(
NivellementPunktEditor.class,
"NivellementPunktEditor.lblFestlegungsart.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 4;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
pnlSimpleAttributes.add(lblFestlegungsart, gridBagConstraints);
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(
org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE,
this,
org.jdesktop.beansbinding.ELProperty.create("${cidsBean.festlegungsart}"),
cmbFestlegungsart,
org.jdesktop.beansbinding.BeanProperty.create("selectedItem"));
bindingGroup.addBinding(binding);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 5;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.weightx = 0.5;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
pnlSimpleAttributes.add(cmbFestlegungsart, gridBagConstraints);
lblLagebezeichnung.setText(org.openide.util.NbBundle.getMessage(
NivellementPunktEditor.class,
"NivellementPunktEditor.lblLagebezeichnung.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(10, 5, 5, 5);
pnlSimpleAttributes.add(lblLagebezeichnung, gridBagConstraints);
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(
org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE,
this,
org.jdesktop.beansbinding.ELProperty.create("${cidsBean.lagebezeichnung}"),
txtLagebezeichnung,
org.jdesktop.beansbinding.BeanProperty.create("text"));
bindingGroup.addBinding(binding);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
gridBagConstraints.gridwidth = 5;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(10, 5, 5, 5);
pnlSimpleAttributes.add(txtLagebezeichnung, gridBagConstraints);
lblLagegenauigkeit.setText(org.openide.util.NbBundle.getMessage(
NivellementPunktEditor.class,
"NivellementPunktEditor.lblLagegenauigkeit.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 5;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
pnlSimpleAttributes.add(lblLagegenauigkeit, gridBagConstraints);
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(
org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE,
this,
org.jdesktop.beansbinding.ELProperty.create("${cidsBean.lagegenauigkeit}"),
cmbLagegenauigkeit,
org.jdesktop.beansbinding.BeanProperty.create("selectedItem"));
bindingGroup.addBinding(binding);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 5;
gridBagConstraints.gridwidth = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
pnlSimpleAttributes.add(cmbLagegenauigkeit, gridBagConstraints);
lblMessungsjahr.setText(org.openide.util.NbBundle.getMessage(
NivellementPunktEditor.class,
"NivellementPunktEditor.lblMessungsjahr.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
pnlSimpleAttributes.add(lblMessungsjahr, gridBagConstraints);
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(
org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE,
this,
org.jdesktop.beansbinding.ELProperty.create("${cidsBean.messungsjahr}"),
txtMessungsjahr,
org.jdesktop.beansbinding.BeanProperty.create("text"));
bindingGroup.addBinding(binding);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 3;
gridBagConstraints.gridwidth = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
pnlSimpleAttributes.add(txtMessungsjahr, gridBagConstraints);
lblPunktnummerNRW.setText(org.openide.util.NbBundle.getMessage(
NivellementPunktEditor.class,
"NivellementPunktEditor.lblPunktnummerNRW.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
pnlSimpleAttributes.add(lblPunktnummerNRW, gridBagConstraints);
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(
org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE,
this,
org.jdesktop.beansbinding.ELProperty.create("${cidsBean.punktnummer_nrw}"),
txtPunktnummerNRW,
org.jdesktop.beansbinding.BeanProperty.create("text"));
bindingGroup.addBinding(binding);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 2;
gridBagConstraints.gridwidth = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
pnlSimpleAttributes.add(txtPunktnummerNRW, gridBagConstraints);
lblBemerkung.setText(org.openide.util.NbBundle.getMessage(
NivellementPunktEditor.class,
"NivellementPunktEditor.lblBemerkung.text")); // NOI18N
lblBemerkung.setVerticalAlignment(javax.swing.SwingConstants.TOP);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 4;
gridBagConstraints.gridy = 3;
gridBagConstraints.gridheight = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
pnlSimpleAttributes.add(lblBemerkung, gridBagConstraints);
txaBemerkung.setColumns(20);
txaBemerkung.setRows(5);
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(
org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE,
this,
org.jdesktop.beansbinding.ELProperty.create("${cidsBean.bemerkung}"),
txaBemerkung,
org.jdesktop.beansbinding.BeanProperty.create("text"));
bindingGroup.addBinding(binding);
scpBemerkung.setViewportView(txaBemerkung);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 5;
gridBagConstraints.gridy = 3;
gridBagConstraints.gridheight = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
pnlSimpleAttributes.add(scpBemerkung, gridBagConstraints);
lblGeometrie.setText(org.openide.util.NbBundle.getMessage(
NivellementPunktEditor.class,
"NivellementPunktEditor.lblGeometrie.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 4;
gridBagConstraints.gridy = 7;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
pnlSimpleAttributes.add(lblGeometrie, gridBagConstraints);
if (!readOnly) {
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(
org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE,
this,
org.jdesktop.beansbinding.ELProperty.create("${cidsBean.geometrie}"),
cmbGeometrie,
org.jdesktop.beansbinding.BeanProperty.create("selectedItem"));
binding.setConverter(((DefaultCismapGeometryComboBoxEditor)cmbGeometrie).getConverter());
bindingGroup.addBinding(binding);
}
if (!readOnly) {
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 5;
gridBagConstraints.gridy = 7;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
pnlSimpleAttributes.add(cmbGeometrie, gridBagConstraints);
}
lblPunktnummerWUP.setText(org.openide.util.NbBundle.getMessage(
NivellementPunktEditor.class,
"NivellementPunktEditor.lblPunktnummerWUP.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
pnlSimpleAttributes.add(lblPunktnummerWUP, gridBagConstraints);
lblPunktnummerWUPSeparator.setText(org.openide.util.NbBundle.getMessage(
NivellementPunktEditor.class,
"NivellementPunktEditor.lblPunktnummerWUPSeparator.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 1;
pnlSimpleAttributes.add(lblPunktnummerWUPSeparator, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 8;
gridBagConstraints.gridwidth = 6;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
pnlSimpleAttributes.add(gluFiller, gridBagConstraints);
txtLaufendeNummer.setColumns(3);
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(
org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE,
this,
org.jdesktop.beansbinding.ELProperty.create("${cidsBean.laufende_nummer}"),
txtLaufendeNummer,
org.jdesktop.beansbinding.BeanProperty.create("text"));
bindingGroup.addBinding(binding);
txtLaufendeNummer.addFocusListener(new java.awt.event.FocusAdapter() {
@Override
public void focusGained(final java.awt.event.FocusEvent evt) {
txtLaufendeNummerFocusGained(evt);
}
@Override
public void focusLost(final java.awt.event.FocusEvent evt) {
txtLaufendeNummerFocusLost(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 3;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.weightx = 0.25;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
pnlSimpleAttributes.add(txtLaufendeNummer, gridBagConstraints);
lblHistorisch.setText(org.openide.util.NbBundle.getMessage(
NivellementPunktEditor.class,
"NivellementPunktEditor.lblHistorisch.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 4;
gridBagConstraints.gridy = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
pnlSimpleAttributes.add(lblHistorisch, gridBagConstraints);
chkHistorisch.setText(org.openide.util.NbBundle.getMessage(
NivellementPunktEditor.class,
"NivellementPunktEditor.chkHistorisch.text")); // NOI18N
chkHistorisch.setContentAreaFilled(false);
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(
org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE,
this,
org.jdesktop.beansbinding.ELProperty.create("${cidsBean.historisch}"),
chkHistorisch,
org.jdesktop.beansbinding.BeanProperty.create("selected"),
"");
binding.setSourceNullValue(false);
binding.setSourceUnreadableValue(false);
bindingGroup.addBinding(binding);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 5;
gridBagConstraints.gridy = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
pnlSimpleAttributes.add(chkHistorisch, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 6;
gridBagConstraints.gridwidth = 4;
gridBagConstraints.gridheight = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
pnlSimpleAttributes.add(gluFillDescription, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(8, 0, 10, 0);
add(pnlSimpleAttributes, gridBagConstraints);
pnlDocument.setLayout(new java.awt.GridBagLayout());
pnlHeaderDocument.setBackground(java.awt.Color.darkGray);
pnlHeaderDocument.setLayout(new java.awt.GridBagLayout());
lblHeaderDocument.setForeground(java.awt.Color.white);
lblHeaderDocument.setText(org.openide.util.NbBundle.getMessage(
NivellementPunktEditor.class,
"NivellementPunktEditor.lblHeaderDocument.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
pnlHeaderDocument.add(lblHeaderDocument, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.weightx = 0.1;
pnlDocument.add(pnlHeaderDocument, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weighty = 0.1;
pnlDocument.add(measuringComponent, gridBagConstraints);
lblMissingRasterdocument.setBackground(java.awt.Color.white);
lblMissingRasterdocument.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
lblMissingRasterdocument.setIcon(new javax.swing.ImageIcon(
getClass().getResource("/de/cismet/cids/custom/objecteditors/wunda_blau/missingRasterdocument.png"))); // NOI18N
lblMissingRasterdocument.setText(org.openide.util.NbBundle.getMessage(
NivellementPunktEditor.class,
"NivellementPunktEditor.lblMissingRasterdocument.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weighty = 0.1;
pnlDocument.add(lblMissingRasterdocument, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.gridheight = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.weightx = 0.1;
gridBagConstraints.weighty = 0.1;
gridBagConstraints.insets = new java.awt.Insets(10, 0, 0, 5);
add(pnlDocument, gridBagConstraints);
pnlControls.setLayout(new java.awt.GridBagLayout());
bgrControls.add(togPan);
togPan.setIcon(new javax.swing.ImageIcon(
getClass().getResource("/de/cismet/cids/custom/wunda_blau/res/pan.gif"))); // NOI18N
togPan.setSelected(true);
togPan.setText(org.openide.util.NbBundle.getMessage(
NivellementPunktEditor.class,
"NivellementPunktEditor.togPan.text")); // NOI18N
togPan.setToolTipText(org.openide.util.NbBundle.getMessage(
NivellementPunktEditor.class,
"NivellementPunktEditor.togPan.toolTipText")); // NOI18N
togPan.setEnabled(false);
togPan.setFocusPainted(false);
togPan.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
togPan.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
togPanActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.insets = new java.awt.Insets(2, 5, 3, 5);
pnlControls.add(togPan, gridBagConstraints);
bgrControls.add(togZoom);
togZoom.setIcon(new javax.swing.ImageIcon(
getClass().getResource("/de/cismet/cids/custom/wunda_blau/res/zoom.gif"))); // NOI18N
togZoom.setText(org.openide.util.NbBundle.getMessage(
NivellementPunktEditor.class,
"NivellementPunktEditor.togZoom.text")); // NOI18N
togZoom.setToolTipText(org.openide.util.NbBundle.getMessage(
NivellementPunktEditor.class,
"NivellementPunktEditor.togZoom.toolTipText")); // NOI18N
togZoom.setEnabled(false);
togZoom.setFocusPainted(false);
togZoom.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
togZoom.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
togZoomActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.insets = new java.awt.Insets(2, 5, 3, 5);
pnlControls.add(togZoom, gridBagConstraints);
btnHome.setIcon(new javax.swing.ImageIcon(
getClass().getResource("/de/cismet/cids/custom/wunda_blau/res/home.gif"))); // NOI18N
btnHome.setText(org.openide.util.NbBundle.getMessage(
NivellementPunktEditor.class,
"NivellementPunktEditor.btnHome.text")); // NOI18N
btnHome.setToolTipText(org.openide.util.NbBundle.getMessage(
NivellementPunktEditor.class,
"NivellementPunktEditor.btnHome.toolTipText")); // NOI18N
btnHome.setEnabled(false);
btnHome.setFocusPainted(false);
btnHome.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
btnHome.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
btnHomeActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 3, 5);
pnlControls.add(btnHome, gridBagConstraints);
semiRoundedPanel4.setBackground(new java.awt.Color(51, 51, 51));
semiRoundedPanel4.setLayout(new java.awt.FlowLayout());
jLabel3.setForeground(new java.awt.Color(255, 255, 255));
jLabel3.setText(org.openide.util.NbBundle.getMessage(
NivellementPunktEditor.class,
"NivellementPunktEditor.jLabel3.text")); // NOI18N
semiRoundedPanel4.add(jLabel3);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
pnlControls.add(semiRoundedPanel4, gridBagConstraints);
btnOpen.setIcon(new javax.swing.ImageIcon(
getClass().getResource("/de/cismet/cids/custom/wunda_blau/res/folder-image.png"))); // NOI18N
btnOpen.setText(org.openide.util.NbBundle.getMessage(
NivellementPunktEditor.class,
"NivellementPunktEditor.btnOpen.text")); // NOI18N
btnOpen.setToolTipText(org.openide.util.NbBundle.getMessage(
NivellementPunktEditor.class,
"NivellementPunktEditor.btnOpen.toolTipText")); // NOI18N
btnOpen.setEnabled(false);
btnOpen.setFocusPainted(false);
btnOpen.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
btnOpen.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
btnOpenActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 7;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.insets = new java.awt.Insets(2, 5, 3, 5);
pnlControls.add(btnOpen, gridBagConstraints);
btnReport.setIcon(new javax.swing.ImageIcon(
getClass().getResource("/de/cismet/cids/custom/objecteditors/wunda_blau/printer.png"))); // NOI18N
btnReport.setText(org.openide.util.NbBundle.getMessage(
NivellementPunktEditor.class,
"NivellementPunktEditor.btnReport.text")); // NOI18N
btnReport.setFocusPainted(false);
btnReport.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
btnReportActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 8;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.insets = new java.awt.Insets(2, 5, 5, 5);
pnlControls.add(btnReport, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(10, 5, 0, 0);
add(pnlControls, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
add(gluFillerControls, gridBagConstraints);
bindingGroup.bind();
} // </editor-fold>//GEN-END:initComponents
|
diff --git a/drools-core/src/main/java/org/drools/ruleflow/instance/impl/RuleFlowSplitInstanceImpl.java b/drools-core/src/main/java/org/drools/ruleflow/instance/impl/RuleFlowSplitInstanceImpl.java
index 4001882eed..c84c91ffdd 100644
--- a/drools-core/src/main/java/org/drools/ruleflow/instance/impl/RuleFlowSplitInstanceImpl.java
+++ b/drools-core/src/main/java/org/drools/ruleflow/instance/impl/RuleFlowSplitInstanceImpl.java
@@ -1,108 +1,108 @@
package org.drools.ruleflow.instance.impl;
/*
* Copyright 2005 JBoss Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.util.Iterator;
import java.util.List;
import org.drools.common.RuleFlowGroupNode;
import org.drools.ruleflow.core.Connection;
import org.drools.ruleflow.core.Constraint;
import org.drools.ruleflow.core.Split;
import org.drools.ruleflow.instance.RuleFlowNodeInstance;
import org.drools.spi.Activation;
import org.drools.spi.RuleFlowGroup;
/**
* Runtime counterpart of a split node.
*
* @author <a href="mailto:[email protected]">Kris Verlaenen</a>
*/
public class RuleFlowSplitInstanceImpl extends RuleFlowNodeInstanceImpl
implements
RuleFlowNodeInstance {
protected Split getSplitNode() {
return (Split) getNode();
}
public void trigger(final RuleFlowNodeInstance from) {
final Split split = getSplitNode();
switch ( split.getType() ) {
case Split.TYPE_AND :
List outgoing = split.getOutgoingConnections();
for ( final Iterator iterator = outgoing.iterator(); iterator.hasNext(); ) {
final Connection connection = (Connection) iterator.next();
getProcessInstance().getNodeInstance( connection.getTo() ).trigger( this );
}
break;
case Split.TYPE_XOR :
outgoing = split.getOutgoingConnections();
int priority = Integer.MAX_VALUE;
Connection selected = null;
RuleFlowGroup systemRuleFlowGroup = getProcessInstance().getAgenda().getRuleFlowGroup("DROOLS_SYSTEM");
for ( final Iterator iterator = outgoing.iterator(); iterator.hasNext(); ) {
final Connection connection = (Connection) iterator.next();
Constraint constraint = split.getConstraint(connection);
if (constraint != null && constraint.getPriority() < priority) {
String rule = "RuleFlow-" + getProcessInstance().getProcess().getId() + "-" +
getNode().getId() + "-" + connection.getTo().getId();
for (Iterator activations = systemRuleFlowGroup.iterator(); activations.hasNext(); ) {
Activation activation = ((RuleFlowGroupNode) activations.next()).getActivation();
if (rule.equals(activation.getRule().getName())) {
selected = connection;
priority = constraint.getPriority();
break;
}
}
}
}
if (selected == null) {
throw new IllegalArgumentException("XOR split could not find at least one valid outgoing connection for split " + getSplitNode().getName());
}
getProcessInstance().getNodeInstance( selected.getTo() ).trigger( this );
break;
case Split.TYPE_OR :
outgoing = split.getOutgoingConnections();
boolean found = false;
systemRuleFlowGroup = getProcessInstance().getAgenda().getRuleFlowGroup("DROOLS_SYSTEM");
for ( final Iterator iterator = outgoing.iterator(); iterator.hasNext(); ) {
final Connection connection = (Connection) iterator.next();
Constraint constraint = split.getConstraint(connection);
if (constraint != null) {
String rule = "RuleFlow-" + getProcessInstance().getProcess().getId() + "-" +
getNode().getId() + "-" + connection.getTo().getId();
for (Iterator activations = systemRuleFlowGroup.iterator(); activations.hasNext(); ) {
- Activation activation = (Activation) activations.next();
+ Activation activation = ((RuleFlowGroupNode) activations.next()).getActivation();
if (rule.equals(activation.getRule().getName())) {
getProcessInstance().getNodeInstance( connection.getTo() ).trigger( this );
found = true;
break;
}
}
}
if (!found) {
throw new IllegalArgumentException("OR split could not find at least one valid outgoing connection for split " + getSplitNode().getName());
}
}
break;
default :
throw new IllegalArgumentException( "Illegal split type " + split.getType() );
}
}
}
| true | true | public void trigger(final RuleFlowNodeInstance from) {
final Split split = getSplitNode();
switch ( split.getType() ) {
case Split.TYPE_AND :
List outgoing = split.getOutgoingConnections();
for ( final Iterator iterator = outgoing.iterator(); iterator.hasNext(); ) {
final Connection connection = (Connection) iterator.next();
getProcessInstance().getNodeInstance( connection.getTo() ).trigger( this );
}
break;
case Split.TYPE_XOR :
outgoing = split.getOutgoingConnections();
int priority = Integer.MAX_VALUE;
Connection selected = null;
RuleFlowGroup systemRuleFlowGroup = getProcessInstance().getAgenda().getRuleFlowGroup("DROOLS_SYSTEM");
for ( final Iterator iterator = outgoing.iterator(); iterator.hasNext(); ) {
final Connection connection = (Connection) iterator.next();
Constraint constraint = split.getConstraint(connection);
if (constraint != null && constraint.getPriority() < priority) {
String rule = "RuleFlow-" + getProcessInstance().getProcess().getId() + "-" +
getNode().getId() + "-" + connection.getTo().getId();
for (Iterator activations = systemRuleFlowGroup.iterator(); activations.hasNext(); ) {
Activation activation = ((RuleFlowGroupNode) activations.next()).getActivation();
if (rule.equals(activation.getRule().getName())) {
selected = connection;
priority = constraint.getPriority();
break;
}
}
}
}
if (selected == null) {
throw new IllegalArgumentException("XOR split could not find at least one valid outgoing connection for split " + getSplitNode().getName());
}
getProcessInstance().getNodeInstance( selected.getTo() ).trigger( this );
break;
case Split.TYPE_OR :
outgoing = split.getOutgoingConnections();
boolean found = false;
systemRuleFlowGroup = getProcessInstance().getAgenda().getRuleFlowGroup("DROOLS_SYSTEM");
for ( final Iterator iterator = outgoing.iterator(); iterator.hasNext(); ) {
final Connection connection = (Connection) iterator.next();
Constraint constraint = split.getConstraint(connection);
if (constraint != null) {
String rule = "RuleFlow-" + getProcessInstance().getProcess().getId() + "-" +
getNode().getId() + "-" + connection.getTo().getId();
for (Iterator activations = systemRuleFlowGroup.iterator(); activations.hasNext(); ) {
Activation activation = (Activation) activations.next();
if (rule.equals(activation.getRule().getName())) {
getProcessInstance().getNodeInstance( connection.getTo() ).trigger( this );
found = true;
break;
}
}
}
if (!found) {
throw new IllegalArgumentException("OR split could not find at least one valid outgoing connection for split " + getSplitNode().getName());
}
}
break;
default :
throw new IllegalArgumentException( "Illegal split type " + split.getType() );
}
}
| public void trigger(final RuleFlowNodeInstance from) {
final Split split = getSplitNode();
switch ( split.getType() ) {
case Split.TYPE_AND :
List outgoing = split.getOutgoingConnections();
for ( final Iterator iterator = outgoing.iterator(); iterator.hasNext(); ) {
final Connection connection = (Connection) iterator.next();
getProcessInstance().getNodeInstance( connection.getTo() ).trigger( this );
}
break;
case Split.TYPE_XOR :
outgoing = split.getOutgoingConnections();
int priority = Integer.MAX_VALUE;
Connection selected = null;
RuleFlowGroup systemRuleFlowGroup = getProcessInstance().getAgenda().getRuleFlowGroup("DROOLS_SYSTEM");
for ( final Iterator iterator = outgoing.iterator(); iterator.hasNext(); ) {
final Connection connection = (Connection) iterator.next();
Constraint constraint = split.getConstraint(connection);
if (constraint != null && constraint.getPriority() < priority) {
String rule = "RuleFlow-" + getProcessInstance().getProcess().getId() + "-" +
getNode().getId() + "-" + connection.getTo().getId();
for (Iterator activations = systemRuleFlowGroup.iterator(); activations.hasNext(); ) {
Activation activation = ((RuleFlowGroupNode) activations.next()).getActivation();
if (rule.equals(activation.getRule().getName())) {
selected = connection;
priority = constraint.getPriority();
break;
}
}
}
}
if (selected == null) {
throw new IllegalArgumentException("XOR split could not find at least one valid outgoing connection for split " + getSplitNode().getName());
}
getProcessInstance().getNodeInstance( selected.getTo() ).trigger( this );
break;
case Split.TYPE_OR :
outgoing = split.getOutgoingConnections();
boolean found = false;
systemRuleFlowGroup = getProcessInstance().getAgenda().getRuleFlowGroup("DROOLS_SYSTEM");
for ( final Iterator iterator = outgoing.iterator(); iterator.hasNext(); ) {
final Connection connection = (Connection) iterator.next();
Constraint constraint = split.getConstraint(connection);
if (constraint != null) {
String rule = "RuleFlow-" + getProcessInstance().getProcess().getId() + "-" +
getNode().getId() + "-" + connection.getTo().getId();
for (Iterator activations = systemRuleFlowGroup.iterator(); activations.hasNext(); ) {
Activation activation = ((RuleFlowGroupNode) activations.next()).getActivation();
if (rule.equals(activation.getRule().getName())) {
getProcessInstance().getNodeInstance( connection.getTo() ).trigger( this );
found = true;
break;
}
}
}
if (!found) {
throw new IllegalArgumentException("OR split could not find at least one valid outgoing connection for split " + getSplitNode().getName());
}
}
break;
default :
throw new IllegalArgumentException( "Illegal split type " + split.getType() );
}
}
|
diff --git a/src/org/sablecc/objectmacro/walkers/GenerateCode.java b/src/org/sablecc/objectmacro/walkers/GenerateCode.java
index 0b5670e..52afd12 100644
--- a/src/org/sablecc/objectmacro/walkers/GenerateCode.java
+++ b/src/org/sablecc/objectmacro/walkers/GenerateCode.java
@@ -1,327 +1,329 @@
/* This file is part of SableCC ( http://sablecc.org ).
*
* See the NOTICE file distributed with this work for copyright information.
*
* 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.sablecc.objectmacro.walkers;
import static org.sablecc.objectmacro.util.Utils.getVarName;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Iterator;
import org.sablecc.objectmacro.macro.Macro_append;
import org.sablecc.objectmacro.macro.Macro_constructor;
import org.sablecc.objectmacro.macro.Macro_macro;
import org.sablecc.objectmacro.macro.Macro_macro_parts;
import org.sablecc.objectmacro.macro.Macro_nested_macro;
import org.sablecc.objectmacro.macro.Macro_root_macro;
import org.sablecc.objectmacro.structures.Expand;
import org.sablecc.objectmacro.structures.Macro;
import org.sablecc.objectmacro.structures.Param;
import org.sablecc.objectmacro.syntax3.analysis.DepthFirstAdapter;
import org.sablecc.objectmacro.syntax3.node.ADQuoteMacroBodyPart;
import org.sablecc.objectmacro.syntax3.node.AEolMacroBodyPart;
import org.sablecc.objectmacro.syntax3.node.AEscapeMacroBodyPart;
import org.sablecc.objectmacro.syntax3.node.AExpandMacroBodyPart;
import org.sablecc.objectmacro.syntax3.node.AFile;
import org.sablecc.objectmacro.syntax3.node.AMacro;
import org.sablecc.objectmacro.syntax3.node.AMacroMacroBodyPart;
import org.sablecc.objectmacro.syntax3.node.ATextMacroBodyPart;
import org.sablecc.objectmacro.syntax3.node.AVarMacroBodyPart;
import org.sablecc.objectmacro.syntax3.node.PMacroBodyPart;
import org.sablecc.objectmacro.syntax3.node.PParam;
import org.sablecc.sablecc.exception.ExitException;
import org.sablecc.sablecc.exception.InternalException;
public class GenerateCode
extends DepthFirstAdapter {
private final File destinationDirectory;
private final String destinationPackage;
private Macro_macro current_macro_macro;
private Macro_macro_parts current_macro_macro_parts;
private String current_indent;
public GenerateCode(
java.io.File destinationDirectory,
String destinationPackage) {
this.destinationDirectory = destinationDirectory;
this.destinationPackage = destinationPackage;
}
@Override
public void outAFile(
AFile node) {
File outFile = new File(this.destinationDirectory, "Macro.java");
try {
FileWriter fw = new FileWriter(outFile);
BufferedWriter bw = new BufferedWriter(fw);
Macro_root_macro macro_root_macro = new Macro_root_macro();
if (!this.destinationPackage.equals("")) {
macro_root_macro
.newMacro_root_macro_package(this.destinationPackage);
}
bw.write(macro_root_macro.toString());
bw.close();
fw.close();
}
catch (IOException e) {
System.err.println("I/O ERROR: failed to write "
+ outFile.getAbsolutePath());
System.err.println(e.getMessage());
throw new ExitException();
}
}
@Override
public void caseAMacro(
AMacro node) {
Macro macro = Macro.getMacro(node);
if (macro.isTopLevel()) {
this.current_macro_macro = new Macro_macro();
if (!this.destinationPackage.equals("")) {
this.current_macro_macro
.newMacro_macro_package(this.destinationPackage);
}
this.current_macro_macro_parts = this.current_macro_macro
.newMacro_macro_parts();
this.current_indent = "";
}
this.current_macro_macro_parts.newMacro_macro_class_head(macro
.getName(), this.current_indent);
for (PParam pParam : node.getParameters()) {
Param param = Param.getParam(pParam);
this.current_macro_macro_parts.newMacro_parameter_declaration(param
.getName(), this.current_indent);
}
for (PMacroBodyPart part : node.getParts()) {
if (part instanceof AMacroMacroBodyPart) {
AMacroMacroBodyPart macroPart = (AMacroMacroBodyPart) part;
Macro subMacro = Macro.getMacro(macroPart.getMacro());
- this.current_macro_macro_parts.newMacro_macro_declaration(
- subMacro.getName(), this.current_indent);
+ if (subMacro.isImplicitlyExpanded()) {
+ this.current_macro_macro_parts.newMacro_macro_declaration(
+ subMacro.getName(), this.current_indent);
+ }
}
else if (part instanceof AExpandMacroBodyPart) {
AExpandMacroBodyPart expandPart = (AExpandMacroBodyPart) part;
Expand expand = Expand.getExpand(expandPart.getExpand());
this.current_macro_macro_parts.newMacro_expand_declaration(
expand.getName(), this.current_indent);
}
}
Macro_constructor macro_constructor = this.current_macro_macro_parts
.newMacro_constructor(macro.getName(), this.current_indent);
if (macro.isTopLevel()) {
macro_constructor.newMacro_public();
}
{
boolean first = true;
for (PParam pParam : node.getParameters()) {
Param param = Param.getParam(pParam);
if (first) {
first = false;
macro_constructor
.newMacro_constructor_first_parameter(param
.getName());
}
else {
macro_constructor
.newMacro_constructor_additional_parameter(param
.getName());
}
macro_constructor.newMacro_parameter_initialisation(param
.getName());
}
}
for (Iterator<Macro> i = macro.getSubMacrosIterator(); i.hasNext();) {
Macro subMacro = i.next();
Macro_nested_macro macro_nested_macro = this.current_macro_macro_parts
.newMacro_nested_macro(subMacro.getName(),
this.current_indent);
{
boolean first = true;
for (PParam pParam : subMacro.getDefinition().getParameters()) {
Param param = Param.getParam(pParam);
if (first) {
first = false;
macro_nested_macro
.newMacro_nested_macro_first_parameter(param
.getName());
macro_nested_macro.newMacro_new_first_parameter(param
.getName());
}
else {
macro_nested_macro
.newMacro_nested_macro_additional_parameter(param
.getName());
macro_nested_macro
.newMacro_new_additional_parameter(param
.getName());
}
}
}
if (subMacro.isImplicitlyExpanded()) {
macro_nested_macro.newMacro_add_to_macro();
}
else {
for (Iterator<Expand> j = subMacro
.getReferringExpandsIterator(); j.hasNext();) {
Expand expand = j.next();
if (expand.getMacro() == macro) {
macro_nested_macro.newMacro_add_to_expand(expand
.getName());
}
}
}
}
Macro_append macro_append = this.current_macro_macro_parts
.newMacro_append(this.current_indent);
for (PMacroBodyPart part : node.getParts()) {
if (part instanceof AVarMacroBodyPart) {
AVarMacroBodyPart varPart = (AVarMacroBodyPart) part;
macro_append.newMacro_instruction().newMacro_var_instruction(
getVarName(varPart.getVar()));
}
else if (part instanceof ATextMacroBodyPart) {
ATextMacroBodyPart textPart = (ATextMacroBodyPart) part;
macro_append.newMacro_instruction().newMacro_text_instruction(
textPart.getText().getText());
}
else if (part instanceof ADQuoteMacroBodyPart) {
macro_append.newMacro_instruction()
.newMacro_dquote_instruction();
}
else if (part instanceof AEolMacroBodyPart) {
macro_append.newMacro_instruction().newMacro_eol_instruction();
}
else if (part instanceof AEscapeMacroBodyPart) {
AEscapeMacroBodyPart escapePart = (AEscapeMacroBodyPart) part;
char c = escapePart.getEscape().getText().charAt(1);
switch (c) {
case '\\':
macro_append.newMacro_instruction()
.newMacro_escape_instruction("\\\\");
break;
case '$':
macro_append.newMacro_instruction()
.newMacro_escape_instruction("$");
break;
default:
throw new InternalException("escape char");
}
}
else if (part instanceof AMacroMacroBodyPart) {
AMacroMacroBodyPart macroPart = (AMacroMacroBodyPart) part;
Macro subMacro = Macro.getMacro(macroPart.getMacro());
if (subMacro.isImplicitlyExpanded()) {
macro_append.newMacro_instruction()
.newMacro_macro_instruction(subMacro.getName());
}
}
else if (part instanceof AExpandMacroBodyPart) {
AExpandMacroBodyPart expandPart = (AExpandMacroBodyPart) part;
Expand expand = Expand.getExpand(expandPart.getExpand());
macro_append.newMacro_instruction()
.newMacro_expand_instruction(expand.getName());
}
else {
throw new InternalException("unexpected part type");
}
}
String oldIndent = this.current_indent;
this.current_indent = this.current_indent + " ";
this.current_macro_macro_parts = this.current_macro_macro
.newMacro_macro_parts();
for (PMacroBodyPart part : node.getParts()) {
part.apply(this);
}
this.current_indent = oldIndent;
this.current_macro_macro_parts = this.current_macro_macro
.newMacro_macro_parts();
this.current_macro_macro_parts
.newMacro_macro_class_tail(this.current_indent);
if (macro.isTopLevel()) {
File outFile = new File(this.destinationDirectory, "M"
+ macro.getName() + ".java");
try {
FileWriter fw = new FileWriter(outFile);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(this.current_macro_macro.toString());
bw.close();
fw.close();
}
catch (IOException e) {
System.err.println("I/O ERROR: failed to write "
+ outFile.getAbsolutePath());
System.err.println(e.getMessage());
throw new ExitException();
}
}
this.current_macro_macro_parts = this.current_macro_macro
.newMacro_macro_parts();
}
}
| true | true | public void caseAMacro(
AMacro node) {
Macro macro = Macro.getMacro(node);
if (macro.isTopLevel()) {
this.current_macro_macro = new Macro_macro();
if (!this.destinationPackage.equals("")) {
this.current_macro_macro
.newMacro_macro_package(this.destinationPackage);
}
this.current_macro_macro_parts = this.current_macro_macro
.newMacro_macro_parts();
this.current_indent = "";
}
this.current_macro_macro_parts.newMacro_macro_class_head(macro
.getName(), this.current_indent);
for (PParam pParam : node.getParameters()) {
Param param = Param.getParam(pParam);
this.current_macro_macro_parts.newMacro_parameter_declaration(param
.getName(), this.current_indent);
}
for (PMacroBodyPart part : node.getParts()) {
if (part instanceof AMacroMacroBodyPart) {
AMacroMacroBodyPart macroPart = (AMacroMacroBodyPart) part;
Macro subMacro = Macro.getMacro(macroPart.getMacro());
this.current_macro_macro_parts.newMacro_macro_declaration(
subMacro.getName(), this.current_indent);
}
else if (part instanceof AExpandMacroBodyPart) {
AExpandMacroBodyPart expandPart = (AExpandMacroBodyPart) part;
Expand expand = Expand.getExpand(expandPart.getExpand());
this.current_macro_macro_parts.newMacro_expand_declaration(
expand.getName(), this.current_indent);
}
}
Macro_constructor macro_constructor = this.current_macro_macro_parts
.newMacro_constructor(macro.getName(), this.current_indent);
if (macro.isTopLevel()) {
macro_constructor.newMacro_public();
}
{
boolean first = true;
for (PParam pParam : node.getParameters()) {
Param param = Param.getParam(pParam);
if (first) {
first = false;
macro_constructor
.newMacro_constructor_first_parameter(param
.getName());
}
else {
macro_constructor
.newMacro_constructor_additional_parameter(param
.getName());
}
macro_constructor.newMacro_parameter_initialisation(param
.getName());
}
}
for (Iterator<Macro> i = macro.getSubMacrosIterator(); i.hasNext();) {
Macro subMacro = i.next();
Macro_nested_macro macro_nested_macro = this.current_macro_macro_parts
.newMacro_nested_macro(subMacro.getName(),
this.current_indent);
{
boolean first = true;
for (PParam pParam : subMacro.getDefinition().getParameters()) {
Param param = Param.getParam(pParam);
if (first) {
first = false;
macro_nested_macro
.newMacro_nested_macro_first_parameter(param
.getName());
macro_nested_macro.newMacro_new_first_parameter(param
.getName());
}
else {
macro_nested_macro
.newMacro_nested_macro_additional_parameter(param
.getName());
macro_nested_macro
.newMacro_new_additional_parameter(param
.getName());
}
}
}
if (subMacro.isImplicitlyExpanded()) {
macro_nested_macro.newMacro_add_to_macro();
}
else {
for (Iterator<Expand> j = subMacro
.getReferringExpandsIterator(); j.hasNext();) {
Expand expand = j.next();
if (expand.getMacro() == macro) {
macro_nested_macro.newMacro_add_to_expand(expand
.getName());
}
}
}
}
Macro_append macro_append = this.current_macro_macro_parts
.newMacro_append(this.current_indent);
for (PMacroBodyPart part : node.getParts()) {
if (part instanceof AVarMacroBodyPart) {
AVarMacroBodyPart varPart = (AVarMacroBodyPart) part;
macro_append.newMacro_instruction().newMacro_var_instruction(
getVarName(varPart.getVar()));
}
else if (part instanceof ATextMacroBodyPart) {
ATextMacroBodyPart textPart = (ATextMacroBodyPart) part;
macro_append.newMacro_instruction().newMacro_text_instruction(
textPart.getText().getText());
}
else if (part instanceof ADQuoteMacroBodyPart) {
macro_append.newMacro_instruction()
.newMacro_dquote_instruction();
}
else if (part instanceof AEolMacroBodyPart) {
macro_append.newMacro_instruction().newMacro_eol_instruction();
}
else if (part instanceof AEscapeMacroBodyPart) {
AEscapeMacroBodyPart escapePart = (AEscapeMacroBodyPart) part;
char c = escapePart.getEscape().getText().charAt(1);
switch (c) {
case '\\':
macro_append.newMacro_instruction()
.newMacro_escape_instruction("\\\\");
break;
case '$':
macro_append.newMacro_instruction()
.newMacro_escape_instruction("$");
break;
default:
throw new InternalException("escape char");
}
}
else if (part instanceof AMacroMacroBodyPart) {
AMacroMacroBodyPart macroPart = (AMacroMacroBodyPart) part;
Macro subMacro = Macro.getMacro(macroPart.getMacro());
if (subMacro.isImplicitlyExpanded()) {
macro_append.newMacro_instruction()
.newMacro_macro_instruction(subMacro.getName());
}
}
else if (part instanceof AExpandMacroBodyPart) {
AExpandMacroBodyPart expandPart = (AExpandMacroBodyPart) part;
Expand expand = Expand.getExpand(expandPart.getExpand());
macro_append.newMacro_instruction()
.newMacro_expand_instruction(expand.getName());
}
else {
throw new InternalException("unexpected part type");
}
}
String oldIndent = this.current_indent;
this.current_indent = this.current_indent + " ";
this.current_macro_macro_parts = this.current_macro_macro
.newMacro_macro_parts();
for (PMacroBodyPart part : node.getParts()) {
part.apply(this);
}
this.current_indent = oldIndent;
this.current_macro_macro_parts = this.current_macro_macro
.newMacro_macro_parts();
this.current_macro_macro_parts
.newMacro_macro_class_tail(this.current_indent);
if (macro.isTopLevel()) {
File outFile = new File(this.destinationDirectory, "M"
+ macro.getName() + ".java");
try {
FileWriter fw = new FileWriter(outFile);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(this.current_macro_macro.toString());
bw.close();
fw.close();
}
catch (IOException e) {
System.err.println("I/O ERROR: failed to write "
+ outFile.getAbsolutePath());
System.err.println(e.getMessage());
throw new ExitException();
}
}
this.current_macro_macro_parts = this.current_macro_macro
.newMacro_macro_parts();
}
| public void caseAMacro(
AMacro node) {
Macro macro = Macro.getMacro(node);
if (macro.isTopLevel()) {
this.current_macro_macro = new Macro_macro();
if (!this.destinationPackage.equals("")) {
this.current_macro_macro
.newMacro_macro_package(this.destinationPackage);
}
this.current_macro_macro_parts = this.current_macro_macro
.newMacro_macro_parts();
this.current_indent = "";
}
this.current_macro_macro_parts.newMacro_macro_class_head(macro
.getName(), this.current_indent);
for (PParam pParam : node.getParameters()) {
Param param = Param.getParam(pParam);
this.current_macro_macro_parts.newMacro_parameter_declaration(param
.getName(), this.current_indent);
}
for (PMacroBodyPart part : node.getParts()) {
if (part instanceof AMacroMacroBodyPart) {
AMacroMacroBodyPart macroPart = (AMacroMacroBodyPart) part;
Macro subMacro = Macro.getMacro(macroPart.getMacro());
if (subMacro.isImplicitlyExpanded()) {
this.current_macro_macro_parts.newMacro_macro_declaration(
subMacro.getName(), this.current_indent);
}
}
else if (part instanceof AExpandMacroBodyPart) {
AExpandMacroBodyPart expandPart = (AExpandMacroBodyPart) part;
Expand expand = Expand.getExpand(expandPart.getExpand());
this.current_macro_macro_parts.newMacro_expand_declaration(
expand.getName(), this.current_indent);
}
}
Macro_constructor macro_constructor = this.current_macro_macro_parts
.newMacro_constructor(macro.getName(), this.current_indent);
if (macro.isTopLevel()) {
macro_constructor.newMacro_public();
}
{
boolean first = true;
for (PParam pParam : node.getParameters()) {
Param param = Param.getParam(pParam);
if (first) {
first = false;
macro_constructor
.newMacro_constructor_first_parameter(param
.getName());
}
else {
macro_constructor
.newMacro_constructor_additional_parameter(param
.getName());
}
macro_constructor.newMacro_parameter_initialisation(param
.getName());
}
}
for (Iterator<Macro> i = macro.getSubMacrosIterator(); i.hasNext();) {
Macro subMacro = i.next();
Macro_nested_macro macro_nested_macro = this.current_macro_macro_parts
.newMacro_nested_macro(subMacro.getName(),
this.current_indent);
{
boolean first = true;
for (PParam pParam : subMacro.getDefinition().getParameters()) {
Param param = Param.getParam(pParam);
if (first) {
first = false;
macro_nested_macro
.newMacro_nested_macro_first_parameter(param
.getName());
macro_nested_macro.newMacro_new_first_parameter(param
.getName());
}
else {
macro_nested_macro
.newMacro_nested_macro_additional_parameter(param
.getName());
macro_nested_macro
.newMacro_new_additional_parameter(param
.getName());
}
}
}
if (subMacro.isImplicitlyExpanded()) {
macro_nested_macro.newMacro_add_to_macro();
}
else {
for (Iterator<Expand> j = subMacro
.getReferringExpandsIterator(); j.hasNext();) {
Expand expand = j.next();
if (expand.getMacro() == macro) {
macro_nested_macro.newMacro_add_to_expand(expand
.getName());
}
}
}
}
Macro_append macro_append = this.current_macro_macro_parts
.newMacro_append(this.current_indent);
for (PMacroBodyPart part : node.getParts()) {
if (part instanceof AVarMacroBodyPart) {
AVarMacroBodyPart varPart = (AVarMacroBodyPart) part;
macro_append.newMacro_instruction().newMacro_var_instruction(
getVarName(varPart.getVar()));
}
else if (part instanceof ATextMacroBodyPart) {
ATextMacroBodyPart textPart = (ATextMacroBodyPart) part;
macro_append.newMacro_instruction().newMacro_text_instruction(
textPart.getText().getText());
}
else if (part instanceof ADQuoteMacroBodyPart) {
macro_append.newMacro_instruction()
.newMacro_dquote_instruction();
}
else if (part instanceof AEolMacroBodyPart) {
macro_append.newMacro_instruction().newMacro_eol_instruction();
}
else if (part instanceof AEscapeMacroBodyPart) {
AEscapeMacroBodyPart escapePart = (AEscapeMacroBodyPart) part;
char c = escapePart.getEscape().getText().charAt(1);
switch (c) {
case '\\':
macro_append.newMacro_instruction()
.newMacro_escape_instruction("\\\\");
break;
case '$':
macro_append.newMacro_instruction()
.newMacro_escape_instruction("$");
break;
default:
throw new InternalException("escape char");
}
}
else if (part instanceof AMacroMacroBodyPart) {
AMacroMacroBodyPart macroPart = (AMacroMacroBodyPart) part;
Macro subMacro = Macro.getMacro(macroPart.getMacro());
if (subMacro.isImplicitlyExpanded()) {
macro_append.newMacro_instruction()
.newMacro_macro_instruction(subMacro.getName());
}
}
else if (part instanceof AExpandMacroBodyPart) {
AExpandMacroBodyPart expandPart = (AExpandMacroBodyPart) part;
Expand expand = Expand.getExpand(expandPart.getExpand());
macro_append.newMacro_instruction()
.newMacro_expand_instruction(expand.getName());
}
else {
throw new InternalException("unexpected part type");
}
}
String oldIndent = this.current_indent;
this.current_indent = this.current_indent + " ";
this.current_macro_macro_parts = this.current_macro_macro
.newMacro_macro_parts();
for (PMacroBodyPart part : node.getParts()) {
part.apply(this);
}
this.current_indent = oldIndent;
this.current_macro_macro_parts = this.current_macro_macro
.newMacro_macro_parts();
this.current_macro_macro_parts
.newMacro_macro_class_tail(this.current_indent);
if (macro.isTopLevel()) {
File outFile = new File(this.destinationDirectory, "M"
+ macro.getName() + ".java");
try {
FileWriter fw = new FileWriter(outFile);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(this.current_macro_macro.toString());
bw.close();
fw.close();
}
catch (IOException e) {
System.err.println("I/O ERROR: failed to write "
+ outFile.getAbsolutePath());
System.err.println(e.getMessage());
throw new ExitException();
}
}
this.current_macro_macro_parts = this.current_macro_macro
.newMacro_macro_parts();
}
|
diff --git a/nexus/nexus-rest-api/src/main/java/org/sonatype/nexus/rest/users/UserForgotPasswordPlexusResource.java b/nexus/nexus-rest-api/src/main/java/org/sonatype/nexus/rest/users/UserForgotPasswordPlexusResource.java
index 4447bc71a..eeacb891e 100644
--- a/nexus/nexus-rest-api/src/main/java/org/sonatype/nexus/rest/users/UserForgotPasswordPlexusResource.java
+++ b/nexus/nexus-rest-api/src/main/java/org/sonatype/nexus/rest/users/UserForgotPasswordPlexusResource.java
@@ -1,87 +1,87 @@
package org.sonatype.nexus.rest.users;
import org.restlet.Context;
import org.restlet.data.Request;
import org.restlet.data.Response;
import org.restlet.data.Status;
import org.restlet.resource.ResourceException;
import org.sonatype.jsecurity.realms.tools.NoSuchUserException;
import org.sonatype.nexus.jsecurity.NoSuchEmailException;
import org.sonatype.nexus.rest.model.UserForgotPasswordRequest;
import org.sonatype.nexus.rest.model.UserForgotPasswordResource;
import org.sonatype.plexus.rest.resource.PathProtectionDescriptor;
/**
* @author tstevens
* @plexus.component role-hint="UserForgotPasswordPlexusResource"
*/
public class UserForgotPasswordPlexusResource
extends AbstractUserPlexusResource
{
public UserForgotPasswordPlexusResource()
{
this.setModifiable( true );
}
@Override
public Object getPayloadInstance()
{
return new UserForgotPasswordRequest();
}
@Override
public String getResourceUri()
{
return "/users_forgotpw";
}
@Override
public PathProtectionDescriptor getResourceProtection()
{
return new PathProtectionDescriptor( getResourceUri(), "authcBasic,perms[nexus:usersforgotpw]" );
}
@Override
public Object post( Context context, Request request, Response response, Object payload )
throws ResourceException
{
UserForgotPasswordRequest forgotPasswordRequest = (UserForgotPasswordRequest) payload;
if ( forgotPasswordRequest != null )
{
UserForgotPasswordResource resource = forgotPasswordRequest.getData();
try
{
if ( !isAnonymousUser( resource.getUserId(), request ) )
{
getNexusSecurity( request ).forgotPassword( resource.getUserId(), resource.getEmail() );
response.setStatus( Status.SUCCESS_ACCEPTED );
}
else
{
- response.setStatus( Status.CLIENT_ERROR_BAD_REQUEST, "Anonymous user cannot forgot password!" );
+ response.setStatus( Status.CLIENT_ERROR_BAD_REQUEST, "Anonymous user cannot forget password!" );
getLogger().debug( "Anonymous user forgot password is blocked!" );
}
}
catch ( NoSuchUserException e )
{
- getLogger().debug( "Invalid user ID!", e );
+ getLogger().debug( "Invalid username!", e );
- throw new ResourceException( Status.CLIENT_ERROR_BAD_REQUEST, "Invalid user ID!" );
+ throw new ResourceException( Status.CLIENT_ERROR_BAD_REQUEST, "Invalid username!" );
}
catch ( NoSuchEmailException e )
{
getLogger().debug( "Invalid email!", e );
response.setStatus( Status.CLIENT_ERROR_BAD_REQUEST, "Email address not found!" );
}
}
// return null because the status is 202
return null;
}
}
| false | true | public Object post( Context context, Request request, Response response, Object payload )
throws ResourceException
{
UserForgotPasswordRequest forgotPasswordRequest = (UserForgotPasswordRequest) payload;
if ( forgotPasswordRequest != null )
{
UserForgotPasswordResource resource = forgotPasswordRequest.getData();
try
{
if ( !isAnonymousUser( resource.getUserId(), request ) )
{
getNexusSecurity( request ).forgotPassword( resource.getUserId(), resource.getEmail() );
response.setStatus( Status.SUCCESS_ACCEPTED );
}
else
{
response.setStatus( Status.CLIENT_ERROR_BAD_REQUEST, "Anonymous user cannot forgot password!" );
getLogger().debug( "Anonymous user forgot password is blocked!" );
}
}
catch ( NoSuchUserException e )
{
getLogger().debug( "Invalid user ID!", e );
throw new ResourceException( Status.CLIENT_ERROR_BAD_REQUEST, "Invalid user ID!" );
}
catch ( NoSuchEmailException e )
{
getLogger().debug( "Invalid email!", e );
response.setStatus( Status.CLIENT_ERROR_BAD_REQUEST, "Email address not found!" );
}
}
// return null because the status is 202
return null;
}
| public Object post( Context context, Request request, Response response, Object payload )
throws ResourceException
{
UserForgotPasswordRequest forgotPasswordRequest = (UserForgotPasswordRequest) payload;
if ( forgotPasswordRequest != null )
{
UserForgotPasswordResource resource = forgotPasswordRequest.getData();
try
{
if ( !isAnonymousUser( resource.getUserId(), request ) )
{
getNexusSecurity( request ).forgotPassword( resource.getUserId(), resource.getEmail() );
response.setStatus( Status.SUCCESS_ACCEPTED );
}
else
{
response.setStatus( Status.CLIENT_ERROR_BAD_REQUEST, "Anonymous user cannot forget password!" );
getLogger().debug( "Anonymous user forgot password is blocked!" );
}
}
catch ( NoSuchUserException e )
{
getLogger().debug( "Invalid username!", e );
throw new ResourceException( Status.CLIENT_ERROR_BAD_REQUEST, "Invalid username!" );
}
catch ( NoSuchEmailException e )
{
getLogger().debug( "Invalid email!", e );
response.setStatus( Status.CLIENT_ERROR_BAD_REQUEST, "Email address not found!" );
}
}
// return null because the status is 202
return null;
}
|
diff --git a/src/main/java/hudson/plugins/git/converter/RemoteConfigConverter.java b/src/main/java/hudson/plugins/git/converter/RemoteConfigConverter.java
index e9a546a..6da5a57 100644
--- a/src/main/java/hudson/plugins/git/converter/RemoteConfigConverter.java
+++ b/src/main/java/hudson/plugins/git/converter/RemoteConfigConverter.java
@@ -1,129 +1,129 @@
/*
* The MIT License
*
* Copyright (c) 2011, Oracle Corporation, Nikita Levyankov
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package hudson.plugins.git.converter;
import com.thoughtworks.xstream.converters.ConversionException;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.converters.reflection.ReflectionProvider;
import com.thoughtworks.xstream.core.util.CustomObjectInputStream;
import com.thoughtworks.xstream.core.util.HierarchicalStreams;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.mapper.Mapper;
import hudson.util.RobustReflectionConverter;
import java.io.NotActiveException;
import java.io.ObjectInputValidation;
import java.util.Map;
import org.eclipse.jgit.transport.RemoteConfig;
/**
* Converter for RemoteConfig. Supports legacy org.spearce.jgit library
* <p/>
* Date: 7/1/11
*
* @author Nikita Levyankov
*/
public class RemoteConfigConverter extends RobustReflectionConverter implements LegacyConverter<RemoteConfig> {
public RemoteConfigConverter(Mapper mapper, ReflectionProvider provider) {
super(mapper, provider);
}
public boolean canConvert(Class type) {
return RemoteConfig.class == type || org.spearce.jgit.transport.RemoteConfig.class == type;
}
/**
* {@inheritDoc}
*/
public boolean isLegacyNode(HierarchicalStreamReader reader, final UnmarshallingContext context) {
return reader.getNodeName().startsWith("org.spearce");
}
/**
* {@inheritDoc}
*/
public RemoteConfig legacyUnmarshal(final HierarchicalStreamReader reader, final UnmarshallingContext context) {
final org.spearce.jgit.transport.RemoteConfig remoteConfig = new org.spearce.jgit.transport.RemoteConfig();
CustomObjectInputStream.StreamCallback callback = new LegacyInputStreamCallback(reader, context, remoteConfig);
try {
- CustomObjectInputStream objectInput = CustomObjectInputStream.getInstance(context, callback);
+ CustomObjectInputStream objectInput = CustomObjectInputStream.getInstance(context, callback, null);
remoteConfig.readExternal(objectInput);
objectInput.popCallback();
return remoteConfig.toRemote();
} catch (Exception e) {
throw new ConversionException("Unmarshal failed", e);
}
}
public Object unmarshal(final HierarchicalStreamReader reader, final UnmarshallingContext context) {
if (isLegacyNode(reader, context)) {
return legacyUnmarshal(reader, context);
}
return super.unmarshal(reader, context);
}
@Override
protected Object instantiateNewInstance(HierarchicalStreamReader reader, UnmarshallingContext context) {
return reflectionProvider.newInstance(RemoteConfig.class);
}
private class LegacyInputStreamCallback implements CustomObjectInputStream.StreamCallback {
private HierarchicalStreamReader reader;
private UnmarshallingContext context;
private org.spearce.jgit.transport.RemoteConfig remoteConfig;
private LegacyInputStreamCallback(HierarchicalStreamReader reader,
final UnmarshallingContext context,
org.spearce.jgit.transport.RemoteConfig remoteConfig) {
this.reader = reader;
this.context = context;
this.remoteConfig = remoteConfig;
}
public Object readFromStream() {
reader.moveDown();
Class type = HierarchicalStreams.readClassType(reader, mapper);
Object streamItem = context.convertAnother(remoteConfig, type);
reader.moveUp();
return streamItem;
}
public Map readFieldsFromStream() {
throw new UnsupportedOperationException();
}
public void defaultReadObject() {
throw new UnsupportedOperationException();
}
public void registerValidation(ObjectInputValidation validation, int priority) throws NotActiveException {
throw new NotActiveException();
}
public void close() {
throw new UnsupportedOperationException();
}
}
}
| true | true | public RemoteConfig legacyUnmarshal(final HierarchicalStreamReader reader, final UnmarshallingContext context) {
final org.spearce.jgit.transport.RemoteConfig remoteConfig = new org.spearce.jgit.transport.RemoteConfig();
CustomObjectInputStream.StreamCallback callback = new LegacyInputStreamCallback(reader, context, remoteConfig);
try {
CustomObjectInputStream objectInput = CustomObjectInputStream.getInstance(context, callback);
remoteConfig.readExternal(objectInput);
objectInput.popCallback();
return remoteConfig.toRemote();
} catch (Exception e) {
throw new ConversionException("Unmarshal failed", e);
}
}
| public RemoteConfig legacyUnmarshal(final HierarchicalStreamReader reader, final UnmarshallingContext context) {
final org.spearce.jgit.transport.RemoteConfig remoteConfig = new org.spearce.jgit.transport.RemoteConfig();
CustomObjectInputStream.StreamCallback callback = new LegacyInputStreamCallback(reader, context, remoteConfig);
try {
CustomObjectInputStream objectInput = CustomObjectInputStream.getInstance(context, callback, null);
remoteConfig.readExternal(objectInput);
objectInput.popCallback();
return remoteConfig.toRemote();
} catch (Exception e) {
throw new ConversionException("Unmarshal failed", e);
}
}
|
diff --git a/Quizicle/src/quiz/AddRating.java b/Quizicle/src/quiz/AddRating.java
index 6591037..76c0fc9 100644
--- a/Quizicle/src/quiz/AddRating.java
+++ b/Quizicle/src/quiz/AddRating.java
@@ -1,52 +1,59 @@
package quiz;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import user.*;
import database.*;
/**
* Servlet implementation class AddRating
*/
public class AddRating extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public AddRating() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int quizID = Integer.valueOf(request.getParameter("quizID"));
String review = request.getParameter("review");
- int rating = Integer.valueOf(request.getParameter("rating"));
- Rating rate = new Rating(((User)request.getSession().getAttribute("User")).getUserID(), quizID, rating, review);
+ //get rating (1-5) and set equal to 5 if invalid input
+ String rating = request.getParameter("rating");
+ int value;
+ if (rating.equals("1") || rating.equals("2") || rating.equals("3") || rating.equals("4") || rating.equals("5")) {
+ value = Integer.valueOf(rating);
+ } else {
+ value = 5;
+ }
+ Rating rate = new Rating(((User)request.getSession().getAttribute("User")).getUserID(), quizID, value, review);
//Need to check if user has already rated this quiz and handle that
//Right now the sql insert errors out if they've already rated it
RatingBank ratingBank = (RatingBank)getServletContext().getAttribute("RatingBank");
ratingBank.addRating(rate);
RequestDispatcher dispatch = request.getRequestDispatcher("QuizSummary.jsp?id=" + quizID);
dispatch.forward(request, response);
}
}
| true | true | protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int quizID = Integer.valueOf(request.getParameter("quizID"));
String review = request.getParameter("review");
int rating = Integer.valueOf(request.getParameter("rating"));
Rating rate = new Rating(((User)request.getSession().getAttribute("User")).getUserID(), quizID, rating, review);
//Need to check if user has already rated this quiz and handle that
//Right now the sql insert errors out if they've already rated it
RatingBank ratingBank = (RatingBank)getServletContext().getAttribute("RatingBank");
ratingBank.addRating(rate);
RequestDispatcher dispatch = request.getRequestDispatcher("QuizSummary.jsp?id=" + quizID);
dispatch.forward(request, response);
}
| protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int quizID = Integer.valueOf(request.getParameter("quizID"));
String review = request.getParameter("review");
//get rating (1-5) and set equal to 5 if invalid input
String rating = request.getParameter("rating");
int value;
if (rating.equals("1") || rating.equals("2") || rating.equals("3") || rating.equals("4") || rating.equals("5")) {
value = Integer.valueOf(rating);
} else {
value = 5;
}
Rating rate = new Rating(((User)request.getSession().getAttribute("User")).getUserID(), quizID, value, review);
//Need to check if user has already rated this quiz and handle that
//Right now the sql insert errors out if they've already rated it
RatingBank ratingBank = (RatingBank)getServletContext().getAttribute("RatingBank");
ratingBank.addRating(rate);
RequestDispatcher dispatch = request.getRequestDispatcher("QuizSummary.jsp?id=" + quizID);
dispatch.forward(request, response);
}
|
diff --git a/src/game/gameplayStates/Home.java b/src/game/gameplayStates/Home.java
index 8dd38d6..d113387 100644
--- a/src/game/gameplayStates/Home.java
+++ b/src/game/gameplayStates/Home.java
@@ -1,156 +1,157 @@
package game.gameplayStates;
import game.Dialogue;
import game.Enemy;
import game.GameObject;
import game.PauseMenu;
import game.StateManager;
import game.StaticObject;
import game.gameplayStates.GamePlayState.simpleMap;
import game.interactables.Bed;
import game.interactables.Chest;
import game.interactables.ChickenWing;
import game.interactables.Cigarette;
import game.interactables.Door;
import game.interactables.Interactable;
import game.interactables.PortalObject;
import game.player.Player;
import java.util.ArrayList;
import java.util.HashMap;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.state.StateBasedGame;
import org.newdawn.slick.tiled.TiledMap;
public class Home extends GamePlayState {
private int m_previousDreamState;
public Home(int stateID) {
m_stateID = stateID;
}
@Override
public void additionalInit(GameContainer container, StateBasedGame stateManager)
throws SlickException {
m_previousDreamState = StateManager.m_dreamState;
// set player initial location
m_playerX = SIZE*2;
m_playerY = SIZE*4;
// set up map
this.m_tiledMap = new TiledMap("assets/maps/home.tmx");
this.m_map = new simpleMap();
this.setBlockedTiles();
// set up objects that will not change regardless of the game state
if(!this.isLoaded()) {
StaticObject posters =
new StaticObject("posters", 3*SIZE, 1*SIZE, "assets/gameObjects/posters.png");
this.addObject(posters, false);
StaticObject carpet =
new StaticObject("carpet", 3*SIZE, 3*SIZE, "assets/gameObjects/carpet.png");
this.addObject(carpet, false);
StaticObject bedTable =
new StaticObject("bedTable", 4*SIZE, 4*SIZE, "assets/gameObjects/bedTable.png");
bedTable.setRenderPriority(true);
this.addObject(bedTable, false);
m_blocked[4][4] = true;
StaticObject table =
new StaticObject("table", SIZE, 4*SIZE, "assets/gameObjects/table.png");
m_blocked[1][4] = true;
m_blocked[1][5] = true;
this.addObject(table, true);
}
}
@Override
public void setupObjects(int city, int dream) throws SlickException {
if (city == 3 && dream == 3) {
super.removeObject("door");
StaticObject door = new StaticObject("door", 2*SIZE, 2*SIZE, "assets/gameObjects/door.png");
door.setDialogue(new String[] {"Its late out... Perhaps you should just hit the sack"});
this.addObject(door, true);
super.removeObject("bed");
Bed bed = new Bed("bed", 3*SIZE, 5*SIZE, StateManager.TOWN_NIGHT_STATE, -1, -1);
m_blocked[3][5] = true;
m_blocked[4][5] = true;
this.addObject(bed, true);
}
else if (city == 3 && dream == 2) {
super.removeObject("door");
PortalObject door = new Door("door", 2*SIZE, 2*SIZE, StateManager.TOWN_DAY_STATE, 11, 28);
this.addObject(door, true);
super.removeObject("bed");
StaticObject bed = new StaticObject("bed", 3*SIZE, 5*SIZE, "assets/gameObjects/bed.png");
bed.setDialogue(new String[] {"But you just got up..."});
this.addObject(bed, true);
m_blocked[3][5] = true;
m_blocked[4][5] = true;
}
else if (city == 2 && dream == 2) {
super.removeObject("door");
StaticObject door = new StaticObject("door", 2*SIZE, 2*SIZE, "assets/gameObjects/door.png");
door.setDialogue(new String[] {"It's late out... Perhaps you should just hit the sack."});
this.addObject(door, true);
super.removeObject("bed");
Bed bed = new Bed("bed", 3*SIZE, 5*SIZE, StateManager.TOWN_NIGHT_STATE, -1, -1);
+ this.addObject(bed, true);
m_blocked[3][5] = true;
m_blocked[4][5] = true;
}
}
@Override
public void setupDialogue(GameContainer container, int city, int dream) {
if (city == 3 && dream == 3) {
((StaticObject)this.getInteractable("door")).setDialogue(new String[]
{"Its late out... Perhaps you should just hit the sack"});
((StaticObject)this.getInteractable("table")).setDialogue(new String[]
{"1. This your macbook, a safe place to visit your collection of non-moving horses.",
"You can also visit find plenty of friends right here on the internet.. special friends."});
}
else if (city == 3 && dream == 2) {
((StaticObject)this.getInteractable("table")).setDialogue(new String[]
{"2. Woah... that horse is indeed better than a boy.", "maybe i'll buy one"});
}
else if(city == 2 && dream == 2) {
}
}
@Override
public void dialogueListener(Interactable i) {
}
@Override
public void additionalEnter(GameContainer container, StateBasedGame stateManager) {
if(StateManager.m_dreamState==2 && StateManager.m_dreamState != this.m_previousDreamState) {
this.displayDialogue(new String[] {"You wake up. What a strange dream.",
"It seems that the strange humanoid escaped into the zoo. " +
"Perhaps you could somehow block off the zoo, so it won't escape there next time..."});
this.m_previousDreamState = StateManager.m_dreamState;
}
}
}
| true | true | public void setupObjects(int city, int dream) throws SlickException {
if (city == 3 && dream == 3) {
super.removeObject("door");
StaticObject door = new StaticObject("door", 2*SIZE, 2*SIZE, "assets/gameObjects/door.png");
door.setDialogue(new String[] {"Its late out... Perhaps you should just hit the sack"});
this.addObject(door, true);
super.removeObject("bed");
Bed bed = new Bed("bed", 3*SIZE, 5*SIZE, StateManager.TOWN_NIGHT_STATE, -1, -1);
m_blocked[3][5] = true;
m_blocked[4][5] = true;
this.addObject(bed, true);
}
else if (city == 3 && dream == 2) {
super.removeObject("door");
PortalObject door = new Door("door", 2*SIZE, 2*SIZE, StateManager.TOWN_DAY_STATE, 11, 28);
this.addObject(door, true);
super.removeObject("bed");
StaticObject bed = new StaticObject("bed", 3*SIZE, 5*SIZE, "assets/gameObjects/bed.png");
bed.setDialogue(new String[] {"But you just got up..."});
this.addObject(bed, true);
m_blocked[3][5] = true;
m_blocked[4][5] = true;
}
else if (city == 2 && dream == 2) {
super.removeObject("door");
StaticObject door = new StaticObject("door", 2*SIZE, 2*SIZE, "assets/gameObjects/door.png");
door.setDialogue(new String[] {"It's late out... Perhaps you should just hit the sack."});
this.addObject(door, true);
super.removeObject("bed");
Bed bed = new Bed("bed", 3*SIZE, 5*SIZE, StateManager.TOWN_NIGHT_STATE, -1, -1);
m_blocked[3][5] = true;
m_blocked[4][5] = true;
}
}
| public void setupObjects(int city, int dream) throws SlickException {
if (city == 3 && dream == 3) {
super.removeObject("door");
StaticObject door = new StaticObject("door", 2*SIZE, 2*SIZE, "assets/gameObjects/door.png");
door.setDialogue(new String[] {"Its late out... Perhaps you should just hit the sack"});
this.addObject(door, true);
super.removeObject("bed");
Bed bed = new Bed("bed", 3*SIZE, 5*SIZE, StateManager.TOWN_NIGHT_STATE, -1, -1);
m_blocked[3][5] = true;
m_blocked[4][5] = true;
this.addObject(bed, true);
}
else if (city == 3 && dream == 2) {
super.removeObject("door");
PortalObject door = new Door("door", 2*SIZE, 2*SIZE, StateManager.TOWN_DAY_STATE, 11, 28);
this.addObject(door, true);
super.removeObject("bed");
StaticObject bed = new StaticObject("bed", 3*SIZE, 5*SIZE, "assets/gameObjects/bed.png");
bed.setDialogue(new String[] {"But you just got up..."});
this.addObject(bed, true);
m_blocked[3][5] = true;
m_blocked[4][5] = true;
}
else if (city == 2 && dream == 2) {
super.removeObject("door");
StaticObject door = new StaticObject("door", 2*SIZE, 2*SIZE, "assets/gameObjects/door.png");
door.setDialogue(new String[] {"It's late out... Perhaps you should just hit the sack."});
this.addObject(door, true);
super.removeObject("bed");
Bed bed = new Bed("bed", 3*SIZE, 5*SIZE, StateManager.TOWN_NIGHT_STATE, -1, -1);
this.addObject(bed, true);
m_blocked[3][5] = true;
m_blocked[4][5] = true;
}
}
|
diff --git a/farrago/jdbc4/Unwrappable16.java b/farrago/jdbc4/Unwrappable16.java
index ba1a70d8f..65ac8a58a 100644
--- a/farrago/jdbc4/Unwrappable16.java
+++ b/farrago/jdbc4/Unwrappable16.java
@@ -1,53 +1,53 @@
/*
// $Id$
// Package org.eigenbase is a class library of data management components.
// Copyright (C) 2008 The Eigenbase Project
// Copyright (C) 2008 SQLstream, Inc.
// Copyright (C) 2008 Dynamo BI Corporation
//
// 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 approved by The Eigenbase Project.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.eigenbase.jdbc4;
import java.sql.*;
// NOTE jvs 8-Oct 2008: If you are looking at the copy of this file under
// farrago/src/org/eigenbase/jdbc4, do not try to edit it or check it out.
// The original is checked into Perforce under farrago/jdbc4, and
// gets copied to farrago/src/org/eigenbase/jdbc4 by ant createCatalog.
/**
* Gunk for JDBC 4 source compatibility.
* See <a href="http://pub.eigenbase.org/wiki/Jdbc4Transition">Eigenpedia</a>.
*
* @author John Sichi
* @version $Id$
*/
public abstract class Unwrappable implements Wrapper
{
// implement Wrapper
- public boolean isWrapperFor(Class iface)
+ public boolean isWrapperFor(Class<?> iface)
{
return false;
}
// implement Wrapper
public <T> T unwrap(Class<T> iface)
{
throw new UnsupportedOperationException("unwrap");
}
}
// End Unwrappable.java
| true | true | public boolean isWrapperFor(Class iface)
{
return false;
}
| public boolean isWrapperFor(Class<?> iface)
{
return false;
}
|
diff --git a/components/bio-formats/src/loci/formats/in/NikonReader.java b/components/bio-formats/src/loci/formats/in/NikonReader.java
index c8bcabe1f..fa7808b4a 100644
--- a/components/bio-formats/src/loci/formats/in/NikonReader.java
+++ b/components/bio-formats/src/loci/formats/in/NikonReader.java
@@ -1,457 +1,456 @@
//
// NikonReader.java
//
/*
OME Bio-Formats package for reading and converting biological file formats.
Copyright (C) 2005-@year@ UW-Madison LOCI and Glencoe Software, Inc.
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, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package loci.formats.in;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Arrays;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import loci.common.RandomAccessInputStream;
import loci.formats.FormatException;
import loci.formats.FormatTools;
import loci.formats.ImageTools;
import loci.formats.MetadataTools;
import loci.formats.codec.BitBuffer;
import loci.formats.codec.NikonCodec;
import loci.formats.codec.NikonCodecOptions;
import loci.formats.meta.MetadataStore;
import loci.formats.tiff.IFD;
import loci.formats.tiff.IFDList;
import loci.formats.tiff.PhotoInterp;
import loci.formats.tiff.TiffCompression;
import loci.formats.tiff.TiffParser;
import loci.formats.tiff.TiffRational;
/**
* NikonReader is the file format reader for Nikon NEF (TIFF) files.
*
* <dl><dt><b>Source code:</b></dt>
* <dd><a href="http://trac.openmicroscopy.org.uk/ome/browser/bioformats.git/components/bio-formats/src/loci/formats/in/NikonReader.java">Trac</a>,
* <a href="http://git.openmicroscopy.org/?p=bioformats.git;a=blob;f=components/bio-formats/src/loci/formats/in/NikonReader.java;hb=HEAD">Gitweb</a></dd></dl>
*
* @author Melissa Linkert melissa at glencoesoftware.com
*/
public class NikonReader extends BaseTiffReader {
// -- Constants --
/** Logger for this class. */
private static final Logger LOGGER =
LoggerFactory.getLogger(NikonReader.class);
public static final String[] NEF_SUFFIX = {"nef"};
// Tags that give a good indication of whether this is an NEF file.
private static final int TIFF_EPS_STANDARD = 37398;
private static final int COLOR_MAP = 33422;
// Maker Note tags.
private static final int FIRMWARE_VERSION = 1;
private static final int ISO = 2;
private static final int QUALITY = 4;
private static final int MAKER_WHITE_BALANCE = 5;
private static final int SHARPENING = 6;
private static final int FOCUS_MODE = 7;
private static final int FLASH_SETTING = 8;
private static final int FLASH_MODE = 9;
private static final int WHITE_BALANCE_FINE = 11;
private static final int WHITE_BALANCE_RGB_COEFFS = 12;
private static final int FLASH_COMPENSATION = 18;
private static final int TONE_COMPENSATION = 129;
private static final int LENS_TYPE = 131;
private static final int LENS = 132;
private static final int FLASH_USED = 135;
private static final int CURVE = 140;
private static final int COLOR_MODE = 141;
private static final int LIGHT_TYPE = 144;
private static final int HUE = 146;
private static final int CAPTURE_EDITOR_DATA = 3585;
// -- Fields --
/** Offset to the Nikon Maker Note. */
protected int makerNoteOffset;
/** The original IFD. */
protected IFD original;
private TiffRational[] whiteBalance;
private Object cfaPattern;
private int[] curve;
private int[] vPredictor;
private boolean lossyCompression;
private int split = -1;
private byte[] lastPlane = null;
private int lastIndex = -1;
// -- Constructor --
/** Constructs a new Nikon reader. */
public NikonReader() {
super("Nikon NEF", new String[] {"nef", "tif", "tiff"});
suffixSufficient = false;
domains = new String[] {FormatTools.GRAPHICS_DOMAIN};
}
// -- IFormatReader API methods --
/* @see loci.formats.IFormatReader#isThisType(String, boolean) */
public boolean isThisType(String name, boolean open) {
// extension is sufficient as long as it is NEF
if (checkSuffix(name, NEF_SUFFIX)) return true;
return super.isThisType(name, open);
}
/* @see loci.formats.IFormatReader#isThisType(RandomAccessInputStream) */
public boolean isThisType(RandomAccessInputStream stream) throws IOException {
TiffParser tp = new TiffParser(stream);
IFD ifd = tp.getFirstIFD();
if (ifd == null) return false;
if (ifd.containsKey(TIFF_EPS_STANDARD)) return true;
String make = ifd.getIFDTextValue(IFD.MAKE);
return make != null && make.indexOf("Nikon") != -1;
}
/**
* @see loci.formats.IFormatReader#openBytes(int, byte[], int, int, int, int)
*/
public byte[] openBytes(int no, byte[] buf, int x, int y, int w, int h)
throws FormatException, IOException
{
FormatTools.checkPlaneParameters(this, no, buf.length, x, y, w, h);
IFD ifd = ifds.get(no);
int[] bps = ifd.getBitsPerSample();
int dataSize = bps[0];
long[] byteCounts = ifd.getStripByteCounts();
long totalBytes = 0;
for (long b : byteCounts) {
totalBytes += b;
}
if (totalBytes == FormatTools.getPlaneSize(this) || bps.length > 1) {
return super.openBytes(no, buf, x, y, w, h);
}
if (lastPlane == null || lastIndex != no) {
long[] offsets = ifd.getStripOffsets();
boolean maybeCompressed = ifd.getCompression() == TiffCompression.NIKON;
boolean compressed =
vPredictor != null && curve != null && maybeCompressed;
if (!maybeCompressed && dataSize == 14) dataSize = 16;
ByteArrayOutputStream src = new ByteArrayOutputStream();
NikonCodec codec = new NikonCodec();
NikonCodecOptions options = new NikonCodecOptions();
options.width = getSizeX();
options.height = getSizeY();
options.bitsPerSample = dataSize;
options.curve = curve;
if (vPredictor != null) {
options.vPredictor = new int[vPredictor.length];
}
options.lossless = !lossyCompression;
options.split = split;
for (int i=0; i<byteCounts.length; i++) {
byte[] t = new byte[(int) byteCounts[i]];
in.seek(offsets[i]);
in.read(t);
if (compressed) {
options.maxBytes = (int) byteCounts[i];
System.arraycopy(vPredictor, 0, options.vPredictor, 0,
vPredictor.length);
t = codec.decompress(t, options);
}
src.write(t);
}
BitBuffer bb = new BitBuffer(src.toByteArray());
short[] pix = new short[getSizeX() * getSizeY() * 3];
src.close();
int[] colorMap = {1, 0, 2, 1}; // default color map
short[] ifdColors = (short[]) ifd.get(COLOR_MAP);
- boolean colorsValid = false;
if (ifdColors != null && ifdColors.length >= colorMap.length) {
- colorsValid = true;
+ boolean colorsValid = true;
for (int q=0; q<colorMap.length; q++) {
if (ifdColors[q] < 0 || ifdColors[q] > 2) {
// found invalid channel index, use default color map instead
colorsValid = false;
break;
}
}
if (colorsValid) {
for (int q=0; q<colorMap.length; q++) {
colorMap[q] = ifdColors[q];
}
}
}
boolean interleaveRows =
- offsets.length == 1 && !maybeCompressed && !colorsValid;
+ offsets.length == 1 && !maybeCompressed && colorMap[0] != 0;
for (int row=0; row<getSizeY(); row++) {
int realRow = interleaveRows ? (row < (getSizeY() / 2) ?
row * 2 : (row - (getSizeY() / 2)) * 2 + 1) : row;
for (int col=0; col<getSizeX(); col++) {
short val = (short) (bb.getBits(dataSize) & 0xffff);
int mapIndex = (realRow % 2) * 2 + (col % 2);
int redOffset = realRow * getSizeX() + col;
int greenOffset = (getSizeY() + realRow) * getSizeX() + col;
int blueOffset = (2 * getSizeY() + realRow) * getSizeX() + col;
if (colorMap[mapIndex] == 0) {
pix[redOffset] = adjustForWhiteBalance(val, 0);
}
else if (colorMap[mapIndex] == 1) {
pix[greenOffset] = adjustForWhiteBalance(val, 1);
}
else if (colorMap[mapIndex] == 2) {
pix[blueOffset] = adjustForWhiteBalance(val, 2);
}
if (maybeCompressed && !compressed) {
int toSkip = 0;
if ((col % 10) == 9) {
toSkip = 1;
}
if (col == getSizeX() - 1) {
toSkip = 10;
}
bb.skipBits(toSkip * 8);
}
}
}
lastPlane = new byte[FormatTools.getPlaneSize(this)];
ImageTools.interpolate(pix, lastPlane, colorMap, getSizeX(), getSizeY(),
isLittleEndian());
lastIndex = no;
}
int bpp = FormatTools.getBytesPerPixel(getPixelType()) * 3;
int rowLen = w * bpp;
int width = getSizeX() * bpp;
for (int row=0; row<h; row++) {
System.arraycopy(
lastPlane, (row + y) * width + x * bpp, buf, row * rowLen, rowLen);
}
return buf;
}
/* @see loci.formats.IFormatReader#close(boolean) */
public void close(boolean fileOnly) throws IOException {
super.close(fileOnly);
if (!fileOnly) {
makerNoteOffset = 0;
original = null;
split = -1;
whiteBalance = null;
cfaPattern = null;
curve = null;
vPredictor = null;
lossyCompression = false;
lastPlane = null;
lastIndex = -1;
}
}
// -- Internal BaseTiffReader API methods --
/* @see BaseTiffReader#initStandardMetadata() */
protected void initStandardMetadata() throws FormatException, IOException {
super.initStandardMetadata();
// reset image dimensions
// the actual image data is stored in IFDs referenced by the SubIFD tag
// in the 'real' IFD
core[0].imageCount = ifds.size();
IFD firstIFD = ifds.get(0);
PhotoInterp photo = firstIFD.getPhotometricInterpretation();
int samples = firstIFD.getSamplesPerPixel();
core[0].rgb = samples > 1 || photo == PhotoInterp.RGB ||
photo == PhotoInterp.CFA_ARRAY;
if (photo == PhotoInterp.CFA_ARRAY) samples = 3;
core[0].sizeX = (int) firstIFD.getImageWidth();
core[0].sizeY = (int) firstIFD.getImageLength();
core[0].sizeZ = 1;
core[0].sizeC = isRGB() ? samples : 1;
core[0].sizeT = ifds.size();
core[0].pixelType = firstIFD.getPixelType();
core[0].indexed = false;
// now look for the EXIF IFD pointer
IFDList exifIFDs = tiffParser.getExifIFDs();
if (exifIFDs.size() > 0) {
IFD exifIFD = exifIFDs.get(0);
tiffParser.fillInIFD(exifIFD);
// put all the EXIF data in the metadata hashtable
for (Integer key : exifIFD.keySet()) {
int tag = key.intValue();
String name = IFD.getIFDTagName(tag);
if (tag == IFD.CFA_PATTERN) {
byte[] cfa = (byte[]) exifIFD.get(key);
int[] colorMap = new int[cfa.length];
for (int i=0; i<cfa.length; i++) colorMap[i] = (int) cfa[i];
addGlobalMeta(name, colorMap);
cfaPattern = colorMap;
}
else {
addGlobalMeta(name, exifIFD.get(key));
if (name.equals("MAKER_NOTE")) {
byte[] b = (byte[]) exifIFD.get(key);
int extra = new String(b, 0, 10).startsWith("Nikon") ? 10 : 0;
byte[] buf = new byte[b.length];
System.arraycopy(b, extra, buf, 0, buf.length - extra);
RandomAccessInputStream makerNote =
new RandomAccessInputStream(buf);
TiffParser tp = new TiffParser(makerNote);
IFD note = null;
try {
note = tp.getFirstIFD();
}
catch (Exception e) {
LOGGER.debug("Failed to parse first IFD", e);
}
if (note != null) {
for (Integer nextKey : note.keySet()) {
int nextTag = nextKey.intValue();
addGlobalMeta(name, note.get(nextKey));
if (nextTag == 150) {
b = (byte[]) note.get(nextKey);
RandomAccessInputStream s = new RandomAccessInputStream(b);
byte check1 = s.readByte();
byte check2 = s.readByte();
lossyCompression = check1 != 0x46;
vPredictor = new int[4];
for (int q=0; q<vPredictor.length; q++) {
vPredictor[q] = s.readShort();
}
curve = new int[16385];
int bps = ifds.get(0).getBitsPerSample()[0];
int max = 1 << bps & 0x7fff;
int step = 0;
int csize = s.readShort();
if (csize > 1) {
step = max / (csize - 1);
}
if (check1 == 0x44 && check2 == 0x20 && step > 0) {
for (int i=0; i<csize; i++) {
curve[i * step] = s.readShort();
}
for (int i=0; i<max; i++) {
int n = i % step;
curve[i] = (curve[i - n] * (step - n) +
curve[i - n + step] * n) / step;
}
s.seek(562);
split = s.readShort();
}
else {
int maxValue = (int) Math.pow(2, bps) - 1;
Arrays.fill(curve, maxValue);
int nElements =
(int) (s.length() - s.getFilePointer()) / 2;
if (nElements < 100) {
for (int i=0; i<curve.length; i++) {
curve[i] = (short) i;
}
}
else {
for (int q=0; q<nElements; q++) {
curve[q] = s.readShort();
}
}
}
s.close();
}
else if (nextTag == WHITE_BALANCE_RGB_COEFFS) {
whiteBalance = (TiffRational[]) note.get(nextKey);
}
}
}
makerNote.close();
}
}
}
}
}
// -- Internal FormatReader API methods --
/* @see loci.formats.FormatReader#initFile(String) */
protected void initFile(String id) throws FormatException, IOException {
super.initFile(id);
original = ifds.get(0);
if (cfaPattern != null) {
original.putIFDValue(IFD.COLOR_MAP, (int[]) cfaPattern);
}
ifds.set(0, original);
core[0].imageCount = 1;
core[0].sizeT = 1;
if (ifds.get(0).getSamplesPerPixel() == 1) {
core[0].interleaved = true;
}
MetadataStore store = makeFilterMetadata();
MetadataTools.populatePixels(store, this);
}
// -- Helper methods --
private short adjustForWhiteBalance(short val, int index) {
if (whiteBalance != null && whiteBalance.length == 3) {
return (short) (val * whiteBalance[index].doubleValue());
}
return val;
}
}
| false | true | public byte[] openBytes(int no, byte[] buf, int x, int y, int w, int h)
throws FormatException, IOException
{
FormatTools.checkPlaneParameters(this, no, buf.length, x, y, w, h);
IFD ifd = ifds.get(no);
int[] bps = ifd.getBitsPerSample();
int dataSize = bps[0];
long[] byteCounts = ifd.getStripByteCounts();
long totalBytes = 0;
for (long b : byteCounts) {
totalBytes += b;
}
if (totalBytes == FormatTools.getPlaneSize(this) || bps.length > 1) {
return super.openBytes(no, buf, x, y, w, h);
}
if (lastPlane == null || lastIndex != no) {
long[] offsets = ifd.getStripOffsets();
boolean maybeCompressed = ifd.getCompression() == TiffCompression.NIKON;
boolean compressed =
vPredictor != null && curve != null && maybeCompressed;
if (!maybeCompressed && dataSize == 14) dataSize = 16;
ByteArrayOutputStream src = new ByteArrayOutputStream();
NikonCodec codec = new NikonCodec();
NikonCodecOptions options = new NikonCodecOptions();
options.width = getSizeX();
options.height = getSizeY();
options.bitsPerSample = dataSize;
options.curve = curve;
if (vPredictor != null) {
options.vPredictor = new int[vPredictor.length];
}
options.lossless = !lossyCompression;
options.split = split;
for (int i=0; i<byteCounts.length; i++) {
byte[] t = new byte[(int) byteCounts[i]];
in.seek(offsets[i]);
in.read(t);
if (compressed) {
options.maxBytes = (int) byteCounts[i];
System.arraycopy(vPredictor, 0, options.vPredictor, 0,
vPredictor.length);
t = codec.decompress(t, options);
}
src.write(t);
}
BitBuffer bb = new BitBuffer(src.toByteArray());
short[] pix = new short[getSizeX() * getSizeY() * 3];
src.close();
int[] colorMap = {1, 0, 2, 1}; // default color map
short[] ifdColors = (short[]) ifd.get(COLOR_MAP);
boolean colorsValid = false;
if (ifdColors != null && ifdColors.length >= colorMap.length) {
colorsValid = true;
for (int q=0; q<colorMap.length; q++) {
if (ifdColors[q] < 0 || ifdColors[q] > 2) {
// found invalid channel index, use default color map instead
colorsValid = false;
break;
}
}
if (colorsValid) {
for (int q=0; q<colorMap.length; q++) {
colorMap[q] = ifdColors[q];
}
}
}
boolean interleaveRows =
offsets.length == 1 && !maybeCompressed && !colorsValid;
for (int row=0; row<getSizeY(); row++) {
int realRow = interleaveRows ? (row < (getSizeY() / 2) ?
row * 2 : (row - (getSizeY() / 2)) * 2 + 1) : row;
for (int col=0; col<getSizeX(); col++) {
short val = (short) (bb.getBits(dataSize) & 0xffff);
int mapIndex = (realRow % 2) * 2 + (col % 2);
int redOffset = realRow * getSizeX() + col;
int greenOffset = (getSizeY() + realRow) * getSizeX() + col;
int blueOffset = (2 * getSizeY() + realRow) * getSizeX() + col;
if (colorMap[mapIndex] == 0) {
pix[redOffset] = adjustForWhiteBalance(val, 0);
}
else if (colorMap[mapIndex] == 1) {
pix[greenOffset] = adjustForWhiteBalance(val, 1);
}
else if (colorMap[mapIndex] == 2) {
pix[blueOffset] = adjustForWhiteBalance(val, 2);
}
if (maybeCompressed && !compressed) {
int toSkip = 0;
if ((col % 10) == 9) {
toSkip = 1;
}
if (col == getSizeX() - 1) {
toSkip = 10;
}
bb.skipBits(toSkip * 8);
}
}
}
lastPlane = new byte[FormatTools.getPlaneSize(this)];
ImageTools.interpolate(pix, lastPlane, colorMap, getSizeX(), getSizeY(),
isLittleEndian());
lastIndex = no;
}
int bpp = FormatTools.getBytesPerPixel(getPixelType()) * 3;
int rowLen = w * bpp;
int width = getSizeX() * bpp;
for (int row=0; row<h; row++) {
System.arraycopy(
lastPlane, (row + y) * width + x * bpp, buf, row * rowLen, rowLen);
}
return buf;
}
| public byte[] openBytes(int no, byte[] buf, int x, int y, int w, int h)
throws FormatException, IOException
{
FormatTools.checkPlaneParameters(this, no, buf.length, x, y, w, h);
IFD ifd = ifds.get(no);
int[] bps = ifd.getBitsPerSample();
int dataSize = bps[0];
long[] byteCounts = ifd.getStripByteCounts();
long totalBytes = 0;
for (long b : byteCounts) {
totalBytes += b;
}
if (totalBytes == FormatTools.getPlaneSize(this) || bps.length > 1) {
return super.openBytes(no, buf, x, y, w, h);
}
if (lastPlane == null || lastIndex != no) {
long[] offsets = ifd.getStripOffsets();
boolean maybeCompressed = ifd.getCompression() == TiffCompression.NIKON;
boolean compressed =
vPredictor != null && curve != null && maybeCompressed;
if (!maybeCompressed && dataSize == 14) dataSize = 16;
ByteArrayOutputStream src = new ByteArrayOutputStream();
NikonCodec codec = new NikonCodec();
NikonCodecOptions options = new NikonCodecOptions();
options.width = getSizeX();
options.height = getSizeY();
options.bitsPerSample = dataSize;
options.curve = curve;
if (vPredictor != null) {
options.vPredictor = new int[vPredictor.length];
}
options.lossless = !lossyCompression;
options.split = split;
for (int i=0; i<byteCounts.length; i++) {
byte[] t = new byte[(int) byteCounts[i]];
in.seek(offsets[i]);
in.read(t);
if (compressed) {
options.maxBytes = (int) byteCounts[i];
System.arraycopy(vPredictor, 0, options.vPredictor, 0,
vPredictor.length);
t = codec.decompress(t, options);
}
src.write(t);
}
BitBuffer bb = new BitBuffer(src.toByteArray());
short[] pix = new short[getSizeX() * getSizeY() * 3];
src.close();
int[] colorMap = {1, 0, 2, 1}; // default color map
short[] ifdColors = (short[]) ifd.get(COLOR_MAP);
if (ifdColors != null && ifdColors.length >= colorMap.length) {
boolean colorsValid = true;
for (int q=0; q<colorMap.length; q++) {
if (ifdColors[q] < 0 || ifdColors[q] > 2) {
// found invalid channel index, use default color map instead
colorsValid = false;
break;
}
}
if (colorsValid) {
for (int q=0; q<colorMap.length; q++) {
colorMap[q] = ifdColors[q];
}
}
}
boolean interleaveRows =
offsets.length == 1 && !maybeCompressed && colorMap[0] != 0;
for (int row=0; row<getSizeY(); row++) {
int realRow = interleaveRows ? (row < (getSizeY() / 2) ?
row * 2 : (row - (getSizeY() / 2)) * 2 + 1) : row;
for (int col=0; col<getSizeX(); col++) {
short val = (short) (bb.getBits(dataSize) & 0xffff);
int mapIndex = (realRow % 2) * 2 + (col % 2);
int redOffset = realRow * getSizeX() + col;
int greenOffset = (getSizeY() + realRow) * getSizeX() + col;
int blueOffset = (2 * getSizeY() + realRow) * getSizeX() + col;
if (colorMap[mapIndex] == 0) {
pix[redOffset] = adjustForWhiteBalance(val, 0);
}
else if (colorMap[mapIndex] == 1) {
pix[greenOffset] = adjustForWhiteBalance(val, 1);
}
else if (colorMap[mapIndex] == 2) {
pix[blueOffset] = adjustForWhiteBalance(val, 2);
}
if (maybeCompressed && !compressed) {
int toSkip = 0;
if ((col % 10) == 9) {
toSkip = 1;
}
if (col == getSizeX() - 1) {
toSkip = 10;
}
bb.skipBits(toSkip * 8);
}
}
}
lastPlane = new byte[FormatTools.getPlaneSize(this)];
ImageTools.interpolate(pix, lastPlane, colorMap, getSizeX(), getSizeY(),
isLittleEndian());
lastIndex = no;
}
int bpp = FormatTools.getBytesPerPixel(getPixelType()) * 3;
int rowLen = w * bpp;
int width = getSizeX() * bpp;
for (int row=0; row<h; row++) {
System.arraycopy(
lastPlane, (row + y) * width + x * bpp, buf, row * rowLen, rowLen);
}
return buf;
}
|
diff --git a/MPesaXlsImporter/src/test/java/ke/co/safaricom/MPesaXlsImporterTest.java b/MPesaXlsImporter/src/test/java/ke/co/safaricom/MPesaXlsImporterTest.java
index c974c0c..41b0e25 100644
--- a/MPesaXlsImporter/src/test/java/ke/co/safaricom/MPesaXlsImporterTest.java
+++ b/MPesaXlsImporter/src/test/java/ke/co/safaricom/MPesaXlsImporterTest.java
@@ -1,132 +1,132 @@
/*
* Copyright (c) 2005-2010 Grameen Foundation USA
* 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.
*
* See also http://www.apache.org/licenses/LICENSE-2.0.html for an
* explanation of the license and how it is applied.
*/
package ke.co.safaricom;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.when;
import java.io.FileInputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.apache.poi.ss.usermodel.Cell;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mifos.accounts.api.AccountPaymentParametersDto;
import org.mifos.accounts.api.AccountReferenceDto;
import org.mifos.accounts.api.AccountService;
import org.mifos.accounts.api.InvalidPaymentReason;
import org.mifos.accounts.api.PaymentTypeDto;
import org.mifos.accounts.api.UserReferenceDto;
import org.mifos.spi.ParseResultDto;
import org.mifos.spi.TransactionImport;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
@RunWith(MockitoJUnitRunner.class)
public class MPesaXlsImporterTest {
TransactionImport transactionImport;
MPesaXlsImporter concreteImporter;
@Mock
AccountService accountService;
@Mock
AccountReferenceDto account;
@Mock
UserReferenceDto userReferenceDto;
@Mock
PaymentTypeDto paymentTypeDto;
List<InvalidPaymentReason> noErrors = new ArrayList<InvalidPaymentReason>();
private final int fakeMifosAccountId = 2;
/**
* Would rather use {@link BeforeClass}, but this causes Mockito to throw an exception insisting that
* "MockitoRunner can only be used with Junit 4.4 or higher."
*/
@Before
public void setUpBeforeMethod() throws Exception {
concreteImporter = new MPesaXlsImporter();
transactionImport = concreteImporter;
transactionImport.setAccountService(accountService);
transactionImport.setUserReferenceDto(userReferenceDto);
when(accountService.validatePayment(any(AccountPaymentParametersDto.class))).thenReturn(noErrors);
when(
accountService.lookupLoanAccountReferenceFromClientGovernmentIdAndLoanProductShortName(anyString(),
anyString())).thenReturn(account);
when(
accountService.lookupSavingsAccountReferenceFromClientGovernmentIdAndSavingsProductShortName(
anyString(), anyString())).thenReturn(account);
- when(accountService.getTotalPayementDueAmount(any(AccountReferenceDto.class))).thenReturn(
+ when(accountService.getTotalPaymentDueAmount(any(AccountReferenceDto.class))).thenReturn(
BigDecimal.valueOf(1000.0));
when(account.getAccountId()).thenReturn(fakeMifosAccountId);
when(paymentTypeDto.getName()).thenReturn(MPesaXlsImporter.PAYMENT_TYPE);
List<PaymentTypeDto> paymentTypeList = new ArrayList<PaymentTypeDto>();
paymentTypeList.add(paymentTypeDto);
when(accountService.getLoanPaymentTypes()).thenReturn(paymentTypeList);
}
/**
* Would rather use {@link AfterClass}, but this causes Mockito to throw an exception insisting that
* "MockitoRunner can only be used with Junit 4.4 or higher."
*/
@After
public void tearDownAfterMethod() {
transactionImport = null;
concreteImporter = null;
}
@Test
public void successfulImport() throws Exception {
String testDataFilename = this.getClass().getResource("/example_import.xls").getFile();
ParseResultDto result = transactionImport.parse(new FileInputStream(testDataFilename));
assertThat(result.getParseErrors().toString(), result.getParseErrors().size(), is(0));
assertThat(result.getSuccessfullyParsedRows().size(), is(9));
assertThat(result.getSuccessfullyParsedRows().get(1).getAccount().getAccountId(), is(fakeMifosAccountId));
}
@Test
public void canParseClientIdentifiers() {
assertThat(concreteImporter.parseClientIdentifiers("28 bl"), is(new String[] { "28", "bl" }));
}
@Mock
Cell cellWithDate;
@Test
public void canParseTextBasedDate() throws Exception {
String fakeDateString = "2009-10-15 14:52:51";
when(cellWithDate.getCellType()).thenReturn(Cell.CELL_TYPE_STRING);
when(cellWithDate.getStringCellValue()).thenReturn(fakeDateString);
Date expected = new SimpleDateFormat(MPesaXlsImporter.dateFormat).parse(fakeDateString);
assertThat(concreteImporter.getDate(cellWithDate), is(expected));
}
}
| true | true | public void setUpBeforeMethod() throws Exception {
concreteImporter = new MPesaXlsImporter();
transactionImport = concreteImporter;
transactionImport.setAccountService(accountService);
transactionImport.setUserReferenceDto(userReferenceDto);
when(accountService.validatePayment(any(AccountPaymentParametersDto.class))).thenReturn(noErrors);
when(
accountService.lookupLoanAccountReferenceFromClientGovernmentIdAndLoanProductShortName(anyString(),
anyString())).thenReturn(account);
when(
accountService.lookupSavingsAccountReferenceFromClientGovernmentIdAndSavingsProductShortName(
anyString(), anyString())).thenReturn(account);
when(accountService.getTotalPayementDueAmount(any(AccountReferenceDto.class))).thenReturn(
BigDecimal.valueOf(1000.0));
when(account.getAccountId()).thenReturn(fakeMifosAccountId);
when(paymentTypeDto.getName()).thenReturn(MPesaXlsImporter.PAYMENT_TYPE);
List<PaymentTypeDto> paymentTypeList = new ArrayList<PaymentTypeDto>();
paymentTypeList.add(paymentTypeDto);
when(accountService.getLoanPaymentTypes()).thenReturn(paymentTypeList);
}
| public void setUpBeforeMethod() throws Exception {
concreteImporter = new MPesaXlsImporter();
transactionImport = concreteImporter;
transactionImport.setAccountService(accountService);
transactionImport.setUserReferenceDto(userReferenceDto);
when(accountService.validatePayment(any(AccountPaymentParametersDto.class))).thenReturn(noErrors);
when(
accountService.lookupLoanAccountReferenceFromClientGovernmentIdAndLoanProductShortName(anyString(),
anyString())).thenReturn(account);
when(
accountService.lookupSavingsAccountReferenceFromClientGovernmentIdAndSavingsProductShortName(
anyString(), anyString())).thenReturn(account);
when(accountService.getTotalPaymentDueAmount(any(AccountReferenceDto.class))).thenReturn(
BigDecimal.valueOf(1000.0));
when(account.getAccountId()).thenReturn(fakeMifosAccountId);
when(paymentTypeDto.getName()).thenReturn(MPesaXlsImporter.PAYMENT_TYPE);
List<PaymentTypeDto> paymentTypeList = new ArrayList<PaymentTypeDto>();
paymentTypeList.add(paymentTypeDto);
when(accountService.getLoanPaymentTypes()).thenReturn(paymentTypeList);
}
|
diff --git a/src/java/ru/gispro/petrores/doc/controller/CreateDocumentController.java b/src/java/ru/gispro/petrores/doc/controller/CreateDocumentController.java
index 10b562b..93a82dc 100644
--- a/src/java/ru/gispro/petrores/doc/controller/CreateDocumentController.java
+++ b/src/java/ru/gispro/petrores/doc/controller/CreateDocumentController.java
@@ -1,701 +1,702 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package ru.gispro.petrores.doc.controller;
import java.io.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.management.RuntimeErrorException;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.servlet.ServletContext;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.Produces;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;
import org.apache.commons.io.output.NullOutputStream;
import org.codehaus.jackson.JsonEncoding;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.map.AnnotationIntrospector;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.node.ObjectNode;
import org.codehaus.jackson.xc.JaxbAnnotationIntrospector;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.context.ServletContextAware;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.View;
import ru.gispro.petrores.doc.entities.*;
import ru.gispro.petrores.doc.entities.File;
import ru.gispro.petrores.doc.entities.Files;
import ru.gispro.petrores.doc.util.Util;
import ru.gispro.petrores.doc.view.JsonView;
/**
*
* @author fkravchenko
*/
@Controller
@RequestMapping(value = "/newDocument")
public class CreateDocumentController{// implements ServletContextAware{
@PersistenceContext(unitName = "petro21PU")
protected EntityManager entityManager;
//private ServletContext servletContext;
private String rootPath = null;
private static DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
//private static JsonView view = new JsonView();
public CreateDocumentController() {
}
@RequestMapping(method = RequestMethod.POST)
//@Produces({"application/json"})
//@ResponseStatus(HttpStatus.CREATED)
@Transactional
public void create(HttpServletRequest req, HttpServletResponse resp) throws Exception {
ObjectMapper mapper = new ObjectMapper();
resp.setHeader("Content-Type", "text/html; charset=UTF-8"); // "application/json");
try{
if(!ServletFileUpload.isMultipartContent(req)){
Document doc = new Document();
ArrayList<Author>authors = new ArrayList<Author>(3);
ArrayList<String>directories = new ArrayList<String>(3);
ArrayList<GeoObject>geoObjects = new ArrayList<GeoObject>(3);
ArrayList<Word>words = new ArrayList<Word>(3);
// Parse the request
Map<String, String[]> params = req.getParameterMap();
Iterator<Map.Entry<String, String[]>>iter = params.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry<String, String[]> item = iter.next();
String name = item.getKey();
String[]value = item.getValue();
{
if("domain".equals(name)){
//Long id = Long.parseLong(Streams.asString(stream, "UTF-8"));
//Domain domain = entityManager.find(Domain.class, id);
Domain domain = mapper.readValue(value[0], Domain.class);
//Domain domain = entityManager.find(Domain.class, mapper.readValue(stream, Domain.class).getId());
doc.setDomain(domain);
/*midPath = domain.getPathPart();
while(domain.getParent()!=null && domain.getParent().getId()!=domain.getId()){
domain = domain.getParent();
midPath = domain.getPathPart() + java.io.File.separator + midPath;
}
midPath = getMidPath(midPath);
realPath = new java.io.File(getRootPath(req) + midPath);
realPath.mkdirs();*/
}else{
if("year".equals(name)){
String s = value[0].trim();
if(s.length()!=0)
doc.setYear(Integer.parseInt(s));
}else if("id".equals(name)){
String s = value[0].trim();
if(s.length()!=0)
doc.setId(Long.parseLong(s));
}else if("number".equals(name)){
String s = value[0].trim();
if(s.length()!=0)
doc.setNumber(s);
}else if("archiveNumber".equals(name)){
String s = value[0].trim();
if(s.length()!=0)
doc.setArchiveNumber(s);
}else if("title".equals(name)){
String s = value[0].trim();
if(s.length()!=0)
doc.setTitle(s);
}else if("fullTitle".equals(name)){
String s = value[0].trim();
if(s.length()!=0)
doc.setFullTitle(s);
}else if("comment".equals(name)){
String s = value[0].trim();
if(s.length()!=0)
doc.setComment(s);
}else if("originationDetails".equals(name)){
String s = value[0].trim();
if(s.length()!=0)
doc.setOriginationDetails(s);
}else if("limitationDetails".equals(name)){
String s = value[0].trim();
if(s.length()!=0)
doc.setLimitationDetails(s);
}else if("originationDate".equals(name)){
String s = value[0].trim();
if(s.length()!=0)
doc.setOriginationDate(df.parse(s));
}else if("approvalDate".equals(name)){
String s = value[0].trim();
if(s.length()!=0)
doc.setApprovalDate(df.parse(s));
}else if("registrationDate".equals(name)){
String s = value[0].trim();
if(s.length()!=0)
doc.setRegistrationDate(df.parse(s));
}else if("placementDate".equals(name)){
String s = value[0].trim();
if(s.length()!=0)
doc.setPlacementDate(df.parse(s));
}else if("type".equals(name)){
doc.setType(mapper.readValue(value[0], Type.class));
}else if("stage".equals(name)){
doc.setStage(mapper.readValue(value[0], Stage.class));
}else if("site".equals(name)){
doc.setSite(mapper.readValue(value[0], Site.class));
}else if("author".equals(name)){
for(String val: value){
authors.add(mapper.readValue(val, Author.class));
}
}else if("directory".equals(name)){
for(String val: value){
directories.add(val);
}
}else if("geoObjects".equals(name)){
if(!value[0].equals("\"\"")){
GeoObject[] gos = mapper.readValue(value[0], GeoObject[].class);
geoObjects.addAll(Arrays.asList(gos));
}
}else if("words".equals(name)){
if(!value[0].equals("\"\"")){
Word[] gos = mapper.readValue(value[0], Word[].class);
words.addAll(Arrays.asList(gos));
}
}else if("geometryType".equals(name)){
if(!value[0].equals("\"\""))
doc.setGeometryType(mapper.readValue(value[0], GeoType.class));
}else if("periodicity".equals(name)){
if(!value[0].equals("\"\""))
doc.setPeriodicity(mapper.readValue(value[0], Periodicity.class));
}else if("classification".equals(name)){
if(!value[0].equals("\"\""))
doc.setClassification(mapper.readValue(value[0], Classification.class));
}else if("typeOfWork".equals(name)){
if(!value[0].equals("\"\""))
doc.setTypeOfWork(mapper.readValue(value[0], TypeOfWork.class));
}else if("workProcess".equals(name)){
if(!value[0].equals("\"\""))
doc.setWorkProcess(mapper.readValue(value[0], WorkProcess.class));
}else if("scale".equals(name)){
String s = value[0].trim();
if(s.length()!=0)
doc.setScale(Integer.parseInt(s));
}else if("resolution".equals(name)){
String s = value[0].trim();
if(s.length()!=0)
doc.setResolution(Integer.parseInt(s));
}else if("projection".equals(name)){
if(!value[0].equals("\"\""))
doc.setProjection(mapper.readValue(value[0], Projection.class));
//String s = value[0].trim();
//if(s.length()!=0)
// doc.setProjectionCode(s);
}else{
// throw away yet
//Streams.asString(stream);
}
}
}
}
//Files ret = new Files(files, (long)files.size());
ArrayList<Author> a2 = new ArrayList(authors.size());
for(Author a: authors){
a2.add(entityManager.find(Author.class, a.getId()));
}
ArrayList<Word> w2 = new ArrayList(authors.size());
for(Word a: words){
Word w = entityManager.find(Word.class, a.getWord());
if(w==null){
//w = a;
w = entityManager.merge(a);
}
w2.add(w);
}
Query q = entityManager.createQuery(
"SELECT f FROM File f WHERE f.path = :path");
ArrayList<File>files = new ArrayList<File>(directories.size());
for(String a: directories){
q.setParameter("path", a);
File f;
List<File>fs = q.getResultList();
if(!fs.isEmpty()){
f = fs.get(0);
}else{
f = new File();
f.setPath(a);
f.setDocument(doc);
f.setFileName("");
f.setMimeType("directory");
}
files.add(f);
}
ArrayList<GeoObject> go2 = new ArrayList(geoObjects.size());
q = entityManager.createQuery(
"SELECT object(o) "
+ "FROM GeoObject AS o "
+ "WHERE o.idInTable = :idInTable "
+ "AND o.tableName = :tableName");
for(GeoObject a: geoObjects){
q.setParameter("idInTable", a.getIdInTable());
q.setParameter("tableName", a.getTableName());
List<GeoObject> goes = q.getResultList();
if(!goes.isEmpty()){
a = goes.get(0);
}else{
a = entityManager.merge(a);
}
go2.add(a);
}
entityManager.flush();
doc.setAuthors(a2);
doc.setGeoObjects(go2);
doc.setFiles(files);
doc.setPlacementDate(new Date());
doc.setWords(w2);
Author placer = (Author) entityManager.
createNamedQuery("Author.findByLogin").
setParameter("login", req.getUserPrincipal().getName()).
getResultList().get(0);
doc.setPlacer(placer);
entityManager.merge(doc);
entityManager.flush();
//for(File f: files){
// f.setDocument(doc);
//}
//entityManager.flush();
Documents ret = new Documents(Arrays.asList(new Document[]{doc}), 1l);
/*ModelMap map = new ModelMap(ret);
map.addAttribute("success", true);
//View view = new JsonView();
ModelAndView mv = new ModelAndView(view, map);
return mv;*/
AnnotationIntrospector introspector = new JaxbAnnotationIntrospector();
mapper.getDeserializationConfig().setAnnotationIntrospector(introspector);
mapper.getSerializationConfig().setAnnotationIntrospector(introspector);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Util.DoubleOutput udo = new Util.DoubleOutput(baos, resp.getOutputStream());
JsonGenerator generator = mapper.getJsonFactory().createJsonGenerator(udo, JsonEncoding.UTF8);
ObjectNode json = mapper.valueToTree(ret);
json.put("success", true);
mapper.writeTree(generator, json);
generator.flush();
doc.setCondensed(baos.toString("UTF-8"));
entityManager.flush();
}else{
Document doc = new Document();
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload();
upload.setHeaderEncoding("UTF-8");
//String path = null;
java.io.File realPath = null;
String midPath = null;
ArrayList<File> files = new ArrayList<File>(3);
ArrayList<Author>authors = new ArrayList<Author>(3);
ArrayList<String>directories = new ArrayList<String>(3);
ArrayList<GeoObject>geoObjects = new ArrayList<GeoObject>(3);
ArrayList<Word>words = new ArrayList<Word>(3);
// Parse the request
FileItemIterator iter = upload.getItemIterator(req);
while (iter.hasNext()) {
FileItemStream item = iter.next();
String name = item.getFieldName();
InputStream stream = item.openStream();
if (item.isFormField()) {
if("domain".equals(name)){
//Long id = Long.parseLong(Streams.asString(stream, "UTF-8"));
//Domain domain = entityManager.find(Domain.class, id);
Domain domain = mapper.readValue(stream, Domain.class);
//Domain domain = entityManager.find(Domain.class, mapper.readValue(stream, Domain.class).getId());
doc.setDomain(domain);
midPath = domain.getPathPart();
while(domain.getParent()!=null && domain.getParent().getId()!=domain.getId()){
domain = domain.getParent();
midPath = domain.getPathPart() + java.io.File.separator + midPath;
}
midPath = getMidPath(midPath);
realPath = new java.io.File(getRootPath(req) + midPath);
realPath.mkdirs();
}else{
if("year".equals(name)){
String s = Streams.asString(stream).trim();
if(s.length()!=0)
doc.setYear(Integer.parseInt(s));
}else if("number".equals(name)){
String s = Streams.asString(stream, "UTF-8").trim();
if(s.length()!=0)
doc.setNumber(s);
}else if("archiveNumber".equals(name)){
String s = Streams.asString(stream, "UTF-8").trim();
if(s.length()!=0)
doc.setArchiveNumber(s);
}else if("title".equals(name)){
String s = Streams.asString(stream, "UTF-8").trim();
if(s.length()!=0)
doc.setTitle(s);
}else if("fullTitle".equals(name)){
String s = Streams.asString(stream, "UTF-8").trim();
if(s.length()!=0)
doc.setFullTitle(s);
}else if("comment".equals(name)){
String s = Streams.asString(stream, "UTF-8").trim();
if(s.length()!=0)
doc.setComment(s);
}else if("originationDetails".equals(name)){
String s = Streams.asString(stream, "UTF-8").trim();
if(s.length()!=0)
doc.setOriginationDetails(s);
}else if("limitationDetails".equals(name)){
String s = Streams.asString(stream, "UTF-8").trim();
if(s.length()!=0)
doc.setLimitationDetails(s);
}else if("originationDate".equals(name)){
String s = Streams.asString(stream, "UTF-8").trim();
if(s.length()!=0)
doc.setOriginationDate(df.parse(s));
}else if("approvalDate".equals(name)){
String s = Streams.asString(stream, "UTF-8").trim();
if(s.length()!=0)
doc.setApprovalDate(df.parse(s));
}else if("registrationDate".equals(name)){
String s = Streams.asString(stream, "UTF-8").trim();
if(s.length()!=0)
doc.setRegistrationDate(df.parse(s));
}else if("placementDate".equals(name)){
String s = Streams.asString(stream, "UTF-8").trim();
if(s.length()!=0)
doc.setPlacementDate(df.parse(s));
}else if("type".equals(name)){
doc.setType(mapper.readValue(stream, Type.class));
}else if("stage".equals(name)){
doc.setStage(mapper.readValue(stream, Stage.class));
}else if("site".equals(name)){
doc.setSite(mapper.readValue(stream, Site.class));
}else if("author".equals(name)){
authors.add(mapper.readValue(stream, Author.class));
}else if("directory".equals(name)){
directories.add(Streams.asString(stream, "UTF-8"));
}else if("geoObjects".equals(name)){
GeoObject[] gos = mapper.readValue(stream, GeoObject[].class);
geoObjects.addAll(Arrays.asList(gos));
//doc.setSite(mapper.readValue(stream, Site.class));
}else if("words".equals(name)){
Word[] gos = mapper.readValue(stream, Word[].class);
words.addAll(Arrays.asList(gos));
}else if("geometryType".equals(name)){
doc.setGeometryType(mapper.readValue(stream, GeoType.class));
}else if("periodicity".equals(name)){
doc.setPeriodicity(mapper.readValue(stream, Periodicity.class));
}else if("typeOfWork".equals(name)){
doc.setTypeOfWork(mapper.readValue(stream, TypeOfWork.class));
}else if("workProcess".equals(name)){
doc.setWorkProcess(mapper.readValue(stream, WorkProcess.class));
}else if("classification".equals(name)){
doc.setClassification(mapper.readValue(stream, Classification.class));
}else if("scale".equals(name)){
String s = Streams.asString(stream, "UTF-8").trim();
if(s.length()!=0)
doc.setScale(Integer.parseInt(s));
}else if("resolution".equals(name)){
String s = Streams.asString(stream, "UTF-8").trim();
if(s.length()!=0)
doc.setResolution(Integer.parseInt(s));
}else if("projection".equals(name)){
doc.setProjection(mapper.readValue(stream, Projection.class));
//String s = Streams.asString(stream, "UTF-8").trim();
//if(s.length()!=0)
// doc.setProjectionCode(s);
}else{
// throw away yet
Streams.asString(stream);
}
}
} else {
if(midPath==null){
//throw new RuntimeException("No path met");
JsonGenerator generator = mapper.getJsonFactory().createJsonGenerator(resp.getOutputStream(), JsonEncoding.UTF8);
ObjectNode json = mapper.createObjectNode();
json.put("failure", true);
json.put("msg", "No path met");
mapper.writeTree(generator, json);
generator.flush();
return;
}
String itemGetName = item.getName();
{
int lastSlash = itemGetName.lastIndexOf('\\');
if(lastSlash>=0){
itemGetName = itemGetName.substring(lastSlash+1);
}
}
java.io.File realFile = new java.io.File(realPath, itemGetName);
if(realFile.exists()){
//throw new RuntimeException("file " + realFile.getAbsolutePath() + " exists");
JsonGenerator generator = mapper.getJsonFactory().createJsonGenerator(resp.getOutputStream(), JsonEncoding.UTF8);
ObjectNode json = mapper.createObjectNode();
json.put("failure", true);
json.put("msg", "file " + realFile.getAbsolutePath() + " exists");
mapper.writeTree(generator, json);
generator.flush();
return;
}
FileOutputStream fos = new FileOutputStream(realFile);
Util.inputToOutWithIndex(
req.getSession().getServletContext().getInitParameter("solrUrl"),
stream,
fos,
midPath + itemGetName,
item.getContentType());
//BufferedInputStream bis = new BufferedInputStream(stream);
//BufferedOutputStream bos = new BufferedOutputStream(fos);
//int byt;
//while((byt = bis.read()) != -1){
// bos.write(byt);
//}
//bos.close();
//bis.close();
stream.close();
fos.close();
File file = new File();
file.setPath(midPath + itemGetName);
file.setFileName(itemGetName);
file.setMimeType(item.getContentType());
entityManager.persist(file);
//entityManager.flush();
files.add(file);
}
}
//Files ret = new Files(files, (long)files.size());
ArrayList<Author> a2 = new ArrayList(authors.size());
for(Author a: authors){
a2.add(entityManager.find(Author.class, a.getId()));
}
ArrayList<Word> w2 = new ArrayList(authors.size());
for(Word a: words){
Word w = entityManager.find(Word.class, a.getWord());
if(w==null){
//w = a;
w = entityManager.merge(a);
}
w2.add(w);
}
//ArrayList<File> dirs = new ArrayList(directories.size());
Query q = entityManager.createQuery(
"SELECT f FROM File f WHERE f.path = :path");
for(String a: directories){
q.setParameter("path", a);
File f;
List<File>fs = q.getResultList();
if(!fs.isEmpty()){
f = fs.get(0);
}else{
f = new File();
f.setPath(a);
f.setFileName("");
f.setMimeType("directory");
}
files.add(f);
}
ArrayList<GeoObject> go2 = new ArrayList(geoObjects.size());
q = entityManager.createQuery(
"SELECT object(o) "
+ "FROM GeoObject AS o "
+ "WHERE o.idInTable = :idInTable "
+ "AND o.tableName = :tableName");
for(GeoObject a: geoObjects){
q.setParameter("idInTable", a.getIdInTable());
q.setParameter("tableName", a.getTableName());
List<GeoObject> goes = q.getResultList();
if(!goes.isEmpty()){
a = goes.get(0);
}else{
a = entityManager.merge(a);
}
go2.add(a);
}
entityManager.flush();
doc.setAuthors(a2);
doc.setGeoObjects(go2);
doc.setFiles(files);
doc.setPlacementDate(new Date());
doc.setWords(w2);
Author placer = (Author) entityManager.
createNamedQuery("Author.findByLogin").
setParameter("login", req.getUserPrincipal().getName()).
getResultList().get(0);
doc.setPlacer(placer);
entityManager.persist(doc);
entityManager.flush();
for(File f: files){
f.setDocument(doc);
}
entityManager.flush();
Documents ret = new Documents(Arrays.asList(new Document[]{doc}), 1l);
/*ModelMap map = new ModelMap(ret);
map.addAttribute("success", true);
//View view = new JsonView();
ModelAndView mv = new ModelAndView(view, map);
return mv;*/
AnnotationIntrospector introspector = new JaxbAnnotationIntrospector();
mapper.getDeserializationConfig().setAnnotationIntrospector(introspector);
mapper.getSerializationConfig().setAnnotationIntrospector(introspector);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Util.DoubleOutput udo = new Util.DoubleOutput(baos, resp.getOutputStream());
JsonGenerator generator = mapper.getJsonFactory().createJsonGenerator(udo, JsonEncoding.UTF8);
ObjectNode json = mapper.valueToTree(ret);
json.put("success", true);
mapper.writeTree(generator, json);
generator.flush();
Util.inputToOutWithIndex(
req.getSession().getServletContext().getInitParameter("solrUrl"),
new ByteArrayInputStream(baos.toByteArray()),
new NullOutputStream(),
"solr" + doc.getFiles().iterator().next().getPath(),
"application/json");
doc.setCondensed(baos.toString("UTF-8"));
entityManager.flush();
}/*else{
JsonGenerator generator = mapper.getJsonFactory().createJsonGenerator(resp.getOutputStream(), JsonEncoding.UTF8);
ObjectNode json = mapper.createObjectNode();
json.put("failure", true);
json.put("msg", "No file");
mapper.writeTree(generator, json);
generator.flush();
}*/
}catch(Exception e){
JsonGenerator generator = mapper.getJsonFactory().createJsonGenerator(resp.getOutputStream(), JsonEncoding.UTF8);
ObjectNode json = mapper.createObjectNode();
json.put("failure", true);
json.put("msg", e.toString());
mapper.writeTree(generator, json);
generator.flush();
+ e.printStackTrace();
}
}
private String getMidPath(String midPath){
midPath = midPath.trim();
if(midPath.length()>0){
if(midPath.startsWith(java.io.File.separator))
midPath = midPath.substring(1);
if(!midPath.endsWith(java.io.File.separator))
midPath = midPath + java.io.File.separator;
}
//path = getRootPath(req) + path;
return midPath;
}
private String getRootPath(HttpServletRequest req){
if(rootPath==null){
rootPath = req.getSession().getServletContext().getInitParameter("documentsPath");
if(rootPath==null)
rootPath = java.io.File.separator;
else if(!rootPath.endsWith(java.io.File.separator))
rootPath = rootPath + java.io.File.separator;
}
return rootPath;
}
/*@ExceptionHandler(Exception.class)
//@Produces({"application/json"})
public @ResponseBody ModelMap handleException(Exception e, HttpServletResponse resp){
ModelMap map = new ModelMap();
map.addAttribute("success", false);
map.addAttribute("msg", e.toString());
return map;
}*/
}
| true | true | public void create(HttpServletRequest req, HttpServletResponse resp) throws Exception {
ObjectMapper mapper = new ObjectMapper();
resp.setHeader("Content-Type", "text/html; charset=UTF-8"); // "application/json");
try{
if(!ServletFileUpload.isMultipartContent(req)){
Document doc = new Document();
ArrayList<Author>authors = new ArrayList<Author>(3);
ArrayList<String>directories = new ArrayList<String>(3);
ArrayList<GeoObject>geoObjects = new ArrayList<GeoObject>(3);
ArrayList<Word>words = new ArrayList<Word>(3);
// Parse the request
Map<String, String[]> params = req.getParameterMap();
Iterator<Map.Entry<String, String[]>>iter = params.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry<String, String[]> item = iter.next();
String name = item.getKey();
String[]value = item.getValue();
{
if("domain".equals(name)){
//Long id = Long.parseLong(Streams.asString(stream, "UTF-8"));
//Domain domain = entityManager.find(Domain.class, id);
Domain domain = mapper.readValue(value[0], Domain.class);
//Domain domain = entityManager.find(Domain.class, mapper.readValue(stream, Domain.class).getId());
doc.setDomain(domain);
/*midPath = domain.getPathPart();
while(domain.getParent()!=null && domain.getParent().getId()!=domain.getId()){
domain = domain.getParent();
midPath = domain.getPathPart() + java.io.File.separator + midPath;
}
midPath = getMidPath(midPath);
realPath = new java.io.File(getRootPath(req) + midPath);
realPath.mkdirs();*/
}else{
if("year".equals(name)){
String s = value[0].trim();
if(s.length()!=0)
doc.setYear(Integer.parseInt(s));
}else if("id".equals(name)){
String s = value[0].trim();
if(s.length()!=0)
doc.setId(Long.parseLong(s));
}else if("number".equals(name)){
String s = value[0].trim();
if(s.length()!=0)
doc.setNumber(s);
}else if("archiveNumber".equals(name)){
String s = value[0].trim();
if(s.length()!=0)
doc.setArchiveNumber(s);
}else if("title".equals(name)){
String s = value[0].trim();
if(s.length()!=0)
doc.setTitle(s);
}else if("fullTitle".equals(name)){
String s = value[0].trim();
if(s.length()!=0)
doc.setFullTitle(s);
}else if("comment".equals(name)){
String s = value[0].trim();
if(s.length()!=0)
doc.setComment(s);
}else if("originationDetails".equals(name)){
String s = value[0].trim();
if(s.length()!=0)
doc.setOriginationDetails(s);
}else if("limitationDetails".equals(name)){
String s = value[0].trim();
if(s.length()!=0)
doc.setLimitationDetails(s);
}else if("originationDate".equals(name)){
String s = value[0].trim();
if(s.length()!=0)
doc.setOriginationDate(df.parse(s));
}else if("approvalDate".equals(name)){
String s = value[0].trim();
if(s.length()!=0)
doc.setApprovalDate(df.parse(s));
}else if("registrationDate".equals(name)){
String s = value[0].trim();
if(s.length()!=0)
doc.setRegistrationDate(df.parse(s));
}else if("placementDate".equals(name)){
String s = value[0].trim();
if(s.length()!=0)
doc.setPlacementDate(df.parse(s));
}else if("type".equals(name)){
doc.setType(mapper.readValue(value[0], Type.class));
}else if("stage".equals(name)){
doc.setStage(mapper.readValue(value[0], Stage.class));
}else if("site".equals(name)){
doc.setSite(mapper.readValue(value[0], Site.class));
}else if("author".equals(name)){
for(String val: value){
authors.add(mapper.readValue(val, Author.class));
}
}else if("directory".equals(name)){
for(String val: value){
directories.add(val);
}
}else if("geoObjects".equals(name)){
if(!value[0].equals("\"\"")){
GeoObject[] gos = mapper.readValue(value[0], GeoObject[].class);
geoObjects.addAll(Arrays.asList(gos));
}
}else if("words".equals(name)){
if(!value[0].equals("\"\"")){
Word[] gos = mapper.readValue(value[0], Word[].class);
words.addAll(Arrays.asList(gos));
}
}else if("geometryType".equals(name)){
if(!value[0].equals("\"\""))
doc.setGeometryType(mapper.readValue(value[0], GeoType.class));
}else if("periodicity".equals(name)){
if(!value[0].equals("\"\""))
doc.setPeriodicity(mapper.readValue(value[0], Periodicity.class));
}else if("classification".equals(name)){
if(!value[0].equals("\"\""))
doc.setClassification(mapper.readValue(value[0], Classification.class));
}else if("typeOfWork".equals(name)){
if(!value[0].equals("\"\""))
doc.setTypeOfWork(mapper.readValue(value[0], TypeOfWork.class));
}else if("workProcess".equals(name)){
if(!value[0].equals("\"\""))
doc.setWorkProcess(mapper.readValue(value[0], WorkProcess.class));
}else if("scale".equals(name)){
String s = value[0].trim();
if(s.length()!=0)
doc.setScale(Integer.parseInt(s));
}else if("resolution".equals(name)){
String s = value[0].trim();
if(s.length()!=0)
doc.setResolution(Integer.parseInt(s));
}else if("projection".equals(name)){
if(!value[0].equals("\"\""))
doc.setProjection(mapper.readValue(value[0], Projection.class));
//String s = value[0].trim();
//if(s.length()!=0)
// doc.setProjectionCode(s);
}else{
// throw away yet
//Streams.asString(stream);
}
}
}
}
//Files ret = new Files(files, (long)files.size());
ArrayList<Author> a2 = new ArrayList(authors.size());
for(Author a: authors){
a2.add(entityManager.find(Author.class, a.getId()));
}
ArrayList<Word> w2 = new ArrayList(authors.size());
for(Word a: words){
Word w = entityManager.find(Word.class, a.getWord());
if(w==null){
//w = a;
w = entityManager.merge(a);
}
w2.add(w);
}
Query q = entityManager.createQuery(
"SELECT f FROM File f WHERE f.path = :path");
ArrayList<File>files = new ArrayList<File>(directories.size());
for(String a: directories){
q.setParameter("path", a);
File f;
List<File>fs = q.getResultList();
if(!fs.isEmpty()){
f = fs.get(0);
}else{
f = new File();
f.setPath(a);
f.setDocument(doc);
f.setFileName("");
f.setMimeType("directory");
}
files.add(f);
}
ArrayList<GeoObject> go2 = new ArrayList(geoObjects.size());
q = entityManager.createQuery(
"SELECT object(o) "
+ "FROM GeoObject AS o "
+ "WHERE o.idInTable = :idInTable "
+ "AND o.tableName = :tableName");
for(GeoObject a: geoObjects){
q.setParameter("idInTable", a.getIdInTable());
q.setParameter("tableName", a.getTableName());
List<GeoObject> goes = q.getResultList();
if(!goes.isEmpty()){
a = goes.get(0);
}else{
a = entityManager.merge(a);
}
go2.add(a);
}
entityManager.flush();
doc.setAuthors(a2);
doc.setGeoObjects(go2);
doc.setFiles(files);
doc.setPlacementDate(new Date());
doc.setWords(w2);
Author placer = (Author) entityManager.
createNamedQuery("Author.findByLogin").
setParameter("login", req.getUserPrincipal().getName()).
getResultList().get(0);
doc.setPlacer(placer);
entityManager.merge(doc);
entityManager.flush();
//for(File f: files){
// f.setDocument(doc);
//}
//entityManager.flush();
Documents ret = new Documents(Arrays.asList(new Document[]{doc}), 1l);
/*ModelMap map = new ModelMap(ret);
map.addAttribute("success", true);
//View view = new JsonView();
ModelAndView mv = new ModelAndView(view, map);
return mv;*/
AnnotationIntrospector introspector = new JaxbAnnotationIntrospector();
mapper.getDeserializationConfig().setAnnotationIntrospector(introspector);
mapper.getSerializationConfig().setAnnotationIntrospector(introspector);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Util.DoubleOutput udo = new Util.DoubleOutput(baos, resp.getOutputStream());
JsonGenerator generator = mapper.getJsonFactory().createJsonGenerator(udo, JsonEncoding.UTF8);
ObjectNode json = mapper.valueToTree(ret);
json.put("success", true);
mapper.writeTree(generator, json);
generator.flush();
doc.setCondensed(baos.toString("UTF-8"));
entityManager.flush();
}else{
Document doc = new Document();
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload();
upload.setHeaderEncoding("UTF-8");
//String path = null;
java.io.File realPath = null;
String midPath = null;
ArrayList<File> files = new ArrayList<File>(3);
ArrayList<Author>authors = new ArrayList<Author>(3);
ArrayList<String>directories = new ArrayList<String>(3);
ArrayList<GeoObject>geoObjects = new ArrayList<GeoObject>(3);
ArrayList<Word>words = new ArrayList<Word>(3);
// Parse the request
FileItemIterator iter = upload.getItemIterator(req);
while (iter.hasNext()) {
FileItemStream item = iter.next();
String name = item.getFieldName();
InputStream stream = item.openStream();
if (item.isFormField()) {
if("domain".equals(name)){
//Long id = Long.parseLong(Streams.asString(stream, "UTF-8"));
//Domain domain = entityManager.find(Domain.class, id);
Domain domain = mapper.readValue(stream, Domain.class);
//Domain domain = entityManager.find(Domain.class, mapper.readValue(stream, Domain.class).getId());
doc.setDomain(domain);
midPath = domain.getPathPart();
while(domain.getParent()!=null && domain.getParent().getId()!=domain.getId()){
domain = domain.getParent();
midPath = domain.getPathPart() + java.io.File.separator + midPath;
}
midPath = getMidPath(midPath);
realPath = new java.io.File(getRootPath(req) + midPath);
realPath.mkdirs();
}else{
if("year".equals(name)){
String s = Streams.asString(stream).trim();
if(s.length()!=0)
doc.setYear(Integer.parseInt(s));
}else if("number".equals(name)){
String s = Streams.asString(stream, "UTF-8").trim();
if(s.length()!=0)
doc.setNumber(s);
}else if("archiveNumber".equals(name)){
String s = Streams.asString(stream, "UTF-8").trim();
if(s.length()!=0)
doc.setArchiveNumber(s);
}else if("title".equals(name)){
String s = Streams.asString(stream, "UTF-8").trim();
if(s.length()!=0)
doc.setTitle(s);
}else if("fullTitle".equals(name)){
String s = Streams.asString(stream, "UTF-8").trim();
if(s.length()!=0)
doc.setFullTitle(s);
}else if("comment".equals(name)){
String s = Streams.asString(stream, "UTF-8").trim();
if(s.length()!=0)
doc.setComment(s);
}else if("originationDetails".equals(name)){
String s = Streams.asString(stream, "UTF-8").trim();
if(s.length()!=0)
doc.setOriginationDetails(s);
}else if("limitationDetails".equals(name)){
String s = Streams.asString(stream, "UTF-8").trim();
if(s.length()!=0)
doc.setLimitationDetails(s);
}else if("originationDate".equals(name)){
String s = Streams.asString(stream, "UTF-8").trim();
if(s.length()!=0)
doc.setOriginationDate(df.parse(s));
}else if("approvalDate".equals(name)){
String s = Streams.asString(stream, "UTF-8").trim();
if(s.length()!=0)
doc.setApprovalDate(df.parse(s));
}else if("registrationDate".equals(name)){
String s = Streams.asString(stream, "UTF-8").trim();
if(s.length()!=0)
doc.setRegistrationDate(df.parse(s));
}else if("placementDate".equals(name)){
String s = Streams.asString(stream, "UTF-8").trim();
if(s.length()!=0)
doc.setPlacementDate(df.parse(s));
}else if("type".equals(name)){
doc.setType(mapper.readValue(stream, Type.class));
}else if("stage".equals(name)){
doc.setStage(mapper.readValue(stream, Stage.class));
}else if("site".equals(name)){
doc.setSite(mapper.readValue(stream, Site.class));
}else if("author".equals(name)){
authors.add(mapper.readValue(stream, Author.class));
}else if("directory".equals(name)){
directories.add(Streams.asString(stream, "UTF-8"));
}else if("geoObjects".equals(name)){
GeoObject[] gos = mapper.readValue(stream, GeoObject[].class);
geoObjects.addAll(Arrays.asList(gos));
//doc.setSite(mapper.readValue(stream, Site.class));
}else if("words".equals(name)){
Word[] gos = mapper.readValue(stream, Word[].class);
words.addAll(Arrays.asList(gos));
}else if("geometryType".equals(name)){
doc.setGeometryType(mapper.readValue(stream, GeoType.class));
}else if("periodicity".equals(name)){
doc.setPeriodicity(mapper.readValue(stream, Periodicity.class));
}else if("typeOfWork".equals(name)){
doc.setTypeOfWork(mapper.readValue(stream, TypeOfWork.class));
}else if("workProcess".equals(name)){
doc.setWorkProcess(mapper.readValue(stream, WorkProcess.class));
}else if("classification".equals(name)){
doc.setClassification(mapper.readValue(stream, Classification.class));
}else if("scale".equals(name)){
String s = Streams.asString(stream, "UTF-8").trim();
if(s.length()!=0)
doc.setScale(Integer.parseInt(s));
}else if("resolution".equals(name)){
String s = Streams.asString(stream, "UTF-8").trim();
if(s.length()!=0)
doc.setResolution(Integer.parseInt(s));
}else if("projection".equals(name)){
doc.setProjection(mapper.readValue(stream, Projection.class));
//String s = Streams.asString(stream, "UTF-8").trim();
//if(s.length()!=0)
// doc.setProjectionCode(s);
}else{
// throw away yet
Streams.asString(stream);
}
}
} else {
if(midPath==null){
//throw new RuntimeException("No path met");
JsonGenerator generator = mapper.getJsonFactory().createJsonGenerator(resp.getOutputStream(), JsonEncoding.UTF8);
ObjectNode json = mapper.createObjectNode();
json.put("failure", true);
json.put("msg", "No path met");
mapper.writeTree(generator, json);
generator.flush();
return;
}
String itemGetName = item.getName();
{
int lastSlash = itemGetName.lastIndexOf('\\');
if(lastSlash>=0){
itemGetName = itemGetName.substring(lastSlash+1);
}
}
java.io.File realFile = new java.io.File(realPath, itemGetName);
if(realFile.exists()){
//throw new RuntimeException("file " + realFile.getAbsolutePath() + " exists");
JsonGenerator generator = mapper.getJsonFactory().createJsonGenerator(resp.getOutputStream(), JsonEncoding.UTF8);
ObjectNode json = mapper.createObjectNode();
json.put("failure", true);
json.put("msg", "file " + realFile.getAbsolutePath() + " exists");
mapper.writeTree(generator, json);
generator.flush();
return;
}
FileOutputStream fos = new FileOutputStream(realFile);
Util.inputToOutWithIndex(
req.getSession().getServletContext().getInitParameter("solrUrl"),
stream,
fos,
midPath + itemGetName,
item.getContentType());
//BufferedInputStream bis = new BufferedInputStream(stream);
//BufferedOutputStream bos = new BufferedOutputStream(fos);
//int byt;
//while((byt = bis.read()) != -1){
// bos.write(byt);
//}
//bos.close();
//bis.close();
stream.close();
fos.close();
File file = new File();
file.setPath(midPath + itemGetName);
file.setFileName(itemGetName);
file.setMimeType(item.getContentType());
entityManager.persist(file);
//entityManager.flush();
files.add(file);
}
}
//Files ret = new Files(files, (long)files.size());
ArrayList<Author> a2 = new ArrayList(authors.size());
for(Author a: authors){
a2.add(entityManager.find(Author.class, a.getId()));
}
ArrayList<Word> w2 = new ArrayList(authors.size());
for(Word a: words){
Word w = entityManager.find(Word.class, a.getWord());
if(w==null){
//w = a;
w = entityManager.merge(a);
}
w2.add(w);
}
//ArrayList<File> dirs = new ArrayList(directories.size());
Query q = entityManager.createQuery(
"SELECT f FROM File f WHERE f.path = :path");
for(String a: directories){
q.setParameter("path", a);
File f;
List<File>fs = q.getResultList();
if(!fs.isEmpty()){
f = fs.get(0);
}else{
f = new File();
f.setPath(a);
f.setFileName("");
f.setMimeType("directory");
}
files.add(f);
}
ArrayList<GeoObject> go2 = new ArrayList(geoObjects.size());
q = entityManager.createQuery(
"SELECT object(o) "
+ "FROM GeoObject AS o "
+ "WHERE o.idInTable = :idInTable "
+ "AND o.tableName = :tableName");
for(GeoObject a: geoObjects){
q.setParameter("idInTable", a.getIdInTable());
q.setParameter("tableName", a.getTableName());
List<GeoObject> goes = q.getResultList();
if(!goes.isEmpty()){
a = goes.get(0);
}else{
a = entityManager.merge(a);
}
go2.add(a);
}
entityManager.flush();
doc.setAuthors(a2);
doc.setGeoObjects(go2);
doc.setFiles(files);
doc.setPlacementDate(new Date());
doc.setWords(w2);
Author placer = (Author) entityManager.
createNamedQuery("Author.findByLogin").
setParameter("login", req.getUserPrincipal().getName()).
getResultList().get(0);
doc.setPlacer(placer);
entityManager.persist(doc);
entityManager.flush();
for(File f: files){
f.setDocument(doc);
}
entityManager.flush();
Documents ret = new Documents(Arrays.asList(new Document[]{doc}), 1l);
/*ModelMap map = new ModelMap(ret);
map.addAttribute("success", true);
//View view = new JsonView();
ModelAndView mv = new ModelAndView(view, map);
return mv;*/
AnnotationIntrospector introspector = new JaxbAnnotationIntrospector();
mapper.getDeserializationConfig().setAnnotationIntrospector(introspector);
mapper.getSerializationConfig().setAnnotationIntrospector(introspector);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Util.DoubleOutput udo = new Util.DoubleOutput(baos, resp.getOutputStream());
JsonGenerator generator = mapper.getJsonFactory().createJsonGenerator(udo, JsonEncoding.UTF8);
ObjectNode json = mapper.valueToTree(ret);
json.put("success", true);
mapper.writeTree(generator, json);
generator.flush();
Util.inputToOutWithIndex(
req.getSession().getServletContext().getInitParameter("solrUrl"),
new ByteArrayInputStream(baos.toByteArray()),
new NullOutputStream(),
"solr" + doc.getFiles().iterator().next().getPath(),
"application/json");
doc.setCondensed(baos.toString("UTF-8"));
entityManager.flush();
}/*else{
JsonGenerator generator = mapper.getJsonFactory().createJsonGenerator(resp.getOutputStream(), JsonEncoding.UTF8);
ObjectNode json = mapper.createObjectNode();
json.put("failure", true);
json.put("msg", "No file");
mapper.writeTree(generator, json);
generator.flush();
}*/
}catch(Exception e){
JsonGenerator generator = mapper.getJsonFactory().createJsonGenerator(resp.getOutputStream(), JsonEncoding.UTF8);
ObjectNode json = mapper.createObjectNode();
json.put("failure", true);
json.put("msg", e.toString());
mapper.writeTree(generator, json);
generator.flush();
}
}
| public void create(HttpServletRequest req, HttpServletResponse resp) throws Exception {
ObjectMapper mapper = new ObjectMapper();
resp.setHeader("Content-Type", "text/html; charset=UTF-8"); // "application/json");
try{
if(!ServletFileUpload.isMultipartContent(req)){
Document doc = new Document();
ArrayList<Author>authors = new ArrayList<Author>(3);
ArrayList<String>directories = new ArrayList<String>(3);
ArrayList<GeoObject>geoObjects = new ArrayList<GeoObject>(3);
ArrayList<Word>words = new ArrayList<Word>(3);
// Parse the request
Map<String, String[]> params = req.getParameterMap();
Iterator<Map.Entry<String, String[]>>iter = params.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry<String, String[]> item = iter.next();
String name = item.getKey();
String[]value = item.getValue();
{
if("domain".equals(name)){
//Long id = Long.parseLong(Streams.asString(stream, "UTF-8"));
//Domain domain = entityManager.find(Domain.class, id);
Domain domain = mapper.readValue(value[0], Domain.class);
//Domain domain = entityManager.find(Domain.class, mapper.readValue(stream, Domain.class).getId());
doc.setDomain(domain);
/*midPath = domain.getPathPart();
while(domain.getParent()!=null && domain.getParent().getId()!=domain.getId()){
domain = domain.getParent();
midPath = domain.getPathPart() + java.io.File.separator + midPath;
}
midPath = getMidPath(midPath);
realPath = new java.io.File(getRootPath(req) + midPath);
realPath.mkdirs();*/
}else{
if("year".equals(name)){
String s = value[0].trim();
if(s.length()!=0)
doc.setYear(Integer.parseInt(s));
}else if("id".equals(name)){
String s = value[0].trim();
if(s.length()!=0)
doc.setId(Long.parseLong(s));
}else if("number".equals(name)){
String s = value[0].trim();
if(s.length()!=0)
doc.setNumber(s);
}else if("archiveNumber".equals(name)){
String s = value[0].trim();
if(s.length()!=0)
doc.setArchiveNumber(s);
}else if("title".equals(name)){
String s = value[0].trim();
if(s.length()!=0)
doc.setTitle(s);
}else if("fullTitle".equals(name)){
String s = value[0].trim();
if(s.length()!=0)
doc.setFullTitle(s);
}else if("comment".equals(name)){
String s = value[0].trim();
if(s.length()!=0)
doc.setComment(s);
}else if("originationDetails".equals(name)){
String s = value[0].trim();
if(s.length()!=0)
doc.setOriginationDetails(s);
}else if("limitationDetails".equals(name)){
String s = value[0].trim();
if(s.length()!=0)
doc.setLimitationDetails(s);
}else if("originationDate".equals(name)){
String s = value[0].trim();
if(s.length()!=0)
doc.setOriginationDate(df.parse(s));
}else if("approvalDate".equals(name)){
String s = value[0].trim();
if(s.length()!=0)
doc.setApprovalDate(df.parse(s));
}else if("registrationDate".equals(name)){
String s = value[0].trim();
if(s.length()!=0)
doc.setRegistrationDate(df.parse(s));
}else if("placementDate".equals(name)){
String s = value[0].trim();
if(s.length()!=0)
doc.setPlacementDate(df.parse(s));
}else if("type".equals(name)){
doc.setType(mapper.readValue(value[0], Type.class));
}else if("stage".equals(name)){
doc.setStage(mapper.readValue(value[0], Stage.class));
}else if("site".equals(name)){
doc.setSite(mapper.readValue(value[0], Site.class));
}else if("author".equals(name)){
for(String val: value){
authors.add(mapper.readValue(val, Author.class));
}
}else if("directory".equals(name)){
for(String val: value){
directories.add(val);
}
}else if("geoObjects".equals(name)){
if(!value[0].equals("\"\"")){
GeoObject[] gos = mapper.readValue(value[0], GeoObject[].class);
geoObjects.addAll(Arrays.asList(gos));
}
}else if("words".equals(name)){
if(!value[0].equals("\"\"")){
Word[] gos = mapper.readValue(value[0], Word[].class);
words.addAll(Arrays.asList(gos));
}
}else if("geometryType".equals(name)){
if(!value[0].equals("\"\""))
doc.setGeometryType(mapper.readValue(value[0], GeoType.class));
}else if("periodicity".equals(name)){
if(!value[0].equals("\"\""))
doc.setPeriodicity(mapper.readValue(value[0], Periodicity.class));
}else if("classification".equals(name)){
if(!value[0].equals("\"\""))
doc.setClassification(mapper.readValue(value[0], Classification.class));
}else if("typeOfWork".equals(name)){
if(!value[0].equals("\"\""))
doc.setTypeOfWork(mapper.readValue(value[0], TypeOfWork.class));
}else if("workProcess".equals(name)){
if(!value[0].equals("\"\""))
doc.setWorkProcess(mapper.readValue(value[0], WorkProcess.class));
}else if("scale".equals(name)){
String s = value[0].trim();
if(s.length()!=0)
doc.setScale(Integer.parseInt(s));
}else if("resolution".equals(name)){
String s = value[0].trim();
if(s.length()!=0)
doc.setResolution(Integer.parseInt(s));
}else if("projection".equals(name)){
if(!value[0].equals("\"\""))
doc.setProjection(mapper.readValue(value[0], Projection.class));
//String s = value[0].trim();
//if(s.length()!=0)
// doc.setProjectionCode(s);
}else{
// throw away yet
//Streams.asString(stream);
}
}
}
}
//Files ret = new Files(files, (long)files.size());
ArrayList<Author> a2 = new ArrayList(authors.size());
for(Author a: authors){
a2.add(entityManager.find(Author.class, a.getId()));
}
ArrayList<Word> w2 = new ArrayList(authors.size());
for(Word a: words){
Word w = entityManager.find(Word.class, a.getWord());
if(w==null){
//w = a;
w = entityManager.merge(a);
}
w2.add(w);
}
Query q = entityManager.createQuery(
"SELECT f FROM File f WHERE f.path = :path");
ArrayList<File>files = new ArrayList<File>(directories.size());
for(String a: directories){
q.setParameter("path", a);
File f;
List<File>fs = q.getResultList();
if(!fs.isEmpty()){
f = fs.get(0);
}else{
f = new File();
f.setPath(a);
f.setDocument(doc);
f.setFileName("");
f.setMimeType("directory");
}
files.add(f);
}
ArrayList<GeoObject> go2 = new ArrayList(geoObjects.size());
q = entityManager.createQuery(
"SELECT object(o) "
+ "FROM GeoObject AS o "
+ "WHERE o.idInTable = :idInTable "
+ "AND o.tableName = :tableName");
for(GeoObject a: geoObjects){
q.setParameter("idInTable", a.getIdInTable());
q.setParameter("tableName", a.getTableName());
List<GeoObject> goes = q.getResultList();
if(!goes.isEmpty()){
a = goes.get(0);
}else{
a = entityManager.merge(a);
}
go2.add(a);
}
entityManager.flush();
doc.setAuthors(a2);
doc.setGeoObjects(go2);
doc.setFiles(files);
doc.setPlacementDate(new Date());
doc.setWords(w2);
Author placer = (Author) entityManager.
createNamedQuery("Author.findByLogin").
setParameter("login", req.getUserPrincipal().getName()).
getResultList().get(0);
doc.setPlacer(placer);
entityManager.merge(doc);
entityManager.flush();
//for(File f: files){
// f.setDocument(doc);
//}
//entityManager.flush();
Documents ret = new Documents(Arrays.asList(new Document[]{doc}), 1l);
/*ModelMap map = new ModelMap(ret);
map.addAttribute("success", true);
//View view = new JsonView();
ModelAndView mv = new ModelAndView(view, map);
return mv;*/
AnnotationIntrospector introspector = new JaxbAnnotationIntrospector();
mapper.getDeserializationConfig().setAnnotationIntrospector(introspector);
mapper.getSerializationConfig().setAnnotationIntrospector(introspector);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Util.DoubleOutput udo = new Util.DoubleOutput(baos, resp.getOutputStream());
JsonGenerator generator = mapper.getJsonFactory().createJsonGenerator(udo, JsonEncoding.UTF8);
ObjectNode json = mapper.valueToTree(ret);
json.put("success", true);
mapper.writeTree(generator, json);
generator.flush();
doc.setCondensed(baos.toString("UTF-8"));
entityManager.flush();
}else{
Document doc = new Document();
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload();
upload.setHeaderEncoding("UTF-8");
//String path = null;
java.io.File realPath = null;
String midPath = null;
ArrayList<File> files = new ArrayList<File>(3);
ArrayList<Author>authors = new ArrayList<Author>(3);
ArrayList<String>directories = new ArrayList<String>(3);
ArrayList<GeoObject>geoObjects = new ArrayList<GeoObject>(3);
ArrayList<Word>words = new ArrayList<Word>(3);
// Parse the request
FileItemIterator iter = upload.getItemIterator(req);
while (iter.hasNext()) {
FileItemStream item = iter.next();
String name = item.getFieldName();
InputStream stream = item.openStream();
if (item.isFormField()) {
if("domain".equals(name)){
//Long id = Long.parseLong(Streams.asString(stream, "UTF-8"));
//Domain domain = entityManager.find(Domain.class, id);
Domain domain = mapper.readValue(stream, Domain.class);
//Domain domain = entityManager.find(Domain.class, mapper.readValue(stream, Domain.class).getId());
doc.setDomain(domain);
midPath = domain.getPathPart();
while(domain.getParent()!=null && domain.getParent().getId()!=domain.getId()){
domain = domain.getParent();
midPath = domain.getPathPart() + java.io.File.separator + midPath;
}
midPath = getMidPath(midPath);
realPath = new java.io.File(getRootPath(req) + midPath);
realPath.mkdirs();
}else{
if("year".equals(name)){
String s = Streams.asString(stream).trim();
if(s.length()!=0)
doc.setYear(Integer.parseInt(s));
}else if("number".equals(name)){
String s = Streams.asString(stream, "UTF-8").trim();
if(s.length()!=0)
doc.setNumber(s);
}else if("archiveNumber".equals(name)){
String s = Streams.asString(stream, "UTF-8").trim();
if(s.length()!=0)
doc.setArchiveNumber(s);
}else if("title".equals(name)){
String s = Streams.asString(stream, "UTF-8").trim();
if(s.length()!=0)
doc.setTitle(s);
}else if("fullTitle".equals(name)){
String s = Streams.asString(stream, "UTF-8").trim();
if(s.length()!=0)
doc.setFullTitle(s);
}else if("comment".equals(name)){
String s = Streams.asString(stream, "UTF-8").trim();
if(s.length()!=0)
doc.setComment(s);
}else if("originationDetails".equals(name)){
String s = Streams.asString(stream, "UTF-8").trim();
if(s.length()!=0)
doc.setOriginationDetails(s);
}else if("limitationDetails".equals(name)){
String s = Streams.asString(stream, "UTF-8").trim();
if(s.length()!=0)
doc.setLimitationDetails(s);
}else if("originationDate".equals(name)){
String s = Streams.asString(stream, "UTF-8").trim();
if(s.length()!=0)
doc.setOriginationDate(df.parse(s));
}else if("approvalDate".equals(name)){
String s = Streams.asString(stream, "UTF-8").trim();
if(s.length()!=0)
doc.setApprovalDate(df.parse(s));
}else if("registrationDate".equals(name)){
String s = Streams.asString(stream, "UTF-8").trim();
if(s.length()!=0)
doc.setRegistrationDate(df.parse(s));
}else if("placementDate".equals(name)){
String s = Streams.asString(stream, "UTF-8").trim();
if(s.length()!=0)
doc.setPlacementDate(df.parse(s));
}else if("type".equals(name)){
doc.setType(mapper.readValue(stream, Type.class));
}else if("stage".equals(name)){
doc.setStage(mapper.readValue(stream, Stage.class));
}else if("site".equals(name)){
doc.setSite(mapper.readValue(stream, Site.class));
}else if("author".equals(name)){
authors.add(mapper.readValue(stream, Author.class));
}else if("directory".equals(name)){
directories.add(Streams.asString(stream, "UTF-8"));
}else if("geoObjects".equals(name)){
GeoObject[] gos = mapper.readValue(stream, GeoObject[].class);
geoObjects.addAll(Arrays.asList(gos));
//doc.setSite(mapper.readValue(stream, Site.class));
}else if("words".equals(name)){
Word[] gos = mapper.readValue(stream, Word[].class);
words.addAll(Arrays.asList(gos));
}else if("geometryType".equals(name)){
doc.setGeometryType(mapper.readValue(stream, GeoType.class));
}else if("periodicity".equals(name)){
doc.setPeriodicity(mapper.readValue(stream, Periodicity.class));
}else if("typeOfWork".equals(name)){
doc.setTypeOfWork(mapper.readValue(stream, TypeOfWork.class));
}else if("workProcess".equals(name)){
doc.setWorkProcess(mapper.readValue(stream, WorkProcess.class));
}else if("classification".equals(name)){
doc.setClassification(mapper.readValue(stream, Classification.class));
}else if("scale".equals(name)){
String s = Streams.asString(stream, "UTF-8").trim();
if(s.length()!=0)
doc.setScale(Integer.parseInt(s));
}else if("resolution".equals(name)){
String s = Streams.asString(stream, "UTF-8").trim();
if(s.length()!=0)
doc.setResolution(Integer.parseInt(s));
}else if("projection".equals(name)){
doc.setProjection(mapper.readValue(stream, Projection.class));
//String s = Streams.asString(stream, "UTF-8").trim();
//if(s.length()!=0)
// doc.setProjectionCode(s);
}else{
// throw away yet
Streams.asString(stream);
}
}
} else {
if(midPath==null){
//throw new RuntimeException("No path met");
JsonGenerator generator = mapper.getJsonFactory().createJsonGenerator(resp.getOutputStream(), JsonEncoding.UTF8);
ObjectNode json = mapper.createObjectNode();
json.put("failure", true);
json.put("msg", "No path met");
mapper.writeTree(generator, json);
generator.flush();
return;
}
String itemGetName = item.getName();
{
int lastSlash = itemGetName.lastIndexOf('\\');
if(lastSlash>=0){
itemGetName = itemGetName.substring(lastSlash+1);
}
}
java.io.File realFile = new java.io.File(realPath, itemGetName);
if(realFile.exists()){
//throw new RuntimeException("file " + realFile.getAbsolutePath() + " exists");
JsonGenerator generator = mapper.getJsonFactory().createJsonGenerator(resp.getOutputStream(), JsonEncoding.UTF8);
ObjectNode json = mapper.createObjectNode();
json.put("failure", true);
json.put("msg", "file " + realFile.getAbsolutePath() + " exists");
mapper.writeTree(generator, json);
generator.flush();
return;
}
FileOutputStream fos = new FileOutputStream(realFile);
Util.inputToOutWithIndex(
req.getSession().getServletContext().getInitParameter("solrUrl"),
stream,
fos,
midPath + itemGetName,
item.getContentType());
//BufferedInputStream bis = new BufferedInputStream(stream);
//BufferedOutputStream bos = new BufferedOutputStream(fos);
//int byt;
//while((byt = bis.read()) != -1){
// bos.write(byt);
//}
//bos.close();
//bis.close();
stream.close();
fos.close();
File file = new File();
file.setPath(midPath + itemGetName);
file.setFileName(itemGetName);
file.setMimeType(item.getContentType());
entityManager.persist(file);
//entityManager.flush();
files.add(file);
}
}
//Files ret = new Files(files, (long)files.size());
ArrayList<Author> a2 = new ArrayList(authors.size());
for(Author a: authors){
a2.add(entityManager.find(Author.class, a.getId()));
}
ArrayList<Word> w2 = new ArrayList(authors.size());
for(Word a: words){
Word w = entityManager.find(Word.class, a.getWord());
if(w==null){
//w = a;
w = entityManager.merge(a);
}
w2.add(w);
}
//ArrayList<File> dirs = new ArrayList(directories.size());
Query q = entityManager.createQuery(
"SELECT f FROM File f WHERE f.path = :path");
for(String a: directories){
q.setParameter("path", a);
File f;
List<File>fs = q.getResultList();
if(!fs.isEmpty()){
f = fs.get(0);
}else{
f = new File();
f.setPath(a);
f.setFileName("");
f.setMimeType("directory");
}
files.add(f);
}
ArrayList<GeoObject> go2 = new ArrayList(geoObjects.size());
q = entityManager.createQuery(
"SELECT object(o) "
+ "FROM GeoObject AS o "
+ "WHERE o.idInTable = :idInTable "
+ "AND o.tableName = :tableName");
for(GeoObject a: geoObjects){
q.setParameter("idInTable", a.getIdInTable());
q.setParameter("tableName", a.getTableName());
List<GeoObject> goes = q.getResultList();
if(!goes.isEmpty()){
a = goes.get(0);
}else{
a = entityManager.merge(a);
}
go2.add(a);
}
entityManager.flush();
doc.setAuthors(a2);
doc.setGeoObjects(go2);
doc.setFiles(files);
doc.setPlacementDate(new Date());
doc.setWords(w2);
Author placer = (Author) entityManager.
createNamedQuery("Author.findByLogin").
setParameter("login", req.getUserPrincipal().getName()).
getResultList().get(0);
doc.setPlacer(placer);
entityManager.persist(doc);
entityManager.flush();
for(File f: files){
f.setDocument(doc);
}
entityManager.flush();
Documents ret = new Documents(Arrays.asList(new Document[]{doc}), 1l);
/*ModelMap map = new ModelMap(ret);
map.addAttribute("success", true);
//View view = new JsonView();
ModelAndView mv = new ModelAndView(view, map);
return mv;*/
AnnotationIntrospector introspector = new JaxbAnnotationIntrospector();
mapper.getDeserializationConfig().setAnnotationIntrospector(introspector);
mapper.getSerializationConfig().setAnnotationIntrospector(introspector);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Util.DoubleOutput udo = new Util.DoubleOutput(baos, resp.getOutputStream());
JsonGenerator generator = mapper.getJsonFactory().createJsonGenerator(udo, JsonEncoding.UTF8);
ObjectNode json = mapper.valueToTree(ret);
json.put("success", true);
mapper.writeTree(generator, json);
generator.flush();
Util.inputToOutWithIndex(
req.getSession().getServletContext().getInitParameter("solrUrl"),
new ByteArrayInputStream(baos.toByteArray()),
new NullOutputStream(),
"solr" + doc.getFiles().iterator().next().getPath(),
"application/json");
doc.setCondensed(baos.toString("UTF-8"));
entityManager.flush();
}/*else{
JsonGenerator generator = mapper.getJsonFactory().createJsonGenerator(resp.getOutputStream(), JsonEncoding.UTF8);
ObjectNode json = mapper.createObjectNode();
json.put("failure", true);
json.put("msg", "No file");
mapper.writeTree(generator, json);
generator.flush();
}*/
}catch(Exception e){
JsonGenerator generator = mapper.getJsonFactory().createJsonGenerator(resp.getOutputStream(), JsonEncoding.UTF8);
ObjectNode json = mapper.createObjectNode();
json.put("failure", true);
json.put("msg", e.toString());
mapper.writeTree(generator, json);
generator.flush();
e.printStackTrace();
}
}
|
diff --git a/org.eclipse.mylyn.reviews.r4e.ui/src/org/eclipse/mylyn/reviews/r4e/ui/internal/dialogs/CloneAnomalyInputDialog.java b/org.eclipse.mylyn.reviews.r4e.ui/src/org/eclipse/mylyn/reviews/r4e/ui/internal/dialogs/CloneAnomalyInputDialog.java
index 90fc6bda..d4b9be7f 100644
--- a/org.eclipse.mylyn.reviews.r4e.ui/src/org/eclipse/mylyn/reviews/r4e/ui/internal/dialogs/CloneAnomalyInputDialog.java
+++ b/org.eclipse.mylyn.reviews.r4e.ui/src/org/eclipse/mylyn/reviews/r4e/ui/internal/dialogs/CloneAnomalyInputDialog.java
@@ -1,729 +1,730 @@
/*******************************************************************************
* Copyright (c) 2012 Ericsson AB 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
*
* Description:
*
* This class implements the dialog used to clone Anomalies
* This is a modeless-like dialog
*
* Contributors:
* Sebastien Dubois - Created for Mylyn Review R4E project
*
******************************************************************************/
package org.eclipse.mylyn.reviews.r4e.ui.internal.dialogs;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.ColumnViewerToolTipSupport;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.ViewerCell;
import org.eclipse.jface.window.ToolTip;
import org.eclipse.jface.window.Window;
import org.eclipse.mylyn.reviews.r4e.core.model.R4EAnomaly;
import org.eclipse.mylyn.reviews.r4e.core.model.R4ECommentType;
import org.eclipse.mylyn.reviews.r4e.core.model.drules.R4EDesignRule;
import org.eclipse.mylyn.reviews.r4e.core.model.drules.R4EDesignRuleClass;
import org.eclipse.mylyn.reviews.r4e.core.model.drules.R4EDesignRuleRank;
import org.eclipse.mylyn.reviews.r4e.ui.internal.model.IR4EUIModelElement;
import org.eclipse.mylyn.reviews.r4e.ui.internal.model.R4EUIAnomalyBasic;
import org.eclipse.mylyn.reviews.r4e.ui.internal.model.R4EUIFileContext;
import org.eclipse.mylyn.reviews.r4e.ui.internal.model.R4EUIModelController;
import org.eclipse.mylyn.reviews.r4e.ui.internal.model.R4EUIReviewBasic;
import org.eclipse.mylyn.reviews.r4e.ui.internal.model.R4EUIReviewItem;
import org.eclipse.mylyn.reviews.r4e.ui.internal.navigator.ReviewNavigatorLabelProvider;
import org.eclipse.mylyn.reviews.r4e.ui.internal.utils.R4EUIConstants;
import org.eclipse.mylyn.reviews.r4e.ui.internal.utils.UIUtils;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CCombo;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.forms.FormDialog;
import org.eclipse.ui.forms.IManagedForm;
import org.eclipse.ui.forms.events.ExpansionAdapter;
import org.eclipse.ui.forms.events.ExpansionEvent;
import org.eclipse.ui.forms.widgets.ExpandableComposite;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.forms.widgets.ScrolledForm;
import org.eclipse.ui.forms.widgets.Section;
public class CloneAnomalyInputDialog extends FormDialog implements IAnomalyInputDialog {
// ------------------------------------------------------------------------
// Constants
// ------------------------------------------------------------------------
/**
* Field CLONE_ANOMALY_DIALOG_TITLE. (value is ""Select Anomaly to Clone"")
*/
private static final String CLONE_ANOMALY_DIALOG_TITLE = "Select Anomaly to Clone";
/**
* Field ANOMALY_LIST_HEADER_MSG. (value is ""Available Cloneable Anomalies"")
*/
private static final String ANOMALY_LIST_HEADER_MSG = "Available Cloneable Anomalies";
/**
* Field ANOMALY_DETAILS_HEADER_MSG. (value is ""Anomaly Details"")
*/
private static final String ANOMALY_DETAILS_HEADER_MSG = "Anomaly Details";
/**
* Field MAX_DISPLAYED_CLONEABLE_ANOMALIES. (value is "10")
*/
private static final int MAX_DISPLAYED_CLONEABLE_ANOMALIES = 10;
// ------------------------------------------------------------------------
// Member variables
// ------------------------------------------------------------------------
/**
* Field fCloneableAnomalyViewer.
*/
private TableViewer fCloneableAnomalyViewer = null;
/**
* Field fAnomalyClass.
*/
private R4EUIAnomalyBasic fClonedAnomaly = null;
/**
* Field fAnomalyTitleTextField.
*/
protected Text fAnomalyTitleTextField = null;
/**
* Field fAnomalyDescriptionTextField.
*/
protected Text fAnomalyDescriptionTextField;
/**
* Field fAnomalyClassTextField.
*/
protected Text fAnomalyClassTextField = null;
/**
* Field fAnomalyRankTextField.
*/
protected Text fAnomalyRankTextField = null;
/**
* Field fDateText.
*/
protected Text fDateText = null;
/**
* Field fAnomalyDueDateValue.
*/
private Date fAnomalyDueDateValue = null;
/**
* Field fRuleIdTextField.
*/
private Text fRuleIdTextField = null;
/**
* Field fAssignedToCombo.
*/
protected CCombo fAssignedToCombo = null;
/**
* Field fAssignedToParticipant.
*/
private String fAssignedToParticipant = null;
// ------------------------------------------------------------------------
// Constructors
// ------------------------------------------------------------------------
/**
* Constructor for R4EAnomalyInputDialog.
*
* @param aParentShell
* Shell
*/
public CloneAnomalyInputDialog(Shell aParentShell) {
super(aParentShell);
setBlockOnOpen(false);
}
// ------------------------------------------------------------------------
// Methods
// ------------------------------------------------------------------------
/**
* Method buttonPressed.
*
* @param buttonId
* int
* @see org.eclipse.jface.dialogs.Dialog#buttonPressed(int)
*/
@Override
protected void buttonPressed(int buttonId) {
if (buttonId == IDialogConstants.OK_ID) {
ISelection selection = fCloneableAnomalyViewer.getSelection();
if (selection instanceof IStructuredSelection) {
if (null != ((IStructuredSelection) selection).getFirstElement()) {
if (((IStructuredSelection) selection).getFirstElement() instanceof R4EUIAnomalyBasic) {
fClonedAnomaly = (R4EUIAnomalyBasic) ((IStructuredSelection) selection).getFirstElement();
fAssignedToParticipant = fAssignedToCombo.getText();
}
}
}
} else {
fClonedAnomaly = null;
fAnomalyDueDateValue = null;
fAssignedToParticipant = null;
}
R4EUIModelController.getNavigatorView().getTreeViewer().refresh();
super.buttonPressed(buttonId);
}
/**
* Method configureShell.
*
* @param shell
* Shell
* @see org.eclipse.jface.window.Window#configureShell(org.eclipse.swt.widgets.Shell)
*/
@Override
protected void configureShell(Shell shell) {
super.configureShell(shell);
shell.setText(CLONE_ANOMALY_DIALOG_TITLE);
shell.setMinimumSize(R4EUIConstants.DIALOG_DEFAULT_WIDTH, R4EUIConstants.DIALOG_DEFAULT_HEIGHT);
}
/**
* Configures the dialog form and creates form content. Clients should override this method.
*
* @param mform
* the dialog form
*/
@Override
protected void createFormContent(final IManagedForm mform) {
final FormToolkit toolkit = mform.getToolkit();
final ScrolledForm sform = mform.getForm();
sform.setExpandVertical(true);
final Composite composite = sform.getBody();
final GridLayout layout = new GridLayout(4, false);
composite.setLayout(layout);
GridData textGridData = null;
//Basic parameters section
final Section basicSection = toolkit.createSection(composite, Section.DESCRIPTION
| ExpandableComposite.TITLE_BAR | ExpandableComposite.TWISTIE | ExpandableComposite.EXPANDED);
final GridData basicSectionGridData = new GridData(GridData.FILL, GridData.FILL, true, true);
basicSectionGridData.horizontalSpan = 4;
basicSection.setLayoutData(basicSectionGridData);
basicSection.setText(ANOMALY_LIST_HEADER_MSG);
basicSection.addExpansionListener(new ExpansionAdapter() {
@Override
public void expansionStateChanged(ExpansionEvent e) {
getShell().setSize(getShell().computeSize(SWT.DEFAULT, SWT.DEFAULT));
}
});
final Composite basicSectionClient = toolkit.createComposite(basicSection);
basicSectionClient.setLayout(layout);
basicSection.setClient(basicSectionClient);
//Cloneable Anomaly Table
Set<R4EUIAnomalyBasic> anomalies = getCloneableAnomalies();
int tableHeight = MAX_DISPLAYED_CLONEABLE_ANOMALIES;
if (anomalies.size() < MAX_DISPLAYED_CLONEABLE_ANOMALIES) {
tableHeight = anomalies.size();
}
textGridData = new GridData(GridData.FILL, GridData.FILL, true, true);
fCloneableAnomalyViewer = new TableViewer(basicSectionClient, SWT.FULL_SELECTION | SWT.BORDER | SWT.READ_ONLY
| SWT.H_SCROLL | SWT.V_SCROLL);
textGridData.heightHint = fCloneableAnomalyViewer.getTable().getItemHeight() * tableHeight;
fCloneableAnomalyViewer.getControl().setLayoutData(textGridData);
fCloneableAnomalyViewer.setContentProvider(ArrayContentProvider.getInstance());
ColumnViewerToolTipSupport.enableFor(fCloneableAnomalyViewer, ToolTip.NO_RECREATE);
fCloneableAnomalyViewer.setLabelProvider(new ReviewNavigatorLabelProvider() {
@Override
public String getText(Object element) {
return ((R4EUIAnomalyBasic) element).getAnomaly().getTitle();
}
@Override
public void update(ViewerCell cell) {
cell.setText(((R4EUIAnomalyBasic) cell.getElement()).getAnomaly().getTitle());
cell.setImage(((R4EUIAnomalyBasic) cell.getElement()).getImage(((R4EUIAnomalyBasic) cell.getElement()).getImageLocation()));
}
});
fCloneableAnomalyViewer.setInput(anomalies);
fCloneableAnomalyViewer.addSelectionChangedListener(new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent event) {
//Check and set files based on selected cloneable anomaly
getButton(IDialogConstants.OK_ID).setEnabled(false);
if (event.getSelection() instanceof IStructuredSelection) {
if (null != ((IStructuredSelection) event.getSelection()).getFirstElement()) {
Object selectedObject = ((IStructuredSelection) event.getSelection()).getFirstElement();
if (selectedObject instanceof R4EUIAnomalyBasic) {
final R4EUIAnomalyBasic uiAnomaly = (R4EUIAnomalyBasic) selectedObject;
R4EAnomaly anomaly = uiAnomaly.getAnomaly();
if (null != anomaly) {
if (null != anomaly.getTitle()) {
fAnomalyTitleTextField.setText(anomaly.getTitle());
}
if (null != anomaly.getDescription()) {
fAnomalyDescriptionTextField.setText(anomaly.getDescription());
}
if (null != anomaly.getType()) {
fAnomalyClassTextField.setText(UIUtils.getClassStr(((R4ECommentType) anomaly.getType()).getType()));
}
if (null != anomaly.getRank()) {
fAnomalyRankTextField.setText(UIUtils.getRankStr(anomaly.getRank()));
}
if (null != anomaly.getRule() && null != anomaly.getRule().getId()) {
fRuleIdTextField.setText(anomaly.getRule().getId());
}
}
getButton(IDialogConstants.OK_ID).setEnabled(true);
}
}
}
}
});
//Extra parameters section
final Section extraSection = toolkit.createSection(composite, Section.DESCRIPTION
| ExpandableComposite.TITLE_BAR | ExpandableComposite.TWISTIE | ExpandableComposite.EXPANDED);
final GridData extraSectionGridData = new GridData(GridData.FILL, GridData.FILL, true, true);
extraSectionGridData.horizontalSpan = 4;
extraSection.setLayoutData(extraSectionGridData);
extraSection.setText(ANOMALY_DETAILS_HEADER_MSG);
extraSection.addExpansionListener(new ExpansionAdapter() {
@Override
public void expansionStateChanged(ExpansionEvent e) {
getShell().setSize(getShell().computeSize(SWT.DEFAULT, SWT.DEFAULT));
}
});
final Composite extraSectionClient = toolkit.createComposite(extraSection);
extraSectionClient.setLayout(layout);
extraSection.setClient(extraSectionClient);
toolkit.setBorderStyle(SWT.NULL);
//Anomaly Title
Label label = toolkit.createLabel(extraSectionClient, R4EUIConstants.ANOMALY_TITLE_LABEL_VALUE);
label.setToolTipText(R4EUIConstants.ANOMALY_TITLE_TOOLTIP);
label.setLayoutData(new GridData(GridData.BEGINNING, GridData.BEGINNING, false, false));
fAnomalyTitleTextField = toolkit.createText(extraSectionClient, "", SWT.SINGLE);
textGridData = new GridData(GridData.FILL, GridData.FILL, true, false);
textGridData.horizontalSpan = 3;
fAnomalyTitleTextField.setToolTipText(R4EUIConstants.ANOMALY_TITLE_TOOLTIP);
fAnomalyTitleTextField.setLayoutData(textGridData);
fAnomalyTitleTextField.setEditable(false);
//Anomaly Description
label = toolkit.createLabel(extraSectionClient, R4EUIConstants.ANOMALY_DESCRIPTION_LABEL_VALUE);
label.setToolTipText(R4EUIConstants.ANOMALY_DESCRIPTION_TOOLTIP);
label.setLayoutData(new GridData(GridData.BEGINNING, GridData.BEGINNING, false, false));
- fAnomalyDescriptionTextField = toolkit.createText(extraSectionClient, "", SWT.MULTI | SWT.V_SCROLL);
+ fAnomalyDescriptionTextField = toolkit.createText(extraSectionClient, "", SWT.MULTI | SWT.H_SCROLL
+ | SWT.V_SCROLL);
textGridData = new GridData(GridData.FILL, GridData.FILL, true, false);
textGridData.horizontalSpan = 3;
textGridData.heightHint = fAnomalyTitleTextField.getLineHeight() * 7;
fAnomalyDescriptionTextField.setToolTipText(R4EUIConstants.ANOMALY_DESCRIPTION_TOOLTIP);
fAnomalyDescriptionTextField.setLayoutData(textGridData);
fAnomalyDescriptionTextField.setEditable(false);
//Anomaly Class
label = toolkit.createLabel(extraSectionClient, R4EUIConstants.CLASS_LABEL);
label.setToolTipText(R4EUIConstants.ANOMALY_CLASS_TOOLTIP);
label.setLayoutData(new GridData(GridData.BEGINNING, GridData.BEGINNING, false, false));
fAnomalyClassTextField = toolkit.createText(extraSectionClient, "", SWT.SINGLE);
textGridData = new GridData(GridData.FILL, GridData.FILL, true, false);
textGridData.horizontalSpan = 3;
fAnomalyClassTextField.setToolTipText(R4EUIConstants.ANOMALY_CLASS_TOOLTIP);
fAnomalyClassTextField.setLayoutData(textGridData);
fAnomalyClassTextField.setEditable(false);
//Anomaly Rank
label = toolkit.createLabel(extraSectionClient, R4EUIConstants.RANK_LABEL);
label.setToolTipText(R4EUIConstants.ANOMALY_RANK_TOOLTIP);
label.setLayoutData(new GridData(GridData.BEGINNING, GridData.BEGINNING, false, false));
fAnomalyRankTextField = toolkit.createText(extraSectionClient, "", SWT.SINGLE);
textGridData = new GridData(GridData.FILL, GridData.FILL, true, false);
textGridData.horizontalSpan = 3;
fAnomalyRankTextField.setToolTipText(R4EUIConstants.ANOMALY_CLASS_TOOLTIP);
fAnomalyRankTextField.setLayoutData(textGridData);
fAnomalyRankTextField.setEditable(false);
//Rule ID
label = toolkit.createLabel(extraSectionClient, R4EUIConstants.RULE_ID_LABEL);
label.setToolTipText(R4EUIConstants.RULE_ID_TOOLTIP);
label.setLayoutData(new GridData(GridData.BEGINNING, GridData.BEGINNING, false, false));
fRuleIdTextField = toolkit.createText(extraSectionClient, "", SWT.SINGLE);
textGridData = new GridData(GridData.FILL, GridData.FILL, true, false);
textGridData.horizontalSpan = 3;
fRuleIdTextField.setToolTipText(R4EUIConstants.ANOMALY_CLASS_TOOLTIP);
fRuleIdTextField.setLayoutData(textGridData);
fRuleIdTextField.setEditable(false);
toolkit.setBorderStyle(SWT.BORDER);
//Assigned To
label = toolkit.createLabel(extraSectionClient, R4EUIConstants.ASSIGNED_TO_LABEL);
textGridData = new GridData(GridData.FILL, GridData.FILL, false, false);
textGridData.horizontalSpan = 1;
label.setLayoutData(textGridData);
fAssignedToCombo = new CCombo(extraSectionClient, SWT.BORDER | SWT.READ_ONLY);
final String[] participants = R4EUIModelController.getActiveReview()
.getParticipantIDs()
.toArray(new String[R4EUIModelController.getActiveReview().getParticipantIDs().size()]);
fAssignedToCombo.removeAll();
fAssignedToCombo.add("");
for (String participant : participants) {
fAssignedToCombo.add(participant);
}
textGridData = new GridData(GridData.FILL, GridData.FILL, true, false);
textGridData.horizontalSpan = 3;
fAssignedToCombo.setToolTipText(R4EUIConstants.ASSIGNED_TO_TOOLTIP);
fAssignedToCombo.setLayoutData(textGridData);
//Due Date
label = toolkit.createLabel(extraSectionClient, R4EUIConstants.DUE_DATE_LABEL);
textGridData = new GridData(GridData.FILL, GridData.FILL, false, false);
textGridData.horizontalSpan = 1;
label.setLayoutData(textGridData);
final Composite dateComposite = toolkit.createComposite(extraSectionClient);
textGridData = new GridData(GridData.FILL, GridData.FILL, true, true);
textGridData.horizontalSpan = 3;
dateComposite.setToolTipText(R4EUIConstants.ANOMALY_DUE_DATE_TOOLTIP);
dateComposite.setLayoutData(textGridData);
dateComposite.setLayout(new GridLayout(2, false));
fDateText = toolkit.createText(dateComposite, "", SWT.BORDER | SWT.READ_ONLY);
fDateText.setLayoutData(new GridData(GridData.FILL, GridData.FILL, true, false));
fDateText.setEditable(false);
final Button calendarButton = toolkit.createButton(dateComposite, "...", SWT.NONE);
calendarButton.setLayoutData(new GridData(GridData.FILL, GridData.FILL, false, false));
calendarButton.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
final ICalendarDialog dialog = R4EUIDialogFactory.getInstance().getCalendarDialog();
final int result = dialog.open();
if (result == Window.OK) {
final SimpleDateFormat dateFormat = new SimpleDateFormat(R4EUIConstants.SIMPLE_DATE_FORMAT);
fDateText.setText(dateFormat.format(dialog.getDate()));
fAnomalyDueDateValue = dialog.getDate();
}
}
public void widgetDefaultSelected(SelectionEvent e) { // $codepro.audit.disable emptyMethod
// No implementation needed
}
});
}
/**
* Get All cloneable anomalies for the parent review.
*
* @return R4EUIAnomalyBasic[]
*/
private Set<R4EUIAnomalyBasic> getCloneableAnomalies() {
Set<R4EUIAnomalyBasic> cloneableAnomalies = new HashSet<R4EUIAnomalyBasic>();
R4EUIReviewBasic parentReview = R4EUIModelController.getActiveReview();
for (R4EUIReviewItem items : parentReview.getReviewItems()) {
if (items.getItem().isEnabled()) {
for (R4EUIFileContext file : items.getFileContexts()) {
if (file.getFileContext().isEnabled()) {
for (IR4EUIModelElement anomaly : file.getAnomalyContainerElement().getChildren()) {
if (((R4EUIAnomalyBasic) anomaly).getAnomaly().isEnabled()) {
boolean isDuplicate = false;
for (R4EUIAnomalyBasic oldAnomaly : cloneableAnomalies) {
if (oldAnomaly.isSameAs((R4EUIAnomalyBasic) anomaly)) {
isDuplicate = true;
break;
}
}
if (!isDuplicate) {
cloneableAnomalies.add((R4EUIAnomalyBasic) anomaly);
}
}
}
}
}
}
}
return cloneableAnomalies;
}
/**
* Configures the button bar.
*
* @param parent
* the parent composite
* @return Control
*/
@Override
protected Control createButtonBar(Composite parent) {
final Control bar = super.createButtonBar(parent);
getButton(IDialogConstants.OK_ID).setEnabled(false);
return bar;
}
/**
* Method isResizable.
*
* @return boolean
* @see org.eclipse.jface.dialogs.Dialog#isResizable()
*/
@Override
protected boolean isResizable() {
return true;
}
/**
* Returns the string typed into this input dialog.
*
* @return the anomaly title input string
* @see org.eclipse.mylyn.reviews.r4e.ui.internal.dialogs.IAnomalyInputDialog#getAnomalyTitleValue()
*/
public String getAnomalyTitleValue() {
String title = null;
if (null != fClonedAnomaly && null != fClonedAnomaly.getAnomaly()) {
title = fClonedAnomaly.getAnomaly().getTitle();
}
return title;
}
/**
* Returns the string typed into this input dialog.
*
* @return the anomaly description input string
* @see org.eclipse.mylyn.reviews.r4e.ui.internal.dialogs.IAnomalyInputDialog#getAnomalyDescriptionValue()
*/
public String getAnomalyDescriptionValue() {
String description = null;
if (null != fClonedAnomaly && null != fClonedAnomaly.getAnomaly()) {
description = fClonedAnomaly.getAnomaly().getDescription();
}
return description;
}
/**
* Returns the string typed into this input dialog.
*
* @return the R4EUIRule reference (if any)
* @see org.eclipse.mylyn.reviews.r4e.ui.internal.dialogs.IAnomalyInputDialog#getRuleReferenceValue()
*/
public R4EDesignRule getRuleReferenceValue() {
R4EDesignRule rule = null;
if (null != fClonedAnomaly && null != fClonedAnomaly.getAnomaly()) {
rule = fClonedAnomaly.getAnomaly().getRule();
}
return rule;
}
/**
* Method setClass_.
*
* @param aClass
* R4EDesignRuleClass
* @see org.eclipse.mylyn.reviews.r4e.ui.internal.dialogs.IAnomalyInputDialog#setClass_(R4EDesignRuleClass)
*/
public void setClass_(R4EDesignRuleClass aClass) {
if (null != aClass) {
fAnomalyClassTextField.setText(UIUtils.getClassStr(aClass));
}
}
/**
* Method getClass_.
*
* @return R4EDesignRuleClass
* @see org.eclipse.mylyn.reviews.r4e.ui.internal.dialogs.IAnomalyInputDialog#getClass_()
*/
public R4EDesignRuleClass getClass_() {
R4EDesignRuleClass class_ = null;
if (null != fClonedAnomaly && null != fClonedAnomaly.getAnomaly()
&& null != fClonedAnomaly.getAnomaly().getType()) {
class_ = ((R4ECommentType) fClonedAnomaly.getAnomaly().getType()).getType();
}
return class_;
}
/**
* Method setRank.
*
* @param aRank
* R4EDesignRuleRank
* @see org.eclipse.mylyn.reviews.r4e.ui.internal.dialogs.IAnomalyInputDialog#setRank(R4EDesignRuleRank)
*/
public void setRank(R4EDesignRuleRank aRank) {
if (null != aRank) {
fAnomalyRankTextField.setText(UIUtils.getRankStr(aRank));
}
}
/**
* Method getRank.
*
* @return R4EDesignRuleRank
* @see org.eclipse.mylyn.reviews.r4e.ui.internal.dialogs.IAnomalyInputDialog#getRank()
*/
public R4EDesignRuleRank getRank() {
R4EDesignRuleRank rank = null;
if (null != fClonedAnomaly && null != fClonedAnomaly.getAnomaly()) {
rank = fClonedAnomaly.getAnomaly().getRank();
}
return rank;
}
/**
* Method setDueDate.
*
* @param aDate
* Date
* @see org.eclipse.mylyn.reviews.r4e.ui.internal.dialogs.IAnomalyInputDialog#setDueDate(Date)
*/
public void setDueDate(Date aDate) {
final SimpleDateFormat dateFormat = new SimpleDateFormat(R4EUIConstants.SIMPLE_DATE_FORMAT);
if (null != aDate) {
fDateText.setText(dateFormat.format(aDate));
}
}
/**
* Method getDueDate.
*
* @return Date
* @see org.eclipse.mylyn.reviews.r4e.ui.internal.dialogs.IAnomalyInputDialog#getDueDate()
*/
public Date getDueDate() {
if (null != fAnomalyDueDateValue) {
return new Date(fAnomalyDueDateValue.getTime());
}
return null;
}
/**
* Method setTitle.
*
* @param aTitle
* String
* @see org.eclipse.mylyn.reviews.r4e.ui.internal.dialogs.IAnomalyInputDialog#setTitle(String)
*/
public void setTitle(String aTitle) {
fAnomalyTitleTextField.setText(aTitle);
}
/**
* Method setDescription.
*
* @param aDescription
* String
* @see org.eclipse.mylyn.reviews.r4e.ui.internal.dialogs.IAnomalyInputDialog#setDescription(String)
*/
public void setDescription(String aDescription) {
fAnomalyDescriptionTextField.setText(aDescription);
}
/**
* Method setRuleID.
*
* @param aId
* String
* @see org.eclipse.mylyn.reviews.r4e.ui.internal.dialogs.IAnomalyInputDialog#setRuleID(String)
*/
public void setRuleID(String aId) {
fRuleIdTextField.setText(aId);
}
/**
* Method getAssignedParticipant.
*
* @return String
* @see org.eclipse.mylyn.reviews.r4e.ui.internal.dialogs.IAnomalyInputDialog#getAssigned()
*/
public String getAssigned() {
return fAssignedToParticipant;
}
/**
* Method setAssigned.
*
* @param aParticipant
* - String
* @see org.eclipse.mylyn.reviews.r4e.ui.internal.dialogs.IAnomalyInputDialog#setAssigned(String)
*/
public void setAssigned(String aParticipant) {
fAssignedToCombo.setText(aParticipant);
}
/**
* Method setShellStyle.
*
* @param newShellStyle
* int
*/
@Override
protected void setShellStyle(int newShellStyle) {
int newstyle = newShellStyle & ~SWT.APPLICATION_MODAL; /* turn off APPLICATION_MODAL */
super.setShellStyle(newstyle);
}
/**
* Method open.
*
* @return int
* @see org.eclipse.mylyn.reviews.r4e.ui.internal.dialogs.IAnomalyInputDialog#open()
*/
@Override
public int open() {
super.open();
pumpMessages(); /* this will let the caller wait till OK, Cancel is pressed, but will let the other GUI responsive */
return super.getReturnCode();
}
/**
* Method pumpMessages.
*/
protected void pumpMessages() {
final Shell sh = getShell();
final Display disp = sh.getDisplay();
while (!sh.isDisposed()) { // $codepro.audit.disable methodInvocationInLoopCondition
if (!disp.readAndDispatch()) {
disp.sleep();
}
}
disp.update();
}
}
| true | true | protected void createFormContent(final IManagedForm mform) {
final FormToolkit toolkit = mform.getToolkit();
final ScrolledForm sform = mform.getForm();
sform.setExpandVertical(true);
final Composite composite = sform.getBody();
final GridLayout layout = new GridLayout(4, false);
composite.setLayout(layout);
GridData textGridData = null;
//Basic parameters section
final Section basicSection = toolkit.createSection(composite, Section.DESCRIPTION
| ExpandableComposite.TITLE_BAR | ExpandableComposite.TWISTIE | ExpandableComposite.EXPANDED);
final GridData basicSectionGridData = new GridData(GridData.FILL, GridData.FILL, true, true);
basicSectionGridData.horizontalSpan = 4;
basicSection.setLayoutData(basicSectionGridData);
basicSection.setText(ANOMALY_LIST_HEADER_MSG);
basicSection.addExpansionListener(new ExpansionAdapter() {
@Override
public void expansionStateChanged(ExpansionEvent e) {
getShell().setSize(getShell().computeSize(SWT.DEFAULT, SWT.DEFAULT));
}
});
final Composite basicSectionClient = toolkit.createComposite(basicSection);
basicSectionClient.setLayout(layout);
basicSection.setClient(basicSectionClient);
//Cloneable Anomaly Table
Set<R4EUIAnomalyBasic> anomalies = getCloneableAnomalies();
int tableHeight = MAX_DISPLAYED_CLONEABLE_ANOMALIES;
if (anomalies.size() < MAX_DISPLAYED_CLONEABLE_ANOMALIES) {
tableHeight = anomalies.size();
}
textGridData = new GridData(GridData.FILL, GridData.FILL, true, true);
fCloneableAnomalyViewer = new TableViewer(basicSectionClient, SWT.FULL_SELECTION | SWT.BORDER | SWT.READ_ONLY
| SWT.H_SCROLL | SWT.V_SCROLL);
textGridData.heightHint = fCloneableAnomalyViewer.getTable().getItemHeight() * tableHeight;
fCloneableAnomalyViewer.getControl().setLayoutData(textGridData);
fCloneableAnomalyViewer.setContentProvider(ArrayContentProvider.getInstance());
ColumnViewerToolTipSupport.enableFor(fCloneableAnomalyViewer, ToolTip.NO_RECREATE);
fCloneableAnomalyViewer.setLabelProvider(new ReviewNavigatorLabelProvider() {
@Override
public String getText(Object element) {
return ((R4EUIAnomalyBasic) element).getAnomaly().getTitle();
}
@Override
public void update(ViewerCell cell) {
cell.setText(((R4EUIAnomalyBasic) cell.getElement()).getAnomaly().getTitle());
cell.setImage(((R4EUIAnomalyBasic) cell.getElement()).getImage(((R4EUIAnomalyBasic) cell.getElement()).getImageLocation()));
}
});
fCloneableAnomalyViewer.setInput(anomalies);
fCloneableAnomalyViewer.addSelectionChangedListener(new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent event) {
//Check and set files based on selected cloneable anomaly
getButton(IDialogConstants.OK_ID).setEnabled(false);
if (event.getSelection() instanceof IStructuredSelection) {
if (null != ((IStructuredSelection) event.getSelection()).getFirstElement()) {
Object selectedObject = ((IStructuredSelection) event.getSelection()).getFirstElement();
if (selectedObject instanceof R4EUIAnomalyBasic) {
final R4EUIAnomalyBasic uiAnomaly = (R4EUIAnomalyBasic) selectedObject;
R4EAnomaly anomaly = uiAnomaly.getAnomaly();
if (null != anomaly) {
if (null != anomaly.getTitle()) {
fAnomalyTitleTextField.setText(anomaly.getTitle());
}
if (null != anomaly.getDescription()) {
fAnomalyDescriptionTextField.setText(anomaly.getDescription());
}
if (null != anomaly.getType()) {
fAnomalyClassTextField.setText(UIUtils.getClassStr(((R4ECommentType) anomaly.getType()).getType()));
}
if (null != anomaly.getRank()) {
fAnomalyRankTextField.setText(UIUtils.getRankStr(anomaly.getRank()));
}
if (null != anomaly.getRule() && null != anomaly.getRule().getId()) {
fRuleIdTextField.setText(anomaly.getRule().getId());
}
}
getButton(IDialogConstants.OK_ID).setEnabled(true);
}
}
}
}
});
//Extra parameters section
final Section extraSection = toolkit.createSection(composite, Section.DESCRIPTION
| ExpandableComposite.TITLE_BAR | ExpandableComposite.TWISTIE | ExpandableComposite.EXPANDED);
final GridData extraSectionGridData = new GridData(GridData.FILL, GridData.FILL, true, true);
extraSectionGridData.horizontalSpan = 4;
extraSection.setLayoutData(extraSectionGridData);
extraSection.setText(ANOMALY_DETAILS_HEADER_MSG);
extraSection.addExpansionListener(new ExpansionAdapter() {
@Override
public void expansionStateChanged(ExpansionEvent e) {
getShell().setSize(getShell().computeSize(SWT.DEFAULT, SWT.DEFAULT));
}
});
final Composite extraSectionClient = toolkit.createComposite(extraSection);
extraSectionClient.setLayout(layout);
extraSection.setClient(extraSectionClient);
toolkit.setBorderStyle(SWT.NULL);
//Anomaly Title
Label label = toolkit.createLabel(extraSectionClient, R4EUIConstants.ANOMALY_TITLE_LABEL_VALUE);
label.setToolTipText(R4EUIConstants.ANOMALY_TITLE_TOOLTIP);
label.setLayoutData(new GridData(GridData.BEGINNING, GridData.BEGINNING, false, false));
fAnomalyTitleTextField = toolkit.createText(extraSectionClient, "", SWT.SINGLE);
textGridData = new GridData(GridData.FILL, GridData.FILL, true, false);
textGridData.horizontalSpan = 3;
fAnomalyTitleTextField.setToolTipText(R4EUIConstants.ANOMALY_TITLE_TOOLTIP);
fAnomalyTitleTextField.setLayoutData(textGridData);
fAnomalyTitleTextField.setEditable(false);
//Anomaly Description
label = toolkit.createLabel(extraSectionClient, R4EUIConstants.ANOMALY_DESCRIPTION_LABEL_VALUE);
label.setToolTipText(R4EUIConstants.ANOMALY_DESCRIPTION_TOOLTIP);
label.setLayoutData(new GridData(GridData.BEGINNING, GridData.BEGINNING, false, false));
fAnomalyDescriptionTextField = toolkit.createText(extraSectionClient, "", SWT.MULTI | SWT.V_SCROLL);
textGridData = new GridData(GridData.FILL, GridData.FILL, true, false);
textGridData.horizontalSpan = 3;
textGridData.heightHint = fAnomalyTitleTextField.getLineHeight() * 7;
fAnomalyDescriptionTextField.setToolTipText(R4EUIConstants.ANOMALY_DESCRIPTION_TOOLTIP);
fAnomalyDescriptionTextField.setLayoutData(textGridData);
fAnomalyDescriptionTextField.setEditable(false);
//Anomaly Class
label = toolkit.createLabel(extraSectionClient, R4EUIConstants.CLASS_LABEL);
label.setToolTipText(R4EUIConstants.ANOMALY_CLASS_TOOLTIP);
label.setLayoutData(new GridData(GridData.BEGINNING, GridData.BEGINNING, false, false));
fAnomalyClassTextField = toolkit.createText(extraSectionClient, "", SWT.SINGLE);
textGridData = new GridData(GridData.FILL, GridData.FILL, true, false);
textGridData.horizontalSpan = 3;
fAnomalyClassTextField.setToolTipText(R4EUIConstants.ANOMALY_CLASS_TOOLTIP);
fAnomalyClassTextField.setLayoutData(textGridData);
fAnomalyClassTextField.setEditable(false);
//Anomaly Rank
label = toolkit.createLabel(extraSectionClient, R4EUIConstants.RANK_LABEL);
label.setToolTipText(R4EUIConstants.ANOMALY_RANK_TOOLTIP);
label.setLayoutData(new GridData(GridData.BEGINNING, GridData.BEGINNING, false, false));
fAnomalyRankTextField = toolkit.createText(extraSectionClient, "", SWT.SINGLE);
textGridData = new GridData(GridData.FILL, GridData.FILL, true, false);
textGridData.horizontalSpan = 3;
fAnomalyRankTextField.setToolTipText(R4EUIConstants.ANOMALY_CLASS_TOOLTIP);
fAnomalyRankTextField.setLayoutData(textGridData);
fAnomalyRankTextField.setEditable(false);
//Rule ID
label = toolkit.createLabel(extraSectionClient, R4EUIConstants.RULE_ID_LABEL);
label.setToolTipText(R4EUIConstants.RULE_ID_TOOLTIP);
label.setLayoutData(new GridData(GridData.BEGINNING, GridData.BEGINNING, false, false));
fRuleIdTextField = toolkit.createText(extraSectionClient, "", SWT.SINGLE);
textGridData = new GridData(GridData.FILL, GridData.FILL, true, false);
textGridData.horizontalSpan = 3;
fRuleIdTextField.setToolTipText(R4EUIConstants.ANOMALY_CLASS_TOOLTIP);
fRuleIdTextField.setLayoutData(textGridData);
fRuleIdTextField.setEditable(false);
toolkit.setBorderStyle(SWT.BORDER);
//Assigned To
label = toolkit.createLabel(extraSectionClient, R4EUIConstants.ASSIGNED_TO_LABEL);
textGridData = new GridData(GridData.FILL, GridData.FILL, false, false);
textGridData.horizontalSpan = 1;
label.setLayoutData(textGridData);
fAssignedToCombo = new CCombo(extraSectionClient, SWT.BORDER | SWT.READ_ONLY);
final String[] participants = R4EUIModelController.getActiveReview()
.getParticipantIDs()
.toArray(new String[R4EUIModelController.getActiveReview().getParticipantIDs().size()]);
fAssignedToCombo.removeAll();
fAssignedToCombo.add("");
for (String participant : participants) {
fAssignedToCombo.add(participant);
}
textGridData = new GridData(GridData.FILL, GridData.FILL, true, false);
textGridData.horizontalSpan = 3;
fAssignedToCombo.setToolTipText(R4EUIConstants.ASSIGNED_TO_TOOLTIP);
fAssignedToCombo.setLayoutData(textGridData);
//Due Date
label = toolkit.createLabel(extraSectionClient, R4EUIConstants.DUE_DATE_LABEL);
textGridData = new GridData(GridData.FILL, GridData.FILL, false, false);
textGridData.horizontalSpan = 1;
label.setLayoutData(textGridData);
final Composite dateComposite = toolkit.createComposite(extraSectionClient);
textGridData = new GridData(GridData.FILL, GridData.FILL, true, true);
textGridData.horizontalSpan = 3;
dateComposite.setToolTipText(R4EUIConstants.ANOMALY_DUE_DATE_TOOLTIP);
dateComposite.setLayoutData(textGridData);
dateComposite.setLayout(new GridLayout(2, false));
fDateText = toolkit.createText(dateComposite, "", SWT.BORDER | SWT.READ_ONLY);
fDateText.setLayoutData(new GridData(GridData.FILL, GridData.FILL, true, false));
fDateText.setEditable(false);
final Button calendarButton = toolkit.createButton(dateComposite, "...", SWT.NONE);
calendarButton.setLayoutData(new GridData(GridData.FILL, GridData.FILL, false, false));
calendarButton.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
final ICalendarDialog dialog = R4EUIDialogFactory.getInstance().getCalendarDialog();
final int result = dialog.open();
if (result == Window.OK) {
final SimpleDateFormat dateFormat = new SimpleDateFormat(R4EUIConstants.SIMPLE_DATE_FORMAT);
fDateText.setText(dateFormat.format(dialog.getDate()));
fAnomalyDueDateValue = dialog.getDate();
}
}
public void widgetDefaultSelected(SelectionEvent e) { // $codepro.audit.disable emptyMethod
// No implementation needed
}
});
}
| protected void createFormContent(final IManagedForm mform) {
final FormToolkit toolkit = mform.getToolkit();
final ScrolledForm sform = mform.getForm();
sform.setExpandVertical(true);
final Composite composite = sform.getBody();
final GridLayout layout = new GridLayout(4, false);
composite.setLayout(layout);
GridData textGridData = null;
//Basic parameters section
final Section basicSection = toolkit.createSection(composite, Section.DESCRIPTION
| ExpandableComposite.TITLE_BAR | ExpandableComposite.TWISTIE | ExpandableComposite.EXPANDED);
final GridData basicSectionGridData = new GridData(GridData.FILL, GridData.FILL, true, true);
basicSectionGridData.horizontalSpan = 4;
basicSection.setLayoutData(basicSectionGridData);
basicSection.setText(ANOMALY_LIST_HEADER_MSG);
basicSection.addExpansionListener(new ExpansionAdapter() {
@Override
public void expansionStateChanged(ExpansionEvent e) {
getShell().setSize(getShell().computeSize(SWT.DEFAULT, SWT.DEFAULT));
}
});
final Composite basicSectionClient = toolkit.createComposite(basicSection);
basicSectionClient.setLayout(layout);
basicSection.setClient(basicSectionClient);
//Cloneable Anomaly Table
Set<R4EUIAnomalyBasic> anomalies = getCloneableAnomalies();
int tableHeight = MAX_DISPLAYED_CLONEABLE_ANOMALIES;
if (anomalies.size() < MAX_DISPLAYED_CLONEABLE_ANOMALIES) {
tableHeight = anomalies.size();
}
textGridData = new GridData(GridData.FILL, GridData.FILL, true, true);
fCloneableAnomalyViewer = new TableViewer(basicSectionClient, SWT.FULL_SELECTION | SWT.BORDER | SWT.READ_ONLY
| SWT.H_SCROLL | SWT.V_SCROLL);
textGridData.heightHint = fCloneableAnomalyViewer.getTable().getItemHeight() * tableHeight;
fCloneableAnomalyViewer.getControl().setLayoutData(textGridData);
fCloneableAnomalyViewer.setContentProvider(ArrayContentProvider.getInstance());
ColumnViewerToolTipSupport.enableFor(fCloneableAnomalyViewer, ToolTip.NO_RECREATE);
fCloneableAnomalyViewer.setLabelProvider(new ReviewNavigatorLabelProvider() {
@Override
public String getText(Object element) {
return ((R4EUIAnomalyBasic) element).getAnomaly().getTitle();
}
@Override
public void update(ViewerCell cell) {
cell.setText(((R4EUIAnomalyBasic) cell.getElement()).getAnomaly().getTitle());
cell.setImage(((R4EUIAnomalyBasic) cell.getElement()).getImage(((R4EUIAnomalyBasic) cell.getElement()).getImageLocation()));
}
});
fCloneableAnomalyViewer.setInput(anomalies);
fCloneableAnomalyViewer.addSelectionChangedListener(new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent event) {
//Check and set files based on selected cloneable anomaly
getButton(IDialogConstants.OK_ID).setEnabled(false);
if (event.getSelection() instanceof IStructuredSelection) {
if (null != ((IStructuredSelection) event.getSelection()).getFirstElement()) {
Object selectedObject = ((IStructuredSelection) event.getSelection()).getFirstElement();
if (selectedObject instanceof R4EUIAnomalyBasic) {
final R4EUIAnomalyBasic uiAnomaly = (R4EUIAnomalyBasic) selectedObject;
R4EAnomaly anomaly = uiAnomaly.getAnomaly();
if (null != anomaly) {
if (null != anomaly.getTitle()) {
fAnomalyTitleTextField.setText(anomaly.getTitle());
}
if (null != anomaly.getDescription()) {
fAnomalyDescriptionTextField.setText(anomaly.getDescription());
}
if (null != anomaly.getType()) {
fAnomalyClassTextField.setText(UIUtils.getClassStr(((R4ECommentType) anomaly.getType()).getType()));
}
if (null != anomaly.getRank()) {
fAnomalyRankTextField.setText(UIUtils.getRankStr(anomaly.getRank()));
}
if (null != anomaly.getRule() && null != anomaly.getRule().getId()) {
fRuleIdTextField.setText(anomaly.getRule().getId());
}
}
getButton(IDialogConstants.OK_ID).setEnabled(true);
}
}
}
}
});
//Extra parameters section
final Section extraSection = toolkit.createSection(composite, Section.DESCRIPTION
| ExpandableComposite.TITLE_BAR | ExpandableComposite.TWISTIE | ExpandableComposite.EXPANDED);
final GridData extraSectionGridData = new GridData(GridData.FILL, GridData.FILL, true, true);
extraSectionGridData.horizontalSpan = 4;
extraSection.setLayoutData(extraSectionGridData);
extraSection.setText(ANOMALY_DETAILS_HEADER_MSG);
extraSection.addExpansionListener(new ExpansionAdapter() {
@Override
public void expansionStateChanged(ExpansionEvent e) {
getShell().setSize(getShell().computeSize(SWT.DEFAULT, SWT.DEFAULT));
}
});
final Composite extraSectionClient = toolkit.createComposite(extraSection);
extraSectionClient.setLayout(layout);
extraSection.setClient(extraSectionClient);
toolkit.setBorderStyle(SWT.NULL);
//Anomaly Title
Label label = toolkit.createLabel(extraSectionClient, R4EUIConstants.ANOMALY_TITLE_LABEL_VALUE);
label.setToolTipText(R4EUIConstants.ANOMALY_TITLE_TOOLTIP);
label.setLayoutData(new GridData(GridData.BEGINNING, GridData.BEGINNING, false, false));
fAnomalyTitleTextField = toolkit.createText(extraSectionClient, "", SWT.SINGLE);
textGridData = new GridData(GridData.FILL, GridData.FILL, true, false);
textGridData.horizontalSpan = 3;
fAnomalyTitleTextField.setToolTipText(R4EUIConstants.ANOMALY_TITLE_TOOLTIP);
fAnomalyTitleTextField.setLayoutData(textGridData);
fAnomalyTitleTextField.setEditable(false);
//Anomaly Description
label = toolkit.createLabel(extraSectionClient, R4EUIConstants.ANOMALY_DESCRIPTION_LABEL_VALUE);
label.setToolTipText(R4EUIConstants.ANOMALY_DESCRIPTION_TOOLTIP);
label.setLayoutData(new GridData(GridData.BEGINNING, GridData.BEGINNING, false, false));
fAnomalyDescriptionTextField = toolkit.createText(extraSectionClient, "", SWT.MULTI | SWT.H_SCROLL
| SWT.V_SCROLL);
textGridData = new GridData(GridData.FILL, GridData.FILL, true, false);
textGridData.horizontalSpan = 3;
textGridData.heightHint = fAnomalyTitleTextField.getLineHeight() * 7;
fAnomalyDescriptionTextField.setToolTipText(R4EUIConstants.ANOMALY_DESCRIPTION_TOOLTIP);
fAnomalyDescriptionTextField.setLayoutData(textGridData);
fAnomalyDescriptionTextField.setEditable(false);
//Anomaly Class
label = toolkit.createLabel(extraSectionClient, R4EUIConstants.CLASS_LABEL);
label.setToolTipText(R4EUIConstants.ANOMALY_CLASS_TOOLTIP);
label.setLayoutData(new GridData(GridData.BEGINNING, GridData.BEGINNING, false, false));
fAnomalyClassTextField = toolkit.createText(extraSectionClient, "", SWT.SINGLE);
textGridData = new GridData(GridData.FILL, GridData.FILL, true, false);
textGridData.horizontalSpan = 3;
fAnomalyClassTextField.setToolTipText(R4EUIConstants.ANOMALY_CLASS_TOOLTIP);
fAnomalyClassTextField.setLayoutData(textGridData);
fAnomalyClassTextField.setEditable(false);
//Anomaly Rank
label = toolkit.createLabel(extraSectionClient, R4EUIConstants.RANK_LABEL);
label.setToolTipText(R4EUIConstants.ANOMALY_RANK_TOOLTIP);
label.setLayoutData(new GridData(GridData.BEGINNING, GridData.BEGINNING, false, false));
fAnomalyRankTextField = toolkit.createText(extraSectionClient, "", SWT.SINGLE);
textGridData = new GridData(GridData.FILL, GridData.FILL, true, false);
textGridData.horizontalSpan = 3;
fAnomalyRankTextField.setToolTipText(R4EUIConstants.ANOMALY_CLASS_TOOLTIP);
fAnomalyRankTextField.setLayoutData(textGridData);
fAnomalyRankTextField.setEditable(false);
//Rule ID
label = toolkit.createLabel(extraSectionClient, R4EUIConstants.RULE_ID_LABEL);
label.setToolTipText(R4EUIConstants.RULE_ID_TOOLTIP);
label.setLayoutData(new GridData(GridData.BEGINNING, GridData.BEGINNING, false, false));
fRuleIdTextField = toolkit.createText(extraSectionClient, "", SWT.SINGLE);
textGridData = new GridData(GridData.FILL, GridData.FILL, true, false);
textGridData.horizontalSpan = 3;
fRuleIdTextField.setToolTipText(R4EUIConstants.ANOMALY_CLASS_TOOLTIP);
fRuleIdTextField.setLayoutData(textGridData);
fRuleIdTextField.setEditable(false);
toolkit.setBorderStyle(SWT.BORDER);
//Assigned To
label = toolkit.createLabel(extraSectionClient, R4EUIConstants.ASSIGNED_TO_LABEL);
textGridData = new GridData(GridData.FILL, GridData.FILL, false, false);
textGridData.horizontalSpan = 1;
label.setLayoutData(textGridData);
fAssignedToCombo = new CCombo(extraSectionClient, SWT.BORDER | SWT.READ_ONLY);
final String[] participants = R4EUIModelController.getActiveReview()
.getParticipantIDs()
.toArray(new String[R4EUIModelController.getActiveReview().getParticipantIDs().size()]);
fAssignedToCombo.removeAll();
fAssignedToCombo.add("");
for (String participant : participants) {
fAssignedToCombo.add(participant);
}
textGridData = new GridData(GridData.FILL, GridData.FILL, true, false);
textGridData.horizontalSpan = 3;
fAssignedToCombo.setToolTipText(R4EUIConstants.ASSIGNED_TO_TOOLTIP);
fAssignedToCombo.setLayoutData(textGridData);
//Due Date
label = toolkit.createLabel(extraSectionClient, R4EUIConstants.DUE_DATE_LABEL);
textGridData = new GridData(GridData.FILL, GridData.FILL, false, false);
textGridData.horizontalSpan = 1;
label.setLayoutData(textGridData);
final Composite dateComposite = toolkit.createComposite(extraSectionClient);
textGridData = new GridData(GridData.FILL, GridData.FILL, true, true);
textGridData.horizontalSpan = 3;
dateComposite.setToolTipText(R4EUIConstants.ANOMALY_DUE_DATE_TOOLTIP);
dateComposite.setLayoutData(textGridData);
dateComposite.setLayout(new GridLayout(2, false));
fDateText = toolkit.createText(dateComposite, "", SWT.BORDER | SWT.READ_ONLY);
fDateText.setLayoutData(new GridData(GridData.FILL, GridData.FILL, true, false));
fDateText.setEditable(false);
final Button calendarButton = toolkit.createButton(dateComposite, "...", SWT.NONE);
calendarButton.setLayoutData(new GridData(GridData.FILL, GridData.FILL, false, false));
calendarButton.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
final ICalendarDialog dialog = R4EUIDialogFactory.getInstance().getCalendarDialog();
final int result = dialog.open();
if (result == Window.OK) {
final SimpleDateFormat dateFormat = new SimpleDateFormat(R4EUIConstants.SIMPLE_DATE_FORMAT);
fDateText.setText(dateFormat.format(dialog.getDate()));
fAnomalyDueDateValue = dialog.getDate();
}
}
public void widgetDefaultSelected(SelectionEvent e) { // $codepro.audit.disable emptyMethod
// No implementation needed
}
});
}
|
diff --git a/sonar-gsoc-duplications/src/main/java/org/sonar/duplications/CloneFinder.java b/sonar-gsoc-duplications/src/main/java/org/sonar/duplications/CloneFinder.java
index e6dc51b..580d6c0 100644
--- a/sonar-gsoc-duplications/src/main/java/org/sonar/duplications/CloneFinder.java
+++ b/sonar-gsoc-duplications/src/main/java/org/sonar/duplications/CloneFinder.java
@@ -1,139 +1,138 @@
/*
* Sonar, open source software quality management tool.
* Copyright (C) 2008-2011 SonarSource
* mailto:contact AT sonarsource DOT com
*
* Sonar 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.
*
* Sonar 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 Sonar; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
*/
package org.sonar.duplications;
import org.sonar.duplications.algorithm.CloneReporterAlgorithm;
import org.sonar.duplications.block.Block;
import org.sonar.duplications.block.BlockChunker;
import org.sonar.duplications.block.FileBlockGroup;
import org.sonar.duplications.index.CloneGroup;
import org.sonar.duplications.index.CloneIndex;
import org.sonar.duplications.statement.Statement;
import org.sonar.duplications.statement.StatementChunker;
import org.sonar.duplications.token.TokenChunker;
import org.sonar.duplications.token.TokenQueue;
import java.io.File;
import java.util.List;
public final class CloneFinder {
private TokenChunker tokenChunker;
private StatementChunker stmtChunker;
private BlockChunker blockChunker;
private CloneIndex cloneIndex;
private CloneReporterAlgorithm cloneReporter;
private CloneFinder(Builder builder) {
this.tokenChunker = builder.tokenChunker;
this.stmtChunker = builder.stmtChunker;
this.blockChunker = builder.blockChunker;
this.cloneIndex = builder.cloneIndex;
cloneReporter = builder.cloneReporter;
}
public static Builder build() {
return new Builder();
}
public static final class Builder {
private TokenChunker tokenChunker;
private StatementChunker stmtChunker;
private BlockChunker blockChunker;
private CloneIndex cloneIndex;
private CloneReporterAlgorithm cloneReporter;
public Builder setTokenChunker(TokenChunker tokenChunker) {
this.tokenChunker = tokenChunker;
return this;
}
public Builder setStatementChunker(StatementChunker stmtChunker) {
this.stmtChunker = stmtChunker;
return this;
}
public Builder setBlockChunker(BlockChunker blockChunker) {
this.blockChunker = blockChunker;
return this;
}
public Builder setCloneIndex(CloneIndex cloneIndex) {
this.cloneIndex = cloneIndex;
return this;
}
public Builder setCloneReporter(CloneReporterAlgorithm cloneReporter) {
this.cloneReporter = cloneReporter;
return this;
}
public CloneFinder build() {
return new CloneFinder(this);
}
}
public void register(FileBlockGroup fileBlockGroup) {
for (Block block : fileBlockGroup.getBlockList()) {
cloneIndex.insert(block);
}
}
public void register(File sourceFile) {
FileBlockGroup blockGroup = tokenize(sourceFile);
register(blockGroup);
}
public FileBlockGroup tokenize(File sourceFile) {
List<Block> blocks;
String absolutePath = sourceFile.getAbsolutePath();
try {
TokenQueue tokenQueue = tokenChunker.chunk(sourceFile);
List<Statement> statements = stmtChunker.chunk(tokenQueue);
blocks = blockChunker.chunk(absolutePath, statements);
} catch (Exception e) {
throw new DuplicationsException("Exception during registering file: " + absolutePath, e);
}
FileBlockGroup fileBlockGroup = new FileBlockGroup(absolutePath);
for (Block block : blocks) {
fileBlockGroup.addBlock(block);
- cloneIndex.insert(block);
}
return fileBlockGroup;
}
public void printCloneReporterStatistics() {
cloneReporter.printStatistics();
}
public List<CloneGroup> findClones(FileBlockGroup fileBlockGroup) {
//build on the fly
if (!cloneIndex.containsResourceId(fileBlockGroup.getResourceId())) {
register(fileBlockGroup);
}
return cloneReporter.reportClones(fileBlockGroup);
}
}
| true | true | public FileBlockGroup tokenize(File sourceFile) {
List<Block> blocks;
String absolutePath = sourceFile.getAbsolutePath();
try {
TokenQueue tokenQueue = tokenChunker.chunk(sourceFile);
List<Statement> statements = stmtChunker.chunk(tokenQueue);
blocks = blockChunker.chunk(absolutePath, statements);
} catch (Exception e) {
throw new DuplicationsException("Exception during registering file: " + absolutePath, e);
}
FileBlockGroup fileBlockGroup = new FileBlockGroup(absolutePath);
for (Block block : blocks) {
fileBlockGroup.addBlock(block);
cloneIndex.insert(block);
}
return fileBlockGroup;
}
| public FileBlockGroup tokenize(File sourceFile) {
List<Block> blocks;
String absolutePath = sourceFile.getAbsolutePath();
try {
TokenQueue tokenQueue = tokenChunker.chunk(sourceFile);
List<Statement> statements = stmtChunker.chunk(tokenQueue);
blocks = blockChunker.chunk(absolutePath, statements);
} catch (Exception e) {
throw new DuplicationsException("Exception during registering file: " + absolutePath, e);
}
FileBlockGroup fileBlockGroup = new FileBlockGroup(absolutePath);
for (Block block : blocks) {
fileBlockGroup.addBlock(block);
}
return fileBlockGroup;
}
|
diff --git a/aura-impl/src/main/java/org/auraframework/impl/system/MasterDefRegistryImpl.java b/aura-impl/src/main/java/org/auraframework/impl/system/MasterDefRegistryImpl.java
index 10a6ca01dd..56e4b57a49 100644
--- a/aura-impl/src/main/java/org/auraframework/impl/system/MasterDefRegistryImpl.java
+++ b/aura-impl/src/main/java/org/auraframework/impl/system/MasterDefRegistryImpl.java
@@ -1,1073 +1,1074 @@
/*
* Copyright (C) 2012 salesforce.com, inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.auraframework.impl.system;
import java.lang.ref.WeakReference;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import org.auraframework.Aura;
import org.auraframework.def.ApplicationDef;
import org.auraframework.def.BaseComponentDef;
import org.auraframework.def.DefDescriptor;
import org.auraframework.def.DefDescriptor.DefType;
import org.auraframework.def.Definition;
import org.auraframework.def.DescriptorFilter;
import org.auraframework.def.SecurityProviderDef;
import org.auraframework.impl.root.DependencyDefImpl;
import org.auraframework.service.LoggingService;
import org.auraframework.system.AuraContext;
import org.auraframework.system.AuraContext.Mode;
import org.auraframework.system.DefRegistry;
import org.auraframework.system.Location;
import org.auraframework.system.MasterDefRegistry;
import org.auraframework.system.Source;
import org.auraframework.system.SourceListener;
import org.auraframework.throwable.AuraRuntimeException;
import org.auraframework.throwable.NoAccessException;
import org.auraframework.throwable.quickfix.DefinitionNotFoundException;
import org.auraframework.throwable.quickfix.QuickFixException;
import org.auraframework.util.text.Hash;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
/**
* Overall Master definition registry implementation, there be dragons here.
*
* This 'master' definition registry is actually a single threaded, per request registry that caches certain things in
* what is effectively a thread local cache. This means that once something is pulled into the local thread, it will not
* change.
*
*/
public class MasterDefRegistryImpl implements MasterDefRegistry {
private static final Set<DefType> securedDefTypes = Sets.immutableEnumSet(DefType.APPLICATION, DefType.COMPONENT,
DefType.CONTROLLER, DefType.ACTION);
private static final Set<String> unsecuredPrefixes = ImmutableSet.of("aura");
private static final Set<String> unsecuredNamespaces = ImmutableSet.of("aura", "ui", "os", "auradev",
"org.auraframework");
private static final Set<String> unsecuredNonProductionNamespaces = ImmutableSet.of("auradev");
private static final ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock();
private static final Lock rLock = rwLock.readLock();
private static final Lock wLock = rwLock.writeLock();
private final static int DEPENDENCY_CACHE_SIZE = 100;
private final static int STRING_CACHE_SIZE = 100;
/**
* A dependency entry for a uid+descriptor.
*
* This entry is created for each descriptor that a context uses at the top level. It is cached globally and
* locally. The second version of the entry (with a quick fix) is only ever cached locally.
*
* all values are final, and unmodifiable.
*/
private static class DependencyEntry {
public final String uid;
public final long lastModTime;
public final SortedSet<DefDescriptor<?>> dependencies;
public final QuickFixException qfe;
public DependencyEntry(String uid, SortedSet<DefDescriptor<?>> dependencies, long lastModTime) {
this.uid = uid;
this.dependencies = Collections.unmodifiableSortedSet(dependencies);
this.lastModTime = lastModTime;
this.qfe = null;
}
public DependencyEntry(QuickFixException qfe) {
this.uid = null;
this.dependencies = null;
this.lastModTime = 0;
this.qfe = qfe;
}
@Override
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append(uid);
sb.append(" : ");
if (qfe != null) {
sb.append(qfe);
} else {
sb.append("[");
sb.append(lastModTime);
sb.append("] :");
sb.append(dependencies);
}
return sb.toString();
}
}
private final static Cache<String, DependencyEntry> dependencies = CacheBuilder.newBuilder()
.initialCapacity(DEPENDENCY_CACHE_SIZE).maximumSize(DEPENDENCY_CACHE_SIZE).build();
private final static Cache<String, String> strings = CacheBuilder.newBuilder().initialCapacity(STRING_CACHE_SIZE)
.maximumSize(STRING_CACHE_SIZE).build();
/**
* A local dependencies cache.
*
* We store both by descriptor and by uid. The descriptor keys must include the type, as the qualified name is not
* sufficient to distinguish it. In the case of the UID, we presume that we are safe.
*
* The two keys stored in the local cache are:
* <ul>
* <li>The UID, which should be sufficiently unique for a single request.</li>
* <li>The type+qualified name of the descriptor. We store this to avoid construction in the case where we don't
* have a UID. This is presumed safe because we assume that a single session will have a consistent set of
* permissions</li>
* </ul>
*/
private final Map<String, DependencyEntry> localDependencies = Maps.newHashMap();
private final RegistryTrie delegateRegistries;
private final Map<DefDescriptor<?>, Definition> defs = Maps.newLinkedHashMap();
private final Set<DefDescriptor<?>> accessCache = Sets.newLinkedHashSet();
private SecurityProviderDef securityProvider;
public MasterDefRegistryImpl(DefRegistry<?>... registries) {
delegateRegistries = new RegistryTrie(registries);
}
@Override
public Set<DefDescriptor<?>> find(DescriptorFilter matcher) {
Set<DefRegistry<?>> registries = delegateRegistries.getRegistries(matcher);
Set<DefDescriptor<?>> matched = Sets.newHashSet();
for (DefRegistry<?> reg : registries) {
//
// This could be a little dangerous, but unless we force all of our
// registries to implement find, this is necessary.
//
if (reg.hasFind()) {
matched.addAll(reg.find(matcher));
}
}
return matched;
}
@Override
public <D extends Definition> Set<DefDescriptor<D>> find(DefDescriptor<D> matcher) {
if (matcher.getNamespace().equals("*")) {
Set<DefDescriptor<D>> matchingDesc = new LinkedHashSet<DefDescriptor<D>>();
String qualifiedNamePattern = null;
switch (matcher.getDefType()) {
case CONTROLLER:
case TESTSUITE:
case MODEL:
case RENDERER:
case HELPER:
case STYLE:
case TYPE:
case PROVIDER:
case SECURITY_PROVIDER:
qualifiedNamePattern = "%s://%s.%s";
break;
case ATTRIBUTE:
case LAYOUT:
case LAYOUT_ITEM:
case TESTCASE:
case APPLICATION:
case COMPONENT:
case INTERFACE:
case EVENT:
case DOCUMENTATION:
case LAYOUTS:
case NAMESPACE:
qualifiedNamePattern = "%s://%s:%s";
break;
case ACTION:
// TODO: FIXME
throw new AuraRuntimeException("Find on ACTION defs not supported.");
}
for (String namespace : delegateRegistries.getAllNamespaces()) {
String qualifiedName = String.format(qualifiedNamePattern,
matcher.getPrefix() != null ? matcher.getPrefix() : "*", namespace,
matcher.getName() != null ? matcher.getName() : "*");
@SuppressWarnings("unchecked")
DefDescriptor<D> namespacedMatcher = (DefDescriptor<D>) DefDescriptorImpl.getInstance(qualifiedName,
matcher.getDefType().getPrimaryInterface());
DefRegistry<D> registry = getRegistryFor(namespacedMatcher);
if (registry != null) {
matchingDesc.addAll(registry.find(namespacedMatcher));
}
}
return matchingDesc;
} else {
return getRegistryFor(matcher).find(matcher);
}
}
/**
* A compiling definition.
*
* This embodies a definition that is in the process of being compiled. It stores the descriptor, definition, and
* the registry to which it belongs to avoid repeated lookups.
*/
private static class CompilingDef<T extends Definition> {
/**
* The descriptor we are compiling.
*/
public DefDescriptor<T> descriptor;
/**
* The compiled def.
*
* Should be non-null by the end of compile.
*/
public T def;
/**
* The registry associated with the def.
*/
public DefRegistry<T> registry;
/**
* All of the parents (needed in the case that we fail).
*/
public Set<Definition> parents = Sets.newHashSet();
/**
* Did we build this definition?.
*
* If this is true, we need to do the validation steps after finishing.
*/
public boolean built = false;
public void markValid() {
if (def != null) {
registry.markValid(descriptor, def);
}
}
}
/**
* The compile context.
*
* FIXME: the AuraContext is only needed for 'setNamepace()'.
*
* This class holds the local information necessary for compilation.
*/
private static class CompileContext {
public final AuraContext context = Aura.getContextService().getCurrentContext();
public final LoggingService loggingService = Aura.getLoggingService();
public final Map<DefDescriptor<? extends Definition>, CompilingDef<?>> compiled = Maps.newHashMap();
public final Map<DefDescriptor<? extends Definition>, Definition> dependencies;
public boolean addedPreloads = false;
// public final Map<DefDescriptor<? extends Definition>, Definition>
// dependencies = Maps.newHashMap();
public CompileContext(Map<DefDescriptor<? extends Definition>, Definition> dependencies) {
this.dependencies = dependencies;
}
public <D extends Definition> CompilingDef<D> getCompiling(DefDescriptor<D> descriptor) {
@SuppressWarnings("unchecked")
CompilingDef<D> cd = (CompilingDef<D>) compiled.get(descriptor);
if (cd == null) {
cd = new CompilingDef<D>();
compiled.put(descriptor, cd);
}
cd.descriptor = descriptor;
return cd;
}
}
/**
* A private helper routine to make the compiler code more sane.
*
* This processes a single definition in a dependency tree. It works as a single step in a breadth first traversal
* of the tree, accumulating children in the 'deps' set, and updating the compile context with the current
* definition.
*
* Note that once the definition has been retrieved, this code uses the 'canonical' descriptor from the definition,
* discarding the incoming descriptor.
*
* @param descriptor the descriptor that we are currently handling, must not be in the compiling defs.
* @param cc the compile context to allow us to accumulate information.
* @param deps the set of dependencies that we are accumulating.
* @throws QuickFixException if the definition is not found, or validateDefinition() throws one.
*/
private <D extends Definition> D getHelper(DefDescriptor<D> descriptor, CompileContext cc,
Set<DefDescriptor<?>> deps) throws QuickFixException {
@SuppressWarnings("unchecked")
D def = (D) defs.get(descriptor);
CompilingDef<D> cd = cc.getCompiling(descriptor);
DefRegistry<D> registry = null;
if (cd.def != null) {
return cd.def;
}
if (def == null) {
registry = getRegistryFor(descriptor);
if (registry != null) {
def = registry.getDef(descriptor);
}
if (def == null) {
//
// At this point, we have failed to get the def, so we should
// throw an
// error. The first stanza is to provide a more useful error
// description
// including the set of components using the missing component.
//
if (!cd.parents.isEmpty()) {
StringBuilder sb = new StringBuilder();
Location handy = null;
for (Definition parent : cd.parents) {
handy = parent.getLocation();
if (sb.length() != 0) {
sb.append(", ");
}
sb.append(parent.getDescriptor().toString());
}
throw new DefinitionNotFoundException(descriptor, handy, sb.toString());
}
throw new DefinitionNotFoundException(descriptor);
}
}
//
// Ok. We have a def. let's figure out what to do with it.
//
@SuppressWarnings("unchecked")
DefDescriptor<D> canonical = (DefDescriptor<D>) def.getDescriptor();
Set<DefDescriptor<?>> newDeps = Sets.newHashSet();
//
// Make sure all of our fields are correct in our compiling def.
//
cd.def = def;
cd.descriptor = canonical;
cd.registry = registry;
if (!def.isValid()) {
//
// If our def is not 'valid', we must have built it, which means we
// need
// to validate. There is a subtle race condition here where more
// than one
// thread can grab a def from a registry, and they may all validate.
//
cd.built = true;
if (cd.registry == null) {
cd.registry = getRegistryFor(descriptor);
}
cc.loggingService.incrementNum(LoggingService.DEF_COUNT);
// FIXME: setting the current namespace on the context seems
// extremely hackish
cc.context.setCurrentNamespace(canonical.getNamespace());
def.validateDefinition();
}
//
// Store the def locally.
//
defs.put(canonical, def);
def.appendDependencies(newDeps);
//
// FIXME: this code will go away with preloads.
// This pulls in the context preloads. not pretty, but it works.
//
- if (!cc.addedPreloads && canonical.getDefType().equals(DefType.APPLICATION)) {
+ if (!cc.addedPreloads && (canonical.getDefType().equals(DefType.APPLICATION)
+ || canonical.equals(cc.context.getApplicationDescriptor()))) {
cc.addedPreloads = true;
Set<String> preloads = cc.context.getPreloads();
for (String preload : preloads) {
if (!preload.contains("_")) {
DependencyDefImpl.Builder ddb = new DependencyDefImpl.Builder();
ddb.setResource(preload);
ddb.setType("APPLICATION,COMPONENT,STYLE,EVENT");
ddb.build().appendDependencies(newDeps);
}
}
}
for (DefDescriptor<?> dep : newDeps) {
if (!defs.containsKey(dep)) {
CompilingDef<?> depcd = cc.getCompiling(dep);
depcd.parents.add(def);
}
}
deps.addAll(newDeps);
cc.dependencies.put(canonical, def);
return def;
}
/**
* finish up the validation of a set of compiling defs.
*
* @param context only needed to do setCurrentNamspace.
*/
private void finishValidation(AuraContext context, Collection<CompilingDef<?>> compiling) throws QuickFixException {
//
// Now validate our references.
//
for (CompilingDef<?> cd : compiling) {
if (cd.built) {
// FIXME: setting the current namespace on the context seems extremely hackish
context.setCurrentNamespace(cd.descriptor.getNamespace());
cd.def.validateReferences();
}
}
//
// And finally, mark everything as happily compiled.
//
for (CompilingDef<?> cd : compiling) {
// FIXME: setting the current namespace on the context seems extremely hackish
if (cd.built) {
context.setCurrentNamespace(cd.descriptor.getNamespace());
cd.markValid();
defs.put(cd.descriptor, cd.def);
}
}
}
/**
* Compile a single definition, finding all of the static dependencies.
*
* This is the primary entry point for compiling a single definition. The basic guarantees enforced here are:
* <ol>
* <li>Each definition has 'validateDefinition()' called on it exactly once.</li>
* <li>No definition is marked as valid until all definitions in the dependency set have been validated</li>
* <li>Each definition has 'validateReferences()' called on it exactly once, after the definitions have been put in
* local cache</li>
* <li>All definitions are marked valid by the DefRegistry after the validation is complete</li>
* <li>No definition should be available to other threads until it is marked valid</li>
* <ol>
*
* In order to do all of this, we keep a set of 'compiling' definitions locally, and use that to calculate
* dependencies and walk the tree. Circular dependencies are handled gracefully, and no other thread can interfere
* because everything is local.
*
* FIXME: this should really cache invalid definitions and make sure that we don't bother re-compiling until there
* is some change of state. However, that is rather more complex than it sounds.... and shouldn't really manifest
* much in a released system.
*
* @param descriptor the descriptor that we wish to compile.
*/
protected <D extends Definition> D compileDef(DefDescriptor<D> descriptor,
Map<DefDescriptor<?>, Definition> dependencies) throws QuickFixException {
Set<DefDescriptor<?>> next = Sets.newHashSet();
CompileContext cc = new CompileContext(dependencies);
D def;
rLock.lock();
try {
cc.loggingService.startTimer(LoggingService.TIMER_DEFINITION_CREATION);
try {
//
// FIXME: in the event of a compiled def, we should be done at the
// first fetch, though realistically,
// this should require that all defs be cached, or we _will_ break.
//
// First, walk all dependencies, compiling them with
// validateDefinition.
// and accumulating the set in a local map.
//
try {
def = getHelper(descriptor, cc, next);
} catch (DefinitionNotFoundException dnfe) {
//
// ignore a nonexistent def here.
// This fits the description of the routine, but it seems a bit
// silly.
//
defs.put(descriptor, null);
return null;
}
//
// This loop accumulates over a breadth first traversal of the
// dependency tree.
// All child definitions are added to the 'next' set, while walking
// the 'current'
// set.
//
while (next.size() > 0) {
Set<DefDescriptor<?>> current = next;
next = Sets.newHashSet();
for (DefDescriptor<?> cdesc : current) {
getHelper(cdesc, cc, next);
}
}
finishValidation(cc.context, cc.compiled.values());
return def;
} finally {
cc.loggingService.stopTimer(LoggingService.TIMER_DEFINITION_CREATION);
}
} finally {
rLock.unlock();
}
}
/**
* Internal routine to compile and return a DependencyEntry.
*
* This routine always compiles the definition, even if it is in the caches. If the incoming descriptor does not
* correspond to a definition, it will return null, otherwise, on failure it will throw a QuickFixException.
*
* Please look at {@link #localDependencies} if you are mucking in here.
*
* Side Effects:
* <ul>
* <li>All definitions that were encountered during the compile will be put in the local def cache, even if a QFE is
* thrown</li>
* <li>A hash is compiled for the definition if it compiles</li>
* <li>a dependency entry is cached locally in any case</li>
* <li>a dependency entry is cached globally if the definition compiled</li>
* </ul>
*
* @param descriptor the incoming descriptor to compile
* @return the definition compiled from the descriptor, or null if not found.
* @throws QuickFixException if the definition failed to compile.
*/
private <T extends Definition> DependencyEntry compileDE(DefDescriptor<T> descriptor) throws QuickFixException {
// See localDependencies comment
String key = makeLocalKey(descriptor);
try {
Map<DefDescriptor<?>, Definition> dds = Maps.newTreeMap();
Definition def = compileDef(descriptor, dds);
DependencyEntry de;
String uid;
long lmt = 0;
if (def == null) {
return null;
}
for (Definition t : dds.values()) {
if (t.getLocation() != null && t.getLocation().getLastModified() > lmt) {
lmt = t.getLocation().getLastModified();
}
}
StringBuilder sb = new StringBuilder(dds.size() * 20);
//
// Calculate our hash based on the descriptors and their hashes (if
// any).
// This uses a promise, and the string builder methods of Hash.
//
Hash.StringBuilder globalBuilder = new Hash.StringBuilder();
for (Map.Entry<DefDescriptor<?>, Definition> entry : dds.entrySet()) {
sb.setLength(0);
sb.append(entry.getKey().getQualifiedName().toLowerCase());
sb.append("|");
String hash = entry.getValue().getOwnHash();
if (hash != null) {
// TODO: we need to ensure that null hashes are ok
sb.append(hash.toString());
}
sb.append(",");
globalBuilder.addString(sb.toString());
}
uid = globalBuilder.build().toString();
//
// Now try a re-lookup. This may catch existing cached
// entries where uid was null.
//
// TODO : this breaks last mod time tests, as it causes the mod time
// to stay at the first compile time. We should phase out last mod
// time, and then re-instantiate this code.
//
// de = getDE(uid, key);
// if (de == null) {
de = new DependencyEntry(uid, Sets.newTreeSet(dds.keySet()), lmt);
dependencies.put(makeGlobalKey(de.uid, descriptor), de);
// See localDependencies comment
localDependencies.put(de.uid, de);
localDependencies.put(key, de);
// }
return de;
} catch (QuickFixException qfe) {
// See localDependencies comment
localDependencies.put(key, new DependencyEntry(qfe));
throw qfe;
}
}
/**
* Get a dependency entry for a given uid.
*
* This is a convenience routine to check both the local and global cache for a value.
*
* Please look at {@link #localDependencies} if you are mucking in here.
*
* Side Effects:
* <ul>
* <li>If a dependency is found in the global cache, it is populated into the local cache.</li>
* </ul>
*
* @param uid the uid may be null, if so, it only checks the local cache.
* @param descriptor the descriptor, used for both global and local cache lookups.
* @return the DependencyEntry or null if none present.
*/
private DependencyEntry getDE(String uid, DefDescriptor<?> descriptor) {
// See localDependencies comment
String key = makeLocalKey(descriptor);
if (uid != null) {
DependencyEntry de = localDependencies.get(uid);
if (de != null) {
return de;
}
de = dependencies.getIfPresent(makeGlobalKey(uid, descriptor));
if (de != null) {
// See localDependencies comment
localDependencies.put(uid, de);
localDependencies.put(key, de);
return de;
}
return null;
} else {
// See localDependencies comment
return localDependencies.get(key);
}
}
/**
* Get a definition from a registry, and build a compilingDef if needed.
*
* This retrieves the definition, and if it is validated, simply puts it in the local cache, otherwise, it builds a
* CompilingDef for it, and returns that for further processing.
*
* @param context The aura context for the compiling def.
* @param descriptor the descriptor for which we need a definition.
* @return A compilingDef for the definition, or null if not needed.
*/
private <D extends Definition> CompilingDef<D> validateHelper(AuraContext context, DefDescriptor<D> descriptor)
throws QuickFixException {
DefRegistry<D> registry = null;
D def;
registry = getRegistryFor(descriptor);
def = registry.getDef(descriptor);
if (!def.isValid()) {
CompilingDef<D> cd = new CompilingDef<D>();
//
// If our def is not 'valid', we must have built it, which means we need
// to validate. There is a subtle race condition here where more than one
// thread can grab a def from a registry, and they may all validate.
//
context.setCurrentNamespace(def.getDescriptor().getNamespace());
def.validateDefinition();
cd.def = def;
cd.registry = registry;
cd.built = true;
cd.descriptor = descriptor;
return cd;
} else {
defs.put(descriptor, def);
}
return null;
}
@Override
public <T extends Definition> long getLastMod(String uid) {
DependencyEntry de = localDependencies.get(uid);
if (de != null) {
return de.lastModTime;
}
return 0;
}
@Override
public <T extends Definition> Set<DefDescriptor<?>> getDependencies(String uid) {
DependencyEntry de = localDependencies.get(uid);
if (de != null) {
return de.dependencies;
}
return null;
}
/**
* Get a definition.
*
* This does a scan of the loaded dependency entries to check if there is something to pull, otherwise, it just
* compiles the entry. This should log a warning somewhere, as it is a dependency that was not noted.
*
* @param descriptor the descriptor to find.
* @return the corresponding definition, or null if it doesn't exist.
* @throws QuickFixException if there is a compile time error.
*/
@Override
public <D extends Definition> D getDef(DefDescriptor<D> descriptor) throws QuickFixException {
rLock.lock();
try {
if (descriptor == null) {
return null;
}
if (defs.containsKey(descriptor)) {
@SuppressWarnings("unchecked")
D def = (D) defs.get(descriptor);
return def;
}
DependencyEntry de = getDE(null, descriptor);
if (de == null) {
for (DependencyEntry det : localDependencies.values()) {
if (det.dependencies != null && det.dependencies.contains(descriptor)) {
de = det;
break;
}
}
}
if (de == null) {
//
// Not in any dependecies.
// This is often a bug, and should be logged.
//
compileDE(descriptor);
@SuppressWarnings("unchecked")
D def = (D) defs.get(descriptor);
return def;
}
//
// found an entry.
// In this case, throw a QFE if we have one.
//
if (de.qfe != null) {
throw de.qfe;
}
//
// Now we need to actually do the build..
//
List<CompilingDef<?>> compiled = Lists.newArrayList();
AuraContext context = Aura.getContextService().getCurrentContext();
for (DefDescriptor<?> dd : de.dependencies) {
CompilingDef<?> def = validateHelper(context, dd);
if (def != null) {
compiled.add(def);
}
}
finishValidation(context, compiled);
@SuppressWarnings("unchecked")
D def = (D) defs.get(descriptor);
return def;
} finally {
rLock.unlock();
}
}
@SuppressWarnings("unchecked")
@Override
public <D extends Definition> void save(D def) {
getRegistryFor((DefDescriptor<D>) def.getDescriptor()).save(def);
defs.remove(def.getDescriptor());
}
@Override
public <D extends Definition> boolean exists(DefDescriptor<D> descriptor) {
if (defs.containsKey(descriptor)) {
return true;
}
DefRegistry<D> reg = getRegistryFor(descriptor);
return reg != null && reg.exists(descriptor);
}
/**
* This figures out based on prefix what registry this component is for, it could return null if the prefix is not
* found.
*/
@SuppressWarnings("unchecked")
private <T extends Definition> DefRegistry<T> getRegistryFor(DefDescriptor<T> descriptor) {
return (DefRegistry<T>) delegateRegistries.getRegistryFor(descriptor);
}
@Override
public <D extends Definition> void addLocalDef(D def) {
defs.put(def.getDescriptor(), def);
}
@Override
public <T extends Definition> Source<T> getSource(DefDescriptor<T> descriptor) {
DefRegistry<T> reg = getRegistryFor(descriptor);
if (reg != null) {
return reg.getSource(descriptor);
}
return null;
}
@Override
public boolean namespaceExists(String ns) {
return delegateRegistries.getAllNamespaces().contains(ns);
}
/**
* Get a security provider for the application.
*
* This should probably catch the quick fix exception and simply treat it as a null security provider. This caches
* the security provider.
*
* @return the sucurity provider for the application or null if none.
* @throws QuickFixException if there was a problem compiling.
*/
private SecurityProviderDef getSecurityProvider() throws QuickFixException {
if (securityProvider == null) {
DefDescriptor<? extends BaseComponentDef> rootDesc = Aura.getContextService().getCurrentContext()
.getApplicationDescriptor();
SecurityProviderDef securityProviderDef = null;
if (rootDesc != null && rootDesc.getDefType().equals(DefType.APPLICATION)) {
ApplicationDef root = (ApplicationDef) getDef(rootDesc);
if (root != null) {
DefDescriptor<SecurityProviderDef> securityDesc = root.getSecurityProviderDefDescriptor();
if (securityDesc != null) {
securityProviderDef = getDef(securityDesc);
}
}
}
securityProvider = securityProviderDef;
}
return securityProvider;
}
@Override
public void assertAccess(DefDescriptor<?> desc) throws QuickFixException {
if (!accessCache.contains(desc)) {
Aura.getLoggingService().incrementNum("SecurityProviderCheck");
DefType defType = desc.getDefType();
String ns = desc.getNamespace();
AuraContext context = Aura.getContextService().getCurrentContext();
Mode mode = context.getMode();
String prefix = desc.getPrefix();
//
// This breaks encapsulation! -gordon
//
boolean isTopLevel = desc.equals(context.getApplicationDescriptor());
if (isTopLevel) {
//
// If we are trying to access the top level component, we need to ensure
// that it is _not_ abstract.
//
BaseComponentDef def = getDef(context.getApplicationDescriptor());
if (def != null && def.isAbstract() && def.getProviderDescriptor() == null) {
throw new NoAccessException(String.format("Access to %s disallowed. Abstract definition.", desc));
}
}
//
// If this is _not_ the top level, we allow circumventing the security provider.
// This means that certain things will short-circuit, hopefully making checks faster...
// Not sure if this is premature optimization or not.
//
if (!isTopLevel || desc.getDefType().equals(DefType.COMPONENT)) {
if (!securedDefTypes.contains(defType)
|| unsecuredPrefixes.contains(prefix)
|| unsecuredNamespaces.contains(ns)
|| (mode != Mode.PROD && (!Aura.getConfigAdapter().isProduction())
&& unsecuredNonProductionNamespaces .contains(ns))) {
accessCache.add(desc);
return;
}
if (ns != null && DefDescriptor.JAVA_PREFIX.equals(prefix)) {
// handle java packages that have namespaces like aura.impl.blah
for (String okNs : unsecuredNamespaces) {
if (ns.startsWith(okNs)) {
accessCache.add(desc);
return;
}
}
}
}
SecurityProviderDef securityProviderDef = getSecurityProvider();
if (securityProviderDef == null) {
if (mode != Mode.PROD && !Aura.getConfigAdapter().isProduction()) {
accessCache.add(desc);
return;
} else {
throw new NoAccessException(String.format("Access to %s disallowed. No Security Provider found.",
desc));
}
} else {
if (!securityProviderDef.isAllowed(desc)) {
throw new NoAccessException(String.format("Access to %s disallowed by %s", desc,
securityProviderDef.getDescriptor().getName()));
}
}
accessCache.add(desc);
}
}
/**
* only used by admin tools to view all registries
*/
public DefRegistry<?>[] getAllRegistries() {
return delegateRegistries.getAllRegistries();
}
/**
* Filter the entire set of current definitions by a set of preloads.
*
* This filtering is very simple, it just looks for local definitions that are not included in the preload set.
*/
@Override
public Map<DefDescriptor<? extends Definition>, Definition> filterRegistry(Set<DefDescriptor<?>> preloads) {
Map<DefDescriptor<? extends Definition>, Definition> filtered;
if (preloads == null || preloads.isEmpty()) {
return Maps.newHashMap(defs);
}
filtered = Maps.newHashMapWithExpectedSize(defs.size());
for (Map.Entry<DefDescriptor<? extends Definition>, Definition> entry : defs.entrySet()) {
if (!preloads.contains(entry.getKey())) {
filtered.put(entry.getKey(), entry.getValue());
}
}
return filtered;
}
@Override
public <T extends Definition> boolean invalidate(DefDescriptor<T> descriptor) {
defs.clear();
localDependencies.clear();
accessCache.clear();
dependencies.invalidateAll();
securityProvider = null;
return false;
}
private String getKey(DependencyEntry de, DefDescriptor<?> descriptor, String key) {
return String.format("%s@%s@%s", de.uid, descriptor.getQualifiedName().toLowerCase(), key);
}
@Override
public <T extends Definition> String getCachedString(String uid, DefDescriptor<?> descriptor, String key) {
DependencyEntry de = localDependencies.get(uid);
if (de != null) {
return strings.getIfPresent(getKey(de, descriptor, key));
}
return null;
}
@Override
public <T extends Definition> void putCachedString(String uid, DefDescriptor<?> descriptor, String key, String value) {
DependencyEntry de = localDependencies.get(uid);
if (de != null) {
strings.put(getKey(de, descriptor, key), value);
}
}
/**
* Get the UID.
*
* This uses some trickery to try to be efficient, including using a dual keyed local cache to avoid looking up
* values more than once even in the absense of remembered context.
*
* Note: there is no guarantee that the definitions have been fetched from cache here, so there is a very subtle
* race condition.
*
* @param uid the uid for cache lookup (null means unknown).
* @param descriptor the descriptor to fetch.
* @return the correct uid for the definition, or null if there is none.
* @throws QuickFixException if the definition cannot be compiled.
*/
@Override
public <T extends Definition> String getUid(String uid, DefDescriptor<T> descriptor) throws QuickFixException {
if (descriptor == null) {
return null;
}
DependencyEntry de = null;
de = getDE(uid, descriptor);
if (de == null) {
try {
de = compileDE(descriptor);
//
// If we can't find our descriptor, we just give back a null.
if (de == null) {
return null;
}
} catch (QuickFixException qfe) {
// try to pick it up from the cache.
de = getDE(null, descriptor);
// this should never happen.
if (de == null) {
throw new AuraRuntimeException("unexpected null on QFE");
}
}
}
if (de.qfe != null) {
throw de.qfe;
}
return de.uid;
}
/** Creates a key for the localDependencies, using DefType and FQN. */
private String makeLocalKey(DefDescriptor<?> descriptor) {
return descriptor.getDefType().toString() + ":" + descriptor.getQualifiedName().toLowerCase();
}
/**
* Creates a key for the global {@link #dependencies}, using UID, type, and FQN.
*/
private String makeGlobalKey(String uid, DefDescriptor<?> descriptor) {
return uid + "/" + makeLocalKey(descriptor);
}
/**
* The driver for cache-consistency management in response to source changes.
* MDR drives the process, will notify all registered listeners while write blocking,
* then invalidate it's own caches.
*
* @param listeners - collections of listeners to notify of source changes
* @param source - DefDescriptor that changed - for granular cache clear
* (currently not considered here, but other listeners may make use of it)
* @param event - what type of event triggered the change
*/
public static void notifyDependentSourceChange(Collection<WeakReference<SourceListener>> listeners,
DefDescriptor<?> source,
SourceListener.SourceMonitorEvent event) {
wLock.lock();
try {
// notify provided listeners, presumably to clear caches
for (WeakReference<SourceListener> i : listeners) {
SourceListener sl = i.get();
if (sl != null) {
sl.onSourceChanged(source, event);
}
}
// lastly, clear MDR's static caches
dependencies.invalidateAll();
} finally {
wLock.unlock();
}
}
}
| true | true | private <D extends Definition> D getHelper(DefDescriptor<D> descriptor, CompileContext cc,
Set<DefDescriptor<?>> deps) throws QuickFixException {
@SuppressWarnings("unchecked")
D def = (D) defs.get(descriptor);
CompilingDef<D> cd = cc.getCompiling(descriptor);
DefRegistry<D> registry = null;
if (cd.def != null) {
return cd.def;
}
if (def == null) {
registry = getRegistryFor(descriptor);
if (registry != null) {
def = registry.getDef(descriptor);
}
if (def == null) {
//
// At this point, we have failed to get the def, so we should
// throw an
// error. The first stanza is to provide a more useful error
// description
// including the set of components using the missing component.
//
if (!cd.parents.isEmpty()) {
StringBuilder sb = new StringBuilder();
Location handy = null;
for (Definition parent : cd.parents) {
handy = parent.getLocation();
if (sb.length() != 0) {
sb.append(", ");
}
sb.append(parent.getDescriptor().toString());
}
throw new DefinitionNotFoundException(descriptor, handy, sb.toString());
}
throw new DefinitionNotFoundException(descriptor);
}
}
//
// Ok. We have a def. let's figure out what to do with it.
//
@SuppressWarnings("unchecked")
DefDescriptor<D> canonical = (DefDescriptor<D>) def.getDescriptor();
Set<DefDescriptor<?>> newDeps = Sets.newHashSet();
//
// Make sure all of our fields are correct in our compiling def.
//
cd.def = def;
cd.descriptor = canonical;
cd.registry = registry;
if (!def.isValid()) {
//
// If our def is not 'valid', we must have built it, which means we
// need
// to validate. There is a subtle race condition here where more
// than one
// thread can grab a def from a registry, and they may all validate.
//
cd.built = true;
if (cd.registry == null) {
cd.registry = getRegistryFor(descriptor);
}
cc.loggingService.incrementNum(LoggingService.DEF_COUNT);
// FIXME: setting the current namespace on the context seems
// extremely hackish
cc.context.setCurrentNamespace(canonical.getNamespace());
def.validateDefinition();
}
//
// Store the def locally.
//
defs.put(canonical, def);
def.appendDependencies(newDeps);
//
// FIXME: this code will go away with preloads.
// This pulls in the context preloads. not pretty, but it works.
//
if (!cc.addedPreloads && canonical.getDefType().equals(DefType.APPLICATION)) {
cc.addedPreloads = true;
Set<String> preloads = cc.context.getPreloads();
for (String preload : preloads) {
if (!preload.contains("_")) {
DependencyDefImpl.Builder ddb = new DependencyDefImpl.Builder();
ddb.setResource(preload);
ddb.setType("APPLICATION,COMPONENT,STYLE,EVENT");
ddb.build().appendDependencies(newDeps);
}
}
}
for (DefDescriptor<?> dep : newDeps) {
if (!defs.containsKey(dep)) {
CompilingDef<?> depcd = cc.getCompiling(dep);
depcd.parents.add(def);
}
}
deps.addAll(newDeps);
cc.dependencies.put(canonical, def);
return def;
}
| private <D extends Definition> D getHelper(DefDescriptor<D> descriptor, CompileContext cc,
Set<DefDescriptor<?>> deps) throws QuickFixException {
@SuppressWarnings("unchecked")
D def = (D) defs.get(descriptor);
CompilingDef<D> cd = cc.getCompiling(descriptor);
DefRegistry<D> registry = null;
if (cd.def != null) {
return cd.def;
}
if (def == null) {
registry = getRegistryFor(descriptor);
if (registry != null) {
def = registry.getDef(descriptor);
}
if (def == null) {
//
// At this point, we have failed to get the def, so we should
// throw an
// error. The first stanza is to provide a more useful error
// description
// including the set of components using the missing component.
//
if (!cd.parents.isEmpty()) {
StringBuilder sb = new StringBuilder();
Location handy = null;
for (Definition parent : cd.parents) {
handy = parent.getLocation();
if (sb.length() != 0) {
sb.append(", ");
}
sb.append(parent.getDescriptor().toString());
}
throw new DefinitionNotFoundException(descriptor, handy, sb.toString());
}
throw new DefinitionNotFoundException(descriptor);
}
}
//
// Ok. We have a def. let's figure out what to do with it.
//
@SuppressWarnings("unchecked")
DefDescriptor<D> canonical = (DefDescriptor<D>) def.getDescriptor();
Set<DefDescriptor<?>> newDeps = Sets.newHashSet();
//
// Make sure all of our fields are correct in our compiling def.
//
cd.def = def;
cd.descriptor = canonical;
cd.registry = registry;
if (!def.isValid()) {
//
// If our def is not 'valid', we must have built it, which means we
// need
// to validate. There is a subtle race condition here where more
// than one
// thread can grab a def from a registry, and they may all validate.
//
cd.built = true;
if (cd.registry == null) {
cd.registry = getRegistryFor(descriptor);
}
cc.loggingService.incrementNum(LoggingService.DEF_COUNT);
// FIXME: setting the current namespace on the context seems
// extremely hackish
cc.context.setCurrentNamespace(canonical.getNamespace());
def.validateDefinition();
}
//
// Store the def locally.
//
defs.put(canonical, def);
def.appendDependencies(newDeps);
//
// FIXME: this code will go away with preloads.
// This pulls in the context preloads. not pretty, but it works.
//
if (!cc.addedPreloads && (canonical.getDefType().equals(DefType.APPLICATION)
|| canonical.equals(cc.context.getApplicationDescriptor()))) {
cc.addedPreloads = true;
Set<String> preloads = cc.context.getPreloads();
for (String preload : preloads) {
if (!preload.contains("_")) {
DependencyDefImpl.Builder ddb = new DependencyDefImpl.Builder();
ddb.setResource(preload);
ddb.setType("APPLICATION,COMPONENT,STYLE,EVENT");
ddb.build().appendDependencies(newDeps);
}
}
}
for (DefDescriptor<?> dep : newDeps) {
if (!defs.containsKey(dep)) {
CompilingDef<?> depcd = cc.getCompiling(dep);
depcd.parents.add(def);
}
}
deps.addAll(newDeps);
cc.dependencies.put(canonical, def);
return def;
}
|
diff --git a/Android/src/org/libsdl/app/SDLActivity.java b/Android/src/org/libsdl/app/SDLActivity.java
index e1a8d7f7..683dd690 100644
--- a/Android/src/org/libsdl/app/SDLActivity.java
+++ b/Android/src/org/libsdl/app/SDLActivity.java
@@ -1,593 +1,593 @@
// Modified by Lasse ��rni for Urho3D
package org.libsdl.app;
import javax.microedition.khronos.egl.EGL10;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.egl.EGLContext;
import javax.microedition.khronos.opengles.GL10;
import javax.microedition.khronos.egl.*;
import android.app.*;
import android.content.*;
import android.view.*;
import android.os.*;
import android.util.Log;
import android.graphics.*;
import android.text.method.*;
import android.text.*;
import android.media.*;
import android.hardware.*;
import android.content.*;
import java.lang.*;
/**
SDL Activity
*/
public class SDLActivity extends Activity {
// Main components
private static SDLActivity mSingleton;
private static SDLSurface mSurface;
// This is what SDL runs in. It invokes SDL_main(), eventually
private static Thread mSDLThread;
// Audio
private static Thread mAudioThread;
private static AudioTrack mAudioTrack;
// EGL private objects
private EGLContext mEGLContext;
private EGLSurface mEGLSurface;
private EGLDisplay mEGLDisplay;
private EGLConfig mEGLConfig;
private int mGLMajor, mGLMinor;
private boolean mFinished = false;
// Load the .so
static {
System.loadLibrary("Urho3D");
}
// Setup
protected void onCreate(Bundle savedInstanceState) {
//Log.v("SDL", "onCreate()");
super.onCreate(savedInstanceState);
// So we can call stuff from static callbacks
mSingleton = this;
// Set up the surface
mSurface = new SDLSurface(getApplication());
setContentView(mSurface);
SurfaceHolder holder = mSurface.getHolder();
}
// Events
protected void onPause() {
Log.v("SDL", "onPause()");
super.onPause();
SDLActivity.nativePause();
}
protected void onResume() {
Log.v("SDL", "onResume()");
super.onResume();
SDLActivity.nativeResume();
}
protected void onDestroy() {
super.onDestroy();
Log.v("SDL", "onDestroy()");
mFinished = true;
// Send a quit message to the application
SDLActivity.nativeQuit();
// Now wait for the SDL thread to quit
if (mSDLThread != null) {
try {
mSDLThread.join();
} catch(Exception e) {
Log.v("SDL", "Problem stopping thread: " + e);
}
mSDLThread = null;
//Log.v("SDL", "Finished waiting for SDL thread");
}
mSingleton = null;
}
// Messages from the SDLMain thread
static int COMMAND_CHANGE_TITLE = 1;
static int COMMAND_FINISH = 2;
// Handler for the messages
Handler commandHandler = new Handler() {
public void handleMessage(Message msg) {
if (msg.arg1 == COMMAND_CHANGE_TITLE) {
setTitle((String)msg.obj);
}
if (msg.arg1 == COMMAND_FINISH) {
if (mFinished == false) {
mFinished = true;
finish();
}
}
}
};
// Send a message from the SDLMain thread
void sendCommand(int command, Object data) {
Message msg = commandHandler.obtainMessage();
msg.arg1 = command;
msg.obj = data;
commandHandler.sendMessage(msg);
}
// C functions we call
public static native void nativeInit();
public static native void nativeQuit();
public static native void nativePause();
public static native void nativeResume();
public static native void onNativeResize(int x, int y, int format);
public static native void onNativeKeyDown(int keycode);
public static native void onNativeKeyUp(int keycode);
public static native void onNativeTouch(int touchDevId, int pointerFingerId,
int action, float x,
float y, float p);
public static native void onNativeAccel(float x, float y, float z);
public static native void nativeRunAudioThread();
// Java functions called from C
public static boolean createGLContext(int majorVersion, int minorVersion) {
return initEGL(majorVersion, minorVersion);
}
public static void flipBuffers() {
flipEGL();
}
public static void setActivityTitle(String title) {
// Called from SDLMain() thread and can't directly affect the view
mSingleton.sendCommand(COMMAND_CHANGE_TITLE, title);
}
public static void finishActivity() {
mSingleton.sendCommand(COMMAND_FINISH, null);
}
public static Context getContext() {
return mSingleton;
}
public static void startApp() {
// Start up the C app thread
if (mSDLThread == null) {
mSDLThread = new Thread(new SDLMain(), "SDLThread");
mSDLThread.start();
}
else {
SDLActivity.nativeResume();
}
}
// EGL functions
public static boolean initEGL(int majorVersion, int minorVersion) {
if (SDLActivity.mSingleton.mEGLDisplay == null) {
//Log.v("SDL", "Starting up OpenGL ES " + majorVersion + "." + minorVersion);
try {
EGL10 egl = (EGL10)EGLContext.getEGL();
EGLDisplay dpy = egl.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY);
int[] version = new int[2];
egl.eglInitialize(dpy, version);
int EGL_OPENGL_ES_BIT = 1;
int EGL_OPENGL_ES2_BIT = 4;
int renderableType = 0;
if (majorVersion == 2) {
renderableType = EGL_OPENGL_ES2_BIT;
} else if (majorVersion == 1) {
renderableType = EGL_OPENGL_ES_BIT;
}
int[] configSpec = {
- //EGL10.EGL_DEPTH_SIZE, 16,
+ EGL10.EGL_DEPTH_SIZE, 16,
EGL10.EGL_RENDERABLE_TYPE, renderableType,
EGL10.EGL_NONE
};
EGLConfig[] configs = new EGLConfig[1];
int[] num_config = new int[1];
if (!egl.eglChooseConfig(dpy, configSpec, configs, 1, num_config) || num_config[0] == 0) {
Log.e("SDL", "No EGL config available");
return false;
}
EGLConfig config = configs[0];
/*int EGL_CONTEXT_CLIENT_VERSION=0x3098;
int contextAttrs[] = new int[] { EGL_CONTEXT_CLIENT_VERSION, majorVersion, EGL10.EGL_NONE };
EGLContext ctx = egl.eglCreateContext(dpy, config, EGL10.EGL_NO_CONTEXT, contextAttrs);
if (ctx == EGL10.EGL_NO_CONTEXT) {
Log.e("SDL", "Couldn't create context");
return false;
}
SDLActivity.mEGLContext = ctx;*/
SDLActivity.mSingleton.mEGLDisplay = dpy;
SDLActivity.mSingleton.mEGLConfig = config;
SDLActivity.mSingleton.mGLMajor = majorVersion;
SDLActivity.mSingleton.mGLMinor = minorVersion;
SDLActivity.createEGLSurface();
} catch(Exception e) {
Log.v("SDL", e + "");
for (StackTraceElement s : e.getStackTrace()) {
Log.v("SDL", s.toString());
}
}
}
else SDLActivity.createEGLSurface();
return true;
}
public static boolean createEGLContext() {
EGL10 egl = (EGL10)EGLContext.getEGL();
int EGL_CONTEXT_CLIENT_VERSION=0x3098;
int contextAttrs[] = new int[] { EGL_CONTEXT_CLIENT_VERSION, SDLActivity.mSingleton.mGLMajor, EGL10.EGL_NONE };
SDLActivity.mSingleton.mEGLContext = egl.eglCreateContext(SDLActivity.mSingleton.mEGLDisplay, SDLActivity.mSingleton.mEGLConfig, EGL10.EGL_NO_CONTEXT, contextAttrs);
if (SDLActivity.mSingleton.mEGLContext == EGL10.EGL_NO_CONTEXT) {
Log.e("SDL", "Couldn't create context");
return false;
}
return true;
}
public static boolean createEGLSurface() {
if (SDLActivity.mSingleton.mEGLDisplay != null && SDLActivity.mSingleton.mEGLConfig != null) {
EGL10 egl = (EGL10)EGLContext.getEGL();
if (SDLActivity.mSingleton.mEGLContext == null) createEGLContext();
Log.v("SDL", "Creating new EGL Surface");
EGLSurface surface = egl.eglCreateWindowSurface(SDLActivity.mSingleton.mEGLDisplay, SDLActivity.mSingleton.mEGLConfig, SDLActivity.mSingleton.mSurface, null);
if (surface == EGL10.EGL_NO_SURFACE) {
Log.e("SDL", "Couldn't create surface");
return false;
}
if (!egl.eglMakeCurrent(SDLActivity.mSingleton.mEGLDisplay, surface, surface, SDLActivity.mSingleton.mEGLContext)) {
Log.e("SDL", "Old EGL Context doesnt work, trying with a new one");
createEGLContext();
if (!egl.eglMakeCurrent(SDLActivity.mSingleton.mEGLDisplay, surface, surface, SDLActivity.mSingleton.mEGLContext)) {
Log.e("SDL", "Failed making EGL Context current");
return false;
}
}
SDLActivity.mSingleton.mEGLSurface = surface;
return true;
}
return false;
}
// EGL buffer flip
public static void flipEGL() {
try {
EGL10 egl = (EGL10)EGLContext.getEGL();
egl.eglWaitNative(EGL10.EGL_CORE_NATIVE_ENGINE, null);
// drawing here
egl.eglWaitGL();
egl.eglSwapBuffers(SDLActivity.mSingleton.mEGLDisplay, SDLActivity.mSingleton.mEGLSurface);
} catch(Exception e) {
Log.v("SDL", "flipEGL(): " + e);
for (StackTraceElement s : e.getStackTrace()) {
Log.v("SDL", s.toString());
}
}
}
// Audio
private static Object buf;
public static Object audioInit(int sampleRate, boolean is16Bit, boolean isStereo, int desiredFrames) {
int channelConfig = isStereo ? AudioFormat.CHANNEL_CONFIGURATION_STEREO : AudioFormat.CHANNEL_CONFIGURATION_MONO;
int audioFormat = is16Bit ? AudioFormat.ENCODING_PCM_16BIT : AudioFormat.ENCODING_PCM_8BIT;
int frameSize = (isStereo ? 2 : 1) * (is16Bit ? 2 : 1);
Log.v("SDL", "SDL audio: wanted " + (isStereo ? "stereo" : "mono") + " " + (is16Bit ? "16-bit" : "8-bit") + " " + ((float)sampleRate / 1000f) + "kHz, " + desiredFrames + " frames buffer");
// Let the user pick a larger buffer if they really want -- but ye
// gods they probably shouldn't, the minimums are horrifyingly high
// latency already
desiredFrames = Math.max(desiredFrames, (AudioTrack.getMinBufferSize(sampleRate, channelConfig, audioFormat) + frameSize - 1) / frameSize);
mAudioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, sampleRate,
channelConfig, audioFormat, desiredFrames * frameSize, AudioTrack.MODE_STREAM);
audioStartThread();
Log.v("SDL", "SDL audio: got " + ((mAudioTrack.getChannelCount() >= 2) ? "stereo" : "mono") + " " + ((mAudioTrack.getAudioFormat() == AudioFormat.ENCODING_PCM_16BIT) ? "16-bit" : "8-bit") + " " + ((float)mAudioTrack.getSampleRate() / 1000f) + "kHz, " + desiredFrames + " frames buffer");
if (is16Bit) {
buf = new short[desiredFrames * (isStereo ? 2 : 1)];
} else {
buf = new byte[desiredFrames * (isStereo ? 2 : 1)];
}
return buf;
}
public static void audioStartThread() {
mAudioThread = new Thread(new Runnable() {
public void run() {
mAudioTrack.play();
nativeRunAudioThread();
}
});
// I'd take REALTIME if I could get it!
mAudioThread.setPriority(Thread.MAX_PRIORITY);
mAudioThread.start();
}
public static void audioWriteShortBuffer(short[] buffer) {
for (int i = 0; i < buffer.length; ) {
int result = mAudioTrack.write(buffer, i, buffer.length - i);
if (result > 0) {
i += result;
} else if (result == 0) {
try {
Thread.sleep(1);
} catch(InterruptedException e) {
// Nom nom
}
} else {
Log.w("SDL", "SDL audio: error return from write(short)");
return;
}
}
}
public static void audioWriteByteBuffer(byte[] buffer) {
for (int i = 0; i < buffer.length; ) {
int result = mAudioTrack.write(buffer, i, buffer.length - i);
if (result > 0) {
i += result;
} else if (result == 0) {
try {
Thread.sleep(1);
} catch(InterruptedException e) {
// Nom nom
}
} else {
Log.w("SDL", "SDL audio: error return from write(short)");
return;
}
}
}
public static void audioQuit() {
if (mAudioThread != null) {
try {
mAudioThread.join();
} catch(Exception e) {
Log.v("SDL", "Problem stopping audio thread: " + e);
}
mAudioThread = null;
//Log.v("SDL", "Finished waiting for audio thread");
}
if (mAudioTrack != null) {
mAudioTrack.stop();
mAudioTrack = null;
}
}
}
/**
Simple nativeInit() runnable
*/
class SDLMain implements Runnable {
public void run() {
// Runs SDL_main()
SDLActivity.nativeInit();
//Log.v("SDL", "SDL thread terminated");
SDLActivity.finishActivity();
}
}
/**
SDLSurface. This is what we draw on, so we need to know when it's created
in order to do anything useful.
Because of this, that's where we set up the SDL thread
*/
class SDLSurface extends SurfaceView implements SurfaceHolder.Callback,
View.OnKeyListener, View.OnTouchListener, SensorEventListener {
// Sensors
private static SensorManager mSensorManager;
// Startup
public SDLSurface(Context context) {
super(context);
getHolder().addCallback(this);
setFocusable(true);
setFocusableInTouchMode(true);
requestFocus();
setOnKeyListener(this);
setOnTouchListener(this);
mSensorManager = (SensorManager)context.getSystemService("sensor");
}
// Called when we have a valid drawing surface
public void surfaceCreated(SurfaceHolder holder) {
Log.v("SDL", "surfaceCreated()");
holder.setType(SurfaceHolder.SURFACE_TYPE_GPU);
SDLActivity.createEGLSurface();
enableSensor(Sensor.TYPE_ACCELEROMETER, true);
}
// Called when we lose the surface
public void surfaceDestroyed(SurfaceHolder holder) {
Log.v("SDL", "surfaceDestroyed()");
SDLActivity.nativePause();
enableSensor(Sensor.TYPE_ACCELEROMETER, false);
}
// Called when the surface is resized
public void surfaceChanged(SurfaceHolder holder,
int format, int width, int height) {
Log.v("SDL", "surfaceChanged()");
int sdlFormat = 0x85151002; // SDL_PIXELFORMAT_RGB565 by default
switch (format) {
case PixelFormat.A_8:
Log.v("SDL", "pixel format A_8");
break;
case PixelFormat.LA_88:
Log.v("SDL", "pixel format LA_88");
break;
case PixelFormat.L_8:
Log.v("SDL", "pixel format L_8");
break;
case PixelFormat.RGBA_4444:
Log.v("SDL", "pixel format RGBA_4444");
sdlFormat = 0x85421002; // SDL_PIXELFORMAT_RGBA4444
break;
case PixelFormat.RGBA_5551:
Log.v("SDL", "pixel format RGBA_5551");
sdlFormat = 0x85441002; // SDL_PIXELFORMAT_RGBA5551
break;
case PixelFormat.RGBA_8888:
Log.v("SDL", "pixel format RGBA_8888");
sdlFormat = 0x86462004; // SDL_PIXELFORMAT_RGBA8888
break;
case PixelFormat.RGBX_8888:
Log.v("SDL", "pixel format RGBX_8888");
sdlFormat = 0x86262004; // SDL_PIXELFORMAT_RGBX8888
break;
case PixelFormat.RGB_332:
Log.v("SDL", "pixel format RGB_332");
sdlFormat = 0x84110801; // SDL_PIXELFORMAT_RGB332
break;
case PixelFormat.RGB_565:
Log.v("SDL", "pixel format RGB_565");
sdlFormat = 0x85151002; // SDL_PIXELFORMAT_RGB565
break;
case PixelFormat.RGB_888:
Log.v("SDL", "pixel format RGB_888");
// Not sure this is right, maybe SDL_PIXELFORMAT_RGB24 instead?
sdlFormat = 0x86161804; // SDL_PIXELFORMAT_RGB888
break;
default:
Log.v("SDL", "pixel format unknown " + format);
break;
}
SDLActivity.onNativeResize(width, height, sdlFormat);
Log.v("SDL", "Window size:" + width + "x"+height);
SDLActivity.startApp();
}
// unused
public void onDraw(Canvas canvas) {}
// Key events
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
//Log.v("SDL", "key down: " + keyCode);
SDLActivity.onNativeKeyDown(keyCode);
return true;
}
else if (event.getAction() == KeyEvent.ACTION_UP) {
//Log.v("SDL", "key up: " + keyCode);
SDLActivity.onNativeKeyUp(keyCode);
return true;
}
return false;
}
// Touch events
public boolean onTouch(View v, MotionEvent event) {
{
final int touchDevId = event.getDeviceId();
final int pointerCount = event.getPointerCount();
// touchId, pointerId, action, x, y, pressure
int actionPointerIndex = event.getActionIndex();
int pointerFingerId = event.getPointerId(actionPointerIndex);
int action = event.getActionMasked();
float x = event.getX(actionPointerIndex);
float y = event.getY(actionPointerIndex);
float p = event.getPressure(actionPointerIndex);
if (action == MotionEvent.ACTION_MOVE && pointerCount > 1) {
// TODO send motion to every pointer if its position has
// changed since prev event.
for (int i = 0; i < pointerCount; i++) {
pointerFingerId = event.getPointerId(i);
x = event.getX(i);
y = event.getY(i);
p = event.getPressure(i);
SDLActivity.onNativeTouch(touchDevId, pointerFingerId, action, x, y, p);
}
} else {
SDLActivity.onNativeTouch(touchDevId, pointerFingerId, action, x, y, p);
}
}
return true;
}
// Sensor events
public void enableSensor(int sensortype, boolean enabled) {
// TODO: This uses getDefaultSensor - what if we have >1 accels?
if (enabled) {
mSensorManager.registerListener(this,
mSensorManager.getDefaultSensor(sensortype),
SensorManager.SENSOR_DELAY_GAME, null);
} else {
mSensorManager.unregisterListener(this,
mSensorManager.getDefaultSensor(sensortype));
}
}
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO
}
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
SDLActivity.onNativeAccel(event.values[0] / SensorManager.GRAVITY_EARTH,
event.values[1] / SensorManager.GRAVITY_EARTH,
event.values[2] / SensorManager.GRAVITY_EARTH);
}
}
}
| true | true | public static boolean initEGL(int majorVersion, int minorVersion) {
if (SDLActivity.mSingleton.mEGLDisplay == null) {
//Log.v("SDL", "Starting up OpenGL ES " + majorVersion + "." + minorVersion);
try {
EGL10 egl = (EGL10)EGLContext.getEGL();
EGLDisplay dpy = egl.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY);
int[] version = new int[2];
egl.eglInitialize(dpy, version);
int EGL_OPENGL_ES_BIT = 1;
int EGL_OPENGL_ES2_BIT = 4;
int renderableType = 0;
if (majorVersion == 2) {
renderableType = EGL_OPENGL_ES2_BIT;
} else if (majorVersion == 1) {
renderableType = EGL_OPENGL_ES_BIT;
}
int[] configSpec = {
//EGL10.EGL_DEPTH_SIZE, 16,
EGL10.EGL_RENDERABLE_TYPE, renderableType,
EGL10.EGL_NONE
};
EGLConfig[] configs = new EGLConfig[1];
int[] num_config = new int[1];
if (!egl.eglChooseConfig(dpy, configSpec, configs, 1, num_config) || num_config[0] == 0) {
Log.e("SDL", "No EGL config available");
return false;
}
EGLConfig config = configs[0];
/*int EGL_CONTEXT_CLIENT_VERSION=0x3098;
int contextAttrs[] = new int[] { EGL_CONTEXT_CLIENT_VERSION, majorVersion, EGL10.EGL_NONE };
EGLContext ctx = egl.eglCreateContext(dpy, config, EGL10.EGL_NO_CONTEXT, contextAttrs);
if (ctx == EGL10.EGL_NO_CONTEXT) {
Log.e("SDL", "Couldn't create context");
return false;
}
SDLActivity.mEGLContext = ctx;*/
SDLActivity.mSingleton.mEGLDisplay = dpy;
SDLActivity.mSingleton.mEGLConfig = config;
SDLActivity.mSingleton.mGLMajor = majorVersion;
SDLActivity.mSingleton.mGLMinor = minorVersion;
SDLActivity.createEGLSurface();
} catch(Exception e) {
Log.v("SDL", e + "");
for (StackTraceElement s : e.getStackTrace()) {
Log.v("SDL", s.toString());
}
}
}
else SDLActivity.createEGLSurface();
return true;
}
| public static boolean initEGL(int majorVersion, int minorVersion) {
if (SDLActivity.mSingleton.mEGLDisplay == null) {
//Log.v("SDL", "Starting up OpenGL ES " + majorVersion + "." + minorVersion);
try {
EGL10 egl = (EGL10)EGLContext.getEGL();
EGLDisplay dpy = egl.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY);
int[] version = new int[2];
egl.eglInitialize(dpy, version);
int EGL_OPENGL_ES_BIT = 1;
int EGL_OPENGL_ES2_BIT = 4;
int renderableType = 0;
if (majorVersion == 2) {
renderableType = EGL_OPENGL_ES2_BIT;
} else if (majorVersion == 1) {
renderableType = EGL_OPENGL_ES_BIT;
}
int[] configSpec = {
EGL10.EGL_DEPTH_SIZE, 16,
EGL10.EGL_RENDERABLE_TYPE, renderableType,
EGL10.EGL_NONE
};
EGLConfig[] configs = new EGLConfig[1];
int[] num_config = new int[1];
if (!egl.eglChooseConfig(dpy, configSpec, configs, 1, num_config) || num_config[0] == 0) {
Log.e("SDL", "No EGL config available");
return false;
}
EGLConfig config = configs[0];
/*int EGL_CONTEXT_CLIENT_VERSION=0x3098;
int contextAttrs[] = new int[] { EGL_CONTEXT_CLIENT_VERSION, majorVersion, EGL10.EGL_NONE };
EGLContext ctx = egl.eglCreateContext(dpy, config, EGL10.EGL_NO_CONTEXT, contextAttrs);
if (ctx == EGL10.EGL_NO_CONTEXT) {
Log.e("SDL", "Couldn't create context");
return false;
}
SDLActivity.mEGLContext = ctx;*/
SDLActivity.mSingleton.mEGLDisplay = dpy;
SDLActivity.mSingleton.mEGLConfig = config;
SDLActivity.mSingleton.mGLMajor = majorVersion;
SDLActivity.mSingleton.mGLMinor = minorVersion;
SDLActivity.createEGLSurface();
} catch(Exception e) {
Log.v("SDL", e + "");
for (StackTraceElement s : e.getStackTrace()) {
Log.v("SDL", s.toString());
}
}
}
else SDLActivity.createEGLSurface();
return true;
}
|
diff --git a/jsf/plugins/org.eclipse.jst.jsf.core/src/org/eclipse/jst/jsf/core/jsfappconfig/ImplicitRuntimeJSFAppConfigProvider.java b/jsf/plugins/org.eclipse.jst.jsf.core/src/org/eclipse/jst/jsf/core/jsfappconfig/ImplicitRuntimeJSFAppConfigProvider.java
index 6100eb329..e86f0e229 100644
--- a/jsf/plugins/org.eclipse.jst.jsf.core/src/org/eclipse/jst/jsf/core/jsfappconfig/ImplicitRuntimeJSFAppConfigProvider.java
+++ b/jsf/plugins/org.eclipse.jst.jsf.core/src/org/eclipse/jst/jsf/core/jsfappconfig/ImplicitRuntimeJSFAppConfigProvider.java
@@ -1,295 +1,300 @@
/*******************************************************************************
* Copyright (c) 2005 Oracle Corporation.
* 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:
* Ian Trimble - initial API and implementation
*******************************************************************************/
package org.eclipse.jst.jsf.core.jsfappconfig;
import org.eclipse.emf.common.util.EList;
import org.eclipse.jst.jsf.facesconfig.emf.ComponentClassType;
import org.eclipse.jst.jsf.facesconfig.emf.ComponentType;
import org.eclipse.jst.jsf.facesconfig.emf.ComponentTypeType;
import org.eclipse.jst.jsf.facesconfig.emf.ConverterClassType;
import org.eclipse.jst.jsf.facesconfig.emf.ConverterForClassType;
import org.eclipse.jst.jsf.facesconfig.emf.ConverterIdType;
import org.eclipse.jst.jsf.facesconfig.emf.ConverterType;
import org.eclipse.jst.jsf.facesconfig.emf.FacesConfigFactory;
import org.eclipse.jst.jsf.facesconfig.emf.FacesConfigType;
import org.eclipse.jst.jsf.facesconfig.emf.ValidatorClassType;
import org.eclipse.jst.jsf.facesconfig.emf.ValidatorIdType;
import org.eclipse.jst.jsf.facesconfig.emf.ValidatorType;
/**
* ImplicitRuntimeJSFAppConfigProvider provides an application configuration
* model that contains implicit configuration objects provided by a JSF
* implementation at runtime.
*
* <p><b>Provisional API - subject to change</b></p>
*
* @author Ian Trimble - Oracle
*/
public class ImplicitRuntimeJSFAppConfigProvider extends AbstractJSFAppConfigProvider {
/**
* Cached {@link FacesConfigType} instance.
*/
protected FacesConfigType facesConfig = null;
/* (non-Javadoc)
* @see org.eclipse.jst.jsf.core.jsfappconfig.IJSFAppConfigProvider#getFacesConfigModel()
*/
public FacesConfigType getFacesConfigModel() {
if (facesConfig == null) {
createModel();
if (facesConfig != null) {
jsfAppConfigLocater.getJSFAppConfigManager().addFacesConfigChangeAdapter(facesConfig);
}
}
return facesConfig;
}
/* (non-Javadoc)
* @see org.eclipse.jst.jsf.core.jsfappconfig.IJSFAppConfigProvider#releaseFacesConfigModel()
*/
public void releaseFacesConfigModel() {
jsfAppConfigLocater.getJSFAppConfigManager().removeFacesConfigChangeAdapter(facesConfig);
facesConfig = null;
}
/**
* Creates the application configuration model and assigns it to the
* facesConfig property.
*/
protected void createModel() {
facesConfig = FacesConfigFactory.eINSTANCE.createFacesConfigType();
//create and add converters by id
EList converters = facesConfig.getConverter();
converters.add(createConverter("BigDecimal")); //$NON-NLS-1$
converters.add(createConverter("BigInteger")); //$NON-NLS-1$
converters.add(createConverter("Boolean")); //$NON-NLS-1$
converters.add(createConverter("Byte")); //$NON-NLS-1$
converters.add(createConverter("Character")); //$NON-NLS-1$
converters.add(createConverter("DateTime")); //$NON-NLS-1$
converters.add(createConverter("Double")); //$NON-NLS-1$
converters.add(createConverter("Float")); //$NON-NLS-1$
converters.add(createConverter("Integer")); //$NON-NLS-1$
converters.add(createConverter("Long")); //$NON-NLS-1$
converters.add(createConverter("Number")); //$NON-NLS-1$
converters.add(createConverter("Short")); //$NON-NLS-1$
+ converters.add(createConverter("Enum")); //$NON-NLS-1$
// converters by for-class (see spec 3.3.3 -- Standard Converter Implementions
converters.add(createForClassConverter("java.lang.Boolean", "javax.faces.convert.BooleanConverter")); //$NON-NLS-1$ //$NON-NLS-2$
converters.add(createForClassConverter("java.lang.Byte", "javax.faces.convert.ByteConverter")); //$NON-NLS-1$ //$NON-NLS-2$
converters.add(createForClassConverter("java.lang.Character", "javax.faces.convert.CharacterConverter")); //$NON-NLS-1$ //$NON-NLS-2$
converters.add(createForClassConverter("java.lang.Double", "javax.faces.convert.DoubleConverter")); //$NON-NLS-1$ //$NON-NLS-2$
converters.add(createForClassConverter("java.lang.Float", "javax.faces.convert.FloatConverter")); //$NON-NLS-1$ //$NON-NLS-2$
converters.add(createForClassConverter("java.lang.Integer", "javax.faces.convert.IntegerConverter")); //$NON-NLS-1$ //$NON-NLS-2$
converters.add(createForClassConverter("java.lang.Long", "javax.faces.convert.LongConverter")); //$NON-NLS-1$ //$NON-NLS-2$
converters.add(createForClassConverter("java.lang.Short", "javax.faces.converter.ShortConverter")); //$NON-NLS-1$ //$NON-NLS-2$
+ converters.add(createForClassConverter("java.lang.Enum", "javax.faces.converter.EnumConverter")); //$NON-NLS-1$ //$NON-NLS-2$
//create and add validators
EList validators = facesConfig.getValidator();
validators.add(createValidator("DoubleRange")); //$NON-NLS-1$
validators.add(createValidator("Length")); //$NON-NLS-1$
validators.add(createValidator("LongRange")); //$NON-NLS-1$
+ validators.add(createValidator("Bean")); //$NON-NLS-1$
+ validators.add(createValidator("RegularExpression")); //$NON-NLS-1$
+ validators.add(createValidator("Required")); //$NON-NLS-1$
//create and add UI components
EList components = facesConfig.getComponent();
components.add(createUIComponent("Column")); //$NON-NLS-1$
components.add(createUIComponent("Command")); //$NON-NLS-1$
components.add(createUIComponent("Data")); //$NON-NLS-1$
components.add(createUIComponent("Form")); //$NON-NLS-1$
components.add(createUIComponent("Graphic")); //$NON-NLS-1$
components.add(createUIComponent("Input")); //$NON-NLS-1$
components.add(createUIComponent("Message")); //$NON-NLS-1$
components.add(createUIComponent("Messages")); //$NON-NLS-1$
components.add(createUIComponent("NamingContainer")); //$NON-NLS-1$
components.add(createUIComponent("Output")); //$NON-NLS-1$
components.add(createUIComponent("Panel")); //$NON-NLS-1$
components.add(createUIComponent("Parameter")); //$NON-NLS-1$
components.add(createUIComponent("SelectBoolean")); //$NON-NLS-1$
components.add(createUIComponent("SelectItem")); //$NON-NLS-1$
components.add(createUIComponent("SelectItems")); //$NON-NLS-1$
components.add(createUIComponent("SelectMany")); //$NON-NLS-1$
components.add(createUIComponent("SelectOne")); //$NON-NLS-1$
components.add(createUIComponent("ViewRoot")); //$NON-NLS-1$
//create and add HTML components
components.add(createHTMLComponent("HtmlCommandButton")); //$NON-NLS-1$
components.add(createHTMLComponent("HtmlCommandLink")); //$NON-NLS-1$
components.add(createHTMLComponent("HtmlDataTable")); //$NON-NLS-1$
components.add(createHTMLComponent("HtmlForm")); //$NON-NLS-1$
components.add(createHTMLComponent("HtmlGraphicImage")); //$NON-NLS-1$
components.add(createHTMLComponent("HtmlInputHidden")); //$NON-NLS-1$
components.add(createHTMLComponent("HtmlInputSecret")); //$NON-NLS-1$
components.add(createHTMLComponent("HtmlInputText")); //$NON-NLS-1$
components.add(createHTMLComponent("HtmlInputTextarea")); //$NON-NLS-1$
components.add(createHTMLComponent("HtmlMessage")); //$NON-NLS-1$
components.add(createHTMLComponent("HtmlMessages")); //$NON-NLS-1$
components.add(createHTMLComponent("HtmlOutputFormat")); //$NON-NLS-1$
components.add(createHTMLComponent("HtmlOutputLabel")); //$NON-NLS-1$
components.add(createHTMLComponent("HtmlOutputLink")); //$NON-NLS-1$
components.add(createHTMLComponent("HtmlOutputText")); //$NON-NLS-1$
components.add(createHTMLComponent("HtmlPanelGrid")); //$NON-NLS-1$
components.add(createHTMLComponent("HtmlPanelGroup")); //$NON-NLS-1$
components.add(createHTMLComponent("HtmlSelectBooleanCheckbox")); //$NON-NLS-1$
components.add(createHTMLComponent("HtmlSelectManyCheckbox")); //$NON-NLS-1$
components.add(createHTMLComponent("HtmlSelectManyListbox")); //$NON-NLS-1$
components.add(createHTMLComponent("HtmlSelectManyMenu")); //$NON-NLS-1$
components.add(createHTMLComponent("HtmlSelectOneListbox")); //$NON-NLS-1$
components.add(createHTMLComponent("HtmlSelectOneMenu")); //$NON-NLS-1$
components.add(createHTMLComponent("HtmlSelectOneRadio")); //$NON-NLS-1$
}
/**
* Creates a {@link ConverterType} instance.
*
* @param name Base name of converter from which converter-id and
* converter-class are formed.
* @return {@link ConverterType} instance.
*/
protected ConverterType createConverter(String name) {
ConverterType converterType = FacesConfigFactory.eINSTANCE.createConverterType();
//set converter-id
ConverterIdType converterIdType = FacesConfigFactory.eINSTANCE.createConverterIdType();
StringBuffer sb = new StringBuffer();
sb.append("javax.faces."); //$NON-NLS-1$
sb.append(name);
converterIdType.setTextContent(sb.toString());
converterType.setConverterId(converterIdType);
//set converter-class
ConverterClassType converterClassType = FacesConfigFactory.eINSTANCE.createConverterClassType();
sb = new StringBuffer();
sb.append("javax.faces.convert."); //$NON-NLS-1$
sb.append(name);
sb.append("Converter"); //$NON-NLS-1$
converterClassType.setTextContent(sb.toString());
converterType.setConverterClass(converterClassType);
return converterType;
}
private ConverterType createForClassConverter(String forClass, String converterClass)
{
ConverterType converterType = FacesConfigFactory.eINSTANCE.createConverterType();
//set converter-id
ConverterForClassType converterForClass = FacesConfigFactory.eINSTANCE.createConverterForClassType();
converterForClass.setTextContent(forClass);
converterType.setConverterForClass(converterForClass);
//set converter-class
ConverterClassType converterClassType = FacesConfigFactory.eINSTANCE.createConverterClassType();
converterClassType.setTextContent(converterClass);
converterType.setConverterClass(converterClassType);
return converterType;
}
/**
* Creates a {@link ValidatorType} instance.
*
* @param name Base name of validator from which validator-id and
* validator-class are formed.
* @return {@link ValidatorType} instance.
*/
protected ValidatorType createValidator(String name) {
ValidatorType validatorType = FacesConfigFactory.eINSTANCE.createValidatorType();
//set validator-id
ValidatorIdType validatorIdType = FacesConfigFactory.eINSTANCE.createValidatorIdType();
StringBuffer sb = new StringBuffer();
sb.append("javax.faces."); //$NON-NLS-1$
sb.append(name);
validatorIdType.setTextContent(sb.toString());
validatorType.setValidatorId(validatorIdType);
//set validator-class
ValidatorClassType validatorClassType = FacesConfigFactory.eINSTANCE.createValidatorClassType();
sb = new StringBuffer();
sb.append("javax.faces.validator."); //$NON-NLS-1$
sb.append(name);
sb.append("Validator"); //$NON-NLS-1$
validatorClassType.setTextContent(sb.toString());
validatorType.setValidatorClass(validatorClassType);
return validatorType;
}
/**
* Creates a {@link ComponentType} instance to represent a standard UI
* component.
*
* @param name Base name of component from which component-type and
* component-class are formed.
* @return {@link ComponentType} instance.
*/
protected ComponentType createUIComponent(String name) {
ComponentType componentType = FacesConfigFactory.eINSTANCE.createComponentType();
//set component-type
ComponentTypeType componentTypeType = FacesConfigFactory.eINSTANCE.createComponentTypeType();
StringBuffer sb = new StringBuffer();
sb.append("javax.faces."); //$NON-NLS-1$
sb.append(name);
componentTypeType.setTextContent(sb.toString());
componentType.setComponentType(componentTypeType);
//set component-class
ComponentClassType componentClassType = FacesConfigFactory.eINSTANCE.createComponentClassType();
sb = new StringBuffer();
sb.append("javax.faces.component.UI"); //$NON-NLS-1$
sb.append(name);
componentClassType.setTextContent(sb.toString());
componentType.setComponentClass(componentClassType);
return componentType;
}
/**
* Creates a {@link ComponentType} instance to represent a concrete HTML
* component.
*
* @param name Base name of component from which component-type and
* component-class are formed.
* @return {@link ComponentType} instance.
*/
protected ComponentType createHTMLComponent(String name) {
ComponentType componentType = FacesConfigFactory.eINSTANCE.createComponentType();
//set component-type
ComponentTypeType componentTypeType = FacesConfigFactory.eINSTANCE.createComponentTypeType();
StringBuffer sb = new StringBuffer();
sb.append("javax.faces."); //$NON-NLS-1$
sb.append(name);
componentTypeType.setTextContent(sb.toString());
componentType.setComponentType(componentTypeType);
//set component-class
ComponentClassType componentClassType = FacesConfigFactory.eINSTANCE.createComponentClassType();
sb = new StringBuffer();
sb.append("javax.faces.component.html."); //$NON-NLS-1$
sb.append(name);
componentClassType.setTextContent(sb.toString());
componentType.setComponentClass(componentClassType);
return componentType;
}
/*
* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
public boolean equals(Object otherObject) {
boolean equals = false;
if (otherObject instanceof ImplicitRuntimeJSFAppConfigProvider) {
equals = true;
}
return equals;
}
/*
* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
public int hashCode() {
return ImplicitRuntimeJSFAppConfigProvider.class.getName().hashCode();
}
/*
* (non-Javadoc)
* @see java.lang.Object#toString()
*/
public String toString() {
return "ImplicitRuntimeJSFAppConfigProvider[]"; //$NON-NLS-1$
}
}
| false | true | protected void createModel() {
facesConfig = FacesConfigFactory.eINSTANCE.createFacesConfigType();
//create and add converters by id
EList converters = facesConfig.getConverter();
converters.add(createConverter("BigDecimal")); //$NON-NLS-1$
converters.add(createConverter("BigInteger")); //$NON-NLS-1$
converters.add(createConverter("Boolean")); //$NON-NLS-1$
converters.add(createConverter("Byte")); //$NON-NLS-1$
converters.add(createConverter("Character")); //$NON-NLS-1$
converters.add(createConverter("DateTime")); //$NON-NLS-1$
converters.add(createConverter("Double")); //$NON-NLS-1$
converters.add(createConverter("Float")); //$NON-NLS-1$
converters.add(createConverter("Integer")); //$NON-NLS-1$
converters.add(createConverter("Long")); //$NON-NLS-1$
converters.add(createConverter("Number")); //$NON-NLS-1$
converters.add(createConverter("Short")); //$NON-NLS-1$
// converters by for-class (see spec 3.3.3 -- Standard Converter Implementions
converters.add(createForClassConverter("java.lang.Boolean", "javax.faces.convert.BooleanConverter")); //$NON-NLS-1$ //$NON-NLS-2$
converters.add(createForClassConverter("java.lang.Byte", "javax.faces.convert.ByteConverter")); //$NON-NLS-1$ //$NON-NLS-2$
converters.add(createForClassConverter("java.lang.Character", "javax.faces.convert.CharacterConverter")); //$NON-NLS-1$ //$NON-NLS-2$
converters.add(createForClassConverter("java.lang.Double", "javax.faces.convert.DoubleConverter")); //$NON-NLS-1$ //$NON-NLS-2$
converters.add(createForClassConverter("java.lang.Float", "javax.faces.convert.FloatConverter")); //$NON-NLS-1$ //$NON-NLS-2$
converters.add(createForClassConverter("java.lang.Integer", "javax.faces.convert.IntegerConverter")); //$NON-NLS-1$ //$NON-NLS-2$
converters.add(createForClassConverter("java.lang.Long", "javax.faces.convert.LongConverter")); //$NON-NLS-1$ //$NON-NLS-2$
converters.add(createForClassConverter("java.lang.Short", "javax.faces.converter.ShortConverter")); //$NON-NLS-1$ //$NON-NLS-2$
//create and add validators
EList validators = facesConfig.getValidator();
validators.add(createValidator("DoubleRange")); //$NON-NLS-1$
validators.add(createValidator("Length")); //$NON-NLS-1$
validators.add(createValidator("LongRange")); //$NON-NLS-1$
//create and add UI components
EList components = facesConfig.getComponent();
components.add(createUIComponent("Column")); //$NON-NLS-1$
components.add(createUIComponent("Command")); //$NON-NLS-1$
components.add(createUIComponent("Data")); //$NON-NLS-1$
components.add(createUIComponent("Form")); //$NON-NLS-1$
components.add(createUIComponent("Graphic")); //$NON-NLS-1$
components.add(createUIComponent("Input")); //$NON-NLS-1$
components.add(createUIComponent("Message")); //$NON-NLS-1$
components.add(createUIComponent("Messages")); //$NON-NLS-1$
components.add(createUIComponent("NamingContainer")); //$NON-NLS-1$
components.add(createUIComponent("Output")); //$NON-NLS-1$
components.add(createUIComponent("Panel")); //$NON-NLS-1$
components.add(createUIComponent("Parameter")); //$NON-NLS-1$
components.add(createUIComponent("SelectBoolean")); //$NON-NLS-1$
components.add(createUIComponent("SelectItem")); //$NON-NLS-1$
components.add(createUIComponent("SelectItems")); //$NON-NLS-1$
components.add(createUIComponent("SelectMany")); //$NON-NLS-1$
components.add(createUIComponent("SelectOne")); //$NON-NLS-1$
components.add(createUIComponent("ViewRoot")); //$NON-NLS-1$
//create and add HTML components
components.add(createHTMLComponent("HtmlCommandButton")); //$NON-NLS-1$
components.add(createHTMLComponent("HtmlCommandLink")); //$NON-NLS-1$
components.add(createHTMLComponent("HtmlDataTable")); //$NON-NLS-1$
components.add(createHTMLComponent("HtmlForm")); //$NON-NLS-1$
components.add(createHTMLComponent("HtmlGraphicImage")); //$NON-NLS-1$
components.add(createHTMLComponent("HtmlInputHidden")); //$NON-NLS-1$
components.add(createHTMLComponent("HtmlInputSecret")); //$NON-NLS-1$
components.add(createHTMLComponent("HtmlInputText")); //$NON-NLS-1$
components.add(createHTMLComponent("HtmlInputTextarea")); //$NON-NLS-1$
components.add(createHTMLComponent("HtmlMessage")); //$NON-NLS-1$
components.add(createHTMLComponent("HtmlMessages")); //$NON-NLS-1$
components.add(createHTMLComponent("HtmlOutputFormat")); //$NON-NLS-1$
components.add(createHTMLComponent("HtmlOutputLabel")); //$NON-NLS-1$
components.add(createHTMLComponent("HtmlOutputLink")); //$NON-NLS-1$
components.add(createHTMLComponent("HtmlOutputText")); //$NON-NLS-1$
components.add(createHTMLComponent("HtmlPanelGrid")); //$NON-NLS-1$
components.add(createHTMLComponent("HtmlPanelGroup")); //$NON-NLS-1$
components.add(createHTMLComponent("HtmlSelectBooleanCheckbox")); //$NON-NLS-1$
components.add(createHTMLComponent("HtmlSelectManyCheckbox")); //$NON-NLS-1$
components.add(createHTMLComponent("HtmlSelectManyListbox")); //$NON-NLS-1$
components.add(createHTMLComponent("HtmlSelectManyMenu")); //$NON-NLS-1$
components.add(createHTMLComponent("HtmlSelectOneListbox")); //$NON-NLS-1$
components.add(createHTMLComponent("HtmlSelectOneMenu")); //$NON-NLS-1$
components.add(createHTMLComponent("HtmlSelectOneRadio")); //$NON-NLS-1$
}
| protected void createModel() {
facesConfig = FacesConfigFactory.eINSTANCE.createFacesConfigType();
//create and add converters by id
EList converters = facesConfig.getConverter();
converters.add(createConverter("BigDecimal")); //$NON-NLS-1$
converters.add(createConverter("BigInteger")); //$NON-NLS-1$
converters.add(createConverter("Boolean")); //$NON-NLS-1$
converters.add(createConverter("Byte")); //$NON-NLS-1$
converters.add(createConverter("Character")); //$NON-NLS-1$
converters.add(createConverter("DateTime")); //$NON-NLS-1$
converters.add(createConverter("Double")); //$NON-NLS-1$
converters.add(createConverter("Float")); //$NON-NLS-1$
converters.add(createConverter("Integer")); //$NON-NLS-1$
converters.add(createConverter("Long")); //$NON-NLS-1$
converters.add(createConverter("Number")); //$NON-NLS-1$
converters.add(createConverter("Short")); //$NON-NLS-1$
converters.add(createConverter("Enum")); //$NON-NLS-1$
// converters by for-class (see spec 3.3.3 -- Standard Converter Implementions
converters.add(createForClassConverter("java.lang.Boolean", "javax.faces.convert.BooleanConverter")); //$NON-NLS-1$ //$NON-NLS-2$
converters.add(createForClassConverter("java.lang.Byte", "javax.faces.convert.ByteConverter")); //$NON-NLS-1$ //$NON-NLS-2$
converters.add(createForClassConverter("java.lang.Character", "javax.faces.convert.CharacterConverter")); //$NON-NLS-1$ //$NON-NLS-2$
converters.add(createForClassConverter("java.lang.Double", "javax.faces.convert.DoubleConverter")); //$NON-NLS-1$ //$NON-NLS-2$
converters.add(createForClassConverter("java.lang.Float", "javax.faces.convert.FloatConverter")); //$NON-NLS-1$ //$NON-NLS-2$
converters.add(createForClassConverter("java.lang.Integer", "javax.faces.convert.IntegerConverter")); //$NON-NLS-1$ //$NON-NLS-2$
converters.add(createForClassConverter("java.lang.Long", "javax.faces.convert.LongConverter")); //$NON-NLS-1$ //$NON-NLS-2$
converters.add(createForClassConverter("java.lang.Short", "javax.faces.converter.ShortConverter")); //$NON-NLS-1$ //$NON-NLS-2$
converters.add(createForClassConverter("java.lang.Enum", "javax.faces.converter.EnumConverter")); //$NON-NLS-1$ //$NON-NLS-2$
//create and add validators
EList validators = facesConfig.getValidator();
validators.add(createValidator("DoubleRange")); //$NON-NLS-1$
validators.add(createValidator("Length")); //$NON-NLS-1$
validators.add(createValidator("LongRange")); //$NON-NLS-1$
validators.add(createValidator("Bean")); //$NON-NLS-1$
validators.add(createValidator("RegularExpression")); //$NON-NLS-1$
validators.add(createValidator("Required")); //$NON-NLS-1$
//create and add UI components
EList components = facesConfig.getComponent();
components.add(createUIComponent("Column")); //$NON-NLS-1$
components.add(createUIComponent("Command")); //$NON-NLS-1$
components.add(createUIComponent("Data")); //$NON-NLS-1$
components.add(createUIComponent("Form")); //$NON-NLS-1$
components.add(createUIComponent("Graphic")); //$NON-NLS-1$
components.add(createUIComponent("Input")); //$NON-NLS-1$
components.add(createUIComponent("Message")); //$NON-NLS-1$
components.add(createUIComponent("Messages")); //$NON-NLS-1$
components.add(createUIComponent("NamingContainer")); //$NON-NLS-1$
components.add(createUIComponent("Output")); //$NON-NLS-1$
components.add(createUIComponent("Panel")); //$NON-NLS-1$
components.add(createUIComponent("Parameter")); //$NON-NLS-1$
components.add(createUIComponent("SelectBoolean")); //$NON-NLS-1$
components.add(createUIComponent("SelectItem")); //$NON-NLS-1$
components.add(createUIComponent("SelectItems")); //$NON-NLS-1$
components.add(createUIComponent("SelectMany")); //$NON-NLS-1$
components.add(createUIComponent("SelectOne")); //$NON-NLS-1$
components.add(createUIComponent("ViewRoot")); //$NON-NLS-1$
//create and add HTML components
components.add(createHTMLComponent("HtmlCommandButton")); //$NON-NLS-1$
components.add(createHTMLComponent("HtmlCommandLink")); //$NON-NLS-1$
components.add(createHTMLComponent("HtmlDataTable")); //$NON-NLS-1$
components.add(createHTMLComponent("HtmlForm")); //$NON-NLS-1$
components.add(createHTMLComponent("HtmlGraphicImage")); //$NON-NLS-1$
components.add(createHTMLComponent("HtmlInputHidden")); //$NON-NLS-1$
components.add(createHTMLComponent("HtmlInputSecret")); //$NON-NLS-1$
components.add(createHTMLComponent("HtmlInputText")); //$NON-NLS-1$
components.add(createHTMLComponent("HtmlInputTextarea")); //$NON-NLS-1$
components.add(createHTMLComponent("HtmlMessage")); //$NON-NLS-1$
components.add(createHTMLComponent("HtmlMessages")); //$NON-NLS-1$
components.add(createHTMLComponent("HtmlOutputFormat")); //$NON-NLS-1$
components.add(createHTMLComponent("HtmlOutputLabel")); //$NON-NLS-1$
components.add(createHTMLComponent("HtmlOutputLink")); //$NON-NLS-1$
components.add(createHTMLComponent("HtmlOutputText")); //$NON-NLS-1$
components.add(createHTMLComponent("HtmlPanelGrid")); //$NON-NLS-1$
components.add(createHTMLComponent("HtmlPanelGroup")); //$NON-NLS-1$
components.add(createHTMLComponent("HtmlSelectBooleanCheckbox")); //$NON-NLS-1$
components.add(createHTMLComponent("HtmlSelectManyCheckbox")); //$NON-NLS-1$
components.add(createHTMLComponent("HtmlSelectManyListbox")); //$NON-NLS-1$
components.add(createHTMLComponent("HtmlSelectManyMenu")); //$NON-NLS-1$
components.add(createHTMLComponent("HtmlSelectOneListbox")); //$NON-NLS-1$
components.add(createHTMLComponent("HtmlSelectOneMenu")); //$NON-NLS-1$
components.add(createHTMLComponent("HtmlSelectOneRadio")); //$NON-NLS-1$
}
|
diff --git a/app/src/com/gimranov/zandy/app/task/APIRequest.java b/app/src/com/gimranov/zandy/app/task/APIRequest.java
index 4a4567a..b7a19c3 100644
--- a/app/src/com/gimranov/zandy/app/task/APIRequest.java
+++ b/app/src/com/gimranov/zandy/app/task/APIRequest.java
@@ -1,1236 +1,1237 @@
/*******************************************************************************
* This file is part of Zandy.
*
* Zandy is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Zandy is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Zandy. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
package com.gimranov.zandy.app.task;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.UUID;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteStatement;
import android.os.Handler;
import android.util.Log;
import com.gimranov.zandy.app.ServerCredentials;
import com.gimranov.zandy.app.XMLResponseParser;
import com.gimranov.zandy.app.data.Attachment;
import com.gimranov.zandy.app.data.Database;
import com.gimranov.zandy.app.data.Item;
import com.gimranov.zandy.app.data.ItemCollection;
/**
* Represents a request to the Zotero API. These can be consumed by
* other things like ZoteroAPITask. These should be queued up for many purposes.
*
* The APIRequest should include the HttpPost / HttpGet / etc. that it needs
* to be executed, and optionally a callback to be called when it completes.
*
* See http://www.zotero.org/support/dev/server_api for information.
*
* @author ajlyon
*
*/
public class APIRequest {
private static final String TAG = "com.gimranov.zandy.app.task.APIRequest";
/**
* Statuses used for items and collections. They are currently strings, but
* they should change to integers. These statuses may be stored in the database.
*/
// XXX i18n
public static final String API_DIRTY = "Unsynced change";
public static final String API_NEW = "New item / collection";
public static final String API_MISSING ="Partial data";
public static final String API_STALE = "Stale data";
public static final String API_WIP = "Sync attempted";
public static final String API_CLEAN = "No unsynced change";
/**
* These are constants represented by integers.
*
* The above should be moving down here some time.
*/
/**
* HTTP response codes that we are used to
*/
public static final int HTTP_ERROR_CONFLICT = 412;
public static final int HTTP_ERROR_UNSPECIFIED = 400;
/**
* The following are used when passing things back to the UI
* from the API request service / thread.
*/
/** Used to indicate database data has changed. */
public static final int UPDATED_DATA = 1000;
/** Current set of requests completed. */
public static final int BATCH_DONE = 2000;
/** Used to indicate an error with no more details. */
public static final int ERROR_UNKNOWN = 4000;
/** Queued more requests */
public static final int QUEUED_MORE = 3000;
/**
* Request types
*/
public static final int ITEMS_ALL = 10000;
public static final int ITEMS_FOR_COLLECTION = 10001;
public static final int ITEMS_CHILDREN = 10002;
public static final int COLLECTIONS_ALL = 10003;
public static final int ITEM_BY_KEY = 10004;
// Requests that require write access
public static final int ITEM_NEW = 20000;
public static final int ITEM_UPDATE = 20001;
public static final int ITEM_DELETE = 20002;
public static final int ITEM_MEMBERSHIP_ADD = 20003;
public static final int ITEM_MEMBERSHIP_REMOVE = 20004;
public static final int ITEM_ATTACHMENT_NEW = 20005;
public static final int ITEM_ATTACHMENT_UPDATE = 20006;
public static final int ITEM_ATTACHMENT_DELETE = 20007;
public static final int ITEM_FIELDS = 30000;
public static final int CREATOR_TYPES = 30001;
public static final int ITEM_FIELDS_L10N = 30002;
public static final int CREATOR_TYPES_L10N = 30003;
/**
* Request status for use within the database
*/
public static final int REQ_NEW = 40000;
public static final int REQ_FAILING = 41000;
/**
* We'll request the whole collection or library rather than
* individual feeds when we have less than this proportion of
* the items. Used when pre-fetching keys.
*/
public static double REREQUEST_CUTOFF = 0.7;
/**
* Type of request we're sending. This should be one of
* the request types listed above.
*/
public int type;
/**
* Callback handler
*/
private APIEvent handler;
/**
* Base query to send.
*/
public String query;
/**
* API key used to make request. Can be omitted for requests that don't need one.
*/
public String key;
/**
* One of get, put, post, delete.
* Lower-case preferred, but we coerce them anyway.
*/
public String method;
/**
* Response disposition: xml or raw. JSON also planned
*/
public String disposition;
/**
* Used when sending JSON in POST and PUT requests.
*/
public String contentType = "application/json";
/**
* Optional token to avoid accidentally sending one request twice. The
* server will decline to carry out a second request with the same writeToken
* for a single API key in a several-hour period.
*/
public String writeToken;
/**
* The eTag received from the server when requesting an item. We can make changes
* (delete, update) to an item only while the tag is valid; if the item changes
* server-side, our request will be declined until we request the item anew and get
* a new valid eTag.
*/
public String ifMatch;
/**
* Request body, generally JSON.
*/
public String body;
/**
* The temporary key (UUID) that the request is based on.
*/
public String updateKey;
/**
* Type of object we expect to get. This and the updateKey are used to update
* the UUIDs / local keys of locally-created items. I know, it's a hack.
*/
public String updateType;
/**
* Status code for the request. Codes should be constants defined in APIRequest;
* take the REQ_* code and add the response code if applicable.
*/
public int status;
/**
* UUID for this request. We use this for DB lookups and as the write token when
* appropriate. Every request should have one.
*/
private String uuid;
/**
* Timestamp when this request was first created.
*/
private Date created;
/**
* Timestamp when this request was last attempted to be run.
*/
private Date lastAttempt;
/**
* Creates a basic APIRequest item. Augment the item using instance methods for more complex
* requests, or pass it to ZoteroAPITask for simpler ones. The request can be run by
* simply calling the instance method `issue(..)`, but not from the UI thread.
*
* The constructor is not to be used directly; use the static methods in this class, or create from
* a cursor. The one exception is the Atom feed continuations produced by XMLResponseParser, but that
* should be moved into this class as well.
*
* @param query Fragment being requested, like /items
* @param method GET, POST, PUT, or DELETE (except that lowercase is preferred)
* @param key Can be null, if you're planning on making requests that don't need a key.
*/
public APIRequest(String query, String method, String key) {
this.query = query;
this.method = method;
this.key = key;
// default to XML processing
this.disposition = "xml";
// If this is processing-intensive, we can probably move it to the save method
this.uuid = UUID.randomUUID().toString();
created = new Date();
}
/**
* Load an APIRequest from its serialized form in the database
* public static final String[] REQUESTCOLS = {"_id", "uuid", "type",
"query", "key", "method", "disposition", "if_match", "update_key",
"update_type", "created", "last_attempt", "status"};
* @param uuid
*/
public APIRequest(Cursor cur) {
// N.B.: getString and such use 0-based indexing
this.uuid = cur.getString(1);
this.type = cur.getInt(2);
this.query = cur.getString(3);
this.key = cur.getString(4);
this.method = cur.getString(5);
this.disposition = cur.getString(6);
this.ifMatch = cur.getString(7);
this.updateKey = cur.getString(8);
this.updateType = cur.getString(9);
this.created = new Date();
this.created.setTime(cur.getLong(10));
this.lastAttempt = new Date();
this.lastAttempt.setTime(cur.getLong(11));
this.status = cur.getInt(12);
this.body = cur.getString(13);
}
/**
* Saves the APIRequest's basic info to the database. Does not maintain handler information.
* @param db
*/
public void save(Database db) {
try {
Log.d(TAG, "Saving APIRequest to database: "+uuid+" "+query);
SQLiteStatement insert = db.compileStatement("insert or replace into apirequests " +
"(uuid, type, query, key, method, disposition, if_match, update_key, update_type, " +
"created, last_attempt, status, body)" +
" values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,?)");
// Why, oh why does bind* use 1-based indexing? And cur.get* uses 0-based!
insert.bindString(1, uuid);
insert.bindLong(2, (long) type);
String createdUnix = Long.toString(created.getTime());
String lastAttemptUnix;
if (lastAttempt == null) lastAttemptUnix = null;
else lastAttemptUnix = Long.toString(lastAttempt.getTime());
String status = Integer.toString(this.status);
// Iterate through null-allowed strings and bind them
String[] strings = {query, key, method, disposition, ifMatch, updateKey, updateType,
createdUnix, lastAttemptUnix, status, body};
for (int i = 0; i < strings.length; i++) {
Log.d(TAG, (3+i)+":"+strings[i]);
if (strings[i] == null) insert.bindNull(3+i);
else insert.bindString(3+i, strings[i]);
}
insert.executeInsert();
insert.clearBindings();
insert.close();
} catch (SQLiteException e) {
Log.e(TAG, "Exception compiling or running insert statement", e);
throw e;
}
}
/**
* Getter for the request's implementation of the APIEvent interface,
* used for call-backs, usually tying into the UI.
*
* Returns a no-op, logging handler if none specified
*
* @return
*/
public APIEvent getHandler() {
if (handler == null) {
/*
* We have to fall back on a no-op event handler to prevent null exceptions
*/
return new APIEvent() {
@Override
public void onComplete(APIRequest request) {
Log.d(TAG, "onComplete called but no handler");
}
@Override
public void onUpdate(APIRequest request) {
Log.d(TAG, "onUpdate called but no handler");
}
@Override
public void onError(APIRequest request, Exception exception) {
Log.d(TAG, "onError called but no handler");
}
@Override
public void onError(APIRequest request, int error) {
Log.d(TAG, "onError called but no handler");
}
};
}
return handler;
}
public void setHandler(APIEvent handler) {
if (this.handler == null) {
this.handler = handler;
return;
}
Log.e(TAG, "APIEvent handler for request cannot be replaced");
}
/**
* Set an Android standard handler to be used for the APIEvents
* @param handler
*/
public void setHandler(Handler handler) {
final Handler mHandler = handler;
if (this.handler == null) {
this.handler = new APIEvent() {
@Override
public void onComplete(APIRequest request) {
mHandler.sendEmptyMessage(BATCH_DONE);
}
@Override
public void onUpdate(APIRequest request) {
mHandler.sendEmptyMessage(UPDATED_DATA);
}
@Override
public void onError(APIRequest request, Exception exception) {
mHandler.sendEmptyMessage(ERROR_UNKNOWN);
}
@Override
public void onError(APIRequest request, int error) {
mHandler.sendEmptyMessage(ERROR_UNKNOWN);
}
};
return;
}
Log.e(TAG, "APIEvent handler for request cannot be replaced");
}
/**
* Populates the body with a JSON representation of
* the specified item.
*
* Use this for updating items, i.e.:
* PUT /users/1/items/ABCD2345
* @param item Item to put in the body.
*/
public void setBody(Item item) {
try {
body = item.getContent().toString(4);
} catch (JSONException e) {
Log.e(TAG, "Error setting body for item", e);
}
}
/**
* Populates the body with a JSON representation of the specified
* items.
*
* Use this for creating new items, i.e.:
* POST /users/1/items
* @param items
*/
public void setBody(ArrayList<Item> items) {
try {
JSONArray array = new JSONArray();
for (Item i : items) {
JSONObject jItem = i.getContent();
array.put(jItem);
}
JSONObject obj = new JSONObject();
obj.put("items", array);
body = obj.toString(4);
} catch (JSONException e) {
Log.e(TAG, "Error setting body for items", e);
}
}
/**
* Populates the body with a JSON representation of specified
* attachments; note that this is will not work with non-note
* attachments until the server API supports them.
*
* @param attachments
*/
public void setBodyWithNotes(ArrayList<Attachment> attachments) {
try {
JSONArray array = new JSONArray();
for (Attachment a : attachments) {
JSONObject jAtt = a.content;
array.put(jAtt);
}
JSONObject obj = new JSONObject();
obj.put("items", array);
body = obj.toString(4);
} catch (JSONException e) {
Log.e(TAG, "Error setting body for attachments", e);
}
}
/**
* Getter for the request's UUID
* @return
*/
public String getUuid() {
return uuid;
}
/**
* Sets the HTTP response code portion of the request's status
*
* @param code
* @return The new status
*/
public int setHttpStatus(int code) {
status = (status - status % 1000) + code;
return status;
}
/**
* Gets the HTTP response code portion of the request's status;
* returns 0 if there was no code set.
*/
public int getHttpStatus() {
return status % 1000;
}
/**
* Record a failed attempt to run the request.
*
* Saves the APIRequest in its current state.
*
* @param db Database object
* @return Date object with new lastAttempt value
*/
public Date recordAttempt(Database db) {
lastAttempt = new Date();
save(db);
return lastAttempt;
}
/**
* To be called when the request succeeds. Currently just
* deletes the corresponding row from the database.
*
* @param db Database object
*/
public void succeeded(Database db) {
String[] args = { uuid };
db.rawQuery("delete from apirequests where uuid=?", args);
}
/**
* Returns HTML-formatted string of the request
*
* XXX i18n, once we settle on a format
*
* @return
*/
public String toHtmlString() {
StringBuilder sb = new StringBuilder();
sb.append("<h1>");
sb.append(status);
sb.append("</h1>");
sb.append("<p><i>");
sb.append(method + "</i> "+query);
sb.append("</p>");
sb.append("<p>Body: ");
sb.append(body);
sb.append("</p>");
sb.append("<p>Created: ");
sb.append(created.toString());
sb.append("</p>");
sb.append("<p>Attempted: ");
if (lastAttempt.getTime() == 0)
sb.append("Never");
else
sb.append(lastAttempt.toString());
sb.append("</p>");
return sb.toString();
}
/**
* Issues the specified request, calling its specified handler as appropriate
*
* This should not be run from a UI thread
*
* @return
* @throws APIException
*/
public void issue(Database db, ServerCredentials cred) throws APIException {
URI uri;
// Add the API key, if missing and we have it
if (!query.contains("key=") && key != null) {
String suffix = (query.contains("?")) ? "&key="+key : "?key="+key;
query = query + suffix;
}
// Force lower-case
method = method.toLowerCase();
Log.i(TAG, "Request "+ method +": " + query);
try {
uri = new URI(query);
} catch (URISyntaxException e1) {
throw new APIException(APIException.INVALID_URI, "Invalid URI: "+query, this);
}
HttpClient client = new DefaultHttpClient();
// The default implementation includes an Expect: header, which
// confuses the Zotero servers.
client.getParams().setParameter("http.protocol.expect-continue", false);
// We also need to send our data nice and raw.
client.getParams().setParameter("http.protocol.content-charset", "UTF-8");
HttpGet get = new HttpGet(uri);
HttpPost post = new HttpPost(uri);
HttpPut put = new HttpPut(uri);
HttpDelete delete = new HttpDelete(uri);
// There are several shared initialization routines for POST and PUT
if ("post".equals(method) || "put".equals(method)) {
if(ifMatch != null) {
post.setHeader("If-Match", ifMatch);
put.setHeader("If-Match", ifMatch);
}
if(contentType != null) {
post.setHeader("Content-Type", contentType);
put.setHeader("Content-Type", contentType);
}
if (body != null) {
Log.d(TAG, "Request body: "+body);
// Force the encoding to UTF-8
StringEntity entity;
try {
entity = new StringEntity(body,"UTF-8");
} catch (UnsupportedEncodingException e) {
throw new APIException(APIException.INVALID_UUID,
"UnsupportedEncodingException. This shouldn't " +
"be possible-- UTF-8 is certainly supported", this);
}
post.setEntity(entity);
put.setEntity(entity);
}
}
if ("get".equals(method)) {
if(contentType != null) {
get.setHeader("Content-Type", contentType);
}
}
/* For requests that return Atom feeds or entries (XML):
* ITEMS_ALL ]
* ITEMS_FOR_COLLECTION ]- Except format=keys
* ITEMS_CHILDREN ]
*
* ITEM_BY_KEY
* COLLECTIONS_ALL
* ITEM_NEW
* ITEM_UPDATE
* ITEM_ATTACHMENT_NEW
* ITEM_ATTACHMENT_UPDATE
*/
if ("xml".equals(disposition)) {
XMLResponseParser parse = new XMLResponseParser();
// These types will always have a temporary key that we've
// been using locally, and which should be replaced by the
// incoming item key.
if (type == ITEM_NEW
|| type == ITEM_ATTACHMENT_NEW) {
parse.update(updateType, updateKey);
}
try {
HttpResponse hr;
if ("post".equals(method)) {
hr = client.execute(post);
} else if ("put".equals(method)) {
hr = client.execute(put);
} else {
// We fall back on GET here, but there really
// shouldn't be anything else, so we throw in that case
// for good measure
if (!"get".equals(method)) {
throw new APIException(APIException.INVALID_METHOD,
"Unexpected method: "+method, this);
}
hr = client.execute(get);
}
// Record the response code
status = hr.getStatusLine().getStatusCode();
Log.d(TAG, status + " : "+ hr.getStatusLine().getReasonPhrase());
if (status < 400) {
HttpEntity he = hr.getEntity();
InputStream in = he.getContent();
parse.setInputStream(in);
- // Entry mode if and only if the request is an update (PUT)
- int mode = ("put".equals(method)) ?
+ // Entry mode if the request is an update (PUT) or if it is a request
+ // for a single item by key (ITEM_BY_KEY)
+ int mode = ("put".equals(method) || type == APIRequest.ITEM_BY_KEY) ?
XMLResponseParser.MODE_ENTRY : XMLResponseParser.MODE_FEED;
try {
parse.parse(mode, uri.toString(), db);
} catch (RuntimeException e) {
throw new RuntimeException("Parser threw exception on request: "+method+" "+query);
}
} else {
ByteArrayOutputStream ostream = new ByteArrayOutputStream();
hr.getEntity().writeTo(ostream);
Log.e(TAG,"Error Body: "+ ostream.toString());
Log.e(TAG,"Request Body:"+ body);
if (status == 412) {
// This is: "Precondition Failed", meaning that we provided
// the wrong etag to update the item. That should mean that
// there is a conflict between what we're sending (PUT) and
// the server. We mark that ourselves and save the request
// to the database, and also notify our handler.
getHandler().onError(this, APIRequest.HTTP_ERROR_CONFLICT);
} else {
Log.e(TAG, "Response status "+status+" : "+ostream.toString());
getHandler().onError(this, APIRequest.HTTP_ERROR_UNSPECIFIED);
}
status = getHttpStatus() + REQ_FAILING;
recordAttempt(db);
// I'm not sure whether we should throw here
throw new APIException(APIException.HTTP_ERROR, ostream.toString(), this);
}
} catch (IOException e) {
StringBuilder sb = new StringBuilder();
for (StackTraceElement el : e.getStackTrace()) {
sb.append(el.toString()+"\n");
}
recordAttempt(db);
throw new APIException(APIException.HTTP_ERROR,
"An IOException was thrown: " + sb.toString(), this);
}
} // end if ("xml".equals(disposition)) {..}
/* For requests that return non-XML data:
* ITEMS_ALL ]
* ITEMS_FOR_COLLECTION ]- For format=keys
* ITEMS_CHILDREN ]
*
* No server response:
* ITEM_DELETE
* ITEM_MEMBERSHIP_ADD
* ITEM_MEMBERSHIP_REMOVE
* ITEM_ATTACHMENT_DELETE
*
* Currently not supported; return JSON:
* ITEM_FIELDS
* CREATOR_TYPES
* ITEM_FIELDS_L10N
* CREATOR_TYPES_L10N
*
* These ones use BasicResponseHandler, which gives us
* the response as a basic string. This is only appropriate
* for smaller responses, since it means we have to wait until
* the entire response is received before parsing it, so we
* don't use it for the XML responses.
*
* The disposition here is "none" or "raw".
*
* The JSON-returning requests, such as ITEM_FIELDS, are not currently
* supported; they should have a disposition of their own.
*/
else {
BasicResponseHandler brh = new BasicResponseHandler();
String resp;
try {
if ("post".equals(method)) {
resp = client.execute(post, brh);
} else if ("put".equals(method)) {
resp = client.execute(put, brh);
} else if ("delete".equals(method)) {
resp = client.execute(delete, brh);
} else {
// We fall back on GET here, but there really
// shouldn't be anything else, so we throw in that case
// for good measure
if (!"get".equals(method)) {
throw new APIException(APIException.INVALID_METHOD,
"Unexpected method: "+method, this);
}
resp = client.execute(get, brh);
}
} catch (IOException e) {
StringBuilder sb = new StringBuilder();
for (StackTraceElement el : e.getStackTrace()) {
sb.append(el.toString()+"\n");
}
recordAttempt(db);
throw new APIException(APIException.HTTP_ERROR,
"An IOException was thrown: " + sb.toString(), this);
}
if ("raw".equals(disposition)) {
/*
* The output should be a newline-delimited set of alphanumeric
* keys.
*/
String[] keys = resp.split("\n");
ArrayList<String> missing = new ArrayList<String>();
if (type == ITEMS_ALL ||
type == ITEMS_FOR_COLLECTION) {
// Try to get a parent collection
// Our query looks like this:
// /users/5770/collections/2AJUSIU9/items
int colloc = query.indexOf("/collections/");
int itemloc = query.indexOf("/items");
// The string "/collections/" is thirteen characters long
ItemCollection coll = ItemCollection.load(
query.substring(colloc+13, itemloc), db);
if (coll != null) {
coll.loadChildren(db);
// If this is a collection's key listing, we first look
// for any synced keys we have that aren't in the list
ArrayList<String> keyAL = new ArrayList<String>(Arrays.asList(keys));
ArrayList<Item> notThere = coll.notInKeys(keyAL);
// We should then remove those memberships
for (Item i : notThere) {
coll.remove(i, true, db);
}
}
ArrayList<Item> recd = new ArrayList<Item>();
for (int j = 0; j < keys.length; j++) {
Item got = Item.load(keys[j], db);
if (got == null) {
missing.add(keys[j]);
} else {
// We can update the collection membership immediately
if (coll != null) coll.add(got, true, db);
recd.add(got);
}
}
if (coll != null) {
coll.saveChildren(db);
coll.save(db);
}
Log.d(TAG, "Received "+keys.length+" keys, "+missing.size() + " missing ones");
Log.d(TAG, "Have "+(double) recd.size() / keys.length + " of list");
if (recd.size() == keys.length) {
Log.d(TAG, "No new items");
succeeded(db);
} else if ((double) recd.size() / keys.length < REREQUEST_CUTOFF) {
Log.d(TAG, "Requesting full list");
APIRequest mReq;
if (type == ITEMS_FOR_COLLECTION) {
mReq = fetchItems(coll, false, cred);
} else {
mReq = fetchItems(false, cred);
}
mReq.status = REQ_NEW;
mReq.save(db);
} else {
Log.d(TAG, "Requesting "+missing.size()+" items one by one");
APIRequest mReq;
for (String key : missing) {
// Queue request for the missing key
mReq = fetchItem(key, cred);
mReq.status = REQ_NEW;
mReq.save(db);
}
// Queue request for the collection again, by key
// XXX This is not the best way to make sure these
// items are put in the correct collection.
if (type == ITEMS_FOR_COLLECTION) {
fetchItems(coll, true, cred).save(db);
}
}
} else if (type == ITEMS_CHILDREN) {
// Try to get a parent item
// Our query looks like this:
// /users/5770/items/2AJUSIU9/children
int itemloc = query.indexOf("/items/");
int childloc = query.indexOf("/children");
// The string "/items/" is seven characters long
Item item = Item.load(
query.substring(itemloc+7, childloc), db);
ArrayList<Attachment> recd = new ArrayList<Attachment>();
for (int j = 0; j < keys.length; j++) {
Attachment got = Attachment.load(keys[j], db);
if (got == null) missing.add(keys[j]);
else recd.add(got);
}
if ((double) recd.size() / keys.length < REREQUEST_CUTOFF) {
APIRequest mReq;
mReq = cred.prep(children(item));
mReq.status = REQ_NEW;
mReq.save(db);
} else {
APIRequest mReq;
for (String key : missing) {
// Queue request for the missing key
mReq = fetchItem(key, cred);
mReq.status = REQ_NEW;
mReq.save(db);
}
}
}
} else if ("json".equals(disposition)) {
// TODO
} else {
/* Here, disposition should be "none" */
// Nothing to be done.
}
getHandler().onComplete(this);
}
}
/** NEXT SECTION: Static methods for generating APIRequests */
/**
* Produces an API request for the specified item key
*
* @param key Item key
* @param cred Credentials
*/
public static APIRequest fetchItem(String key, ServerCredentials cred) {
APIRequest req = new APIRequest(ServerCredentials.APIBASE
+ cred.prep(ServerCredentials.ITEMS)
+"/"+key, "get", null);
req.query = req.query + "?content=json";
req.disposition = "xml";
req.type = ITEM_BY_KEY;
req.key = cred.getKey();
return req;
}
/**
* Produces an API request for the items in a specified collection.
*
* @param collection The collection to fetch
* @param keysOnly Use format=keys rather than format=atom/content=json
* @param cred Credentials
*/
public static APIRequest fetchItems(ItemCollection collection, boolean keysOnly, ServerCredentials cred) {
return fetchItems(collection.getKey(), keysOnly, cred);
}
/**
* Produces an API request for the items in a specified collection.
*
* @param collectionKey The collection to fetch
* @param keysOnly Use format=keys rather than format=atom/content=json
* @param cred Credentials
*/
public static APIRequest fetchItems(String collectionKey, boolean keysOnly, ServerCredentials cred) {
APIRequest req = new APIRequest(ServerCredentials.APIBASE
+ cred.prep(ServerCredentials.COLLECTIONS)
+"/"+collectionKey+"/items", "get", null);
if (keysOnly) {
req.query = req.query + "?format=keys";
req.disposition = "raw";
} else {
req.query = req.query + "?content=json";
req.disposition = "xml";
}
req.type = APIRequest.ITEMS_FOR_COLLECTION;
req.key = cred.getKey();
return req;
}
/**
* Produces an API request for all items
*
* @param keysOnly Use format=keys rather than format=atom/content=json
* @param cred Credentials
*/
public static APIRequest fetchItems(boolean keysOnly, ServerCredentials cred) {
APIRequest req = new APIRequest(ServerCredentials.APIBASE
+ cred.prep(ServerCredentials.ITEMS)
+"/top", "get", null);
if (keysOnly) {
req.query = req.query + "?format=keys";
req.disposition = "raw";
} else {
req.query = req.query + "?content=json";
req.disposition = "xml";
}
req.type = APIRequest.ITEMS_ALL;
req.key = cred.getKey();
return req;
}
/**
* Produces an API request for all collections
*
* @param c Context
*/
public static APIRequest fetchCollections(ServerCredentials cred) {
APIRequest req = new APIRequest(ServerCredentials.APIBASE
+ cred.prep(ServerCredentials.COLLECTIONS)
+ "?content=json",
"get", null);
req.disposition = "xml";
req.type = APIRequest.COLLECTIONS_ALL;
req.key = cred.getKey();
return req;
}
/**
* Produces an API request to remove the specified item from the collection.
* This request always needs a key, but it isn't set automatically and should
* be set by whatever consumes this request.
*
* From the API docs:
* DELETE /users/1/collections/QRST9876/items/ABCD2345
*
* @param item
* @param collection
* @return
*/
public static APIRequest remove(Item item, ItemCollection collection) {
APIRequest templ = new APIRequest(ServerCredentials.APIBASE
+ ServerCredentials.COLLECTIONS + "/"
+ collection.getKey() + "/items/" + item.getKey(),
"DELETE",
null);
templ.disposition = "none";
return templ;
}
/**
* Produces an API request to add the specified items to the collection.
* This request always needs a key, but it isn't set automatically and should
* be set by whatever consumes this request.
*
* From the API docs:
* POST /users/1/collections/QRST9876/items
*
* ABCD2345 FBCD2335
*
* @param items
* @param collection
* @return
*/
public static APIRequest add(ArrayList<Item> items, ItemCollection collection) {
APIRequest templ = new APIRequest(ServerCredentials.APIBASE
+ ServerCredentials.COLLECTIONS
+ "/"
+ collection.getKey() + "/items",
"POST",
null);
templ.body = "";
for (Item i : items) {
templ.body += i.getKey() + " ";
}
templ.disposition = "none";
return templ;
}
/**
* Craft a request to add a single item to the server
*
* @param item
* @param collection
* @return
*/
public static APIRequest add(Item item, ItemCollection collection) {
ArrayList<Item> items = new ArrayList<Item>();
items.add(item);
return add(items, collection);
}
/**
* Craft a request to add items to the server
* This does not attempt to update them, just add them.
*
* @param items
* @return
*/
public static APIRequest add(ArrayList<Item> items) {
APIRequest templ = new APIRequest(ServerCredentials.APIBASE
+ ServerCredentials.ITEMS
+ "?content=json",
"POST",
null);
templ.setBody(items);
templ.disposition = "xml";
templ.updateType = "item";
// TODO this needs to be reworked to send all the keys. Or the whole system
// needs to be reworked.
Log.d(TAG, "Using the templ key of the first new item for now...");
templ.updateKey = items.get(0).getKey();
return templ;
}
/**
* Craft a request to add child items (notes, attachments) to the server
* This does not attempt to update them, just add them.
*
* @param item The parent item of the attachments
* @param attachments
* @return
*/
public static APIRequest add(Item item, ArrayList<Attachment> attachments) {
APIRequest templ = new APIRequest(ServerCredentials.APIBASE
+ ServerCredentials.ITEMS
+ "/" + item.getKey() + "/children?content=json",
"POST",
null);
templ.setBodyWithNotes(attachments);
templ.disposition = "xml";
templ.updateType = "attachment";
// TODO this needs to be reworked to send all the keys. Or the whole system
// needs to be reworked.
Log.d(TAG, "Using the templ key of the first new attachment for now...");
templ.updateKey = attachments.get(0).key;
return templ;
}
/**
* Craft a request for the children of the specified item
* @param item
* @return
*/
public static APIRequest children(Item item) {
APIRequest templ = new APIRequest(ServerCredentials.APIBASE
+ ServerCredentials.ITEMS+"/"+item.getKey()+"/children?content=json",
"GET",
null);
templ.disposition = "xml";
templ.type = ITEMS_CHILDREN;
return templ;
}
/**
* Craft a request to update an attachment on the server
* Does not refresh eTag
*
* @param attachment
* @return
*/
public static APIRequest update(Attachment attachment, Database db) {
Log.d(TAG, "Attachment key pre-update: "+attachment.key);
// If we have an attachment marked as new, update it
if (attachment.key.length() > 10) {
Item item = Item.load(attachment.parentKey, db);
ArrayList<Attachment> aL = new ArrayList<Attachment>();
aL.add(attachment);
if (item == null) {
Log.e(TAG, "Orphaned attachment with key: "+attachment.key);
attachment.delete(db);
// send something, so we don't get errors elsewhere
return new APIRequest(ServerCredentials.APIBASE, "GET", null);
}
return add(item, aL);
}
APIRequest templ = new APIRequest(ServerCredentials.APIBASE
+ ServerCredentials.ITEMS+"/" + attachment.key,
"PUT",
null);
try {
templ.body = attachment.content.toString(4);
} catch (JSONException e) {
Log.e(TAG, "JSON exception setting body for attachment update: "+attachment.key,e);
}
templ.ifMatch = '"' + attachment.etag + '"';
templ.disposition = "xml";
return templ;
}
/**
* Craft a request to update an attachment on the server
* Does not refresh eTag
*
* @param item
* @return
*/
public static APIRequest update(Item item) {
// If we have an item markes as new, update it
if (item.getKey().length() > 10) {
ArrayList<Item> mAL = new ArrayList<Item>();
mAL.add(item);
return add(mAL);
}
APIRequest templ = new APIRequest(ServerCredentials.APIBASE
+ ServerCredentials.ITEMS+"/"+item.getKey(),
"PUT",
null);
templ.setBody(item);
templ.ifMatch = '"' + item.getEtag() + '"';
Log.d(TAG,"etag: "+item.getEtag());
templ.disposition = "xml";
return templ;
}
/**
* Produces API requests to delete queued items from the server.
* This request always needs a key.
*
* From the API docs:
* DELETE /users/1/items/ABCD2345
* If-Match: "8e984e9b2a8fb560b0085b40f6c2c2b7"
*
* @param c
* @return
*/
public static ArrayList<APIRequest> delete(Context c) {
ArrayList<APIRequest> list = new ArrayList<APIRequest>();
Database db = new Database(c);
String[] args = {};
Cursor cur = db.rawQuery("select item_key, etag from deleteditems", args);
if (cur == null) {
db.close();
Log.d(TAG, "No deleted items found in database");
return list;
}
do {
APIRequest templ = new APIRequest(ServerCredentials.APIBASE
+ ServerCredentials.ITEMS + "/" + cur.getString(0),
"DELETE",
null);
templ.disposition = "none";
templ.ifMatch = cur.getString(1);
Log.d(TAG, "Adding deleted item: "+cur.getString(0) + " : " + templ.ifMatch);
// Save the request to the database to be dispatched later
templ.save(db);
list.add(templ);
} while (cur.moveToNext() != false);
cur.close();
db.rawQuery("delete from deleteditems", args);
db.close();
return list;
}
/**
* Returns APIRequest objects from the database
* @return
*/
public static ArrayList<APIRequest> queue(Database db) {
ArrayList<APIRequest> list = new ArrayList<APIRequest>();
String[] cols = Database.REQUESTCOLS;
String[] args = { };
Cursor cur = db.query("apirequests", cols, "", args, null, null,
null, null);
if (cur == null) return list;
do {
APIRequest req = new APIRequest(cur);
list.add(req);
Log.d(TAG, "Queueing request: "+req.query);
} while (cur.moveToNext() != false);
cur.close();
return list;
}
}
| true | true | public void issue(Database db, ServerCredentials cred) throws APIException {
URI uri;
// Add the API key, if missing and we have it
if (!query.contains("key=") && key != null) {
String suffix = (query.contains("?")) ? "&key="+key : "?key="+key;
query = query + suffix;
}
// Force lower-case
method = method.toLowerCase();
Log.i(TAG, "Request "+ method +": " + query);
try {
uri = new URI(query);
} catch (URISyntaxException e1) {
throw new APIException(APIException.INVALID_URI, "Invalid URI: "+query, this);
}
HttpClient client = new DefaultHttpClient();
// The default implementation includes an Expect: header, which
// confuses the Zotero servers.
client.getParams().setParameter("http.protocol.expect-continue", false);
// We also need to send our data nice and raw.
client.getParams().setParameter("http.protocol.content-charset", "UTF-8");
HttpGet get = new HttpGet(uri);
HttpPost post = new HttpPost(uri);
HttpPut put = new HttpPut(uri);
HttpDelete delete = new HttpDelete(uri);
// There are several shared initialization routines for POST and PUT
if ("post".equals(method) || "put".equals(method)) {
if(ifMatch != null) {
post.setHeader("If-Match", ifMatch);
put.setHeader("If-Match", ifMatch);
}
if(contentType != null) {
post.setHeader("Content-Type", contentType);
put.setHeader("Content-Type", contentType);
}
if (body != null) {
Log.d(TAG, "Request body: "+body);
// Force the encoding to UTF-8
StringEntity entity;
try {
entity = new StringEntity(body,"UTF-8");
} catch (UnsupportedEncodingException e) {
throw new APIException(APIException.INVALID_UUID,
"UnsupportedEncodingException. This shouldn't " +
"be possible-- UTF-8 is certainly supported", this);
}
post.setEntity(entity);
put.setEntity(entity);
}
}
if ("get".equals(method)) {
if(contentType != null) {
get.setHeader("Content-Type", contentType);
}
}
/* For requests that return Atom feeds or entries (XML):
* ITEMS_ALL ]
* ITEMS_FOR_COLLECTION ]- Except format=keys
* ITEMS_CHILDREN ]
*
* ITEM_BY_KEY
* COLLECTIONS_ALL
* ITEM_NEW
* ITEM_UPDATE
* ITEM_ATTACHMENT_NEW
* ITEM_ATTACHMENT_UPDATE
*/
if ("xml".equals(disposition)) {
XMLResponseParser parse = new XMLResponseParser();
// These types will always have a temporary key that we've
// been using locally, and which should be replaced by the
// incoming item key.
if (type == ITEM_NEW
|| type == ITEM_ATTACHMENT_NEW) {
parse.update(updateType, updateKey);
}
try {
HttpResponse hr;
if ("post".equals(method)) {
hr = client.execute(post);
} else if ("put".equals(method)) {
hr = client.execute(put);
} else {
// We fall back on GET here, but there really
// shouldn't be anything else, so we throw in that case
// for good measure
if (!"get".equals(method)) {
throw new APIException(APIException.INVALID_METHOD,
"Unexpected method: "+method, this);
}
hr = client.execute(get);
}
// Record the response code
status = hr.getStatusLine().getStatusCode();
Log.d(TAG, status + " : "+ hr.getStatusLine().getReasonPhrase());
if (status < 400) {
HttpEntity he = hr.getEntity();
InputStream in = he.getContent();
parse.setInputStream(in);
// Entry mode if and only if the request is an update (PUT)
int mode = ("put".equals(method)) ?
XMLResponseParser.MODE_ENTRY : XMLResponseParser.MODE_FEED;
try {
parse.parse(mode, uri.toString(), db);
} catch (RuntimeException e) {
throw new RuntimeException("Parser threw exception on request: "+method+" "+query);
}
} else {
ByteArrayOutputStream ostream = new ByteArrayOutputStream();
hr.getEntity().writeTo(ostream);
Log.e(TAG,"Error Body: "+ ostream.toString());
Log.e(TAG,"Request Body:"+ body);
if (status == 412) {
// This is: "Precondition Failed", meaning that we provided
// the wrong etag to update the item. That should mean that
// there is a conflict between what we're sending (PUT) and
// the server. We mark that ourselves and save the request
// to the database, and also notify our handler.
getHandler().onError(this, APIRequest.HTTP_ERROR_CONFLICT);
} else {
Log.e(TAG, "Response status "+status+" : "+ostream.toString());
getHandler().onError(this, APIRequest.HTTP_ERROR_UNSPECIFIED);
}
status = getHttpStatus() + REQ_FAILING;
recordAttempt(db);
// I'm not sure whether we should throw here
throw new APIException(APIException.HTTP_ERROR, ostream.toString(), this);
}
} catch (IOException e) {
StringBuilder sb = new StringBuilder();
for (StackTraceElement el : e.getStackTrace()) {
sb.append(el.toString()+"\n");
}
recordAttempt(db);
throw new APIException(APIException.HTTP_ERROR,
"An IOException was thrown: " + sb.toString(), this);
}
} // end if ("xml".equals(disposition)) {..}
/* For requests that return non-XML data:
* ITEMS_ALL ]
* ITEMS_FOR_COLLECTION ]- For format=keys
* ITEMS_CHILDREN ]
*
* No server response:
* ITEM_DELETE
* ITEM_MEMBERSHIP_ADD
* ITEM_MEMBERSHIP_REMOVE
* ITEM_ATTACHMENT_DELETE
*
* Currently not supported; return JSON:
* ITEM_FIELDS
* CREATOR_TYPES
* ITEM_FIELDS_L10N
* CREATOR_TYPES_L10N
*
* These ones use BasicResponseHandler, which gives us
* the response as a basic string. This is only appropriate
* for smaller responses, since it means we have to wait until
* the entire response is received before parsing it, so we
* don't use it for the XML responses.
*
* The disposition here is "none" or "raw".
*
* The JSON-returning requests, such as ITEM_FIELDS, are not currently
* supported; they should have a disposition of their own.
*/
else {
BasicResponseHandler brh = new BasicResponseHandler();
String resp;
try {
if ("post".equals(method)) {
resp = client.execute(post, brh);
} else if ("put".equals(method)) {
resp = client.execute(put, brh);
} else if ("delete".equals(method)) {
resp = client.execute(delete, brh);
} else {
// We fall back on GET here, but there really
// shouldn't be anything else, so we throw in that case
// for good measure
if (!"get".equals(method)) {
throw new APIException(APIException.INVALID_METHOD,
"Unexpected method: "+method, this);
}
resp = client.execute(get, brh);
}
} catch (IOException e) {
StringBuilder sb = new StringBuilder();
for (StackTraceElement el : e.getStackTrace()) {
sb.append(el.toString()+"\n");
}
recordAttempt(db);
throw new APIException(APIException.HTTP_ERROR,
"An IOException was thrown: " + sb.toString(), this);
}
if ("raw".equals(disposition)) {
/*
* The output should be a newline-delimited set of alphanumeric
* keys.
*/
String[] keys = resp.split("\n");
ArrayList<String> missing = new ArrayList<String>();
if (type == ITEMS_ALL ||
type == ITEMS_FOR_COLLECTION) {
// Try to get a parent collection
// Our query looks like this:
// /users/5770/collections/2AJUSIU9/items
int colloc = query.indexOf("/collections/");
int itemloc = query.indexOf("/items");
// The string "/collections/" is thirteen characters long
ItemCollection coll = ItemCollection.load(
query.substring(colloc+13, itemloc), db);
if (coll != null) {
coll.loadChildren(db);
// If this is a collection's key listing, we first look
// for any synced keys we have that aren't in the list
ArrayList<String> keyAL = new ArrayList<String>(Arrays.asList(keys));
ArrayList<Item> notThere = coll.notInKeys(keyAL);
// We should then remove those memberships
for (Item i : notThere) {
coll.remove(i, true, db);
}
}
ArrayList<Item> recd = new ArrayList<Item>();
for (int j = 0; j < keys.length; j++) {
Item got = Item.load(keys[j], db);
if (got == null) {
missing.add(keys[j]);
} else {
// We can update the collection membership immediately
if (coll != null) coll.add(got, true, db);
recd.add(got);
}
}
if (coll != null) {
coll.saveChildren(db);
coll.save(db);
}
Log.d(TAG, "Received "+keys.length+" keys, "+missing.size() + " missing ones");
Log.d(TAG, "Have "+(double) recd.size() / keys.length + " of list");
if (recd.size() == keys.length) {
Log.d(TAG, "No new items");
succeeded(db);
} else if ((double) recd.size() / keys.length < REREQUEST_CUTOFF) {
Log.d(TAG, "Requesting full list");
APIRequest mReq;
if (type == ITEMS_FOR_COLLECTION) {
mReq = fetchItems(coll, false, cred);
} else {
mReq = fetchItems(false, cred);
}
mReq.status = REQ_NEW;
mReq.save(db);
} else {
Log.d(TAG, "Requesting "+missing.size()+" items one by one");
APIRequest mReq;
for (String key : missing) {
// Queue request for the missing key
mReq = fetchItem(key, cred);
mReq.status = REQ_NEW;
mReq.save(db);
}
// Queue request for the collection again, by key
// XXX This is not the best way to make sure these
// items are put in the correct collection.
if (type == ITEMS_FOR_COLLECTION) {
fetchItems(coll, true, cred).save(db);
}
}
} else if (type == ITEMS_CHILDREN) {
// Try to get a parent item
// Our query looks like this:
// /users/5770/items/2AJUSIU9/children
int itemloc = query.indexOf("/items/");
int childloc = query.indexOf("/children");
// The string "/items/" is seven characters long
Item item = Item.load(
query.substring(itemloc+7, childloc), db);
ArrayList<Attachment> recd = new ArrayList<Attachment>();
for (int j = 0; j < keys.length; j++) {
Attachment got = Attachment.load(keys[j], db);
if (got == null) missing.add(keys[j]);
else recd.add(got);
}
if ((double) recd.size() / keys.length < REREQUEST_CUTOFF) {
APIRequest mReq;
mReq = cred.prep(children(item));
mReq.status = REQ_NEW;
mReq.save(db);
} else {
APIRequest mReq;
for (String key : missing) {
// Queue request for the missing key
mReq = fetchItem(key, cred);
mReq.status = REQ_NEW;
mReq.save(db);
}
}
}
} else if ("json".equals(disposition)) {
// TODO
} else {
/* Here, disposition should be "none" */
// Nothing to be done.
}
getHandler().onComplete(this);
}
}
| public void issue(Database db, ServerCredentials cred) throws APIException {
URI uri;
// Add the API key, if missing and we have it
if (!query.contains("key=") && key != null) {
String suffix = (query.contains("?")) ? "&key="+key : "?key="+key;
query = query + suffix;
}
// Force lower-case
method = method.toLowerCase();
Log.i(TAG, "Request "+ method +": " + query);
try {
uri = new URI(query);
} catch (URISyntaxException e1) {
throw new APIException(APIException.INVALID_URI, "Invalid URI: "+query, this);
}
HttpClient client = new DefaultHttpClient();
// The default implementation includes an Expect: header, which
// confuses the Zotero servers.
client.getParams().setParameter("http.protocol.expect-continue", false);
// We also need to send our data nice and raw.
client.getParams().setParameter("http.protocol.content-charset", "UTF-8");
HttpGet get = new HttpGet(uri);
HttpPost post = new HttpPost(uri);
HttpPut put = new HttpPut(uri);
HttpDelete delete = new HttpDelete(uri);
// There are several shared initialization routines for POST and PUT
if ("post".equals(method) || "put".equals(method)) {
if(ifMatch != null) {
post.setHeader("If-Match", ifMatch);
put.setHeader("If-Match", ifMatch);
}
if(contentType != null) {
post.setHeader("Content-Type", contentType);
put.setHeader("Content-Type", contentType);
}
if (body != null) {
Log.d(TAG, "Request body: "+body);
// Force the encoding to UTF-8
StringEntity entity;
try {
entity = new StringEntity(body,"UTF-8");
} catch (UnsupportedEncodingException e) {
throw new APIException(APIException.INVALID_UUID,
"UnsupportedEncodingException. This shouldn't " +
"be possible-- UTF-8 is certainly supported", this);
}
post.setEntity(entity);
put.setEntity(entity);
}
}
if ("get".equals(method)) {
if(contentType != null) {
get.setHeader("Content-Type", contentType);
}
}
/* For requests that return Atom feeds or entries (XML):
* ITEMS_ALL ]
* ITEMS_FOR_COLLECTION ]- Except format=keys
* ITEMS_CHILDREN ]
*
* ITEM_BY_KEY
* COLLECTIONS_ALL
* ITEM_NEW
* ITEM_UPDATE
* ITEM_ATTACHMENT_NEW
* ITEM_ATTACHMENT_UPDATE
*/
if ("xml".equals(disposition)) {
XMLResponseParser parse = new XMLResponseParser();
// These types will always have a temporary key that we've
// been using locally, and which should be replaced by the
// incoming item key.
if (type == ITEM_NEW
|| type == ITEM_ATTACHMENT_NEW) {
parse.update(updateType, updateKey);
}
try {
HttpResponse hr;
if ("post".equals(method)) {
hr = client.execute(post);
} else if ("put".equals(method)) {
hr = client.execute(put);
} else {
// We fall back on GET here, but there really
// shouldn't be anything else, so we throw in that case
// for good measure
if (!"get".equals(method)) {
throw new APIException(APIException.INVALID_METHOD,
"Unexpected method: "+method, this);
}
hr = client.execute(get);
}
// Record the response code
status = hr.getStatusLine().getStatusCode();
Log.d(TAG, status + " : "+ hr.getStatusLine().getReasonPhrase());
if (status < 400) {
HttpEntity he = hr.getEntity();
InputStream in = he.getContent();
parse.setInputStream(in);
// Entry mode if the request is an update (PUT) or if it is a request
// for a single item by key (ITEM_BY_KEY)
int mode = ("put".equals(method) || type == APIRequest.ITEM_BY_KEY) ?
XMLResponseParser.MODE_ENTRY : XMLResponseParser.MODE_FEED;
try {
parse.parse(mode, uri.toString(), db);
} catch (RuntimeException e) {
throw new RuntimeException("Parser threw exception on request: "+method+" "+query);
}
} else {
ByteArrayOutputStream ostream = new ByteArrayOutputStream();
hr.getEntity().writeTo(ostream);
Log.e(TAG,"Error Body: "+ ostream.toString());
Log.e(TAG,"Request Body:"+ body);
if (status == 412) {
// This is: "Precondition Failed", meaning that we provided
// the wrong etag to update the item. That should mean that
// there is a conflict between what we're sending (PUT) and
// the server. We mark that ourselves and save the request
// to the database, and also notify our handler.
getHandler().onError(this, APIRequest.HTTP_ERROR_CONFLICT);
} else {
Log.e(TAG, "Response status "+status+" : "+ostream.toString());
getHandler().onError(this, APIRequest.HTTP_ERROR_UNSPECIFIED);
}
status = getHttpStatus() + REQ_FAILING;
recordAttempt(db);
// I'm not sure whether we should throw here
throw new APIException(APIException.HTTP_ERROR, ostream.toString(), this);
}
} catch (IOException e) {
StringBuilder sb = new StringBuilder();
for (StackTraceElement el : e.getStackTrace()) {
sb.append(el.toString()+"\n");
}
recordAttempt(db);
throw new APIException(APIException.HTTP_ERROR,
"An IOException was thrown: " + sb.toString(), this);
}
} // end if ("xml".equals(disposition)) {..}
/* For requests that return non-XML data:
* ITEMS_ALL ]
* ITEMS_FOR_COLLECTION ]- For format=keys
* ITEMS_CHILDREN ]
*
* No server response:
* ITEM_DELETE
* ITEM_MEMBERSHIP_ADD
* ITEM_MEMBERSHIP_REMOVE
* ITEM_ATTACHMENT_DELETE
*
* Currently not supported; return JSON:
* ITEM_FIELDS
* CREATOR_TYPES
* ITEM_FIELDS_L10N
* CREATOR_TYPES_L10N
*
* These ones use BasicResponseHandler, which gives us
* the response as a basic string. This is only appropriate
* for smaller responses, since it means we have to wait until
* the entire response is received before parsing it, so we
* don't use it for the XML responses.
*
* The disposition here is "none" or "raw".
*
* The JSON-returning requests, such as ITEM_FIELDS, are not currently
* supported; they should have a disposition of their own.
*/
else {
BasicResponseHandler brh = new BasicResponseHandler();
String resp;
try {
if ("post".equals(method)) {
resp = client.execute(post, brh);
} else if ("put".equals(method)) {
resp = client.execute(put, brh);
} else if ("delete".equals(method)) {
resp = client.execute(delete, brh);
} else {
// We fall back on GET here, but there really
// shouldn't be anything else, so we throw in that case
// for good measure
if (!"get".equals(method)) {
throw new APIException(APIException.INVALID_METHOD,
"Unexpected method: "+method, this);
}
resp = client.execute(get, brh);
}
} catch (IOException e) {
StringBuilder sb = new StringBuilder();
for (StackTraceElement el : e.getStackTrace()) {
sb.append(el.toString()+"\n");
}
recordAttempt(db);
throw new APIException(APIException.HTTP_ERROR,
"An IOException was thrown: " + sb.toString(), this);
}
if ("raw".equals(disposition)) {
/*
* The output should be a newline-delimited set of alphanumeric
* keys.
*/
String[] keys = resp.split("\n");
ArrayList<String> missing = new ArrayList<String>();
if (type == ITEMS_ALL ||
type == ITEMS_FOR_COLLECTION) {
// Try to get a parent collection
// Our query looks like this:
// /users/5770/collections/2AJUSIU9/items
int colloc = query.indexOf("/collections/");
int itemloc = query.indexOf("/items");
// The string "/collections/" is thirteen characters long
ItemCollection coll = ItemCollection.load(
query.substring(colloc+13, itemloc), db);
if (coll != null) {
coll.loadChildren(db);
// If this is a collection's key listing, we first look
// for any synced keys we have that aren't in the list
ArrayList<String> keyAL = new ArrayList<String>(Arrays.asList(keys));
ArrayList<Item> notThere = coll.notInKeys(keyAL);
// We should then remove those memberships
for (Item i : notThere) {
coll.remove(i, true, db);
}
}
ArrayList<Item> recd = new ArrayList<Item>();
for (int j = 0; j < keys.length; j++) {
Item got = Item.load(keys[j], db);
if (got == null) {
missing.add(keys[j]);
} else {
// We can update the collection membership immediately
if (coll != null) coll.add(got, true, db);
recd.add(got);
}
}
if (coll != null) {
coll.saveChildren(db);
coll.save(db);
}
Log.d(TAG, "Received "+keys.length+" keys, "+missing.size() + " missing ones");
Log.d(TAG, "Have "+(double) recd.size() / keys.length + " of list");
if (recd.size() == keys.length) {
Log.d(TAG, "No new items");
succeeded(db);
} else if ((double) recd.size() / keys.length < REREQUEST_CUTOFF) {
Log.d(TAG, "Requesting full list");
APIRequest mReq;
if (type == ITEMS_FOR_COLLECTION) {
mReq = fetchItems(coll, false, cred);
} else {
mReq = fetchItems(false, cred);
}
mReq.status = REQ_NEW;
mReq.save(db);
} else {
Log.d(TAG, "Requesting "+missing.size()+" items one by one");
APIRequest mReq;
for (String key : missing) {
// Queue request for the missing key
mReq = fetchItem(key, cred);
mReq.status = REQ_NEW;
mReq.save(db);
}
// Queue request for the collection again, by key
// XXX This is not the best way to make sure these
// items are put in the correct collection.
if (type == ITEMS_FOR_COLLECTION) {
fetchItems(coll, true, cred).save(db);
}
}
} else if (type == ITEMS_CHILDREN) {
// Try to get a parent item
// Our query looks like this:
// /users/5770/items/2AJUSIU9/children
int itemloc = query.indexOf("/items/");
int childloc = query.indexOf("/children");
// The string "/items/" is seven characters long
Item item = Item.load(
query.substring(itemloc+7, childloc), db);
ArrayList<Attachment> recd = new ArrayList<Attachment>();
for (int j = 0; j < keys.length; j++) {
Attachment got = Attachment.load(keys[j], db);
if (got == null) missing.add(keys[j]);
else recd.add(got);
}
if ((double) recd.size() / keys.length < REREQUEST_CUTOFF) {
APIRequest mReq;
mReq = cred.prep(children(item));
mReq.status = REQ_NEW;
mReq.save(db);
} else {
APIRequest mReq;
for (String key : missing) {
// Queue request for the missing key
mReq = fetchItem(key, cred);
mReq.status = REQ_NEW;
mReq.save(db);
}
}
}
} else if ("json".equals(disposition)) {
// TODO
} else {
/* Here, disposition should be "none" */
// Nothing to be done.
}
getHandler().onComplete(this);
}
}
|
diff --git a/src/java-server-framework/org/xins/server/XSLTCallingConvention.java b/src/java-server-framework/org/xins/server/XSLTCallingConvention.java
index cead8c519..e34693bdc 100644
--- a/src/java-server-framework/org/xins/server/XSLTCallingConvention.java
+++ b/src/java-server-framework/org/xins/server/XSLTCallingConvention.java
@@ -1,419 +1,419 @@
/*
* $Id$
*
* Copyright 2003-2005 Wanadoo Nederland B.V.
* See the COPYRIGHT file for redistribution and use restrictions.
*/
package org.xins.server;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringReader;
import java.io.Writer;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Templates;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.xins.common.Utils;
import org.xins.common.collections.InvalidPropertyValueException;
import org.xins.common.collections.MissingRequiredPropertyException;
import org.xins.common.collections.PropertyReader;
import org.xins.common.io.FastStringWriter;
import org.xins.common.manageable.InitializationException;
import org.xins.common.text.TextUtils;
import org.xins.logdoc.ExceptionUtils;
/**
* XSLT calling convention.
* The XSLT calling convention input is the same as for the standard calling
* convention. The XSLT calling convention output is the result of the XML
* normally returned by the standard calling convention and the specified
* XSLT.
* The Mime type of the return data can be specified in the XSLT using the
* media-type or method attribute of the XSL output element.
* More information about the XSLT calling conventino can be found in the
* <a href="http://www.xins.org/docs/index.html">user guide</a>.
*
* @version $Revision$ $Date$
* @author Anthony Goubard (<a href="mailto:[email protected]">[email protected]</a>)
* @author Ernst de Haan (<a href="mailto:[email protected]">[email protected]</a>)
*/
class XSLTCallingConvention extends StandardCallingConvention {
//-------------------------------------------------------------------------
// Class fields
//-------------------------------------------------------------------------
/**
* The name of the runtime property that defines if the templates should be
* cached. Should be either <code>"true"</code> or <code>"false"</code>.
* By default the cache is enabled.
*/
private final static String TEMPLATES_CACHE_PROPERTY = "templates.cache";
/**
* The name of the runtime property that defines the location of the XSLT
* templates. Should indicate a directory, either locally or remotely.
* Local locations will be interpreted as relative to the user home
* directory. The value should be a URL or a relative directory.
*
* <p>Examples of valid locations include:
*
* <ul>
* <li><code>projects/dubey/xslt/</code></li>
* <li><code>file:///home/john.doe/projects/dubey/xslt/</code></li>
* <li><code>http://johndoe.com/projects/dubey/xslt/</code></li>
* <li><code>https://xslt.johndoe.com/</code></li>
* </ul>
*/
private final static String TEMPLATES_LOCATION_PROPERTY = "templates.callingconvention.source";
/**
* The name of the input parameter that specifies the location of the XSLT
* template to use.
*/
final static String TEMPLATE_PARAMETER = "_template";
/**
* The name of the input parameter used to clear the template cache.
*/
final static String CLEAR_TEMPLATE_CACHE_PARAMETER = "_cleartemplatecache";
//-------------------------------------------------------------------------
// Class functions
//-------------------------------------------------------------------------
//-------------------------------------------------------------------------
// Constructors
//-------------------------------------------------------------------------
/**
* Constructs a new <code>XSLTCallingConvention</code> object.
*/
XSLTCallingConvention() {
// Create the transformer factory
_factory = TransformerFactory.newInstance();
_factory.setURIResolver(new URIResolver());
// Initialize the template cache
_templateCache = new HashMap(89);
}
//-------------------------------------------------------------------------
// Fields
//-------------------------------------------------------------------------
/**
* The XSLT transformer. Never <code>null</code>.
*/
private final TransformerFactory _factory;
/**
* Flag that indicates whether the templates should be cached. This field
* is set during initialization.
*/
private boolean _cacheTemplates;
/**
* Location of the XSLT templates. This field is initially
* <code>null</code> and set during initialization.
*/
private String _location;
/**
* Cache for the XSLT templates. Never <code>null</code>.
*/
private Map _templateCache;
//-------------------------------------------------------------------------
// Methods
//-------------------------------------------------------------------------
protected void initImpl(PropertyReader runtimeProperties)
throws MissingRequiredPropertyException,
InvalidPropertyValueException,
InitializationException {
// Determine if the template cache should be enabled
String cacheEnabled = runtimeProperties.get(TEMPLATES_CACHE_PROPERTY);
initCacheEnabled(cacheEnabled);
// Get the base directory of the style sheets.
initXSLTLocation(runtimeProperties);
}
/**
* Determines if the template cache should be enabled. If no value is
* passed, then by default the cache is enabled. An invalid value, however,
* will trigger an {@link InvalidPropertyValueException}.
*
* @param cacheEnabled
* the value of the runtime property that specifies whether the cache
* should be enabled, can be <code>null</code>.
*
* @throws InvalidPropertyValueException
* if the value is incorrect.
*/
private void initCacheEnabled(String cacheEnabled)
throws InvalidPropertyValueException {
// By default, the template cache is enabled
if (TextUtils.isEmpty(cacheEnabled)) {
_cacheTemplates = true;
// Trim before comparing with 'true' and 'false'
} else {
cacheEnabled = cacheEnabled.trim();
if ("true".equals(cacheEnabled)) {
_cacheTemplates = true;
} else if ("false".equals(cacheEnabled)) {
_cacheTemplates = false;
} else {
throw new InvalidPropertyValueException(TEMPLATES_CACHE_PROPERTY,
cacheEnabled, "Expected either \"true\" or \"false\".");
}
}
// Log whether the cache is enabled or not
if (_cacheTemplates) {
Log.log_3440();
} else {
Log.log_3441();
}
}
/**
* Initializes the location for the XSLT templates. Examples include:
*
* <ul>
* <li><code>http://xslt.mycompany.com/myapi/</code></li>
* <li><code>file:///c:/home/</code></li>
* </ul>
*
* <p>XSLT template files must match the names of the corresponding
* functions.
*
* @param runtimeProperties
* the runtime properties, cannot be <code>null</code>.
*
* @throws NullPointerException
* if <code>runtimeProperties == null</code>.
*/
private void initXSLTLocation(PropertyReader runtimeProperties) {
// Get the value of the property
_location = runtimeProperties.get(TEMPLATES_LOCATION_PROPERTY);
// If the value is not a URL, it's considered as a relative path.
// Relative URLs use the user directory as base dir.
if (TextUtils.isEmpty(_location) || _location.indexOf("://") == -1) {
// Trim the location and make sure it's never null
_location = TextUtils.trim(_location, "");
// Attempt to convert the home directory to a URL
String home = System.getProperty("user.dir");
String homeURL = "";
try {
homeURL = new File(home).toURL().toString();
// If the conversion to a URL failed, then just use the original
} catch (IOException exception) {
Utils.logIgnoredException(
XSLTCallingConvention.class.getName(), "initImpl",
"java.io.File", "toURL()",
exception);
}
// Prepend the home directory URL
_location = homeURL + _location;
}
// Log the base directory for XSLT templates
Log.log_3442(_location);
}
protected void convertResultImpl(FunctionResult xinsResult,
HttpServletResponse httpResponse,
HttpServletRequest httpRequest)
throws IOException {
// If the request is to clear the cache, just clear the cache.
if ("true".equals(httpRequest.getParameter(CLEAR_TEMPLATE_CACHE_PARAMETER))) {
_templateCache.clear();
PrintWriter out = httpResponse.getWriter();
out.write("Done.");
out.close();
return;
}
// Get the XML output similar to the standard calling convention.
FastStringWriter xmlOutput = new FastStringWriter();
CallResultOutputter.output(xmlOutput, xinsResult, false);
xmlOutput.close();
// Get the location of the XSLT file.
String xsltLocation = httpRequest.getParameter(TEMPLATE_PARAMETER);
if (xsltLocation == null) {
xsltLocation = _location + httpRequest.getParameter("_function") + ".xslt";
}
try {
// Load the template or get it from the cache.
Templates templates = null;
- if (!_cacheTemplates && _templateCache.containsKey(xsltLocation)) {
+ if (_cacheTemplates && _templateCache.containsKey(xsltLocation)) {
templates = (Templates) _templateCache.get(xsltLocation);
} else {
templates = _factory.newTemplates(_factory.getURIResolver().resolve(xsltLocation, _location));
if (_cacheTemplates) {
_templateCache.put(xsltLocation, templates);
}
}
// Proceed to the transformation.
Transformer xformer = templates.newTransformer();
Source source = new StreamSource(new StringReader(xmlOutput.toString()));
Writer buffer = new FastStringWriter(1024);
Result result = new StreamResult(buffer);
xformer.transform(source, result);
// Determine the MIME type for the output.
Properties outputProperties = templates.getOutputProperties();
String mimeType = outputProperties.getProperty("media-type");
if (mimeType == null) {
String method = outputProperties.getProperty("method");
if ("xml".equals(method)) {
mimeType = "text/xml";
} else if ("html".equals(method)) {
mimeType = "text/html";
} else if ("text".equals(method)) {
mimeType = "text/plain";
}
}
String encoding = outputProperties.getProperty("encoding");
if (mimeType != null && encoding != null) {
mimeType += ";charset=" + encoding;
}
if (mimeType != null) {
httpResponse.setContentType(mimeType);
}
httpResponse.setStatus(HttpServletResponse.SC_OK);
PrintWriter out = httpResponse.getWriter();
out.print(buffer.toString());
out.close();
} catch (Exception exception) {
if (exception instanceof IOException) {
throw (IOException) exception;
} else {
String message = "Cannot transform the result with the XSLT "
+ "located at \""
+ xsltLocation
+ "\".";
IOException ioe = new IOException(message);
ExceptionUtils.setCause(ioe, exception);
throw ioe;
}
}
}
//-------------------------------------------------------------------------
// Inner classes
//-------------------------------------------------------------------------
/**
* Class used to revolved URL locations when an SLT file refers to another
* XSLT file using a relative URL.
*
* @version $Revision$ $Date$
* @author Anthony Goubard (<a href="mailto:[email protected]">[email protected]</a>)
*/
static class URIResolver implements javax.xml.transform.URIResolver {
//----------------------------------------------------------------------
// Constructors
//----------------------------------------------------------------------
//----------------------------------------------------------------------
// Fields
//----------------------------------------------------------------------
/**
* The base directory of the previous call to resolve, if any. Cannot be <code>null</code>.
*/
private String _base = "";
//----------------------------------------------------------------------
// Methods
//----------------------------------------------------------------------
/**
* Revolves a hyperlink reference.
*
* @param href
* the hyperlink to resolve, cannot be <code>null</code>.
*
* @param base
* the base URI in effect when the href attribute was encountered,
* can be <code>null</code>.
*
* @return
* a {@link Source} object, or <code>null</code> if the href cannot
* be resolved, and the processor should try to resolve the URI
* itself.
*
* @throws TransformerException
* if an error occurs when trying to resolve the URI.
*/
public Source resolve(String href, String base)
throws TransformerException {
// If no base is specified, use the last location.
if (base == null) {
base = _base;
// The base should always ends with a slash.
} else if (! base.endsWith("/")) {
base += '/';
}
_base = base;
// Result the URL
String url = null;
if (href.indexOf(":/") == -1) {
url = base + href;
} else {
url = href;
_base = href.substring(0, href.lastIndexOf('/') + 1);
}
// Return the source of the resolved XSLT.
try {
return new StreamSource(new URL(url).openStream());
} catch (IOException ioe) {
throw new TransformerException(ioe);
}
}
}
}
| true | true | protected void convertResultImpl(FunctionResult xinsResult,
HttpServletResponse httpResponse,
HttpServletRequest httpRequest)
throws IOException {
// If the request is to clear the cache, just clear the cache.
if ("true".equals(httpRequest.getParameter(CLEAR_TEMPLATE_CACHE_PARAMETER))) {
_templateCache.clear();
PrintWriter out = httpResponse.getWriter();
out.write("Done.");
out.close();
return;
}
// Get the XML output similar to the standard calling convention.
FastStringWriter xmlOutput = new FastStringWriter();
CallResultOutputter.output(xmlOutput, xinsResult, false);
xmlOutput.close();
// Get the location of the XSLT file.
String xsltLocation = httpRequest.getParameter(TEMPLATE_PARAMETER);
if (xsltLocation == null) {
xsltLocation = _location + httpRequest.getParameter("_function") + ".xslt";
}
try {
// Load the template or get it from the cache.
Templates templates = null;
if (!_cacheTemplates && _templateCache.containsKey(xsltLocation)) {
templates = (Templates) _templateCache.get(xsltLocation);
} else {
templates = _factory.newTemplates(_factory.getURIResolver().resolve(xsltLocation, _location));
if (_cacheTemplates) {
_templateCache.put(xsltLocation, templates);
}
}
// Proceed to the transformation.
Transformer xformer = templates.newTransformer();
Source source = new StreamSource(new StringReader(xmlOutput.toString()));
Writer buffer = new FastStringWriter(1024);
Result result = new StreamResult(buffer);
xformer.transform(source, result);
// Determine the MIME type for the output.
Properties outputProperties = templates.getOutputProperties();
String mimeType = outputProperties.getProperty("media-type");
if (mimeType == null) {
String method = outputProperties.getProperty("method");
if ("xml".equals(method)) {
mimeType = "text/xml";
} else if ("html".equals(method)) {
mimeType = "text/html";
} else if ("text".equals(method)) {
mimeType = "text/plain";
}
}
String encoding = outputProperties.getProperty("encoding");
if (mimeType != null && encoding != null) {
mimeType += ";charset=" + encoding;
}
if (mimeType != null) {
httpResponse.setContentType(mimeType);
}
httpResponse.setStatus(HttpServletResponse.SC_OK);
PrintWriter out = httpResponse.getWriter();
out.print(buffer.toString());
out.close();
} catch (Exception exception) {
if (exception instanceof IOException) {
throw (IOException) exception;
} else {
String message = "Cannot transform the result with the XSLT "
+ "located at \""
+ xsltLocation
+ "\".";
IOException ioe = new IOException(message);
ExceptionUtils.setCause(ioe, exception);
throw ioe;
}
}
}
| protected void convertResultImpl(FunctionResult xinsResult,
HttpServletResponse httpResponse,
HttpServletRequest httpRequest)
throws IOException {
// If the request is to clear the cache, just clear the cache.
if ("true".equals(httpRequest.getParameter(CLEAR_TEMPLATE_CACHE_PARAMETER))) {
_templateCache.clear();
PrintWriter out = httpResponse.getWriter();
out.write("Done.");
out.close();
return;
}
// Get the XML output similar to the standard calling convention.
FastStringWriter xmlOutput = new FastStringWriter();
CallResultOutputter.output(xmlOutput, xinsResult, false);
xmlOutput.close();
// Get the location of the XSLT file.
String xsltLocation = httpRequest.getParameter(TEMPLATE_PARAMETER);
if (xsltLocation == null) {
xsltLocation = _location + httpRequest.getParameter("_function") + ".xslt";
}
try {
// Load the template or get it from the cache.
Templates templates = null;
if (_cacheTemplates && _templateCache.containsKey(xsltLocation)) {
templates = (Templates) _templateCache.get(xsltLocation);
} else {
templates = _factory.newTemplates(_factory.getURIResolver().resolve(xsltLocation, _location));
if (_cacheTemplates) {
_templateCache.put(xsltLocation, templates);
}
}
// Proceed to the transformation.
Transformer xformer = templates.newTransformer();
Source source = new StreamSource(new StringReader(xmlOutput.toString()));
Writer buffer = new FastStringWriter(1024);
Result result = new StreamResult(buffer);
xformer.transform(source, result);
// Determine the MIME type for the output.
Properties outputProperties = templates.getOutputProperties();
String mimeType = outputProperties.getProperty("media-type");
if (mimeType == null) {
String method = outputProperties.getProperty("method");
if ("xml".equals(method)) {
mimeType = "text/xml";
} else if ("html".equals(method)) {
mimeType = "text/html";
} else if ("text".equals(method)) {
mimeType = "text/plain";
}
}
String encoding = outputProperties.getProperty("encoding");
if (mimeType != null && encoding != null) {
mimeType += ";charset=" + encoding;
}
if (mimeType != null) {
httpResponse.setContentType(mimeType);
}
httpResponse.setStatus(HttpServletResponse.SC_OK);
PrintWriter out = httpResponse.getWriter();
out.print(buffer.toString());
out.close();
} catch (Exception exception) {
if (exception instanceof IOException) {
throw (IOException) exception;
} else {
String message = "Cannot transform the result with the XSLT "
+ "located at \""
+ xsltLocation
+ "\".";
IOException ioe = new IOException(message);
ExceptionUtils.setCause(ioe, exception);
throw ioe;
}
}
}
|
diff --git a/src/main/java/com/atlassian/labs/speakeasy/install/convention/ConventionDescriptorGeneratorServiceFactory.java b/src/main/java/com/atlassian/labs/speakeasy/install/convention/ConventionDescriptorGeneratorServiceFactory.java
index e658516..ea69402 100644
--- a/src/main/java/com/atlassian/labs/speakeasy/install/convention/ConventionDescriptorGeneratorServiceFactory.java
+++ b/src/main/java/com/atlassian/labs/speakeasy/install/convention/ConventionDescriptorGeneratorServiceFactory.java
@@ -1,176 +1,179 @@
package com.atlassian.labs.speakeasy.install.convention;
import com.atlassian.labs.speakeasy.descriptor.DescriptorGeneratorManager;
import com.atlassian.labs.speakeasy.descriptor.SpeakeasyWebResourceModuleDescriptor;
import com.atlassian.labs.speakeasy.commonjs.descriptor.SpeakeasyCommonJsModulesDescriptor;
import com.atlassian.labs.speakeasy.install.PluginOperationFailedException;
import com.atlassian.labs.speakeasy.install.convention.external.ConventionDescriptorGenerator;
import com.atlassian.labs.speakeasy.descriptor.webfragment.SpeakeasyWebItemModuleDescriptor;
import com.atlassian.labs.speakeasy.model.JsonManifest;
import com.atlassian.plugin.*;
import com.atlassian.plugin.event.PluginEventManager;
import com.atlassian.plugin.hostcontainer.HostContainer;
import com.atlassian.plugin.osgi.util.OsgiHeaderUtil;
import com.atlassian.plugin.webresource.WebResourceManager;
import com.atlassian.plugin.webresource.WebResourceModuleDescriptor;
import org.dom4j.DocumentFactory;
import org.dom4j.Element;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceFactory;
import org.osgi.framework.ServiceRegistration;
import static com.google.common.collect.Sets.newHashSet;
/**
*
*/
public class ConventionDescriptorGeneratorServiceFactory implements ServiceFactory
{
private final BundleContext bundleContext;
private final PluginAccessor pluginAccessor;
private final HostContainer hostContainer;
private final DescriptorGeneratorManager descriptorGeneratorManager;
private final PluginEventManager pluginEventManager;
private final JsonToElementParser jsonToElementParser;
private final WebResourceManager webResourceManager;
private final JsonManifestHandler jsonManifestHandler;
private final PluginController pluginController;
//private final Set<String> trackedPlugins = new CopyOnWriteArraySet<String>();
public ConventionDescriptorGeneratorServiceFactory(final BundleContext bundleContext, final PluginAccessor pluginAccessor, HostContainer hostContainer, DescriptorGeneratorManager descriptorGeneratorManager, JsonToElementParser jsonToElementParser, WebResourceManager webResourceManager, PluginEventManager pluginEventManager, final PluginController pluginController, JsonManifestHandler jsonManifestHandler)
{
this.bundleContext = bundleContext;
this.pluginAccessor = pluginAccessor;
this.hostContainer = hostContainer;
this.descriptorGeneratorManager = descriptorGeneratorManager;
this.jsonToElementParser = jsonToElementParser;
this.pluginEventManager = pluginEventManager;
this.webResourceManager = webResourceManager;
this.pluginController = pluginController;
this.jsonManifestHandler = jsonManifestHandler;
}
public Object getService(Bundle bundle, ServiceRegistration registration)
{
DocumentFactory factory = DocumentFactory.getInstance();
String pluginKey = OsgiHeaderUtil.getPluginKey(bundle);
Plugin plugin = pluginAccessor.getPlugin(pluginKey);
if (bundle.getEntry("atlassian-extension.json") != null)
{
JsonManifest mf = jsonManifestHandler.read(plugin);
- registerScreenshotWebResourceDescriptor(bundle, factory, plugin, mf.getScreenshot());
+ if (mf.getScreenshot() != null)
+ {
+ registerScreenshotWebResourceDescriptor(bundle, factory, plugin, mf.getScreenshot());
+ }
}
if (bundle.getEntry("js/") != null)
{
SpeakeasyCommonJsModulesDescriptor descriptor = new SpeakeasyCommonJsModulesDescriptor(
bundleContext, hostContainer, descriptorGeneratorManager, pluginAccessor);
Element modules = factory.createElement("scoped-modules")
.addAttribute("key", "modules")
.addAttribute("location", "js");
if (bundle.getEntry("css/") != null)
{
modules.addElement("dependency").setText("css");
}
descriptor.init(plugin, modules);
bundle.getBundleContext().registerService(ModuleDescriptor.class.getName(), descriptor, null);
}
if (bundle.getEntry("images/") != null)
{
registerSpeakeasyWebResourceDescriptor(bundle, factory, plugin, "images");
}
if (bundle.getEntry("css") != null)
{
registerSpeakeasyWebResourceDescriptor(bundle, factory, plugin, "css");
}
if (bundle.getEntry("ui/web-items.json") != null)
{
registerSpeakeasyWebItems(bundle, plugin);
}
//trackedPlugins.add(pluginKey);
return new ConventionDescriptorGenerator()
{
};
}
private void registerSpeakeasyWebItems(Bundle bundle, Plugin plugin)
{
try
{
for (Element element : jsonToElementParser.createWebItems(plugin.getResourceAsStream("ui/web-items.json")))
{
SpeakeasyWebItemModuleDescriptor descriptor = new SpeakeasyWebItemModuleDescriptor(bundleContext, descriptorGeneratorManager, webResourceManager);
descriptor.init(plugin, element);
bundle.getBundleContext().registerService(ModuleDescriptor.class.getName(), descriptor, null);
}
}
catch (PluginOperationFailedException e)
{
e.setPluginKey(plugin.getKey());
throw e;
}
}
private void registerScreenshotWebResourceDescriptor(Bundle bundle, DocumentFactory factory, Plugin plugin, String screenshotPath)
{
WebResourceModuleDescriptor descriptor = new WebResourceModuleDescriptor(hostContainer);
Element element = factory.createElement("web-resource")
.addAttribute("key", "screenshot");
element.addElement("resource")
.addAttribute("type", "download")
.addAttribute("name", "screenshot.png")
.addAttribute("location", screenshotPath);
descriptor.init(plugin, element);
bundle.getBundleContext().registerService(ModuleDescriptor.class.getName(), descriptor, null);
}
private void registerSpeakeasyWebResourceDescriptor(Bundle bundle, DocumentFactory factory, Plugin plugin, String type)
{
SpeakeasyWebResourceModuleDescriptor descriptor = new SpeakeasyWebResourceModuleDescriptor(hostContainer, bundleContext, descriptorGeneratorManager);
Element element = factory.createElement("scoped-web-resource")
.addAttribute("key", type)
.addAttribute("scan", "/" + type);
element.addElement("transformation")
.addAttribute("extension", "css")
.addElement("transformer")
.addAttribute("key", "cssVariables")
.addAttribute("imagesModuleKey", plugin.getKey() + ":" + "images-" + bundle.getLastModified())
.addAttribute("fullModuleKey", plugin.getKey() + ":" + "css-" + bundle.getLastModified());
descriptor.init(plugin, element);
bundle.getBundleContext().registerService(ModuleDescriptor.class.getName(), descriptor, null);
}
public void ungetService(Bundle bundle, ServiceRegistration registration, Object service)
{
final String pluginKey = OsgiHeaderUtil.getPluginKey(bundle);
// Plugin plugin = pluginAccessor.getPlugin(pluginKey);
// if (trackedPlugins.contains(plugin.getKey()))
// {
// for (ModuleDescriptor descriptor : plugin.getModuleDescriptors())
// {
// if (descriptor instanceof StateAware)
// {
// ((StateAware)descriptor).disabled();
// }
// }
// }
//trackedPlugins.remove(pluginKey);
}
}
| true | true | public Object getService(Bundle bundle, ServiceRegistration registration)
{
DocumentFactory factory = DocumentFactory.getInstance();
String pluginKey = OsgiHeaderUtil.getPluginKey(bundle);
Plugin plugin = pluginAccessor.getPlugin(pluginKey);
if (bundle.getEntry("atlassian-extension.json") != null)
{
JsonManifest mf = jsonManifestHandler.read(plugin);
registerScreenshotWebResourceDescriptor(bundle, factory, plugin, mf.getScreenshot());
}
if (bundle.getEntry("js/") != null)
{
SpeakeasyCommonJsModulesDescriptor descriptor = new SpeakeasyCommonJsModulesDescriptor(
bundleContext, hostContainer, descriptorGeneratorManager, pluginAccessor);
Element modules = factory.createElement("scoped-modules")
.addAttribute("key", "modules")
.addAttribute("location", "js");
if (bundle.getEntry("css/") != null)
{
modules.addElement("dependency").setText("css");
}
descriptor.init(plugin, modules);
bundle.getBundleContext().registerService(ModuleDescriptor.class.getName(), descriptor, null);
}
if (bundle.getEntry("images/") != null)
{
registerSpeakeasyWebResourceDescriptor(bundle, factory, plugin, "images");
}
if (bundle.getEntry("css") != null)
{
registerSpeakeasyWebResourceDescriptor(bundle, factory, plugin, "css");
}
if (bundle.getEntry("ui/web-items.json") != null)
{
registerSpeakeasyWebItems(bundle, plugin);
}
//trackedPlugins.add(pluginKey);
return new ConventionDescriptorGenerator()
{
};
}
| public Object getService(Bundle bundle, ServiceRegistration registration)
{
DocumentFactory factory = DocumentFactory.getInstance();
String pluginKey = OsgiHeaderUtil.getPluginKey(bundle);
Plugin plugin = pluginAccessor.getPlugin(pluginKey);
if (bundle.getEntry("atlassian-extension.json") != null)
{
JsonManifest mf = jsonManifestHandler.read(plugin);
if (mf.getScreenshot() != null)
{
registerScreenshotWebResourceDescriptor(bundle, factory, plugin, mf.getScreenshot());
}
}
if (bundle.getEntry("js/") != null)
{
SpeakeasyCommonJsModulesDescriptor descriptor = new SpeakeasyCommonJsModulesDescriptor(
bundleContext, hostContainer, descriptorGeneratorManager, pluginAccessor);
Element modules = factory.createElement("scoped-modules")
.addAttribute("key", "modules")
.addAttribute("location", "js");
if (bundle.getEntry("css/") != null)
{
modules.addElement("dependency").setText("css");
}
descriptor.init(plugin, modules);
bundle.getBundleContext().registerService(ModuleDescriptor.class.getName(), descriptor, null);
}
if (bundle.getEntry("images/") != null)
{
registerSpeakeasyWebResourceDescriptor(bundle, factory, plugin, "images");
}
if (bundle.getEntry("css") != null)
{
registerSpeakeasyWebResourceDescriptor(bundle, factory, plugin, "css");
}
if (bundle.getEntry("ui/web-items.json") != null)
{
registerSpeakeasyWebItems(bundle, plugin);
}
//trackedPlugins.add(pluginKey);
return new ConventionDescriptorGenerator()
{
};
}
|
diff --git a/game/src/main/java/org/geekygoblin/nedetlesmaki/game/systems/GameSystem.java b/game/src/main/java/org/geekygoblin/nedetlesmaki/game/systems/GameSystem.java
index cb3c59d..2100eb2 100644
--- a/game/src/main/java/org/geekygoblin/nedetlesmaki/game/systems/GameSystem.java
+++ b/game/src/main/java/org/geekygoblin/nedetlesmaki/game/systems/GameSystem.java
@@ -1,330 +1,330 @@
/*
* Copyright © 2013, Pierre Marijon <[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 X 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.geekygoblin.nedetlesmaki.game.systems;
import javax.inject.Inject;
import javax.inject.Singleton;
import java.util.ArrayList;
import java.util.Iterator;
import com.artemis.Entity;
import com.artemis.ComponentMapper;
import com.artemis.annotations.Mapper;
import com.artemis.systems.VoidEntitySystem;
import com.artemis.utils.ImmutableBag;
import org.geekygoblin.nedetlesmaki.game.components.gamesystems.Color;
import org.geekygoblin.nedetlesmaki.game.components.gamesystems.Pushable;
import org.geekygoblin.nedetlesmaki.game.components.gamesystems.Pusher;
import org.geekygoblin.nedetlesmaki.game.components.gamesystems.Position;
import org.geekygoblin.nedetlesmaki.game.components.gamesystems.Movable;
import org.geekygoblin.nedetlesmaki.game.components.gamesystems.BlockOnPlate;
import org.geekygoblin.nedetlesmaki.game.components.gamesystems.StopOnPlate;
import org.geekygoblin.nedetlesmaki.game.components.gamesystems.Square;
import org.geekygoblin.nedetlesmaki.game.components.gamesystems.Plate;
import org.geekygoblin.nedetlesmaki.game.components.gamesystems.Boostable;
import org.geekygoblin.nedetlesmaki.game.manager.EntityIndexManager;
import org.geekygoblin.nedetlesmaki.game.utils.PosOperation;
import org.geekygoblin.nedetlesmaki.game.utils.Mouvement;
import org.geekygoblin.nedetlesmaki.game.constants.AnimationType;
import org.geekygoblin.nedetlesmaki.game.Game;
import org.geekygoblin.nedetlesmaki.game.constants.ColorType;
/**
*
* @author natir
*/
@Singleton
public class GameSystem extends VoidEntitySystem {
private EntityIndexManager index;
private boolean run;
@Mapper
ComponentMapper<Pushable> pushableMapper;
@Mapper
ComponentMapper<Pusher> pusherMapper;
@Mapper
ComponentMapper<Position> positionMapper;
@Mapper
ComponentMapper<Movable> movableMapper;
@Mapper
ComponentMapper<Plate> plateMapper;
@Mapper
ComponentMapper<Color> colorMapper;
@Mapper
ComponentMapper<Boostable> boostMapper;
@Mapper
ComponentMapper<BlockOnPlate> blockOnPlateMapper;
@Mapper
ComponentMapper<StopOnPlate> stopOnPlateMapper;
@Inject
public GameSystem(EntityIndexManager index) {
this.index = index;
this.run = false;
}
@Override
protected void processSystem() {
if(this.run) {
this.endOfLevel();
}
}
public ArrayList<Mouvement> moveEntity(Entity e, Position dirP) {
this.run = true;
/*Check if move possible*/
Position oldP = this.getPosition(e);
ArrayList<Mouvement> mouv = new ArrayList<Mouvement>();
for (int i = 0; i != this.getMovable(e); i++) {
Position newP = PosOperation.sum(oldP, dirP);
- if (i > this.getBoost(e)) {
+ if (i > this.getBoost(e) - 1) {
e.getComponent(Pusher.class).setPusher(true);
}
if (this.positionIsVoid(newP)) {
Square s = index.getSquare(newP.getX(), newP.getY());
if (this.testStopOnPlate(e, s)) {
mouv.add(runValideMove(oldP, newP, e));
if (this.getBoost(e) != 20) {
e.getComponent(Pusher.class).setPusher(false);
}
return mouv;
}
if (!this.testBlockedPlate(e, s)) {
mouv.add(runValideMove(oldP, newP, e));
}
} else {
if (this.isPusherEntity(e)) {
ArrayList<Entity> aNextE = index.getSquare(newP.getX(), newP.getY()).getWith(Pushable.class);
if (!aNextE.isEmpty()) {
Entity nextE = aNextE.get(0);
if (this.isPushableEntity(nextE)) {
ArrayList<Mouvement> recMouv = this.moveEntity(nextE, dirP);
if(recMouv.size() != 0) {
mouv.addAll(recMouv);
mouv.add(runValideMove(oldP, newP, e));
}
}
}
}
if (this.getBoost(e) != 20) {
e.getComponent(Pusher.class).setPusher(false);
}
return mouv;
}
}
return mouv;
}
private Mouvement runValideMove(Position oldP, Position newP, Entity e) {
if (index.moveEntity(oldP.getX(), oldP.getY(), newP.getX(), newP.getY())) {
Position diff = PosOperation.deduction(newP, oldP);
Mouvement m = new Mouvement(e).addPosition(diff).addAnimation(AnimationType.no);
if (e == ((Game) this.world).getNed()) {
if (diff.getX() > 0) {
m = new Mouvement(e).addPosition(diff).addAnimation(AnimationType.ned_right);
} else if (diff.getX() < 0) {
m = new Mouvement(e).addPosition(diff).addAnimation(AnimationType.ned_left);
} else if (diff.getY() > 0) {
m = new Mouvement(e).addPosition(diff).addAnimation(AnimationType.ned_down);
} else if (diff.getY() < 0) {
m = new Mouvement(e).addPosition(diff).addAnimation(AnimationType.ned_up);
}
}
e.getComponent(Position.class).setX(newP.getX());
e.getComponent(Position.class).setY(newP.getY());
return m;
}
return null;
}
private boolean testStopOnPlate(Entity eMove, Square obj) {
if (obj == null) {
return false;
}
ArrayList<Entity> array = obj.getWith(Plate.class);
if (array.size() == 0) {
return false;
}
Entity plate = obj.getWith(Plate.class).get(0);
Plate p = plateMapper.getSafe(plate);
StopOnPlate b = stopOnPlateMapper.getSafe(eMove);
if (b == null) {
return false;
}
if (p.isPlate()) {
if (b.stop()) {
if (this.colorMapper.getSafe(plate).getColor() == this.colorMapper.getSafe(eMove).getColor() && this.colorMapper.getSafe(eMove).getColor() != ColorType.orange) {
return true;
}
}
}
return false;
}
private boolean testBlockedPlate(Entity eMove, Square obj) {
if (obj == null) {
return false;
}
ArrayList<Entity> array = obj.getWith(Plate.class);
if (array.size() == 0) {
return false;
}
Entity plate = obj.getWith(Plate.class).get(0);
Plate p = plate.getComponent(Plate.class);
BlockOnPlate b = blockOnPlateMapper.getSafe(eMove);
if (b == null) {
return false;
}
if (p.isPlate()) {
if (b.block()) {
return true;
}
}
return false;
}
public boolean positionIsVoid(Position p) {
Square s = index.getSquare(p.getX(), p.getY());
if (s != null) {
ArrayList<Entity> plate = s.getWith(Plate.class);
ArrayList<Entity> all = s.getAll();
if (all.size() == plate.size()) {
return true;
} else {
return false;
}
}
return true;
}
public boolean isPushableEntity(Entity e) {
Pushable p = this.pushableMapper.getSafe(e);
if (p != null) {
if (p.isPushable()) {
return true;
}
}
return false;
}
public boolean isPusherEntity(Entity e) {
Pusher p = this.pusherMapper.getSafe(e);
if (p != null) {
if (p.isPusher()) {
return true;
}
}
return false;
}
public Position getPosition(Entity e) {
Position p = this.positionMapper.getSafe(e);
if (p != null) {
return p;
}
return new Position(-1, -1);
}
public int getMovable(Entity e) {
Movable m = this.movableMapper.getSafe(e);
if (m != null) {
return m.getNbCase();
}
return 0;
}
public int getBoost(Entity e) {
Boostable b = this.boostMapper.getSafe(e);
if (b != null) {
return b.getNbCase();
}
return 20;
}
private void endOfLevel() {
ImmutableBag<Entity> plateGroup = this.index.getAllPlate();
for (int i = 0; i != plateGroup.size(); i++) {
Entity platE = plateGroup.get(i);
Plate plate = this.plateMapper.getSafe(platE);
Position p = this.positionMapper.getSafe(platE);
Color colorPlate = this.colorMapper.getSafe(platE);
ArrayList<Entity> colorEntity = this.index.getSquare(p.getX(), p.getY()).getWith(Color.class);
if (colorEntity.size() == 2) {
Color colorA = this.colorMapper.getSafe(colorEntity.get(0));
Color colorB = this.colorMapper.getSafe(colorEntity.get(1));
if (colorA != colorB && !plate.isPlate()) {
return;
}
} else {
return;
}
}
System.out.print("End of level\n");
}
}
| true | true | public ArrayList<Mouvement> moveEntity(Entity e, Position dirP) {
this.run = true;
/*Check if move possible*/
Position oldP = this.getPosition(e);
ArrayList<Mouvement> mouv = new ArrayList<Mouvement>();
for (int i = 0; i != this.getMovable(e); i++) {
Position newP = PosOperation.sum(oldP, dirP);
if (i > this.getBoost(e)) {
e.getComponent(Pusher.class).setPusher(true);
}
if (this.positionIsVoid(newP)) {
Square s = index.getSquare(newP.getX(), newP.getY());
if (this.testStopOnPlate(e, s)) {
mouv.add(runValideMove(oldP, newP, e));
if (this.getBoost(e) != 20) {
e.getComponent(Pusher.class).setPusher(false);
}
return mouv;
}
if (!this.testBlockedPlate(e, s)) {
mouv.add(runValideMove(oldP, newP, e));
}
} else {
if (this.isPusherEntity(e)) {
ArrayList<Entity> aNextE = index.getSquare(newP.getX(), newP.getY()).getWith(Pushable.class);
if (!aNextE.isEmpty()) {
Entity nextE = aNextE.get(0);
if (this.isPushableEntity(nextE)) {
ArrayList<Mouvement> recMouv = this.moveEntity(nextE, dirP);
if(recMouv.size() != 0) {
mouv.addAll(recMouv);
mouv.add(runValideMove(oldP, newP, e));
}
}
}
}
if (this.getBoost(e) != 20) {
e.getComponent(Pusher.class).setPusher(false);
}
return mouv;
}
}
return mouv;
}
| public ArrayList<Mouvement> moveEntity(Entity e, Position dirP) {
this.run = true;
/*Check if move possible*/
Position oldP = this.getPosition(e);
ArrayList<Mouvement> mouv = new ArrayList<Mouvement>();
for (int i = 0; i != this.getMovable(e); i++) {
Position newP = PosOperation.sum(oldP, dirP);
if (i > this.getBoost(e) - 1) {
e.getComponent(Pusher.class).setPusher(true);
}
if (this.positionIsVoid(newP)) {
Square s = index.getSquare(newP.getX(), newP.getY());
if (this.testStopOnPlate(e, s)) {
mouv.add(runValideMove(oldP, newP, e));
if (this.getBoost(e) != 20) {
e.getComponent(Pusher.class).setPusher(false);
}
return mouv;
}
if (!this.testBlockedPlate(e, s)) {
mouv.add(runValideMove(oldP, newP, e));
}
} else {
if (this.isPusherEntity(e)) {
ArrayList<Entity> aNextE = index.getSquare(newP.getX(), newP.getY()).getWith(Pushable.class);
if (!aNextE.isEmpty()) {
Entity nextE = aNextE.get(0);
if (this.isPushableEntity(nextE)) {
ArrayList<Mouvement> recMouv = this.moveEntity(nextE, dirP);
if(recMouv.size() != 0) {
mouv.addAll(recMouv);
mouv.add(runValideMove(oldP, newP, e));
}
}
}
}
if (this.getBoost(e) != 20) {
e.getComponent(Pusher.class).setPusher(false);
}
return mouv;
}
}
return mouv;
}
|
diff --git a/WorldTools/src/PlayerTools.java b/WorldTools/src/PlayerTools.java
index 2f8cd88..b921429 100644
--- a/WorldTools/src/PlayerTools.java
+++ b/WorldTools/src/PlayerTools.java
@@ -1,641 +1,644 @@
/*
* WorldTools
* Copyright (C) 2012
*
* 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/>.
*/
import java.io.File;
import java.util.ArrayList;
/**
* @author Spenk & Glacksy
* @category Player Listener
* @version 1.0
*
* @description
* tools for players
* and admins
*
*/
public class PlayerTools extends PluginListener{
ArrayList<String> god = new ArrayList<String>();
ArrayList<String> frozen = new ArrayList<String>();
private static Location exactSpawn = null;
public boolean onCommand(Player Player, String[] split) {
if (split[0].equalsIgnoreCase("/drain")){
if ((Player.canUseCommand("/worldtools"))||Player.canUseCommand("/drain")){
int dist = 0;
if (split.length == 2) try { dist = Integer.parseInt(split[1]); } catch (Throwable localThrowable) {
} if (dist == 0) {
Player.sendMessage("�9[�6-�8-�6-�8-�6-�9Drain Help�6-�8-�6-�8-�6-�9]");
Player.sendMessage("�a/drain <radius> - Drain water/lava");
Player.sendMessage("�a/drainwater <radius> - Drain water");
Player.sendMessage("�a/drainlava <radius> - Drain lava");
Player.sendMessage("�a/ext <radius> - Remove fire"); return true;
}
int radius = 0;
try {radius = Integer.parseInt(split[1]);}catch(NumberFormatException nfe){Player.notify("The correct usage is /drain <radius>");return true;}
int xmin = (int)Player.getX()-radius;
int xmax = (int)Player.getX()+radius;
int ymin = (int)Player.getY()-radius;
int ymax = (int)Player.getY()+radius;
int zmin = (int)Player.getZ()-radius;
int zmax = (int)Player.getZ()+radius;
for (int x = xmin; x <= xmax; x++) {
for (int y = ymin; y <= ymax; y++) {
for (int z = zmin; z <= zmax; z++) {
if (Player.getWorld().getBlockAt(x, y, z).getType() == 8){Player.getWorld().setBlockAt(95, x, y, z);}
if (Player.getWorld().getBlockAt(x, y, z).getType() == 95){Player.getWorld().setBlockAt(9, x, y, z);}
if (Player.getWorld().getBlockAt(x, y, z).getType() == 10){Player.getWorld().setBlockAt(95, x, y, z);}
if (Player.getWorld().getBlockAt(x, y, z).getType() == 95){Player.getWorld().setBlockAt(11, x, y, z);}
}
}
}
Player.sendMessage("�aLava & Water Successfully Drained!");
return true;
}
Player.notify("You cant use this command");return true;
}
if (split[0].equalsIgnoreCase("/drainlava")){
- if ((Player.canUseCommand("/worldtools")) && (Player.canUseCommand("/drainlava"))){
+ if ((Player.canUseCommand("/worldtools")) || (Player.canUseCommand("/drainlava"))){
int dist = 0;
if (split.length == 2) try { dist = Integer.parseInt(split[1]); } catch (Throwable localThrowable1) {
} if (dist == 0) { Player.sendMessage("�cWrong syntax! Usage: /drainlava <radius>"); return true; }
int radius = 0;
try {radius = Integer.parseInt(split[1]);}catch(NumberFormatException nfe){Player.notify("The correct usage is /drainlava <radius>");return true;}
int xmin = (int)Player.getX()-radius;
int xmax = (int)Player.getX()+radius;
int ymin = (int)Player.getY()-radius;
int ymax = (int)Player.getY()+radius;
int zmin = (int)Player.getZ()-radius;
int zmax = (int)Player.getZ()+radius;
for (int x = xmin; x <= xmax; x++) {
for (int y = ymin; y <= ymax; y++) {
for (int z = zmin; z <= zmax; z++) {
if (Player.getWorld().getBlockAt(x, y, z).getType() == 11){Player.getWorld().setBlockAt(95, x, y, z);}
if (Player.getWorld().getBlockAt(x, y, z).getType() == 95){Player.getWorld().setBlockAt(10, x, y, z);}
}
}
}
Player.sendMessage("�aLava Successfully Removed!");
return true;
}
Player.notify("You cant use this command");return true;
}
if (split[0].equalsIgnoreCase("/drainwater")) {
- if ((Player.canUseCommand("/worldtools")) && (Player.canUseCommand("/drainwater"))){
+ if ((Player.canUseCommand("/worldtools")) || (Player.canUseCommand("/drainwater"))){
int dist = 0;
if (split.length == 2) try { dist = Integer.parseInt(split[1]); } catch (Throwable localThrowable2) {
} if (dist == 0) { Player.sendMessage("�cWrong syntax! Usage: /drainwater <radius>"); return true; }
int radius = 0;
try {radius = Integer.parseInt(split[1]);}catch(NumberFormatException nfe){Player.notify("The correct usage is /drainwater <radius>");return true;}
int xmin = (int)Player.getX()-radius;
int xmax = (int)Player.getX()+radius;
int ymin = (int)Player.getY()-radius;
int ymax = (int)Player.getY()+radius;
int zmin = (int)Player.getZ()-radius;
int zmax = (int)Player.getZ()+radius;
for (int x = xmin; x <= xmax; x++) {
for (int y = ymin; y <= ymax; y++) {
for (int z = zmin; z <= zmax; z++) {
if (Player.getWorld().getBlockAt(x, y, z).getType() == 9){Player.getWorld().setBlockAt(95, x, y, z);}
if (Player.getWorld().getBlockAt(x, y, z).getType() == 95){Player.getWorld().setBlockAt(8, x, y, z);}
}
}
}
Player.sendMessage("�aWater Successfully Removed!");
return true;
}
Player.notify("You cant use this command");return true;
}
if (split[0].equalsIgnoreCase("/ext")) {
- if ((Player.canUseCommand("/worldtools")) && (Player.canUseCommand("/ext"))){
+ if ((Player.canUseCommand("/worldtools")) || (Player.canUseCommand("/ext"))){
int dist = 0;
if (split.length == 2) try { dist = Integer.parseInt(split[1]); } catch (Throwable localThrowable3) {
} if (dist == 0) { Player.sendMessage("�cWrong syntax! Usage: /ext <radius>"); return true; }
int radius = 0;
try {radius = Integer.parseInt(split[1]);}catch(NumberFormatException nfe){Player.notify("The correct usage is /ext <radius>");return true;}
int xmin = (int)Player.getX()-radius;
int xmax = (int)Player.getX()+radius;
int ymin = (int)Player.getY()-radius;
int ymax = (int)Player.getY()+radius;
int zmin = (int)Player.getZ()-radius;
int zmax = (int)Player.getZ()+radius;
for (int x = xmin; x <= xmax; x++) {
for (int y = ymin; y <= ymax; y++) {
for (int z = zmin; z <= zmax; z++) {
if (Player.getWorld().getBlockAt(x, y, z).getType() == 51){Player.getWorld().setBlockAt(0, x, y, z);}
}
}
}
Player.sendMessage("�aFire Successfully Extinguished");
return true;
}
Player.notify("You cant use this command");return true;
}
if (split[0].equalsIgnoreCase("/melt")) {
if ((Player.canUseCommand("/worldtools")) || (Player.canUseCommand("/melt"))){
int dist = 0;
if (split.length == 2) try { dist = Integer.parseInt(split[1]); } catch (Throwable localThrowable4) {
} if (dist == 0) { Player.sendMessage("�cWrong syntax! Usage: /melt <radius>"); return true; }
int radius = 0;
try {radius = Integer.parseInt(split[1]);}catch(NumberFormatException nfe){Player.notify("The correct usage is /melt <radius>");return true;}
int xmin = (int)Player.getX()-radius;
int xmax = (int)Player.getX()+radius;
int ymin = (int)Player.getY()-radius;
int ymax = (int)Player.getY()+radius;
int zmin = (int)Player.getZ()-radius;
int zmax = (int)Player.getZ()+radius;
for (int x = xmin; x <= xmax; x++) {
for (int y = ymin; y <= ymax; y++) {
for (int z = zmin; z <= zmax; z++) {
if (Player.getWorld().getBlockAt(x, y, z).getType() == 78){Player.getWorld().setBlockAt(0, x, y, z);}
if (Player.getWorld().getBlockAt(x, y, z).getType() == 79){Player.getWorld().setBlockAt(8, x, y, z);}
}
}
}
Player.sendMessage("�aThe Snow & Ice has been successfully melted!");
return true;
}
Player.notify("You cant use this command");return true;
}
if (split[0].equalsIgnoreCase("/snow")) {
if ((Player.canUseCommand("/worldtools")) || (Player.canUseCommand("/snow"))){
int dist = 0;
if (split.length == 2) try { dist = Integer.parseInt(split[1]); } catch (Throwable localThrowable5) {
} if (dist == 0) { Player.sendMessage("�cWrong syntax! Usage: /snow <radius>"); return true; }
int radius = 0;
try {radius = Integer.parseInt(split[1]);}catch(NumberFormatException nfe){Player.notify("The correct usage is /snow <radius>");return true;}
int xmin = (int)Player.getX()-radius;
int xmax = (int)Player.getX()+radius;
int ymin = (int)Player.getY()-radius;
int ymax = (int)Player.getY()+radius;
int zmin = (int)Player.getZ()-radius;
int zmax = (int)Player.getZ()+radius;
for (int x = xmin; x <= xmax; x++) {
for (int y = ymin; y <= ymax; y++) {
for (int z = zmin; z <= zmax; z++) {
if (Player.getWorld().getBlockAt(x, y, z).getType() == 0){Player.getWorld().setBlockAt(78, x, y, z);}
if (Player.getWorld().getBlockAt(x, y, z).getType() == 8){Player.getWorld().setBlockAt(79, x, y, z);}
if (Player.getWorld().getBlockAt(x, y, z).getType() == 9){Player.getWorld().setBlockAt(79, x, y, z);}
}
}
}
Player.sendMessage("�a Snow placed & water frozen!");
return true;
}
Player.notify("You cant use this command");return true;
}
- if ((split[0].equalsIgnoreCase("/waterfix")) && (Player.canUseCommand("/worldtools")) && (Player.canUseCommand("/waterfix"))) {
+ if (split[0].equalsIgnoreCase("/waterfix")) {
+ if ((Player.canUseCommand("/worldtools")) && (Player.canUseCommand("/waterfix"))){
int dist = 0;
if (split.length == 2) try { dist = Integer.parseInt(split[1]); } catch (Throwable localThrowable6) {
} if (dist == 0) { Player.sendMessage("�cWrong syntax! Usage: /waterfix <radius>"); return true; }
int radius = 0;
try {radius = Integer.parseInt(split[1]);}catch(NumberFormatException nfe){Player.notify("The correct usage is /waterfix <radius>");return true;}
int xmin = (int)Player.getX()-radius;
int xmax = (int)Player.getX()+radius;
int ymin = (int)Player.getY()-radius;
int ymax = (int)Player.getY()+radius;
int zmin = (int)Player.getZ()-radius;
int zmax = (int)Player.getZ()+radius;
for (int x = xmin; x <= xmax; x++) {
for (int y = ymin; y <= ymax; y++) {
for (int z = zmin; z <= zmax; z++) {
if (Player.getWorld().getBlockAt(x, y, z).getType() == 8){Player.getWorld().setBlockAt(95, x, y, z);}
if (Player.getWorld().getBlockAt(x, y, z).getType() == 9){Player.getWorld().setBlockAt(95, x, y, z);}
if (Player.getWorld().getBlockAt(x, y, z).getType() == 95){Player.getWorld().setBlockAt(9, x, y, z);}
}
}
}
Player.sendMessage("�a Water Successfully Fixed!");
return true;
}
+ Player.notify("You cant use this command");return true;
+ }
if (split[0].equalsIgnoreCase("/lavafix")) {
if ((Player.canUseCommand("/worldtool")) || (Player.canUseCommand("/lavafix"))){
int dist = 0;
if (split.length == 2) try { dist = Integer.parseInt(split[1]); } catch (Throwable localThrowable7) {
} if (dist == 0) { Player.sendMessage("�cWrong syntax! Usage: /lavafix <radius>"); return true; }
int radius = 0;
try {radius = Integer.parseInt(split[1]);}catch(NumberFormatException nfe){Player.notify("The correct usage is /lavafix <radius>");return true;}
int xmin = (int)Player.getX()-radius;
int xmax = (int)Player.getX()+radius;
int ymin = (int)Player.getY()-radius;
int ymax = (int)Player.getY()+radius;
int zmin = (int)Player.getZ()-radius;
int zmax = (int)Player.getZ()+radius;
for (int x = xmin; x <= xmax; x++) {
for (int y = ymin; y <= ymax; y++) {
for (int z = zmin; z <= zmax; z++) {
if (Player.getWorld().getBlockAt(x, y, z).getType() == 10){Player.getWorld().setBlockAt(95, x, y, z);}
if (Player.getWorld().getBlockAt(x, y, z).getType() == 11){Player.getWorld().setBlockAt(95, x, y, z);}
if (Player.getWorld().getBlockAt(x, y, z).getType() == 95){Player.getWorld().setBlockAt(9, x, y, z);}
}//TODO
}
}
Player.sendMessage("�a Lava Successfully Fixed!");
return true;
}
Player.notify("You cant use this command");return true;
}
if (split[0].equalsIgnoreCase("/lighter")){
if(Player.canUseCommand("/lighter") || (Player.canUseCommand("/worldtools"))) {
int dist = 0;
if (split.length == 0) try { dist = Integer.parseInt(split[0]); } catch (Throwable localThrowable8) {
} if (dist == 0) { Player.sendMessage("�cWrong syntax! Usage: /lighter"); return true;
}
Player.giveItem(260, 1);
Player.sendMessage("�a No smoke without �6fire!");
return true;
}
Player.notify("You cant use this command");return true;
}
if (split[0].equalsIgnoreCase("/cmob")){
if(Player.canUseCommand("/cmob") || (Player.canUseCommand("/worldtools"))) {
try {
int r = Integer.valueOf(split[1]).intValue();
WorldToolsVoids.cMob(r);
Player.sendMessage("�aCleared mobs");
return true;
} catch (Exception e) {
Player.sendMessage("�cWrong syntax! Usage: /cmob <radius>");
return true;
}
}
Player.notify("You cant use this command");return true;
}
/**
* killmobs
*/
if (split[0].equalsIgnoreCase("/killmobs")){
if (Player.canUseCommand("/killmobs") || (Player.canUseCommand("/worldtools"))) {
int mobcount = Player.getWorld().getMobList().size();
for (int i = 0; i < mobcount; i++) {
((Mob)Player.getWorld().getMobList().get(i)).setHealth(0);
}
Player.sendMessage("�aYou Killed " + mobcount + " Mobs.");
return true;
}
Player.notify("You cant use this command");return true;
}
/**
* replace feature
*
*/
if (split[0].equalsIgnoreCase("/wreplace")){
if ((Player.canUseCommand("/wreplace") || (Player.canUseCommand("/worldtools")))){
if (split.length <4 || split.length >4){
Player.notify("The correct usage is '/wreplace fromid toid radius'");
return true;
}
Integer.parseInt(split[1]); Integer.parseInt(split[2]);Integer.parseInt(split[3]);
int fromid = 0;
try{fromid = Integer.parseInt(split[1]);}catch(NumberFormatException nfe){Player.notify("The correct usage is '/wreplace fromid toid radius");return true;}
int toid = 0;
try{fromid = Integer.parseInt(split[1]);}catch(NumberFormatException nfe){Player.notify("The correct usage is '/wreplace fromid toid radius");return true;}
int radius = 0;
try{fromid = Integer.parseInt(split[1]);}catch(NumberFormatException nfe){Player.notify("The correct usage is '/wreplace fromid toid radius");return true;}
WorldToolsVoids.replace(Player,fromid,toid,radius);
Player.sendMessage("�aBlocks Replaced.");
return true;
}
Player.notify("You cant use this command");return true;
}
if ((split[0].equalsIgnoreCase("/worldtools")) && (Player.canUseCommand("/worldtools"))) {
if (split.length >1 || split.length <1){Player.notify("The correct usage is '/worldtools'");return true;}
Player.sendMessage("�6 WorldTools " + WorldTools.version + " by Glacksy �8&�6 Spenk");
return true;
}
if ((split[0].equalsIgnoreCase("/suicide"))){
if ((Player.canUseCommand("/suicide") || (Player.canUseCommand("/worldtool")))){
if (split.length >1 || split.length <1){Player.notify("The correct usage is '/suicide'");return true;}
Player.setHealth(0);
Player.sendMessage("�cYou committed suicide");
return true;
}
Player.notify("You cant use this command");return true;
}
/**
* kill code
* @author spenk
*/
if ((split[0].equalsIgnoreCase("/kill"))){
if ((Player.canUseCommand("/worldtools")) || (Player.canUseCommand("/kill"))){
if (split.length <2 || split.length >2){
Player.notify("The correct usage is /kill <player>");
return true;
}else{
Player player = etc.getServer().matchPlayer(split[1]);
if (player == null){
Player.notify("�cThis Player Doesnt Exist or is currently not online!");
return true;
}
player.sendMessage("�4You got killed by �2"+Player.getName());
player.dropInventory(player.getLocation());
player.setHealth(0);
Player.sendMessage("�2Player sucsessfully killed!");
return true;
}
}
Player.sendMessage("�cYou cant use this command");
return true;
}
if ((split[0].equalsIgnoreCase("/heal"))){
if ((Player.canUseCommand("/worldtools")) || (Player.canUseCommand("/heal"))){
if (split.length <2 || split.length >2){
Player.sendMessage("�cThe correct usage is /heal <player>");
return true;
}else{
Player player = etc.getServer().matchPlayer(split[1]);
if (player == null){
Player.sendMessage("�cThis Player Doesnt Exist or is currently not online!");
return true;
}
player.sendMessage("�4You were healed by �2"+Player.getName());
player.setHealth(20);
player.setFoodLevel(20);
Player.sendMessage("�2Player sucsessfully healed!");
return true;
}
}
Player.notify("You cant use this command");return true;
}
if (split[0].equalsIgnoreCase("/save-inv")){
if (Player.canUseCommand("/worldtools") || (Player.canUseCommand("/save-inv"))){
if (split.length <1 || split.length >1){Player.notify("The correct usage is '/save-inv'");return true;}
etc.getServer().saveInventories();
Player.sendMessage("�aInventories saved");
return true;
}
Player.notify("You cant use this command");return true;
}
if ((split[0].equalsIgnoreCase("/godmode"))) {
- if ((Player.canUseCommand("/godmode")) && (Player.canUseCommand("/worldtools"))){
+ if ((Player.canUseCommand("/godmode")) || (Player.canUseCommand("/worldtools"))){
if (split.length > 2){Player.notify("The correct usage is /godmode (player)");return true;
}
if (split.length == 1){
if (!god.contains(Player.getName())) {
god.add(Player.getName());
Player.sendMessage("�3Godmode have been enabled");
return true;
}else{
god.remove(Player.getName());
Player.sendMessage("�3Godmode have been disabled");
return true;
}
}
if (split.length == 2){
Player player2 = etc.getServer().matchPlayer(split[1]);
if (player2 == null){Player.notify("This player does not exist or is not logged in!");return true;}
if (!god.contains(player2.getName())) {
god.add(player2.getName());
Player.sendMessage("�3Godmode have been enabled");
player2.sendMessage("�3Godmode have been enabled");
return true;
}else{
god.remove(player2.getName());
Player.sendMessage("�3Godmode have been disabled");
player2.sendMessage("�3Godmode have been disabled");
return true;
}
}
Player.notify("You cant use this command");return true;
}
}
if (split[0].equalsIgnoreCase("/feed")){
- if (Player.canUseCommand("/worldtools") && (Player.canUseCommand("/feed"))){
+ if (Player.canUseCommand("/worldtools") || (Player.canUseCommand("/feed"))){
if (split.length <2 || split.length >2){
Player.notify("The correct usage is /feed player");
return true;
}
Player player2 = etc.getServer().matchPlayer(split[1]);
if (player2 == null) { Player.notify("This Player does not exist or is currently not logged in!"); return true;}
player2.setFoodLevel(20);
Player.sendMessage("�2"+player2.getName()+"'s foodlevel is restored!");
player2.sendMessage("�2"+Player.getName()+" Restored your foodlevel!");
return true;
}
Player.notify("You cant use this command");return true;
}
if (split[0].equalsIgnoreCase("/getip")){
if (Player.canUseCommand("/worldtools") || (Player.canUseCommand("/getip"))){
if (split.length <2 || split.length >2){
Player.notify("The correct usage is /getip <player>");
return true;
}
Player player2 = etc.getServer().matchPlayer(split[1]);
if (player2 == null){Player.notify("This player doesnt exist or is not logged in");return true;}
Player.sendMessage("�4"+player2.getName()+"�2 His IP is �4"+player2.getIP());
return true;
}
if (split[0].equalsIgnoreCase("/forcewarp")){
if (Player.canUseCommand("/worldtools") || (Player.canUseCommand("/forcewarp"))){
if (split.length <3 || split.length >3){
Player.notify("The correct usage is /forcewarp player warpname");
return true;
}
Player player2 = etc.getServer().matchPlayer(split[1]);
if (player2 == null) { Player.notify("This Player does not exist or is currently not logged in!"); return true;}
Warp warp = etc.getDataSource().getWarp(split[2]);
if (warp == null){Player.notify("This warp doesnt exist!");return true;}
player2.teleportTo(warp.Location);
Player.sendMessage("�2"+player2.getName()+" is warped!");
player2.sendMessage("�2"+Player.getName()+" warped you!");
return true;
}
Player.notify("You cant use this command");return true;
}
if (split[0].equalsIgnoreCase("/switchworlds")){
if (Player.canUseCommand("/worldtools") || (Player.canUseCommand("/switchworlds"))){
if (split.length <3 || split.length >3){
Player.notify("The correct usage is /swichworlds player worldname");
Player.notify("-1 = nether, 0 = normal world , 1 = end");
return true;
}
Player player2 = etc.getServer().matchPlayer(split[1]);
if (player2 == null) { Player.notify("This Player does not exist or is currently not logged in!"); return true;}
File f = new File(split[2]);
if (!f.exists()){
Player.notify("This World does not exist!");
return true;
}
if (!etc.getServer().isWorldLoaded(split[2])){
Player.notify("This world isnt loaded! please load it before you try to teleport!");
return true;
}
World[] w = etc.getServer().getWorld(split[2]);
player2.switchWorlds(w[0]);
Player.sendMessage("�2"+player2.getName()+" Has swiched to world "+w[0].getName());
player2.sendMessage("�2"+Player.getName()+" Has swiched you to world "+w[0].getName());
return true;
}
Player.notify("You cant use this command");return true;
}
if (split[0].equalsIgnoreCase("/freeze")) {
if (Player.canUseCommand("/freeze") || (Player.canUseCommand("/worldtools"))){
if (split.length > 2 || split.length < 2){Player.notify("The correct usage is '/freeze <player>'");return true;}
Player offender = etc.getServer().matchPlayer(split[1]);
if (offender == null){
Player.notify("This Player does not exist or is currently not logged in!");
return true;
}
if ((!frozen.contains(offender.getName())) && (split[1] != null)) {
offender.sendMessage("�2You have been frozen by �3" + Player.getName() + "�e!");
Player.sendMessage("�2You froze �3" + offender.getName() + "�2!");
frozen.add(offender.getName());
return true;
}
offender.sendMessage("�2You have been thawed!");
Player.sendMessage("�2You unfroze �3" + Player.getName() + "�2!");
frozen.remove(offender.getName());
return true;
}
Player.notify("You cant use this command");return true;
}
if (split[0].equalsIgnoreCase("/setspawn")){
if (Player.canUseCommand("/setspawn")||Player.canUseCommand("/worldtools")){
if (split.length > 1 || split.length < 1){Player.notify("The correct usage is '/setspawn'");return true;}
exactSpawn = new Location(Player.getX(), Player.getY(), Player.getZ(), Player.getRotation(), Player.getPitch());
PropertiesFile props = new PropertiesFile("worldtools.properties");
props.setString("exact-spawn", exactSpawn.x + "," + exactSpawn.y + "," + exactSpawn.z + "," + exactSpawn.rotX + "," + exactSpawn.rotY);
return true;
}
Player.notify("You cant use this command");return true;
}
if (split[0].equalsIgnoreCase("/spawn") && exactSpawn != null) {
if ((Player.canUseCommand("/spawn")) || Player.canUseCommand("/worldtools")){
Player.teleportTo(exactSpawn);
return true;
}
Player.notify("You cant use this command");return true;
}
if (split[0].equalsIgnoreCase("/locate")){
if (Player.canUseCommand("/locate")|| Player.canUseCommand("/worldtools")){
if (split.length > 2 || split.length < 2){
Player.notify("The correct usage is '/locate <player>'");return true;
}
Player player2 = etc.getServer().matchPlayer(split[1]);
if (player2 == null){Player.notify("�cTis player doesnt exist or is currently not logged in!");return true;}
Player.sendMessage(player2.getName()+"Is located in World:"+player2.getWorld().getName()+" in Dimension:"+player2.getLocation().dimension +" at location X:"+player2.getX() +" Y:"+player2.getY() +" Z:"+player2.getZ());
return true;
}
Player.notify("You cant use this command");return true;
}
}
return false;
}
public void onPlayerMove(Player player, Location from, Location to) {
if (frozen.contains(player.getName()))
player.teleportTo(from);
}
public void onLogin(Player player) {
if (god.contains(player.getName()))
if (god.contains(player.getName()))
god.remove(player.getName());
god.remove(player.getName());
}
public boolean onDamage(PluginLoader.DamageType type, BaseEntity attacker, BaseEntity defender, int amount)
{
if ((defender.isPlayer()) &&
(god.contains(defender.getPlayer().getName()))) {
Player localplayer = defender.getPlayer();
if ((localplayer.canUseCommand("/godmode")) &&
(type.equals(PluginLoader.DamageType.ENTITY)) &&
(type.equals(PluginLoader.DamageType.CACTUS)) &&
(type.equals(PluginLoader.DamageType.FALL)) &&
(type.equals(PluginLoader.DamageType.FIRE)) &&
(type.equals(PluginLoader.DamageType.LAVA)) &&
(type.equals(PluginLoader.DamageType.SUFFOCATION)) &&
(type.equals(PluginLoader.DamageType.FIRE_TICK)) &&
(type.equals(PluginLoader.DamageType.CREEPER_EXPLOSION)) &&
(type.equals(PluginLoader.DamageType.EXPLOSION)) &&
(type.equals(PluginLoader.DamageType.POTION)) &&
(type.equals(PluginLoader.DamageType.STARVATION)) &&
(type.equals(PluginLoader.DamageType.WATER)) &&
(type.equals(PluginLoader.DamageType.LIGHTNING)))
{
return true;
}
}
return false;
}
}
/**
* @commands
* /drain
* /drainlava
* /drainwater
* /ext
* /melt
* /snow
* /lavafix
* /waterfix
* /lighter
* /cmob
* /wreplace
* /killmobs
* /suicide
* /kill
* /heal
* /save-inv
* /freeze
* /godmode
* /food
* /swichworlds
* /getip
*/
// end of class
| false | true | public boolean onCommand(Player Player, String[] split) {
if (split[0].equalsIgnoreCase("/drain")){
if ((Player.canUseCommand("/worldtools"))||Player.canUseCommand("/drain")){
int dist = 0;
if (split.length == 2) try { dist = Integer.parseInt(split[1]); } catch (Throwable localThrowable) {
} if (dist == 0) {
Player.sendMessage("�9[�6-�8-�6-�8-�6-�9Drain Help�6-�8-�6-�8-�6-�9]");
Player.sendMessage("�a/drain <radius> - Drain water/lava");
Player.sendMessage("�a/drainwater <radius> - Drain water");
Player.sendMessage("�a/drainlava <radius> - Drain lava");
Player.sendMessage("�a/ext <radius> - Remove fire"); return true;
}
int radius = 0;
try {radius = Integer.parseInt(split[1]);}catch(NumberFormatException nfe){Player.notify("The correct usage is /drain <radius>");return true;}
int xmin = (int)Player.getX()-radius;
int xmax = (int)Player.getX()+radius;
int ymin = (int)Player.getY()-radius;
int ymax = (int)Player.getY()+radius;
int zmin = (int)Player.getZ()-radius;
int zmax = (int)Player.getZ()+radius;
for (int x = xmin; x <= xmax; x++) {
for (int y = ymin; y <= ymax; y++) {
for (int z = zmin; z <= zmax; z++) {
if (Player.getWorld().getBlockAt(x, y, z).getType() == 8){Player.getWorld().setBlockAt(95, x, y, z);}
if (Player.getWorld().getBlockAt(x, y, z).getType() == 95){Player.getWorld().setBlockAt(9, x, y, z);}
if (Player.getWorld().getBlockAt(x, y, z).getType() == 10){Player.getWorld().setBlockAt(95, x, y, z);}
if (Player.getWorld().getBlockAt(x, y, z).getType() == 95){Player.getWorld().setBlockAt(11, x, y, z);}
}
}
}
Player.sendMessage("�aLava & Water Successfully Drained!");
return true;
}
Player.notify("You cant use this command");return true;
}
if (split[0].equalsIgnoreCase("/drainlava")){
if ((Player.canUseCommand("/worldtools")) && (Player.canUseCommand("/drainlava"))){
int dist = 0;
if (split.length == 2) try { dist = Integer.parseInt(split[1]); } catch (Throwable localThrowable1) {
} if (dist == 0) { Player.sendMessage("�cWrong syntax! Usage: /drainlava <radius>"); return true; }
int radius = 0;
try {radius = Integer.parseInt(split[1]);}catch(NumberFormatException nfe){Player.notify("The correct usage is /drainlava <radius>");return true;}
int xmin = (int)Player.getX()-radius;
int xmax = (int)Player.getX()+radius;
int ymin = (int)Player.getY()-radius;
int ymax = (int)Player.getY()+radius;
int zmin = (int)Player.getZ()-radius;
int zmax = (int)Player.getZ()+radius;
for (int x = xmin; x <= xmax; x++) {
for (int y = ymin; y <= ymax; y++) {
for (int z = zmin; z <= zmax; z++) {
if (Player.getWorld().getBlockAt(x, y, z).getType() == 11){Player.getWorld().setBlockAt(95, x, y, z);}
if (Player.getWorld().getBlockAt(x, y, z).getType() == 95){Player.getWorld().setBlockAt(10, x, y, z);}
}
}
}
Player.sendMessage("�aLava Successfully Removed!");
return true;
}
Player.notify("You cant use this command");return true;
}
if (split[0].equalsIgnoreCase("/drainwater")) {
if ((Player.canUseCommand("/worldtools")) && (Player.canUseCommand("/drainwater"))){
int dist = 0;
if (split.length == 2) try { dist = Integer.parseInt(split[1]); } catch (Throwable localThrowable2) {
} if (dist == 0) { Player.sendMessage("�cWrong syntax! Usage: /drainwater <radius>"); return true; }
int radius = 0;
try {radius = Integer.parseInt(split[1]);}catch(NumberFormatException nfe){Player.notify("The correct usage is /drainwater <radius>");return true;}
int xmin = (int)Player.getX()-radius;
int xmax = (int)Player.getX()+radius;
int ymin = (int)Player.getY()-radius;
int ymax = (int)Player.getY()+radius;
int zmin = (int)Player.getZ()-radius;
int zmax = (int)Player.getZ()+radius;
for (int x = xmin; x <= xmax; x++) {
for (int y = ymin; y <= ymax; y++) {
for (int z = zmin; z <= zmax; z++) {
if (Player.getWorld().getBlockAt(x, y, z).getType() == 9){Player.getWorld().setBlockAt(95, x, y, z);}
if (Player.getWorld().getBlockAt(x, y, z).getType() == 95){Player.getWorld().setBlockAt(8, x, y, z);}
}
}
}
Player.sendMessage("�aWater Successfully Removed!");
return true;
}
Player.notify("You cant use this command");return true;
}
if (split[0].equalsIgnoreCase("/ext")) {
if ((Player.canUseCommand("/worldtools")) && (Player.canUseCommand("/ext"))){
int dist = 0;
if (split.length == 2) try { dist = Integer.parseInt(split[1]); } catch (Throwable localThrowable3) {
} if (dist == 0) { Player.sendMessage("�cWrong syntax! Usage: /ext <radius>"); return true; }
int radius = 0;
try {radius = Integer.parseInt(split[1]);}catch(NumberFormatException nfe){Player.notify("The correct usage is /ext <radius>");return true;}
int xmin = (int)Player.getX()-radius;
int xmax = (int)Player.getX()+radius;
int ymin = (int)Player.getY()-radius;
int ymax = (int)Player.getY()+radius;
int zmin = (int)Player.getZ()-radius;
int zmax = (int)Player.getZ()+radius;
for (int x = xmin; x <= xmax; x++) {
for (int y = ymin; y <= ymax; y++) {
for (int z = zmin; z <= zmax; z++) {
if (Player.getWorld().getBlockAt(x, y, z).getType() == 51){Player.getWorld().setBlockAt(0, x, y, z);}
}
}
}
Player.sendMessage("�aFire Successfully Extinguished");
return true;
}
Player.notify("You cant use this command");return true;
}
if (split[0].equalsIgnoreCase("/melt")) {
if ((Player.canUseCommand("/worldtools")) || (Player.canUseCommand("/melt"))){
int dist = 0;
if (split.length == 2) try { dist = Integer.parseInt(split[1]); } catch (Throwable localThrowable4) {
} if (dist == 0) { Player.sendMessage("�cWrong syntax! Usage: /melt <radius>"); return true; }
int radius = 0;
try {radius = Integer.parseInt(split[1]);}catch(NumberFormatException nfe){Player.notify("The correct usage is /melt <radius>");return true;}
int xmin = (int)Player.getX()-radius;
int xmax = (int)Player.getX()+radius;
int ymin = (int)Player.getY()-radius;
int ymax = (int)Player.getY()+radius;
int zmin = (int)Player.getZ()-radius;
int zmax = (int)Player.getZ()+radius;
for (int x = xmin; x <= xmax; x++) {
for (int y = ymin; y <= ymax; y++) {
for (int z = zmin; z <= zmax; z++) {
if (Player.getWorld().getBlockAt(x, y, z).getType() == 78){Player.getWorld().setBlockAt(0, x, y, z);}
if (Player.getWorld().getBlockAt(x, y, z).getType() == 79){Player.getWorld().setBlockAt(8, x, y, z);}
}
}
}
Player.sendMessage("�aThe Snow & Ice has been successfully melted!");
return true;
}
Player.notify("You cant use this command");return true;
}
if (split[0].equalsIgnoreCase("/snow")) {
if ((Player.canUseCommand("/worldtools")) || (Player.canUseCommand("/snow"))){
int dist = 0;
if (split.length == 2) try { dist = Integer.parseInt(split[1]); } catch (Throwable localThrowable5) {
} if (dist == 0) { Player.sendMessage("�cWrong syntax! Usage: /snow <radius>"); return true; }
int radius = 0;
try {radius = Integer.parseInt(split[1]);}catch(NumberFormatException nfe){Player.notify("The correct usage is /snow <radius>");return true;}
int xmin = (int)Player.getX()-radius;
int xmax = (int)Player.getX()+radius;
int ymin = (int)Player.getY()-radius;
int ymax = (int)Player.getY()+radius;
int zmin = (int)Player.getZ()-radius;
int zmax = (int)Player.getZ()+radius;
for (int x = xmin; x <= xmax; x++) {
for (int y = ymin; y <= ymax; y++) {
for (int z = zmin; z <= zmax; z++) {
if (Player.getWorld().getBlockAt(x, y, z).getType() == 0){Player.getWorld().setBlockAt(78, x, y, z);}
if (Player.getWorld().getBlockAt(x, y, z).getType() == 8){Player.getWorld().setBlockAt(79, x, y, z);}
if (Player.getWorld().getBlockAt(x, y, z).getType() == 9){Player.getWorld().setBlockAt(79, x, y, z);}
}
}
}
Player.sendMessage("�a Snow placed & water frozen!");
return true;
}
Player.notify("You cant use this command");return true;
}
if ((split[0].equalsIgnoreCase("/waterfix")) && (Player.canUseCommand("/worldtools")) && (Player.canUseCommand("/waterfix"))) {
int dist = 0;
if (split.length == 2) try { dist = Integer.parseInt(split[1]); } catch (Throwable localThrowable6) {
} if (dist == 0) { Player.sendMessage("�cWrong syntax! Usage: /waterfix <radius>"); return true; }
int radius = 0;
try {radius = Integer.parseInt(split[1]);}catch(NumberFormatException nfe){Player.notify("The correct usage is /waterfix <radius>");return true;}
int xmin = (int)Player.getX()-radius;
int xmax = (int)Player.getX()+radius;
int ymin = (int)Player.getY()-radius;
int ymax = (int)Player.getY()+radius;
int zmin = (int)Player.getZ()-radius;
int zmax = (int)Player.getZ()+radius;
for (int x = xmin; x <= xmax; x++) {
for (int y = ymin; y <= ymax; y++) {
for (int z = zmin; z <= zmax; z++) {
if (Player.getWorld().getBlockAt(x, y, z).getType() == 8){Player.getWorld().setBlockAt(95, x, y, z);}
if (Player.getWorld().getBlockAt(x, y, z).getType() == 9){Player.getWorld().setBlockAt(95, x, y, z);}
if (Player.getWorld().getBlockAt(x, y, z).getType() == 95){Player.getWorld().setBlockAt(9, x, y, z);}
}
}
}
Player.sendMessage("�a Water Successfully Fixed!");
return true;
}
if (split[0].equalsIgnoreCase("/lavafix")) {
if ((Player.canUseCommand("/worldtool")) || (Player.canUseCommand("/lavafix"))){
int dist = 0;
if (split.length == 2) try { dist = Integer.parseInt(split[1]); } catch (Throwable localThrowable7) {
} if (dist == 0) { Player.sendMessage("�cWrong syntax! Usage: /lavafix <radius>"); return true; }
int radius = 0;
try {radius = Integer.parseInt(split[1]);}catch(NumberFormatException nfe){Player.notify("The correct usage is /lavafix <radius>");return true;}
int xmin = (int)Player.getX()-radius;
int xmax = (int)Player.getX()+radius;
int ymin = (int)Player.getY()-radius;
int ymax = (int)Player.getY()+radius;
int zmin = (int)Player.getZ()-radius;
int zmax = (int)Player.getZ()+radius;
for (int x = xmin; x <= xmax; x++) {
for (int y = ymin; y <= ymax; y++) {
for (int z = zmin; z <= zmax; z++) {
if (Player.getWorld().getBlockAt(x, y, z).getType() == 10){Player.getWorld().setBlockAt(95, x, y, z);}
if (Player.getWorld().getBlockAt(x, y, z).getType() == 11){Player.getWorld().setBlockAt(95, x, y, z);}
if (Player.getWorld().getBlockAt(x, y, z).getType() == 95){Player.getWorld().setBlockAt(9, x, y, z);}
}//TODO
}
}
Player.sendMessage("�a Lava Successfully Fixed!");
return true;
}
Player.notify("You cant use this command");return true;
}
if (split[0].equalsIgnoreCase("/lighter")){
if(Player.canUseCommand("/lighter") || (Player.canUseCommand("/worldtools"))) {
int dist = 0;
if (split.length == 0) try { dist = Integer.parseInt(split[0]); } catch (Throwable localThrowable8) {
} if (dist == 0) { Player.sendMessage("�cWrong syntax! Usage: /lighter"); return true;
}
Player.giveItem(260, 1);
Player.sendMessage("�a No smoke without �6fire!");
return true;
}
Player.notify("You cant use this command");return true;
}
if (split[0].equalsIgnoreCase("/cmob")){
if(Player.canUseCommand("/cmob") || (Player.canUseCommand("/worldtools"))) {
try {
int r = Integer.valueOf(split[1]).intValue();
WorldToolsVoids.cMob(r);
Player.sendMessage("�aCleared mobs");
return true;
} catch (Exception e) {
Player.sendMessage("�cWrong syntax! Usage: /cmob <radius>");
return true;
}
}
Player.notify("You cant use this command");return true;
}
/**
* killmobs
*/
if (split[0].equalsIgnoreCase("/killmobs")){
if (Player.canUseCommand("/killmobs") || (Player.canUseCommand("/worldtools"))) {
int mobcount = Player.getWorld().getMobList().size();
for (int i = 0; i < mobcount; i++) {
((Mob)Player.getWorld().getMobList().get(i)).setHealth(0);
}
Player.sendMessage("�aYou Killed " + mobcount + " Mobs.");
return true;
}
Player.notify("You cant use this command");return true;
}
/**
* replace feature
*
*/
if (split[0].equalsIgnoreCase("/wreplace")){
if ((Player.canUseCommand("/wreplace") || (Player.canUseCommand("/worldtools")))){
if (split.length <4 || split.length >4){
Player.notify("The correct usage is '/wreplace fromid toid radius'");
return true;
}
Integer.parseInt(split[1]); Integer.parseInt(split[2]);Integer.parseInt(split[3]);
int fromid = 0;
try{fromid = Integer.parseInt(split[1]);}catch(NumberFormatException nfe){Player.notify("The correct usage is '/wreplace fromid toid radius");return true;}
int toid = 0;
try{fromid = Integer.parseInt(split[1]);}catch(NumberFormatException nfe){Player.notify("The correct usage is '/wreplace fromid toid radius");return true;}
int radius = 0;
try{fromid = Integer.parseInt(split[1]);}catch(NumberFormatException nfe){Player.notify("The correct usage is '/wreplace fromid toid radius");return true;}
WorldToolsVoids.replace(Player,fromid,toid,radius);
Player.sendMessage("�aBlocks Replaced.");
return true;
}
Player.notify("You cant use this command");return true;
}
if ((split[0].equalsIgnoreCase("/worldtools")) && (Player.canUseCommand("/worldtools"))) {
if (split.length >1 || split.length <1){Player.notify("The correct usage is '/worldtools'");return true;}
Player.sendMessage("�6 WorldTools " + WorldTools.version + " by Glacksy �8&�6 Spenk");
return true;
}
if ((split[0].equalsIgnoreCase("/suicide"))){
if ((Player.canUseCommand("/suicide") || (Player.canUseCommand("/worldtool")))){
if (split.length >1 || split.length <1){Player.notify("The correct usage is '/suicide'");return true;}
Player.setHealth(0);
Player.sendMessage("�cYou committed suicide");
return true;
}
Player.notify("You cant use this command");return true;
}
/**
* kill code
* @author spenk
*/
if ((split[0].equalsIgnoreCase("/kill"))){
if ((Player.canUseCommand("/worldtools")) || (Player.canUseCommand("/kill"))){
if (split.length <2 || split.length >2){
Player.notify("The correct usage is /kill <player>");
return true;
}else{
Player player = etc.getServer().matchPlayer(split[1]);
if (player == null){
Player.notify("�cThis Player Doesnt Exist or is currently not online!");
return true;
}
player.sendMessage("�4You got killed by �2"+Player.getName());
player.dropInventory(player.getLocation());
player.setHealth(0);
Player.sendMessage("�2Player sucsessfully killed!");
return true;
}
}
Player.sendMessage("�cYou cant use this command");
return true;
}
if ((split[0].equalsIgnoreCase("/heal"))){
if ((Player.canUseCommand("/worldtools")) || (Player.canUseCommand("/heal"))){
if (split.length <2 || split.length >2){
Player.sendMessage("�cThe correct usage is /heal <player>");
return true;
}else{
Player player = etc.getServer().matchPlayer(split[1]);
if (player == null){
Player.sendMessage("�cThis Player Doesnt Exist or is currently not online!");
return true;
}
player.sendMessage("�4You were healed by �2"+Player.getName());
player.setHealth(20);
player.setFoodLevel(20);
Player.sendMessage("�2Player sucsessfully healed!");
return true;
}
}
Player.notify("You cant use this command");return true;
}
if (split[0].equalsIgnoreCase("/save-inv")){
if (Player.canUseCommand("/worldtools") || (Player.canUseCommand("/save-inv"))){
if (split.length <1 || split.length >1){Player.notify("The correct usage is '/save-inv'");return true;}
etc.getServer().saveInventories();
Player.sendMessage("�aInventories saved");
return true;
}
Player.notify("You cant use this command");return true;
}
if ((split[0].equalsIgnoreCase("/godmode"))) {
if ((Player.canUseCommand("/godmode")) && (Player.canUseCommand("/worldtools"))){
if (split.length > 2){Player.notify("The correct usage is /godmode (player)");return true;
}
if (split.length == 1){
if (!god.contains(Player.getName())) {
god.add(Player.getName());
Player.sendMessage("�3Godmode have been enabled");
return true;
}else{
god.remove(Player.getName());
Player.sendMessage("�3Godmode have been disabled");
return true;
}
}
if (split.length == 2){
Player player2 = etc.getServer().matchPlayer(split[1]);
if (player2 == null){Player.notify("This player does not exist or is not logged in!");return true;}
if (!god.contains(player2.getName())) {
god.add(player2.getName());
Player.sendMessage("�3Godmode have been enabled");
player2.sendMessage("�3Godmode have been enabled");
return true;
}else{
god.remove(player2.getName());
Player.sendMessage("�3Godmode have been disabled");
player2.sendMessage("�3Godmode have been disabled");
return true;
}
}
Player.notify("You cant use this command");return true;
}
}
if (split[0].equalsIgnoreCase("/feed")){
if (Player.canUseCommand("/worldtools") && (Player.canUseCommand("/feed"))){
if (split.length <2 || split.length >2){
Player.notify("The correct usage is /feed player");
return true;
}
Player player2 = etc.getServer().matchPlayer(split[1]);
if (player2 == null) { Player.notify("This Player does not exist or is currently not logged in!"); return true;}
player2.setFoodLevel(20);
Player.sendMessage("�2"+player2.getName()+"'s foodlevel is restored!");
player2.sendMessage("�2"+Player.getName()+" Restored your foodlevel!");
return true;
}
Player.notify("You cant use this command");return true;
}
if (split[0].equalsIgnoreCase("/getip")){
if (Player.canUseCommand("/worldtools") || (Player.canUseCommand("/getip"))){
if (split.length <2 || split.length >2){
Player.notify("The correct usage is /getip <player>");
return true;
}
Player player2 = etc.getServer().matchPlayer(split[1]);
if (player2 == null){Player.notify("This player doesnt exist or is not logged in");return true;}
Player.sendMessage("�4"+player2.getName()+"�2 His IP is �4"+player2.getIP());
return true;
}
if (split[0].equalsIgnoreCase("/forcewarp")){
if (Player.canUseCommand("/worldtools") || (Player.canUseCommand("/forcewarp"))){
if (split.length <3 || split.length >3){
Player.notify("The correct usage is /forcewarp player warpname");
return true;
}
Player player2 = etc.getServer().matchPlayer(split[1]);
if (player2 == null) { Player.notify("This Player does not exist or is currently not logged in!"); return true;}
Warp warp = etc.getDataSource().getWarp(split[2]);
if (warp == null){Player.notify("This warp doesnt exist!");return true;}
player2.teleportTo(warp.Location);
Player.sendMessage("�2"+player2.getName()+" is warped!");
player2.sendMessage("�2"+Player.getName()+" warped you!");
return true;
}
Player.notify("You cant use this command");return true;
}
if (split[0].equalsIgnoreCase("/switchworlds")){
if (Player.canUseCommand("/worldtools") || (Player.canUseCommand("/switchworlds"))){
if (split.length <3 || split.length >3){
Player.notify("The correct usage is /swichworlds player worldname");
Player.notify("-1 = nether, 0 = normal world , 1 = end");
return true;
}
Player player2 = etc.getServer().matchPlayer(split[1]);
if (player2 == null) { Player.notify("This Player does not exist or is currently not logged in!"); return true;}
File f = new File(split[2]);
if (!f.exists()){
Player.notify("This World does not exist!");
return true;
}
if (!etc.getServer().isWorldLoaded(split[2])){
Player.notify("This world isnt loaded! please load it before you try to teleport!");
return true;
}
World[] w = etc.getServer().getWorld(split[2]);
player2.switchWorlds(w[0]);
Player.sendMessage("�2"+player2.getName()+" Has swiched to world "+w[0].getName());
player2.sendMessage("�2"+Player.getName()+" Has swiched you to world "+w[0].getName());
return true;
}
Player.notify("You cant use this command");return true;
}
if (split[0].equalsIgnoreCase("/freeze")) {
if (Player.canUseCommand("/freeze") || (Player.canUseCommand("/worldtools"))){
if (split.length > 2 || split.length < 2){Player.notify("The correct usage is '/freeze <player>'");return true;}
Player offender = etc.getServer().matchPlayer(split[1]);
if (offender == null){
Player.notify("This Player does not exist or is currently not logged in!");
return true;
}
if ((!frozen.contains(offender.getName())) && (split[1] != null)) {
offender.sendMessage("�2You have been frozen by �3" + Player.getName() + "�e!");
Player.sendMessage("�2You froze �3" + offender.getName() + "�2!");
frozen.add(offender.getName());
return true;
}
offender.sendMessage("�2You have been thawed!");
Player.sendMessage("�2You unfroze �3" + Player.getName() + "�2!");
frozen.remove(offender.getName());
return true;
}
Player.notify("You cant use this command");return true;
}
if (split[0].equalsIgnoreCase("/setspawn")){
if (Player.canUseCommand("/setspawn")||Player.canUseCommand("/worldtools")){
if (split.length > 1 || split.length < 1){Player.notify("The correct usage is '/setspawn'");return true;}
exactSpawn = new Location(Player.getX(), Player.getY(), Player.getZ(), Player.getRotation(), Player.getPitch());
PropertiesFile props = new PropertiesFile("worldtools.properties");
props.setString("exact-spawn", exactSpawn.x + "," + exactSpawn.y + "," + exactSpawn.z + "," + exactSpawn.rotX + "," + exactSpawn.rotY);
return true;
}
Player.notify("You cant use this command");return true;
}
if (split[0].equalsIgnoreCase("/spawn") && exactSpawn != null) {
if ((Player.canUseCommand("/spawn")) || Player.canUseCommand("/worldtools")){
Player.teleportTo(exactSpawn);
return true;
}
Player.notify("You cant use this command");return true;
}
if (split[0].equalsIgnoreCase("/locate")){
if (Player.canUseCommand("/locate")|| Player.canUseCommand("/worldtools")){
if (split.length > 2 || split.length < 2){
Player.notify("The correct usage is '/locate <player>'");return true;
}
Player player2 = etc.getServer().matchPlayer(split[1]);
if (player2 == null){Player.notify("�cTis player doesnt exist or is currently not logged in!");return true;}
Player.sendMessage(player2.getName()+"Is located in World:"+player2.getWorld().getName()+" in Dimension:"+player2.getLocation().dimension +" at location X:"+player2.getX() +" Y:"+player2.getY() +" Z:"+player2.getZ());
return true;
}
Player.notify("You cant use this command");return true;
}
}
return false;
}
| public boolean onCommand(Player Player, String[] split) {
if (split[0].equalsIgnoreCase("/drain")){
if ((Player.canUseCommand("/worldtools"))||Player.canUseCommand("/drain")){
int dist = 0;
if (split.length == 2) try { dist = Integer.parseInt(split[1]); } catch (Throwable localThrowable) {
} if (dist == 0) {
Player.sendMessage("�9[�6-�8-�6-�8-�6-�9Drain Help�6-�8-�6-�8-�6-�9]");
Player.sendMessage("�a/drain <radius> - Drain water/lava");
Player.sendMessage("�a/drainwater <radius> - Drain water");
Player.sendMessage("�a/drainlava <radius> - Drain lava");
Player.sendMessage("�a/ext <radius> - Remove fire"); return true;
}
int radius = 0;
try {radius = Integer.parseInt(split[1]);}catch(NumberFormatException nfe){Player.notify("The correct usage is /drain <radius>");return true;}
int xmin = (int)Player.getX()-radius;
int xmax = (int)Player.getX()+radius;
int ymin = (int)Player.getY()-radius;
int ymax = (int)Player.getY()+radius;
int zmin = (int)Player.getZ()-radius;
int zmax = (int)Player.getZ()+radius;
for (int x = xmin; x <= xmax; x++) {
for (int y = ymin; y <= ymax; y++) {
for (int z = zmin; z <= zmax; z++) {
if (Player.getWorld().getBlockAt(x, y, z).getType() == 8){Player.getWorld().setBlockAt(95, x, y, z);}
if (Player.getWorld().getBlockAt(x, y, z).getType() == 95){Player.getWorld().setBlockAt(9, x, y, z);}
if (Player.getWorld().getBlockAt(x, y, z).getType() == 10){Player.getWorld().setBlockAt(95, x, y, z);}
if (Player.getWorld().getBlockAt(x, y, z).getType() == 95){Player.getWorld().setBlockAt(11, x, y, z);}
}
}
}
Player.sendMessage("�aLava & Water Successfully Drained!");
return true;
}
Player.notify("You cant use this command");return true;
}
if (split[0].equalsIgnoreCase("/drainlava")){
if ((Player.canUseCommand("/worldtools")) || (Player.canUseCommand("/drainlava"))){
int dist = 0;
if (split.length == 2) try { dist = Integer.parseInt(split[1]); } catch (Throwable localThrowable1) {
} if (dist == 0) { Player.sendMessage("�cWrong syntax! Usage: /drainlava <radius>"); return true; }
int radius = 0;
try {radius = Integer.parseInt(split[1]);}catch(NumberFormatException nfe){Player.notify("The correct usage is /drainlava <radius>");return true;}
int xmin = (int)Player.getX()-radius;
int xmax = (int)Player.getX()+radius;
int ymin = (int)Player.getY()-radius;
int ymax = (int)Player.getY()+radius;
int zmin = (int)Player.getZ()-radius;
int zmax = (int)Player.getZ()+radius;
for (int x = xmin; x <= xmax; x++) {
for (int y = ymin; y <= ymax; y++) {
for (int z = zmin; z <= zmax; z++) {
if (Player.getWorld().getBlockAt(x, y, z).getType() == 11){Player.getWorld().setBlockAt(95, x, y, z);}
if (Player.getWorld().getBlockAt(x, y, z).getType() == 95){Player.getWorld().setBlockAt(10, x, y, z);}
}
}
}
Player.sendMessage("�aLava Successfully Removed!");
return true;
}
Player.notify("You cant use this command");return true;
}
if (split[0].equalsIgnoreCase("/drainwater")) {
if ((Player.canUseCommand("/worldtools")) || (Player.canUseCommand("/drainwater"))){
int dist = 0;
if (split.length == 2) try { dist = Integer.parseInt(split[1]); } catch (Throwable localThrowable2) {
} if (dist == 0) { Player.sendMessage("�cWrong syntax! Usage: /drainwater <radius>"); return true; }
int radius = 0;
try {radius = Integer.parseInt(split[1]);}catch(NumberFormatException nfe){Player.notify("The correct usage is /drainwater <radius>");return true;}
int xmin = (int)Player.getX()-radius;
int xmax = (int)Player.getX()+radius;
int ymin = (int)Player.getY()-radius;
int ymax = (int)Player.getY()+radius;
int zmin = (int)Player.getZ()-radius;
int zmax = (int)Player.getZ()+radius;
for (int x = xmin; x <= xmax; x++) {
for (int y = ymin; y <= ymax; y++) {
for (int z = zmin; z <= zmax; z++) {
if (Player.getWorld().getBlockAt(x, y, z).getType() == 9){Player.getWorld().setBlockAt(95, x, y, z);}
if (Player.getWorld().getBlockAt(x, y, z).getType() == 95){Player.getWorld().setBlockAt(8, x, y, z);}
}
}
}
Player.sendMessage("�aWater Successfully Removed!");
return true;
}
Player.notify("You cant use this command");return true;
}
if (split[0].equalsIgnoreCase("/ext")) {
if ((Player.canUseCommand("/worldtools")) || (Player.canUseCommand("/ext"))){
int dist = 0;
if (split.length == 2) try { dist = Integer.parseInt(split[1]); } catch (Throwable localThrowable3) {
} if (dist == 0) { Player.sendMessage("�cWrong syntax! Usage: /ext <radius>"); return true; }
int radius = 0;
try {radius = Integer.parseInt(split[1]);}catch(NumberFormatException nfe){Player.notify("The correct usage is /ext <radius>");return true;}
int xmin = (int)Player.getX()-radius;
int xmax = (int)Player.getX()+radius;
int ymin = (int)Player.getY()-radius;
int ymax = (int)Player.getY()+radius;
int zmin = (int)Player.getZ()-radius;
int zmax = (int)Player.getZ()+radius;
for (int x = xmin; x <= xmax; x++) {
for (int y = ymin; y <= ymax; y++) {
for (int z = zmin; z <= zmax; z++) {
if (Player.getWorld().getBlockAt(x, y, z).getType() == 51){Player.getWorld().setBlockAt(0, x, y, z);}
}
}
}
Player.sendMessage("�aFire Successfully Extinguished");
return true;
}
Player.notify("You cant use this command");return true;
}
if (split[0].equalsIgnoreCase("/melt")) {
if ((Player.canUseCommand("/worldtools")) || (Player.canUseCommand("/melt"))){
int dist = 0;
if (split.length == 2) try { dist = Integer.parseInt(split[1]); } catch (Throwable localThrowable4) {
} if (dist == 0) { Player.sendMessage("�cWrong syntax! Usage: /melt <radius>"); return true; }
int radius = 0;
try {radius = Integer.parseInt(split[1]);}catch(NumberFormatException nfe){Player.notify("The correct usage is /melt <radius>");return true;}
int xmin = (int)Player.getX()-radius;
int xmax = (int)Player.getX()+radius;
int ymin = (int)Player.getY()-radius;
int ymax = (int)Player.getY()+radius;
int zmin = (int)Player.getZ()-radius;
int zmax = (int)Player.getZ()+radius;
for (int x = xmin; x <= xmax; x++) {
for (int y = ymin; y <= ymax; y++) {
for (int z = zmin; z <= zmax; z++) {
if (Player.getWorld().getBlockAt(x, y, z).getType() == 78){Player.getWorld().setBlockAt(0, x, y, z);}
if (Player.getWorld().getBlockAt(x, y, z).getType() == 79){Player.getWorld().setBlockAt(8, x, y, z);}
}
}
}
Player.sendMessage("�aThe Snow & Ice has been successfully melted!");
return true;
}
Player.notify("You cant use this command");return true;
}
if (split[0].equalsIgnoreCase("/snow")) {
if ((Player.canUseCommand("/worldtools")) || (Player.canUseCommand("/snow"))){
int dist = 0;
if (split.length == 2) try { dist = Integer.parseInt(split[1]); } catch (Throwable localThrowable5) {
} if (dist == 0) { Player.sendMessage("�cWrong syntax! Usage: /snow <radius>"); return true; }
int radius = 0;
try {radius = Integer.parseInt(split[1]);}catch(NumberFormatException nfe){Player.notify("The correct usage is /snow <radius>");return true;}
int xmin = (int)Player.getX()-radius;
int xmax = (int)Player.getX()+radius;
int ymin = (int)Player.getY()-radius;
int ymax = (int)Player.getY()+radius;
int zmin = (int)Player.getZ()-radius;
int zmax = (int)Player.getZ()+radius;
for (int x = xmin; x <= xmax; x++) {
for (int y = ymin; y <= ymax; y++) {
for (int z = zmin; z <= zmax; z++) {
if (Player.getWorld().getBlockAt(x, y, z).getType() == 0){Player.getWorld().setBlockAt(78, x, y, z);}
if (Player.getWorld().getBlockAt(x, y, z).getType() == 8){Player.getWorld().setBlockAt(79, x, y, z);}
if (Player.getWorld().getBlockAt(x, y, z).getType() == 9){Player.getWorld().setBlockAt(79, x, y, z);}
}
}
}
Player.sendMessage("�a Snow placed & water frozen!");
return true;
}
Player.notify("You cant use this command");return true;
}
if (split[0].equalsIgnoreCase("/waterfix")) {
if ((Player.canUseCommand("/worldtools")) && (Player.canUseCommand("/waterfix"))){
int dist = 0;
if (split.length == 2) try { dist = Integer.parseInt(split[1]); } catch (Throwable localThrowable6) {
} if (dist == 0) { Player.sendMessage("�cWrong syntax! Usage: /waterfix <radius>"); return true; }
int radius = 0;
try {radius = Integer.parseInt(split[1]);}catch(NumberFormatException nfe){Player.notify("The correct usage is /waterfix <radius>");return true;}
int xmin = (int)Player.getX()-radius;
int xmax = (int)Player.getX()+radius;
int ymin = (int)Player.getY()-radius;
int ymax = (int)Player.getY()+radius;
int zmin = (int)Player.getZ()-radius;
int zmax = (int)Player.getZ()+radius;
for (int x = xmin; x <= xmax; x++) {
for (int y = ymin; y <= ymax; y++) {
for (int z = zmin; z <= zmax; z++) {
if (Player.getWorld().getBlockAt(x, y, z).getType() == 8){Player.getWorld().setBlockAt(95, x, y, z);}
if (Player.getWorld().getBlockAt(x, y, z).getType() == 9){Player.getWorld().setBlockAt(95, x, y, z);}
if (Player.getWorld().getBlockAt(x, y, z).getType() == 95){Player.getWorld().setBlockAt(9, x, y, z);}
}
}
}
Player.sendMessage("�a Water Successfully Fixed!");
return true;
}
Player.notify("You cant use this command");return true;
}
if (split[0].equalsIgnoreCase("/lavafix")) {
if ((Player.canUseCommand("/worldtool")) || (Player.canUseCommand("/lavafix"))){
int dist = 0;
if (split.length == 2) try { dist = Integer.parseInt(split[1]); } catch (Throwable localThrowable7) {
} if (dist == 0) { Player.sendMessage("�cWrong syntax! Usage: /lavafix <radius>"); return true; }
int radius = 0;
try {radius = Integer.parseInt(split[1]);}catch(NumberFormatException nfe){Player.notify("The correct usage is /lavafix <radius>");return true;}
int xmin = (int)Player.getX()-radius;
int xmax = (int)Player.getX()+radius;
int ymin = (int)Player.getY()-radius;
int ymax = (int)Player.getY()+radius;
int zmin = (int)Player.getZ()-radius;
int zmax = (int)Player.getZ()+radius;
for (int x = xmin; x <= xmax; x++) {
for (int y = ymin; y <= ymax; y++) {
for (int z = zmin; z <= zmax; z++) {
if (Player.getWorld().getBlockAt(x, y, z).getType() == 10){Player.getWorld().setBlockAt(95, x, y, z);}
if (Player.getWorld().getBlockAt(x, y, z).getType() == 11){Player.getWorld().setBlockAt(95, x, y, z);}
if (Player.getWorld().getBlockAt(x, y, z).getType() == 95){Player.getWorld().setBlockAt(9, x, y, z);}
}//TODO
}
}
Player.sendMessage("�a Lava Successfully Fixed!");
return true;
}
Player.notify("You cant use this command");return true;
}
if (split[0].equalsIgnoreCase("/lighter")){
if(Player.canUseCommand("/lighter") || (Player.canUseCommand("/worldtools"))) {
int dist = 0;
if (split.length == 0) try { dist = Integer.parseInt(split[0]); } catch (Throwable localThrowable8) {
} if (dist == 0) { Player.sendMessage("�cWrong syntax! Usage: /lighter"); return true;
}
Player.giveItem(260, 1);
Player.sendMessage("�a No smoke without �6fire!");
return true;
}
Player.notify("You cant use this command");return true;
}
if (split[0].equalsIgnoreCase("/cmob")){
if(Player.canUseCommand("/cmob") || (Player.canUseCommand("/worldtools"))) {
try {
int r = Integer.valueOf(split[1]).intValue();
WorldToolsVoids.cMob(r);
Player.sendMessage("�aCleared mobs");
return true;
} catch (Exception e) {
Player.sendMessage("�cWrong syntax! Usage: /cmob <radius>");
return true;
}
}
Player.notify("You cant use this command");return true;
}
/**
* killmobs
*/
if (split[0].equalsIgnoreCase("/killmobs")){
if (Player.canUseCommand("/killmobs") || (Player.canUseCommand("/worldtools"))) {
int mobcount = Player.getWorld().getMobList().size();
for (int i = 0; i < mobcount; i++) {
((Mob)Player.getWorld().getMobList().get(i)).setHealth(0);
}
Player.sendMessage("�aYou Killed " + mobcount + " Mobs.");
return true;
}
Player.notify("You cant use this command");return true;
}
/**
* replace feature
*
*/
if (split[0].equalsIgnoreCase("/wreplace")){
if ((Player.canUseCommand("/wreplace") || (Player.canUseCommand("/worldtools")))){
if (split.length <4 || split.length >4){
Player.notify("The correct usage is '/wreplace fromid toid radius'");
return true;
}
Integer.parseInt(split[1]); Integer.parseInt(split[2]);Integer.parseInt(split[3]);
int fromid = 0;
try{fromid = Integer.parseInt(split[1]);}catch(NumberFormatException nfe){Player.notify("The correct usage is '/wreplace fromid toid radius");return true;}
int toid = 0;
try{fromid = Integer.parseInt(split[1]);}catch(NumberFormatException nfe){Player.notify("The correct usage is '/wreplace fromid toid radius");return true;}
int radius = 0;
try{fromid = Integer.parseInt(split[1]);}catch(NumberFormatException nfe){Player.notify("The correct usage is '/wreplace fromid toid radius");return true;}
WorldToolsVoids.replace(Player,fromid,toid,radius);
Player.sendMessage("�aBlocks Replaced.");
return true;
}
Player.notify("You cant use this command");return true;
}
if ((split[0].equalsIgnoreCase("/worldtools")) && (Player.canUseCommand("/worldtools"))) {
if (split.length >1 || split.length <1){Player.notify("The correct usage is '/worldtools'");return true;}
Player.sendMessage("�6 WorldTools " + WorldTools.version + " by Glacksy �8&�6 Spenk");
return true;
}
if ((split[0].equalsIgnoreCase("/suicide"))){
if ((Player.canUseCommand("/suicide") || (Player.canUseCommand("/worldtool")))){
if (split.length >1 || split.length <1){Player.notify("The correct usage is '/suicide'");return true;}
Player.setHealth(0);
Player.sendMessage("�cYou committed suicide");
return true;
}
Player.notify("You cant use this command");return true;
}
/**
* kill code
* @author spenk
*/
if ((split[0].equalsIgnoreCase("/kill"))){
if ((Player.canUseCommand("/worldtools")) || (Player.canUseCommand("/kill"))){
if (split.length <2 || split.length >2){
Player.notify("The correct usage is /kill <player>");
return true;
}else{
Player player = etc.getServer().matchPlayer(split[1]);
if (player == null){
Player.notify("�cThis Player Doesnt Exist or is currently not online!");
return true;
}
player.sendMessage("�4You got killed by �2"+Player.getName());
player.dropInventory(player.getLocation());
player.setHealth(0);
Player.sendMessage("�2Player sucsessfully killed!");
return true;
}
}
Player.sendMessage("�cYou cant use this command");
return true;
}
if ((split[0].equalsIgnoreCase("/heal"))){
if ((Player.canUseCommand("/worldtools")) || (Player.canUseCommand("/heal"))){
if (split.length <2 || split.length >2){
Player.sendMessage("�cThe correct usage is /heal <player>");
return true;
}else{
Player player = etc.getServer().matchPlayer(split[1]);
if (player == null){
Player.sendMessage("�cThis Player Doesnt Exist or is currently not online!");
return true;
}
player.sendMessage("�4You were healed by �2"+Player.getName());
player.setHealth(20);
player.setFoodLevel(20);
Player.sendMessage("�2Player sucsessfully healed!");
return true;
}
}
Player.notify("You cant use this command");return true;
}
if (split[0].equalsIgnoreCase("/save-inv")){
if (Player.canUseCommand("/worldtools") || (Player.canUseCommand("/save-inv"))){
if (split.length <1 || split.length >1){Player.notify("The correct usage is '/save-inv'");return true;}
etc.getServer().saveInventories();
Player.sendMessage("�aInventories saved");
return true;
}
Player.notify("You cant use this command");return true;
}
if ((split[0].equalsIgnoreCase("/godmode"))) {
if ((Player.canUseCommand("/godmode")) || (Player.canUseCommand("/worldtools"))){
if (split.length > 2){Player.notify("The correct usage is /godmode (player)");return true;
}
if (split.length == 1){
if (!god.contains(Player.getName())) {
god.add(Player.getName());
Player.sendMessage("�3Godmode have been enabled");
return true;
}else{
god.remove(Player.getName());
Player.sendMessage("�3Godmode have been disabled");
return true;
}
}
if (split.length == 2){
Player player2 = etc.getServer().matchPlayer(split[1]);
if (player2 == null){Player.notify("This player does not exist or is not logged in!");return true;}
if (!god.contains(player2.getName())) {
god.add(player2.getName());
Player.sendMessage("�3Godmode have been enabled");
player2.sendMessage("�3Godmode have been enabled");
return true;
}else{
god.remove(player2.getName());
Player.sendMessage("�3Godmode have been disabled");
player2.sendMessage("�3Godmode have been disabled");
return true;
}
}
Player.notify("You cant use this command");return true;
}
}
if (split[0].equalsIgnoreCase("/feed")){
if (Player.canUseCommand("/worldtools") || (Player.canUseCommand("/feed"))){
if (split.length <2 || split.length >2){
Player.notify("The correct usage is /feed player");
return true;
}
Player player2 = etc.getServer().matchPlayer(split[1]);
if (player2 == null) { Player.notify("This Player does not exist or is currently not logged in!"); return true;}
player2.setFoodLevel(20);
Player.sendMessage("�2"+player2.getName()+"'s foodlevel is restored!");
player2.sendMessage("�2"+Player.getName()+" Restored your foodlevel!");
return true;
}
Player.notify("You cant use this command");return true;
}
if (split[0].equalsIgnoreCase("/getip")){
if (Player.canUseCommand("/worldtools") || (Player.canUseCommand("/getip"))){
if (split.length <2 || split.length >2){
Player.notify("The correct usage is /getip <player>");
return true;
}
Player player2 = etc.getServer().matchPlayer(split[1]);
if (player2 == null){Player.notify("This player doesnt exist or is not logged in");return true;}
Player.sendMessage("�4"+player2.getName()+"�2 His IP is �4"+player2.getIP());
return true;
}
if (split[0].equalsIgnoreCase("/forcewarp")){
if (Player.canUseCommand("/worldtools") || (Player.canUseCommand("/forcewarp"))){
if (split.length <3 || split.length >3){
Player.notify("The correct usage is /forcewarp player warpname");
return true;
}
Player player2 = etc.getServer().matchPlayer(split[1]);
if (player2 == null) { Player.notify("This Player does not exist or is currently not logged in!"); return true;}
Warp warp = etc.getDataSource().getWarp(split[2]);
if (warp == null){Player.notify("This warp doesnt exist!");return true;}
player2.teleportTo(warp.Location);
Player.sendMessage("�2"+player2.getName()+" is warped!");
player2.sendMessage("�2"+Player.getName()+" warped you!");
return true;
}
Player.notify("You cant use this command");return true;
}
if (split[0].equalsIgnoreCase("/switchworlds")){
if (Player.canUseCommand("/worldtools") || (Player.canUseCommand("/switchworlds"))){
if (split.length <3 || split.length >3){
Player.notify("The correct usage is /swichworlds player worldname");
Player.notify("-1 = nether, 0 = normal world , 1 = end");
return true;
}
Player player2 = etc.getServer().matchPlayer(split[1]);
if (player2 == null) { Player.notify("This Player does not exist or is currently not logged in!"); return true;}
File f = new File(split[2]);
if (!f.exists()){
Player.notify("This World does not exist!");
return true;
}
if (!etc.getServer().isWorldLoaded(split[2])){
Player.notify("This world isnt loaded! please load it before you try to teleport!");
return true;
}
World[] w = etc.getServer().getWorld(split[2]);
player2.switchWorlds(w[0]);
Player.sendMessage("�2"+player2.getName()+" Has swiched to world "+w[0].getName());
player2.sendMessage("�2"+Player.getName()+" Has swiched you to world "+w[0].getName());
return true;
}
Player.notify("You cant use this command");return true;
}
if (split[0].equalsIgnoreCase("/freeze")) {
if (Player.canUseCommand("/freeze") || (Player.canUseCommand("/worldtools"))){
if (split.length > 2 || split.length < 2){Player.notify("The correct usage is '/freeze <player>'");return true;}
Player offender = etc.getServer().matchPlayer(split[1]);
if (offender == null){
Player.notify("This Player does not exist or is currently not logged in!");
return true;
}
if ((!frozen.contains(offender.getName())) && (split[1] != null)) {
offender.sendMessage("�2You have been frozen by �3" + Player.getName() + "�e!");
Player.sendMessage("�2You froze �3" + offender.getName() + "�2!");
frozen.add(offender.getName());
return true;
}
offender.sendMessage("�2You have been thawed!");
Player.sendMessage("�2You unfroze �3" + Player.getName() + "�2!");
frozen.remove(offender.getName());
return true;
}
Player.notify("You cant use this command");return true;
}
if (split[0].equalsIgnoreCase("/setspawn")){
if (Player.canUseCommand("/setspawn")||Player.canUseCommand("/worldtools")){
if (split.length > 1 || split.length < 1){Player.notify("The correct usage is '/setspawn'");return true;}
exactSpawn = new Location(Player.getX(), Player.getY(), Player.getZ(), Player.getRotation(), Player.getPitch());
PropertiesFile props = new PropertiesFile("worldtools.properties");
props.setString("exact-spawn", exactSpawn.x + "," + exactSpawn.y + "," + exactSpawn.z + "," + exactSpawn.rotX + "," + exactSpawn.rotY);
return true;
}
Player.notify("You cant use this command");return true;
}
if (split[0].equalsIgnoreCase("/spawn") && exactSpawn != null) {
if ((Player.canUseCommand("/spawn")) || Player.canUseCommand("/worldtools")){
Player.teleportTo(exactSpawn);
return true;
}
Player.notify("You cant use this command");return true;
}
if (split[0].equalsIgnoreCase("/locate")){
if (Player.canUseCommand("/locate")|| Player.canUseCommand("/worldtools")){
if (split.length > 2 || split.length < 2){
Player.notify("The correct usage is '/locate <player>'");return true;
}
Player player2 = etc.getServer().matchPlayer(split[1]);
if (player2 == null){Player.notify("�cTis player doesnt exist or is currently not logged in!");return true;}
Player.sendMessage(player2.getName()+"Is located in World:"+player2.getWorld().getName()+" in Dimension:"+player2.getLocation().dimension +" at location X:"+player2.getX() +" Y:"+player2.getY() +" Z:"+player2.getZ());
return true;
}
Player.notify("You cant use this command");return true;
}
}
return false;
}
|
diff --git a/shell/obr/src/main/java/org/apache/felix/karaf/shell/obr/RefreshUrlCommand.java b/shell/obr/src/main/java/org/apache/felix/karaf/shell/obr/RefreshUrlCommand.java
index a4d7e2e9..888d6f85 100644
--- a/shell/obr/src/main/java/org/apache/felix/karaf/shell/obr/RefreshUrlCommand.java
+++ b/shell/obr/src/main/java/org/apache/felix/karaf/shell/obr/RefreshUrlCommand.java
@@ -1,50 +1,50 @@
/*
* 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.felix.karaf.shell.obr;
import java.net.URL;
import java.util.List;
import org.osgi.service.obr.Repository;
import org.osgi.service.obr.RepositoryAdmin;
import org.apache.felix.gogo.commands.Argument;
import org.apache.felix.gogo.commands.Command;
@Command(scope = "obr", name = "refreshUrl", description = "Reloads the repositories to obtain a fresh list of bundles.")
public class RefreshUrlCommand extends ObrCommandSupport {
@Argument(index = 0, name = "urls", description = "Repository URLs to refresh (leave empty for all)", required = false, multiValued = true)
List<String> urls;
protected void doExecute(RepositoryAdmin admin) throws Exception {
- if (urls != null || urls.isEmpty()) {
+ if (urls != null && !urls.isEmpty()) {
for (String url : urls) {
admin.removeRepository(new URL(url));
admin.addRepository(new URL(url));
}
} else {
Repository[] repos = admin.listRepositories();
if ((repos != null) && (repos.length > 0)) {
for (int i = 0; i < repos.length; i++) {
admin.removeRepository(repos[i].getURL());
admin.addRepository(repos[i].getURL());
}
}
}
}
}
| true | true | protected void doExecute(RepositoryAdmin admin) throws Exception {
if (urls != null || urls.isEmpty()) {
for (String url : urls) {
admin.removeRepository(new URL(url));
admin.addRepository(new URL(url));
}
} else {
Repository[] repos = admin.listRepositories();
if ((repos != null) && (repos.length > 0)) {
for (int i = 0; i < repos.length; i++) {
admin.removeRepository(repos[i].getURL());
admin.addRepository(repos[i].getURL());
}
}
}
}
| protected void doExecute(RepositoryAdmin admin) throws Exception {
if (urls != null && !urls.isEmpty()) {
for (String url : urls) {
admin.removeRepository(new URL(url));
admin.addRepository(new URL(url));
}
} else {
Repository[] repos = admin.listRepositories();
if ((repos != null) && (repos.length > 0)) {
for (int i = 0; i < repos.length; i++) {
admin.removeRepository(repos[i].getURL());
admin.addRepository(repos[i].getURL());
}
}
}
}
|
diff --git a/modules/org.restlet/src/org/restlet/engine/converter/ConverterUtils.java b/modules/org.restlet/src/org/restlet/engine/converter/ConverterUtils.java
index 3c616c4b4..7d2c4b68d 100644
--- a/modules/org.restlet/src/org/restlet/engine/converter/ConverterUtils.java
+++ b/modules/org.restlet/src/org/restlet/engine/converter/ConverterUtils.java
@@ -1,157 +1,163 @@
/**
* Copyright 2005-2009 Noelios Technologies.
*
* The contents of this file are subject to the terms of one of the following
* open source licenses: LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL 1.0 (the
* "Licenses"). You can select the license that you prefer but you may not use
* this file except in compliance with one of these Licenses.
*
* You can obtain a copy of the LGPL 3.0 license at
* http://www.opensource.org/licenses/lgpl-3.0.html
*
* You can obtain a copy of the LGPL 2.1 license at
* http://www.opensource.org/licenses/lgpl-2.1.php
*
* You can obtain a copy of the CDDL 1.0 license at
* http://www.opensource.org/licenses/cddl1.php
*
* You can obtain a copy of the EPL 1.0 license at
* http://www.opensource.org/licenses/eclipse-1.0.php
*
* See the Licenses for the specific language governing permissions and
* limitations under the Licenses.
*
* Alternatively, you can obtain a royalty free commercial license with less
* limitations, transferable or non-transferable, directly at
* http://www.noelios.com/products/restlet-engine
*
* Restlet is a registered trademark of Noelios Technologies.
*/
package org.restlet.engine.converter;
import java.util.ArrayList;
import java.util.List;
import org.restlet.engine.Engine;
import org.restlet.engine.resource.VariantInfo;
import org.restlet.representation.Representation;
import org.restlet.representation.Variant;
import org.restlet.resource.UniformResource;
/**
* Utilities for the converter service.
*
* @author Jerome Louvel
*/
public class ConverterUtils {
/**
* Returns the list of variants that can be converted from a given object
* class.
*
* @param sourceClass
* The source class.
* @param targetVariant
* The expected representation metadata.
* @return The list of variants that can be converted.
*/
public static List<VariantInfo> getVariants(Class<?> sourceClass,
Variant targetVariant) {
List<VariantInfo> result = null;
List<VariantInfo> helperVariants = null;
for (ConverterHelper ch : Engine.getInstance()
.getRegisteredConverters()) {
+ // List of variants that can be converted from the source class
helperVariants = ch.getVariants(sourceClass);
if (helperVariants != null) {
+ // Loop over the variants list
for (VariantInfo helperVariant : helperVariants) {
if (helperVariant.includes(targetVariant)) {
if (result == null) {
result = new ArrayList<VariantInfo>();
}
+ // Detected a more generic variant, but still consider
+ // the conversion is possible to the target variant.
+ // TODO Add support for the other kind of metadata
result
.add(new VariantInfo(targetVariant
.getMediaType()));
- } else if (helperVariant.includes(targetVariant)) {
+ } else if (targetVariant.includes(helperVariant)) {
+ // Add this variant for content negotiation.
if (result == null) {
result = new ArrayList<VariantInfo>();
}
result.add(helperVariant);
}
}
}
}
return result;
}
/**
* Returns the best converter helper matching the given parameters.
*
* @param source
* The object to convert to a representation.
* @param target
* The target representation variant.
* @param resource
* The optional parent resource.
* @return The matched converter helper or null.
*/
public static ConverterHelper getBestHelper(Object source, Variant target,
UniformResource resource) {
ConverterHelper result = null;
float bestScore = -1.0F;
float currentScore;
for (ConverterHelper ch : Engine.getInstance()
.getRegisteredConverters()) {
currentScore = ch.score(source, target, resource);
if (currentScore > bestScore) {
result = ch;
}
}
return result;
}
/**
* Returns the best converter helper matching the given parameters.
*
* @param <T>
* The target class.
* @param source
* The source representation variant.
* @param target
* The target class.
* @param resource
* The parent resource.
* @return The matched converter helper or null.
*/
public static <T> ConverterHelper getBestHelper(Representation source,
Class<T> target, UniformResource resource) {
ConverterHelper result = null;
float bestScore = -1.0F;
float currentScore;
for (ConverterHelper ch : Engine.getInstance()
.getRegisteredConverters()) {
currentScore = ch.score(source, target, resource);
if (currentScore > bestScore) {
result = ch;
}
}
return result;
}
/**
* Private constructor to ensure that the class acts as a true utility class
* i.e. it isn't instantiable and extensible.
*/
private ConverterUtils() {
}
}
| false | true | public static List<VariantInfo> getVariants(Class<?> sourceClass,
Variant targetVariant) {
List<VariantInfo> result = null;
List<VariantInfo> helperVariants = null;
for (ConverterHelper ch : Engine.getInstance()
.getRegisteredConverters()) {
helperVariants = ch.getVariants(sourceClass);
if (helperVariants != null) {
for (VariantInfo helperVariant : helperVariants) {
if (helperVariant.includes(targetVariant)) {
if (result == null) {
result = new ArrayList<VariantInfo>();
}
result
.add(new VariantInfo(targetVariant
.getMediaType()));
} else if (helperVariant.includes(targetVariant)) {
if (result == null) {
result = new ArrayList<VariantInfo>();
}
result.add(helperVariant);
}
}
}
}
return result;
}
| public static List<VariantInfo> getVariants(Class<?> sourceClass,
Variant targetVariant) {
List<VariantInfo> result = null;
List<VariantInfo> helperVariants = null;
for (ConverterHelper ch : Engine.getInstance()
.getRegisteredConverters()) {
// List of variants that can be converted from the source class
helperVariants = ch.getVariants(sourceClass);
if (helperVariants != null) {
// Loop over the variants list
for (VariantInfo helperVariant : helperVariants) {
if (helperVariant.includes(targetVariant)) {
if (result == null) {
result = new ArrayList<VariantInfo>();
}
// Detected a more generic variant, but still consider
// the conversion is possible to the target variant.
// TODO Add support for the other kind of metadata
result
.add(new VariantInfo(targetVariant
.getMediaType()));
} else if (targetVariant.includes(helperVariant)) {
// Add this variant for content negotiation.
if (result == null) {
result = new ArrayList<VariantInfo>();
}
result.add(helperVariant);
}
}
}
}
return result;
}
|
diff --git a/src/org/antlr/works/visualization/graphics/graph/GGraphGroup.java b/src/org/antlr/works/visualization/graphics/graph/GGraphGroup.java
index dacc2e7..9f113f7 100644
--- a/src/org/antlr/works/visualization/graphics/graph/GGraphGroup.java
+++ b/src/org/antlr/works/visualization/graphics/graph/GGraphGroup.java
@@ -1,399 +1,398 @@
/*
[The "BSD licence"]
Copyright (c) 2005 Jean Bovet
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 name of the author may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.antlr.works.visualization.graphics.graph;
import org.antlr.analysis.NFAState;
import org.antlr.works.visualization.fa.FAState;
import org.antlr.works.visualization.fa.FATransition;
import org.antlr.works.visualization.graphics.GContext;
import org.antlr.works.visualization.graphics.path.GPath;
import org.antlr.works.visualization.graphics.path.GPathElement;
import org.antlr.works.visualization.graphics.path.GPathGroup;
import org.antlr.works.visualization.graphics.primitive.GDimension;
import org.antlr.works.visualization.graphics.shape.GNode;
import org.antlr.works.visualization.skin.syntaxdiagram.SDSkin;
import java.awt.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
public class GGraphGroup extends GGraphAbstract {
public static final int TITLE_OFFSET = 100;
public GDimension dimension = new GDimension();
public List graphs = new ArrayList();
public GPathGroup pathGroup = new GPathGroup();
protected GContext defaultContext;
public GGraphGroup() {
// The default context is used to evaluate the position of certain objects in addPath()
// because position requires a context to be evaluated ;-)
defaultContext = new GContext();
defaultContext.setSkin(new SDSkin());
}
public void setEnable(boolean flag) {
pathGroup.setEnable(flag);
}
public void setContext(GContext context) {
super.setContext(context);
for (Iterator iterator = graphs.iterator(); iterator.hasNext();) {
GGraph graph = (GGraph) iterator.next();
graph.setContext(context);
}
pathGroup.setContext(context);
}
public void add(GGraph graph) {
dimension.maxWidth(graph.dimension.width);
dimension.addUp(graph.dimension.up);
dimension.addDown(graph.dimension.down);
if(graphs.size()>0)
dimension.addDown(GContext.LINE_SPACE);
graphs.add(graph);
}
public float getHeight() {
return getDimension().getPixelHeight(context);
}
public float getWidth() {
return getDimension().getPixelWidth(context)+TITLE_OFFSET;
}
protected int pathIndex;
public List getTransitionsMatchingSkippedStates(List candidates, List states) {
/** First convert the list of NFAStates to a list of Integer containing
* the state number
*/
List statesNumbers = new ArrayList();
for(int i=0; i<states.size(); i++) {
statesNumbers.add((new Integer(((NFAState)states.get(i)).stateNumber)));
}
/** Select only the transitions that containing all the state numbers */
List newCandidates = new ArrayList();
for(int c=0; c<candidates.size(); c++) {
FATransition t = (FATransition)candidates.get(c);
if(t.skippedStates != null && t.skippedStates.containsAll(statesNumbers)) {
newCandidates.add(t);
}
}
return newCandidates;
}
public FATransition getNodeTransitionToNextNonSkippedState(GNode node, List path) {
List candidateTransitions = new ArrayList(node.state.transitions);
FATransition candidate = null;
int start = pathIndex;
loop:
for(; pathIndex < path.size(); pathIndex++) {
candidateTransitions = getTransitionsMatchingSkippedStates(candidateTransitions, path.subList(start, pathIndex+1));
switch(candidateTransitions.size()) {
case 0: // No more transitions. Exit and use the candidate transition.
break loop;
case 1:
// The uniquely identified transition has been found.
// Continue to loop until all skipped states have been found.
candidate = (FATransition) candidateTransitions.get(0);
break;
default:
// More than one transition candidates found. Look if any of these
// transitions's target state correspond to the next path state to avoid
// missing a transition: this can happen if a transition is a subset of
// the others (the next state of the path can return no transition at all)
if(pathIndex+1 < path.size()) {
NFAState nextPathState = (NFAState) path.get(pathIndex+1);
for(int i=0; i<candidateTransitions.size(); i++) {
FATransition t = (FATransition)candidateTransitions.get(i);
if(t.target.stateNumber == nextPathState.stateNumber) {
pathIndex++; // always points to the next element after the transition
return t;
}
}
}
break;
}
}
return candidate;
}
public void addNextElementInSameRule(List elements, GNode node, GNode nextNode, NFAState nextState) {
elements.add(GPathElement.createElement(node));
FATransition t = node.state.getTransitionToStateNumber(nextState.stateNumber);
if(t == null) {
// Probably a loop. In this case, the transition is located in the target state.
t = nextNode.state.getTransitionToStateNumber(node.state.stateNumber);
if(t == null) {
// Still no transition found. This is a reference to the same rule (recursive)
elements.add(GPathElement.createLink(node, nextNode));
} else {
// Add the loop transition to the path
elements.add(GPathElement.createElement(nextNode.getLink(t)));
}
} else {
// Add the transition to the path
elements.add(GPathElement.createElement(node.getLink(t)));
}
}
public void addNextElementInOtherRule(List elements, GNode node, GNode externalNode, GNode nextNode, NFAState nextState) {
if(externalNode == null) {
// The external node is not specified. Try to find it.
if(node.state.getFirstTransition() == null) {
// If the node contains no transition (probably if it is at the end of a rule), then
// ignore externalNode. We will draw only a link from node to nextNode.
} else {
// Find the transition that points to the external rule ref
FATransition t = node.state.getTransitionToExternalStateRule(nextState.getEnclosingRule());
if(t == null) {
System.err.println("[GGraphGroup] No transition to external state "+nextState.stateNumber+"["+nextState.getEnclosingRule()+"] - using first transition by default");
t = node.state.getFirstTransition();
}
externalNode = findNodeForStateNumber(t.target.stateNumber);
}
}
if(externalNode == null) {
// Add the link between node and nextNode, ignore externalNode because it doesn't exist
elements.add(GPathElement.createElement(node));
elements.add(GPathElement.createLink(node, nextNode));
} else {
elements.add(GPathElement.createElement(node));
// Add the link between node and externalNode.
FATransition t = node.state.getTransitionToStateNumber(externalNode.state.stateNumber);
elements.add(GPathElement.createElement(node.getLink(t)));
elements.add(GPathElement.createElement(externalNode));
// Add the link between externalNode and nextNode
elements.add(GPathElement.createLink(externalNode, nextNode));
}
}
public void addPath(List path, boolean disabled, Map skippedStates) {
List elements = new ArrayList();
/** path contains a list of NFAState states (from ANTLR): they represent
* all the states along the path. The graphical representation of the NFA/SD
* does not necessarily contains all the states of the path because the representation
* can be simplified to remove all unecessary states.
* The problem here is to use the information stored in the transition of the
* graphical representation to figure out exactly which graphical node corresponds
* to the path.
*/
/*System.out.println("***");
for (Iterator iterator = path.iterator(); iterator.hasNext();) {
System.out.println(iterator.next());
- } */
+ }*/
NFAState state;
GNode node;
NFAState nextState = null;
GNode nextNode = null;
for(pathIndex = 0; pathIndex < path.size(); pathIndex++) {
if(pathIndex == 0) {
nextState = (NFAState)path.get(pathIndex);
nextNode = findNodeForStateNumber(nextState.stateNumber);
if(nextNode == null) {
// A path can start from anywhere in the graph. It might happen
// that the starting state of the path has been skipped by
// the optimization in FAFactory. We use the skippedStates mapping
// to find out what is the parent state of the skipped state.
FAState parentState = (FAState) skippedStates.get(new Integer(nextState.stateNumber));
if(parentState == null) {
System.err.println("[GGraphGroup] Starting path state "+nextState.stateNumber+"["+nextState.getEnclosingRule()+"] cannot be found in the graph");
return;
} else {
nextNode = findNodeForStateNumber(parentState.stateNumber);
}
}
continue;
} else {
state = nextState;
node = nextNode;
}
nextState = (NFAState)path.get(pathIndex);
nextNode = findNodeForStateNumber(nextState.stateNumber);
GNode externalNode = null;
if(nextNode == null) {
// The state has probably been skipped during the graphical rendering.
// Find the next non-skipped state.
FATransition t = getNodeTransitionToNextNonSkippedState(node, path);
if(t == null) {
// No transition found. Look in the skipped states mapping because
// it might be possible that the next state is in another rule but
// cannot be found because it has been skipped.
FAState parentState = (FAState) skippedStates.get(new Integer(nextState.stateNumber));
if(parentState == null) {
- // OK. The node really does not exist.
- if(node != null)
- elements.add(GPathElement.createElement(node));
- break;
+ // OK. The node really does not exist. Continue by skipping it.
+ nextNode = node;
+ continue;
} else {
nextNode = findNodeForStateNumber(parentState.stateNumber);
}
} else {
nextState = (NFAState)path.get(pathIndex);
if(t.target.stateNumber == nextState.stateNumber) {
nextNode = findNodeForStateNumber(t.target.stateNumber);
} else {
// The only case that the target state of the transition if not
// the next state of the path is when the next state of the path
// is in another rule. In this case, the target state of the transition
// will contain a negative state number indicating an external rule reference:
// this external rule reference is added by AW during rendering and is not
// part of any ANTLR NFA.
// This node is the node representing the external rule reference
// before jumping outside of the rule
externalNode = findNodeForStateNumber(t.target.stateNumber);
// This node is the first node in the other rule
nextNode = findNodeForStateNumber(nextState.stateNumber);
}
}
}
- if(state == null)
+ if(state == null || node == null || nextNode == null)
continue;
if(state.getEnclosingRule().equals(nextState.getEnclosingRule()))
addNextElementInSameRule(elements, node, nextNode, nextState);
else
addNextElementInOtherRule(elements, node, externalNode, nextNode, nextState);
}
if(nextNode != null)
elements.add(GPathElement.createElement(nextNode));
pathGroup.addPath(new GPath(elements, disabled));
}
public void addUnreachableAlt(NFAState state, Integer alt) {
List elements = new ArrayList();
GNode node = findNodeForStateNumber(state.stateNumber);
if(node == null) {
System.err.println("[GGraphGroup] Decision state "+state.stateNumber+"["+state.getEnclosingRule()+"] cannot be found in the graph");
return;
}
List transitions = node.state.transitions;
int altNum = alt.intValue()-1;
if(altNum >= transitions.size()) {
System.err.println("[GGraphGroup] Unreachable alt "+altNum+"["+state.getEnclosingRule()+"] is out of bounds: "+transitions.size());
return;
}
FATransition t = (FATransition) transitions.get(altNum);
elements.add(GPathElement.createElement(node));
elements.add(GPathElement.createElement(node.getLink(t)));
/** This path has to be visible but not selectable */
GPath path = new GPath(elements, true);
path.setVisible(true);
path.setSelectable(false);
pathGroup.addPath(path);
}
public GNode findNodeForStateNumber(int stateNumber) {
for (Iterator iterator = graphs.iterator(); iterator.hasNext();) {
GGraph graph = (GGraph) iterator.next();
GNode node = graph.findNodeForStateNumber(stateNumber);
if(node != null) {
return node;
}
}
return null;
}
public GDimension getDimension() {
return dimension;
}
public void render(float ox, float oy) {
ox += TITLE_OFFSET;
for (int i = 0; i<graphs.size(); i++) {
GGraph graph = (GGraph)graphs.get(i);
graph.render(ox, oy);
if(i<graphs.size()-1)
oy += graph.getHeight()+context.getPixelLineSpace();
}
setRendered(true);
}
public void draw() {
context.nodeColor = Color.black;
context.linkColor = Color.black;
context.setLineWidth(1);
for (int i = 0; i<graphs.size(); i++) {
GGraph graph = (GGraph)graphs.get(i);
graph.draw();
context.setColor(Color.black);
context.drawString(context.getRuleFont(), graph.name, TITLE_OFFSET-5, graph.offsetY, GContext.ALIGN_RIGHT);
}
pathGroup.draw();
if(context.drawdimension) {
context.setLineWidth(1);
context.setColor(Color.lightGray);
float width = getDimension().getPixelWidth(context);
float up = getDimension().getPixelUp(context);
float down = getDimension().getPixelDown(context);
if(up+down>0)
context.drawRect(0, 0, width, up+down, false);
}
}
}
| false | true | public void addPath(List path, boolean disabled, Map skippedStates) {
List elements = new ArrayList();
/** path contains a list of NFAState states (from ANTLR): they represent
* all the states along the path. The graphical representation of the NFA/SD
* does not necessarily contains all the states of the path because the representation
* can be simplified to remove all unecessary states.
* The problem here is to use the information stored in the transition of the
* graphical representation to figure out exactly which graphical node corresponds
* to the path.
*/
/*System.out.println("***");
for (Iterator iterator = path.iterator(); iterator.hasNext();) {
System.out.println(iterator.next());
} */
NFAState state;
GNode node;
NFAState nextState = null;
GNode nextNode = null;
for(pathIndex = 0; pathIndex < path.size(); pathIndex++) {
if(pathIndex == 0) {
nextState = (NFAState)path.get(pathIndex);
nextNode = findNodeForStateNumber(nextState.stateNumber);
if(nextNode == null) {
// A path can start from anywhere in the graph. It might happen
// that the starting state of the path has been skipped by
// the optimization in FAFactory. We use the skippedStates mapping
// to find out what is the parent state of the skipped state.
FAState parentState = (FAState) skippedStates.get(new Integer(nextState.stateNumber));
if(parentState == null) {
System.err.println("[GGraphGroup] Starting path state "+nextState.stateNumber+"["+nextState.getEnclosingRule()+"] cannot be found in the graph");
return;
} else {
nextNode = findNodeForStateNumber(parentState.stateNumber);
}
}
continue;
} else {
state = nextState;
node = nextNode;
}
nextState = (NFAState)path.get(pathIndex);
nextNode = findNodeForStateNumber(nextState.stateNumber);
GNode externalNode = null;
if(nextNode == null) {
// The state has probably been skipped during the graphical rendering.
// Find the next non-skipped state.
FATransition t = getNodeTransitionToNextNonSkippedState(node, path);
if(t == null) {
// No transition found. Look in the skipped states mapping because
// it might be possible that the next state is in another rule but
// cannot be found because it has been skipped.
FAState parentState = (FAState) skippedStates.get(new Integer(nextState.stateNumber));
if(parentState == null) {
// OK. The node really does not exist.
if(node != null)
elements.add(GPathElement.createElement(node));
break;
} else {
nextNode = findNodeForStateNumber(parentState.stateNumber);
}
} else {
nextState = (NFAState)path.get(pathIndex);
if(t.target.stateNumber == nextState.stateNumber) {
nextNode = findNodeForStateNumber(t.target.stateNumber);
} else {
// The only case that the target state of the transition if not
// the next state of the path is when the next state of the path
// is in another rule. In this case, the target state of the transition
// will contain a negative state number indicating an external rule reference:
// this external rule reference is added by AW during rendering and is not
// part of any ANTLR NFA.
// This node is the node representing the external rule reference
// before jumping outside of the rule
externalNode = findNodeForStateNumber(t.target.stateNumber);
// This node is the first node in the other rule
nextNode = findNodeForStateNumber(nextState.stateNumber);
}
}
}
if(state == null)
continue;
if(state.getEnclosingRule().equals(nextState.getEnclosingRule()))
addNextElementInSameRule(elements, node, nextNode, nextState);
else
addNextElementInOtherRule(elements, node, externalNode, nextNode, nextState);
}
if(nextNode != null)
elements.add(GPathElement.createElement(nextNode));
pathGroup.addPath(new GPath(elements, disabled));
}
| public void addPath(List path, boolean disabled, Map skippedStates) {
List elements = new ArrayList();
/** path contains a list of NFAState states (from ANTLR): they represent
* all the states along the path. The graphical representation of the NFA/SD
* does not necessarily contains all the states of the path because the representation
* can be simplified to remove all unecessary states.
* The problem here is to use the information stored in the transition of the
* graphical representation to figure out exactly which graphical node corresponds
* to the path.
*/
/*System.out.println("***");
for (Iterator iterator = path.iterator(); iterator.hasNext();) {
System.out.println(iterator.next());
}*/
NFAState state;
GNode node;
NFAState nextState = null;
GNode nextNode = null;
for(pathIndex = 0; pathIndex < path.size(); pathIndex++) {
if(pathIndex == 0) {
nextState = (NFAState)path.get(pathIndex);
nextNode = findNodeForStateNumber(nextState.stateNumber);
if(nextNode == null) {
// A path can start from anywhere in the graph. It might happen
// that the starting state of the path has been skipped by
// the optimization in FAFactory. We use the skippedStates mapping
// to find out what is the parent state of the skipped state.
FAState parentState = (FAState) skippedStates.get(new Integer(nextState.stateNumber));
if(parentState == null) {
System.err.println("[GGraphGroup] Starting path state "+nextState.stateNumber+"["+nextState.getEnclosingRule()+"] cannot be found in the graph");
return;
} else {
nextNode = findNodeForStateNumber(parentState.stateNumber);
}
}
continue;
} else {
state = nextState;
node = nextNode;
}
nextState = (NFAState)path.get(pathIndex);
nextNode = findNodeForStateNumber(nextState.stateNumber);
GNode externalNode = null;
if(nextNode == null) {
// The state has probably been skipped during the graphical rendering.
// Find the next non-skipped state.
FATransition t = getNodeTransitionToNextNonSkippedState(node, path);
if(t == null) {
// No transition found. Look in the skipped states mapping because
// it might be possible that the next state is in another rule but
// cannot be found because it has been skipped.
FAState parentState = (FAState) skippedStates.get(new Integer(nextState.stateNumber));
if(parentState == null) {
// OK. The node really does not exist. Continue by skipping it.
nextNode = node;
continue;
} else {
nextNode = findNodeForStateNumber(parentState.stateNumber);
}
} else {
nextState = (NFAState)path.get(pathIndex);
if(t.target.stateNumber == nextState.stateNumber) {
nextNode = findNodeForStateNumber(t.target.stateNumber);
} else {
// The only case that the target state of the transition if not
// the next state of the path is when the next state of the path
// is in another rule. In this case, the target state of the transition
// will contain a negative state number indicating an external rule reference:
// this external rule reference is added by AW during rendering and is not
// part of any ANTLR NFA.
// This node is the node representing the external rule reference
// before jumping outside of the rule
externalNode = findNodeForStateNumber(t.target.stateNumber);
// This node is the first node in the other rule
nextNode = findNodeForStateNumber(nextState.stateNumber);
}
}
}
if(state == null || node == null || nextNode == null)
continue;
if(state.getEnclosingRule().equals(nextState.getEnclosingRule()))
addNextElementInSameRule(elements, node, nextNode, nextState);
else
addNextElementInOtherRule(elements, node, externalNode, nextNode, nextState);
}
if(nextNode != null)
elements.add(GPathElement.createElement(nextNode));
pathGroup.addPath(new GPath(elements, disabled));
}
|
diff --git a/ide/eclipse/server/org.wso2.developerstudio.eclipse.carbonserver.base/src/org/wso2/developerstudio/eclipse/carbonserver/base/manager/CarbonServerManager.java b/ide/eclipse/server/org.wso2.developerstudio.eclipse.carbonserver.base/src/org/wso2/developerstudio/eclipse/carbonserver/base/manager/CarbonServerManager.java
index cff420304..eccce8b55 100644
--- a/ide/eclipse/server/org.wso2.developerstudio.eclipse.carbonserver.base/src/org/wso2/developerstudio/eclipse/carbonserver/base/manager/CarbonServerManager.java
+++ b/ide/eclipse/server/org.wso2.developerstudio.eclipse.carbonserver.base/src/org/wso2/developerstudio/eclipse/carbonserver/base/manager/CarbonServerManager.java
@@ -1,816 +1,818 @@
/*
* Copyright (c) 2010, WSO2 Inc. (http://www.wso2.org) 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 org.wso2.developerstudio.eclipse.carbonserver.base.manager;
import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResourceChangeEvent;
import org.eclipse.core.resources.IResourceChangeListener;
import org.eclipse.core.resources.IResourceDelta;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jst.server.generic.core.internal.GenericServer;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.wst.server.core.IModule;
import org.eclipse.wst.server.core.IServer;
import org.eclipse.wst.server.core.ServerCore;
import org.eclipse.wst.server.core.ServerPort;
import org.wso2.developerstudio.eclipse.carbonserver.base.Activator;
import org.wso2.developerstudio.eclipse.carbonserver.base.exception.NoSuchCarbonOperationDefinedException;
import org.wso2.developerstudio.eclipse.carbonserver.base.impl.Credentials;
import org.wso2.developerstudio.eclipse.carbonserver.base.interfaces.ICredentials;
import org.wso2.developerstudio.eclipse.carbonserver.base.monitor.CarbonServerLifeCycleListener;
import org.wso2.developerstudio.eclipse.logging.core.IDeveloperStudioLog;
import org.wso2.developerstudio.eclipse.logging.core.Logger;
import org.wso2.developerstudio.eclipse.server.base.core.IServerManager;
import org.wso2.developerstudio.eclipse.server.base.core.ServerController;
import org.wso2.developerstudio.eclipse.utils.file.FileUtils;
public final class CarbonServerManager implements IServerManager {
private static IDeveloperStudioLog log=Logger.getLog(Activator.PLUGIN_ID);
private static List<IServer> servers;
private static Map<String,ICarbonOperationManager> serverPlugins;
private static Map<String,String> serverRuntimePlugins;
private static CarbonServerManager instance;
private static Map<IServer,CarbonServerInformation> appServerInformation;
private static CarbonServerLifeCycleListener carbonServerLifeCycleListener;
private CarbonServerManager(){
init();
}
public static CarbonServerManager getInstance(){
if (instance==null)
instance=new CarbonServerManager();
return instance;
}
private static Map<String,ICarbonOperationManager> getServerPlugin(){
if (serverPlugins==null)
serverPlugins=new HashMap<String,ICarbonOperationManager>();
if (serverRuntimePlugins==null)
serverRuntimePlugins=new HashMap<String,String>();
return serverPlugins;
}
private static Map<String,String> getServerRuntimeIdPlugin(){
if (serverRuntimePlugins==null)
serverRuntimePlugins=new HashMap<String,String>();
return serverRuntimePlugins;
}
public static List<IServer> getServers(){
if (servers==null)
servers=new ArrayList<IServer>();
return servers;
}
public static void serverAdded(IServer server){
ICarbonOperationManager serverOperationManager = getServerOperationManager(server);
if (serverOperationManager!=null){
getServers().add(server);
IServerManager wsasServerManager = ServerController.getInstance().getServerManager();
HashMap<String,Object> operationParameters=new HashMap<String,Object>();
operationParameters.put(ICarbonOperationManager.PARAMETER_TYPE, ICarbonOperationManager.OPERATION_GET_SERVER_PORTS);
Object r;
CarbonServerInformation serverInformation = new CarbonServerInformation();
serverInformation.setServerId(server.getId());
ServerPort[] wsasPorts=new ServerPort[]{};
try {
r = wsasServerManager.executeOperationOnServer(server, operationParameters);
if (r instanceof ServerPort[])
wsasPorts=(ServerPort[])r;
}catch (NoSuchCarbonOperationDefinedException e) {
//ports cannot be retrieved
}catch (Exception e) {
log.error(e);
}
serverInformation.setServerPorts(wsasPorts);
//The localrepo path is for now is the bin distribution path. this needs to be fixed in order to be set inside the workspace path
// String workspaceRootPath = ResourcesPlugin.getWorkspace().getRoot().getLocation().toOSString();
// String serverPath=FileUtils.addNodesToPath(workspaceRootPath, new String[]{".metadata",".carbon",server.getId()});
IPath serverHome = getServerHome(server);
if (serverHome!=null) {
String serverPath = serverHome.toOSString();
(new File(serverPath)).mkdirs();
serverInformation.setServerLocalWorkspacePath(serverPath);
}
getAppServerInformation().put(server, serverInformation);
try {
initializeServerConfigurations(server);
} catch (Exception e) {
log.error(e);
}
}
}
public static void serverRemoved(IServer server){
if (getServers().contains(server)){
try {
cleanupServerConfigurations(server);
} catch (Exception e) {
log.error(e);
}
getServers().remove(server);
if (getAppServerInformation().containsKey(server))
getAppServerInformation().remove(server);
}
}
public static void serverStateChanged(IServer server){
}
public static void registerAppServerPlugin(String serverId, ICarbonOperationManager opManager){
if (!getServerPlugin().containsKey(serverId)){
getServerPlugin().put(serverId, opManager);
getServerRuntimeIdPlugin().put(opManager.getRuntimeId(), serverId);
addExistingServers();
}
}
public static void unregisterAppServerPlugin(String serverId){
if (getServerPlugin().containsKey(serverId))
serverPlugins.remove(serverId);
}
public static ICarbonOperationManager getServerOperationManager(IServer server){
return getServerOperationManager(server.getId());
}
public static ICarbonOperationManager getServerOperationManager(String serverId){
IServer server = getServer(serverId);
if (getServerPlugin().containsKey(server.getServerType().getId()))
return getServerPlugin().get(server.getServerType().getId());
else{
return null;
}
}
public static ICarbonOperationManager getServerOperationManagerByServerType(String serverTypeId){
if (getServerPlugin().containsKey(serverTypeId))
return getServerPlugin().get(serverTypeId);
else{
return null;
}
}
public Object executeOperationOnServer(IServer server,
Map<String, Object> operation) throws Exception {
return executeOperationOnServer(server.getId(),operation);
}
public Object executeOperationOnServer(String serverId,Map<String, Object> operation) throws Exception {
ICarbonOperationManager serverOperationManager = getServerOperationManager(serverId);
if (!operation.containsKey(ICarbonOperationManager.PARAMETER_SERVER))
addServerToParameters(operation, getServer(serverId));
if (serverOperationManager==null)
return null;
else
return serverOperationManager.executeOperation(operation);
}
public static IServer getServer(String serverId){
IServer server=null;
for(IServer s:getServers()){
if (s.getId().equalsIgnoreCase(serverId)){
server=s;
break;
}
}
if (server==null){
IServer[] s= ServerCore.getServers();
for(IServer aserver:s){
if (aserver.getId().equals(serverId)){
server=aserver;
break;
}
}
}
return server;
}
public IProject[] getProjectsUsedByRuntime(String serverId) {
return null;
}
public String getRuntimeServerIdForProject(IProject project) {
// for(IServer server:getServers()){
// for(IModule module:server.getModules()){
// if (module.getProject()==project){
// break;
// }
// }
// }
return null;
}
public static String[] getServerIdForProject(IProject project) {
List<String> serverIds=new ArrayList<String>();
IServer[] serversForProject = getServersForProject(project);
for(IServer server:serversForProject){
serverIds.add(server.getId());
}
return serverIds.toArray(new String[]{});
}
public static IServer[] getServersForProject(IProject project) {
List<IServer> serverIds=new ArrayList<IServer>();
for(IServer server:getServers()){
for(IModule module:server.getModules()){
if (module.getProject()==project){
serverIds.add(server);
}
}
}
return serverIds.toArray(new IServer[]{});
}
public IPath getServerHome(String serverId) {
IServer server = getServer(serverId);
return getServerHome(server);
}
public static IPath getServerHome(IServer server){
IPath location=null;
if (server!=null){
IServerManager wsasServerManager = getInstance();
HashMap<String,Object> operationParameters=new HashMap<String,Object>();
operationParameters.put(ICarbonOperationManager.PARAMETER_TYPE, ICarbonOperationManager.OPERATION_GET_SERVER_HOME);
Object r;
try {
r = wsasServerManager.executeOperationOnServer(server, operationParameters);
if (r instanceof IPath)
location=(IPath)r;
} catch (NoSuchCarbonOperationDefinedException e) {
return null;
} catch (Exception e) {
log.error(e);
}
}
return location;
}
public int getServerStatus(String serverId) {
IServer server = getServer(serverId);
if (server==null)
return 0;
else
return server.getServerState();
}
public boolean restartServer(String serverId) {
IServer server = getServer(serverId);
if (server==null)
return false;
else{
//TODO the restart a server
return false;
}
}
public boolean startServer(String serverId,Object shell) {
IServer server = getServer(serverId);
if (server==null)
return false;
else{
try {
if (server.getServerState()!=IServer.STATE_STARTING){
server.start("run",(IProgressMonitor)null);
}
if (shell==null)
return true;
else{
if (shell instanceof Shell)
return waitUntilTheServerStarts(server,(Shell)shell);
else
return true;
}
} catch (CoreException e) {
return false;
}
}
}
public static IServer getRunningServer(){
IServer server=null;
for(IServer s:getServers()){
if (s.getServerState()==IServer.STATE_STARTED){
server=s;
break;
}
}
return server;
}
public boolean stopServer(String serverId) {
IServer server = getServer(serverId);
if (server==null)
return false;
else{
server.stop(false);
return true;
}
}
public static void initiateAppServerManagementOperations(){
carbonServerLifeCycleListener = new CarbonServerLifeCycleListener();
ServerCore.addServerLifecycleListener(carbonServerLifeCycleListener);
}
public static void deInitiateAppServerManagementOperations(){
if (carbonServerLifeCycleListener!=null){
ServerCore.removeServerLifecycleListener(carbonServerLifeCycleListener);
}
}
private static void addExistingServers(){
IServer[] s= ServerCore.getServers();
for(IServer server:s){
if (!getServers().contains(server))
serverAdded(server);
}
}
public String[] getServerIds() {
List<String> list=new ArrayList<String>();
for(IServer server:getServers()){
list.add(server.getId());
}
return list.toArray(new String[]{});
}
public String[] getServerLibraryPaths(String serverId) throws Exception {
IServer server = getServer(serverId);
return getServerLibraryPaths(server);
}
public static String[] getServerLibraryPaths(IServer server) throws Exception {
String[] result=null;
if (server!=null){
IServerManager wsasServerManager = ServerController.getInstance().getServerManager();
HashMap<String,Object> operationParameters=new HashMap<String,Object>();
operationParameters.put(ICarbonOperationManager.PARAMETER_TYPE, ICarbonOperationManager.OPERATION_GET_LIBRARY_PATHS);
Object r = wsasServerManager.executeOperationOnServer(server, operationParameters);//getWSDLConversionResultUrl(resourceFile);
if (r instanceof String[]){
result=(String[])r;
IPath serverLocation = getServerHome(server);
for(int i=0;i<result.length;i++){
result[i]=FileUtils.addAnotherNodeToPath(serverLocation.toOSString(), result[i]);
}
}
}
return result;
}
public static URL getServiceWSDLUrl(IServer server, String serviceName) throws Exception {
URL result=null;
if (server!=null){
IServerManager wsasServerManager = ServerController.getInstance().getServerManager();
HashMap<String,Object> operationParameters=new HashMap<String,Object>();
operationParameters.put(ICarbonOperationManager.PARAMETER_TYPE, ICarbonOperationManager.OPERATION_GET_SERVICE_WSDL_URL);
operationParameters.put(ICarbonOperationManager.PARAMETER_SERVICE_NAME, serviceName);
Object r = wsasServerManager.executeOperationOnServer(server, operationParameters);//getWSDLConversionResultUrl(resourceFile);
if (r instanceof URL){
result=(URL)r;
}
}
return result;
}
public static URL getServiceTryItUrl(IServer server, String serviceName) throws Exception {
URL result=null;
if (server!=null){
IServerManager wsasServerManager = ServerController.getInstance().getServerManager();
HashMap<String,Object> operationParameters=new HashMap<String,Object>();
operationParameters.put(ICarbonOperationManager.PARAMETER_TYPE, ICarbonOperationManager.OPERATION_GET_SERVICE_TRY_IT_URL);
operationParameters.put(ICarbonOperationManager.PARAMETER_SERVICE_NAME, serviceName);
Object r = wsasServerManager.executeOperationOnServer(server, operationParameters);//getWSDLConversionResultUrl(resourceFile);
if (r instanceof URL){
result=(URL)r;
}
}
return result;
}
public static Map<IServer,CarbonServerInformation> getAppServerInformation(){
if (appServerInformation==null)
appServerInformation=new HashMap<IServer,CarbonServerInformation>();
return appServerInformation;
}
public ServerPort[] getServerPorts(IServer server){
GenericServer gserver=(GenericServer) server.getAdapter(GenericServer.class);
return gserver.getServerPorts();
}
public static String getServerLocalWorkspacePath(IServer server){
if (getAppServerInformation().containsKey(server)) {
return getAppServerInformation().get(server).getServerLocalWorkspacePath();
}else
return null;
}
public Map<String, Integer> getServerPorts(String serverId) throws Exception {
Map<String, Integer> result=new HashMap<String,Integer>();
IServer server = getServer(serverId);
if (server!=null){
ServerPort[] serverPorts2 = getServerPorts(server);
if (serverPorts2!=null)
for(ServerPort s:serverPorts2){
result.put(s.getProtocol(), s.getPort());
}
}
return result;
}
public static void addServerToParameters(Map<String,Object> properties,IServer server){
properties.put(ICarbonOperationManager.PARAMETER_SERVER, server);
}
public static boolean isOperationSupported(IServer server,int operation) throws Exception{
IServerManager wsasServerManager = ServerController.getInstance().getServerManager();
HashMap<String,Object> operationParameters=new HashMap<String,Object>();
operationParameters.put(ICarbonOperationManager.PARAMETER_TYPE, ICarbonOperationManager.OPERATION_SUPPORTED_OPERATIONS);
operationParameters.put(ICarbonOperationManager.PARAMETER_OP_TYPES, operation);
Object r = wsasServerManager.executeOperationOnServer(server, operationParameters);
if (r instanceof Boolean){
return (Boolean)r;
}
return false;
}
public static void initializeServerConfigurations(IServer server) throws Exception{
IServerManager wsasServerManager = ServerController.getInstance().getServerManager();
HashMap<String,Object> operationParameters=new HashMap<String,Object>();
operationParameters.put(ICarbonOperationManager.PARAMETER_TYPE, ICarbonOperationManager.OPERATION_INITIALIZE_SERVER_CONFIGURATIONS);
wsasServerManager.executeOperationOnServer(server, operationParameters);
}
public static void cleanupServerConfigurations(IServer server) throws Exception{
IServerManager wsasServerManager = ServerController.getInstance().getServerManager();
HashMap<String,Object> operationParameters=new HashMap<String,Object>();
operationParameters.put(ICarbonOperationManager.PARAMETER_TYPE, ICarbonOperationManager.OPERATION_CLEANUP_SERVER_CONFIGURATIONS);
wsasServerManager.executeOperationOnServer(server, operationParameters);
}
public boolean publishServiceModule(String serverId, String webTempPath,
String projectName) {
IServer server=getServer(serverId);
IProject project=ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);
IServerManager wsasServerManager = ServerController.getInstance().getServerManager();
HashMap<String,Object> operationParameters=new HashMap<String,Object>();
operationParameters.put(ICarbonOperationManager.PARAMETER_TYPE, ICarbonOperationManager.OPERATION_PUBLISH_MODULE);
operationParameters.put(ICarbonOperationManager.PARAMETER_WebTempPath,webTempPath);
operationParameters.put(ICarbonOperationManager.PARAMETER_PROJECT,project);
try {
wsasServerManager.executeOperationOnServer(server, operationParameters);
return true;
} catch (Exception e) {
log.error(e);
return false;
}
}
public boolean hotUpdateServiceModule(String serverId, String webTempPath,
String projectName) {
IServer server=getServer(serverId);
IProject project=ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);
CarbonServerManager wsasServerManager = this;
HashMap<String,Object> operationParameters=new HashMap<String,Object>();
operationParameters.put(ICarbonOperationManager.PARAMETER_TYPE, ICarbonOperationManager.OPERATION_HOT_UPDATE_MODULE);
operationParameters.put(ICarbonOperationManager.PARAMETER_WebTempPath,webTempPath);
operationParameters.put(ICarbonOperationManager.PARAMETER_PROJECT,project);
try {
wsasServerManager.executeOperationOnServer(server, operationParameters);
return true;
} catch (Exception e) {
log.error(e);
return false;
}
}
public boolean redeployServiceModule(String serverId, String webTempPath, String projectName) {
IServer server = getServer(serverId);
IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);
CarbonServerManager wsasServerManager = this;
HashMap<String, Object> operationParameters = new HashMap<String, Object>();
operationParameters.put(ICarbonOperationManager.PARAMETER_TYPE,
ICarbonOperationManager.OPERATION_REDEPLOY_MODULE);
operationParameters.put(ICarbonOperationManager.PARAMETER_WebTempPath, webTempPath);
operationParameters.put(ICarbonOperationManager.PARAMETER_PROJECT, project);
try {
wsasServerManager.executeOperationOnServer(server, operationParameters);
return true;
} catch (Exception e) {
log.error(e);
return false;
}
}
public boolean unpublishServiceModule(String serverId, String webTempPath,
String projectName) {
IServer server=getServer(serverId);
IProject project=ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);
CarbonServerManager wsasServerManager = this;
HashMap<String,Object> operationParameters=new HashMap<String,Object>();
operationParameters.put(ICarbonOperationManager.PARAMETER_TYPE, ICarbonOperationManager.OPERATION_UNPUBLISH_MODULE);
operationParameters.put(ICarbonOperationManager.PARAMETER_WebTempPath,webTempPath);
operationParameters.put(ICarbonOperationManager.PARAMETER_PROJECT,project);
try {
wsasServerManager.executeOperationOnServer(server, operationParameters);
return true;
} catch (Exception e) {
log.error(e);
return false;
}
}
public static boolean waitForServerToChangeState(IServer server,Shell shell,int changeStateFrom, int changeStateTo, String msg){
ProgressMonitorDialog progressMonitorDialog = new ProgressMonitorDialog(shell);
CarbonServerStateChange serverStateChange = new CarbonServerStateChange(server,changeStateFrom,changeStateTo,180000,msg);
progressMonitorDialog.setBlockOnOpen(false);
try {
progressMonitorDialog.run(true,true,serverStateChange);
return progressMonitorDialog.getReturnCode()!=ProgressMonitorDialog.CANCEL;
} catch (InvocationTargetException e) {
log.error(e);
} catch (InterruptedException e) {
log.error(e);
}
return false;
}
public static boolean waitUntilTheServerStarts(IServer server,Shell shell){
return waitForServerToChangeState(server,shell,IServer.STATE_STOPPED,IServer.STATE_STARTED,"Starting WSAS Server "+server.getId()+"...");
}
public Map<IFolder,IProject> getPublishedPaths(String serverId) {
return getPublishedPaths(getServer(serverId));
}
public static Map<IFolder,IProject> getPublishedPaths(IServer server) {
if (server==null) return null;
IServerManager wsasServerManager = ServerController.getInstance().getServerManager();
HashMap<String,Object> operationParameters=new HashMap<String,Object>();
operationParameters.put(ICarbonOperationManager.PARAMETER_TYPE, ICarbonOperationManager.OPERATION_GET_PUBLISHED_SERVICES);
try {
Object result = wsasServerManager.executeOperationOnServer(server, operationParameters);
if (result instanceof Map){
return (Map<IFolder, IProject>)result;
}
return null;
} catch (Exception e) {
log.error(e);
return null;
}
}
public IProject[] getPublishedProjects(String serverId) {
return null;
}
public IProject[] getPublishedProjectsFromAllServers() {
return null;
}
public String getServerRuntimeId(String serverId) {
return getServerOperationManager(serverId).getRuntimeId();
}
public boolean isRuntimeIdPresent(String runtimeId) {
return getServerRuntimeIdPlugin().containsKey(runtimeId);
}
public String getServerTypeIdForRuntimeId(String runtimeId) {
if (getServerRuntimeIdPlugin().containsKey(runtimeId))
return getServerRuntimeIdPlugin().get(runtimeId);
else
return null;
}
public String[] getServerRelativeLibraryPaths(String serverTypeId)
throws Exception {
String[] result=null;
ICarbonOperationManager serverOperationManager = getServerOperationManagerByServerType(serverTypeId);
HashMap<String,Object> operationParameters=new HashMap<String,Object>();
operationParameters.put(ICarbonOperationManager.PARAMETER_TYPE, ICarbonOperationManager.OPERATION_GET_LIBRARY_PATHS);
Object r=serverOperationManager.executeOperation(operationParameters);
if (r instanceof String[]){
result=(String[])r;
}
return result;
}
public String[] getServerCodegenLibraries(String serverId)
throws Exception {
IServer server = getServer(serverId);
return getServerCodegenLibraries(server);
}
public static String[] getServerCodegenLibraries(IServer server)
throws Exception {
String[] result=null;
if (server!=null){
IServerManager wsasServerManager = ServerController.getInstance().getServerManager();
HashMap<String,Object> operationParameters=new HashMap<String,Object>();
operationParameters.put(ICarbonOperationManager.PARAMETER_TYPE, ICarbonOperationManager.OPERATION_GET_CODEGEN_LIBRARIES);
Object r = wsasServerManager.executeOperationOnServer(server, operationParameters);//getWSDLConversionResultUrl(resourceFile);
if (r instanceof String[]){
result=(String[])r;
}
}
return result;
}
public String[] getServerAxis2Libraries(String serverTypeId, String wsasHome)
throws Exception {
String[] result=null;
ICarbonOperationManager serverOperationManager = getServerOperationManagerByServerType(serverTypeId);
HashMap<String,Object> operationParameters=new HashMap<String,Object>();
operationParameters.put(ICarbonOperationManager.PARAMETER_TYPE, ICarbonOperationManager.OPERATION_GET_AXIS2_LIBRARIES);
operationParameters.put(ICarbonOperationManager.PARAMETER_PATH, wsasHome);
Object r=serverOperationManager.executeOperation(operationParameters);
if (r instanceof String[]){
result=(String[])r;
}
return result;
}
private void init(){
createWorkspaceListener();
}
private void createWorkspaceListener(){
IWorkspace workspace = ResourcesPlugin.getWorkspace();
IResourceChangeListener listener = new IResourceChangeListener() {
public void resourceChanged(IResourceChangeEvent event) {
if (event.getDelta()!=null && event.getDelta().getAffectedChildren()!=null) {
for (IResourceDelta resource : event.getDelta()
.getAffectedChildren()) {
if (resource.getResource() instanceof IProject) {
IProject project = (IProject) resource
.getResource();
if (project.exists()) {
// List javaProjectSourceDirectories = WSASUtils.getJavaProjectSourceDirectories(project);
for (IResourceDelta resource2 : resource
.getAffectedChildren()) {
try {
String name = resource2
.getProjectRelativePath()
.toFile().getName();
if (name.equals(".project")
|| name.equals(".settings")) {
continue;
}
IPath pathChanged = project
.getLocation()
.append(
resource2
.getProjectRelativePath());
// if (javaProjectSourceDirectories.contains(pathChanged.toOSString())){
IServer[] serversForProject = getServersForProject(project);
for (IServer server : serversForProject) {
- CarbonServerInformation serverInformation = getAppServerInformation()
- .get(server);
- if (!serverInformation
- .getChangedProjects()
- .contains(project)) {
- serverInformation
+ if (!server.getServerType().getId().equalsIgnoreCase("org.wso2.developerstudio.eclipse.carbon.server.remote")) {
+ CarbonServerInformation serverInformation = getAppServerInformation()
+ .get(server);
+ if (!serverInformation
.getChangedProjects()
- .add(project);
- hotUpdateServiceModule(server
- .getId(), "", project
- .getName());
+ .contains(project)) {
+ serverInformation
+ .getChangedProjects()
+ .add(project);
+ hotUpdateServiceModule(
+ server.getId(), "",
+ project.getName());
+ }
}
}
break;
// }
} catch (Exception e) {
}
}
}
}
}
}
}
};
workspace.addResourceChangeListener(listener);
}
public String[] getServerCodegenLibrariesFromRuntimeId(String runtimeId, String runtimePath)
throws Exception {
String serverTypeId = getServerTypeIdForRuntimeId(runtimeId);
String[] result=null;
HashMap<String,Object> operationParameters=new HashMap<String,Object>();
operationParameters.put(ICarbonOperationManager.PARAMETER_TYPE, ICarbonOperationManager.OPERATION_GET_CODEGEN_LIBRARIES);
operationParameters.put(ICarbonOperationManager.PARAMETER_RUNTIME, runtimeId);
operationParameters.put(ICarbonOperationManager.PARAMETER_PATH, runtimePath);
ICarbonOperationManager wsasOperationManager = getServerOperationManagerByServerType(serverTypeId);
Object r = wsasOperationManager.executeOperation(operationParameters);//getWSDLConversionResultUrl(resourceFile);
if (r instanceof String[]){
result=(String[])r;
}
return result;
}
public static ICredentials getServerCredentials(IServer server) throws Exception{
Map<String,String> result=null;
if (server!=null){
IServerManager esbServerManager = ServerController.getInstance().getServerManager();
HashMap<String,Object> operationParameters=new HashMap<String,Object>();
operationParameters.put(ICarbonOperationManager.PARAMETER_TYPE, ICarbonOperationManager.OPERATION_GET_SERVER_CREDENTIALS);
Object r = esbServerManager.executeOperationOnServer(server, operationParameters);//getWSDLConversionResultUrl(resourceFile);
if (r instanceof Map){
result=(Map<String,String>)r;
}
}
Credentials credentials = null;
if (result!=null) {
credentials = new Credentials(result.get("username"), result
.get("password"));
}
return credentials;
}
public static URL getServerURL(IServer server) throws Exception{
URL result=null;
if (server!=null){
IServerManager esbServerManager = ServerController.getInstance().getServerManager();
HashMap<String,Object> operationParameters=new HashMap<String,Object>();
operationParameters.put(ICarbonOperationManager.PARAMETER_TYPE, ICarbonOperationManager.OPERATION_SERVER_URL);
Object r = esbServerManager.executeOperationOnServer(server, operationParameters);//getWSDLConversionResultUrl(resourceFile);
if (r instanceof URL){
result=(URL)r;
}
}
return result;
}
public static String getServerAuthenticatedCookie(IServer server, String httpsPort) throws Exception{
String result=null;
if (server!=null){
IServerManager esbServerManager = ServerController.getInstance().getServerManager();
HashMap<String,Object> operationParameters=new HashMap<String,Object>();
operationParameters.put(ICarbonOperationManager.PARAMETER_TYPE, ICarbonOperationManager.OPERATION_GET_SERVER_AUTHENTICATED_COOKIE);
operationParameters.put(ICarbonOperationManager.PARAMETER_SERVER_PORT, httpsPort);
Object r = esbServerManager.executeOperationOnServer(server, operationParameters);
if (r instanceof String){
result=(String)r;
}
}
return result;
}
public static String getServerAuthenticatedCookie(IServer server) throws Exception{
String result=null;
if (server!=null){
ServerPort[] serverPorts = getInstance().getServerPorts(server);
String httpsPort="9443";
for (ServerPort port : serverPorts) {
if (port.getProtocol().equalsIgnoreCase("https")){
httpsPort=Integer.toString(port.getPort());
}
}
result = getServerAuthenticatedCookie(server,httpsPort);
}
return result;
}
}
| false | true | private void createWorkspaceListener(){
IWorkspace workspace = ResourcesPlugin.getWorkspace();
IResourceChangeListener listener = new IResourceChangeListener() {
public void resourceChanged(IResourceChangeEvent event) {
if (event.getDelta()!=null && event.getDelta().getAffectedChildren()!=null) {
for (IResourceDelta resource : event.getDelta()
.getAffectedChildren()) {
if (resource.getResource() instanceof IProject) {
IProject project = (IProject) resource
.getResource();
if (project.exists()) {
// List javaProjectSourceDirectories = WSASUtils.getJavaProjectSourceDirectories(project);
for (IResourceDelta resource2 : resource
.getAffectedChildren()) {
try {
String name = resource2
.getProjectRelativePath()
.toFile().getName();
if (name.equals(".project")
|| name.equals(".settings")) {
continue;
}
IPath pathChanged = project
.getLocation()
.append(
resource2
.getProjectRelativePath());
// if (javaProjectSourceDirectories.contains(pathChanged.toOSString())){
IServer[] serversForProject = getServersForProject(project);
for (IServer server : serversForProject) {
CarbonServerInformation serverInformation = getAppServerInformation()
.get(server);
if (!serverInformation
.getChangedProjects()
.contains(project)) {
serverInformation
.getChangedProjects()
.add(project);
hotUpdateServiceModule(server
.getId(), "", project
.getName());
}
}
break;
// }
} catch (Exception e) {
}
}
}
}
}
}
}
};
workspace.addResourceChangeListener(listener);
}
| private void createWorkspaceListener(){
IWorkspace workspace = ResourcesPlugin.getWorkspace();
IResourceChangeListener listener = new IResourceChangeListener() {
public void resourceChanged(IResourceChangeEvent event) {
if (event.getDelta()!=null && event.getDelta().getAffectedChildren()!=null) {
for (IResourceDelta resource : event.getDelta()
.getAffectedChildren()) {
if (resource.getResource() instanceof IProject) {
IProject project = (IProject) resource
.getResource();
if (project.exists()) {
// List javaProjectSourceDirectories = WSASUtils.getJavaProjectSourceDirectories(project);
for (IResourceDelta resource2 : resource
.getAffectedChildren()) {
try {
String name = resource2
.getProjectRelativePath()
.toFile().getName();
if (name.equals(".project")
|| name.equals(".settings")) {
continue;
}
IPath pathChanged = project
.getLocation()
.append(
resource2
.getProjectRelativePath());
// if (javaProjectSourceDirectories.contains(pathChanged.toOSString())){
IServer[] serversForProject = getServersForProject(project);
for (IServer server : serversForProject) {
if (!server.getServerType().getId().equalsIgnoreCase("org.wso2.developerstudio.eclipse.carbon.server.remote")) {
CarbonServerInformation serverInformation = getAppServerInformation()
.get(server);
if (!serverInformation
.getChangedProjects()
.contains(project)) {
serverInformation
.getChangedProjects()
.add(project);
hotUpdateServiceModule(
server.getId(), "",
project.getName());
}
}
}
break;
// }
} catch (Exception e) {
}
}
}
}
}
}
}
};
workspace.addResourceChangeListener(listener);
}
|
diff --git a/modules/util/src/main/java/org/mortbay/servlet/MultiPartFilter.java b/modules/util/src/main/java/org/mortbay/servlet/MultiPartFilter.java
index ad03711..fa0b045 100644
--- a/modules/util/src/main/java/org/mortbay/servlet/MultiPartFilter.java
+++ b/modules/util/src/main/java/org/mortbay/servlet/MultiPartFilter.java
@@ -1,463 +1,465 @@
// ========================================================================
// Copyright 1996-2005 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ========================================================================
package org.mortbay.servlet;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
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.HttpServletRequestWrapper;
import org.mortbay.util.LazyList;
import org.mortbay.util.MultiMap;
import org.mortbay.util.StringUtil;
import org.mortbay.util.TypeUtil;
/* ------------------------------------------------------------ */
/**
* Multipart Form Data Filter.
* <p>
* This class decodes the multipart/form-data stream sent by a HTML form that uses a file input
* item. Any files sent are stored to a tempary file and a File object added to the request
* as an attribute. All other values are made available via the normal getParameter API and
* the setCharacterEncoding mechanism is respected when converting bytes to Strings.
*
* If the init paramter "delete" is set to "true", any files created will be deleted when the
* current request returns.
*
* @author Greg Wilkins
* @author Jim Crossley
*/
public class MultiPartFilter implements Filter
{
private final static String FILES ="org.mortbay.servlet.MultiPartFilter.files";
private File tempdir;
private boolean _deleteFiles;
private ServletContext _context;
private int _fileOutputBuffer = 0;
/* ------------------------------------------------------------------------------- */
/**
* @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
*/
public void init(FilterConfig filterConfig) throws ServletException
{
tempdir=(File)filterConfig.getServletContext().getAttribute("javax.servlet.context.tempdir");
_deleteFiles="true".equals(filterConfig.getInitParameter("deleteFiles"));
String fileOutputBuffer = filterConfig.getInitParameter("fileOutputBuffer");
if(fileOutputBuffer!=null)
_fileOutputBuffer = Integer.parseInt(fileOutputBuffer);
_context=filterConfig.getServletContext();
}
/* ------------------------------------------------------------------------------- */
/**
* @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
{
HttpServletRequest srequest=(HttpServletRequest)request;
if(srequest.getContentType()==null||!srequest.getContentType().startsWith("multipart/form-data"))
{
chain.doFilter(request,response);
return;
}
BufferedInputStream in = new BufferedInputStream(request.getInputStream());
String content_type=srequest.getContentType();
// TODO - handle encodings
String boundary="--"+value(content_type.substring(content_type.indexOf("boundary=")));
byte[] byteBoundary=(boundary+"--").getBytes(StringUtil.__ISO_8859_1);
MultiMap params = new MultiMap();
for (Iterator i = request.getParameterMap().entrySet().iterator();i.hasNext();)
{
Map.Entry entry=(Map.Entry)i.next();
Object value=entry.getValue();
if (value instanceof String[])
params.addValues(entry.getKey(),(String[])value);
else
params.add(entry.getKey(),value);
}
try
{
// Get first boundary
byte[] bytes=TypeUtil.readLine(in);
String line=bytes==null?null:new String(bytes,"UTF-8");
if(line==null || !line.equals(boundary))
{
throw new IOException("Missing initial multi part boundary");
}
// Read each part
boolean lastPart=false;
String content_disposition=null;
- while(!lastPart)
+ outer:while(!lastPart)
{
while(true)
{
bytes=TypeUtil.readLine(in);
// If blank line, end of part headers
- if(bytes==null || bytes.length==0)
+ if(bytes==null)
+ break outer;
+ if (bytes.length==0)
break;
line=new String(bytes,"UTF-8");
// place part header key and value in map
int c=line.indexOf(':',0);
if(c>0)
{
String key=line.substring(0,c).trim().toLowerCase();
String value=line.substring(c+1,line.length()).trim();
if(key.equals("content-disposition"))
content_disposition=value;
}
}
// Extract content-disposition
boolean form_data=false;
if(content_disposition==null)
{
throw new IOException("Missing content-disposition");
}
StringTokenizer tok=new StringTokenizer(content_disposition,";");
String name=null;
String filename=null;
while(tok.hasMoreTokens())
{
String t=tok.nextToken().trim();
String tl=t.toLowerCase();
if(t.startsWith("form-data"))
form_data=true;
else if(tl.startsWith("name="))
name=value(t);
else if(tl.startsWith("filename="))
filename=value(t);
}
// Check disposition
if(!form_data)
{
continue;
}
//It is valid for reset and submit buttons to have an empty name.
//If no name is supplied, the browser skips sending the info for that field.
//However, if you supply the empty string as the name, the browser sends the
//field, with name as the empty string. So, only continue this loop if we
//have not yet seen a name field.
if(name==null)
{
continue;
}
OutputStream out=null;
File file=null;
try
{
if (filename!=null && filename.length()>0)
{
file = File.createTempFile("MultiPart", "", tempdir);
out = new FileOutputStream(file);
if(_fileOutputBuffer>0)
out = new BufferedOutputStream(out, _fileOutputBuffer);
request.setAttribute(name,file);
params.add(name, filename);
if (_deleteFiles)
{
file.deleteOnExit();
ArrayList files = (ArrayList)request.getAttribute(FILES);
if (files==null)
{
files=new ArrayList();
request.setAttribute(FILES,files);
}
files.add(file);
}
}
else
out=new ByteArrayOutputStream();
int state=-2;
int c;
boolean cr=false;
boolean lf=false;
// loop for all lines`
while(true)
{
int b=0;
while((c=(state!=-2)?state:in.read())!=-1)
{
state=-2;
// look for CR and/or LF
if(c==13||c==10)
{
if(c==13)
state=in.read();
break;
}
// look for boundary
if(b>=0&&b<byteBoundary.length&&c==byteBoundary[b])
b++;
else
{
// this is not a boundary
if(cr)
out.write(13);
if(lf)
out.write(10);
cr=lf=false;
if(b>0)
out.write(byteBoundary,0,b);
b=-1;
out.write(c);
}
}
// check partial boundary
if((b>0&&b<byteBoundary.length-2)||(b==byteBoundary.length-1))
{
if(cr)
out.write(13);
if(lf)
out.write(10);
cr=lf=false;
out.write(byteBoundary,0,b);
b=-1;
}
// boundary match
if(b>0||c==-1)
{
if(b==byteBoundary.length)
lastPart=true;
if(state==10)
state=-2;
break;
}
// handle CR LF
if(cr)
out.write(13);
if(lf)
out.write(10);
cr=(c==13);
lf=(c==10||state==10);
if(state==10)
state=-2;
}
}
finally
{
out.close();
}
if (file==null)
{
bytes = ((ByteArrayOutputStream)out).toByteArray();
params.add(name,bytes);
}
}
// handle request
chain.doFilter(new Wrapper(srequest,params),response);
}
finally
{
deleteFiles(request);
}
}
private void deleteFiles(ServletRequest request)
{
ArrayList files = (ArrayList)request.getAttribute(FILES);
if (files!=null)
{
Iterator iter = files.iterator();
while (iter.hasNext())
{
File file=(File)iter.next();
try
{
file.delete();
}
catch(Exception e)
{
_context.log("failed to delete "+file,e);
}
}
}
}
/* ------------------------------------------------------------ */
private String value(String nameEqualsValue)
{
String value=nameEqualsValue.substring(nameEqualsValue.indexOf('=')+1).trim();
int i=value.indexOf(';');
if(i>0)
value=value.substring(0,i);
if(value.startsWith("\""))
{
value=value.substring(1,value.indexOf('"',1));
}
else
{
i=value.indexOf(' ');
if(i>0)
value=value.substring(0,i);
}
return value;
}
/* ------------------------------------------------------------------------------- */
/**
* @see javax.servlet.Filter#destroy()
*/
public void destroy()
{
}
private static class Wrapper extends HttpServletRequestWrapper
{
String encoding="UTF-8";
MultiMap map;
/* ------------------------------------------------------------------------------- */
/** Constructor.
* @param request
*/
public Wrapper(HttpServletRequest request, MultiMap map)
{
super(request);
this.map=map;
}
/* ------------------------------------------------------------------------------- */
/**
* @see javax.servlet.ServletRequest#getContentLength()
*/
public int getContentLength()
{
return 0;
}
/* ------------------------------------------------------------------------------- */
/**
* @see javax.servlet.ServletRequest#getParameter(java.lang.String)
*/
public String getParameter(String name)
{
Object o=map.get(name);
if (!(o instanceof byte[]) && LazyList.size(o)>0)
o=LazyList.get(o,0);
if (o instanceof byte[])
{
try
{
String s=new String((byte[])o,encoding);
return s;
}
catch(Exception e)
{
e.printStackTrace();
}
}
else if (o!=null)
return String.valueOf(o);
return null;
}
/* ------------------------------------------------------------------------------- */
/**
* @see javax.servlet.ServletRequest#getParameterMap()
*/
public Map getParameterMap()
{
return Collections.unmodifiableMap(map.toStringArrayMap());
}
/* ------------------------------------------------------------------------------- */
/**
* @see javax.servlet.ServletRequest#getParameterNames()
*/
public Enumeration getParameterNames()
{
return Collections.enumeration(map.keySet());
}
/* ------------------------------------------------------------------------------- */
/**
* @see javax.servlet.ServletRequest#getParameterValues(java.lang.String)
*/
public String[] getParameterValues(String name)
{
List l=map.getValues(name);
if (l==null || l.size()==0)
return new String[0];
String[] v = new String[l.size()];
for (int i=0;i<l.size();i++)
{
Object o=l.get(i);
if (o instanceof byte[])
{
try
{
v[i]=new String((byte[])o,encoding);
}
catch(Exception e)
{
e.printStackTrace();
}
}
else if (o instanceof String)
v[i]=(String)o;
}
return v;
}
/* ------------------------------------------------------------------------------- */
/**
* @see javax.servlet.ServletRequest#setCharacterEncoding(java.lang.String)
*/
public void setCharacterEncoding(String enc)
throws UnsupportedEncodingException
{
encoding=enc;
}
}
}
| false | true | public void doFilter(ServletRequest request,ServletResponse response,FilterChain chain)
throws IOException, ServletException
{
HttpServletRequest srequest=(HttpServletRequest)request;
if(srequest.getContentType()==null||!srequest.getContentType().startsWith("multipart/form-data"))
{
chain.doFilter(request,response);
return;
}
BufferedInputStream in = new BufferedInputStream(request.getInputStream());
String content_type=srequest.getContentType();
// TODO - handle encodings
String boundary="--"+value(content_type.substring(content_type.indexOf("boundary=")));
byte[] byteBoundary=(boundary+"--").getBytes(StringUtil.__ISO_8859_1);
MultiMap params = new MultiMap();
for (Iterator i = request.getParameterMap().entrySet().iterator();i.hasNext();)
{
Map.Entry entry=(Map.Entry)i.next();
Object value=entry.getValue();
if (value instanceof String[])
params.addValues(entry.getKey(),(String[])value);
else
params.add(entry.getKey(),value);
}
try
{
// Get first boundary
byte[] bytes=TypeUtil.readLine(in);
String line=bytes==null?null:new String(bytes,"UTF-8");
if(line==null || !line.equals(boundary))
{
throw new IOException("Missing initial multi part boundary");
}
// Read each part
boolean lastPart=false;
String content_disposition=null;
while(!lastPart)
{
while(true)
{
bytes=TypeUtil.readLine(in);
// If blank line, end of part headers
if(bytes==null || bytes.length==0)
break;
line=new String(bytes,"UTF-8");
// place part header key and value in map
int c=line.indexOf(':',0);
if(c>0)
{
String key=line.substring(0,c).trim().toLowerCase();
String value=line.substring(c+1,line.length()).trim();
if(key.equals("content-disposition"))
content_disposition=value;
}
}
// Extract content-disposition
boolean form_data=false;
if(content_disposition==null)
{
throw new IOException("Missing content-disposition");
}
StringTokenizer tok=new StringTokenizer(content_disposition,";");
String name=null;
String filename=null;
while(tok.hasMoreTokens())
{
String t=tok.nextToken().trim();
String tl=t.toLowerCase();
if(t.startsWith("form-data"))
form_data=true;
else if(tl.startsWith("name="))
name=value(t);
else if(tl.startsWith("filename="))
filename=value(t);
}
// Check disposition
if(!form_data)
{
continue;
}
//It is valid for reset and submit buttons to have an empty name.
//If no name is supplied, the browser skips sending the info for that field.
//However, if you supply the empty string as the name, the browser sends the
//field, with name as the empty string. So, only continue this loop if we
//have not yet seen a name field.
if(name==null)
{
continue;
}
OutputStream out=null;
File file=null;
try
{
if (filename!=null && filename.length()>0)
{
file = File.createTempFile("MultiPart", "", tempdir);
out = new FileOutputStream(file);
if(_fileOutputBuffer>0)
out = new BufferedOutputStream(out, _fileOutputBuffer);
request.setAttribute(name,file);
params.add(name, filename);
if (_deleteFiles)
{
file.deleteOnExit();
ArrayList files = (ArrayList)request.getAttribute(FILES);
if (files==null)
{
files=new ArrayList();
request.setAttribute(FILES,files);
}
files.add(file);
}
}
else
out=new ByteArrayOutputStream();
int state=-2;
int c;
boolean cr=false;
boolean lf=false;
// loop for all lines`
while(true)
{
int b=0;
while((c=(state!=-2)?state:in.read())!=-1)
{
state=-2;
// look for CR and/or LF
if(c==13||c==10)
{
if(c==13)
state=in.read();
break;
}
// look for boundary
if(b>=0&&b<byteBoundary.length&&c==byteBoundary[b])
b++;
else
{
// this is not a boundary
if(cr)
out.write(13);
if(lf)
out.write(10);
cr=lf=false;
if(b>0)
out.write(byteBoundary,0,b);
b=-1;
out.write(c);
}
}
// check partial boundary
if((b>0&&b<byteBoundary.length-2)||(b==byteBoundary.length-1))
{
if(cr)
out.write(13);
if(lf)
out.write(10);
cr=lf=false;
out.write(byteBoundary,0,b);
b=-1;
}
// boundary match
if(b>0||c==-1)
{
if(b==byteBoundary.length)
lastPart=true;
if(state==10)
state=-2;
break;
}
// handle CR LF
if(cr)
out.write(13);
if(lf)
out.write(10);
cr=(c==13);
lf=(c==10||state==10);
if(state==10)
state=-2;
}
}
finally
{
out.close();
}
if (file==null)
{
bytes = ((ByteArrayOutputStream)out).toByteArray();
params.add(name,bytes);
}
}
// handle request
chain.doFilter(new Wrapper(srequest,params),response);
}
finally
{
deleteFiles(request);
}
}
| public void doFilter(ServletRequest request,ServletResponse response,FilterChain chain)
throws IOException, ServletException
{
HttpServletRequest srequest=(HttpServletRequest)request;
if(srequest.getContentType()==null||!srequest.getContentType().startsWith("multipart/form-data"))
{
chain.doFilter(request,response);
return;
}
BufferedInputStream in = new BufferedInputStream(request.getInputStream());
String content_type=srequest.getContentType();
// TODO - handle encodings
String boundary="--"+value(content_type.substring(content_type.indexOf("boundary=")));
byte[] byteBoundary=(boundary+"--").getBytes(StringUtil.__ISO_8859_1);
MultiMap params = new MultiMap();
for (Iterator i = request.getParameterMap().entrySet().iterator();i.hasNext();)
{
Map.Entry entry=(Map.Entry)i.next();
Object value=entry.getValue();
if (value instanceof String[])
params.addValues(entry.getKey(),(String[])value);
else
params.add(entry.getKey(),value);
}
try
{
// Get first boundary
byte[] bytes=TypeUtil.readLine(in);
String line=bytes==null?null:new String(bytes,"UTF-8");
if(line==null || !line.equals(boundary))
{
throw new IOException("Missing initial multi part boundary");
}
// Read each part
boolean lastPart=false;
String content_disposition=null;
outer:while(!lastPart)
{
while(true)
{
bytes=TypeUtil.readLine(in);
// If blank line, end of part headers
if(bytes==null)
break outer;
if (bytes.length==0)
break;
line=new String(bytes,"UTF-8");
// place part header key and value in map
int c=line.indexOf(':',0);
if(c>0)
{
String key=line.substring(0,c).trim().toLowerCase();
String value=line.substring(c+1,line.length()).trim();
if(key.equals("content-disposition"))
content_disposition=value;
}
}
// Extract content-disposition
boolean form_data=false;
if(content_disposition==null)
{
throw new IOException("Missing content-disposition");
}
StringTokenizer tok=new StringTokenizer(content_disposition,";");
String name=null;
String filename=null;
while(tok.hasMoreTokens())
{
String t=tok.nextToken().trim();
String tl=t.toLowerCase();
if(t.startsWith("form-data"))
form_data=true;
else if(tl.startsWith("name="))
name=value(t);
else if(tl.startsWith("filename="))
filename=value(t);
}
// Check disposition
if(!form_data)
{
continue;
}
//It is valid for reset and submit buttons to have an empty name.
//If no name is supplied, the browser skips sending the info for that field.
//However, if you supply the empty string as the name, the browser sends the
//field, with name as the empty string. So, only continue this loop if we
//have not yet seen a name field.
if(name==null)
{
continue;
}
OutputStream out=null;
File file=null;
try
{
if (filename!=null && filename.length()>0)
{
file = File.createTempFile("MultiPart", "", tempdir);
out = new FileOutputStream(file);
if(_fileOutputBuffer>0)
out = new BufferedOutputStream(out, _fileOutputBuffer);
request.setAttribute(name,file);
params.add(name, filename);
if (_deleteFiles)
{
file.deleteOnExit();
ArrayList files = (ArrayList)request.getAttribute(FILES);
if (files==null)
{
files=new ArrayList();
request.setAttribute(FILES,files);
}
files.add(file);
}
}
else
out=new ByteArrayOutputStream();
int state=-2;
int c;
boolean cr=false;
boolean lf=false;
// loop for all lines`
while(true)
{
int b=0;
while((c=(state!=-2)?state:in.read())!=-1)
{
state=-2;
// look for CR and/or LF
if(c==13||c==10)
{
if(c==13)
state=in.read();
break;
}
// look for boundary
if(b>=0&&b<byteBoundary.length&&c==byteBoundary[b])
b++;
else
{
// this is not a boundary
if(cr)
out.write(13);
if(lf)
out.write(10);
cr=lf=false;
if(b>0)
out.write(byteBoundary,0,b);
b=-1;
out.write(c);
}
}
// check partial boundary
if((b>0&&b<byteBoundary.length-2)||(b==byteBoundary.length-1))
{
if(cr)
out.write(13);
if(lf)
out.write(10);
cr=lf=false;
out.write(byteBoundary,0,b);
b=-1;
}
// boundary match
if(b>0||c==-1)
{
if(b==byteBoundary.length)
lastPart=true;
if(state==10)
state=-2;
break;
}
// handle CR LF
if(cr)
out.write(13);
if(lf)
out.write(10);
cr=(c==13);
lf=(c==10||state==10);
if(state==10)
state=-2;
}
}
finally
{
out.close();
}
if (file==null)
{
bytes = ((ByteArrayOutputStream)out).toByteArray();
params.add(name,bytes);
}
}
// handle request
chain.doFilter(new Wrapper(srequest,params),response);
}
finally
{
deleteFiles(request);
}
}
|
diff --git a/contrib/wikipedia/src/de/zib/scalaris/examples/wikipedia/bliki/MyScalarisWikiModel.java b/contrib/wikipedia/src/de/zib/scalaris/examples/wikipedia/bliki/MyScalarisWikiModel.java
index 05d39c86..d80aa20b 100644
--- a/contrib/wikipedia/src/de/zib/scalaris/examples/wikipedia/bliki/MyScalarisWikiModel.java
+++ b/contrib/wikipedia/src/de/zib/scalaris/examples/wikipedia/bliki/MyScalarisWikiModel.java
@@ -1,136 +1,136 @@
/**
* Copyright 2011 Zuse Institute Berlin
*
* 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 de.zib.scalaris.examples.wikipedia.bliki;
import java.util.HashMap;
import java.util.Map;
import de.zib.scalaris.Connection;
import de.zib.scalaris.examples.wikipedia.RevisionResult;
import de.zib.scalaris.examples.wikipedia.ScalarisDataHandler;
/**
* Wiki model using Scalaris to fetch (new) data, e.g. templates.
*
* @author Nico Kruber, [email protected]
*/
public class MyScalarisWikiModel extends MyWikiModel {
protected Connection connection;
protected Map<String, String> magicWordCache = new HashMap<String, String>();
/**
* Creates a new wiki model to render wiki text using the given connection
* to Scalaris.
*
* @param imageBaseURL
* base url pointing to images - can contain ${image} for
* replacement
* @param linkBaseURL
* base url pointing to links - can contain ${title} for
* replacement
* @param connection
* connection to Scalaris
* @param namespace
* namespace of the wiki
*/
public MyScalarisWikiModel(String imageBaseURL, String linkBaseURL, Connection connection, MyNamespace namespace) {
super(imageBaseURL, linkBaseURL, namespace);
this.connection = connection;
}
/* (non-Javadoc)
* @see info.bliki.wiki.model.AbstractWikiModel#getRawWikiContent(java.lang.String, java.lang.String, java.util.Map)
*/
@Override
public String getRawWikiContent(String namespace, String articleName,
Map<String, String> templateParameters) {
if (isTemplateNamespace(namespace)) {
String magicWord = articleName;
String parameter = "";
int index = magicWord.indexOf(':');
if (index > 0) {
parameter = magicWord.substring(index + 1).trim();
magicWord = magicWord.substring(0, index);
}
if (MyScalarisMagicWord.isMagicWord(magicWord)) {
// cache values for magic words:
if (magicWordCache.containsKey(articleName)) {
return magicWordCache.get(articleName);
} else {
String value = MyScalarisMagicWord.processMagicWord(magicWord, parameter, this);
magicWordCache.put(articleName, value);
return value;
}
} else {
// retrieve template from Scalaris:
// note: templates are already cached, no need to cache them here
if (connection != null) {
// (ugly) fix for template parameter replacement if no parameters given,
// e.g. "{{noun}}" in the simple English Wiktionary
- if (templateParameters.isEmpty()) {
+ if (templateParameters != null && templateParameters.isEmpty()) {
templateParameters.put("", null);
}
String pageName = getTemplateNamespace() + ":" + articleName;
RevisionResult getRevResult = ScalarisDataHandler.getRevision(connection, pageName);
if (getRevResult.success) {
String text = getRevResult.revision.getText();
text = removeNoIncludeContents(text);
return text;
} else {
// System.err.println(getRevResult.message);
// return "<b>ERROR: template " + pageName + " not available: " + getRevResult.message + "</b>";
/*
* the template was not found and will never be - assume
* an empty content instead of letting the model try
* again (which is what it does if null is returned)
*/
return "";
}
}
}
}
if (getRedirectLink() != null) {
// requesting a page from a redirect?
return getRedirectContent(getRedirectLink());
}
// System.out.println("getRawWikiContent(" + namespace + ", " + articleName + ", " +
// templateParameters + ")");
return null;
}
/**
* Gets the contents of the newest revision of the page redirected to.
*
* @param pageName
* the name of the page redirected to
*
* @return the contents of the newest revision of that page or a placeholder
* string
*/
public String getRedirectContent(String pageName) {
RevisionResult getRevResult = ScalarisDataHandler.getRevision(connection, pageName);
if (getRevResult.success) {
// make PAGENAME in the redirected content work as expected
setPageName(pageName);
return getRevResult.revision.getText();
} else {
// System.err.println(getRevResult.message);
// return "<b>ERROR: redirect to " + getRedirectLink() + " failed: " + getRevResult.message + "</b>";
return "#redirect [[" + pageName + "]]";
}
}
}
| true | true | public String getRawWikiContent(String namespace, String articleName,
Map<String, String> templateParameters) {
if (isTemplateNamespace(namespace)) {
String magicWord = articleName;
String parameter = "";
int index = magicWord.indexOf(':');
if (index > 0) {
parameter = magicWord.substring(index + 1).trim();
magicWord = magicWord.substring(0, index);
}
if (MyScalarisMagicWord.isMagicWord(magicWord)) {
// cache values for magic words:
if (magicWordCache.containsKey(articleName)) {
return magicWordCache.get(articleName);
} else {
String value = MyScalarisMagicWord.processMagicWord(magicWord, parameter, this);
magicWordCache.put(articleName, value);
return value;
}
} else {
// retrieve template from Scalaris:
// note: templates are already cached, no need to cache them here
if (connection != null) {
// (ugly) fix for template parameter replacement if no parameters given,
// e.g. "{{noun}}" in the simple English Wiktionary
if (templateParameters.isEmpty()) {
templateParameters.put("", null);
}
String pageName = getTemplateNamespace() + ":" + articleName;
RevisionResult getRevResult = ScalarisDataHandler.getRevision(connection, pageName);
if (getRevResult.success) {
String text = getRevResult.revision.getText();
text = removeNoIncludeContents(text);
return text;
} else {
// System.err.println(getRevResult.message);
// return "<b>ERROR: template " + pageName + " not available: " + getRevResult.message + "</b>";
/*
* the template was not found and will never be - assume
* an empty content instead of letting the model try
* again (which is what it does if null is returned)
*/
return "";
}
}
}
}
if (getRedirectLink() != null) {
// requesting a page from a redirect?
return getRedirectContent(getRedirectLink());
}
// System.out.println("getRawWikiContent(" + namespace + ", " + articleName + ", " +
// templateParameters + ")");
return null;
}
| public String getRawWikiContent(String namespace, String articleName,
Map<String, String> templateParameters) {
if (isTemplateNamespace(namespace)) {
String magicWord = articleName;
String parameter = "";
int index = magicWord.indexOf(':');
if (index > 0) {
parameter = magicWord.substring(index + 1).trim();
magicWord = magicWord.substring(0, index);
}
if (MyScalarisMagicWord.isMagicWord(magicWord)) {
// cache values for magic words:
if (magicWordCache.containsKey(articleName)) {
return magicWordCache.get(articleName);
} else {
String value = MyScalarisMagicWord.processMagicWord(magicWord, parameter, this);
magicWordCache.put(articleName, value);
return value;
}
} else {
// retrieve template from Scalaris:
// note: templates are already cached, no need to cache them here
if (connection != null) {
// (ugly) fix for template parameter replacement if no parameters given,
// e.g. "{{noun}}" in the simple English Wiktionary
if (templateParameters != null && templateParameters.isEmpty()) {
templateParameters.put("", null);
}
String pageName = getTemplateNamespace() + ":" + articleName;
RevisionResult getRevResult = ScalarisDataHandler.getRevision(connection, pageName);
if (getRevResult.success) {
String text = getRevResult.revision.getText();
text = removeNoIncludeContents(text);
return text;
} else {
// System.err.println(getRevResult.message);
// return "<b>ERROR: template " + pageName + " not available: " + getRevResult.message + "</b>";
/*
* the template was not found and will never be - assume
* an empty content instead of letting the model try
* again (which is what it does if null is returned)
*/
return "";
}
}
}
}
if (getRedirectLink() != null) {
// requesting a page from a redirect?
return getRedirectContent(getRedirectLink());
}
// System.out.println("getRawWikiContent(" + namespace + ", " + articleName + ", " +
// templateParameters + ")");
return null;
}
|
diff --git a/common/src/test/java/com/andre/dbcompare/DbCompare.java b/common/src/test/java/com/andre/dbcompare/DbCompare.java
index cf5f81b..b00dc63 100644
--- a/common/src/test/java/com/andre/dbcompare/DbCompare.java
+++ b/common/src/test/java/com/andre/dbcompare/DbCompare.java
@@ -1,139 +1,140 @@
package com.andre.dbcompare;
import java.util.*;
import java.io.*;
import java.sql.*;
import javax.sql.*;
import org.apache.log4j.Logger;
//import com.beust.jcommander.JCommander;
//import com.beust.jcommander.Parameter;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.ApplicationContext;
public class DbCompare {
private static Logger logger = Logger.getLogger(DbCompare.class);
//private Options options = new Options();
//private JCommander jcommander;
private String [] configFiles = { "appContext.xml" };
private List<String> queries ;
private String username;
private String password;
private DataSource dataSource1;
private DataSource dataSource2;
public static void main(String [] args) throws Exception {
(new DbCompare()).process(args);
}
void process(String [] args) throws Exception {
initSpring();
for (String query : queries)
process(query);
}
void process(String query) throws Exception {
Connection conn1 = dataSource1.getConnection();
Connection conn2 = dataSource2.getConnection();
MyRunnable task1 = new MyRunnable(conn1,query);
Thread thread1 = new Thread(task1);
MyRunnable task2 = new MyRunnable(conn2,query);
Thread thread2 = new Thread(task2);
thread1.start();
thread2.start();
+ thread1.join();
thread2.join();
ResultSetMetaData meta = task1.rs.getMetaData();
int numCols = meta.getColumnCount();
int numRows;
boolean hasError = false;
for (numRows=0 ; task1.rs.next() && task2.rs.next() && !hasError ; numRows++) {
for (int col=1 ; col <= numCols && !hasError; col++) {
Object o1 = task1.rs.getObject(col) ;
Object o2 = task2.rs.getObject(col) ;
if (!o1.equals(o2)) {
error("Row="+numRows+" Column "+col+" is not the same: col1="+o1+" col2="+o2+" Query="+query);
hasError = true ;
}
}
}
if (! hasError) {
if (task1.rs.next() || task1.rs.next()) {
error("Result sets are not the same size. Query="+query);
return ;
}
info("OK: #rows="+numRows+" Query="+query);
}
task1.rs.close();
task2.rs.close();
}
class MyRunnable implements Runnable {
public String query;
public Connection conn;
public ResultSet rs ;
public MyRunnable(Connection conn, String query) {
this.query = query;
this.conn = conn;
}
public void run() {
try {
process(query);
} catch (Exception e) {
error("query="+query+" ex="+e);
}
}
void process(String query) throws Exception {
long t0=System.currentTimeMillis();
try {
long t1=System.currentTimeMillis();
Statement stmt = conn.createStatement() ;
rs = stmt.executeQuery(query);
long timeConn=t1-t0;
long timeExecute=System.currentTimeMillis()-t1;
long timeTotal=System.currentTimeMillis()-t0;
//logger.debug("timeTotal="+timeTotal+" timeConn="+timeConn+" timeExecute="+timeExecute);
} finally {
//if (conn != null) conn.close();
}
}
}
@SuppressWarnings("unchecked")
private void initSpring() throws Exception {
//logger.debug("configFiles="+Arrays.toString(configFiles));
ApplicationContext context = new ClassPathXmlApplicationContext(configFiles);
dataSource1 = context.getBean("dataSource1",DataSource.class);
dataSource2 = context.getBean("dataSource2",DataSource.class);
queries = (List<String>)context.getBean("queries");
}
/*
class Options {
@Parameter(names = { "-u", "--url" }, description = "Portal URL", required = true )
public String url ;
@Parameter(names = { "-i", "--iterations" }, description = "Iterations")
public int iterations = 1;
@Parameter(names = { "-h", "--help" }, description = "Help")
public boolean help = false;
}
void usage() {
jcommander.usage();
}
*/
void info(Object o) { System.out.println(o);}
void debug(Object o) { System.out.println(""+o);}
void error(Object o) { System.out.println("ERROR: "+o);}
}
| true | true | void process(String query) throws Exception {
Connection conn1 = dataSource1.getConnection();
Connection conn2 = dataSource2.getConnection();
MyRunnable task1 = new MyRunnable(conn1,query);
Thread thread1 = new Thread(task1);
MyRunnable task2 = new MyRunnable(conn2,query);
Thread thread2 = new Thread(task2);
thread1.start();
thread2.start();
thread2.join();
ResultSetMetaData meta = task1.rs.getMetaData();
int numCols = meta.getColumnCount();
int numRows;
boolean hasError = false;
for (numRows=0 ; task1.rs.next() && task2.rs.next() && !hasError ; numRows++) {
for (int col=1 ; col <= numCols && !hasError; col++) {
Object o1 = task1.rs.getObject(col) ;
Object o2 = task2.rs.getObject(col) ;
if (!o1.equals(o2)) {
error("Row="+numRows+" Column "+col+" is not the same: col1="+o1+" col2="+o2+" Query="+query);
hasError = true ;
}
}
}
if (! hasError) {
if (task1.rs.next() || task1.rs.next()) {
error("Result sets are not the same size. Query="+query);
return ;
}
info("OK: #rows="+numRows+" Query="+query);
}
task1.rs.close();
task2.rs.close();
}
| void process(String query) throws Exception {
Connection conn1 = dataSource1.getConnection();
Connection conn2 = dataSource2.getConnection();
MyRunnable task1 = new MyRunnable(conn1,query);
Thread thread1 = new Thread(task1);
MyRunnable task2 = new MyRunnable(conn2,query);
Thread thread2 = new Thread(task2);
thread1.start();
thread2.start();
thread1.join();
thread2.join();
ResultSetMetaData meta = task1.rs.getMetaData();
int numCols = meta.getColumnCount();
int numRows;
boolean hasError = false;
for (numRows=0 ; task1.rs.next() && task2.rs.next() && !hasError ; numRows++) {
for (int col=1 ; col <= numCols && !hasError; col++) {
Object o1 = task1.rs.getObject(col) ;
Object o2 = task2.rs.getObject(col) ;
if (!o1.equals(o2)) {
error("Row="+numRows+" Column "+col+" is not the same: col1="+o1+" col2="+o2+" Query="+query);
hasError = true ;
}
}
}
if (! hasError) {
if (task1.rs.next() || task1.rs.next()) {
error("Result sets are not the same size. Query="+query);
return ;
}
info("OK: #rows="+numRows+" Query="+query);
}
task1.rs.close();
task2.rs.close();
}
|
diff --git a/CapstoneProject/src/java/capstone/server/GameManager.java b/CapstoneProject/src/java/capstone/server/GameManager.java
index 51ff0ec..bbcfa92 100644
--- a/CapstoneProject/src/java/capstone/server/GameManager.java
+++ b/CapstoneProject/src/java/capstone/server/GameManager.java
@@ -1,158 +1,158 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package capstone.server;
import capstone.game.*;
import capstone.player.GameBot;
import capstone.player.Player;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.HttpSession;
/**
*
* @author Max
*/
public class GameManager {
static Map<HttpSession, RemotePlayer> players = new ConcurrentHashMap<HttpSession, RemotePlayer>();
static Map<HttpSession, GameSession> gameSessions = new ConcurrentHashMap<HttpSession, GameSession>();
static Map<GameSession, List<HttpSession>> watchers = new ConcurrentHashMap<GameSession, List<HttpSession>>();
static Map<String, GameSession> gameIDs = new ConcurrentHashMap<String, GameSession>();
static Map<HttpSession, BlockingQueue<String>> states = new ConcurrentHashMap<HttpSession, BlockingQueue<String>>();
static Map<String, String> openGames = new ConcurrentHashMap<String,String>();
//For now, only one bot - DefaultBot
private static final Player DEFAULT_BOT = new GameBot();
//Add a player to an existing game
public static void joinGame(HttpSession session, String gameID){
try {
session.getServletContext().log("Player joining game session (ID "+gameID+")");
RemotePlayer player = players.get(session);
GameSession game = gameIDs.get(gameID);
game.Join(player);
if(!game.isOpen()){
openGames.remove(game.SessionID);
}
} catch (IllegalGameException ex) {
newGame(session);
}
}
public static void BotJoin(HttpSession session){
try {
gameSessions.get(session).Join(DEFAULT_BOT);
} catch (IllegalGameException ex) {
Logger.getLogger(GameManager.class.getName()).log(Level.WARNING, "Error adding bot to game", ex);
}
}
public static String getOpenGames(){
StringBuilder builder = new StringBuilder();
builder=builder.append("{\"games:\"");
boolean first=true;
for(Entry<String, String> entry: openGames.entrySet()){
if(!first){
builder=builder.append(",");
}
else{
first=false;
}
builder=builder.append("[\"").append(entry.getKey()).append("\",\"").append(entry.getValue()).append("\"]");
}
return builder.append("}").toString();
}
//Create a new game session
public static void newGame(HttpSession session){
GameSession game = new GameSession();
gameIDs.put(game.SessionID, game);
try {
game.Join(players.get(session));
gameSessions.put(session, game);
- openGames.put(game.SessionID, session.getAttribute("name").toString());
+ openGames.put(game.SessionID, session.getAttribute("_user").toString());
List<HttpSession> sessions = watchers.get(game);
if(sessions==null){
sessions=new ArrayList<HttpSession>();
watchers.put(game, sessions);
}
sessions.add(session);
String initialMessage = JSONBuilder.buildJSON(game, players.get(session));
states.get(session).offer(initialMessage);
} catch (IllegalGameException ex) {
Logger.getLogger(GameManager.class.getName()).log(Level.SEVERE, "Error creating new game", ex);
}
}
public static void newPlayer(HttpSession session, String name){
session.setAttribute("_user", name);
if(!players.containsKey(session)){
players.put(session, new RemotePlayer(name));
}
BlockingQueue<String> messageQueue = new ArrayBlockingQueue<String>(10);
states.put(session, messageQueue);
}
public static void disconnect (HttpSession session) {
GameManager.leave(session);
players.remove(session);
states.remove(session);
}
public static void leave(HttpSession session){
GameSession game = gameSessions.get(session);
game.Leave(players.get(session));
states.get(session).clear();
gameIDs.remove(game.SessionID);
openGames.remove(game.SessionID);
}
//Return the oldest state. If a newer state is available, remove that state.
public static String getGame(HttpSession session){
BlockingQueue<String> messages = states.get(session);
try {
return messages.take();
} catch (InterruptedException ex) {
Logger.getLogger(GameManager.class.getName()).log(Level.SEVERE, null, ex);
return null;
}
}
public static RemotePlayer getPlayer(HttpSession session){
return players.get(session);
}
public static void makeMove(HttpSession session, int a, int b, int x, int y){
Coordinates coords = new Coordinates(a, b, x, y);
GameSession game = gameSessions.get(session);
RemotePlayer player = players.get(session);
GameState board = game.getCurrentGame();
//only move if we're supposed to
if(player.isActive()){
if (GameRules.validMove(board, coords)){
player.setActive(false);
game.move(player, coords);
String nextState=JSONBuilder.buildJSON(game, player);
for(HttpSession s: watchers.get(game)){
states.get(s).offer(nextState);
}
}
}
}
}
| true | true | public static void newGame(HttpSession session){
GameSession game = new GameSession();
gameIDs.put(game.SessionID, game);
try {
game.Join(players.get(session));
gameSessions.put(session, game);
openGames.put(game.SessionID, session.getAttribute("name").toString());
List<HttpSession> sessions = watchers.get(game);
if(sessions==null){
sessions=new ArrayList<HttpSession>();
watchers.put(game, sessions);
}
sessions.add(session);
String initialMessage = JSONBuilder.buildJSON(game, players.get(session));
states.get(session).offer(initialMessage);
} catch (IllegalGameException ex) {
Logger.getLogger(GameManager.class.getName()).log(Level.SEVERE, "Error creating new game", ex);
}
}
| public static void newGame(HttpSession session){
GameSession game = new GameSession();
gameIDs.put(game.SessionID, game);
try {
game.Join(players.get(session));
gameSessions.put(session, game);
openGames.put(game.SessionID, session.getAttribute("_user").toString());
List<HttpSession> sessions = watchers.get(game);
if(sessions==null){
sessions=new ArrayList<HttpSession>();
watchers.put(game, sessions);
}
sessions.add(session);
String initialMessage = JSONBuilder.buildJSON(game, players.get(session));
states.get(session).offer(initialMessage);
} catch (IllegalGameException ex) {
Logger.getLogger(GameManager.class.getName()).log(Level.SEVERE, "Error creating new game", ex);
}
}
|
diff --git a/extensions/bundles/vcpe/src/main/java/org/opennaas/extensions/vcpe/manager/templates/Template.java b/extensions/bundles/vcpe/src/main/java/org/opennaas/extensions/vcpe/manager/templates/Template.java
index d391cd146..b3baa0be8 100644
--- a/extensions/bundles/vcpe/src/main/java/org/opennaas/extensions/vcpe/manager/templates/Template.java
+++ b/extensions/bundles/vcpe/src/main/java/org/opennaas/extensions/vcpe/manager/templates/Template.java
@@ -1,1167 +1,1167 @@
/**
*
*/
package org.opennaas.extensions.vcpe.manager.templates;
import static com.google.common.collect.Iterables.filter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import org.opennaas.extensions.router.model.utils.IPUtilsHelper;
import org.opennaas.extensions.vcpe.manager.VCPENetworkManagerException;
import org.opennaas.extensions.vcpe.manager.model.VCPEManagerModel;
import org.opennaas.extensions.vcpe.manager.model.VCPEPhysicalInfrastructure;
import org.opennaas.extensions.vcpe.model.BGP;
import org.opennaas.extensions.vcpe.model.Domain;
import org.opennaas.extensions.vcpe.model.Interface;
import org.opennaas.extensions.vcpe.model.Link;
import org.opennaas.extensions.vcpe.model.LogicalRouter;
import org.opennaas.extensions.vcpe.model.Router;
import org.opennaas.extensions.vcpe.model.VCPENetworkElement;
import org.opennaas.extensions.vcpe.model.VCPENetworkModel;
import org.opennaas.extensions.vcpe.model.VCPETemplate;
import org.opennaas.extensions.vcpe.model.VRRP;
import org.opennaas.extensions.vcpe.model.helper.VCPENetworkModelHelper;
/**
* @author Jordi
*/
public class Template implements ITemplate {
private static final String TEMPLATE = "/templates/template.properties";
private static final String BGP_TEMPLATE = "/templates/bgpModel1.properties";
private String templateType = TemplateSelector.VCPE_TEMPLATE;
private Properties props;
private Properties bgpProps;
/**
* @throws VCPENetworkManagerException
*
*/
public Template() throws VCPENetworkManagerException {
try {
props = new Properties();
props.load(this.getClass().getResourceAsStream(TEMPLATE));
bgpProps = new Properties();
bgpProps.load(this.getClass().getResourceAsStream(BGP_TEMPLATE));
} catch (IOException e) {
throw new VCPENetworkManagerException("can't load the template properties");
}
}
public String getTemplateType() {
return templateType;
}
/**
* Generate the model
*
* @return VCPENetworkModel
*/
@Override
public VCPENetworkModel buildModel(VCPENetworkModel initialModel) throws VCPENetworkManagerException {
VCPENetworkModel model = new VCPENetworkModel();
model.setId(initialModel.getId());
model.setName(initialModel.getName());
model.setClientIpRange(initialModel.getClientIpRange());
model.setTemplateType(initialModel.getTemplateType());
// FIXME TEMPORAL CODE. REMOVE WHEN REFACTOR IS COMPLETED. initialModel will be a complete model.
// Generate the physical model
VCPENetworkModel phy = generateAndMapPhysicalElements(initialModel);
// checkPhysicalAvailability(physicalElements, managerModel);
// Generate the logical model
VCPENetworkModel logical = generateAndMapLogicalElements(phy, initialModel);
// set VRRP configuration
// model.setVrrp(configureVRRP(logical));
model.setVrrp(logical.getVrrp());
model.setBgp(generateBGPConfig(logical));
// Add all elements
List<VCPENetworkElement> elements = new ArrayList<VCPENetworkElement>();
model.setElements(elements);
elements.addAll(logical.getElements());
return model;
}
@Override
public VCPENetworkModel getPhysicalInfrastructureSuggestion() throws VCPENetworkManagerException {
VCPENetworkModel generated = generatePhysicalElements();
// TODO suggested mapping should be more intelligent, not properties driven
VCPENetworkModel mappedFromProperties = mapPhysicalElementsFromProperties(generated, props);
// TODO MUST CHECK MAPPED ELEMENTS EXIST IN PHYSICAL TOPOLOGY
return mappedFromProperties;
}
@Override
public VCPENetworkModel getLogicalInfrastructureSuggestion(VCPENetworkModel physicalInfrastructure) {
VCPENetworkModel phy = generateAndMapPhysicalElements(physicalInfrastructure);
VCPENetworkModel generated = generateLogicalElements();
// TODO suggested mapping should be more intelligent, not properties driven
VCPENetworkModel mappedFromProperties = mapLogicalElementsFromProperties(generated, props);
VCPENetworkModel mappedWithPhy = mapLogicalAndPhysical(phy, mappedFromProperties);
// TODO MUST CHECK MAPPED ELEMENTS EXIST IN PHYSICAL INFRASTRUCTURE
return mappedWithPhy;
}
// FIXME TEMPORAL METHOD. REMOVE WHEN REFACTOR IS FINISHED
private VCPENetworkModel generateAndMapPhysicalElements(VCPENetworkModel initialModel) {
VCPENetworkModel generated = generatePhysicalElements();
VCPENetworkModel mappedFromProperties = mapPhysicalElementsFromProperties(generated, props);
VCPENetworkModel mapped = mapPhysicalElementsFromInputModel(mappedFromProperties, initialModel);
// TODO MUST CHECK MAPPED ELEMENTS EXIST IN PHYSICAL TOPOLOGY
return mapped;
}
// FIXME TEMPORAL METHOD. REMOVE WHEN REFACTOR IS FINISHED
private VCPENetworkModel generateAndMapLogicalElements(VCPENetworkModel phy, VCPENetworkModel initialModel) {
VCPENetworkModel suggested = getLogicalInfrastructureSuggestion(phy);
VCPENetworkModel mapped = mapLogicalElementsFromInputModel(suggested, initialModel);
// TODO MUST CHECK MAPPED ELEMENTS EXIST IN PHYSICAL TOPOLOGY
return mapped;
}
private VCPENetworkModel generatePhysicalElements() {
Router core = new Router();
core.setTemplateName(VCPETemplate.CORE_PHY_ROUTER);
Interface coreMaster = new Interface();
coreMaster.setTemplateName(VCPETemplate.CORE_PHY_INTERFACE_MASTER);
Interface coreBkp = new Interface();
coreBkp.setTemplateName(VCPETemplate.CORE_PHY_INTERFACE_BKP);
Interface coreLo = new Interface();
coreLo.setTemplateName(VCPETemplate.CORE_PHY_LO_INTERFACE);
List<Interface> coreInterfaces = new ArrayList<Interface>();
coreInterfaces.add(coreMaster);
coreInterfaces.add(coreBkp);
coreInterfaces.add(coreLo);
core.setInterfaces(coreInterfaces);
Router r1 = new Router();
r1.setTemplateName(VCPETemplate.CPE1_PHY_ROUTER);
Interface inter1 = new Interface();
inter1.setTemplateName(VCPETemplate.INTER1_PHY_INTERFACE_LOCAL);
Interface inter1other = new Interface();
inter1other.setTemplateName(VCPETemplate.INTER1_PHY_INTERFACE_AUTOBAHN);
Interface down1 = new Interface();
down1.setTemplateName(VCPETemplate.DOWN1_PHY_INTERFACE_LOCAL);
Interface down1other = new Interface();
down1other.setTemplateName(VCPETemplate.DOWN1_PHY_INTERFACE_AUTOBAHN);
Interface up1 = new Interface();
up1.setTemplateName(VCPETemplate.UP1_PHY_INTERFACE_LOCAL);
// Interface client1 = new Interface();
// client1.setTemplateName(VCPETemplate.CLIENT1_PHY_INTERFACE_AUTOBAHN);
Interface lo1 = new Interface();
lo1.setTemplateName(VCPETemplate.LO1_PHY_INTERFACE);
List<Interface> r1Interfaces = new ArrayList<Interface>();
r1Interfaces.add(inter1);
r1Interfaces.add(down1);
r1Interfaces.add(up1);
r1Interfaces.add(lo1);
r1.setInterfaces(r1Interfaces);
Router r2 = new Router();
r2.setTemplateName(VCPETemplate.CPE2_PHY_ROUTER);
Interface inter2 = new Interface();
inter2.setTemplateName(VCPETemplate.INTER2_PHY_INTERFACE_LOCAL);
Interface inter2other = new Interface();
inter2other.setTemplateName(VCPETemplate.INTER2_PHY_INTERFACE_AUTOBAHN);
Interface down2 = new Interface();
down2.setTemplateName(VCPETemplate.DOWN2_PHY_INTERFACE_LOCAL);
Interface down2other = new Interface();
down2other.setTemplateName(VCPETemplate.DOWN2_PHY_INTERFACE_AUTOBAHN);
Interface up2 = new Interface();
up2.setTemplateName(VCPETemplate.UP2_PHY_INTERFACE_LOCAL);
// Interface client2 = new Interface();
// client2.setTemplateName(VCPETemplate.CLIENT2_PHY_INTERFACE_AUTOBAHN);
Interface lo2 = new Interface();
lo2.setTemplateName(VCPETemplate.LO2_PHY_INTERFACE);
List<Interface> r2Interfaces = new ArrayList<Interface>();
r2Interfaces.add(inter2);
r2Interfaces.add(down2);
r2Interfaces.add(up2);
r2Interfaces.add(lo2);
r2.setInterfaces(r2Interfaces);
Domain autobahn = new Domain();
autobahn.setTemplateName(VCPETemplate.AUTOBAHN);
List<Interface> autobahnInterfaces = new ArrayList<Interface>();
autobahnInterfaces.add(inter1other);
autobahnInterfaces.add(inter2other);
autobahnInterfaces.add(down1other);
autobahnInterfaces.add(down2other);
// autobahnInterfaces.add(client1);
// autobahnInterfaces.add(client2);
autobahn.setInterfaces(autobahnInterfaces);
List<VCPENetworkElement> elements = new ArrayList<VCPENetworkElement>();
elements.add(core);
elements.addAll(core.getInterfaces());
elements.add(r1);
elements.addAll(r1.getInterfaces());
elements.add(r2);
elements.addAll(r2.getInterfaces());
elements.add(autobahn);
elements.addAll(autobahn.getInterfaces());
VCPENetworkModel model = new VCPENetworkModel();
model.setElements(elements);
model.setTemplateType(getTemplateType());
model.setCreated(false);
return model;
}
private VCPENetworkModel generateLogicalElements() {
// LogicalRouter 1
Router vcpe1 = new LogicalRouter();
vcpe1.setTemplateName(VCPETemplate.VCPE1_ROUTER);
List<Interface> interfaces = new ArrayList<Interface>();
vcpe1.setInterfaces(interfaces);
Interface inter1 = new Interface();
Interface down1 = new Interface();
Interface up1 = new Interface();
Interface lo1 = new Interface();
interfaces.add(inter1);
interfaces.add(down1);
interfaces.add(up1);
interfaces.add(lo1);
inter1.setTemplateName(VCPETemplate.INTER1_INTERFACE_LOCAL);
down1.setTemplateName(VCPETemplate.DOWN1_INTERFACE_LOCAL);
up1.setTemplateName(VCPETemplate.UP1_INTERFACE_LOCAL);
lo1.setTemplateName(VCPETemplate.LO1_INTERFACE);
// LogicalRouter 2
Router vcpe2 = new LogicalRouter();
vcpe2.setTemplateName(VCPETemplate.VCPE2_ROUTER);
interfaces = new ArrayList<Interface>();
vcpe2.setInterfaces(interfaces);
Interface inter2 = new Interface();
Interface down2 = new Interface();
Interface up2 = new Interface();
Interface lo2 = new Interface();
interfaces.add(inter2);
interfaces.add(down2);
interfaces.add(up2);
interfaces.add(lo2);
inter2.setTemplateName(VCPETemplate.INTER2_INTERFACE_LOCAL);
down2.setTemplateName(VCPETemplate.DOWN2_INTERFACE_LOCAL);
up2.setTemplateName(VCPETemplate.UP2_INTERFACE_LOCAL);
lo2.setTemplateName(VCPETemplate.LO2_INTERFACE);
// BoD
// Notice these logical interfaces are not inside a BoD object (by now)
List<Interface> bodInterfaces = new ArrayList<Interface>();
Interface inter1other = new Interface();
Interface down1other = new Interface();
Interface inter2other = new Interface();
Interface down2other = new Interface();
Interface client1other = new Interface();
Interface client2other = new Interface();
Interface client1otherPhy = new Interface();
Interface client2otherPhy = new Interface();
bodInterfaces.add(inter1other);
bodInterfaces.add(down1other);
bodInterfaces.add(inter2other);
bodInterfaces.add(down2other);
bodInterfaces.add(client1other);
bodInterfaces.add(client2other);
- bodInterfaces.add(client2otherPhy);
+ bodInterfaces.add(client1otherPhy);
bodInterfaces.add(client2otherPhy);
inter1other.setTemplateName(VCPETemplate.INTER1_INTERFACE_AUTOBAHN);
down1other.setTemplateName(VCPETemplate.DOWN1_INTERFACE_AUTOBAHN);
inter2other.setTemplateName(VCPETemplate.INTER2_INTERFACE_AUTOBAHN);
down2other.setTemplateName(VCPETemplate.DOWN2_INTERFACE_AUTOBAHN);
client1other.setTemplateName(VCPETemplate.CLIENT1_INTERFACE_AUTOBAHN);
client2other.setTemplateName(VCPETemplate.CLIENT2_INTERFACE_AUTOBAHN);
- client1other.setTemplateName(VCPETemplate.CLIENT1_PHY_INTERFACE_AUTOBAHN);
- client2other.setTemplateName(VCPETemplate.CLIENT2_PHY_INTERFACE_AUTOBAHN);
+ client1otherPhy.setTemplateName(VCPETemplate.CLIENT1_PHY_INTERFACE_AUTOBAHN);
+ client2otherPhy.setTemplateName(VCPETemplate.CLIENT2_PHY_INTERFACE_AUTOBAHN);
// noc network interface
// Notice these logical interfaces are not inside a router object (by now)
Interface up1other = new Interface();
Interface up2other = new Interface();
up1other.setTemplateName(VCPETemplate.UP1_INTERFACE_PEER);
up2other.setTemplateName(VCPETemplate.UP2_INTERFACE_PEER);
// LINKS
// Inter links
Link linkInter1local = getLink(null, VCPETemplate.INTER1_LINK_LOCAL, VCPETemplate.LINK_TYPE_ETH, inter1, inter1other);
Link linkInter1other = getLink(null, VCPETemplate.INTER_LINK_AUTOBAHN, VCPETemplate.LINK_TYPE_AUTOBAHN, inter1other, inter2other);
Link linkInter2local = getLink(null, VCPETemplate.INTER2_LINK_LOCAL, VCPETemplate.LINK_TYPE_ETH, inter2, inter2other);
// Down links
Link linkDown1local = getLink(null, VCPETemplate.DOWN1_LINK_LOCAL, VCPETemplate.LINK_TYPE_ETH, down1, down1other);
Link linkDown1other = getLink(null, VCPETemplate.DOWN1_LINK_AUTOBAHN, VCPETemplate.LINK_TYPE_AUTOBAHN, down1other, client1other);
Link linkDown2local = getLink(null, VCPETemplate.DOWN2_LINK_LOCAL, VCPETemplate.LINK_TYPE_ETH, down2, down2other);
Link linkDown2other = getLink(null, VCPETemplate.DOWN2_LINK_AUTOBAHN, VCPETemplate.LINK_TYPE_AUTOBAHN, down2other, client2other);
// Up links
Link linkUp1 = getLink(null, VCPETemplate.UP1_LINK, VCPETemplate.LINK_TYPE_LT, up1, up1other);
Link linkUp2 = getLink(null, VCPETemplate.UP2_LINK, VCPETemplate.LINK_TYPE_LT, up2, up2other);
// Virtual links
Link linkInter = getLink(null, VCPETemplate.INTER_LINK, VCPETemplate.LINK_TYPE_VIRTUAL, inter1, inter2);
List<Link> subLinks = new ArrayList<Link>();
subLinks.add(linkInter1local);
subLinks.add(linkInter1other);
subLinks.add(linkInter2local);
linkInter.setImplementedBy(subLinks);
Link linkdown1 = getLink(null, VCPETemplate.DOWN1_LINK, VCPETemplate.LINK_TYPE_VIRTUAL, down1, client1other);
subLinks = new ArrayList<Link>();
subLinks.add(linkDown1local);
subLinks.add(linkDown1other);
linkdown1.setImplementedBy(subLinks);
Link linkdown2 = getLink(null, VCPETemplate.DOWN2_LINK, VCPETemplate.LINK_TYPE_VIRTUAL, down2, client2other);
subLinks.add(linkDown2local);
subLinks.add(linkDown2other);
linkdown2.setImplementedBy(subLinks);
List<VCPENetworkElement> elements = new ArrayList<VCPENetworkElement>();
elements.add(vcpe1);
elements.addAll(vcpe1.getInterfaces());
elements.add(vcpe2);
elements.addAll(vcpe2.getInterfaces());
elements.addAll(bodInterfaces);
elements.add(up1other);
elements.add(up2other);
elements.add(linkInter);
elements.addAll(linkInter.getImplementedBy());
elements.add(linkdown1);
elements.addAll(linkdown1.getImplementedBy());
elements.add(linkdown2);
elements.addAll(linkdown2.getImplementedBy());
elements.add(linkUp1);
elements.add(linkUp2);
// configure VRRP
VRRP vrrp = new VRRP();
vrrp.setMasterRouter(vcpe1);
vrrp.setMasterInterface(down1);
vrrp.setBackupRouter(vcpe2);
vrrp.setBackupInterface(down2);
VCPENetworkModel model = new VCPENetworkModel();
model.setElements(elements);
model.setTemplateType(getTemplateType());
model.setCreated(false);
model.setVrrp(vrrp);
model.setBgp(new BGP());
return model;
}
private VCPENetworkModel mapPhysicalElementsFromProperties(VCPENetworkModel model, Properties props) {
Router core = (Router) VCPENetworkModelHelper.getElementByTemplateName(model, VCPETemplate.CORE_PHY_ROUTER);
core.setName(props.getProperty("vcpenetwork.routercore.name"));
Interface coremaster = (Interface) VCPENetworkModelHelper.getElementByTemplateName(core.getInterfaces(),
VCPETemplate.CORE_PHY_INTERFACE_MASTER);
coremaster.setName(props.getProperty("vcpenetwork.routercore.interface.master.name"));
coremaster.setPhysicalInterfaceName(props.getProperty("vcpenetwork.routercore.interface.master.name"));
Interface corebkp = (Interface) VCPENetworkModelHelper.getElementByTemplateName(core.getInterfaces(), VCPETemplate.CORE_PHY_INTERFACE_BKP);
corebkp.setName(props.getProperty("vcpenetwork.routercore.interface.bkp.name"));
corebkp.setPhysicalInterfaceName(props.getProperty("vcpenetwork.routercore.interface.bkp.name"));
Interface corelo = (Interface) VCPENetworkModelHelper.getElementByTemplateName(core.getInterfaces(), VCPETemplate.CORE_PHY_LO_INTERFACE);
corelo.setName(props.getProperty("vcpenetwork.routercore.interface.lo.name"));
corelo.setPhysicalInterfaceName(props.getProperty("vcpenetwork.routercore.interface.lo.name"));
// Router1
Router r1 = (Router) VCPENetworkModelHelper.getElementByTemplateName(model, VCPETemplate.CPE1_PHY_ROUTER);
r1.setName(props.getProperty("vcpenetwork.router1.name"));
Interface inter1 = (Interface) VCPENetworkModelHelper.getElementByTemplateName(r1.getInterfaces(), VCPETemplate.INTER1_PHY_INTERFACE_LOCAL);
inter1.setName(props.getProperty("vcpenetwork.router1.interface.inter.name"));
inter1.setPhysicalInterfaceName(props.getProperty("vcpenetwork.router1.interface.inter.name"));
Interface down1 = (Interface) VCPENetworkModelHelper.getElementByTemplateName(r1.getInterfaces(), VCPETemplate.DOWN1_PHY_INTERFACE_LOCAL);
down1.setName(props.getProperty("vcpenetwork.router1.interface.down.name"));
down1.setPhysicalInterfaceName(props.getProperty("vcpenetwork.router1.interface.down.name"));
Interface up1 = (Interface) VCPENetworkModelHelper.getElementByTemplateName(r1.getInterfaces(), VCPETemplate.UP1_PHY_INTERFACE_LOCAL);
up1.setName(props.getProperty("vcpenetwork.router1.interface.up.name"));
up1.setPhysicalInterfaceName(props.getProperty("vcpenetwork.router1.interface.up.name"));
Interface lo1 = (Interface) VCPENetworkModelHelper.getElementByTemplateName(r1.getInterfaces(), VCPETemplate.LO1_PHY_INTERFACE);
lo1.setName(props.getProperty("vcpenetwork.router1.interface.lo.name"));
lo1.setPhysicalInterfaceName(props.getProperty("vcpenetwork.router1.interface.lo.name"));
// Router2
Router r2 = (Router) VCPENetworkModelHelper.getElementByTemplateName(model, VCPETemplate.CPE2_PHY_ROUTER);
r2.setName(props.getProperty("vcpenetwork.router2.name"));
Interface inter2 = (Interface) VCPENetworkModelHelper.getElementByTemplateName(r2.getInterfaces(), VCPETemplate.INTER2_PHY_INTERFACE_LOCAL);
inter2.setName(props.getProperty("vcpenetwork.router2.interface.inter.name"));
inter2.setPhysicalInterfaceName(props.getProperty("vcpenetwork.router2.interface.inter.name"));
Interface down2 = (Interface) VCPENetworkModelHelper.getElementByTemplateName(r2.getInterfaces(), VCPETemplate.DOWN2_PHY_INTERFACE_LOCAL);
down2.setName(props.getProperty("vcpenetwork.router2.interface.down.name"));
down2.setPhysicalInterfaceName(props.getProperty("vcpenetwork.router2.interface.down.name"));
Interface up2 = (Interface) VCPENetworkModelHelper.getElementByTemplateName(r2.getInterfaces(), VCPETemplate.UP2_PHY_INTERFACE_LOCAL);
up2.setName(props.getProperty("vcpenetwork.router2.interface.up.name"));
up2.setPhysicalInterfaceName(props.getProperty("vcpenetwork.router2.interface.up.name"));
Interface lo2 = (Interface) VCPENetworkModelHelper.getElementByTemplateName(r2.getInterfaces(), VCPETemplate.LO2_PHY_INTERFACE);
lo2.setName(props.getProperty("vcpenetwork.router2.interface.lo.name"));
lo2.setPhysicalInterfaceName(props.getProperty("vcpenetwork.router2.interface.lo.name"));
// BoD
Domain autobahn = (Domain) VCPENetworkModelHelper.getElementByTemplateName(model, VCPETemplate.AUTOBAHN);
autobahn.setName(props.getProperty("vcpenetwork.bod.name"));
Interface inter1other = (Interface) VCPENetworkModelHelper.getElementByTemplateName(autobahn.getInterfaces(),
VCPETemplate.INTER1_PHY_INTERFACE_AUTOBAHN);
inter1other.setName(props.getProperty("vcpenetwork.router1.interface.inter.other.name"));
inter1other.setPhysicalInterfaceName(props.getProperty("vcpenetwork.router1.interface.inter.other.name"));
Interface down1other = (Interface) VCPENetworkModelHelper.getElementByTemplateName(autobahn.getInterfaces(),
VCPETemplate.DOWN1_PHY_INTERFACE_AUTOBAHN);
down1other.setName(props.getProperty("vcpenetwork.router1.interface.down.other.name"));
down1other.setPhysicalInterfaceName(props.getProperty("vcpenetwork.router1.interface.down.other.name"));
Interface inter2other = (Interface) VCPENetworkModelHelper.getElementByTemplateName(autobahn.getInterfaces(),
VCPETemplate.INTER2_PHY_INTERFACE_AUTOBAHN);
inter2other.setName(props.getProperty("vcpenetwork.router2.interface.inter.other.name"));
inter2other.setPhysicalInterfaceName(props.getProperty("vcpenetwork.router2.interface.inter.other.name"));
Interface down2other = (Interface) VCPENetworkModelHelper.getElementByTemplateName(autobahn.getInterfaces(),
VCPETemplate.DOWN2_PHY_INTERFACE_AUTOBAHN);
down2other.setName(props.getProperty("vcpenetwork.router2.interface.down.other.name"));
down2other.setPhysicalInterfaceName(props.getProperty("vcpenetwork.router2.interface.down.other.name"));
// TODO BoD client interfaces
// NOT SUGGESTED (they change in every client)
return model;
}
private VCPENetworkModel mapLogicalElementsFromProperties(VCPENetworkModel model, Properties props) {
// Logical Router 1
Router vcpe1 = (Router) VCPENetworkModelHelper.getElementByTemplateName(model, VCPETemplate.VCPE1_ROUTER);
vcpe1.setName(props.getProperty("vcpenetwork.logicalrouter1.name"));
Interface ifaceInter = (Interface) VCPENetworkModelHelper
.getElementByTemplateName(vcpe1.getInterfaces(), VCPETemplate.INTER1_INTERFACE_LOCAL);
ifaceInter.setPhysicalInterfaceName(props.getProperty("vcpenetwork.logicalrouter1.interface.inter.name"));
ifaceInter.setPort(Integer.parseInt(props.getProperty("vcpenetwork.logicalrouter1.interface.inter.port").trim()));
ifaceInter.setVlan(Integer.parseInt(props.getProperty("vcpenetwork.logicalrouter1.interface.inter.vlan").trim()));
ifaceInter.setIpAddress(props.getProperty("vcpenetwork.logicalrouter1.interface.inter.ipaddress"));
ifaceInter.setName(ifaceInter.getPhysicalInterfaceName() + "." + ifaceInter.getPort());
Interface ifaceDown = (Interface) VCPENetworkModelHelper.getElementByTemplateName(vcpe1.getInterfaces(), VCPETemplate.DOWN1_INTERFACE_LOCAL);
ifaceDown.setPhysicalInterfaceName(props.getProperty("vcpenetwork.logicalrouter1.interface.down.name"));
ifaceDown.setPort(Integer.parseInt(props.getProperty("vcpenetwork.logicalrouter1.interface.down.port").trim()));
ifaceDown.setVlan(Integer.parseInt(props.getProperty("vcpenetwork.logicalrouter1.interface.down.vlan").trim()));
ifaceDown.setIpAddress(props.getProperty("vcpenetwork.logicalrouter1.interface.down.ipaddress"));
ifaceDown.setName(ifaceDown.getPhysicalInterfaceName() + "." + ifaceDown.getPort());
Interface ifaceUp = (Interface) VCPENetworkModelHelper.getElementByTemplateName(vcpe1.getInterfaces(), VCPETemplate.UP1_INTERFACE_LOCAL);
ifaceUp.setPhysicalInterfaceName(props.getProperty("vcpenetwork.logicalrouter1.interface.up.name"));
ifaceUp.setPort(Integer.parseInt(props.getProperty("vcpenetwork.logicalrouter1.interface.up.port").trim()));
ifaceUp.setVlan(Integer.parseInt(props.getProperty("vcpenetwork.logicalrouter1.interface.up.vlan").trim()));
ifaceUp.setIpAddress(props.getProperty("vcpenetwork.logicalrouter1.interface.up.ipaddress"));
ifaceUp.setName(ifaceUp.getPhysicalInterfaceName() + "." + ifaceUp.getPort());
Interface ifaceLo = (Interface) VCPENetworkModelHelper.getElementByTemplateName(vcpe1.getInterfaces(), VCPETemplate.LO1_INTERFACE);
ifaceLo.setPhysicalInterfaceName(props.getProperty("vcpenetwork.logicalrouter1.interface.lo.name"));
ifaceLo.setPort(Integer.parseInt(props.getProperty("vcpenetwork.logicalrouter1.interface.lo.port").trim()));
ifaceLo.setIpAddress(props.getProperty("vcpenetwork.logicalrouter1.interface.lo.ipaddress"));
ifaceLo.setName(ifaceLo.getPhysicalInterfaceName() + "." + ifaceLo.getPort());
// Logical Router 2
Router vcpe2 = (Router) VCPENetworkModelHelper.getElementByTemplateName(model, VCPETemplate.VCPE2_ROUTER);
vcpe2.setName(props.getProperty("vcpenetwork.logicalrouter2.name"));
ifaceInter = (Interface) VCPENetworkModelHelper.getElementByTemplateName(vcpe2.getInterfaces(), VCPETemplate.INTER2_INTERFACE_LOCAL);
ifaceInter.setPhysicalInterfaceName(props.getProperty("vcpenetwork.logicalrouter2.interface.inter.name"));
ifaceInter.setPort(Integer.parseInt(props.getProperty("vcpenetwork.logicalrouter2.interface.inter.port").trim()));
ifaceInter.setVlan(Integer.parseInt(props.getProperty("vcpenetwork.logicalrouter2.interface.inter.vlan").trim()));
ifaceInter.setIpAddress(props.getProperty("vcpenetwork.logicalrouter2.interface.inter.ipaddress"));
ifaceInter.setName(ifaceInter.getPhysicalInterfaceName() + "." + ifaceInter.getPort());
ifaceDown = (Interface) VCPENetworkModelHelper.getElementByTemplateName(vcpe2.getInterfaces(), VCPETemplate.DOWN2_INTERFACE_LOCAL);
ifaceDown.setPhysicalInterfaceName(props.getProperty("vcpenetwork.logicalrouter2.interface.down.name"));
ifaceDown.setPort(Integer.parseInt(props.getProperty("vcpenetwork.logicalrouter2.interface.down.port").trim()));
ifaceDown.setVlan(Integer.parseInt(props.getProperty("vcpenetwork.logicalrouter2.interface.down.vlan").trim()));
ifaceDown.setIpAddress(props.getProperty("vcpenetwork.logicalrouter2.interface.down.ipaddress"));
ifaceDown.setName(ifaceDown.getPhysicalInterfaceName() + "." + ifaceDown.getPort());
ifaceUp = (Interface) VCPENetworkModelHelper.getElementByTemplateName(vcpe2.getInterfaces(), VCPETemplate.UP2_INTERFACE_LOCAL);
ifaceUp.setPhysicalInterfaceName(props.getProperty("vcpenetwork.logicalrouter2.interface.up.name"));
ifaceUp.setPort(Integer.parseInt(props.getProperty("vcpenetwork.logicalrouter2.interface.up.port").trim()));
ifaceUp.setVlan(Integer.parseInt(props.getProperty("vcpenetwork.logicalrouter2.interface.up.vlan").trim()));
ifaceUp.setIpAddress(props.getProperty("vcpenetwork.logicalrouter2.interface.up.ipaddress"));
ifaceUp.setName(ifaceUp.getPhysicalInterfaceName() + "." + ifaceUp.getPort());
ifaceLo = (Interface) VCPENetworkModelHelper.getElementByTemplateName(vcpe2.getInterfaces(), VCPETemplate.LO2_INTERFACE);
ifaceLo.setPhysicalInterfaceName(props.getProperty("vcpenetwork.logicalrouter2.interface.lo.name"));
ifaceLo.setPort(Integer.parseInt(props.getProperty("vcpenetwork.logicalrouter2.interface.lo.port").trim()));
ifaceLo.setIpAddress(props.getProperty("vcpenetwork.logicalrouter2.interface.lo.ipaddress"));
ifaceLo.setName(ifaceLo.getPhysicalInterfaceName() + "." + ifaceLo.getPort());
// BoD
Interface ifaceClient1 = (Interface) VCPENetworkModelHelper.getElementByTemplateName(model, VCPETemplate.CLIENT1_INTERFACE_AUTOBAHN);
ifaceClient1.setPhysicalInterfaceName(props.getProperty("vcpenetwork.logicalrouter1.interface.client.name"));
ifaceClient1.setPort(Integer.parseInt(props.getProperty("vcpenetwork.logicalrouter1.interface.client.port").trim()));
ifaceClient1.setVlan(Integer.parseInt(props.getProperty("vcpenetwork.logicalrouter1.interface.client.vlan").trim()));
ifaceClient1.setName(ifaceClient1.getPhysicalInterfaceName() + "." + ifaceClient1.getPort());
Interface ifaceClient2 = (Interface) VCPENetworkModelHelper.getElementByTemplateName(model, VCPETemplate.CLIENT2_INTERFACE_AUTOBAHN);
ifaceClient2.setPhysicalInterfaceName(props.getProperty("vcpenetwork.logicalrouter2.interface.client.name"));
ifaceClient2.setPort(Integer.parseInt(props.getProperty("vcpenetwork.logicalrouter2.interface.client.port").trim()));
ifaceClient2.setVlan(Integer.parseInt(props.getProperty("vcpenetwork.logicalrouter2.interface.client.vlan").trim()));
ifaceClient2.setName(ifaceClient2.getPhysicalInterfaceName() + "." + ifaceClient2.getPort());
Interface inter1other = (Interface) VCPENetworkModelHelper.getElementByTemplateName(model, VCPETemplate.INTER1_INTERFACE_AUTOBAHN);
inter1other.setPhysicalInterfaceName(props.getProperty("vcpenetwork.logicalrouter1.interface.inter.other.name"));
inter1other.setPort(Integer.parseInt(props.getProperty("vcpenetwork.logicalrouter1.interface.inter.other.port").trim()));
inter1other.setVlan(Integer.parseInt(props.getProperty("vcpenetwork.logicalrouter1.interface.inter.other.vlan").trim()));
inter1other.setName(inter1other.getPhysicalInterfaceName() + "." + inter1other.getPort());
Interface down1other = (Interface) VCPENetworkModelHelper.getElementByTemplateName(model, VCPETemplate.DOWN1_INTERFACE_AUTOBAHN);
down1other.setPhysicalInterfaceName(props.getProperty("vcpenetwork.logicalrouter1.interface.down.other.name"));
down1other.setPort(Integer.parseInt(props.getProperty("vcpenetwork.logicalrouter1.interface.down.other.port").trim()));
down1other.setVlan(Integer.parseInt(props.getProperty("vcpenetwork.logicalrouter1.interface.down.other.vlan").trim()));
down1other.setName(down1other.getPhysicalInterfaceName() + "." + down1other.getPort());
Interface inter2other = (Interface) VCPENetworkModelHelper.getElementByTemplateName(model, VCPETemplate.INTER2_INTERFACE_AUTOBAHN);
inter2other.setPhysicalInterfaceName(props.getProperty("vcpenetwork.logicalrouter2.interface.inter.other.name"));
inter2other.setPort(Integer.parseInt(props.getProperty("vcpenetwork.logicalrouter2.interface.inter.other.port").trim()));
inter2other.setVlan(Integer.parseInt(props.getProperty("vcpenetwork.logicalrouter2.interface.inter.other.vlan").trim()));
inter2other.setName(inter2other.getPhysicalInterfaceName() + "." + inter2other.getPort());
Interface down2other = (Interface) VCPENetworkModelHelper.getElementByTemplateName(model, VCPETemplate.DOWN2_INTERFACE_AUTOBAHN);
down2other.setPhysicalInterfaceName(props.getProperty("vcpenetwork.logicalrouter2.interface.down.other.name"));
down2other.setPort(Integer.parseInt(props.getProperty("vcpenetwork.logicalrouter2.interface.down.other.port").trim()));
down2other.setVlan(Integer.parseInt(props.getProperty("vcpenetwork.logicalrouter2.interface.down.other.vlan").trim()));
down2other.setName(down2other.getPhysicalInterfaceName() + "." + down2other.getPort());
// Noc network
Interface up1other = (Interface) VCPENetworkModelHelper.getElementByTemplateName(model, VCPETemplate.UP1_INTERFACE_PEER);
up1other.setPhysicalInterfaceName(props.getProperty("vcpenetwork.logicalrouter1.interface.up.other.name"));
up1other.setPort(Integer.parseInt(props.getProperty("vcpenetwork.logicalrouter1.interface.up.other.port").trim()));
up1other.setVlan(Integer.parseInt(props.getProperty("vcpenetwork.logicalrouter1.interface.up.other.vlan").trim()));
up1other.setIpAddress(props.getProperty("vcpenetwork.logicalrouter1.interface.up.other.ipaddress"));
up1other.setName(up1other.getPhysicalInterfaceName() + "." + up1other.getPort());
Interface up2other = (Interface) VCPENetworkModelHelper.getElementByTemplateName(model, VCPETemplate.UP2_INTERFACE_PEER);
up2other.setPhysicalInterfaceName(props.getProperty("vcpenetwork.logicalrouter2.interface.up.other.name"));
up2other.setPort(Integer.parseInt(props.getProperty("vcpenetwork.logicalrouter2.interface.up.other.port").trim()));
up2other.setVlan(Integer.parseInt(props.getProperty("vcpenetwork.logicalrouter2.interface.up.other.vlan").trim()));
up2other.setIpAddress(props.getProperty("vcpenetwork.logicalrouter2.interface.up.other.ipaddress"));
up2other.setName(up2other.getPhysicalInterfaceName() + "." + up2other.getPort());
// VRRP
int vrrpGoup = Integer.parseInt(props.getProperty("vcpenetwork.vrrp.group").trim());
int masterVRRPPriority = Integer.parseInt(props.getProperty("vcpenetwork.vrrp.master.priority").trim());
int backupVRRPPriority = Integer.parseInt(props.getProperty("vcpenetwork.vrrp.backup.priority").trim());
model.getVrrp().setGroup(vrrpGoup);
model.getVrrp().setPriorityMaster(masterVRRPPriority);
model.getVrrp().setPriorityBackup(backupVRRPPriority);
model.getVrrp().setVirtualIPAddress(props.getProperty("vcpenetwork.vrrp.virtualIPAddress"));
// BGP
model.getBgp().setClientASNumber(props.getProperty("vcpenetwork.bgp.clientASNumber"));
model.getBgp().setNocASNumber(props.getProperty("vcpenetwork.bgp.nocASNumber"));
List<String> clientPrefixes = new ArrayList<String>();
clientPrefixes.add(props.getProperty("vcpenetwork.bgp.clientPrefixes"));
model.getBgp().setCustomerPrefixes(clientPrefixes);
// VCPE
model.setClientIpRange(props.getProperty("vcpenetwork.client.iprange"));
return model;
}
private VCPENetworkModel mapPhysicalElementsFromInputModel(VCPENetworkModel model, VCPENetworkModel inputModel) {
// TODO update ALL elements with data in inputModel (everything may have changed)
// // select client1 interface using inputModel
// Interface inputClient1 = (Interface) VCPENetworkModelHelper.getElementByTemplateName(inputModel,
// VCPETemplate.CLIENT1_PHY_INTERFACE_AUTOBAHN);
//
// Interface client1 = (Interface) VCPENetworkModelHelper.getElementByTemplateName(model, VCPETemplate.CLIENT1_PHY_INTERFACE_AUTOBAHN);
// client1.setName(inputClient1.getName());
// client1.setPhysicalInterfaceName(inputClient1.getPhysicalInterfaceName());
//
// // select client2 interface using inputModel
// Interface inputClient2 = (Interface) VCPENetworkModelHelper.getElementByTemplateName(inputModel,
// VCPETemplate.CLIENT2_PHY_INTERFACE_AUTOBAHN);
//
// Interface client2 = (Interface) VCPENetworkModelHelper.getElementByTemplateName(model, VCPETemplate.CLIENT2_PHY_INTERFACE_AUTOBAHN);
// client2.setName(inputClient2.getName());
// client2.setPhysicalInterfaceName(inputClient2.getPhysicalInterfaceName());
return model;
}
private VCPENetworkModel mapLogicalElementsFromInputModel(VCPENetworkModel model, VCPENetworkModel inputModel) {
// TODO update ALL elements with data in inputModel (everything may have changed)
// LR1
Router vcpe1input = (Router) VCPENetworkModelHelper.getElementByTemplateName(inputModel, VCPETemplate.VCPE1_ROUTER);
Router vcpe1 = (Router) VCPENetworkModelHelper.getElementByTemplateName(model, VCPETemplate.VCPE1_ROUTER);
vcpe1.setName(vcpe1input.getName() + "-" + inputModel.getName());
Interface inter1input = (Interface) VCPENetworkModelHelper.getElementByTemplateName(vcpe1input.getInterfaces(),
VCPETemplate.INTER1_INTERFACE_LOCAL);
Interface down1input = (Interface) VCPENetworkModelHelper.getElementByTemplateName(vcpe1input.getInterfaces(),
VCPETemplate.DOWN1_INTERFACE_LOCAL);
Interface up1input = (Interface) VCPENetworkModelHelper
.getElementByTemplateName(vcpe1input.getInterfaces(), VCPETemplate.UP1_INTERFACE_LOCAL);
Interface lo1input = (Interface) VCPENetworkModelHelper
.getElementByTemplateName(vcpe1input.getInterfaces(), VCPETemplate.LO1_INTERFACE);
Interface inter1 = (Interface) VCPENetworkModelHelper.getElementByTemplateName(vcpe1.getInterfaces(), VCPETemplate.INTER1_INTERFACE_LOCAL);
Interface down1 = (Interface) VCPENetworkModelHelper.getElementByTemplateName(vcpe1.getInterfaces(), VCPETemplate.DOWN1_INTERFACE_LOCAL);
Interface up1 = (Interface) VCPENetworkModelHelper.getElementByTemplateName(vcpe1.getInterfaces(), VCPETemplate.UP1_INTERFACE_LOCAL);
Interface lo1 = (Interface) VCPENetworkModelHelper.getElementByTemplateName(vcpe1.getInterfaces(), VCPETemplate.LO1_INTERFACE);
if (inter1input != null)
updateInterface(inter1, inter1input.getName(), inter1input.getVlan(), inter1input.getIpAddress(), inter1input.getPhysicalInterfaceName(),
inter1input.getPort());
if (down1input != null)
updateInterface(down1, down1input.getName(), down1input.getVlan(), down1input.getIpAddress(), down1input.getPhysicalInterfaceName(),
down1input.getPort());
if (up1input != null)
updateInterface(up1, up1input.getName(), up1input.getVlan(), up1input.getIpAddress(), up1input.getPhysicalInterfaceName(),
up1input.getPort());
if (lo1input != null)
updateInterface(lo1, lo1input.getName(), lo1input.getVlan(), lo1input.getIpAddress(), lo1input.getPhysicalInterfaceName(),
lo1input.getPort());
// LR2
Router vcpe2input = (Router) VCPENetworkModelHelper.getElementByTemplateName(inputModel, VCPETemplate.VCPE2_ROUTER);
Router vcpe2 = (Router) VCPENetworkModelHelper.getElementByTemplateName(model, VCPETemplate.VCPE2_ROUTER);
vcpe2.setName(vcpe2input.getName() + "-" + inputModel.getName());
Interface inter2input = (Interface) VCPENetworkModelHelper.getElementByTemplateName(vcpe2input.getInterfaces(),
VCPETemplate.INTER2_INTERFACE_LOCAL);
Interface down2input = (Interface) VCPENetworkModelHelper.getElementByTemplateName(vcpe2input.getInterfaces(),
VCPETemplate.DOWN2_INTERFACE_LOCAL);
Interface up2input = (Interface) VCPENetworkModelHelper
.getElementByTemplateName(vcpe2input.getInterfaces(), VCPETemplate.UP2_INTERFACE_LOCAL);
Interface lo2input = (Interface) VCPENetworkModelHelper
.getElementByTemplateName(vcpe2input.getInterfaces(), VCPETemplate.LO2_INTERFACE);
Interface inter2 = (Interface) VCPENetworkModelHelper.getElementByTemplateName(vcpe2.getInterfaces(), VCPETemplate.INTER2_INTERFACE_LOCAL);
Interface down2 = (Interface) VCPENetworkModelHelper.getElementByTemplateName(vcpe2.getInterfaces(), VCPETemplate.DOWN2_INTERFACE_LOCAL);
Interface up2 = (Interface) VCPENetworkModelHelper.getElementByTemplateName(vcpe2.getInterfaces(), VCPETemplate.UP2_INTERFACE_LOCAL);
Interface lo2 = (Interface) VCPENetworkModelHelper.getElementByTemplateName(vcpe2.getInterfaces(), VCPETemplate.LO2_INTERFACE);
if (inter2input != null)
updateInterface(inter2, inter2input.getName(), inter2input.getVlan(), inter2input.getIpAddress(), inter2input.getPhysicalInterfaceName(),
inter2input.getPort());
if (down2input != null)
updateInterface(down2, down2input.getName(), down2input.getVlan(), down2input.getIpAddress(), down2input.getPhysicalInterfaceName(),
down2input.getPort());
if (up2input != null)
updateInterface(up2, up2input.getName(), up2input.getVlan(), up2input.getIpAddress(), up2input.getPhysicalInterfaceName(),
up2input.getPort());
if (lo2input != null)
updateInterface(lo2, lo2input.getName(), lo2input.getVlan(), lo2input.getIpAddress(), lo2input.getPhysicalInterfaceName(),
lo2input.getPort());
// BOD
Interface client1input = (Interface) VCPENetworkModelHelper.getElementByTemplateName(inputModel, VCPETemplate.CLIENT1_INTERFACE_AUTOBAHN);
Interface client2input = (Interface) VCPENetworkModelHelper.getElementByTemplateName(inputModel, VCPETemplate.CLIENT2_INTERFACE_AUTOBAHN);
Interface client1 = (Interface) VCPENetworkModelHelper.getElementByTemplateName(model, VCPETemplate.CLIENT1_INTERFACE_AUTOBAHN);
Interface client2 = (Interface) VCPENetworkModelHelper.getElementByTemplateName(model, VCPETemplate.CLIENT2_INTERFACE_AUTOBAHN);
updateInterface(client1, client1input.getName(), client1input.getVlan(), client1input.getIpAddress(),
client1input.getPhysicalInterfaceName(), client1input.getPort());
updateInterface(client2, client2input.getName(), client2input.getVlan(), client2input.getIpAddress(),
client2input.getPhysicalInterfaceName(), client2input.getPort());
// set client physical interfaces
// select client1 interface using inputModel
Interface inputClient1 = (Interface) VCPENetworkModelHelper.getElementByTemplateName(inputModel,
VCPETemplate.CLIENT1_INTERFACE_AUTOBAHN);
Interface client1phy = (Interface) VCPENetworkModelHelper.getElementByTemplateName(model, VCPETemplate.CLIENT1_PHY_INTERFACE_AUTOBAHN);
client1phy.setName(inputClient1.getName());
client1phy.setPhysicalInterfaceName(inputClient1.getPhysicalInterfaceName());
// select client2 interface using inputModel
Interface inputClient2 = (Interface) VCPENetworkModelHelper.getElementByTemplateName(inputModel,
VCPETemplate.CLIENT2_INTERFACE_AUTOBAHN);
Interface client2phy = (Interface) VCPENetworkModelHelper.getElementByTemplateName(model, VCPETemplate.CLIENT2_PHY_INTERFACE_AUTOBAHN);
client2phy.setName(inputClient2.getName());
client2phy.setPhysicalInterfaceName(inputClient2.getPhysicalInterfaceName());
// VRRP
if (inputModel.getVrrp().getGroup() != null)
model.getVrrp().setGroup(inputModel.getVrrp().getGroup()); // TODO MUST CHANGE BETWEEN VCPEs
if (inputModel.getVrrp().getPriorityMaster() != null)
model.getVrrp().setPriorityMaster(inputModel.getVrrp().getPriorityMaster());
if (inputModel.getVrrp().getPriorityBackup() != null)
model.getVrrp().setPriorityBackup(inputModel.getVrrp().getPriorityBackup());
if (inputModel.getVrrp().getVirtualIPAddress() != null)
model.getVrrp().setVirtualIPAddress(inputModel.getVrrp().getVirtualIPAddress());
// BGP
if (inputModel.getBgp().getClientASNumber() != null)
model.getBgp().setClientASNumber(inputModel.getBgp().getClientASNumber());
if (inputModel.getBgp().getNocASNumber() != null)
model.getBgp().setNocASNumber(inputModel.getBgp().getNocASNumber());
if (inputModel.getBgp().getCustomerPrefixes() != null && !inputModel.getBgp().getCustomerPrefixes().isEmpty())
model.getBgp().setCustomerPrefixes(inputModel.getBgp().getCustomerPrefixes());
// TODO mapDependantLogicalElements(model);
return model;
}
private VCPENetworkModel mapLogicalAndPhysical(VCPENetworkModel physicalInfrastructure, VCPENetworkModel logicalInfrastructure) {
// put all physical elements in logicalInfrastructure
logicalInfrastructure.getElements().addAll(physicalInfrastructure.getElements());
// put up logical interfaces into core router
Router core = (Router) VCPENetworkModelHelper.getElementByTemplateName(logicalInfrastructure, VCPETemplate.CORE_PHY_ROUTER);
core.getInterfaces().add((Interface) VCPENetworkModelHelper.getElementByTemplateName(logicalInfrastructure, VCPETemplate.UP1_INTERFACE_PEER));
core.getInterfaces().add((Interface) VCPENetworkModelHelper.getElementByTemplateName(logicalInfrastructure, VCPETemplate.UP2_INTERFACE_PEER));
// put bod logical interfaces into bod
Domain bod = (Domain) VCPENetworkModelHelper.getElementByTemplateName(logicalInfrastructure, VCPETemplate.AUTOBAHN);
bod.getInterfaces().add(
(Interface) VCPENetworkModelHelper.getElementByTemplateName(logicalInfrastructure, VCPETemplate.CLIENT1_INTERFACE_AUTOBAHN));
bod.getInterfaces().add(
(Interface) VCPENetworkModelHelper.getElementByTemplateName(logicalInfrastructure, VCPETemplate.CLIENT2_INTERFACE_AUTOBAHN));
bod.getInterfaces().add(
(Interface) VCPENetworkModelHelper.getElementByTemplateName(logicalInfrastructure, VCPETemplate.INTER1_INTERFACE_AUTOBAHN));
bod.getInterfaces().add(
(Interface) VCPENetworkModelHelper.getElementByTemplateName(logicalInfrastructure, VCPETemplate.DOWN1_INTERFACE_AUTOBAHN));
bod.getInterfaces().add(
(Interface) VCPENetworkModelHelper.getElementByTemplateName(logicalInfrastructure, VCPETemplate.INTER2_INTERFACE_AUTOBAHN));
bod.getInterfaces().add(
(Interface) VCPENetworkModelHelper.getElementByTemplateName(logicalInfrastructure, VCPETemplate.DOWN2_INTERFACE_AUTOBAHN));
return logicalInfrastructure;
}
/**
* @param initialModel
* @return
*/
private List<VCPENetworkElement> generateLogicalElements(VCPENetworkModel initialModel) {
// ----------------------------- VCPE-router1 -----------------------------
Router vcpe1 = (Router) VCPENetworkModelHelper.getElementByTemplateName(initialModel, VCPETemplate.VCPE1_ROUTER);
vcpe1.setName(props.getProperty("vcpenetwork.logicalrouter1.name") + "-" + initialModel.getName());
// Interfaces VCPE-router1
Interface inter1 = (Interface) VCPENetworkModelHelper.getElementByTemplateName(initialModel, VCPETemplate.INTER1_INTERFACE_LOCAL);
Interface down1 = (Interface) VCPENetworkModelHelper.getElementByTemplateName(initialModel, VCPETemplate.DOWN1_INTERFACE_LOCAL);
Interface up1 = (Interface) VCPENetworkModelHelper.getElementByTemplateName(initialModel, VCPETemplate.UP1_INTERFACE_LOCAL);
// Other interfaces VCPE-router1
String inter1OtherName = props.getProperty("vcpenetwork.logicalrouter1.interface.inter.other.name");
String inter1OtherPort = props.getProperty("vcpenetwork.logicalrouter1.interface.inter.other.port");
Long inter1OtherVlan = Long.valueOf(props.getProperty("vcpenetwork.logicalrouter1.interface.inter.other.vlan").trim());
Interface inter1other = getInterface(inter1OtherName + "." + inter1OtherPort, VCPETemplate.INTER1_INTERFACE_AUTOBAHN, inter1OtherVlan, null,
inter1OtherName, Integer.parseInt(inter1OtherPort));
String down1OtherName = props.getProperty("vcpenetwork.logicalrouter1.interface.down.other.name");
String down1OtherPort = props.getProperty("vcpenetwork.logicalrouter1.interface.down.other.port");
Long down1OtherVlan = Long.valueOf(props.getProperty("vcpenetwork.logicalrouter1.interface.down.other.vlan"));
Interface down1other = getInterface(down1OtherName + "." + down1OtherPort, VCPETemplate.DOWN1_INTERFACE_AUTOBAHN, down1OtherVlan, null,
down1OtherName, Integer.parseInt(down1OtherPort));
String up1OtherName = props.getProperty("vcpenetwork.logicalrouter1.interface.up.other.name");
String up1OtherPort = props.getProperty("vcpenetwork.logicalrouter1.interface.up.other.port");
Long up1OtherVlan = Long.valueOf(props.getProperty("vcpenetwork.logicalrouter1.interface.up.other.vlan"));
String up1OtherIp = props.getProperty("vcpenetwork.logicalrouter1.interface.up.other.ipaddress");
Interface up1other = getInterface(up1OtherName + "." + up1OtherPort, VCPETemplate.UP1_INTERFACE_PEER, up1OtherVlan, up1OtherIp,
up1OtherName, Integer.parseInt(up1OtherPort));
// Loopback interface VCPE-router1
String loopback1Name = props.getProperty("vcpenetwork.logicalrouter1.interface.lo.name");
String loopback1Port = props.getProperty("vcpenetwork.logicalrouter1.interface.lo.port");
Long loopback1Vlan = 0L;
String loopback1Ip = props.getProperty("vcpenetwork.logicalrouter1.interface.lo.ipaddress");
Interface loopback1 = getInterface(loopback1Name + "." + loopback1Port, VCPETemplate.LO1_INTERFACE, loopback1Vlan, loopback1Ip,
loopback1Name, Integer.parseInt(loopback1Port));
vcpe1.getInterfaces().add(loopback1);
// ----------------------------- VCPE-router2 -----------------------------
Router vcpe2 = (Router) VCPENetworkModelHelper.getElementByTemplateName(initialModel, VCPETemplate.VCPE2_ROUTER);
vcpe2.setName(props.getProperty("vcpenetwork.logicalrouter2.name") + "-" + initialModel.getName());
// Interfaces VCPE-router2
Interface inter2 = (Interface) VCPENetworkModelHelper.getElementByTemplateName(initialModel, VCPETemplate.INTER2_INTERFACE_LOCAL);
Interface down2 = (Interface) VCPENetworkModelHelper.getElementByTemplateName(initialModel, VCPETemplate.DOWN2_INTERFACE_LOCAL);
Interface up2 = (Interface) VCPENetworkModelHelper.getElementByTemplateName(initialModel, VCPETemplate.UP2_INTERFACE_LOCAL);
// Other interfaces VCPE-router2
String inter2OtherName = props.getProperty("vcpenetwork.logicalrouter2.interface.inter.other.name");
String inter2OtherPort = props.getProperty("vcpenetwork.logicalrouter2.interface.inter.other.port");
Long inter2OtherVlan = Long.valueOf(props.getProperty("vcpenetwork.logicalrouter2.interface.inter.other.vlan").trim());
Interface inter2other = getInterface(inter2OtherName + "." + inter2OtherPort, VCPETemplate.INTER2_INTERFACE_AUTOBAHN, inter2OtherVlan, null,
inter2OtherName, Integer.parseInt(inter2OtherPort));
String down2OtherName = props.getProperty("vcpenetwork.logicalrouter2.interface.down.other.name");
String down2OtherPort = props.getProperty("vcpenetwork.logicalrouter2.interface.down.other.port");
Long down2OtherVlan = Long.valueOf(props.getProperty("vcpenetwork.logicalrouter2.interface.down.other.vlan").trim());
Interface down2other = getInterface(down2OtherName + "." + down2OtherPort, VCPETemplate.DOWN2_INTERFACE_AUTOBAHN, down2OtherVlan, null,
down2OtherName, Integer.parseInt(down2OtherPort));
String up2OtherName = props.getProperty("vcpenetwork.logicalrouter2.interface.up.other.name");
String up2OtherPort = props.getProperty("vcpenetwork.logicalrouter2.interface.up.other.port");
Long up2OtherVlan = Long.valueOf(props.getProperty("vcpenetwork.logicalrouter2.interface.up.other.vlan").trim());
String up2OtherIp = props.getProperty("vcpenetwork.logicalrouter2.interface.up.other.ipaddress");
Interface up2other = getInterface(up2OtherName + "." + up2OtherPort, VCPETemplate.UP2_INTERFACE_PEER, up2OtherVlan, up2OtherIp,
up2OtherName, Integer.parseInt(up2OtherPort));
// Loopback interface VCPE-router2
String loopback2Name = props.getProperty("vcpenetwork.logicalrouter2.interface.lo.name");
String loopback2Port = props.getProperty("vcpenetwork.logicalrouter2.interface.lo.port");
Long loopback2Vlan = 0L;
String loopback2Ip = props.getProperty("vcpenetwork.logicalrouter2.interface.lo.ipaddress");
Interface loopback2 = getInterface(loopback2Name + "." + loopback2Port, VCPETemplate.LO2_INTERFACE, loopback2Vlan, loopback2Ip,
loopback2Name, Integer.parseInt(loopback2Port));
vcpe2.getInterfaces().add(loopback2);
// Client interfaces
Interface client1other = (Interface) VCPENetworkModelHelper.getElementByTemplateName(initialModel, VCPETemplate.CLIENT1_INTERFACE_AUTOBAHN);
Interface client2other = (Interface) VCPENetworkModelHelper.getElementByTemplateName(initialModel, VCPETemplate.CLIENT2_INTERFACE_AUTOBAHN);
// ----------------------------- Links ------------------------------------
// Inter links
String linkInter1otherId = props.getProperty("vcpenetwork.logicalrouter1.link.inter.other.id");
Link linkInter1local = getLink(null, VCPETemplate.INTER1_LINK_LOCAL, VCPETemplate.LINK_TYPE_ETH, inter1, inter1other);
Link linkInter1other = getLink(linkInter1otherId, VCPETemplate.INTER_LINK_AUTOBAHN, VCPETemplate.LINK_TYPE_AUTOBAHN, inter1other, inter2other);
Link linkInter2local = getLink(null, VCPETemplate.INTER2_LINK_LOCAL, VCPETemplate.LINK_TYPE_ETH, inter2, inter2other);
// Down links
String linkDown1otherId = props.getProperty("vcpenetwork.logicalrouter1.link.down.other.id");
String linkDown2otherId = props.getProperty("vcpenetwork.logicalrouter2.link.down.other.id");
Link linkDown1local = getLink(null, VCPETemplate.DOWN1_LINK_LOCAL, VCPETemplate.LINK_TYPE_ETH, down1, down1other);
Link linkDown1other = getLink(linkDown1otherId, VCPETemplate.DOWN1_LINK_AUTOBAHN, VCPETemplate.LINK_TYPE_AUTOBAHN, down1other, client1other);
Link linkDown2local = getLink(null, VCPETemplate.DOWN2_LINK_LOCAL, VCPETemplate.LINK_TYPE_ETH, down2, down2other);
Link linkDown2other = getLink(linkDown2otherId, VCPETemplate.DOWN2_LINK_AUTOBAHN, VCPETemplate.LINK_TYPE_AUTOBAHN, down2other, client2other);
// Up links
Link linkUp1 = getLink(null, VCPETemplate.UP1_LINK, VCPETemplate.LINK_TYPE_LT, up1, up1other);
Link linkUp2 = getLink(null, VCPETemplate.UP2_LINK, VCPETemplate.LINK_TYPE_LT, up2, up2other);
// Virtual links
Link inter = getLink(null, VCPETemplate.INTER_LINK, VCPETemplate.LINK_TYPE_VIRTUAL, inter1, inter2);
List<Link> subLinks = new ArrayList<Link>();
subLinks.add(linkInter1local);
subLinks.add(linkInter1other);
subLinks.add(linkInter2local);
inter.setImplementedBy(subLinks);
Link linkdown1 = getLink(null, VCPETemplate.DOWN1_LINK, VCPETemplate.LINK_TYPE_VIRTUAL, down1, client1other);
subLinks = new ArrayList<Link>();
subLinks.add(linkDown1local);
subLinks.add(linkDown1other);
linkdown1.setImplementedBy(subLinks);
Link linkdown2 = getLink(null, VCPETemplate.DOWN2_LINK, VCPETemplate.LINK_TYPE_VIRTUAL, down2, client2other);
subLinks.add(linkDown2local);
subLinks.add(linkDown2other);
linkdown2.setImplementedBy(subLinks);
List<VCPENetworkElement> elements = new ArrayList<VCPENetworkElement>();
elements.add(vcpe1);
elements.addAll(vcpe1.getInterfaces());
elements.add(inter1other);
elements.add(down1other);
elements.add(up1other);
elements.add(vcpe2);
elements.addAll(vcpe2.getInterfaces());
elements.add(inter2other);
elements.add(down2other);
elements.add(up2other);
elements.add(client1other);
elements.add(client2other);
elements.add(inter);
elements.addAll(inter.getImplementedBy());
elements.add(linkdown1);
elements.addAll(linkdown1.getImplementedBy());
elements.add(linkdown2);
elements.addAll(linkdown2.getImplementedBy());
elements.add(linkUp1);
elements.add(linkUp2);
return elements;
}
private VRRP configureVRRP(VCPENetworkModel model) {
// VRRP group
int vrrpGoup = Integer.parseInt(props.getProperty("vcpenetwork.vrrp.group"));
// configuration VCPE-router1
int masterVRRPPriority = Integer.parseInt(props.getProperty("vcpenetwork.vrrp.master.priority"));
// configuration VCPE-router2
int backupVRRPPriority = Integer.parseInt(props.getProperty("vcpenetwork.vrrp.backup.priority"));
// get master router and interface
Router masterRouter = (Router) VCPENetworkModelHelper.getElementByTemplateName(model, VCPETemplate.VCPE1_ROUTER);
Interface masterInterface = (Interface) VCPENetworkModelHelper.getElementByTemplateName(model, VCPETemplate.DOWN1_INTERFACE_LOCAL);
// get backup router and interface
Router backupRouter = (Router) VCPENetworkModelHelper.getElementByTemplateName(model, VCPETemplate.VCPE2_ROUTER);
Interface backupInterface = (Interface) VCPENetworkModelHelper.getElementByTemplateName(model, VCPETemplate.DOWN2_INTERFACE_LOCAL);
// set values
VRRP vrrp = new VRRP();
vrrp.setVirtualIPAddress(model.getVrrp().getVirtualIPAddress());
vrrp.setGroup(vrrpGoup);
vrrp.setPriorityMaster(masterVRRPPriority);
vrrp.setPriorityBackup(backupVRRPPriority);
vrrp.setMasterRouter(masterRouter);
vrrp.setMasterInterface(masterInterface);
vrrp.setBackupRouter(backupRouter);
vrrp.setBackupInterface(backupInterface);
return vrrp;
}
private ConfigureBGPRequestParameters generateBGPParameters(VCPENetworkModel model) {
BGP bgp = model.getBgp();
ConfigureBGPRequestParameters params = new ConfigureBGPRequestParameters();
params.clientIPRanges = bgp.getCustomerPrefixes();
params.clientASNumber = bgp.getClientASNumber();
params.remoteASNum = bgp.getNocASNumber();
params.loAddr1 = "193.1.190.141/30"; // TODO get this from GUI
params.upRemoteAddr1 = "193.1.190.134/30"; // TODO get this from GUI
params.interAddr1 = ((Interface) VCPENetworkModelHelper.getElementByTemplateName(model, VCPETemplate.INTER1_INTERFACE_LOCAL))
.getIpAddress();
params.loAddr2 = "193.1.190.145/30"; // TODO get this from GUI
params.upRemoteAddr2 = "193.1.190.130/30"; // TODO get this from GUI
params.interAddr2 = ((Interface) VCPENetworkModelHelper.getElementByTemplateName(model, VCPETemplate.INTER2_INTERFACE_LOCAL))
.getIpAddress();
return params;
}
private BGP generateBGPConfig(VCPENetworkModel initialModel) {
BGP bgp = initialModel.getBgp();
ConfigureBGPRequestParameters bgpParams = generateBGPParameters(initialModel);
// FACTORY 1
String router1id = IPUtilsHelper.composedIPAddressToIPAddressAndMask(bgpParams.loAddr1)[0];
Properties props1 = (Properties) bgpProps.clone();
props1.setProperty("bgp.routerid", router1id); // no mask
props1.setProperty("bgp.group.0.peeras", bgpParams.remoteASNum);
props1.setProperty("bgp.group.0.session.0.peeras", bgpParams.remoteASNum);
props1.setProperty("bgp.group.0.session.0.peername", IPUtilsHelper.composedIPAddressToIPAddressAndMask(bgpParams.upRemoteAddr1)[0]); // no
// mask
props1.setProperty("bgp.group.1.peeras", bgpParams.clientASNumber);
props1.setProperty("bgp.group.1.session.0.peeras", bgpParams.clientASNumber);
props1.setProperty("bgp.group.1.session.0.peername", IPUtilsHelper.composedIPAddressToIPAddressAndMask(bgpParams.interAddr2)[0]); // no mask
// prefixes
props1.setProperty("prefixlist.2.prefixes.size", Integer.toString(bgp.getCustomerPrefixes().size() + 1));
props1.setProperty("prefixlist.2.prefix." + 0, IPUtilsHelper.composedIPAddressToIPAddressAndMask(bgpParams.loAddr1)[0] + "/32");
for (int i = 0; i < bgp.getCustomerPrefixes().size(); i++) {
props1.setProperty("prefixlist.2.prefix." + (i + 1), bgp.getCustomerPrefixes().get(i));
}
// policies
props1.setProperty("policy.0.rule.0.condition.0.filterlist.0.entries.size", Integer.toString(bgp.getCustomerPrefixes().size() + 1));
props1.setProperty("policy.0.rule.0.condition.0.filterlist.0.entry." + 0 + ".type", "routeFilterEntry");
props1.setProperty("policy.0.rule.0.condition.0.filterlist.0.entry." + 0 + ".address",
IPUtilsHelper.composedIPAddressToIPAddressAndMask(bgpParams.loAddr1)[0] + "/32");
props1.setProperty("policy.0.rule.0.condition.0.filterlist.0.entry." + 0 + ".option", "exact");
for (int i = 0; i < bgp.getCustomerPrefixes().size(); i++) {
props1.setProperty("policy.0.rule.0.condition.0.filterlist.0.entry." + (i + 1) + ".type", "routeFilterEntry");
props1.setProperty("policy.0.rule.0.condition.0.filterlist.0.entry." + (i + 1) + ".address", bgp.getCustomerPrefixes().get(i));
props1.setProperty("policy.0.rule.0.condition.0.filterlist.0.entry." + (i + 1) + ".option", "exact");
}
BGPModelFactory factory1 = new BGPModelFactory(props1);
bgp.setBgpConfigForMaster(factory1.createRouterWithBGP());
// FACTORY 2
String router2id = IPUtilsHelper.composedIPAddressToIPAddressAndMask(bgpParams.loAddr2)[0];
Properties props2 = (Properties) bgpProps.clone();
props2.setProperty("bgp.routerid", router2id); // no mask
props2.setProperty("bgp.group.0.peeras", bgpParams.remoteASNum);
props2.setProperty("bgp.group.0.session.0.peeras", bgpParams.remoteASNum);
props2.setProperty("bgp.group.0.session.0.peername", IPUtilsHelper.composedIPAddressToIPAddressAndMask(bgpParams.upRemoteAddr2)[0]); // no
// mask
props2.setProperty("bgp.group.1.peeras", bgpParams.clientASNumber);
props2.setProperty("bgp.group.1.session.0.peeras", bgpParams.clientASNumber);
props2.setProperty("bgp.group.1.session.0.peername", IPUtilsHelper.composedIPAddressToIPAddressAndMask(bgpParams.interAddr1)[0]); // no mask
// prefixes
props2.setProperty("prefixlist.2.prefixes.size", Integer.toString(bgp.getCustomerPrefixes().size() + 1));
props2.setProperty("prefixlist.2.prefix." + 0, IPUtilsHelper.composedIPAddressToIPAddressAndMask(bgpParams.loAddr2)[0] + "/32");
for (int i = 0; i < bgp.getCustomerPrefixes().size(); i++) {
props2.setProperty("prefixlist.2.prefix." + (i + 1), bgp.getCustomerPrefixes().get(i));
}
// policies
props2.setProperty("policy.0.rule.0.condition.0.filterlist.0.entries.size", Integer.toString(bgp.getCustomerPrefixes().size() + 1));
props2.setProperty("policy.0.rule.0.condition.0.filterlist.0.entry." + 0 + ".type", "routeFilterEntry");
props2.setProperty("policy.0.rule.0.condition.0.filterlist.0.entry." + 0 + ".address",
IPUtilsHelper.composedIPAddressToIPAddressAndMask(bgpParams.loAddr2)[0] + "/32");
props2.setProperty("policy.0.rule.0.condition.0.filterlist.0.entry." + 0 + ".option", "exact");
for (int i = 0; i < bgp.getCustomerPrefixes().size(); i++) {
props2.setProperty("policy.0.rule.0.condition.0.filterlist.0.entry." + (i + 1) + ".type", "routeFilterEntry");
props2.setProperty("policy.0.rule.0.condition.0.filterlist.0.entry." + (i + 1) + ".address", bgp.getCustomerPrefixes().get(i));
props2.setProperty("policy.0.rule.0.condition.0.filterlist.0.entry." + (i + 1) + ".option", "exact");
}
BGPModelFactory factory2 = new BGPModelFactory(props2);
bgp.setBgpConfigForBackup(factory2.createRouterWithBGP());
return bgp;
}
/**
* @param name
* @param templateName
* @param vlan
* @param ipAddress
* @return the interface
*/
private Interface getInterface(String name, String templateName, long vlan, String ipAddress, String physicalInterfaceName, int port) {
Interface iface = new Interface();
iface.setName(name);
iface.setTemplateName(templateName);
iface.setIpAddress(ipAddress);
iface.setVlan(vlan);
iface.setPhysicalInterfaceName(physicalInterfaceName);
iface.setPort(port);
return iface;
}
/**
* @param name
* @param templateName
* @param vlan
* @param ipAddress
* @return the interface
*/
private Interface updateInterface(Interface iface, String name, long vlan, String ipAddress, String physicalInterfaceName, int port) {
iface.setName(name);
iface.setIpAddress(ipAddress);
iface.setVlan(vlan);
iface.setPhysicalInterfaceName(physicalInterfaceName);
iface.setPort(port);
return iface;
}
/**
* @param id
* @param templateName
* @param type
* @param source
* @param sink
* @return
*/
private Link getLink(String id, String templateName, String type, Interface source, Interface sink) {
Link link = new Link();
link.setId(id);
link.setTemplateName(templateName);
link.setType(type);
link.setSource(source);
link.setSink(sink);
return link;
}
private void checkPhysicalAvailability(List<VCPENetworkElement> toBeChecked, VCPEManagerModel managerModel) throws VCPENetworkManagerException {
checkExistenceInPhysicalInsfrastructure(toBeChecked, managerModel.getPhysicalInfrastructure());
}
private void checkExistenceInPhysicalInsfrastructure(List<VCPENetworkElement> toBeChecked, VCPEPhysicalInfrastructure phyInfrastructure) {
List<VCPENetworkElement> availablePhysicalElements = phyInfrastructure.getAllElements();
for (Domain domain : filter(toBeChecked, Domain.class)) {
if (!availablePhysicalElements.contains(domain))
throw new VCPENetworkManagerException("Domain " + domain.getName() + " is not available in physical insfrastructure");
Domain phyInfrDomain = (Domain) availablePhysicalElements.get(availablePhysicalElements.indexOf(domain));
for (Interface iface : domain.getInterfaces()) {
if (!phyInfrDomain.getInterfaces().contains(iface))
throw new VCPENetworkManagerException(
"Interface " + iface.getName() + " for domain " + domain.getName() + " is not available in physical insfrastructure");
}
}
for (Router router : filter(toBeChecked, Router.class)) {
if (!availablePhysicalElements.contains(router))
throw new VCPENetworkManagerException("Router " + router.getName() + " is not available in physical insfrastructure");
Router phyInfrRouter = (Router) availablePhysicalElements.get(availablePhysicalElements.indexOf(router));
for (Interface iface : router.getInterfaces()) {
if (!phyInfrRouter.getInterfaces().contains(iface))
throw new VCPENetworkManagerException(
"Interface " + iface.getName() + " for router " + router.getName() + " is not available in physical insfrastructure");
}
}
for (Link link : filter(toBeChecked, Link.class)) {
if (!availablePhysicalElements.contains(link))
throw new VCPENetworkManagerException("Link " + link.getName() + " is not available in physical insfrastructure");
}
}
}
| false | true | private VCPENetworkModel generateLogicalElements() {
// LogicalRouter 1
Router vcpe1 = new LogicalRouter();
vcpe1.setTemplateName(VCPETemplate.VCPE1_ROUTER);
List<Interface> interfaces = new ArrayList<Interface>();
vcpe1.setInterfaces(interfaces);
Interface inter1 = new Interface();
Interface down1 = new Interface();
Interface up1 = new Interface();
Interface lo1 = new Interface();
interfaces.add(inter1);
interfaces.add(down1);
interfaces.add(up1);
interfaces.add(lo1);
inter1.setTemplateName(VCPETemplate.INTER1_INTERFACE_LOCAL);
down1.setTemplateName(VCPETemplate.DOWN1_INTERFACE_LOCAL);
up1.setTemplateName(VCPETemplate.UP1_INTERFACE_LOCAL);
lo1.setTemplateName(VCPETemplate.LO1_INTERFACE);
// LogicalRouter 2
Router vcpe2 = new LogicalRouter();
vcpe2.setTemplateName(VCPETemplate.VCPE2_ROUTER);
interfaces = new ArrayList<Interface>();
vcpe2.setInterfaces(interfaces);
Interface inter2 = new Interface();
Interface down2 = new Interface();
Interface up2 = new Interface();
Interface lo2 = new Interface();
interfaces.add(inter2);
interfaces.add(down2);
interfaces.add(up2);
interfaces.add(lo2);
inter2.setTemplateName(VCPETemplate.INTER2_INTERFACE_LOCAL);
down2.setTemplateName(VCPETemplate.DOWN2_INTERFACE_LOCAL);
up2.setTemplateName(VCPETemplate.UP2_INTERFACE_LOCAL);
lo2.setTemplateName(VCPETemplate.LO2_INTERFACE);
// BoD
// Notice these logical interfaces are not inside a BoD object (by now)
List<Interface> bodInterfaces = new ArrayList<Interface>();
Interface inter1other = new Interface();
Interface down1other = new Interface();
Interface inter2other = new Interface();
Interface down2other = new Interface();
Interface client1other = new Interface();
Interface client2other = new Interface();
Interface client1otherPhy = new Interface();
Interface client2otherPhy = new Interface();
bodInterfaces.add(inter1other);
bodInterfaces.add(down1other);
bodInterfaces.add(inter2other);
bodInterfaces.add(down2other);
bodInterfaces.add(client1other);
bodInterfaces.add(client2other);
bodInterfaces.add(client2otherPhy);
bodInterfaces.add(client2otherPhy);
inter1other.setTemplateName(VCPETemplate.INTER1_INTERFACE_AUTOBAHN);
down1other.setTemplateName(VCPETemplate.DOWN1_INTERFACE_AUTOBAHN);
inter2other.setTemplateName(VCPETemplate.INTER2_INTERFACE_AUTOBAHN);
down2other.setTemplateName(VCPETemplate.DOWN2_INTERFACE_AUTOBAHN);
client1other.setTemplateName(VCPETemplate.CLIENT1_INTERFACE_AUTOBAHN);
client2other.setTemplateName(VCPETemplate.CLIENT2_INTERFACE_AUTOBAHN);
client1other.setTemplateName(VCPETemplate.CLIENT1_PHY_INTERFACE_AUTOBAHN);
client2other.setTemplateName(VCPETemplate.CLIENT2_PHY_INTERFACE_AUTOBAHN);
// noc network interface
// Notice these logical interfaces are not inside a router object (by now)
Interface up1other = new Interface();
Interface up2other = new Interface();
up1other.setTemplateName(VCPETemplate.UP1_INTERFACE_PEER);
up2other.setTemplateName(VCPETemplate.UP2_INTERFACE_PEER);
// LINKS
// Inter links
Link linkInter1local = getLink(null, VCPETemplate.INTER1_LINK_LOCAL, VCPETemplate.LINK_TYPE_ETH, inter1, inter1other);
Link linkInter1other = getLink(null, VCPETemplate.INTER_LINK_AUTOBAHN, VCPETemplate.LINK_TYPE_AUTOBAHN, inter1other, inter2other);
Link linkInter2local = getLink(null, VCPETemplate.INTER2_LINK_LOCAL, VCPETemplate.LINK_TYPE_ETH, inter2, inter2other);
// Down links
Link linkDown1local = getLink(null, VCPETemplate.DOWN1_LINK_LOCAL, VCPETemplate.LINK_TYPE_ETH, down1, down1other);
Link linkDown1other = getLink(null, VCPETemplate.DOWN1_LINK_AUTOBAHN, VCPETemplate.LINK_TYPE_AUTOBAHN, down1other, client1other);
Link linkDown2local = getLink(null, VCPETemplate.DOWN2_LINK_LOCAL, VCPETemplate.LINK_TYPE_ETH, down2, down2other);
Link linkDown2other = getLink(null, VCPETemplate.DOWN2_LINK_AUTOBAHN, VCPETemplate.LINK_TYPE_AUTOBAHN, down2other, client2other);
// Up links
Link linkUp1 = getLink(null, VCPETemplate.UP1_LINK, VCPETemplate.LINK_TYPE_LT, up1, up1other);
Link linkUp2 = getLink(null, VCPETemplate.UP2_LINK, VCPETemplate.LINK_TYPE_LT, up2, up2other);
// Virtual links
Link linkInter = getLink(null, VCPETemplate.INTER_LINK, VCPETemplate.LINK_TYPE_VIRTUAL, inter1, inter2);
List<Link> subLinks = new ArrayList<Link>();
subLinks.add(linkInter1local);
subLinks.add(linkInter1other);
subLinks.add(linkInter2local);
linkInter.setImplementedBy(subLinks);
Link linkdown1 = getLink(null, VCPETemplate.DOWN1_LINK, VCPETemplate.LINK_TYPE_VIRTUAL, down1, client1other);
subLinks = new ArrayList<Link>();
subLinks.add(linkDown1local);
subLinks.add(linkDown1other);
linkdown1.setImplementedBy(subLinks);
Link linkdown2 = getLink(null, VCPETemplate.DOWN2_LINK, VCPETemplate.LINK_TYPE_VIRTUAL, down2, client2other);
subLinks.add(linkDown2local);
subLinks.add(linkDown2other);
linkdown2.setImplementedBy(subLinks);
List<VCPENetworkElement> elements = new ArrayList<VCPENetworkElement>();
elements.add(vcpe1);
elements.addAll(vcpe1.getInterfaces());
elements.add(vcpe2);
elements.addAll(vcpe2.getInterfaces());
elements.addAll(bodInterfaces);
elements.add(up1other);
elements.add(up2other);
elements.add(linkInter);
elements.addAll(linkInter.getImplementedBy());
elements.add(linkdown1);
elements.addAll(linkdown1.getImplementedBy());
elements.add(linkdown2);
elements.addAll(linkdown2.getImplementedBy());
elements.add(linkUp1);
elements.add(linkUp2);
// configure VRRP
VRRP vrrp = new VRRP();
vrrp.setMasterRouter(vcpe1);
vrrp.setMasterInterface(down1);
vrrp.setBackupRouter(vcpe2);
vrrp.setBackupInterface(down2);
VCPENetworkModel model = new VCPENetworkModel();
model.setElements(elements);
model.setTemplateType(getTemplateType());
model.setCreated(false);
model.setVrrp(vrrp);
model.setBgp(new BGP());
return model;
}
| private VCPENetworkModel generateLogicalElements() {
// LogicalRouter 1
Router vcpe1 = new LogicalRouter();
vcpe1.setTemplateName(VCPETemplate.VCPE1_ROUTER);
List<Interface> interfaces = new ArrayList<Interface>();
vcpe1.setInterfaces(interfaces);
Interface inter1 = new Interface();
Interface down1 = new Interface();
Interface up1 = new Interface();
Interface lo1 = new Interface();
interfaces.add(inter1);
interfaces.add(down1);
interfaces.add(up1);
interfaces.add(lo1);
inter1.setTemplateName(VCPETemplate.INTER1_INTERFACE_LOCAL);
down1.setTemplateName(VCPETemplate.DOWN1_INTERFACE_LOCAL);
up1.setTemplateName(VCPETemplate.UP1_INTERFACE_LOCAL);
lo1.setTemplateName(VCPETemplate.LO1_INTERFACE);
// LogicalRouter 2
Router vcpe2 = new LogicalRouter();
vcpe2.setTemplateName(VCPETemplate.VCPE2_ROUTER);
interfaces = new ArrayList<Interface>();
vcpe2.setInterfaces(interfaces);
Interface inter2 = new Interface();
Interface down2 = new Interface();
Interface up2 = new Interface();
Interface lo2 = new Interface();
interfaces.add(inter2);
interfaces.add(down2);
interfaces.add(up2);
interfaces.add(lo2);
inter2.setTemplateName(VCPETemplate.INTER2_INTERFACE_LOCAL);
down2.setTemplateName(VCPETemplate.DOWN2_INTERFACE_LOCAL);
up2.setTemplateName(VCPETemplate.UP2_INTERFACE_LOCAL);
lo2.setTemplateName(VCPETemplate.LO2_INTERFACE);
// BoD
// Notice these logical interfaces are not inside a BoD object (by now)
List<Interface> bodInterfaces = new ArrayList<Interface>();
Interface inter1other = new Interface();
Interface down1other = new Interface();
Interface inter2other = new Interface();
Interface down2other = new Interface();
Interface client1other = new Interface();
Interface client2other = new Interface();
Interface client1otherPhy = new Interface();
Interface client2otherPhy = new Interface();
bodInterfaces.add(inter1other);
bodInterfaces.add(down1other);
bodInterfaces.add(inter2other);
bodInterfaces.add(down2other);
bodInterfaces.add(client1other);
bodInterfaces.add(client2other);
bodInterfaces.add(client1otherPhy);
bodInterfaces.add(client2otherPhy);
inter1other.setTemplateName(VCPETemplate.INTER1_INTERFACE_AUTOBAHN);
down1other.setTemplateName(VCPETemplate.DOWN1_INTERFACE_AUTOBAHN);
inter2other.setTemplateName(VCPETemplate.INTER2_INTERFACE_AUTOBAHN);
down2other.setTemplateName(VCPETemplate.DOWN2_INTERFACE_AUTOBAHN);
client1other.setTemplateName(VCPETemplate.CLIENT1_INTERFACE_AUTOBAHN);
client2other.setTemplateName(VCPETemplate.CLIENT2_INTERFACE_AUTOBAHN);
client1otherPhy.setTemplateName(VCPETemplate.CLIENT1_PHY_INTERFACE_AUTOBAHN);
client2otherPhy.setTemplateName(VCPETemplate.CLIENT2_PHY_INTERFACE_AUTOBAHN);
// noc network interface
// Notice these logical interfaces are not inside a router object (by now)
Interface up1other = new Interface();
Interface up2other = new Interface();
up1other.setTemplateName(VCPETemplate.UP1_INTERFACE_PEER);
up2other.setTemplateName(VCPETemplate.UP2_INTERFACE_PEER);
// LINKS
// Inter links
Link linkInter1local = getLink(null, VCPETemplate.INTER1_LINK_LOCAL, VCPETemplate.LINK_TYPE_ETH, inter1, inter1other);
Link linkInter1other = getLink(null, VCPETemplate.INTER_LINK_AUTOBAHN, VCPETemplate.LINK_TYPE_AUTOBAHN, inter1other, inter2other);
Link linkInter2local = getLink(null, VCPETemplate.INTER2_LINK_LOCAL, VCPETemplate.LINK_TYPE_ETH, inter2, inter2other);
// Down links
Link linkDown1local = getLink(null, VCPETemplate.DOWN1_LINK_LOCAL, VCPETemplate.LINK_TYPE_ETH, down1, down1other);
Link linkDown1other = getLink(null, VCPETemplate.DOWN1_LINK_AUTOBAHN, VCPETemplate.LINK_TYPE_AUTOBAHN, down1other, client1other);
Link linkDown2local = getLink(null, VCPETemplate.DOWN2_LINK_LOCAL, VCPETemplate.LINK_TYPE_ETH, down2, down2other);
Link linkDown2other = getLink(null, VCPETemplate.DOWN2_LINK_AUTOBAHN, VCPETemplate.LINK_TYPE_AUTOBAHN, down2other, client2other);
// Up links
Link linkUp1 = getLink(null, VCPETemplate.UP1_LINK, VCPETemplate.LINK_TYPE_LT, up1, up1other);
Link linkUp2 = getLink(null, VCPETemplate.UP2_LINK, VCPETemplate.LINK_TYPE_LT, up2, up2other);
// Virtual links
Link linkInter = getLink(null, VCPETemplate.INTER_LINK, VCPETemplate.LINK_TYPE_VIRTUAL, inter1, inter2);
List<Link> subLinks = new ArrayList<Link>();
subLinks.add(linkInter1local);
subLinks.add(linkInter1other);
subLinks.add(linkInter2local);
linkInter.setImplementedBy(subLinks);
Link linkdown1 = getLink(null, VCPETemplate.DOWN1_LINK, VCPETemplate.LINK_TYPE_VIRTUAL, down1, client1other);
subLinks = new ArrayList<Link>();
subLinks.add(linkDown1local);
subLinks.add(linkDown1other);
linkdown1.setImplementedBy(subLinks);
Link linkdown2 = getLink(null, VCPETemplate.DOWN2_LINK, VCPETemplate.LINK_TYPE_VIRTUAL, down2, client2other);
subLinks.add(linkDown2local);
subLinks.add(linkDown2other);
linkdown2.setImplementedBy(subLinks);
List<VCPENetworkElement> elements = new ArrayList<VCPENetworkElement>();
elements.add(vcpe1);
elements.addAll(vcpe1.getInterfaces());
elements.add(vcpe2);
elements.addAll(vcpe2.getInterfaces());
elements.addAll(bodInterfaces);
elements.add(up1other);
elements.add(up2other);
elements.add(linkInter);
elements.addAll(linkInter.getImplementedBy());
elements.add(linkdown1);
elements.addAll(linkdown1.getImplementedBy());
elements.add(linkdown2);
elements.addAll(linkdown2.getImplementedBy());
elements.add(linkUp1);
elements.add(linkUp2);
// configure VRRP
VRRP vrrp = new VRRP();
vrrp.setMasterRouter(vcpe1);
vrrp.setMasterInterface(down1);
vrrp.setBackupRouter(vcpe2);
vrrp.setBackupInterface(down2);
VCPENetworkModel model = new VCPENetworkModel();
model.setElements(elements);
model.setTemplateType(getTemplateType());
model.setCreated(false);
model.setVrrp(vrrp);
model.setBgp(new BGP());
return model;
}
|
diff --git a/src/minecraft/basiccomponents/common/BCLoader.java b/src/minecraft/basiccomponents/common/BCLoader.java
index 4b3fe66..75d1dca 100644
--- a/src/minecraft/basiccomponents/common/BCLoader.java
+++ b/src/minecraft/basiccomponents/common/BCLoader.java
@@ -1,286 +1,286 @@
package basiccomponents.common;
import net.minecraft.block.Block;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.item.crafting.FurnaceRecipes;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.liquids.LiquidContainerData;
import net.minecraftforge.liquids.LiquidContainerRegistry;
import net.minecraftforge.liquids.LiquidStack;
import net.minecraftforge.oredict.OreDictionary;
import net.minecraftforge.oredict.ShapedOreRecipe;
import universalelectricity.core.UniversalElectricity;
import universalelectricity.prefab.RecipeHelper;
import universalelectricity.prefab.UETab;
import universalelectricity.prefab.UpdateNotifier;
import universalelectricity.prefab.network.ConnectionHandler;
import universalelectricity.prefab.network.PacketManager;
import universalelectricity.prefab.ore.OreGenReplaceStone;
import universalelectricity.prefab.ore.OreGenerator;
import basiccomponents.common.block.BlockBCOre;
import basiccomponents.common.block.BlockBasicMachine;
import basiccomponents.common.block.BlockCopperWire;
import basiccomponents.common.block.BlockOilFlowing;
import basiccomponents.common.block.BlockOilStill;
import basiccomponents.common.item.ItemBasic;
import basiccomponents.common.item.ItemBattery;
import basiccomponents.common.item.ItemBlockBCOre;
import basiccomponents.common.item.ItemBlockBasicMachine;
import basiccomponents.common.item.ItemBlockCopperWire;
import basiccomponents.common.item.ItemCircuit;
import basiccomponents.common.item.ItemOilBucket;
import basiccomponents.common.item.ItemWrench;
import cpw.mods.fml.common.ICraftingHandler;
import cpw.mods.fml.common.Mod;
import cpw.mods.fml.common.Mod.Init;
import cpw.mods.fml.common.Mod.Instance;
import cpw.mods.fml.common.Mod.PreInit;
import cpw.mods.fml.common.SidedProxy;
import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import cpw.mods.fml.common.network.NetworkMod;
import cpw.mods.fml.common.network.NetworkRegistry;
import cpw.mods.fml.common.registry.GameRegistry;
import cpw.mods.fml.common.registry.LanguageRegistry;
@Mod(modid = BCLoader.CHANNEL, name = BCLoader.NAME, version = UniversalElectricity.VERSION)
@NetworkMod(channels = BCLoader.CHANNEL, clientSideRequired = true, serverSideRequired = false, connectionHandler = ConnectionHandler.class, packetHandler = PacketManager.class)
public class BCLoader implements ICraftingHandler
{
public static final String NAME = "Basic Components";
public static final String CHANNEL = "BasicComponents";
public static final String FILE_PATH = "/basiccomponents/";
public static final String LANGUAGE_PATH = FILE_PATH + "language/";
public static final String TEXTURE_PATH = FILE_PATH + "textures/";
public static final String BLOCK_TEXTURE_FILE = TEXTURE_PATH + "blocks.png";
public static final String ITEM_TEXTURE_FILE = TEXTURE_PATH + "items.png";
private static final String[] LANGUAGES_SUPPORTED = new String[] { "en_US", "zh_CN", "es_ES", "it_IT" };
@Instance("BasicComponents")
public static BCLoader instance;
@SidedProxy(clientSide = "basiccomponents.client.ClientProxy", serverSide = "basiccomponents.common.CommonProxy")
public static CommonProxy proxy;
@PreInit
public void preInit(FMLPreInitializationEvent event)
{
UniversalElectricity.register(this, UniversalElectricity.MAJOR_VERSION, UniversalElectricity.MINOR_VERSION, UniversalElectricity.REVISION_VERSION, false);
NetworkRegistry.instance().registerGuiHandler(this, this.proxy);
/**
* Define the items and blocks.
*/
UniversalElectricity.CONFIGURATION.load();
BasicComponents.blockBasicOre = new BlockBCOre(UniversalElectricity.CONFIGURATION.getBlock("Copper and Tin Ores", BasicComponents.BLOCK_ID_PREFIX + 0).getInt());
BasicComponents.blockCopperWire = new BlockCopperWire(UniversalElectricity.CONFIGURATION.getBlock("Copper_Wire", BasicComponents.BLOCK_ID_PREFIX + 1).getInt());
BasicComponents.oilMoving = new BlockOilFlowing(UniversalElectricity.CONFIGURATION.getBlock("Oil_Flowing", BasicComponents.BLOCK_ID_PREFIX + 2).getInt());
BasicComponents.oilStill = new BlockOilStill(UniversalElectricity.CONFIGURATION.getBlock("Oil_Still", BasicComponents.BLOCK_ID_PREFIX + 3).getInt());
BasicComponents.blockMachine = new BlockBasicMachine(UniversalElectricity.CONFIGURATION.getBlock("Basic Machine", BasicComponents.BLOCK_ID_PREFIX + 4).getInt(), 0);
BasicComponents.itemBattery = new ItemBattery(UniversalElectricity.CONFIGURATION.getItem("Battery", BasicComponents.ITEM_ID_PREFIX + 1).getInt(), 0);
BasicComponents.itemWrench = new ItemWrench(UniversalElectricity.CONFIGURATION.getItem("Universal Wrench", BasicComponents.ITEM_ID_PREFIX + 2).getInt(), 20);
BasicComponents.itemCircuit = new ItemCircuit(UniversalElectricity.CONFIGURATION.getItem("Circuit", BasicComponents.ITEM_ID_PREFIX + 3).getInt(), 16);
BasicComponents.itemCopperIngot = new ItemBasic("ingotCopper", UniversalElectricity.CONFIGURATION.getItem("Copper Ingot", BasicComponents.ITEM_ID_PREFIX + 4).getInt(), 1);
BasicComponents.itemTinIngot = new ItemBasic("ingotTin", UniversalElectricity.CONFIGURATION.getItem("Tin Ingot", BasicComponents.ITEM_ID_PREFIX + 5).getInt(), 2);
BasicComponents.itemBronzeIngot = new ItemBasic("ingotBronze", UniversalElectricity.CONFIGURATION.getItem("Bronze Ingot", BasicComponents.ITEM_ID_PREFIX + 6).getInt(), 7);
BasicComponents.itemSteelIngot = new ItemBasic("ingotSteel", UniversalElectricity.CONFIGURATION.getItem("Steel Ingot", BasicComponents.ITEM_ID_PREFIX + 7).getInt(), 3);
BasicComponents.itemBronzeDust = new ItemBasic("dustBronze", UniversalElectricity.CONFIGURATION.getItem("Bronze Dust", BasicComponents.ITEM_ID_PREFIX + 8).getInt(), 6);
BasicComponents.itemSteelDust = new ItemBasic("dustSteel", UniversalElectricity.CONFIGURATION.getItem("Steel Dust", BasicComponents.ITEM_ID_PREFIX + 9).getInt(), 5);
BasicComponents.itemCopperPlate = new ItemBasic("plateCopper", UniversalElectricity.CONFIGURATION.getItem("Copper Plate", BasicComponents.ITEM_ID_PREFIX + 10).getInt(), 10);
BasicComponents.itemTinPlate = new ItemBasic("plateTin", UniversalElectricity.CONFIGURATION.getItem("Tin Plate", BasicComponents.ITEM_ID_PREFIX + 11).getInt(), 11);
BasicComponents.itemBronzePlate = new ItemBasic("plateBronze", UniversalElectricity.CONFIGURATION.getItem("Bronze Plate", BasicComponents.ITEM_ID_PREFIX + 12).getInt(), 8);
BasicComponents.itemSteelPlate = new ItemBasic("plateSteel", UniversalElectricity.CONFIGURATION.getItem("Steel Plate", BasicComponents.ITEM_ID_PREFIX + 13).getInt(), 9);
BasicComponents.itemMotor = new ItemBasic("motor", UniversalElectricity.CONFIGURATION.getItem("Motor", BasicComponents.ITEM_ID_PREFIX + 14).getInt(), 12);
BasicComponents.itemOilBucket = new ItemOilBucket(UniversalElectricity.CONFIGURATION.getItem("Oil Bucket", BasicComponents.ITEM_ID_PREFIX + 15).getInt(), 4);
BasicComponents.coalGenerator = ((BlockBasicMachine) BasicComponents.blockMachine).getCoalGenerator();
BasicComponents.batteryBox = ((BlockBasicMachine) BasicComponents.blockMachine).getBatteryBox();
BasicComponents.electricFurnace = ((BlockBasicMachine) BasicComponents.blockMachine).getElectricFurnace();
BasicComponents.copperOreGeneration = new OreGenReplaceStone("Copper Ore", "oreCopper", new ItemStack(BasicComponents.blockBasicOre, 1, 0), 0, 50, 40, 4).enable();
BasicComponents.tinOreGeneration = new OreGenReplaceStone("Tin Ore", "oreTin", new ItemStack(BasicComponents.blockBasicOre, 1, 1), 0, 50, 36, 3).enable();
UniversalElectricity.CONFIGURATION.save();
/**
* @author Cammygames
*/
LiquidContainerRegistry.registerLiquid(new LiquidContainerData(new LiquidStack(BasicComponents.oilStill, LiquidContainerRegistry.BUCKET_VOLUME), new ItemStack(BasicComponents.itemOilBucket), new ItemStack(Item.bucketEmpty)));
MinecraftForge.EVENT_BUS.register(BasicComponents.itemOilBucket);
// Register Blocks
GameRegistry.registerBlock(BasicComponents.blockBasicOre, ItemBlockBCOre.class, "Ore");
GameRegistry.registerBlock(BasicComponents.blockMachine, ItemBlockBasicMachine.class, "Basic Machine");
GameRegistry.registerBlock(BasicComponents.blockCopperWire, ItemBlockCopperWire.class, "Copper Wire");
GameRegistry.registerBlock(BasicComponents.oilMoving, "Oil Moving");
GameRegistry.registerBlock(BasicComponents.oilStill, "OilS till");
GameRegistry.registerCraftingHandler(this);
/**
* Registering all Basic Component items into the Forge Ore Dictionary.
*/
OreDictionary.registerOre("copperWire", BasicComponents.blockCopperWire);
OreDictionary.registerOre("coalGenerator", BasicComponents.coalGenerator);
OreDictionary.registerOre("batteryBox", BasicComponents.batteryBox);
OreDictionary.registerOre("electricFurnace", BasicComponents.electricFurnace);
OreDictionary.registerOre("battery", BasicComponents.itemBattery);
OreDictionary.registerOre("wrench", BasicComponents.itemWrench);
OreDictionary.registerOre("motor", BasicComponents.itemMotor);
OreDictionary.registerOre("basicCircuit", new ItemStack(BasicComponents.itemCircuit, 1, 0));
OreDictionary.registerOre("advancedCircuit", new ItemStack(BasicComponents.itemCircuit, 1, 1));
OreDictionary.registerOre("eliteCircuit", new ItemStack(BasicComponents.itemCircuit, 1, 2));
OreDictionary.registerOre("oilMoving", BasicComponents.oilMoving);
OreDictionary.registerOre("oilStill", BasicComponents.oilStill);
OreDictionary.registerOre("oilBucket", BasicComponents.itemOilBucket);
OreDictionary.registerOre("ingotCopper", BasicComponents.itemCopperIngot);
OreDictionary.registerOre("ingotTin", BasicComponents.itemTinIngot);
OreDictionary.registerOre("ingotBronze", BasicComponents.itemBronzeIngot);
OreDictionary.registerOre("ingotSteel", BasicComponents.itemSteelIngot);
OreDictionary.registerOre("dustBronze", BasicComponents.itemBronzeDust);
OreDictionary.registerOre("dustSteel", BasicComponents.itemSteelDust);
OreDictionary.registerOre("plateCopper", BasicComponents.itemCopperPlate);
OreDictionary.registerOre("plateTin", BasicComponents.itemTinPlate);
OreDictionary.registerOre("plateBronze", BasicComponents.itemBronzePlate);
OreDictionary.registerOre("plateSteel", BasicComponents.itemSteelPlate);
UETab.setItemStack(BasicComponents.batteryBox);
UpdateNotifier.INSTANCE.checkUpdate(NAME, UniversalElectricity.VERSION, "http://www.calclavia.com/downloads/ue/recommendedversion.txt");
proxy.preInit();
}
@Init
public void load(FMLInitializationEvent evt)
{
proxy.init();
int languages = 0;
/**
* Load all languages.
*/
for (String language : LANGUAGES_SUPPORTED)
{
LanguageRegistry.instance().loadLocalization(LANGUAGE_PATH + language + ".properties", language, false);
if (LanguageRegistry.instance().getStringLocalization("children", language) != "")
{
try
{
String[] children = LanguageRegistry.instance().getStringLocalization("children", language).split(",");
for (String child : children)
{
if (child != "" || child != null)
{
LanguageRegistry.instance().loadLocalization(LANGUAGE_PATH + language + ".properties", child, false);
languages++;
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
languages++;
}
System.out.println("Basic Components: Loaded " + languages + " languages.");
OreGenerator.addOre(BasicComponents.copperOreGeneration);
OreGenerator.addOre(BasicComponents.tinOreGeneration);
// Recipes
// Oil Bucket
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(BasicComponents.itemOilBucket), new Object[] { "CCC", "CBC", "CCC", 'B', Item.bucketWater, 'C', Item.coal }));
// Motor
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(BasicComponents.itemMotor), new Object[] { "@!@", "!#!", "@!@", '!', "ingotSteel", '#', Item.ingotIron, '@', BasicComponents.blockCopperWire }));
// Wrench
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(BasicComponents.itemWrench), new Object[] { " S ", " DS", "S ", 'S', "ingotSteel", 'D', Item.diamond }));
// Battery Box
GameRegistry.addRecipe(new ShapedOreRecipe(BasicComponents.batteryBox, new Object[] { "?!?", "###", "?!?", '#', BasicComponents.blockCopperWire, '!', BasicComponents.itemSteelPlate, '?', BasicComponents.itemBattery.getUncharged() }));
GameRegistry.addSmelting(BasicComponents.batteryBox.itemID, new ItemStack(BasicComponents.itemSteelDust, 6), 0f);
// Coal Generator
GameRegistry.addRecipe(new ShapedOreRecipe(BasicComponents.coalGenerator, new Object[] { "SCS", "FMF", "BBB", 'B', "ingotBronze", 'S', BasicComponents.itemSteelPlate, 'C', BasicComponents.blockCopperWire, 'M', BasicComponents.itemMotor, 'F', Block.stoneOvenIdle }));
GameRegistry.addSmelting(BasicComponents.coalGenerator.itemID, new ItemStack(BasicComponents.itemSteelDust, 6), 0f);
// Electric Furnace
GameRegistry.addRecipe(new ShapedOreRecipe(BasicComponents.electricFurnace, new Object[] { "SSS", "SCS", "SMS", 'S', "ingotSteel", 'C', BasicComponents.itemCircuit, 'M', BasicComponents.itemMotor }));
GameRegistry.addSmelting(BasicComponents.electricFurnace.itemID, new ItemStack(BasicComponents.itemSteelDust, 6), 0f);
// Copper
FurnaceRecipes.smelting().addSmelting(BasicComponents.blockBasicOre.blockID, 0, new ItemStack(BasicComponents.itemCopperIngot), 0.7f);
// Copper Wire
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(BasicComponents.blockCopperWire, 6), new Object[] { "!!!", "@@@", "!!!", '!', Item.leather, '@', "ingotCopper" }));
// Tin
FurnaceRecipes.smelting().addSmelting(BasicComponents.blockBasicOre.blockID, 1, new ItemStack(BasicComponents.itemTinIngot), 0.7f);
// Battery
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(BasicComponents.itemBattery), new Object[] { " T ", "TRT", "TCT", 'T', "ingotTin", 'R', Item.redstone, 'C', Item.coal }));
// Steel
- RecipeHelper.addRecipe(new ShapedOreRecipe(new ItemStack(BasicComponents.itemSteelDust), new Object[] { " C ", "CIC", " C ", 'C', new ItemStack(Item.coal, 1, 1), 'I', Item.ingotIron }), "Steel Dust", UniversalElectricity.CONFIGURATION, true);
- RecipeHelper.addRecipe(new ShapedOreRecipe(new ItemStack(BasicComponents.itemSteelDust), new Object[] { " C ", "CIC", " C ", 'C', new ItemStack(Item.coal, 1, 0), 'I', Item.ingotIron }), "Steel Dust", UniversalElectricity.CONFIGURATION, true);
+ RecipeHelper.addRecipe(new ShapedOreRecipe(new ItemStack(BasicComponents.itemSteelDust), new Object[] { "C C", " I ", "C C", 'C', new ItemStack(Item.coal, 1, 1), 'I', Item.ingotIron }), "Steel Dust", UniversalElectricity.CONFIGURATION, true);
+ RecipeHelper.addRecipe(new ShapedOreRecipe(new ItemStack(BasicComponents.itemSteelDust), new Object[] { "C C", " I ", "C C", 'C', new ItemStack(Item.coal, 1, 0), 'I', Item.ingotIron }), "Steel Dust", UniversalElectricity.CONFIGURATION, true);
GameRegistry.addSmelting(BasicComponents.itemSteelDust.shiftedIndex, new ItemStack(BasicComponents.itemSteelIngot), 0.8f);
GameRegistry.addSmelting(BasicComponents.itemSteelPlate.shiftedIndex, new ItemStack(BasicComponents.itemSteelDust, 3), 0f);
// Bronze
RecipeHelper.addRecipe(new ShapedOreRecipe(new ItemStack(BasicComponents.itemBronzeDust), new Object[] { "!#!", '!', "ingotCopper", '#', "ingotTin" }), "Bronze Dust", UniversalElectricity.CONFIGURATION, true);
GameRegistry.addSmelting(BasicComponents.itemBronzeDust.shiftedIndex, new ItemStack(BasicComponents.itemBronzeIngot), 0.6f);
GameRegistry.addSmelting(BasicComponents.itemBronzePlate.shiftedIndex, new ItemStack(BasicComponents.itemBronzeDust, 3), 0f);
// Plates
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(BasicComponents.itemCopperPlate), new Object[] { "!!", "!!", '!', "ingotCopper" }));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(BasicComponents.itemTinPlate), new Object[] { "!!", "!!", '!', "ingotTin" }));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(BasicComponents.itemSteelPlate), new Object[] { "!!", "!!", '!', "ingotSteel" }));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(BasicComponents.itemBronzePlate), new Object[] { "!!", "!!", '!', "ingotBronze" }));
// Circuit
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(BasicComponents.itemCircuit, 1, 0), new Object[] { "!#!", "#@#", "!#!", '@', BasicComponents.itemBronzePlate, '#', Item.redstone, '!', BasicComponents.blockCopperWire }));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(BasicComponents.itemCircuit, 1, 0), new Object[] { "!#!", "#@#", "!#!", '@', BasicComponents.itemSteelPlate, '#', Item.redstone, '!', BasicComponents.blockCopperWire }));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(BasicComponents.itemCircuit, 1, 1), new Object[] { "@@@", "#?#", "@@@", '@', Item.redstone, '?', Item.diamond, '#', BasicComponents.itemCircuit }));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(BasicComponents.itemCircuit, 1, 2), new Object[] { "@@@", "?#?", "@@@", '@', Item.ingotGold, '?', new ItemStack(BasicComponents.itemCircuit, 1, 1), '#', Block.blockLapis }));
}
@Override
public void onCrafting(EntityPlayer player, ItemStack item, IInventory craftMatrix)
{
if (item.itemID == BasicComponents.itemOilBucket.shiftedIndex)
{
for (int i = 0; i < craftMatrix.getSizeInventory(); i++)
{
if (craftMatrix.getStackInSlot(i) != null)
{
if (craftMatrix.getStackInSlot(i).itemID == Item.bucketWater.shiftedIndex)
{
craftMatrix.setInventorySlotContents(i, null);
return;
}
}
}
}
}
@Override
public void onSmelting(EntityPlayer player, ItemStack item)
{
}
}
| true | true | public void load(FMLInitializationEvent evt)
{
proxy.init();
int languages = 0;
/**
* Load all languages.
*/
for (String language : LANGUAGES_SUPPORTED)
{
LanguageRegistry.instance().loadLocalization(LANGUAGE_PATH + language + ".properties", language, false);
if (LanguageRegistry.instance().getStringLocalization("children", language) != "")
{
try
{
String[] children = LanguageRegistry.instance().getStringLocalization("children", language).split(",");
for (String child : children)
{
if (child != "" || child != null)
{
LanguageRegistry.instance().loadLocalization(LANGUAGE_PATH + language + ".properties", child, false);
languages++;
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
languages++;
}
System.out.println("Basic Components: Loaded " + languages + " languages.");
OreGenerator.addOre(BasicComponents.copperOreGeneration);
OreGenerator.addOre(BasicComponents.tinOreGeneration);
// Recipes
// Oil Bucket
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(BasicComponents.itemOilBucket), new Object[] { "CCC", "CBC", "CCC", 'B', Item.bucketWater, 'C', Item.coal }));
// Motor
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(BasicComponents.itemMotor), new Object[] { "@!@", "!#!", "@!@", '!', "ingotSteel", '#', Item.ingotIron, '@', BasicComponents.blockCopperWire }));
// Wrench
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(BasicComponents.itemWrench), new Object[] { " S ", " DS", "S ", 'S', "ingotSteel", 'D', Item.diamond }));
// Battery Box
GameRegistry.addRecipe(new ShapedOreRecipe(BasicComponents.batteryBox, new Object[] { "?!?", "###", "?!?", '#', BasicComponents.blockCopperWire, '!', BasicComponents.itemSteelPlate, '?', BasicComponents.itemBattery.getUncharged() }));
GameRegistry.addSmelting(BasicComponents.batteryBox.itemID, new ItemStack(BasicComponents.itemSteelDust, 6), 0f);
// Coal Generator
GameRegistry.addRecipe(new ShapedOreRecipe(BasicComponents.coalGenerator, new Object[] { "SCS", "FMF", "BBB", 'B', "ingotBronze", 'S', BasicComponents.itemSteelPlate, 'C', BasicComponents.blockCopperWire, 'M', BasicComponents.itemMotor, 'F', Block.stoneOvenIdle }));
GameRegistry.addSmelting(BasicComponents.coalGenerator.itemID, new ItemStack(BasicComponents.itemSteelDust, 6), 0f);
// Electric Furnace
GameRegistry.addRecipe(new ShapedOreRecipe(BasicComponents.electricFurnace, new Object[] { "SSS", "SCS", "SMS", 'S', "ingotSteel", 'C', BasicComponents.itemCircuit, 'M', BasicComponents.itemMotor }));
GameRegistry.addSmelting(BasicComponents.electricFurnace.itemID, new ItemStack(BasicComponents.itemSteelDust, 6), 0f);
// Copper
FurnaceRecipes.smelting().addSmelting(BasicComponents.blockBasicOre.blockID, 0, new ItemStack(BasicComponents.itemCopperIngot), 0.7f);
// Copper Wire
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(BasicComponents.blockCopperWire, 6), new Object[] { "!!!", "@@@", "!!!", '!', Item.leather, '@', "ingotCopper" }));
// Tin
FurnaceRecipes.smelting().addSmelting(BasicComponents.blockBasicOre.blockID, 1, new ItemStack(BasicComponents.itemTinIngot), 0.7f);
// Battery
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(BasicComponents.itemBattery), new Object[] { " T ", "TRT", "TCT", 'T', "ingotTin", 'R', Item.redstone, 'C', Item.coal }));
// Steel
RecipeHelper.addRecipe(new ShapedOreRecipe(new ItemStack(BasicComponents.itemSteelDust), new Object[] { " C ", "CIC", " C ", 'C', new ItemStack(Item.coal, 1, 1), 'I', Item.ingotIron }), "Steel Dust", UniversalElectricity.CONFIGURATION, true);
RecipeHelper.addRecipe(new ShapedOreRecipe(new ItemStack(BasicComponents.itemSteelDust), new Object[] { " C ", "CIC", " C ", 'C', new ItemStack(Item.coal, 1, 0), 'I', Item.ingotIron }), "Steel Dust", UniversalElectricity.CONFIGURATION, true);
GameRegistry.addSmelting(BasicComponents.itemSteelDust.shiftedIndex, new ItemStack(BasicComponents.itemSteelIngot), 0.8f);
GameRegistry.addSmelting(BasicComponents.itemSteelPlate.shiftedIndex, new ItemStack(BasicComponents.itemSteelDust, 3), 0f);
// Bronze
RecipeHelper.addRecipe(new ShapedOreRecipe(new ItemStack(BasicComponents.itemBronzeDust), new Object[] { "!#!", '!', "ingotCopper", '#', "ingotTin" }), "Bronze Dust", UniversalElectricity.CONFIGURATION, true);
GameRegistry.addSmelting(BasicComponents.itemBronzeDust.shiftedIndex, new ItemStack(BasicComponents.itemBronzeIngot), 0.6f);
GameRegistry.addSmelting(BasicComponents.itemBronzePlate.shiftedIndex, new ItemStack(BasicComponents.itemBronzeDust, 3), 0f);
// Plates
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(BasicComponents.itemCopperPlate), new Object[] { "!!", "!!", '!', "ingotCopper" }));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(BasicComponents.itemTinPlate), new Object[] { "!!", "!!", '!', "ingotTin" }));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(BasicComponents.itemSteelPlate), new Object[] { "!!", "!!", '!', "ingotSteel" }));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(BasicComponents.itemBronzePlate), new Object[] { "!!", "!!", '!', "ingotBronze" }));
// Circuit
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(BasicComponents.itemCircuit, 1, 0), new Object[] { "!#!", "#@#", "!#!", '@', BasicComponents.itemBronzePlate, '#', Item.redstone, '!', BasicComponents.blockCopperWire }));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(BasicComponents.itemCircuit, 1, 0), new Object[] { "!#!", "#@#", "!#!", '@', BasicComponents.itemSteelPlate, '#', Item.redstone, '!', BasicComponents.blockCopperWire }));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(BasicComponents.itemCircuit, 1, 1), new Object[] { "@@@", "#?#", "@@@", '@', Item.redstone, '?', Item.diamond, '#', BasicComponents.itemCircuit }));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(BasicComponents.itemCircuit, 1, 2), new Object[] { "@@@", "?#?", "@@@", '@', Item.ingotGold, '?', new ItemStack(BasicComponents.itemCircuit, 1, 1), '#', Block.blockLapis }));
}
@Override
public void onCrafting(EntityPlayer player, ItemStack item, IInventory craftMatrix)
{
if (item.itemID == BasicComponents.itemOilBucket.shiftedIndex)
{
for (int i = 0; i < craftMatrix.getSizeInventory(); i++)
{
if (craftMatrix.getStackInSlot(i) != null)
{
if (craftMatrix.getStackInSlot(i).itemID == Item.bucketWater.shiftedIndex)
{
craftMatrix.setInventorySlotContents(i, null);
return;
}
}
}
}
}
@Override
public void onSmelting(EntityPlayer player, ItemStack item)
{
}
}
| public void load(FMLInitializationEvent evt)
{
proxy.init();
int languages = 0;
/**
* Load all languages.
*/
for (String language : LANGUAGES_SUPPORTED)
{
LanguageRegistry.instance().loadLocalization(LANGUAGE_PATH + language + ".properties", language, false);
if (LanguageRegistry.instance().getStringLocalization("children", language) != "")
{
try
{
String[] children = LanguageRegistry.instance().getStringLocalization("children", language).split(",");
for (String child : children)
{
if (child != "" || child != null)
{
LanguageRegistry.instance().loadLocalization(LANGUAGE_PATH + language + ".properties", child, false);
languages++;
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
languages++;
}
System.out.println("Basic Components: Loaded " + languages + " languages.");
OreGenerator.addOre(BasicComponents.copperOreGeneration);
OreGenerator.addOre(BasicComponents.tinOreGeneration);
// Recipes
// Oil Bucket
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(BasicComponents.itemOilBucket), new Object[] { "CCC", "CBC", "CCC", 'B', Item.bucketWater, 'C', Item.coal }));
// Motor
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(BasicComponents.itemMotor), new Object[] { "@!@", "!#!", "@!@", '!', "ingotSteel", '#', Item.ingotIron, '@', BasicComponents.blockCopperWire }));
// Wrench
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(BasicComponents.itemWrench), new Object[] { " S ", " DS", "S ", 'S', "ingotSteel", 'D', Item.diamond }));
// Battery Box
GameRegistry.addRecipe(new ShapedOreRecipe(BasicComponents.batteryBox, new Object[] { "?!?", "###", "?!?", '#', BasicComponents.blockCopperWire, '!', BasicComponents.itemSteelPlate, '?', BasicComponents.itemBattery.getUncharged() }));
GameRegistry.addSmelting(BasicComponents.batteryBox.itemID, new ItemStack(BasicComponents.itemSteelDust, 6), 0f);
// Coal Generator
GameRegistry.addRecipe(new ShapedOreRecipe(BasicComponents.coalGenerator, new Object[] { "SCS", "FMF", "BBB", 'B', "ingotBronze", 'S', BasicComponents.itemSteelPlate, 'C', BasicComponents.blockCopperWire, 'M', BasicComponents.itemMotor, 'F', Block.stoneOvenIdle }));
GameRegistry.addSmelting(BasicComponents.coalGenerator.itemID, new ItemStack(BasicComponents.itemSteelDust, 6), 0f);
// Electric Furnace
GameRegistry.addRecipe(new ShapedOreRecipe(BasicComponents.electricFurnace, new Object[] { "SSS", "SCS", "SMS", 'S', "ingotSteel", 'C', BasicComponents.itemCircuit, 'M', BasicComponents.itemMotor }));
GameRegistry.addSmelting(BasicComponents.electricFurnace.itemID, new ItemStack(BasicComponents.itemSteelDust, 6), 0f);
// Copper
FurnaceRecipes.smelting().addSmelting(BasicComponents.blockBasicOre.blockID, 0, new ItemStack(BasicComponents.itemCopperIngot), 0.7f);
// Copper Wire
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(BasicComponents.blockCopperWire, 6), new Object[] { "!!!", "@@@", "!!!", '!', Item.leather, '@', "ingotCopper" }));
// Tin
FurnaceRecipes.smelting().addSmelting(BasicComponents.blockBasicOre.blockID, 1, new ItemStack(BasicComponents.itemTinIngot), 0.7f);
// Battery
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(BasicComponents.itemBattery), new Object[] { " T ", "TRT", "TCT", 'T', "ingotTin", 'R', Item.redstone, 'C', Item.coal }));
// Steel
RecipeHelper.addRecipe(new ShapedOreRecipe(new ItemStack(BasicComponents.itemSteelDust), new Object[] { "C C", " I ", "C C", 'C', new ItemStack(Item.coal, 1, 1), 'I', Item.ingotIron }), "Steel Dust", UniversalElectricity.CONFIGURATION, true);
RecipeHelper.addRecipe(new ShapedOreRecipe(new ItemStack(BasicComponents.itemSteelDust), new Object[] { "C C", " I ", "C C", 'C', new ItemStack(Item.coal, 1, 0), 'I', Item.ingotIron }), "Steel Dust", UniversalElectricity.CONFIGURATION, true);
GameRegistry.addSmelting(BasicComponents.itemSteelDust.shiftedIndex, new ItemStack(BasicComponents.itemSteelIngot), 0.8f);
GameRegistry.addSmelting(BasicComponents.itemSteelPlate.shiftedIndex, new ItemStack(BasicComponents.itemSteelDust, 3), 0f);
// Bronze
RecipeHelper.addRecipe(new ShapedOreRecipe(new ItemStack(BasicComponents.itemBronzeDust), new Object[] { "!#!", '!', "ingotCopper", '#', "ingotTin" }), "Bronze Dust", UniversalElectricity.CONFIGURATION, true);
GameRegistry.addSmelting(BasicComponents.itemBronzeDust.shiftedIndex, new ItemStack(BasicComponents.itemBronzeIngot), 0.6f);
GameRegistry.addSmelting(BasicComponents.itemBronzePlate.shiftedIndex, new ItemStack(BasicComponents.itemBronzeDust, 3), 0f);
// Plates
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(BasicComponents.itemCopperPlate), new Object[] { "!!", "!!", '!', "ingotCopper" }));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(BasicComponents.itemTinPlate), new Object[] { "!!", "!!", '!', "ingotTin" }));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(BasicComponents.itemSteelPlate), new Object[] { "!!", "!!", '!', "ingotSteel" }));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(BasicComponents.itemBronzePlate), new Object[] { "!!", "!!", '!', "ingotBronze" }));
// Circuit
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(BasicComponents.itemCircuit, 1, 0), new Object[] { "!#!", "#@#", "!#!", '@', BasicComponents.itemBronzePlate, '#', Item.redstone, '!', BasicComponents.blockCopperWire }));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(BasicComponents.itemCircuit, 1, 0), new Object[] { "!#!", "#@#", "!#!", '@', BasicComponents.itemSteelPlate, '#', Item.redstone, '!', BasicComponents.blockCopperWire }));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(BasicComponents.itemCircuit, 1, 1), new Object[] { "@@@", "#?#", "@@@", '@', Item.redstone, '?', Item.diamond, '#', BasicComponents.itemCircuit }));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(BasicComponents.itemCircuit, 1, 2), new Object[] { "@@@", "?#?", "@@@", '@', Item.ingotGold, '?', new ItemStack(BasicComponents.itemCircuit, 1, 1), '#', Block.blockLapis }));
}
@Override
public void onCrafting(EntityPlayer player, ItemStack item, IInventory craftMatrix)
{
if (item.itemID == BasicComponents.itemOilBucket.shiftedIndex)
{
for (int i = 0; i < craftMatrix.getSizeInventory(); i++)
{
if (craftMatrix.getStackInSlot(i) != null)
{
if (craftMatrix.getStackInSlot(i).itemID == Item.bucketWater.shiftedIndex)
{
craftMatrix.setInventorySlotContents(i, null);
return;
}
}
}
}
}
@Override
public void onSmelting(EntityPlayer player, ItemStack item)
{
}
}
|
diff --git a/src/com/untamedears/bottleO/EventListener.java b/src/com/untamedears/bottleO/EventListener.java
index 04bc76b..066b02a 100644
--- a/src/com/untamedears/bottleO/EventListener.java
+++ b/src/com/untamedears/bottleO/EventListener.java
@@ -1,297 +1,297 @@
package com.untamedears.bottleO;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Random;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.GameMode;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.enchantment.EnchantItemEvent;
import org.bukkit.event.enchantment.PrepareItemEnchantEvent;
import org.bukkit.event.entity.ExpBottleEvent;
import org.bukkit.event.player.PlayerExpChangeEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerLoginEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.PlayerInventory;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
public class EventListener implements Listener {
protected static int XP_PER_BOTTLE = 25;
protected static long WAIT_TIME_MILLIS = 5000;
protected static int MAX_BOOKSHELVES = 30;
protected static int BOTTLES_PER_EMERALD = 9;
protected static int EMERALDS_PER_BLOCK = 9;
protected static Random rand;
//cool-down timers
protected static HashMap<String,Long> playerWaitHash = new HashMap<String,Long>(100);
protected bottleO plugin;
public EventListener(bottleO plugin) {
this.plugin = plugin;
}
//calculate legacy total xp
private int getLegacyTotalXP(int levels, float exp) {
float result = (float) ((1.75*levels*levels) + (5*levels));
result = Math.round(result);
float remainder = Math.round(Math.round(getLegacyNextXpJump(levels))*exp);
return (int)(remainder+result);
}
//calculate legacy xp required to get to next level
private float getLegacyNextXpJump(int level) {
return (float)(3.5*level) + (float)(6.7);
}
//calculate legacy level from xp
private int getLegacyLevel(int totalXP) {
if (totalXP > 0) {
int level = 1;
int xpGuess = getLegacyTotalXP(level,0);
while (xpGuess < totalXP) {
level++;
xpGuess = getLegacyTotalXP(level,0);
}
return level-1;
}
return 0;
}
//calculate legacy exp from level and totalXP
private float getLegacyExp(int level, int totalXP) {
int levelXP = Math.round(getLegacyTotalXP(level,0));
int remainder = totalXP-levelXP;
float required = Math.round(getLegacyNextXpJump(level));
float exp = (remainder/required);
return exp;
}
//change xp yield from bottle
@EventHandler(priority=EventPriority.HIGHEST)
public void onExpBottleEvent(ExpBottleEvent e) {
e.setExperience(XP_PER_BOTTLE);
}
//modify xp growth rate
@EventHandler(priority=EventPriority.HIGHEST)
public void onPlayerExpChangeEvent(PlayerExpChangeEvent e) {
Player p = e.getPlayer();
int levels = p.getLevel();
int amount = e.getAmount();
float exp = p.getExp();
Integer legacyTotalXp = getLegacyTotalXP(levels,exp) + amount;
Integer legacyLevel = getLegacyLevel(legacyTotalXp);
Float legacyExp = getLegacyExp(legacyLevel, legacyTotalXp);
e.setAmount(0);
p.setTotalExperience(0);
p.setLevel(legacyLevel);
p.setExp(legacyExp);
}
//generate xp bottles
@EventHandler(priority=EventPriority.HIGHEST)
public void onPlayerInteractEvent(PlayerInteractEvent e) {
//check the event isn't cancelled and they have clicked on an enchanting table
if (!e.isCancelled() && e.getClickedBlock().getType() == Material.ENCHANTMENT_TABLE) {
//if the player is holding glass bottles
if (e.getMaterial() == Material.GLASS_BOTTLE) {
Player p = e.getPlayer();
//check player has waited for the required amount of time
if (!playerWaitHash.containsKey(p.getName())) {
//if there is no time recorded, add the current time
bottleO.log.info("no record of "+p.getName()+" logging in!");
playerWaitHash.put(p.getName(), System.currentTimeMillis());
}
long loginTime = playerWaitHash.get(p.getName());
long timeDiff = System.currentTimeMillis() - (loginTime+WAIT_TIME_MILLIS);
if (timeDiff < 0) {
bottleO.log.info(p.getName()+" must wait "+(float)(-timeDiff)/1000+" seconds!");
p.sendMessage(ChatColor.RED+"["+bottleO.pluginName+"]"+ChatColor.WHITE+" you must wait "+ChatColor.RED+(float)(-timeDiff)/1000+ChatColor.WHITE+" seconds to make more exp bottles.");
return;
}
int initialAmount = p.getItemInHand().getAmount();
int amount = initialAmount;
int totalXP = getLegacyTotalXP(p.getLevel(),p.getExp());
if (totalXP < 0) {
String infoMessage = "invalid xp values for "+p.getName()+", calculated xp:"+totalXP+", level:"+p.getLevel()+", progress:"+p.getExp()+", ";
bottleO.log.info(infoMessage+"impossible xp value, stopping.");
return;
}
int totalCost = amount*XP_PER_BOTTLE;
PlayerInventory inventory = p.getInventory();
int newTotalXP;
//sanity checking
if (XP_PER_BOTTLE > 0 && amount > 0 && amount <= 64) {
if (totalXP < totalCost) {
if (totalXP >= XP_PER_BOTTLE) {
totalCost = totalXP;
totalCost -= (totalXP % XP_PER_BOTTLE);
amount = totalCost / XP_PER_BOTTLE;
} else {
amount = 0;
}
}
//if there is enough xp and bottles
if (amount > 0) {
//remove some glass bottles from hand
ItemStack stack = p.getItemInHand();
stack.setAmount(initialAmount-amount);
p.setItemInHand(stack);
//set the new xp value and check it is correct
newTotalXP = totalXP-totalCost;
int legacyLevel = getLegacyLevel(newTotalXP);
p.setTotalExperience(0);
p.setLevel(legacyLevel);
p.setExp(getLegacyExp(legacyLevel, newTotalXP));
//p.giveExp(newTotalXP);
int finalXP = getLegacyTotalXP(p.getLevel(),p.getExp());
//sanity checking
if (finalXP == newTotalXP && finalXP == (totalXP - totalCost)) {
//try to put xp bottles in inventory
HashMap<Integer, ItemStack> hash = inventory.addItem(new ItemStack(Material.EXP_BOTTLE, amount));
//otherwise replace glass bottles in hand and drop glass bottles
if (!hash.isEmpty()) {
Iterator<Integer> it = hash.keySet().iterator();
if (it.hasNext()) {
ItemStack glassStack = p.getItemInHand().clone();
p.setItemInHand(hash.get(it.next()));
p.getWorld().dropItem(p.getLocation(), glassStack);
}
}
//restart cool-down timer
playerWaitHash.put(p.getName(), System.currentTimeMillis());
//add slowness potion effect because it looks cool
p.addPotionEffect(new PotionEffect(PotionEffectType.SLOW, 40, 3));
bottleO.log.info("success! "+p.getName()+", init:"+totalXP+", final:"+finalXP+", cost:"+totalCost+", bottles:"+(totalCost/XP_PER_BOTTLE));
}
// this should never happen
else {
p.setTotalExperience(0);
p.setLevel(0);
p.setExp(0);
bottleO.log.info("panic! "+p.getName()+", init:"+totalXP+", final:"+finalXP+", attempted cost:"+totalCost);
}
}
}
- } else if (e.getMaterial() == Material.EMERALD || e.getMaterial() == Material.EMERALD_BLOCK) {
+ } else if ((e.getMaterial() == Material.EMERALD || e.getMaterial() == Material.EMERALD_BLOCK) && !e.getPlayer().isSneaking()) {
Player p = e.getPlayer();
//check player has waited for the required amount of time
if (!playerWaitHash.containsKey(p.getName())) {
//if there is no time recorded, add the current time
bottleO.log.info("no record of "+p.getName()+" logging in!");
playerWaitHash.put(p.getName(), System.currentTimeMillis());
}
long loginTime = playerWaitHash.get(p.getName());
long timeDiff = System.currentTimeMillis() - (loginTime+WAIT_TIME_MILLIS);
if (timeDiff < 0) {
bottleO.log.info(p.getName()+" must wait "+(float)(-timeDiff)/1000+" seconds!");
p.sendMessage(ChatColor.RED+"["+bottleO.pluginName+"]"+ChatColor.WHITE+" you must wait "+ChatColor.RED+(float)(-timeDiff)/1000+ChatColor.WHITE+" seconds to recover more exp.");
return;
}
//calculate amount of xp
ItemStack i = p.getItemInHand();
Material m = e.getMaterial();
int amount = i.getAmount();
int xp = amount*BOTTLES_PER_EMERALD*XP_PER_BOTTLE;
if (m == Material.EMERALD_BLOCK) {
xp *= EMERALDS_PER_BLOCK;
}
PlayerExpChangeEvent event = new PlayerExpChangeEvent(p, xp);
Bukkit.getPluginManager().callEvent(event);
//destroy items
p.setItemInHand(new ItemStack(Material.AIR));
p.addPotionEffect(new PotionEffect(PotionEffectType.SPEED, 40, 3));
//restart cool-down timer
playerWaitHash.put(p.getName(), System.currentTimeMillis());
bottleO.log.info("xp recovered! "+m.toString()+", "+amount+", "+xp);
}
}
}
//record login time
@EventHandler(priority=EventPriority.HIGHEST)
public void onPlayerLoginEvent(PlayerLoginEvent e) {
Player p = e.getPlayer();
playerWaitHash.put(p.getName(), System.currentTimeMillis());
}
@EventHandler(priority=EventPriority.HIGHEST)
public void onPrepareItemEnchant(PrepareItemEnchantEvent e) {
int level;
if (e.getEnchanter().getGameMode() == GameMode.CREATIVE) {
level = 50;
}
else {
level = e.getEnchanter().getLevel();
}
int[] levels = e.getExpLevelCostsOffered();
Random rnd = new Random();
//number of bookshelves around the enchanting table
int bonus = e.getEnchantmentBonus();
//limit bookshelves to 30
if (bonus > MAX_BOOKSHELVES) {
bonus = MAX_BOOKSHELVES;
}
if (bonus <= 0) {
levels[0] = rnd.nextInt(5) / 2;
levels[1] = rnd.nextInt(5) * 2 / 3;
levels[2] = Math.min(4, level);
}
else {
levels[0] = (rnd.nextInt(5) + 2 + (bonus / 2) + rnd.nextInt(bonus)) / 2;
levels[1] = (rnd.nextInt(5) + 2 + (bonus / 2) + rnd.nextInt(bonus)) * 2 / 3;
levels[2] = Math.min(5 + (bonus / 2) + bonus, level);
}
for (int i = 0; i < 3; i++) {
if (levels[i] < 1) {
levels[i] = 1;
}
}
}
@EventHandler(priority=EventPriority.HIGHEST)
public void onEnchantItem(EnchantItemEvent e) {
Enchantments enchantments = new Enchantments(e.getExpLevelCost(), e.getItem().getType());
if (enchantments.getCount() <= 0) {
e.setCancelled(true);
return;
}
enchantments.applyEnchantments(e.getEnchantsToAdd());
}
}
| true | true | public void onPlayerInteractEvent(PlayerInteractEvent e) {
//check the event isn't cancelled and they have clicked on an enchanting table
if (!e.isCancelled() && e.getClickedBlock().getType() == Material.ENCHANTMENT_TABLE) {
//if the player is holding glass bottles
if (e.getMaterial() == Material.GLASS_BOTTLE) {
Player p = e.getPlayer();
//check player has waited for the required amount of time
if (!playerWaitHash.containsKey(p.getName())) {
//if there is no time recorded, add the current time
bottleO.log.info("no record of "+p.getName()+" logging in!");
playerWaitHash.put(p.getName(), System.currentTimeMillis());
}
long loginTime = playerWaitHash.get(p.getName());
long timeDiff = System.currentTimeMillis() - (loginTime+WAIT_TIME_MILLIS);
if (timeDiff < 0) {
bottleO.log.info(p.getName()+" must wait "+(float)(-timeDiff)/1000+" seconds!");
p.sendMessage(ChatColor.RED+"["+bottleO.pluginName+"]"+ChatColor.WHITE+" you must wait "+ChatColor.RED+(float)(-timeDiff)/1000+ChatColor.WHITE+" seconds to make more exp bottles.");
return;
}
int initialAmount = p.getItemInHand().getAmount();
int amount = initialAmount;
int totalXP = getLegacyTotalXP(p.getLevel(),p.getExp());
if (totalXP < 0) {
String infoMessage = "invalid xp values for "+p.getName()+", calculated xp:"+totalXP+", level:"+p.getLevel()+", progress:"+p.getExp()+", ";
bottleO.log.info(infoMessage+"impossible xp value, stopping.");
return;
}
int totalCost = amount*XP_PER_BOTTLE;
PlayerInventory inventory = p.getInventory();
int newTotalXP;
//sanity checking
if (XP_PER_BOTTLE > 0 && amount > 0 && amount <= 64) {
if (totalXP < totalCost) {
if (totalXP >= XP_PER_BOTTLE) {
totalCost = totalXP;
totalCost -= (totalXP % XP_PER_BOTTLE);
amount = totalCost / XP_PER_BOTTLE;
} else {
amount = 0;
}
}
//if there is enough xp and bottles
if (amount > 0) {
//remove some glass bottles from hand
ItemStack stack = p.getItemInHand();
stack.setAmount(initialAmount-amount);
p.setItemInHand(stack);
//set the new xp value and check it is correct
newTotalXP = totalXP-totalCost;
int legacyLevel = getLegacyLevel(newTotalXP);
p.setTotalExperience(0);
p.setLevel(legacyLevel);
p.setExp(getLegacyExp(legacyLevel, newTotalXP));
//p.giveExp(newTotalXP);
int finalXP = getLegacyTotalXP(p.getLevel(),p.getExp());
//sanity checking
if (finalXP == newTotalXP && finalXP == (totalXP - totalCost)) {
//try to put xp bottles in inventory
HashMap<Integer, ItemStack> hash = inventory.addItem(new ItemStack(Material.EXP_BOTTLE, amount));
//otherwise replace glass bottles in hand and drop glass bottles
if (!hash.isEmpty()) {
Iterator<Integer> it = hash.keySet().iterator();
if (it.hasNext()) {
ItemStack glassStack = p.getItemInHand().clone();
p.setItemInHand(hash.get(it.next()));
p.getWorld().dropItem(p.getLocation(), glassStack);
}
}
//restart cool-down timer
playerWaitHash.put(p.getName(), System.currentTimeMillis());
//add slowness potion effect because it looks cool
p.addPotionEffect(new PotionEffect(PotionEffectType.SLOW, 40, 3));
bottleO.log.info("success! "+p.getName()+", init:"+totalXP+", final:"+finalXP+", cost:"+totalCost+", bottles:"+(totalCost/XP_PER_BOTTLE));
}
// this should never happen
else {
p.setTotalExperience(0);
p.setLevel(0);
p.setExp(0);
bottleO.log.info("panic! "+p.getName()+", init:"+totalXP+", final:"+finalXP+", attempted cost:"+totalCost);
}
}
}
} else if (e.getMaterial() == Material.EMERALD || e.getMaterial() == Material.EMERALD_BLOCK) {
Player p = e.getPlayer();
//check player has waited for the required amount of time
if (!playerWaitHash.containsKey(p.getName())) {
//if there is no time recorded, add the current time
bottleO.log.info("no record of "+p.getName()+" logging in!");
playerWaitHash.put(p.getName(), System.currentTimeMillis());
}
long loginTime = playerWaitHash.get(p.getName());
long timeDiff = System.currentTimeMillis() - (loginTime+WAIT_TIME_MILLIS);
if (timeDiff < 0) {
bottleO.log.info(p.getName()+" must wait "+(float)(-timeDiff)/1000+" seconds!");
p.sendMessage(ChatColor.RED+"["+bottleO.pluginName+"]"+ChatColor.WHITE+" you must wait "+ChatColor.RED+(float)(-timeDiff)/1000+ChatColor.WHITE+" seconds to recover more exp.");
return;
}
//calculate amount of xp
ItemStack i = p.getItemInHand();
Material m = e.getMaterial();
int amount = i.getAmount();
int xp = amount*BOTTLES_PER_EMERALD*XP_PER_BOTTLE;
if (m == Material.EMERALD_BLOCK) {
xp *= EMERALDS_PER_BLOCK;
}
PlayerExpChangeEvent event = new PlayerExpChangeEvent(p, xp);
Bukkit.getPluginManager().callEvent(event);
//destroy items
p.setItemInHand(new ItemStack(Material.AIR));
p.addPotionEffect(new PotionEffect(PotionEffectType.SPEED, 40, 3));
//restart cool-down timer
playerWaitHash.put(p.getName(), System.currentTimeMillis());
bottleO.log.info("xp recovered! "+m.toString()+", "+amount+", "+xp);
}
}
}
| public void onPlayerInteractEvent(PlayerInteractEvent e) {
//check the event isn't cancelled and they have clicked on an enchanting table
if (!e.isCancelled() && e.getClickedBlock().getType() == Material.ENCHANTMENT_TABLE) {
//if the player is holding glass bottles
if (e.getMaterial() == Material.GLASS_BOTTLE) {
Player p = e.getPlayer();
//check player has waited for the required amount of time
if (!playerWaitHash.containsKey(p.getName())) {
//if there is no time recorded, add the current time
bottleO.log.info("no record of "+p.getName()+" logging in!");
playerWaitHash.put(p.getName(), System.currentTimeMillis());
}
long loginTime = playerWaitHash.get(p.getName());
long timeDiff = System.currentTimeMillis() - (loginTime+WAIT_TIME_MILLIS);
if (timeDiff < 0) {
bottleO.log.info(p.getName()+" must wait "+(float)(-timeDiff)/1000+" seconds!");
p.sendMessage(ChatColor.RED+"["+bottleO.pluginName+"]"+ChatColor.WHITE+" you must wait "+ChatColor.RED+(float)(-timeDiff)/1000+ChatColor.WHITE+" seconds to make more exp bottles.");
return;
}
int initialAmount = p.getItemInHand().getAmount();
int amount = initialAmount;
int totalXP = getLegacyTotalXP(p.getLevel(),p.getExp());
if (totalXP < 0) {
String infoMessage = "invalid xp values for "+p.getName()+", calculated xp:"+totalXP+", level:"+p.getLevel()+", progress:"+p.getExp()+", ";
bottleO.log.info(infoMessage+"impossible xp value, stopping.");
return;
}
int totalCost = amount*XP_PER_BOTTLE;
PlayerInventory inventory = p.getInventory();
int newTotalXP;
//sanity checking
if (XP_PER_BOTTLE > 0 && amount > 0 && amount <= 64) {
if (totalXP < totalCost) {
if (totalXP >= XP_PER_BOTTLE) {
totalCost = totalXP;
totalCost -= (totalXP % XP_PER_BOTTLE);
amount = totalCost / XP_PER_BOTTLE;
} else {
amount = 0;
}
}
//if there is enough xp and bottles
if (amount > 0) {
//remove some glass bottles from hand
ItemStack stack = p.getItemInHand();
stack.setAmount(initialAmount-amount);
p.setItemInHand(stack);
//set the new xp value and check it is correct
newTotalXP = totalXP-totalCost;
int legacyLevel = getLegacyLevel(newTotalXP);
p.setTotalExperience(0);
p.setLevel(legacyLevel);
p.setExp(getLegacyExp(legacyLevel, newTotalXP));
//p.giveExp(newTotalXP);
int finalXP = getLegacyTotalXP(p.getLevel(),p.getExp());
//sanity checking
if (finalXP == newTotalXP && finalXP == (totalXP - totalCost)) {
//try to put xp bottles in inventory
HashMap<Integer, ItemStack> hash = inventory.addItem(new ItemStack(Material.EXP_BOTTLE, amount));
//otherwise replace glass bottles in hand and drop glass bottles
if (!hash.isEmpty()) {
Iterator<Integer> it = hash.keySet().iterator();
if (it.hasNext()) {
ItemStack glassStack = p.getItemInHand().clone();
p.setItemInHand(hash.get(it.next()));
p.getWorld().dropItem(p.getLocation(), glassStack);
}
}
//restart cool-down timer
playerWaitHash.put(p.getName(), System.currentTimeMillis());
//add slowness potion effect because it looks cool
p.addPotionEffect(new PotionEffect(PotionEffectType.SLOW, 40, 3));
bottleO.log.info("success! "+p.getName()+", init:"+totalXP+", final:"+finalXP+", cost:"+totalCost+", bottles:"+(totalCost/XP_PER_BOTTLE));
}
// this should never happen
else {
p.setTotalExperience(0);
p.setLevel(0);
p.setExp(0);
bottleO.log.info("panic! "+p.getName()+", init:"+totalXP+", final:"+finalXP+", attempted cost:"+totalCost);
}
}
}
} else if ((e.getMaterial() == Material.EMERALD || e.getMaterial() == Material.EMERALD_BLOCK) && !e.getPlayer().isSneaking()) {
Player p = e.getPlayer();
//check player has waited for the required amount of time
if (!playerWaitHash.containsKey(p.getName())) {
//if there is no time recorded, add the current time
bottleO.log.info("no record of "+p.getName()+" logging in!");
playerWaitHash.put(p.getName(), System.currentTimeMillis());
}
long loginTime = playerWaitHash.get(p.getName());
long timeDiff = System.currentTimeMillis() - (loginTime+WAIT_TIME_MILLIS);
if (timeDiff < 0) {
bottleO.log.info(p.getName()+" must wait "+(float)(-timeDiff)/1000+" seconds!");
p.sendMessage(ChatColor.RED+"["+bottleO.pluginName+"]"+ChatColor.WHITE+" you must wait "+ChatColor.RED+(float)(-timeDiff)/1000+ChatColor.WHITE+" seconds to recover more exp.");
return;
}
//calculate amount of xp
ItemStack i = p.getItemInHand();
Material m = e.getMaterial();
int amount = i.getAmount();
int xp = amount*BOTTLES_PER_EMERALD*XP_PER_BOTTLE;
if (m == Material.EMERALD_BLOCK) {
xp *= EMERALDS_PER_BLOCK;
}
PlayerExpChangeEvent event = new PlayerExpChangeEvent(p, xp);
Bukkit.getPluginManager().callEvent(event);
//destroy items
p.setItemInHand(new ItemStack(Material.AIR));
p.addPotionEffect(new PotionEffect(PotionEffectType.SPEED, 40, 3));
//restart cool-down timer
playerWaitHash.put(p.getName(), System.currentTimeMillis());
bottleO.log.info("xp recovered! "+m.toString()+", "+amount+", "+xp);
}
}
}
|
diff --git a/main/src/main/java/org/geoserver/security/GeoserverUserDao.java b/main/src/main/java/org/geoserver/security/GeoserverUserDao.java
index 4601328..ad8d846 100644
--- a/main/src/main/java/org/geoserver/security/GeoserverUserDao.java
+++ b/main/src/main/java/org/geoserver/security/GeoserverUserDao.java
@@ -1,299 +1,299 @@
/* Copyright (c) 2001 - 2007 TOPP - www.openplans.org. All rights reserved.
* This code is licensed under the GPL 2.0 license, availible at the root
* application directory.
*/
package org.geoserver.security;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.acegisecurity.GrantedAuthority;
import org.acegisecurity.userdetails.User;
import org.acegisecurity.userdetails.UserDetails;
import org.acegisecurity.userdetails.UserDetailsService;
import org.acegisecurity.userdetails.UsernameNotFoundException;
import org.acegisecurity.userdetails.memory.UserAttribute;
import org.acegisecurity.userdetails.memory.UserAttributeEditor;
import org.geoserver.config.GeoServer;
import org.geoserver.config.GeoServerInfo;
import org.geoserver.platform.GeoServerExtensions;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.DataAccessResourceFailureException;
import org.vfny.geoserver.global.GeoserverDataDirectory;
/**
* A simple DAO reading/writing the user's property files
*
* @author Andrea Aime - OpenGeo
*
*/
public class GeoserverUserDao implements UserDetailsService {
/** logger */
static Logger LOGGER = org.geotools.util.logging.Logging.getLogger("org.geoserver.security");
TreeMap<String, User> userMap;
PropertyFileWatcher userDefinitionsFile;
File securityDir;
/**
* Returns the {@link GeoserverUserDao} instance registered in the GeoServer Spring context
*/
public static GeoserverUserDao get() {
return GeoServerExtensions.bean(GeoserverUserDao.class);
}
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException,
DataAccessException {
checkUserMap();
UserDetails user = userMap.get(username);
if (user == null)
throw new UsernameNotFoundException("Could not find user: " + username);
return user;
}
/**
* Either loads the default property file on the first access, or reloads it if it has been
* modified since last access.
*
* @throws DataAccessResourceFailureException
*/
void checkUserMap() throws DataAccessResourceFailureException {
InputStream is = null;
OutputStream os = null;
- if ((userMap == null) || ((userDefinitionsFile != null) && userDefinitionsFile.isStale())) {
+ if ((userMap == null) || userDefinitionsFile == null || userDefinitionsFile.isStale()) {
try {
if (userDefinitionsFile == null) {
securityDir = GeoserverDataDirectory.findCreateConfigDir("security");
File propFile = new File(securityDir, "users.properties");
if (!propFile.exists()) {
// we're probably dealing with an old data dir, create
// the file without
// changing the username and password if possible
Properties p = new Properties();
GeoServerInfo global = GeoServerExtensions.bean(GeoServer.class).getGlobal();
if ((global != null) && (global.getAdminUsername() != null)
&& !global.getAdminUsername().trim().equals("")) {
p.put(global.getAdminUsername(), global.getAdminPassword()
+ ",ROLE_ADMINISTRATOR");
} else {
p.put("admin", "geoserver,ROLE_ADMINISTRATOR");
}
os = new FileOutputStream(propFile);
p.store(os, "Format: name=password,ROLE1,...,ROLEN");
os.close();
// setup a sample service.properties
File serviceFile = new File(securityDir, "service.properties");
os = new FileOutputStream(serviceFile);
is = GeoserverUserDao.class
.getResourceAsStream("serviceTemplate.properties");
byte[] buffer = new byte[1024];
int count = 0;
while ((count = is.read(buffer)) > 0) {
os.write(buffer, 0, count);
}
}
userDefinitionsFile = new PropertyFileWatcher(propFile);
}
userMap = loadUsersFromProperties(userDefinitionsFile.getProperties());
} catch (Exception e) {
LOGGER.log(Level.SEVERE, "An error occurred loading user definitions", e);
} finally {
if (is != null)
try {
is.close();
} catch (IOException ei) { /* nothing to do */
}
if (os != null)
try {
os.close();
} catch (IOException eo) { /* nothing to do */
}
}
}
}
/**
* Get the list of roles currently known by users (there's guarantee the well known
* ROLE_ADMINISTRATOR will be part of the lot)
*/
public List<String> getRoles() {
checkUserMap();
Set<String> roles = new TreeSet<String>();
roles.add("ROLE_ADMINISTRATOR");
for (User user : getUsers()) {
for (GrantedAuthority ga : user.getAuthorities()) {
roles.add(ga.getAuthority());
}
}
return new ArrayList<String>(roles);
}
/**
* Returns the list of users. To be used for UI editing of users, it's a live map
*
* @return
*/
public List<User> getUsers() {
checkUserMap();
return new ArrayList(userMap.values());
}
/**
* Adds a user in the user map
* @param user
*/
public void putUser(User user) {
checkUserMap();
if(userMap.containsKey(user.getUsername()))
throw new IllegalArgumentException("The user " + user.getUsername() + " already exists");
else
userMap.put(user.getUsername(), user);
}
/**
* Updates a user in the user map
* @param user
*/
public void setUser(User user) {
checkUserMap();
if(userMap.containsKey(user.getUsername()))
userMap.put(user.getUsername(), user);
else
throw new IllegalArgumentException("The user " + user.getUsername() + " already exists");
}
/**
* Removes the specified user from the users list
* @param username
* @return
*/
public boolean removeUser(String username) {
checkUserMap();
return userMap.remove(username) != null;
}
/**
* Writes down the current users map to file system
*/
public void storeUsers() throws IOException {
FileOutputStream os = null;
try {
// turn back the users into a users map
Properties p = storeUsersToProperties(userMap);
// write out to the data dir
File propFile = new File(securityDir, "users.properties");
os = new FileOutputStream(propFile);
p.store(os, null);
} catch (Exception e) {
if (e instanceof IOException)
throw (IOException) e;
else
throw (IOException) new IOException(
"Could not write updated users list to file system").initCause(e);
} finally {
if (os != null)
os.close();
}
}
/**
* Force the dao to reload its definitions from the file
*/
public void reload() {
userDefinitionsFile = null;
}
/**
* Loads the user from property file into the users map
*
* @param users
* @param props
*/
TreeMap<String, User> loadUsersFromProperties(Properties props) {
TreeMap<String, User> users = new TreeMap<String, User>();
UserAttributeEditor configAttribEd = new UserAttributeEditor();
for (Iterator iter = props.keySet().iterator(); iter.hasNext();) {
// the attribute editors parses the list of strings into password, username and enabled
// flag
String username = (String) iter.next();
configAttribEd.setAsText(props.getProperty(username));
// if the parsing succeeded turn that into a user object
UserAttribute attr = (UserAttribute) configAttribEd.getValue();
if (attr != null) {
User user = createUserObject(username, attr.getPassword(), attr.isEnabled(), attr.getAuthorities());
users.put(username, user);
}
}
return users;
}
protected User createUserObject(String username,String password, boolean isEnabled,GrantedAuthority[] authorities) {
return new User(username, password, isEnabled, true, true,
true, authorities);
}
/**
* Stores the provided user map into a properties object
*
* @param userMap
* @return
*/
Properties storeUsersToProperties(Map<String, User> userMap) {
Properties p = new Properties();
for (User user : userMap.values()) {
p.setProperty(user.getUsername(), serializeUser(user));
}
return p;
}
/**
* Turns the users password, granted authorities and enabled state into a property file value
*
* @param user
* @return
*/
String serializeUser(User user) {
StringBuffer sb = new StringBuffer();
sb.append(user.getPassword());
sb.append(",");
for (GrantedAuthority ga : user.getAuthorities()) {
sb.append(ga.getAuthority());
sb.append(",");
}
sb.append(user.isEnabled() ? "enabled" : "disabled");
return sb.toString();
}
}
| true | true | void checkUserMap() throws DataAccessResourceFailureException {
InputStream is = null;
OutputStream os = null;
if ((userMap == null) || ((userDefinitionsFile != null) && userDefinitionsFile.isStale())) {
try {
if (userDefinitionsFile == null) {
securityDir = GeoserverDataDirectory.findCreateConfigDir("security");
File propFile = new File(securityDir, "users.properties");
if (!propFile.exists()) {
// we're probably dealing with an old data dir, create
// the file without
// changing the username and password if possible
Properties p = new Properties();
GeoServerInfo global = GeoServerExtensions.bean(GeoServer.class).getGlobal();
if ((global != null) && (global.getAdminUsername() != null)
&& !global.getAdminUsername().trim().equals("")) {
p.put(global.getAdminUsername(), global.getAdminPassword()
+ ",ROLE_ADMINISTRATOR");
} else {
p.put("admin", "geoserver,ROLE_ADMINISTRATOR");
}
os = new FileOutputStream(propFile);
p.store(os, "Format: name=password,ROLE1,...,ROLEN");
os.close();
// setup a sample service.properties
File serviceFile = new File(securityDir, "service.properties");
os = new FileOutputStream(serviceFile);
is = GeoserverUserDao.class
.getResourceAsStream("serviceTemplate.properties");
byte[] buffer = new byte[1024];
int count = 0;
while ((count = is.read(buffer)) > 0) {
os.write(buffer, 0, count);
}
}
userDefinitionsFile = new PropertyFileWatcher(propFile);
}
userMap = loadUsersFromProperties(userDefinitionsFile.getProperties());
} catch (Exception e) {
LOGGER.log(Level.SEVERE, "An error occurred loading user definitions", e);
} finally {
if (is != null)
try {
is.close();
} catch (IOException ei) { /* nothing to do */
}
if (os != null)
try {
os.close();
} catch (IOException eo) { /* nothing to do */
}
}
}
}
| void checkUserMap() throws DataAccessResourceFailureException {
InputStream is = null;
OutputStream os = null;
if ((userMap == null) || userDefinitionsFile == null || userDefinitionsFile.isStale()) {
try {
if (userDefinitionsFile == null) {
securityDir = GeoserverDataDirectory.findCreateConfigDir("security");
File propFile = new File(securityDir, "users.properties");
if (!propFile.exists()) {
// we're probably dealing with an old data dir, create
// the file without
// changing the username and password if possible
Properties p = new Properties();
GeoServerInfo global = GeoServerExtensions.bean(GeoServer.class).getGlobal();
if ((global != null) && (global.getAdminUsername() != null)
&& !global.getAdminUsername().trim().equals("")) {
p.put(global.getAdminUsername(), global.getAdminPassword()
+ ",ROLE_ADMINISTRATOR");
} else {
p.put("admin", "geoserver,ROLE_ADMINISTRATOR");
}
os = new FileOutputStream(propFile);
p.store(os, "Format: name=password,ROLE1,...,ROLEN");
os.close();
// setup a sample service.properties
File serviceFile = new File(securityDir, "service.properties");
os = new FileOutputStream(serviceFile);
is = GeoserverUserDao.class
.getResourceAsStream("serviceTemplate.properties");
byte[] buffer = new byte[1024];
int count = 0;
while ((count = is.read(buffer)) > 0) {
os.write(buffer, 0, count);
}
}
userDefinitionsFile = new PropertyFileWatcher(propFile);
}
userMap = loadUsersFromProperties(userDefinitionsFile.getProperties());
} catch (Exception e) {
LOGGER.log(Level.SEVERE, "An error occurred loading user definitions", e);
} finally {
if (is != null)
try {
is.close();
} catch (IOException ei) { /* nothing to do */
}
if (os != null)
try {
os.close();
} catch (IOException eo) { /* nothing to do */
}
}
}
}
|
diff --git a/web/src/main/java/de/betterform/agent/web/servlet/XFormsInspectorServlet.java b/web/src/main/java/de/betterform/agent/web/servlet/XFormsInspectorServlet.java
index f2f49489..e7289393 100644
--- a/web/src/main/java/de/betterform/agent/web/servlet/XFormsInspectorServlet.java
+++ b/web/src/main/java/de/betterform/agent/web/servlet/XFormsInspectorServlet.java
@@ -1,140 +1,141 @@
/*
* Copyright (c) 2010. betterForm Project - http://www.betterform.de
* Licensed under the terms of BSD License
*/
package de.betterform.agent.web.servlet;
import de.betterform.agent.web.WebFactory;
import de.betterform.agent.web.WebUtil;
import de.betterform.xml.config.Config;
import de.betterform.xml.config.XFormsConfigException;
import de.betterform.xml.dom.DOMUtil;
import de.betterform.xml.xforms.XFormsProcessor;
import de.betterform.xml.xforms.exception.XFormsException;
import de.betterform.xml.xforms.model.Model;
import de.betterform.xml.xpath.XPathUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.xforms.XFormsModelElement;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.transform.TransformerException;
import java.io.IOException;
import java.io.OutputStream;
/**
* @author Joern Turner
*/
public class XFormsInspectorServlet extends HttpServlet /* extends AbstractXFormsServlet */ {
private static final Log LOGGER = LogFactory.getLog(XFormsInspectorServlet.class);
public static final String defContentType = "text/html; charset=UTF-8";
private de.betterform.agent.web.WebFactory webFactory;
/**
* Returns a short description of the servlet.
*
* @return - Returns a short description of the servlet.
*/
public String getServletInfo() {
return "responsible for showing the views to the user in betterForm XForms applications";
}
/**
* Destroys the servlet.
*/
public void destroy() {
}
/**
*
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String resource = request.getRequestURI();
/*
must be in the form:
'xforms/[SESSION-ID]/[model-id]/[instance-id]' OR
'xforms/[SESSION-ID]/hostDOM'
*/
//
// later probably and optional xpath locationpath can be added
HttpSession session = request.getSession(true);
String[] steps = XPathUtil.splitPathExpr(resource);
String xformsSessionId = steps[3];
XFormsProcessor processor = WebUtil.getWebProcessor(xformsSessionId);
if(processor == null){
sendError(request, response, session, null,"Processor with sessionId '" + xformsSessionId + "' not found.");
return;
}
try {
if (resource.indexOf("hostDOM") != -1) {
// output Host document markup
Node host = processor.getXForms();
OutputStream out = response.getOutputStream();
response.setContentType("text/plain");
+ request.setAttribute(WebFactory.IGNORE_RESPONSE_BODY, "TRUE");
DOMUtil.prettyPrintDOM(host, out);
out.close();
} else {
String modelId = steps[4];
String instanceId = steps[5];
//try to get model
XFormsModelElement model;
try{
model = processor.getXFormsModel(modelId) ;
}catch(XFormsException xe){
sendError(request, response, session, xe,"Model with id '" + modelId + "' not found.");
return;
}
// fetch Instance and serialize as XML
try{
Document instance = model.getInstanceDocument(instanceId);
OutputStream out = response.getOutputStream();
response.setContentType("application/xml");
DOMUtil.prettyPrintDOM(instance, out);
}catch(DOMException de){
sendError(request, response, session, null,"Instance with id '" + instanceId + "' not found.");
return;
}
}
} catch (XFormsException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} catch (TransformerException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
// write to outputstream
}
private void sendError(HttpServletRequest request, HttpServletResponse response, HttpSession session, Exception e,String message) throws ServletException, IOException {
session.setAttribute("betterform.exception", e);
session.setAttribute("betterform.exception.message",message);
session.setAttribute("betterform.referer", request.getRequestURL());
String path = null;
try {
path = "/" + Config.getInstance().getProperty(WebFactory.ERROPAGE_PROPERTY);
} catch (XFormsConfigException ce) {
ce.printStackTrace();
}
getServletContext().getRequestDispatcher(path).forward(request,response);
}
}
| true | true | protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String resource = request.getRequestURI();
/*
must be in the form:
'xforms/[SESSION-ID]/[model-id]/[instance-id]' OR
'xforms/[SESSION-ID]/hostDOM'
*/
//
// later probably and optional xpath locationpath can be added
HttpSession session = request.getSession(true);
String[] steps = XPathUtil.splitPathExpr(resource);
String xformsSessionId = steps[3];
XFormsProcessor processor = WebUtil.getWebProcessor(xformsSessionId);
if(processor == null){
sendError(request, response, session, null,"Processor with sessionId '" + xformsSessionId + "' not found.");
return;
}
try {
if (resource.indexOf("hostDOM") != -1) {
// output Host document markup
Node host = processor.getXForms();
OutputStream out = response.getOutputStream();
response.setContentType("text/plain");
DOMUtil.prettyPrintDOM(host, out);
out.close();
} else {
String modelId = steps[4];
String instanceId = steps[5];
//try to get model
XFormsModelElement model;
try{
model = processor.getXFormsModel(modelId) ;
}catch(XFormsException xe){
sendError(request, response, session, xe,"Model with id '" + modelId + "' not found.");
return;
}
// fetch Instance and serialize as XML
try{
Document instance = model.getInstanceDocument(instanceId);
OutputStream out = response.getOutputStream();
response.setContentType("application/xml");
DOMUtil.prettyPrintDOM(instance, out);
}catch(DOMException de){
sendError(request, response, session, null,"Instance with id '" + instanceId + "' not found.");
return;
}
}
} catch (XFormsException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} catch (TransformerException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
// write to outputstream
}
| protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String resource = request.getRequestURI();
/*
must be in the form:
'xforms/[SESSION-ID]/[model-id]/[instance-id]' OR
'xforms/[SESSION-ID]/hostDOM'
*/
//
// later probably and optional xpath locationpath can be added
HttpSession session = request.getSession(true);
String[] steps = XPathUtil.splitPathExpr(resource);
String xformsSessionId = steps[3];
XFormsProcessor processor = WebUtil.getWebProcessor(xformsSessionId);
if(processor == null){
sendError(request, response, session, null,"Processor with sessionId '" + xformsSessionId + "' not found.");
return;
}
try {
if (resource.indexOf("hostDOM") != -1) {
// output Host document markup
Node host = processor.getXForms();
OutputStream out = response.getOutputStream();
response.setContentType("text/plain");
request.setAttribute(WebFactory.IGNORE_RESPONSE_BODY, "TRUE");
DOMUtil.prettyPrintDOM(host, out);
out.close();
} else {
String modelId = steps[4];
String instanceId = steps[5];
//try to get model
XFormsModelElement model;
try{
model = processor.getXFormsModel(modelId) ;
}catch(XFormsException xe){
sendError(request, response, session, xe,"Model with id '" + modelId + "' not found.");
return;
}
// fetch Instance and serialize as XML
try{
Document instance = model.getInstanceDocument(instanceId);
OutputStream out = response.getOutputStream();
response.setContentType("application/xml");
DOMUtil.prettyPrintDOM(instance, out);
}catch(DOMException de){
sendError(request, response, session, null,"Instance with id '" + instanceId + "' not found.");
return;
}
}
} catch (XFormsException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} catch (TransformerException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
// write to outputstream
}
|
diff --git a/juddi-core/src/main/java/org/apache/juddi/config/Install.java b/juddi-core/src/main/java/org/apache/juddi/config/Install.java
index de5572a1e..0e49caecd 100644
--- a/juddi-core/src/main/java/org/apache/juddi/config/Install.java
+++ b/juddi-core/src/main/java/org/apache/juddi/config/Install.java
@@ -1,501 +1,501 @@
/*
* Copyright 2001-2008 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.juddi.config;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Date;
import java.util.List;
import java.util.StringTokenizer;
import java.util.UUID;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.juddi.api.impl.UDDIInquiryImpl;
import org.apache.juddi.error.ErrorMessage;
import org.apache.juddi.error.FatalErrorException;
import org.apache.juddi.error.InvalidKeyPassedException;
import org.apache.juddi.error.KeyUnavailableException;
import org.apache.juddi.error.ValueNotAllowedException;
import org.apache.juddi.keygen.KeyGenerator;
import org.apache.juddi.mapping.MappingApiToModel;
import org.apache.juddi.model.UddiEntityPublisher;
import org.apache.juddi.query.PersistenceManager;
import org.apache.juddi.validation.ValidatePublish;
import org.apache.juddi.validation.ValidateUDDIKey;
import org.apache.log4j.Logger;
import org.uddi.api_v3.SaveTModel;
import org.uddi.api_v3.TModel;
import org.uddi.v3_service.DispositionReportFaultMessage;
/**
* @author <a href="mailto:[email protected]">Jeff Faath</a>
*/
public class Install {
public static final String FILE_ROOT_BUSINESSENTITY = "root_BusinessEntity.xml";
public static final String FILE_ROOT_PUBLISHER = "root_Publisher.xml";
public static final String FILE_ROOT_TMODELKEYGEN = "root_tModelKeyGen.xml";
public static final String FILE_UDDI_PUBLISHER = "UDDI_Publisher.xml";
public static final String FILE_UDDI_TMODELS = "UDDI_tModels.xml";
public static final String FILE_JOE_PUBLISHER = "joepublisher_Publisher.xml";
public static final String FILE_SSYNDICATOR = "ssyndicator_Publisher.xml";
public static final String FILE_PERSISTENCE = "persistence.xml";
public static final String JUDDI_INSTALL_DATA_DIR = "juddi_install_data/";
public static Logger log = Logger.getLogger(Install.class);
public static void install() throws JAXBException, DispositionReportFaultMessage, IOException {
install(JUDDI_INSTALL_DATA_DIR, null, false);
}
public static void install(String srcDir, String userPartition, boolean reloadConfig) throws JAXBException, DispositionReportFaultMessage, IOException {
if (srcDir != null) {
- if (srcDir.endsWith("\\") || srcDir.endsWith("/")) {
+ if (srcDir.endsWith(java.io.File.separator)) {
// Do nothing
}
else
- srcDir = srcDir + "\\";
+ srcDir = srcDir + java.io.File.separator;
}
else
srcDir = "";
EntityManager em = PersistenceManager.getEntityManager();
EntityTransaction tx = em.getTransaction();
UddiEntityPublisher rootPublisher = null;
UddiEntityPublisher uddiPublisher = null;
try {
tx.begin();
if (alreadyInstalled(em))
throw new FatalErrorException(new ErrorMessage("errors.install.AlreadyInstalled"));
TModel rootTModelKeyGen = (TModel)buildEntityFromDoc(JUDDI_INSTALL_DATA_DIR + FILE_ROOT_TMODELKEYGEN, "org.uddi.api_v3");
org.uddi.api_v3.BusinessEntity rootBusinessEntity = (org.uddi.api_v3.BusinessEntity)buildEntityFromDoc(srcDir + FILE_ROOT_BUSINESSENTITY, "org.uddi.api_v3");
String rootPartition = getRootPartition(rootTModelKeyGen, userPartition);
String nodeId = getNodeId(rootBusinessEntity.getBusinessKey(), rootPartition);
rootPublisher = installPublisher(em, JUDDI_INSTALL_DATA_DIR + FILE_ROOT_PUBLISHER);
uddiPublisher = installPublisher(em, JUDDI_INSTALL_DATA_DIR + FILE_UDDI_PUBLISHER);
// TODO: These do not belong here
// Inserting 2 test publishers
installPublisher(em, JUDDI_INSTALL_DATA_DIR + FILE_JOE_PUBLISHER);
installPublisher(em, JUDDI_INSTALL_DATA_DIR + FILE_SSYNDICATOR);
installRootPublisherKeyGen(em, rootTModelKeyGen, rootPartition, rootPublisher, nodeId);
rootBusinessEntity.setBusinessKey(nodeId);
installRootBusinessEntity(em, rootBusinessEntity, rootPublisher, rootPartition);
installUDDITModels(em, JUDDI_INSTALL_DATA_DIR + FILE_UDDI_TMODELS, uddiPublisher, nodeId);
tx.commit();
}
catch(DispositionReportFaultMessage dr) {
log .error(dr.getMessage(),dr);
tx.rollback();
throw dr;
}
catch (JAXBException je) {
log .error(je.getMessage(),je);
tx.rollback();
throw je;
}
catch (IOException ie) {
log .error(ie.getMessage(),ie);
tx.rollback();
throw ie;
}
finally {
if (em.isOpen()) {
em.close();
}
}
// Now that all necessary persistent entities are loaded, the configuration must be reloaded to be sure all properties are set.
if (reloadConfig) {
try { AppConfig.reloadConfig(); } catch (ConfigurationException ce) { log.error(ce.getMessage(), ce); }
}
}
public static void uninstall() {
// Close the open emf, open a new one with Persistence.create...(String, Map) and overwrite the property that handles the table
// generation. The persistence.xml file will have to be read in to determine which property
// to overwrite. The property will be specific to the provider.
// Hibernate: <property name="hibernate.hbm2ddl.auto" value="update"/> ->use "create-drop" or just "drop"?
// OpenJPA: openjpa.jdbc.SynchronizeMappings=buildSchema(SchemaAction='add,deleteTableContents')
// etc...(find more)
// Then close this emf. Question: is the original emf reusable or will closing it cause problems?
}
public static boolean alreadyInstalled() {
EntityManager em = PersistenceManager.getEntityManager();
EntityTransaction tx = em.getTransaction();
tx.begin();
boolean result = alreadyInstalled(em);
tx.commit();
em.close();
return result;
}
public static boolean alreadyInstalled(EntityManager em) {
org.apache.juddi.model.Publisher publisher = em.find(org.apache.juddi.model.Publisher.class, Constants.ROOT_PUBLISHER);
if (publisher != null)
return true;
publisher = em.find(org.apache.juddi.model.Publisher.class, Constants.UDDI_PUBLISHER);
if (publisher != null)
return true;
return false;
}
public static String getRootPartition(TModel rootTModelKeyGen, String userPartition) throws JAXBException, IOException, DispositionReportFaultMessage {
String result = rootTModelKeyGen.getTModelKey().substring(0, rootTModelKeyGen.getTModelKey().lastIndexOf(KeyGenerator.PARTITION_SEPARATOR));
if (userPartition != null && userPartition.length() > 0) {
// A root partition was provided by the user. Must validate it. The first component should be a domain key and the any following
// tokens should be a valid KSS.
userPartition = userPartition.trim();
if (userPartition.endsWith(KeyGenerator.PARTITION_SEPARATOR) || userPartition.startsWith(KeyGenerator.PARTITION_SEPARATOR))
throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.MalformedKey", userPartition));
StringTokenizer tokenizer = new StringTokenizer(userPartition.toLowerCase(), KeyGenerator.PARTITION_SEPARATOR);
for(int count = 0; tokenizer.hasMoreTokens(); count++) {
String nextToken = tokenizer.nextToken();
if (count == 0) {
if(!ValidateUDDIKey.isValidDomainKey(nextToken))
throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.MalformedKey", userPartition));
}
else {
if (!ValidateUDDIKey.isValidKSS(nextToken))
throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.MalformedKey", userPartition));
}
}
// If the user-supplied root partition checks out, we can use that.
result = KeyGenerator.UDDI_SCHEME + KeyGenerator.PARTITION_SEPARATOR + userPartition;
}
return result;
}
public static String getNodeId(String userNodeId, String rootPartition) throws DispositionReportFaultMessage {
String result = userNodeId;
if (result == null || result.length() == 0) {
result = rootPartition + KeyGenerator.PARTITION_SEPARATOR + UUID.randomUUID();
}
else {
ValidateUDDIKey.validateUDDIv3Key(result);
String keyPartition = result.substring(0, result.lastIndexOf(KeyGenerator.PARTITION_SEPARATOR));
if (!rootPartition.equalsIgnoreCase(keyPartition))
throw new KeyUnavailableException(new ErrorMessage("errors.keyunavailable.BadPartition", userNodeId));
}
return result;
}
public static org.uddi.api_v3.BusinessEntity getNodeBusinessEntity(String businessKey) throws DispositionReportFaultMessage {
UDDIInquiryImpl inquiry = new UDDIInquiryImpl();
org.uddi.api_v3.GetBusinessDetail gbd = new org.uddi.api_v3.GetBusinessDetail();
gbd.getBusinessKey().add(businessKey);
org.uddi.api_v3.BusinessDetail bd = inquiry.getBusinessDetail(gbd);
if (bd != null) {
List<org.uddi.api_v3.BusinessEntity> beList = bd.getBusinessEntity();
if (beList != null && beList.size() > 0)
return beList.get(0);
}
return new org.uddi.api_v3.BusinessEntity();
}
private static String installRootBusinessEntity(EntityManager em, org.uddi.api_v3.BusinessEntity rootBusinessEntity, UddiEntityPublisher rootPublisher, String rootPartition)
throws JAXBException, DispositionReportFaultMessage, IOException {
validateRootBusinessEntity(rootBusinessEntity, rootPublisher, rootPartition);
org.apache.juddi.model.BusinessEntity modelBusinessEntity = new org.apache.juddi.model.BusinessEntity();
MappingApiToModel.mapBusinessEntity(rootBusinessEntity, modelBusinessEntity);
modelBusinessEntity.setAuthorizedName(rootPublisher.getAuthorizedName());
Date now = new Date();
modelBusinessEntity.setCreated(now);
modelBusinessEntity.setModified(now);
modelBusinessEntity.setModifiedIncludingChildren(now);
modelBusinessEntity.setNodeId(modelBusinessEntity.getEntityKey());
for (org.apache.juddi.model.BusinessService service : modelBusinessEntity.getBusinessServices()) {
service.setAuthorizedName(rootPublisher.getAuthorizedName());
service.setCreated(now);
service.setModified(now);
service.setModifiedIncludingChildren(now);
service.setNodeId(modelBusinessEntity.getEntityKey());
for (org.apache.juddi.model.BindingTemplate binding : service.getBindingTemplates()) {
binding.setAuthorizedName(rootPublisher.getAuthorizedName());
binding.setCreated(now);
binding.setModified(now);
binding.setModifiedIncludingChildren(now);
binding.setNodeId(modelBusinessEntity.getEntityKey());
}
}
em.persist(modelBusinessEntity);
return modelBusinessEntity.getEntityKey();
}
// A watered down version of ValidatePublish's validateBusinessEntity, designed for the specific condition that this is run upon the initial
// jUDDI install.
private static void validateRootBusinessEntity(org.uddi.api_v3.BusinessEntity businessEntity, UddiEntityPublisher rootPublisher, String rootPartition)
throws DispositionReportFaultMessage {
// A supplied businessService can't be null
if (businessEntity == null)
throw new ValueNotAllowedException(new ErrorMessage("errors.businessentity.NullInput"));
// The business key should already be set to the previously calculated and validated nodeId. This validation is unnecessary but kept for
// symmetry with the other entity validations.
String entityKey = businessEntity.getBusinessKey();
if (entityKey == null || entityKey.length() == 0) {
entityKey = rootPartition + KeyGenerator.PARTITION_SEPARATOR + UUID.randomUUID();
businessEntity.setBusinessKey(entityKey);
}
else {
ValidateUDDIKey.validateUDDIv3Key(entityKey);
String keyPartition = entityKey.substring(0, entityKey.lastIndexOf(KeyGenerator.PARTITION_SEPARATOR));
if (!rootPartition.equalsIgnoreCase(keyPartition))
throw new KeyUnavailableException(new ErrorMessage("errors.keyunavailable.BadPartition", entityKey));
}
ValidatePublish validatePublish = new ValidatePublish(rootPublisher);
validatePublish.validateNames(businessEntity.getName());
validatePublish.validateDiscoveryUrls(businessEntity.getDiscoveryURLs());
validatePublish.validateContacts(businessEntity.getContacts());
validatePublish.validateCategoryBag(businessEntity.getCategoryBag());
validatePublish.validateIdentifierBag(businessEntity.getIdentifierBag());
org.uddi.api_v3.BusinessServices businessServices = businessEntity.getBusinessServices();
if (businessServices != null) {
List<org.uddi.api_v3.BusinessService> businessServiceList = businessServices.getBusinessService();
if (businessServiceList == null || businessServiceList.size() == 0)
throw new ValueNotAllowedException(new ErrorMessage("errors.businessservices.NoInput"));
for (org.uddi.api_v3.BusinessService businessService : businessServiceList) {
validateRootBusinessService(businessService, businessEntity, rootPublisher, rootPartition);
}
}
}
// A watered down version of ValidatePublish's validateBusinessService, designed for the specific condition that this is run upon the initial
// jUDDI install.
private static void validateRootBusinessService(org.uddi.api_v3.BusinessService businessService, org.uddi.api_v3.BusinessEntity parent, UddiEntityPublisher rootPublisher, String rootPartition)
throws DispositionReportFaultMessage {
// A supplied businessService can't be null
if (businessService == null)
throw new ValueNotAllowedException(new ErrorMessage("errors.businessservice.NullInput"));
// A business key doesn't have to be provided, but if it is, it should match the parent business's key
String parentKey = businessService.getBusinessKey();
if (parentKey != null && parentKey.length()> 0) {
if (!parentKey.equalsIgnoreCase(parent.getBusinessKey()))
throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.ParentBusinessNotFound", parentKey));
}
// Retrieve the service's passed key
String entityKey = businessService.getServiceKey();
if (entityKey == null || entityKey.length() == 0) {
entityKey = rootPartition + KeyGenerator.PARTITION_SEPARATOR + UUID.randomUUID();
businessService.setServiceKey(entityKey);
}
else {
ValidateUDDIKey.validateUDDIv3Key(entityKey);
String keyPartition = entityKey.substring(0, entityKey.lastIndexOf(KeyGenerator.PARTITION_SEPARATOR));
if (!rootPartition.equalsIgnoreCase(keyPartition))
throw new KeyUnavailableException(new ErrorMessage("errors.keyunavailable.BadPartition", entityKey));
}
ValidatePublish validatePublish = new ValidatePublish(rootPublisher);
validatePublish.validateNames(businessService.getName());
validatePublish.validateCategoryBag(businessService.getCategoryBag());
org.uddi.api_v3.BindingTemplates bindingTemplates = businessService.getBindingTemplates();
if (bindingTemplates != null) {
List<org.uddi.api_v3.BindingTemplate> bindingTemplateList = bindingTemplates.getBindingTemplate();
if (bindingTemplateList == null || bindingTemplateList.size() == 0)
throw new ValueNotAllowedException(new ErrorMessage("errors.bindingtemplates.NoInput"));
for (org.uddi.api_v3.BindingTemplate bindingTemplate : bindingTemplateList) {
validateRootBindingTemplate(bindingTemplate, businessService, rootPublisher, rootPartition);
}
}
}
// A watered down version of ValidatePublish's validatBindingTemplate, designed for the specific condition that this is run upon the initial
// jUDDI install.
private static void validateRootBindingTemplate(org.uddi.api_v3.BindingTemplate bindingTemplate, org.uddi.api_v3.BusinessService parent, UddiEntityPublisher rootPublisher, String rootPartition)
throws DispositionReportFaultMessage {
// A supplied businessService can't be null
if (bindingTemplate == null)
throw new ValueNotAllowedException(new ErrorMessage("errors.bindingtemplate.NullInput"));
// A service key doesn't have to be provided, but if it is, it should match the parent service's key
String parentKey = bindingTemplate.getServiceKey();
if (parentKey != null && parentKey.length()> 0) {
if (!parentKey.equalsIgnoreCase(parent.getServiceKey()))
throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.ParentServiceNotFound", parentKey));
}
// Retrieve the service's passed key
String entityKey = bindingTemplate.getBindingKey();
if (entityKey == null || entityKey.length() == 0) {
entityKey = rootPartition + KeyGenerator.PARTITION_SEPARATOR + UUID.randomUUID();
bindingTemplate.setBindingKey(entityKey);
}
else {
ValidateUDDIKey.validateUDDIv3Key(entityKey);
String keyPartition = entityKey.substring(0, entityKey.lastIndexOf(KeyGenerator.PARTITION_SEPARATOR));
if (!rootPartition.equalsIgnoreCase(keyPartition))
throw new KeyUnavailableException(new ErrorMessage("errors.keyunavailable.BadPartition", entityKey));
}
ValidatePublish validatePublish = new ValidatePublish(rootPublisher);
validatePublish.validateCategoryBag(bindingTemplate.getCategoryBag());
validatePublish.validateTModelInstanceDetails(bindingTemplate.getTModelInstanceDetails());
}
private static void installUDDITModels(EntityManager em, String resource, UddiEntityPublisher publisher, String nodeId)
throws JAXBException, DispositionReportFaultMessage, IOException {
SaveTModel apiSaveTModel = (SaveTModel)buildEntityFromDoc(resource, "org.uddi.api_v3");
installTModels(em, apiSaveTModel.getTModel(), publisher, nodeId);
}
private static UddiEntityPublisher installPublisher(EntityManager em, String resource)
throws JAXBException, DispositionReportFaultMessage, IOException {
org.apache.juddi.api.datatype.Publisher apiPub = (org.apache.juddi.api.datatype.Publisher)buildEntityFromDoc(resource, "org.apache.juddi.api.datatype");
org.apache.juddi.model.Publisher modelPub = new org.apache.juddi.model.Publisher();
MappingApiToModel.mapPublisher(apiPub, modelPub);
em.persist(modelPub);
return modelPub;
}
private static void installTModels(EntityManager em, List<org.uddi.api_v3.TModel> apiTModelList, UddiEntityPublisher publisher, String nodeId) throws DispositionReportFaultMessage {
if (apiTModelList != null) {
for (org.uddi.api_v3.TModel apiTModel : apiTModelList) {
String tModelKey = apiTModel.getTModelKey();
if (tModelKey.toUpperCase().endsWith(KeyGenerator.KEYGENERATOR_SUFFIX.toUpperCase())) {
installPublisherKeyGen(em, apiTModel, publisher, nodeId);
}
else {
org.apache.juddi.model.Tmodel modelTModel = new org.apache.juddi.model.Tmodel();
MappingApiToModel.mapTModel(apiTModel, modelTModel);
modelTModel.setAuthorizedName(publisher.getAuthorizedName());
Date now = new Date();
modelTModel.setCreated(now);
modelTModel.setModified(now);
modelTModel.setModifiedIncludingChildren(now);
modelTModel.setNodeId(nodeId);
em.persist(modelTModel);
}
}
}
}
private static void installRootPublisherKeyGen(EntityManager em, TModel rootTModelKeyGen, String rootPartition, UddiEntityPublisher publisher, String nodeId)
throws DispositionReportFaultMessage {
rootTModelKeyGen.setTModelKey(rootPartition + KeyGenerator.PARTITION_SEPARATOR + KeyGenerator.KEYGENERATOR_SUFFIX);
installPublisherKeyGen(em, rootTModelKeyGen, publisher, nodeId);
}
private static void installPublisherKeyGen(EntityManager em, TModel apiTModel, UddiEntityPublisher publisher, String nodeId) throws DispositionReportFaultMessage {
org.apache.juddi.model.Tmodel modelTModel = new org.apache.juddi.model.Tmodel();
MappingApiToModel.mapTModel(apiTModel, modelTModel);
modelTModel.setAuthorizedName(publisher.getAuthorizedName());
Date now = new Date();
modelTModel.setCreated(now);
modelTModel.setModified(now);
modelTModel.setModifiedIncludingChildren(now);
modelTModel.setNodeId(nodeId);
em.persist(modelTModel);
}
private static Object buildEntityFromDoc(String resource, String thePackage) throws JAXBException, IOException {
InputStream resourceStream = null;
URL url = Thread.currentThread().getContextClassLoader().getResource(resource);
if (url != null)
resourceStream = url.openStream();
if (resourceStream == null) {
resourceStream = new FileInputStream(new File(resource));
}
JAXBContext jc = JAXBContext.newInstance(thePackage);
Unmarshaller unmarshaller = jc.createUnmarshaller();
Object obj = ((JAXBElement<?>)unmarshaller.unmarshal(resourceStream)).getValue();
return obj;
}
}
| false | true | public static void install(String srcDir, String userPartition, boolean reloadConfig) throws JAXBException, DispositionReportFaultMessage, IOException {
if (srcDir != null) {
if (srcDir.endsWith("\\") || srcDir.endsWith("/")) {
// Do nothing
}
else
srcDir = srcDir + "\\";
}
else
srcDir = "";
EntityManager em = PersistenceManager.getEntityManager();
EntityTransaction tx = em.getTransaction();
UddiEntityPublisher rootPublisher = null;
UddiEntityPublisher uddiPublisher = null;
try {
tx.begin();
if (alreadyInstalled(em))
throw new FatalErrorException(new ErrorMessage("errors.install.AlreadyInstalled"));
TModel rootTModelKeyGen = (TModel)buildEntityFromDoc(JUDDI_INSTALL_DATA_DIR + FILE_ROOT_TMODELKEYGEN, "org.uddi.api_v3");
org.uddi.api_v3.BusinessEntity rootBusinessEntity = (org.uddi.api_v3.BusinessEntity)buildEntityFromDoc(srcDir + FILE_ROOT_BUSINESSENTITY, "org.uddi.api_v3");
String rootPartition = getRootPartition(rootTModelKeyGen, userPartition);
String nodeId = getNodeId(rootBusinessEntity.getBusinessKey(), rootPartition);
rootPublisher = installPublisher(em, JUDDI_INSTALL_DATA_DIR + FILE_ROOT_PUBLISHER);
uddiPublisher = installPublisher(em, JUDDI_INSTALL_DATA_DIR + FILE_UDDI_PUBLISHER);
// TODO: These do not belong here
// Inserting 2 test publishers
installPublisher(em, JUDDI_INSTALL_DATA_DIR + FILE_JOE_PUBLISHER);
installPublisher(em, JUDDI_INSTALL_DATA_DIR + FILE_SSYNDICATOR);
installRootPublisherKeyGen(em, rootTModelKeyGen, rootPartition, rootPublisher, nodeId);
rootBusinessEntity.setBusinessKey(nodeId);
installRootBusinessEntity(em, rootBusinessEntity, rootPublisher, rootPartition);
installUDDITModels(em, JUDDI_INSTALL_DATA_DIR + FILE_UDDI_TMODELS, uddiPublisher, nodeId);
tx.commit();
}
catch(DispositionReportFaultMessage dr) {
log .error(dr.getMessage(),dr);
tx.rollback();
throw dr;
}
catch (JAXBException je) {
log .error(je.getMessage(),je);
tx.rollback();
throw je;
}
catch (IOException ie) {
log .error(ie.getMessage(),ie);
tx.rollback();
throw ie;
}
finally {
if (em.isOpen()) {
em.close();
}
}
// Now that all necessary persistent entities are loaded, the configuration must be reloaded to be sure all properties are set.
if (reloadConfig) {
try { AppConfig.reloadConfig(); } catch (ConfigurationException ce) { log.error(ce.getMessage(), ce); }
}
}
| public static void install(String srcDir, String userPartition, boolean reloadConfig) throws JAXBException, DispositionReportFaultMessage, IOException {
if (srcDir != null) {
if (srcDir.endsWith(java.io.File.separator)) {
// Do nothing
}
else
srcDir = srcDir + java.io.File.separator;
}
else
srcDir = "";
EntityManager em = PersistenceManager.getEntityManager();
EntityTransaction tx = em.getTransaction();
UddiEntityPublisher rootPublisher = null;
UddiEntityPublisher uddiPublisher = null;
try {
tx.begin();
if (alreadyInstalled(em))
throw new FatalErrorException(new ErrorMessage("errors.install.AlreadyInstalled"));
TModel rootTModelKeyGen = (TModel)buildEntityFromDoc(JUDDI_INSTALL_DATA_DIR + FILE_ROOT_TMODELKEYGEN, "org.uddi.api_v3");
org.uddi.api_v3.BusinessEntity rootBusinessEntity = (org.uddi.api_v3.BusinessEntity)buildEntityFromDoc(srcDir + FILE_ROOT_BUSINESSENTITY, "org.uddi.api_v3");
String rootPartition = getRootPartition(rootTModelKeyGen, userPartition);
String nodeId = getNodeId(rootBusinessEntity.getBusinessKey(), rootPartition);
rootPublisher = installPublisher(em, JUDDI_INSTALL_DATA_DIR + FILE_ROOT_PUBLISHER);
uddiPublisher = installPublisher(em, JUDDI_INSTALL_DATA_DIR + FILE_UDDI_PUBLISHER);
// TODO: These do not belong here
// Inserting 2 test publishers
installPublisher(em, JUDDI_INSTALL_DATA_DIR + FILE_JOE_PUBLISHER);
installPublisher(em, JUDDI_INSTALL_DATA_DIR + FILE_SSYNDICATOR);
installRootPublisherKeyGen(em, rootTModelKeyGen, rootPartition, rootPublisher, nodeId);
rootBusinessEntity.setBusinessKey(nodeId);
installRootBusinessEntity(em, rootBusinessEntity, rootPublisher, rootPartition);
installUDDITModels(em, JUDDI_INSTALL_DATA_DIR + FILE_UDDI_TMODELS, uddiPublisher, nodeId);
tx.commit();
}
catch(DispositionReportFaultMessage dr) {
log .error(dr.getMessage(),dr);
tx.rollback();
throw dr;
}
catch (JAXBException je) {
log .error(je.getMessage(),je);
tx.rollback();
throw je;
}
catch (IOException ie) {
log .error(ie.getMessage(),ie);
tx.rollback();
throw ie;
}
finally {
if (em.isOpen()) {
em.close();
}
}
// Now that all necessary persistent entities are loaded, the configuration must be reloaded to be sure all properties are set.
if (reloadConfig) {
try { AppConfig.reloadConfig(); } catch (ConfigurationException ce) { log.error(ce.getMessage(), ce); }
}
}
|
diff --git a/src/main/java/mikera/arrayz/AbstractArray.java b/src/main/java/mikera/arrayz/AbstractArray.java
index b4640104..9baef22b 100644
--- a/src/main/java/mikera/arrayz/AbstractArray.java
+++ b/src/main/java/mikera/arrayz/AbstractArray.java
@@ -1,183 +1,183 @@
package mikera.arrayz;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import mikera.vectorz.AScalar;
import mikera.vectorz.Ops;
import mikera.vectorz.Tools;
import mikera.vectorz.util.VectorzException;
/**
* Base class for INDArray implementations
* @author Mike
* @param <T>
*
*/
public abstract class AbstractArray<T> implements INDArray, Iterable<T> {
public double get() {
return get(new int[0]);
}
public double get(int x) {
return get(new int[] {x});
}
public double get(int x, int y) {
return get(new int[] {x,y});
}
public INDArray innerProduct(INDArray a) {
if (a instanceof AScalar) {
INDArray c=clone();
c.scale(((AScalar)a).get());
return c;
}
throw new UnsupportedOperationException();
}
public INDArray outerProduct(INDArray a) {
ArrayList<INDArray> al=new ArrayList<INDArray>();
for (Object s:this) {
if (s instanceof INDArray) {
al.add(((INDArray)s).outerProduct(a));
} else {
double x=Tools.toDouble(s);
INDArray sa=a.clone();
sa.scale(x);
al.add(sa);
}
}
return Arrayz.create(al);
}
public void set(double value) {
set(new int[0],value);
}
public void set(int x, double value) {
set(new int[] {x},value);
}
public void set(int x, int y, double value) {
set(new int[] {x,y},value);
}
public void set (INDArray a) {
int tdims=this.dimensionality();
int adims=a.dimensionality();
if (adims<tdims) {
int sc=getShape()[0];
for (int i=0; i<sc; i++) {
INDArray s=slice(i);
s.set(a);
}
} else if (adims==tdims) {
int sc=sliceCount();
for (int i=0; i<sc; i++) {
INDArray s=slice(i);
s.set(a.slice(i));
}
} else {
- throw new IllegalArgumentException("Can't set array to value to higher dimensionality");
+ throw new IllegalArgumentException("Can't set array to value of higher dimensionality");
}
}
public void set(Object o) {
if (o instanceof INDArray) {set((INDArray)o); return;}
if (o instanceof Number) {
set(((Number)o).doubleValue()); return;
}
if (o instanceof Iterable<?>) {
int i=0;
for (Object ob: ((Iterable<?>)o)) {
slice(i).set(ob);
}
}
throw new UnsupportedOperationException("Can't set to value for "+o.getClass().toString());
}
public void square() {
applyOp(Ops.SQUARE);
}
@Override
public Iterator<T> iterator() {
return new SliceIterator<T>(this);
}
public boolean equals(Object o) {
if (!(o instanceof INDArray)) return false;
return equals((INDArray)o);
}
@Override
public int hashCode() {
return asVector().hashCode();
}
public AbstractArray<?> clone() {
try {
return (AbstractArray<?>)super.clone();
} catch (CloneNotSupportedException e) {
throw new VectorzException("AbstractArray clone failed");
}
}
@Override
public void add(INDArray a) {
int n=sliceCount();
int na=a.sliceCount();
int dims=dimensionality();
int adims=a.dimensionality();
if (dims==adims) {
if (n!=na) throw new VectorzException("Non-matching dimensions");
for (int i=0; i<n; i++) {
slice(i).add(a.slice(i));
}
} else if (adims<dims) {
for (int i=0; i<n; i++) {
slice(i).add(a);
}
} else {
throw new VectorzException("Cannot add array of greater dimensionality");
}
}
@Override
public void sub(INDArray a) {
int n=sliceCount();
int na=a.sliceCount();
int dims=dimensionality();
int adims=a.dimensionality();
if (dims==adims) {
if (n!=na) throw new VectorzException("Non-matching dimensions");
for (int i=0; i<n; i++) {
slice(i).sub(a.slice(i));
}
} else if (adims<dims) {
for (int i=0; i<n; i++) {
slice(i).sub(a);
}
} else {
throw new VectorzException("Cannot add array of greater dimensionality");
}
}
@Override
public INDArray reshape(int... targetShape) {
return Arrayz.createFromVector(asVector(), targetShape);
}
@Override
public INDArray broadcast(int... targetShape) {
int dims=dimensionality();
int tdims=targetShape.length;
if (tdims<dims) {
throw new VectorzException("Can't broadcast to a smaller shape!");
} else if (dims==tdims) {
return this;
} else {
int n=targetShape[0];
INDArray s=broadcast(Arrays.copyOfRange(targetShape, 1, tdims));
return SliceArray.repeat(s,n);
}
}
}
| true | true | public void set (INDArray a) {
int tdims=this.dimensionality();
int adims=a.dimensionality();
if (adims<tdims) {
int sc=getShape()[0];
for (int i=0; i<sc; i++) {
INDArray s=slice(i);
s.set(a);
}
} else if (adims==tdims) {
int sc=sliceCount();
for (int i=0; i<sc; i++) {
INDArray s=slice(i);
s.set(a.slice(i));
}
} else {
throw new IllegalArgumentException("Can't set array to value to higher dimensionality");
}
}
| public void set (INDArray a) {
int tdims=this.dimensionality();
int adims=a.dimensionality();
if (adims<tdims) {
int sc=getShape()[0];
for (int i=0; i<sc; i++) {
INDArray s=slice(i);
s.set(a);
}
} else if (adims==tdims) {
int sc=sliceCount();
for (int i=0; i<sc; i++) {
INDArray s=slice(i);
s.set(a.slice(i));
}
} else {
throw new IllegalArgumentException("Can't set array to value of higher dimensionality");
}
}
|
diff --git a/core/carrot2-util-attribute/src/org/carrot2/util/attribute/AttributeBinder.java b/core/carrot2-util-attribute/src/org/carrot2/util/attribute/AttributeBinder.java
index 5e8a65ed3..767369405 100644
--- a/core/carrot2-util-attribute/src/org/carrot2/util/attribute/AttributeBinder.java
+++ b/core/carrot2-util-attribute/src/org/carrot2/util/attribute/AttributeBinder.java
@@ -1,830 +1,832 @@
/*
* Carrot2 project.
*
* Copyright (C) 2002-2010, Dawid Weiss, Stanisław Osiński.
* All rights reserved.
*
* Refer to the full license file "carrot2.LICENSE"
* in the root folder of the repository checkout or at:
* http://www.carrot2.org/carrot2.LICENSE
*/
package org.carrot2.util.attribute;
import java.io.File;
import java.lang.annotation.Annotation;
import java.lang.reflect.*;
import java.util.*;
import org.apache.commons.lang.ClassUtils;
import org.carrot2.util.*;
import org.carrot2.util.attribute.constraint.*;
import org.carrot2.util.resource.IResource;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.common.collect.*;
/**
* Provides methods for binding (setting and collecting) values of attributes defined by
* the {@link Attribute} annotation.
*/
public class AttributeBinder
{
/** Consistency checks to be applied before binding */
private final static ConsistencyCheck [] CONSISTENCY_CHECKS = new ConsistencyCheck []
{
new ConsistencyCheckRequiredAnnotations(),
new ConsistencyCheckImplementingClasses()
};
/**
* Performs binding (setting or collecting) of {@link Attribute} values on the
* provided <code>instance</code>. The direction of binding, i.e. whether attributes
* will be set or collected from the <code>object</code> depends on the provided
* <code>bindingDirectionAnnotation</code>, which can be either {@link Input} or
* {@link Output} for setting and collecting attribute values of the
* <code>object</code>, respectively.
* <p>
* Binding will be performed for all attributes of the provided <code>object</code>,
* no matter where in the <code>object</code>'s hierarchy the attribute is declared.
* Binding will recursively descend into all fields of the <code>object</code> whose
* types are marked with {@link Bindable}, no matter whether these fields are
* attributes or not.
* <p>
* Keys of the <code>values</code> map are interpreted as attribute keys as defined by
* {@link Attribute#key()}. When setting attribute values, the map must contain non-
* <code>null</code> mappings for all {@link Required} attributes that have not yet
* been set on the <code>object</code> to a non-<code>null</code> value. Otherwise an
* {@link AttributeBindingException} will be thrown. If the map has no mapping for
* some non-{@link Required} attribute, the value of that attribute will not be
* changed. However, if the map contains a <code>null</code> mapping for some non-
* {@link Required} attribute, the value that attribute will be set to
* <code>null</code>.
* <p>
* When setting attributes, values will be transferred from the map without any
* conversion with two exceptions.
* <ol>
* <li>If the type of the value is {@link String} and the type of the attribute field
* is not {@link String}, the {@link AttributeTransformerFromString} will be applied
* to the value prior to transferring it to the attribute field. If you want to bypass
* this conversion, use
* {@link #bind(Object, IAttributeBinderAction[], Class, Class...)}.</li>
* <li>If the type of the attribute field is not {@link Class} and the corresponding
* value in the <code>values</code> map is of type {@link Class}, an attempt will be
* made to coerce the class to a corresponding instance by calling its parameterless
* constructor. If the created type is {@link Bindable}, an attempt will also be made
* to bind attributes of the newly created object using the <code>values</code> map,
* current <code>bindingDirectionAnnotation</code> and
* <code>filteringAnnotations</code>.</li>
* </ol>
* <p>
* Before value of an attribute is set, the new value is checked against all
* constraints defined for the attribute and must meet all these constraints.
* Otherwise, the {@link ConstraintViolationException} will be thrown.
* <p>
*
* @param object the object to set or collect attributes from. The type of the
* provided object must be annotated with {@link Bindable}.
* @param values the values of {@link Input} attributes to be set or a placeholder for
* {@link Output} attributes to be collected. If attribute values are to be
* collected, the provided Map must be modifiable.
* @param bindingDirectionAnnotation {@link Input} if attribute values are to be set
* on the provided <code>object</code>, or {@link Output} if attribute
* values are to be collected from the <code>object</code>.
* @param filteringAnnotations additional domain-specific annotations that the
* attribute fields must have in order to be bound. This parameter can be
* used to selectively bind different set of attributes depending, e.g. on
* the life cycle of the <code>object</code>.
* @return entries from the <code>values</code> map that did not get bound to any of
* the {@link Input} attributes.
* @throws InstantiationException if coercion of a class attribute value to an
* instance fails, e.g. because the parameterless constructor is not
* present/ visible.
* @throws AttributeBindingException if in the <code>values</code> map there are no or
* <code>null</code> values provided for one or more {@link Required}
* attributes.
* @throws AttributeBindingException reflection-based setting or reading field values
* fails.
* @throws IllegalArgumentException if <code>bindingDirectionAnnotation</code> is
* different from {@link Input} or {@link Output}.
* @throws IllegalArgumentException if <code>object</code>'s type is not
* {@link Bindable}.
* @throws IllegalArgumentException for debugging purposes, if an attribute field is
* found that is missing some of the required annotations.
* @throws UnsupportedOperationException if an attempt is made to bind values of
* attributes with circular references.
*/
public static <T> Map<String, Object> bind(T object, Map<String, Object> values,
Class<? extends Annotation> bindingDirectionAnnotation,
Class<? extends Annotation>... filteringAnnotations)
throws InstantiationException, AttributeBindingException
{
return bind(object, values, true, bindingDirectionAnnotation,
filteringAnnotations);
}
/**
* A version of {@link #bind(Object, Map, Class, Class...)} that can optionally skip
* {@link Required} attribute checking. For experts only.
*/
public static <T> Map<String, Object> bind(T object, Map<String, Object> values,
boolean checkRequired, Class<? extends Annotation> bindingDirectionAnnotation,
Class<? extends Annotation>... filteringAnnotations)
throws InstantiationException, AttributeBindingException
{
return bind(object, values, checkRequired, bindingDirectionAnnotation,
filteringAnnotations.length > 0 ? new FilteringAnnotationsPredicate(
filteringAnnotations) : Predicates.<Field> alwaysTrue());
}
/**
* A version of {@link #bind(Object, Map, boolean, Class, Class...)} with a
* {@link Predicate} instead of filtering annotations. For experts only.
*/
public static <T> Map<String, Object> bind(T object, Map<String, Object> values,
boolean checkRequired, Class<? extends Annotation> bindingDirectionAnnotation,
Predicate<Field> predicate) throws InstantiationException,
AttributeBindingException
{
final AttributeBinderActionBind attributeBinderActionBind = new AttributeBinderActionBind(
Input.class, values, checkRequired, AttributeTransformerFromString.INSTANCE);
final IAttributeBinderAction [] actions = new IAttributeBinderAction []
{
attributeBinderActionBind,
new AttributeBinderActionCollect(Output.class, values),
};
bind(object, actions, bindingDirectionAnnotation, predicate);
return attributeBinderActionBind.remainingValues;
}
/**
* A complementary version of the {@link #bind(Object, Map, Class, Class...)} method.
* This method <strong>collects</strong> values of {@link Input} attributes and
* <strong>sets</strong> values of {@link Output} attributes.
*
* @return entries from the <code>values</code> map that did not get bound to any of
* the {@link Output} attributes.
*/
public static <T> Map<String, Object> unbind(T object, Map<String, Object> values,
Class<? extends Annotation> bindingDirectionAnnotation,
Class<? extends Annotation>... filteringAnnotations)
throws InstantiationException, AttributeBindingException
{
final AttributeBinderActionBind attributeBinderActionBind = new AttributeBinderActionBind(
Output.class, values, true, AttributeTransformerFromString.INSTANCE);
final IAttributeBinderAction [] actions = new IAttributeBinderAction []
{
new AttributeBinderActionCollect(Input.class, values),
attributeBinderActionBind,
};
bind(object, actions, bindingDirectionAnnotation, filteringAnnotations);
return attributeBinderActionBind.remainingValues;
}
/**
* A more flexible version of {@link #bind(Object, Map, Class, Class...)} that accepts
* custom {@link IAttributeBinderAction}s. For experts only.
*/
public static <T> void bind(T object,
IAttributeBinderAction [] attributeBinderActions,
Class<? extends Annotation> bindingDirectionAnnotation,
Class<? extends Annotation>... filteringAnnotations)
throws InstantiationException, AttributeBindingException
{
bind(object, attributeBinderActions, bindingDirectionAnnotation,
filteringAnnotations.length > 0 ? new FilteringAnnotationsPredicate(
filteringAnnotations) : Predicates.<Field> alwaysTrue());
}
/**
* A more flexible version of {@link #bind(Object, Map, Class, Class...)} that accepts
* custom {@link IAttributeBinderAction}s. For experts only.
*/
public static <T> void bind(T object,
IAttributeBinderAction [] attributeBinderActions,
Class<? extends Annotation> bindingDirectionAnnotation, Predicate<Field> predicate)
throws InstantiationException, AttributeBindingException
{
bind(new HashSet<Object>(), new BindingTracker(), 0, object,
attributeBinderActions, bindingDirectionAnnotation, predicate);
}
/**
* A predicate that evaluates to <code>true</code> if the attribute is annotated with
* at least one of the provided annotations.
*/
public static class FilteringAnnotationsPredicate implements Predicate<Field>
{
private final Class<? extends Annotation> [] filteringAnnotations;
public FilteringAnnotationsPredicate(
Class<? extends Annotation> [] filteringAnnotations)
{
this.filteringAnnotations = filteringAnnotations;
}
public boolean apply(Field field)
{
for (Class<? extends Annotation> annotation : filteringAnnotations)
{
if (field.getAnnotation(annotation) != null)
{
return true;
}
}
return false;
}
}
/**
* Internal implementation that tracks object that have already been bound.
*/
static <T> void bind(Set<Object> boundObjects, BindingTracker bindingTracker,
int level, T object, IAttributeBinderAction [] attributeBinderActions,
Class<? extends Annotation> bindingDirectionAnnotation, Predicate<Field> predicate)
throws InstantiationException, AttributeBindingException
{
// Binding direction can be either @Input or @Output
if (!Input.class.equals(bindingDirectionAnnotation)
&& !Output.class.equals(bindingDirectionAnnotation))
{
throw new IllegalArgumentException(
"bindingDirectionAnnotation must either be "
+ Input.class.getSimpleName() + " or " + Output.class.getSimpleName());
}
// We can only bind values on classes that are @Bindable
if (object.getClass().getAnnotation(Bindable.class) == null)
{
throw new IllegalArgumentException("Class is not bindable: "
+ object.getClass().getName());
}
// For keeping track of circular references
boundObjects.add(object);
// Get all fields (including those from bindable super classes)
final Collection<Field> fieldSet = BindableUtils
.getFieldsFromBindableHierarchy(object.getClass());
for (final Field field : fieldSet)
{
final String key = BindableUtils.getKey(field);
Object value = null;
// Get the @Bindable value to perform a recursive call on it later on
try
{
field.setAccessible(true);
value = field.get(object);
}
catch (final Exception e)
{
throw new AttributeBindingException(key, "Could not get field value "
+ object.getClass().getName() + "#" + field.getName());
}
// Apply consistency checks
boolean consistent = true;
for (int i = 0; consistent && i < CONSISTENCY_CHECKS.length; i++)
{
consistent &= CONSISTENCY_CHECKS[i].check(field,
bindingDirectionAnnotation);
}
// We skip fields that do not have all the required annotations
if (consistent && predicate.apply(field))
{
try
{
// Apply binding actions provided
for (int i = 0; i < attributeBinderActions.length; i++)
{
attributeBinderActions[i].performAction(bindingTracker, level,
object, key, field, value, bindingDirectionAnnotation,
predicate);
}
// The value may have changed as a result of binding, so we need
// to re-read it here. Otherwise, the recursive descent below
// would bind values to an abandoned reference obtained at the
// top of this method.
value = field.get(object);
}
catch (ConstraintViolationException e)
{
throw new AttributeBindingException(key, e.getMessage(), e);
}
catch (AttributeBindingException e)
{
// Rethrow the original binding exception.
throw e;
}
catch (Exception e)
{
throw new AttributeBindingException(key, "Could not get field value "
+ object.getClass().getName() + "#" + field.getName(), e);
}
}
// If value is not null and its class is @Bindable, we must descend into it
if (value != null && value.getClass().getAnnotation(Bindable.class) != null)
{
// Check for circular references
if (boundObjects.contains(value))
{
throw new UnsupportedOperationException(
"Circular references are not supported");
}
// Recursively descend into other types.
bind(boundObjects, bindingTracker, level + 1, value,
attributeBinderActions, bindingDirectionAnnotation, predicate);
}
}
}
/**
* An action to be applied during attribute binding.
*/
public static interface IAttributeBinderAction
{
public <T> void performAction(BindingTracker bindingTracker, int level, T object,
String key, Field field, Object value,
Class<? extends Annotation> bindingDirectionAnnotation,
Predicate<Field> predicate) throws InstantiationException;
}
/**
* Transforms attribute values.
*/
public static interface IAttributeTransformer
{
public Object transform(Object value, String key, Field field,
Class<? extends Annotation> bindingDirectionAnnotation);
}
/**
* Transforms {@link String} attribute values to the types required by the target
* field by:
* <ol>
* <li>Leaving non-{@link String} typed values unchanged.</li>
* <li>Looking for a static <code>valueOf(String)</code> in the target type and using
* it for conversion.</li>
* <li>If the method is not available, trying to load a class named as the value of
* the attribute, so that this class can be further coerced to the class instance.</li>
* <li>If the class cannot be loaded, leaving the the value unchanged.</li>
* </ol>
*/
public static class AttributeTransformerFromString implements IAttributeTransformer
{
/** Shared instance of the transformer. */
public static final AttributeTransformerFromString INSTANCE = new AttributeTransformerFromString();
/**
* Private constructor, use {{@link #INSTANCE}.
*/
private AttributeTransformerFromString()
{
}
public Object transform(Object value, String key, Field field,
Class<? extends Annotation> bindingDirectionAnnotation)
{
if (!(value instanceof String))
{
return value;
}
final String stringValue = (String) value;
final Class<?> fieldType = ClassUtils.primitiveToWrapper(field.getType());
if (String.class.equals(fieldType))
{
// Return Strings unchanged
return stringValue;
}
else
{
// Try valueOf(String) on the declared type
Object convertedValue = null;
convertedValue = callValueOf(stringValue, fieldType);
if (convertedValue != null)
{
return convertedValue;
}
// Try valueOf(String) of the declared implementing classes, useful
// when field type is an interface, which is probably a common case.
// We process implementing classes in the order they appear in the
// annotation, which means we'll transform to an instance of the first
// class that returns a non-null valueOf(String).
final ImplementingClasses implementingClasses = field
.getAnnotation(ImplementingClasses.class);
if (implementingClasses != null)
{
final Class<?> [] classes = implementingClasses.classes();
for (Class<?> toClass : classes)
{
convertedValue = callValueOf(stringValue, toClass);
if (convertedValue != null)
{
return convertedValue;
}
}
}
/*
* Try if we can assign anyway. If the attribute is of a non-primitive
* type, it must have an ImplementingClasses annotation, see
* ConsistencyCheckImplementingClasses. If the value meets the constraint,
* we'll return the original value.
*/
if (implementingClasses != null
&& field.getType().isAssignableFrom(String.class)
&& ConstraintValidator.isMet(stringValue, implementingClasses).length == 0)
{
return stringValue;
}
// Try loading the class indicated by this string.
try
{
return ReflectionUtils.classForName(stringValue);
}
catch (ClassNotFoundException e)
{
// Just skip this possibility.
}
return stringValue;
}
}
private Object callValueOf(final String stringValue, final Class<?> fieldType)
{
try
{
final Method valueOfMethod = fieldType.getMethod("valueOf", String.class);
return valueOfMethod.invoke(null, stringValue);
}
catch (NoSuchMethodException e)
{
return null;
}
catch (IllegalAccessException e)
{
throw new RuntimeException("No access to valueOf() method in: "
+ fieldType.getName());
}
catch (InvocationTargetException e)
{
final Throwable target = e.getTargetException();
if (target instanceof NumberFormatException)
{
return null;
}
else
{
throw ExceptionUtils.wrapAsRuntimeException(target);
}
}
}
}
/**
* An action that binds all {@link Input} attributes.
*/
public static class AttributeBinderActionBind implements IAttributeBinderAction
{
private final Map<String, Object> values;
public final Map<String, Object> remainingValues;
private final Class<?> bindingDirectionAnnotation;
private final boolean checkRequired;
private final IAttributeTransformer [] transformers;
public AttributeBinderActionBind(Class<?> bindingDirectionAnnotation,
Map<String, Object> values, boolean checkRequired,
IAttributeTransformer... transformers)
{
this.values = values;
this.bindingDirectionAnnotation = bindingDirectionAnnotation;
this.checkRequired = checkRequired;
this.transformers = transformers;
this.remainingValues = Maps.newHashMap(values);
}
public <T> void performAction(BindingTracker bindingTracker, int level, T object,
String key, Field field, Object value,
Class<? extends Annotation> bindingDirectionAnnotation,
Predicate<Field> predicate) throws InstantiationException
{
if (this.bindingDirectionAnnotation.equals(bindingDirectionAnnotation)
&& field.getAnnotation(bindingDirectionAnnotation) != null)
{
final boolean required = field.getAnnotation(Required.class) != null
&& checkRequired;
final Object currentValue = value;
// Transfer values from the map to the fields. If the input map
// doesn't contain an entry for this key, do nothing. Otherwise,
// perform binding as usual. This will allow to set null values
if (!values.containsKey(key))
{
if (currentValue == null && required)
{
// Throw exception only if the current value is null
throw new AttributeBindingException(key,
"No value for required attribute: " + key + " ("
+ field.getDeclaringClass().getName() + "#"
+ field.getName() + ")");
}
return;
}
// Note that the value can still be null here
value = values.get(key);
if (required)
{
if (value == null)
{
throw new AttributeBindingException(key,
"Not allowed to set required attribute to null: " + key);
}
}
// Apply value transformers before any other checks, conversions
// to allow type-changing transformations as well.
for (IAttributeTransformer transformer : transformers)
{
value = transformer.transform(value, key, field,
bindingDirectionAnnotation);
}
// Try to coerce from class to its instance first
// Notice that if some extra annotations are provided, the newly
// created instance will get only those attributes bound that
// match any of the extra annotations.
if (Class.class.isInstance(value) && !field.getType().equals(Class.class))
{
final Class<?> clazz = ((Class<?>) value);
try
{
value = clazz.newInstance();
if (clazz.isAnnotationPresent(Bindable.class))
{
bind(value, values, false, Input.class, predicate);
}
}
catch (final InstantiationException e)
{
throw new InstantiationException(
"Could not create instance of class: " + clazz.getName()
- + " for attribute " + key);
+ + " for attribute " + key
+ + ": " + e.getMessage());
}
catch (final IllegalAccessException e)
{
throw new InstantiationException(
"Could not create instance of class: " + clazz.getName()
- + " for attribute " + key);
+ + " for attribute " + key
+ + ": " + e.getMessage());
}
}
if (value != null)
{
// Check constraints
final Annotation [] unmetConstraints = ConstraintValidator.isMet(
value, field.getAnnotations());
if (unmetConstraints.length > 0)
{
throw new ConstraintViolationException(key, value,
unmetConstraints);
}
}
// Finally, set the field value
try
{
field.setAccessible(true);
field.set(object, value);
}
catch (final Exception e)
{
throw new AttributeBindingException(key, "Could not assign field "
+ object.getClass().getName() + "#" + field.getName()
+ " with value " + value, e);
}
remainingValues.remove(key);
}
}
}
/**
* An action that binds all {@link Output} attributes.
*/
public static class AttributeBinderActionCollect implements IAttributeBinderAction
{
final private Map<String, Object> values;
final private Class<?> bindingDirectionAnnotation;
final IAttributeTransformer [] transformers;
public AttributeBinderActionCollect(Class<?> bindingDirectionAnnotation,
Map<String, Object> values, IAttributeTransformer... transformers)
{
this.values = values;
this.bindingDirectionAnnotation = bindingDirectionAnnotation;
this.transformers = transformers;
}
public <T> void performAction(BindingTracker bindingTracker, int level, T object,
String key, Field field, Object value,
Class<? extends Annotation> bindingDirectionAnnotation,
Predicate<Field> predicate) throws InstantiationException
{
if (this.bindingDirectionAnnotation.equals(bindingDirectionAnnotation)
&& field.getAnnotation(bindingDirectionAnnotation) != null)
{
try
{
field.setAccessible(true);
// Apply transforms
for (IAttributeTransformer transformer : transformers)
{
value = transformer.transform(value, key, field,
bindingDirectionAnnotation);
}
if (bindingTracker.canBind(object, key, level))
{
values.put(key, value);
}
}
catch (final Exception e)
{
throw new AttributeBindingException(key, "Could not get field value "
+ object.getClass().getName() + "#" + field.getName(), e);
}
}
}
}
/**
* Checks individual attribute definitions for consistency, e.g. whether they have all
* required annotations.
*/
static abstract class ConsistencyCheck
{
/**
* Checks an attribute's annotations.
*
* @param bindingDirection
* @return <code>true</code> if the attribute passed the check and can be bound,
* <code>false</code> if the attribute did not pass the check and cannot
* be bound.
* @throws IllegalArgumentException when attribute's annotations are inconsistent
*/
abstract boolean check(Field field, Class<? extends Annotation> bindingDirection);
}
/**
* Checks if all required attribute annotations are provided.
*/
static class ConsistencyCheckRequiredAnnotations extends ConsistencyCheck
{
@Override
boolean check(Field field, Class<? extends Annotation> bindingDirection)
{
final boolean hasAttribute = field.getAnnotation(Attribute.class) != null;
boolean hasBindingDirection = field.getAnnotation(Input.class) != null
|| field.getAnnotation(Output.class) != null;
if (hasAttribute)
{
if (!hasBindingDirection)
{
throw new IllegalArgumentException(
"Define binding direction annotation (@"
+ Input.class.getSimpleName() + " or @"
+ Output.class.getSimpleName() + ") for field "
+ field.getClass().getName() + "#" + field.getName());
}
}
else
{
if (hasBindingDirection)
{
throw new IllegalArgumentException(
"Binding direction defined for a field (" + field.getClass()
+ "#" + field.getName() + ") that does not have an @"
+ Attribute.class.getSimpleName() + " annotation");
}
}
return hasAttribute;
}
}
/**
* Checks whether attributes of non-primitive types have the
* {@link ImplementingClasses} constraint.
*/
static class ConsistencyCheckImplementingClasses extends ConsistencyCheck
{
static Set<Class<?>> ALLOWED_PLAIN_TYPES = ImmutableSet.<Class<?>> of(Byte.class,
Short.class, Integer.class, Long.class, Float.class, Double.class,
Boolean.class, String.class, Character.class, Class.class, IResource.class,
Collection.class, Map.class, File.class);
static Set<Class<?>> ALLOWED_ASSIGNABLE_TYPES = ImmutableSet.<Class<?>> of(
Enum.class, IResource.class, Collection.class, Map.class);
@Override
boolean check(Field field, Class<? extends Annotation> bindingDirection)
{
if (field.getAnnotation(Input.class) == null)
{
return true;
}
final Class<?> attributeType = ClassUtils.primitiveToWrapper(field.getType());
if (!ALLOWED_PLAIN_TYPES.contains(attributeType)
&& !isAllowedAssignableType(attributeType)
&& field.getAnnotation(ImplementingClasses.class) == null)
{
throw new IllegalArgumentException("Non-primitive typed attribute "
+ field.getDeclaringClass().getName() + "#" + field.getName()
+ " must have the @" + ImplementingClasses.class.getSimpleName()
+ " constraint.");
}
return true;
}
private static boolean isAllowedAssignableType(Class<?> attributeType)
{
for (Class<?> clazz : ALLOWED_ASSIGNABLE_TYPES)
{
if (clazz.isAssignableFrom(attributeType))
{
return true;
}
}
return false;
}
}
/**
* Tracks which attributes have already been collected and prevents overwriting of
* collected values.
*/
private static class BindingTracker
{
/**
* The lowest nesting level from which the attribute has been collected.
*/
private Map<String, Integer> bindingLevel = Maps.newHashMap();
/**
* Containing instance + attribute key pairs that have already been collected.
*/
private Set<Pair<Object, String>> boundInstances = Sets.newHashSet();
boolean canBind(Object instance, String key, int level)
{
final Pair<Object, String> pair = new Pair<Object, String>(instance, key);
if (boundInstances.contains(pair))
{
throw new AttributeBindingException(
"Collecting values of multiple attributes with the same key (" + key
+ ") in the same instance of class ("
+ instance.getClass().getName() + ") is not allowed");
}
boundInstances.add(pair);
// We can collect this attribute if:
// 1) it has not yet been collected or
// 2) it has been collected at a deeper level of the nesting hierarchy
// but we found another value for it found closer to the root object for
// which binding is performed.
final Integer boundAtLevel = bindingLevel.get(key);
final boolean canBind = boundAtLevel == null
|| (boundAtLevel != null && boundAtLevel > level);
if (canBind)
{
bindingLevel.put(key, level);
}
return canBind;
}
}
}
| false | true | public <T> void performAction(BindingTracker bindingTracker, int level, T object,
String key, Field field, Object value,
Class<? extends Annotation> bindingDirectionAnnotation,
Predicate<Field> predicate) throws InstantiationException
{
if (this.bindingDirectionAnnotation.equals(bindingDirectionAnnotation)
&& field.getAnnotation(bindingDirectionAnnotation) != null)
{
final boolean required = field.getAnnotation(Required.class) != null
&& checkRequired;
final Object currentValue = value;
// Transfer values from the map to the fields. If the input map
// doesn't contain an entry for this key, do nothing. Otherwise,
// perform binding as usual. This will allow to set null values
if (!values.containsKey(key))
{
if (currentValue == null && required)
{
// Throw exception only if the current value is null
throw new AttributeBindingException(key,
"No value for required attribute: " + key + " ("
+ field.getDeclaringClass().getName() + "#"
+ field.getName() + ")");
}
return;
}
// Note that the value can still be null here
value = values.get(key);
if (required)
{
if (value == null)
{
throw new AttributeBindingException(key,
"Not allowed to set required attribute to null: " + key);
}
}
// Apply value transformers before any other checks, conversions
// to allow type-changing transformations as well.
for (IAttributeTransformer transformer : transformers)
{
value = transformer.transform(value, key, field,
bindingDirectionAnnotation);
}
// Try to coerce from class to its instance first
// Notice that if some extra annotations are provided, the newly
// created instance will get only those attributes bound that
// match any of the extra annotations.
if (Class.class.isInstance(value) && !field.getType().equals(Class.class))
{
final Class<?> clazz = ((Class<?>) value);
try
{
value = clazz.newInstance();
if (clazz.isAnnotationPresent(Bindable.class))
{
bind(value, values, false, Input.class, predicate);
}
}
catch (final InstantiationException e)
{
throw new InstantiationException(
"Could not create instance of class: " + clazz.getName()
+ " for attribute " + key);
}
catch (final IllegalAccessException e)
{
throw new InstantiationException(
"Could not create instance of class: " + clazz.getName()
+ " for attribute " + key);
}
}
if (value != null)
{
// Check constraints
final Annotation [] unmetConstraints = ConstraintValidator.isMet(
value, field.getAnnotations());
if (unmetConstraints.length > 0)
{
throw new ConstraintViolationException(key, value,
unmetConstraints);
}
}
// Finally, set the field value
try
{
field.setAccessible(true);
field.set(object, value);
}
catch (final Exception e)
{
throw new AttributeBindingException(key, "Could not assign field "
+ object.getClass().getName() + "#" + field.getName()
+ " with value " + value, e);
}
remainingValues.remove(key);
}
}
| public <T> void performAction(BindingTracker bindingTracker, int level, T object,
String key, Field field, Object value,
Class<? extends Annotation> bindingDirectionAnnotation,
Predicate<Field> predicate) throws InstantiationException
{
if (this.bindingDirectionAnnotation.equals(bindingDirectionAnnotation)
&& field.getAnnotation(bindingDirectionAnnotation) != null)
{
final boolean required = field.getAnnotation(Required.class) != null
&& checkRequired;
final Object currentValue = value;
// Transfer values from the map to the fields. If the input map
// doesn't contain an entry for this key, do nothing. Otherwise,
// perform binding as usual. This will allow to set null values
if (!values.containsKey(key))
{
if (currentValue == null && required)
{
// Throw exception only if the current value is null
throw new AttributeBindingException(key,
"No value for required attribute: " + key + " ("
+ field.getDeclaringClass().getName() + "#"
+ field.getName() + ")");
}
return;
}
// Note that the value can still be null here
value = values.get(key);
if (required)
{
if (value == null)
{
throw new AttributeBindingException(key,
"Not allowed to set required attribute to null: " + key);
}
}
// Apply value transformers before any other checks, conversions
// to allow type-changing transformations as well.
for (IAttributeTransformer transformer : transformers)
{
value = transformer.transform(value, key, field,
bindingDirectionAnnotation);
}
// Try to coerce from class to its instance first
// Notice that if some extra annotations are provided, the newly
// created instance will get only those attributes bound that
// match any of the extra annotations.
if (Class.class.isInstance(value) && !field.getType().equals(Class.class))
{
final Class<?> clazz = ((Class<?>) value);
try
{
value = clazz.newInstance();
if (clazz.isAnnotationPresent(Bindable.class))
{
bind(value, values, false, Input.class, predicate);
}
}
catch (final InstantiationException e)
{
throw new InstantiationException(
"Could not create instance of class: " + clazz.getName()
+ " for attribute " + key
+ ": " + e.getMessage());
}
catch (final IllegalAccessException e)
{
throw new InstantiationException(
"Could not create instance of class: " + clazz.getName()
+ " for attribute " + key
+ ": " + e.getMessage());
}
}
if (value != null)
{
// Check constraints
final Annotation [] unmetConstraints = ConstraintValidator.isMet(
value, field.getAnnotations());
if (unmetConstraints.length > 0)
{
throw new ConstraintViolationException(key, value,
unmetConstraints);
}
}
// Finally, set the field value
try
{
field.setAccessible(true);
field.set(object, value);
}
catch (final Exception e)
{
throw new AttributeBindingException(key, "Could not assign field "
+ object.getClass().getName() + "#" + field.getName()
+ " with value " + value, e);
}
remainingValues.remove(key);
}
}
|
diff --git a/src/main/java/com/twistlet/falcon/controller/ListPatronController.java b/src/main/java/com/twistlet/falcon/controller/ListPatronController.java
index ad1b9fe..14266d6 100644
--- a/src/main/java/com/twistlet/falcon/controller/ListPatronController.java
+++ b/src/main/java/com/twistlet/falcon/controller/ListPatronController.java
@@ -1,244 +1,245 @@
package com.twistlet.falcon.controller;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.twistlet.falcon.controller.bean.User;
import com.twistlet.falcon.model.entity.FalconPatron;
import com.twistlet.falcon.model.entity.FalconUser;
import com.twistlet.falcon.model.service.PatronService;
import com.twistlet.falcon.model.service.StaffService;
@Controller
public class ListPatronController {
private final StaffService staffService;
private final PatronService patronService;
@Autowired
public ListPatronController(StaffService staffService,
PatronService patronService) {
this.staffService = staffService;
this.patronService = patronService;
}
@RequestMapping("/list-patient")
@ResponseBody
public List<Map<String, String>> listPatient(
@RequestParam("term") final String partialName) {
final List<FalconUser> users = staffService.listPatients(partialName);
final List<Map<String, String>> list = new ArrayList<>();
for (final FalconUser falconUser : users) {
final Map<String, String> map = new LinkedHashMap<>();
map.put("name", falconUser.getName());
map.put("phone", StringUtils.trimToEmpty(falconUser.getPhone()));
map.put("mail", StringUtils.trimToEmpty(falconUser.getEmail()));
list.add(map);
}
return list;
}
@RequestMapping("/list-patient/{admin}/{date}")
@ResponseBody
public List<User> listAllPatrons(@PathVariable("admin") String admin, @PathVariable(value="date") String date) {
FalconUser falconUser = new FalconUser();
falconUser.setUsername(admin);
List<User> patients = patronService.listRegisteredPatrons(falconUser);
return patients;
}
@RequestMapping("/list-patient/{admin}/{date}/{startTime}/{endTime}")
@ResponseBody
public Set<User> listAvailablePatrons(@PathVariable("admin") String admin,
@PathVariable(value="date") String date,
@PathVariable("startTime") String start,
@PathVariable("endTime") String end) {
FalconUser falconUser = new FalconUser();
final SimpleDateFormat sdf = new SimpleDateFormat("ddMMyyyy HHmm");
Set<User> patients = new HashSet<>();
try {
final Date startDate = sdf.parse(date + " " + start);
final Date endDate = sdf.parse(date + " " + end);
falconUser.setUsername(admin);
patients = patronService.listAvailablePatrons(falconUser, startDate, endDate);
} catch (ParseException e) {
e.printStackTrace();
}
return patients;
}
@RequestMapping("/list-patron-name/{admin}/{date}")
@ResponseBody
public List<String> listPatronNames(@PathVariable("admin") String username, @PathVariable(value="date") String date,
@RequestParam("term") String name) {
FalconUser admin = new FalconUser();
admin.setUsername(username);
List<FalconPatron> patrons = patronService.listPatronByAdminNameLike(admin, name);
List<String> names = new ArrayList<>();
for (FalconPatron patron : patrons) {
names.add(patron.getFalconUserByPatron().getName() + " (" + patron.getFalconUserByPatron().getNric() + ")");
}
return names;
}
@RequestMapping("/list-patron-nric/{admin}/{date}")
@ResponseBody
public List<String> listPatronNric(@PathVariable("admin") String username, @PathVariable(value="date") String date,
@RequestParam("term") String name) {
FalconUser admin = new FalconUser();
admin.setUsername(username);
List<FalconPatron> patrons = patronService.listPatronByAdminNricLike(admin, name);
List<String> names = new ArrayList<>();
for (FalconPatron patron : patrons) {
names.add(patron.getFalconUserByPatron().getNric());
}
return names;
}
@RequestMapping("/list-patron-phone/{admin}/{date}")
@ResponseBody
public List<String> listPatronPhone(@PathVariable("admin") String username, @PathVariable(value="date") String date,
@RequestParam("term") String name) {
FalconUser admin = new FalconUser();
admin.setUsername(username);
List<FalconPatron> patrons = patronService.listPatronByAdminMobileLike(admin, name);
List<String> names = new ArrayList<>();
for (FalconPatron patron : patrons) {
names.add(patron.getFalconUserByPatron().getPhone());
}
return names;
}
@RequestMapping("/list-patron-email/{admin}/{date}")
@ResponseBody
public List<String> listPatronEmail(@PathVariable("admin") String username, @PathVariable(value="date") String date,
@RequestParam("term") String name) {
FalconUser admin = new FalconUser();
admin.setUsername(username);
List<FalconPatron> patrons = patronService.listPatronByAdminEmailLike(admin, name);
List<String> names = new ArrayList<>();
for (FalconPatron patron : patrons) {
names.add(patron.getFalconUserByPatron().getEmail());
}
return names;
}
@RequestMapping("/search-patron/{admin}/{date}")
@ResponseBody
public FalconUser searchPatron(@PathVariable("admin") String username, @PathVariable(value="date") String date,
@RequestParam(value = "name", required = false) String name,
@RequestParam(value = "mobile", required = false) String mobile,
@RequestParam(value = "nric", required = false) String nric,
@RequestParam(value = "email", required = false) String email) {
FalconUser admin = new FalconUser();
admin.setUsername(username);
FalconUser patron = new FalconUser();
patron.setEmail(email);
patron.setName(name);
patron.setPhone(mobile);
patron.setNric(nric);
List<FalconPatron> patrons = patronService.listPatronByAdminPatronLike(admin, patron);
FalconUser matchingUser = null;
if (CollectionUtils.size(patrons) == 1) {
matchingUser = patrons.get(0).getFalconUserByPatron();
matchingUser.setFalconLocations(null);
matchingUser.setFalconPatronsForAdmin(null);
matchingUser.setFalconPatronsForPatron(null);
matchingUser.setFalconPatronsForPatron(null);
matchingUser.setFalconServices(null);
matchingUser.setFalconStaffs(null);
matchingUser.setFalconUserRoles(null);
}
return matchingUser;
}
@RequestMapping("/validate-patron")
@ResponseBody
public String validatePatron(final HttpServletRequest request) {
final String stringId = request.getParameter("fieldId");
final String value = request.getParameter("fieldValue");
final String username = request.getParameter("username-patron");
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
String name = auth.getName();
FalconUser user = new FalconUser();
if("identificationnum-patron".equals(stringId)){
user.setNric(value);
}else if("mobilenum-patron".equals(stringId)){
user.setPhone(value);
}else if("email-patron".equals(stringId)){
user.setEmail(value);
}
boolean isValid = true;
List<FalconUser> users = patronService.listUserByCriteria(user);
if(CollectionUtils.isNotEmpty(users)){
//check if current id passed is equal to retrieved id. Valid is id is equal
for(FalconUser theUser : users){
if(StringUtils.isNotBlank(username)){
/**
* updating user
*/
if(username.equals(theUser.getUsername())){
break;
}else{
isValid = false;
+ break;
}
}else{
/**
* check if different admin is trying to add same user
*/
Set<FalconPatron> registeredAdmins = theUser.getFalconPatronsForPatron();
for(FalconPatron patron : registeredAdmins){
if(name.equals(patron.getFalconUserByAdmin().getUsername())){
isValid = false;
break;
}
}
}
}
}
return "[\""+ stringId + "\", " + isValid +"]";
}
@RequestMapping("/registration/validate-patron")
@ResponseBody
public String validateNewUser(final HttpServletRequest request) {
final String stringId = request.getParameter("fieldId");
final String value = request.getParameter("fieldValue");
FalconUser user = new FalconUser();
if("identificationnum-patron".equals(stringId)){
user.setNric(value);
}else if("mobilenum-patron".equals(stringId)){
user.setPhone(value);
}else if("email-patron".equals(stringId)){
user.setEmail(value);
}
boolean isValid = true;
List<FalconUser> users = patronService.listUserByCriteria(user);
if(CollectionUtils.isNotEmpty(users)){
isValid = false;
}
return "[\""+ stringId + "\", " + isValid +"]";
}
}
| true | true | public String validatePatron(final HttpServletRequest request) {
final String stringId = request.getParameter("fieldId");
final String value = request.getParameter("fieldValue");
final String username = request.getParameter("username-patron");
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
String name = auth.getName();
FalconUser user = new FalconUser();
if("identificationnum-patron".equals(stringId)){
user.setNric(value);
}else if("mobilenum-patron".equals(stringId)){
user.setPhone(value);
}else if("email-patron".equals(stringId)){
user.setEmail(value);
}
boolean isValid = true;
List<FalconUser> users = patronService.listUserByCriteria(user);
if(CollectionUtils.isNotEmpty(users)){
//check if current id passed is equal to retrieved id. Valid is id is equal
for(FalconUser theUser : users){
if(StringUtils.isNotBlank(username)){
/**
* updating user
*/
if(username.equals(theUser.getUsername())){
break;
}else{
isValid = false;
}
}else{
/**
* check if different admin is trying to add same user
*/
Set<FalconPatron> registeredAdmins = theUser.getFalconPatronsForPatron();
for(FalconPatron patron : registeredAdmins){
if(name.equals(patron.getFalconUserByAdmin().getUsername())){
isValid = false;
break;
}
}
}
}
}
return "[\""+ stringId + "\", " + isValid +"]";
}
| public String validatePatron(final HttpServletRequest request) {
final String stringId = request.getParameter("fieldId");
final String value = request.getParameter("fieldValue");
final String username = request.getParameter("username-patron");
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
String name = auth.getName();
FalconUser user = new FalconUser();
if("identificationnum-patron".equals(stringId)){
user.setNric(value);
}else if("mobilenum-patron".equals(stringId)){
user.setPhone(value);
}else if("email-patron".equals(stringId)){
user.setEmail(value);
}
boolean isValid = true;
List<FalconUser> users = patronService.listUserByCriteria(user);
if(CollectionUtils.isNotEmpty(users)){
//check if current id passed is equal to retrieved id. Valid is id is equal
for(FalconUser theUser : users){
if(StringUtils.isNotBlank(username)){
/**
* updating user
*/
if(username.equals(theUser.getUsername())){
break;
}else{
isValid = false;
break;
}
}else{
/**
* check if different admin is trying to add same user
*/
Set<FalconPatron> registeredAdmins = theUser.getFalconPatronsForPatron();
for(FalconPatron patron : registeredAdmins){
if(name.equals(patron.getFalconUserByAdmin().getUsername())){
isValid = false;
break;
}
}
}
}
}
return "[\""+ stringId + "\", " + isValid +"]";
}
|
diff --git a/de.hswt.hrm.component.ui/src/de/hswt/hrm/component/ui/part/CategoryPartUtil.java b/de.hswt.hrm.component.ui/src/de/hswt/hrm/component/ui/part/CategoryPartUtil.java
index 50aec906..f97f967c 100644
--- a/de.hswt.hrm.component.ui/src/de/hswt/hrm/component/ui/part/CategoryPartUtil.java
+++ b/de.hswt.hrm.component.ui/src/de/hswt/hrm/component/ui/part/CategoryPartUtil.java
@@ -1,138 +1,138 @@
package de.hswt.hrm.component.ui.part;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import org.eclipse.jface.viewers.ColumnLabelProvider;
import org.eclipse.jface.wizard.WizardDialog;
import org.eclipse.swt.widgets.Shell;
import com.google.common.base.Optional;
import de.hswt.hrm.common.ui.swt.table.ColumnDescription;
import de.hswt.hrm.component.model.Category;
import de.hswt.hrm.component.ui.wizard.CategoryWizard;
public class CategoryPartUtil {
public CategoryPartUtil() {
}
public static Optional<Category> showWizard(Shell shell, Optional<Category> category) {
CategoryWizard catWiz = new CategoryWizard(category);
WizardDialog wizDiag = new WizardDialog(shell,catWiz);
wizDiag.open();
return catWiz.getCategory();
}
public static List<ColumnDescription<Category>> getColumns() {
List<ColumnDescription<Category>> columns = new ArrayList<>();
columns.add(getName());
columns.add(getDefaultQuantifier());
columns.add(getDefaultBoolRating());
columns.add(getWidth());
columns.add(getHeight());
return columns;
}
private static ColumnDescription<Category> getName() {
return new ColumnDescription<>("Name", new ColumnLabelProvider() {
@Override
public String getText(Object element) {
Category cat = (Category) element;
return cat.getName();
}
}, new Comparator<Category>() {
@Override
public int compare(Category c1, Category c2) {
return c1.getName().compareToIgnoreCase(c2.getName());
}
});
}
private static ColumnDescription<Category> getDefaultQuantifier() {
return new ColumnDescription<>("Gewichtung", new ColumnLabelProvider() {
@Override
public String getText(Object element) {
Category cat = (Category) element;
return Integer.toString(cat.getDefaultQuantifier());
}
}, new Comparator<Category>() {
@Override
public int compare(Category c1, Category c2) {
String quant1 = Integer.toString(c1.getDefaultQuantifier());
String quant2 = Integer.toString(c2.getDefaultQuantifier());
return quant1.compareToIgnoreCase(quant2);
}
});
}
private static ColumnDescription<Category> getDefaultBoolRating() {
- return new ColumnDescription<>("bewertet", new ColumnLabelProvider() {
+ return new ColumnDescription<>("Bewertet", new ColumnLabelProvider() {
@Override
public String getText(Object element) {
Category cat = (Category) element;
if (cat.getDefaultBoolRating()) {
return "Ja";
} else {
return "Nein";
}
}
}, new Comparator<Category>() {
@Override
public int compare(Category c1, Category c2) {
String bRate1;
String bRate2;
if (c1.getDefaultBoolRating()) {
bRate1 = "Ja";
} else {
bRate1 = "Nein";
}
if (c2.getDefaultBoolRating()) {
bRate2 = "Ja";
} else {
bRate2 = "Nein";
}
return bRate1.compareToIgnoreCase(bRate2);
}
});
}
private static ColumnDescription<Category> getWidth() {
return new ColumnDescription<>("Breite", new ColumnLabelProvider() {
@Override
public String getText(Object element) {
Category cat = (Category) element;
return Integer.toString(cat.getWidth());
}
}, new Comparator<Category>() {
@Override
public int compare(Category c1, Category c2) {
String w1 = Integer.toString(c1.getWidth());
String w2 = Integer.toString(c2.getWidth());
return w1.compareToIgnoreCase(w2);
}
});
}
private static ColumnDescription<Category> getHeight() {
return new ColumnDescription<>("Höhe", new ColumnLabelProvider() {
@Override
public String getText(Object element) {
Category cat = (Category) element;
return Integer.toString(cat.getHeight());
}
}, new Comparator<Category>() {
@Override
public int compare(Category c1, Category c2) {
String h1 = Integer.toString(c1.getHeight());
String h2 = Integer.toString(c2.getHeight());
return h1.compareToIgnoreCase(h2);
}
});
}
}
| true | true | private static ColumnDescription<Category> getDefaultBoolRating() {
return new ColumnDescription<>("bewertet", new ColumnLabelProvider() {
@Override
public String getText(Object element) {
Category cat = (Category) element;
if (cat.getDefaultBoolRating()) {
return "Ja";
} else {
return "Nein";
}
}
}, new Comparator<Category>() {
@Override
public int compare(Category c1, Category c2) {
String bRate1;
String bRate2;
if (c1.getDefaultBoolRating()) {
bRate1 = "Ja";
} else {
bRate1 = "Nein";
}
if (c2.getDefaultBoolRating()) {
bRate2 = "Ja";
} else {
bRate2 = "Nein";
}
return bRate1.compareToIgnoreCase(bRate2);
}
});
}
| private static ColumnDescription<Category> getDefaultBoolRating() {
return new ColumnDescription<>("Bewertet", new ColumnLabelProvider() {
@Override
public String getText(Object element) {
Category cat = (Category) element;
if (cat.getDefaultBoolRating()) {
return "Ja";
} else {
return "Nein";
}
}
}, new Comparator<Category>() {
@Override
public int compare(Category c1, Category c2) {
String bRate1;
String bRate2;
if (c1.getDefaultBoolRating()) {
bRate1 = "Ja";
} else {
bRate1 = "Nein";
}
if (c2.getDefaultBoolRating()) {
bRate2 = "Ja";
} else {
bRate2 = "Nein";
}
return bRate1.compareToIgnoreCase(bRate2);
}
});
}
|
diff --git a/src/main/java/com/censoredsoftware/Demigods/Episodes/Demo/Structure/Altar.java b/src/main/java/com/censoredsoftware/Demigods/Episodes/Demo/Structure/Altar.java
index ed38feed..45b21aeb 100644
--- a/src/main/java/com/censoredsoftware/Demigods/Episodes/Demo/Structure/Altar.java
+++ b/src/main/java/com/censoredsoftware/Demigods/Episodes/Demo/Structure/Altar.java
@@ -1,499 +1,499 @@
package com.censoredsoftware.Demigods.Episodes.Demo.Structure;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.world.ChunkLoadEvent;
import com.censoredsoftware.Demigods.Engine.Demigods;
import com.censoredsoftware.Demigods.Engine.Object.Structure;
import com.censoredsoftware.Demigods.Engine.Utility.*;
import com.censoredsoftware.Demigods.Episodes.Demo.EpisodeDemo;
public class Altar extends Structure
{
private final static List<BlockData> enchantTable = new ArrayList<BlockData>(1)
{
{
add(new BlockData(Material.ENCHANTMENT_TABLE));
}
};
private final static List<BlockData> stoneBrick = new ArrayList<BlockData>(3)
{
{
add(new BlockData(Material.SMOOTH_BRICK, 8));
add(new BlockData(Material.SMOOTH_BRICK, (byte) 1, 1));
add(new BlockData(Material.SMOOTH_BRICK, (byte) 2, 1));
}
};
private final static List<BlockData> quartz = new ArrayList<BlockData>(1)
{
{
add(new BlockData(Material.QUARTZ_BLOCK));
}
};
private final static List<BlockData> pillarQuartz = new ArrayList<BlockData>(1)
{
{
add(new BlockData(Material.QUARTZ_BLOCK, (byte) 2));
}
};
private final static List<BlockData> stoneBrickSlabBottom = new ArrayList<BlockData>(1)
{
{
add(new BlockData(Material.getMaterial(44), (byte) 5));
}
};
private final static List<BlockData> stoneBrickSlabTop = new ArrayList<BlockData>(1)
{
{
add(new BlockData(Material.getMaterial(44), (byte) 13));
}
};
private final static List<BlockData> quartzSlabBottom = new ArrayList<BlockData>(1)
{
{
add(new BlockData(Material.getMaterial(44), (byte) 7));
}
};
private final static List<BlockData> quartzSlabTop = new ArrayList<BlockData>(1)
{
{
add(new BlockData(Material.getMaterial(44), (byte) 15));
}
};
private final static List<BlockData> stoneBrickSpecial = new ArrayList<BlockData>(1)
{
{
add(new BlockData(Material.getMaterial(98), (byte) 3));
}
};
private final static List<BlockData> quartzSpecial = new ArrayList<BlockData>(1)
{
{
add(new BlockData(Material.QUARTZ_BLOCK, (byte) 1));
}
};
private final static List<BlockData> spruceWood = new ArrayList<BlockData>(1)
{
{
add(new BlockData(Material.getMaterial(5), (byte) 1));
}
};
private final static List<BlockData> spruceSlab = new ArrayList<BlockData>(1)
{
{
add(new BlockData(Material.getMaterial(126), (byte) 1));
}
};
private final static List<BlockData> birchWood = new ArrayList<BlockData>(1)
{
{
add(new BlockData(Material.getMaterial(5), (byte) 2));
}
};
private final static List<BlockData> birchSlab = new ArrayList<BlockData>(1)
{
{
add(new BlockData(Material.getMaterial(126), (byte) 2));
}
};
private final static Schematic general = new Schematic("general", "_Alex")
{
{
// Create roof
add(new Cuboid(2, 3, 2, stoneBrickSlabTop));
add(new Cuboid(-2, 3, -2, stoneBrickSlabTop));
add(new Cuboid(2, 3, -2, stoneBrickSlabTop));
add(new Cuboid(-2, 3, 2, stoneBrickSlabTop));
add(new Cuboid(2, 4, 2, stoneBrick));
add(new Cuboid(-2, 4, -2, stoneBrick));
add(new Cuboid(2, 4, -2, stoneBrick));
add(new Cuboid(-2, 4, 2, stoneBrick));
add(new Cuboid(2, 5, 2, spruceSlab));
add(new Cuboid(-2, 5, -2, spruceSlab));
add(new Cuboid(2, 5, -2, spruceSlab));
add(new Cuboid(-2, 5, 2, spruceSlab));
add(new Cuboid(0, 6, 0, spruceSlab));
add(new Cuboid(-1, 5, -1, 1, 5, 1, spruceWood));
// Create the enchantment table
add(new Cuboid(0, 2, 0, enchantTable));
// Create magical table stand
add(new Cuboid(0, 1, 0, stoneBrick));
// Create outer steps
add(new Cuboid(3, 0, 3, stoneBrickSlabBottom));
add(new Cuboid(-3, 0, -3, stoneBrickSlabBottom));
add(new Cuboid(3, 0, -3, stoneBrickSlabBottom));
add(new Cuboid(-3, 0, 3, stoneBrickSlabBottom));
add(new Cuboid(4, 0, -2, 4, 0, 2, stoneBrickSlabBottom));
add(new Cuboid(-4, 0, -2, -4, 0, 2, stoneBrickSlabBottom));
add(new Cuboid(-2, 0, -4, 2, 0, -4, stoneBrickSlabBottom));
add(new Cuboid(-2, 0, 4, 2, 0, 4, stoneBrickSlabBottom));
// Create inner steps
add(new Cuboid(3, 0, -1, 3, 0, 1, stoneBrick));
add(new Cuboid(-1, 0, 3, 1, 0, 3, stoneBrick));
add(new Cuboid(-3, 0, -1, -3, 0, 1, stoneBrick));
add(new Cuboid(-1, 0, -3, 1, 0, -3, stoneBrick));
// Create pillars
add(new Cuboid(3, 4, 2, spruceSlab));
add(new Cuboid(3, 4, -2, spruceSlab));
add(new Cuboid(2, 4, 3, spruceSlab));
add(new Cuboid(-2, 4, 3, spruceSlab));
add(new Cuboid(-3, 4, 2, spruceSlab));
add(new Cuboid(-3, 4, -2, spruceSlab));
add(new Cuboid(2, 4, -3, spruceSlab));
add(new Cuboid(-2, 4, -3, spruceSlab));
add(new Cuboid(3, 0, 2, 3, 3, 2, stoneBrick));
add(new Cuboid(3, 0, -2, 3, 3, -2, stoneBrick));
add(new Cuboid(2, 0, 3, 2, 3, 3, stoneBrick));
add(new Cuboid(-2, 0, 3, -2, 3, 3, stoneBrick));
add(new Cuboid(-3, 0, 2, -3, 3, 2, stoneBrick));
add(new Cuboid(-3, 0, -2, -3, 3, -2, stoneBrick));
add(new Cuboid(2, 0, -3, 2, 3, -3, stoneBrick));
add(new Cuboid(-2, 0, -3, -2, 3, -3, stoneBrick));
// Left beam
add(new Cuboid(1, 4, -2, -1, 4, -2, stoneBrick).exclude(0, 4, -2));
add(new Cuboid(0, 4, -2, stoneBrickSpecial));
add(new Cuboid(-1, 5, -2, 1, 5, -2, spruceSlab));
// Right beam
add(new Cuboid(1, 4, 2, -1, 4, 2, stoneBrick).exclude(0, 4, 2));
add(new Cuboid(0, 4, 2, stoneBrickSpecial));
add(new Cuboid(-1, 5, 2, 1, 5, 2, spruceSlab));
// Top beam
add(new Cuboid(2, 4, 1, 2, 4, -1, stoneBrick).exclude(2, 4, 0));
add(new Cuboid(2, 4, 0, stoneBrickSpecial));
add(new Cuboid(2, 5, -1, 2, 5, 1, spruceSlab));
// Bottom beam
add(new Cuboid(-2, 4, 1, -2, 4, -1, stoneBrick).exclude(-2, 4, 0));
add(new Cuboid(-2, 4, 0, stoneBrickSpecial));
add(new Cuboid(-2, 5, -1, -2, 5, 1, spruceSlab));
// Create main platform
add(new Cuboid(0, 1, 0, stoneBrick));
add(new Cuboid(-2, 1, -2, 2, 1, 2, stoneBrickSlabBottom).exclude(0, 1, 0));
}
};
private final static Schematic holy = new Schematic("holy", "HmmmQuestionMark")
{
{
// Create roof
add(new Cuboid(2, 3, 2, quartzSlabTop));
add(new Cuboid(-2, 3, -2, quartzSlabTop));
add(new Cuboid(2, 3, -2, quartzSlabTop));
add(new Cuboid(-2, 3, 2, quartzSlabTop));
add(new Cuboid(2, 4, 2, quartz));
add(new Cuboid(-2, 4, -2, quartz));
add(new Cuboid(2, 4, -2, quartz));
add(new Cuboid(-2, 4, 2, quartz));
add(new Cuboid(2, 5, 2, birchSlab));
add(new Cuboid(-2, 5, -2, birchSlab));
add(new Cuboid(2, 5, -2, birchSlab));
add(new Cuboid(-2, 5, 2, birchSlab));
add(new Cuboid(0, 6, 0, birchSlab));
add(new Cuboid(-1, 5, -1, 1, 5, 1, birchWood));
// Create the enchantment table
add(new Cuboid(0, 2, 0, enchantTable));
// Create magical table stand
add(new Cuboid(0, 1, 0, quartzSpecial));
// Create outer steps
add(new Cuboid(3, 0, 3, quartzSlabBottom));
add(new Cuboid(-3, 0, -3, quartzSlabBottom));
add(new Cuboid(3, 0, -3, quartzSlabBottom));
add(new Cuboid(-3, 0, 3, quartzSlabBottom));
add(new Cuboid(4, 0, -2, 4, 0, 2, quartzSlabBottom));
add(new Cuboid(-4, 0, -2, -4, 0, 2, quartzSlabBottom));
add(new Cuboid(-2, 0, -4, 2, 0, -4, quartzSlabBottom));
add(new Cuboid(-2, 0, 4, 2, 0, 4, quartzSlabBottom));
// Create inner steps
add(new Cuboid(3, 0, -1, 3, 0, 1, quartz).exclude(3, 0, 0));
add(new Cuboid(-1, 0, 3, 1, 0, 3, quartz).exclude(0, 0, 3));
add(new Cuboid(-3, 0, -1, -3, 0, 1, quartz).exclude(-3, 0, 0));
add(new Cuboid(-1, 0, -3, 1, 0, -3, quartz).exclude(0, 0, -3));
add(new Cuboid(3, 0, 0, quartzSpecial));
add(new Cuboid(0, 0, 3, quartzSpecial));
add(new Cuboid(-3, 0, 0, quartzSpecial));
add(new Cuboid(0, 0, -3, quartzSpecial));
// Create pillars
add(new Cuboid(3, 4, 2, birchSlab));
add(new Cuboid(3, 4, -2, birchSlab));
add(new Cuboid(2, 4, 3, birchSlab));
add(new Cuboid(-2, 4, 3, birchSlab));
add(new Cuboid(-3, 4, 2, birchSlab));
add(new Cuboid(-3, 4, -2, birchSlab));
add(new Cuboid(2, 4, -3, birchSlab));
add(new Cuboid(-2, 4, -3, birchSlab));
add(new Cuboid(3, 0, 2, 3, 3, 2, pillarQuartz));
add(new Cuboid(3, 0, -2, 3, 3, -2, pillarQuartz));
add(new Cuboid(2, 0, 3, 2, 3, 3, pillarQuartz));
add(new Cuboid(-2, 0, 3, -2, 3, 3, pillarQuartz));
add(new Cuboid(-3, 0, 2, -3, 3, 2, pillarQuartz));
add(new Cuboid(-3, 0, -2, -3, 3, -2, pillarQuartz));
add(new Cuboid(2, 0, -3, 2, 3, -3, pillarQuartz));
add(new Cuboid(-2, 0, -3, -2, 3, -3, pillarQuartz));
// Left beam
add(new Cuboid(1, 4, -2, -1, 4, -2, quartz).exclude(0, 4, -2));
add(new Cuboid(0, 4, -2, quartzSpecial));
add(new Cuboid(-1, 5, -2, 1, 5, -2, birchSlab));
// Right beam
add(new Cuboid(1, 4, 2, -1, 4, 2, quartz).exclude(0, 4, 2));
add(new Cuboid(0, 4, 2, quartzSpecial));
add(new Cuboid(-1, 5, 2, 1, 5, 2, birchSlab));
// Top beam
add(new Cuboid(2, 4, 1, 2, 4, -1, quartz).exclude(2, 4, 0));
add(new Cuboid(2, 4, 0, quartzSpecial));
add(new Cuboid(2, 5, -1, 2, 5, 1, birchSlab));
// Bottom beam
add(new Cuboid(-2, 4, 1, -2, 4, -1, quartz).exclude(-2, 4, 0));
add(new Cuboid(-2, 4, 0, quartzSpecial));
add(new Cuboid(-2, 5, -1, -2, 5, 1, birchSlab));
// Create main platform
add(new Cuboid(0, 1, 0, quartz));
add(new Cuboid(-2, 1, -2, 2, 1, 2, quartzSlabBottom).exclude(0, 1, 0));
}
};
public static enum AltarDesign implements Design
{
GENERAL("general"), HOLY("holy");
private String name;
private AltarDesign(String name)
{
this.name = name;
}
@Override
public String getName()
{
return name;
}
}
@Override
public Set<Flag> getFlags()
{
return new HashSet<Flag>()
{
{
add(Flag.NO_PVP);
add(Flag.PRAYER_LOCATION);
add(Flag.PROTECTED_BLOCKS);
}
};
}
@Override
public String getStructureType()
{
return "Altar";
}
@Override
public Schematic get(String name)
{
if(name.equals(general.toString())) return general;
return holy;
}
@Override
public int getRadius()
{
return Demigods.config.getSettingInt("zones.altar_radius");
}
@Override
public Location getClickableBlock(Location reference)
{
return reference.clone().add(0, 2, 0);
}
@Override
public Listener getUniqueListener()
{
return new AltarListener();
}
@Override
public Set<Save> getAll()
{
return Util.findAll("type", getStructureType());
}
@Override
public Save createNew(Location reference, boolean generate)
{
Save save = new Save();
save.setReferenceLocation(reference);
save.setType(getStructureType());
save.setDesign(getDesign(reference));
save.addFlags(getFlags());
save.save();
if(generate) save.generate();
return save;
}
public String getDesign(Location reference)
{
switch(reference.getBlock().getBiome())
{
case ICE_PLAINS:
return AltarDesign.HOLY.getName();
default:
return AltarDesign.GENERAL.getName();
}
}
public static boolean altarNearby(Location location)
{
for(Save structureSave : Util.findAll("type", "Altar"))
{
if(structureSave.getReferenceLocation().distance(location) <= Demigods.config.getSettingInt("generation.min_blocks_between_altars")) return true;
}
return false;
}
}
class AltarListener implements Listener
{
@EventHandler(priority = EventPriority.MONITOR)
public void onChunkLoad(final ChunkLoadEvent event)
{
if(!event.isNewChunk()) return;
// Define variables
final Location location = LocationUtility.randomChunkLocation(event.getChunk());
// Check if it can generate
if(LocationUtility.canGenerateStrict(location, 3))
{
// Return a random boolean based on the chance of Altar generation
if(MiscUtility.randomPercentBool(Demigods.config.getSettingDouble("generation.altar_chance")))
{
// If another Altar doesn't exist nearby then make one
if(!Altar.altarNearby(location))
{
AdminUtility.sendDebug(ChatColor.RED + "Altar generated by SERVER at " + ChatColor.GRAY + "(" + location.getWorld().getName() + ") " + location.getX() + ", " + location.getY() + ", " + location.getZ());
EpisodeDemo.Structures.ALTAR.getStructure().createNew(location, true);
location.getWorld().strikeLightningEffect(location);
location.getWorld().strikeLightningEffect(location);
Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(Demigods.plugin, new Runnable()
{
@Override
public void run()
{
for(Entity entity : event.getWorld().getEntities())
{
if(entity instanceof Player)
{
if(entity.getLocation().distance(location) < 400)
{
((Player) entity).sendMessage(ChatColor.GRAY + "" + ChatColor.ITALIC + Demigods.text.getText(TextUtility.Text.ALTAR_SPAWNED_NEAR));
}
}
}
}
}, 1);
}
}
}
}
@EventHandler(priority = EventPriority.HIGHEST)
public void demigodsAdminWand(PlayerInteractEvent event)
{
if(event.getClickedBlock() == null) return;
// Define variables
Block clickedBlock = event.getClickedBlock();
Location location = clickedBlock.getLocation();
Player player = event.getPlayer();
/**
* Handle Altars
*/
boolean general = clickedBlock.getType().equals(Material.EMERALD_BLOCK);
boolean holy = clickedBlock.getType().equals(Material.COAL_BLOCK);
- if(AdminUtility.useWand(player) && general || holy)
+ if(AdminUtility.useWand(player) && (general || holy))
{
event.setCancelled(true);
// Remove clicked block
clickedBlock.setType(Material.AIR);
AdminUtility.sendDebug(ChatColor.RED + "Altar generated by ADMIN WAND at " + ChatColor.GRAY + "(" + location.getWorld().getName() + ") " + location.getX() + ", " + location.getY() + ", " + location.getZ());
player.sendMessage(ChatColor.GRAY + Demigods.text.getText(TextUtility.Text.ADMIN_WAND_GENERATE_ALTAR));
// Generate the Altar based on the block given.
Structure.Save save = EpisodeDemo.Structures.ALTAR.getStructure().createNew(location, false);
if(holy) save.setDesign("holy");
if(general) save.setDesign("general");
save.generate();
player.sendMessage(ChatColor.GREEN + Demigods.text.getText(TextUtility.Text.ADMIN_WAND_GENERATE_ALTAR_COMPLETE));
return;
}
if(event.getAction().equals(Action.RIGHT_CLICK_BLOCK) && AdminUtility.useWand(player) && Structure.Util.partOfStructureWithType(location, "Altar"))
{
event.setCancelled(true);
Structure.Save altar = Structure.Util.getStructureSave(location);
if(DataUtility.hasTimed(player.getName(), "destroy_altar"))
{
AdminUtility.sendDebug(ChatColor.RED + "Altar at " + ChatColor.GRAY + "(" + location.getWorld().getName() + ") " + location.getX() + ", " + location.getY() + ", " + location.getZ() + " removed by " + "ADMIN WAND" + ".");
// Remove the Altar
altar.remove();
DataUtility.removeTimed(player.getName(), "destroy_altar");
player.sendMessage(ChatColor.GREEN + Demigods.text.getText(TextUtility.Text.ADMIN_WAND_REMOVE_ALTAR_COMPLETE));
}
else
{
DataUtility.saveTimed(player.getName(), "destroy_altar", true, 5);
player.sendMessage(ChatColor.RED + Demigods.text.getText(TextUtility.Text.ADMIN_WAND_REMOVE_ALTAR));
}
}
}
}
| true | true | public void demigodsAdminWand(PlayerInteractEvent event)
{
if(event.getClickedBlock() == null) return;
// Define variables
Block clickedBlock = event.getClickedBlock();
Location location = clickedBlock.getLocation();
Player player = event.getPlayer();
/**
* Handle Altars
*/
boolean general = clickedBlock.getType().equals(Material.EMERALD_BLOCK);
boolean holy = clickedBlock.getType().equals(Material.COAL_BLOCK);
if(AdminUtility.useWand(player) && general || holy)
{
event.setCancelled(true);
// Remove clicked block
clickedBlock.setType(Material.AIR);
AdminUtility.sendDebug(ChatColor.RED + "Altar generated by ADMIN WAND at " + ChatColor.GRAY + "(" + location.getWorld().getName() + ") " + location.getX() + ", " + location.getY() + ", " + location.getZ());
player.sendMessage(ChatColor.GRAY + Demigods.text.getText(TextUtility.Text.ADMIN_WAND_GENERATE_ALTAR));
// Generate the Altar based on the block given.
Structure.Save save = EpisodeDemo.Structures.ALTAR.getStructure().createNew(location, false);
if(holy) save.setDesign("holy");
if(general) save.setDesign("general");
save.generate();
player.sendMessage(ChatColor.GREEN + Demigods.text.getText(TextUtility.Text.ADMIN_WAND_GENERATE_ALTAR_COMPLETE));
return;
}
if(event.getAction().equals(Action.RIGHT_CLICK_BLOCK) && AdminUtility.useWand(player) && Structure.Util.partOfStructureWithType(location, "Altar"))
{
event.setCancelled(true);
Structure.Save altar = Structure.Util.getStructureSave(location);
if(DataUtility.hasTimed(player.getName(), "destroy_altar"))
{
AdminUtility.sendDebug(ChatColor.RED + "Altar at " + ChatColor.GRAY + "(" + location.getWorld().getName() + ") " + location.getX() + ", " + location.getY() + ", " + location.getZ() + " removed by " + "ADMIN WAND" + ".");
// Remove the Altar
altar.remove();
DataUtility.removeTimed(player.getName(), "destroy_altar");
player.sendMessage(ChatColor.GREEN + Demigods.text.getText(TextUtility.Text.ADMIN_WAND_REMOVE_ALTAR_COMPLETE));
}
else
{
DataUtility.saveTimed(player.getName(), "destroy_altar", true, 5);
player.sendMessage(ChatColor.RED + Demigods.text.getText(TextUtility.Text.ADMIN_WAND_REMOVE_ALTAR));
}
}
}
| public void demigodsAdminWand(PlayerInteractEvent event)
{
if(event.getClickedBlock() == null) return;
// Define variables
Block clickedBlock = event.getClickedBlock();
Location location = clickedBlock.getLocation();
Player player = event.getPlayer();
/**
* Handle Altars
*/
boolean general = clickedBlock.getType().equals(Material.EMERALD_BLOCK);
boolean holy = clickedBlock.getType().equals(Material.COAL_BLOCK);
if(AdminUtility.useWand(player) && (general || holy))
{
event.setCancelled(true);
// Remove clicked block
clickedBlock.setType(Material.AIR);
AdminUtility.sendDebug(ChatColor.RED + "Altar generated by ADMIN WAND at " + ChatColor.GRAY + "(" + location.getWorld().getName() + ") " + location.getX() + ", " + location.getY() + ", " + location.getZ());
player.sendMessage(ChatColor.GRAY + Demigods.text.getText(TextUtility.Text.ADMIN_WAND_GENERATE_ALTAR));
// Generate the Altar based on the block given.
Structure.Save save = EpisodeDemo.Structures.ALTAR.getStructure().createNew(location, false);
if(holy) save.setDesign("holy");
if(general) save.setDesign("general");
save.generate();
player.sendMessage(ChatColor.GREEN + Demigods.text.getText(TextUtility.Text.ADMIN_WAND_GENERATE_ALTAR_COMPLETE));
return;
}
if(event.getAction().equals(Action.RIGHT_CLICK_BLOCK) && AdminUtility.useWand(player) && Structure.Util.partOfStructureWithType(location, "Altar"))
{
event.setCancelled(true);
Structure.Save altar = Structure.Util.getStructureSave(location);
if(DataUtility.hasTimed(player.getName(), "destroy_altar"))
{
AdminUtility.sendDebug(ChatColor.RED + "Altar at " + ChatColor.GRAY + "(" + location.getWorld().getName() + ") " + location.getX() + ", " + location.getY() + ", " + location.getZ() + " removed by " + "ADMIN WAND" + ".");
// Remove the Altar
altar.remove();
DataUtility.removeTimed(player.getName(), "destroy_altar");
player.sendMessage(ChatColor.GREEN + Demigods.text.getText(TextUtility.Text.ADMIN_WAND_REMOVE_ALTAR_COMPLETE));
}
else
{
DataUtility.saveTimed(player.getName(), "destroy_altar", true, 5);
player.sendMessage(ChatColor.RED + Demigods.text.getText(TextUtility.Text.ADMIN_WAND_REMOVE_ALTAR));
}
}
}
|
diff --git a/src/main/java/com/monits/commons/utils/RandomUtils.java b/src/main/java/com/monits/commons/utils/RandomUtils.java
index 2b0181e..e0d6c3b 100644
--- a/src/main/java/com/monits/commons/utils/RandomUtils.java
+++ b/src/main/java/com/monits/commons/utils/RandomUtils.java
@@ -1,78 +1,78 @@
/*
Copyright 2011 Monits
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.
*/
/**
* Random Utils.
*
* @copyright 2011 Monits
* @license Apache 2.0 License
* @version Release: 1.0.0
* @link http://www.monits.com/
* @since 1.0.0
*/
package com.monits.commons.utils;
import java.util.Random;
/**
* Random Utils.
*
* @author Maximiliano Luque <[email protected]>
* @copyright 2011 Monits
* @license Apache 2.0 License
* @version Release: 1.0.0
* @link http://www.monits.com/
* @since 1.0.0
*/
public class RandomUtils {
/**
* Utility classes should not have a public or default constructor.
*/
private RandomUtils() {
throw new UnsupportedOperationException();
}
/**
* Generates a random String with the number of characters requested.
*
* @param amount The number of characters in the string. If negative, it will be treated as zero.
*
* @return The random String.
*/
public static String generateRandomString(int amount) {
Random random = new Random();
char[] characters = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
- 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',
- 'm', 'n', 'ñ', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w',
- 'x', 'y', 'z', };
+ 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',
+ 'm', 'n', 'ñ', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w',
+ 'x', 'y', 'z', };
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < amount ; i++) {
buffer.append(characters[random.nextInt(characters.length - 1)]);
}
return buffer.toString();
}
}
| true | true | public static String generateRandomString(int amount) {
Random random = new Random();
char[] characters = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',
'm', 'n', 'ñ', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w',
'x', 'y', 'z', };
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < amount ; i++) {
buffer.append(characters[random.nextInt(characters.length - 1)]);
}
return buffer.toString();
}
| public static String generateRandomString(int amount) {
Random random = new Random();
char[] characters = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',
'm', 'n', 'ñ', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w',
'x', 'y', 'z', };
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < amount ; i++) {
buffer.append(characters[random.nextInt(characters.length - 1)]);
}
return buffer.toString();
}
|
diff --git a/dev/core/src/com/google/gwt/dev/jjs/impl/Pruner.java b/dev/core/src/com/google/gwt/dev/jjs/impl/Pruner.java
index 26c71f624..5d2c92b3b 100644
--- a/dev/core/src/com/google/gwt/dev/jjs/impl/Pruner.java
+++ b/dev/core/src/com/google/gwt/dev/jjs/impl/Pruner.java
@@ -1,841 +1,840 @@
/*
* Copyright 2007 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.gwt.dev.jjs.impl;
import com.google.gwt.dev.jjs.ast.CanBeStatic;
import com.google.gwt.dev.jjs.ast.Context;
import com.google.gwt.dev.jjs.ast.JAbsentArrayDimension;
import com.google.gwt.dev.jjs.ast.JArrayType;
import com.google.gwt.dev.jjs.ast.JBinaryOperation;
import com.google.gwt.dev.jjs.ast.JBinaryOperator;
import com.google.gwt.dev.jjs.ast.JClassType;
import com.google.gwt.dev.jjs.ast.JExpression;
import com.google.gwt.dev.jjs.ast.JField;
import com.google.gwt.dev.jjs.ast.JFieldRef;
import com.google.gwt.dev.jjs.ast.JInterfaceType;
import com.google.gwt.dev.jjs.ast.JLocal;
import com.google.gwt.dev.jjs.ast.JLocalRef;
import com.google.gwt.dev.jjs.ast.JMethod;
import com.google.gwt.dev.jjs.ast.JMethodBody;
import com.google.gwt.dev.jjs.ast.JMethodCall;
import com.google.gwt.dev.jjs.ast.JModVisitor;
import com.google.gwt.dev.jjs.ast.JNewArray;
import com.google.gwt.dev.jjs.ast.JNewInstance;
import com.google.gwt.dev.jjs.ast.JNode;
import com.google.gwt.dev.jjs.ast.JParameter;
import com.google.gwt.dev.jjs.ast.JParameterRef;
import com.google.gwt.dev.jjs.ast.JPrimitiveType;
import com.google.gwt.dev.jjs.ast.JProgram;
import com.google.gwt.dev.jjs.ast.JReferenceType;
import com.google.gwt.dev.jjs.ast.JStringLiteral;
import com.google.gwt.dev.jjs.ast.JThisRef;
import com.google.gwt.dev.jjs.ast.JType;
import com.google.gwt.dev.jjs.ast.JVariable;
import com.google.gwt.dev.jjs.ast.JVariableRef;
import com.google.gwt.dev.jjs.ast.JVisitor;
import com.google.gwt.dev.jjs.ast.js.JMultiExpression;
import com.google.gwt.dev.jjs.ast.js.JsniFieldRef;
import com.google.gwt.dev.jjs.ast.js.JsniMethodBody;
import com.google.gwt.dev.jjs.ast.js.JsniMethodRef;
import com.google.gwt.dev.js.ast.JsContext;
import com.google.gwt.dev.js.ast.JsExpression;
import com.google.gwt.dev.js.ast.JsFunction;
import com.google.gwt.dev.js.ast.JsName;
import com.google.gwt.dev.js.ast.JsNameRef;
import com.google.gwt.dev.js.ast.JsVisitor;
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;
/**
* Remove globally unreferenced classes, interfaces, methods, parameters, and
* fields from the AST. This algorithm is based on having known "entry points"
* into the application which serve as the root(s) from which reachability is
* determined and everything else is rescued. Pruner determines reachability at
* a global level based on method calls and new operations; it does not perform
* any local code flow analysis. But, a local code flow optimization pass that
* can eliminate method calls would allow Pruner to prune additional nodes.
*
* Note: references to pruned types may still exist in the tree after this pass
* runs, however, it should only be in contexts that do not rely on any code
* generation for the pruned type. For example, it's legal to have a variable of
* a pruned type, or to try to cast to a pruned type. These will cause natural
* failures at run time; or later optimizations might be able to hard-code
* failures at compile time.
*
* Note: this class is limited to pruning parameters of static methods only.
*/
public class Pruner {
/**
* Remove assignments to pruned fields, locals and params.
*/
private class CleanupRefsVisitor extends JModVisitor {
@Override
public void endVisit(JBinaryOperation x, Context ctx) {
// The LHS of assignments may have been pruned.
if (x.getOp() == JBinaryOperator.ASG) {
JExpression lhs = x.getLhs();
if (lhs.hasSideEffects()) {
return;
}
if (lhs instanceof JFieldRef || lhs instanceof JLocalRef
|| lhs instanceof JParameterRef) {
JVariable var = ((JVariableRef) lhs).getTarget();
if (!referencedNonTypes.contains(var)) {
// Just replace with my RHS
ctx.replaceMe(x.getRhs());
}
}
}
}
@Override
public void endVisit(JMethodCall x, Context ctx) {
JMethod method = x.getTarget();
// Did we prune the parameters of the method we're calling?
if (removedMethodParamsMap.containsKey(method)) {
// This must be a static method
assert method.isStatic();
- assert x.getInstance() == null;
- JMethodCall newCall = new JMethodCall(program, x.getSourceInfo(), null,
- method);
+ JMethodCall newCall = new JMethodCall(program, x.getSourceInfo(),
+ x.getInstance(), method);
JMultiExpression currentMulti = null;
ArrayList<JParameter> removedParams = removedMethodParamsMap.get(method);
for (int i = 0; i < x.getArgs().size(); i++) {
JParameter param = removedParams.get(i);
JExpression arg = x.getArgs().get(i);
if (referencedNonTypes.contains(param)) {
// We rescued this parameter
// Do we need to add the multi we've been building?
if (currentMulti == null) {
newCall.getArgs().add(arg);
} else {
currentMulti.exprs.add(arg);
newCall.getArgs().add(currentMulti);
currentMulti = null;
}
} else if (arg.hasSideEffects()) {
// We didn't rescue this parameter and it has side-effects. Add it
// to a new multi
if (currentMulti == null) {
currentMulti = new JMultiExpression(program, x.getSourceInfo());
}
currentMulti.exprs.add(arg);
}
}
// We have orphaned parameters - add them on the end, wrapped in the
// multi (JS ignores extra parameters)
if (currentMulti != null) {
newCall.getArgs().add(currentMulti);
}
ctx.replaceMe(newCall);
}
}
}
/**
* Remove any unreferenced classes and interfaces from JProgram. Remove any
* unreferenced methods and fields from their containing classes.
*/
private class PruneVisitor extends JVisitor {
private boolean didChange = false;
@Override
public boolean didChange() {
return didChange;
}
@Override
public boolean visit(JClassType type, Context ctx) {
assert (referencedTypes.contains(type));
boolean isInstantiated = program.typeOracle.isInstantiatedType(type);
for (Iterator<JField> it = type.fields.iterator(); it.hasNext();) {
JField field = it.next();
if (!referencedNonTypes.contains(field)
|| pruneViaNoninstantiability(isInstantiated, field)) {
it.remove();
didChange = true;
}
}
for (Iterator<JMethod> it = type.methods.iterator(); it.hasNext();) {
JMethod method = it.next();
if (!methodIsReferenced(method)
|| pruneViaNoninstantiability(isInstantiated, method)) {
it.remove();
didChange = true;
} else {
accept(method);
}
}
return false;
}
@Override
public boolean visit(JInterfaceType type, Context ctx) {
boolean isReferenced = referencedTypes.contains(type);
boolean isInstantiated = program.typeOracle.isInstantiatedType(type);
for (Iterator<JField> it = type.fields.iterator(); it.hasNext();) {
JField field = it.next();
// all interface fields are static and final
if (!isReferenced || !referencedNonTypes.contains(field)) {
it.remove();
didChange = true;
}
}
Iterator<JMethod> it = type.methods.iterator();
if (it.hasNext()) {
// start at index 1; never prune clinit directly out of the interface
it.next();
}
while (it.hasNext()) {
JMethod method = it.next();
// all other interface methods are instance and abstract
if (!isInstantiated || !methodIsReferenced(method)) {
it.remove();
didChange = true;
}
}
return false;
}
@Override
public boolean visit(JMethod x, Context ctx) {
if (x.isStatic()) {
/*
* Don't prune parameters on unreferenced methods. The methods might not
* be reachable through the current method traversal routines, but might
* be used or checked elsewhere.
*
* Basically, if we never actually checked if the method parameters were
* used or not, don't prune them. Doing so would leave a number of
* dangling JParameterRefs that blow up in later optimizations.
*/
if (!referencedNonTypes.contains(x)) {
return true;
}
JsFunction func = x.isNative()
? ((JsniMethodBody) x.getBody()).getFunc() : null;
ArrayList<JParameter> removedParams = new ArrayList<JParameter>(
x.params);
for (int i = 0; i < x.params.size(); i++) {
JParameter param = x.params.get(i);
if (!referencedNonTypes.contains(param)) {
x.params.remove(i);
didChange = true;
removedMethodParamsMap.put(x, removedParams);
// Remove the associated JSNI parameter
if (func != null) {
func.getParameters().remove(i);
}
i--;
}
}
}
return true;
}
@Override
public boolean visit(JMethodBody x, Context ctx) {
for (Iterator<JLocal> it = x.locals.iterator(); it.hasNext();) {
JLocal local = it.next();
if (!referencedNonTypes.contains(local)) {
it.remove();
didChange = true;
}
}
return false;
}
@Override
public boolean visit(JProgram program, Context ctx) {
for (Iterator<JReferenceType> it = program.getDeclaredTypes().iterator(); it.hasNext();) {
JReferenceType type = it.next();
if (referencedTypes.contains(type)
|| program.typeOracle.isInstantiatedType(type)) {
accept(type);
} else {
it.remove();
didChange = true;
}
}
return false;
}
/**
* Returns <code>true</code> if a method is referenced.
*/
private boolean methodIsReferenced(JMethod method) {
// Is the method directly referenced?
if (referencedNonTypes.contains(method)) {
return true;
}
/*
* Special case: if method is the static impl for a live instance method,
* don't prune it unless this is the final prune.
*
* In some cases, the staticImpl can be inlined into the instance method
* but still be needed at other call sites.
*/
JMethod staticImplFor = program.staticImplFor(method);
if (staticImplFor != null && referencedNonTypes.contains(staticImplFor)) {
if (saveCodeGenTypes) {
return true;
}
}
return false;
}
private boolean pruneViaNoninstantiability(boolean isInstantiated,
CanBeStatic it) {
return (!isInstantiated && !it.isStatic());
}
}
/**
* Marks as "referenced" any types, methods, and fields that are reachable.
* Also marks as "instantiable" any the classes and interfaces that can
* possibly be instantiated.
*
* TODO(later): make RescueVisitor use less stack?
*/
private class RescueVisitor extends JVisitor {
private final Set<JReferenceType> instantiatedTypes = new HashSet<JReferenceType>();
public void commitInstantiatedTypes() {
program.typeOracle.setInstantiatedTypes(instantiatedTypes);
}
@Override
public boolean visit(JArrayType type, Context ctx) {
assert (referencedTypes.contains(type));
boolean isInstantiated = instantiatedTypes.contains(type);
JType leafType = type.getLeafType();
int dims = type.getDims();
// Rescue my super array type
if (leafType instanceof JReferenceType) {
JReferenceType rLeafType = (JReferenceType) leafType;
if (rLeafType.extnds != null) {
JArrayType superArray = program.getTypeArray(rLeafType.extnds, dims);
rescue(superArray, true, isInstantiated);
}
for (int i = 0; i < rLeafType.implments.size(); ++i) {
JInterfaceType intfType = rLeafType.implments.get(i);
JArrayType intfArray = program.getTypeArray(intfType, dims);
rescue(intfArray, true, isInstantiated);
}
}
return false;
}
@Override
public boolean visit(JBinaryOperation x, Context ctx) {
// special string concat handling
if (x.getOp() == JBinaryOperator.ADD
&& x.getType() == program.getTypeJavaLangString()) {
rescueByConcat(x.getLhs().getType());
rescueByConcat(x.getRhs().getType());
} else if (x.getOp() == JBinaryOperator.ASG) {
// Don't rescue variables that are merely assigned to and never read
boolean doSkip = false;
JExpression lhs = x.getLhs();
if (lhs.hasSideEffects()) {
// cannot skip
} else if (lhs instanceof JLocalRef) {
// locals are ok to skip
doSkip = true;
} else if (lhs instanceof JParameterRef) {
// parameters are ok to skip
doSkip = true;
} else if (lhs instanceof JFieldRef) {
JFieldRef fieldRef = (JFieldRef) lhs;
/*
* Whether we can skip depends on what the qualifier is; we have to be
* certain the qualifier cannot be a null pointer (in which case we'd
* fail to throw the appropriate exception.
*
* TODO: better non-null tracking!
*/
JExpression instance = fieldRef.getInstance();
if (fieldRef.getField().isStatic()) {
// statics are always okay
doSkip = true;
} else if (instance instanceof JThisRef) {
// a this ref cannot be null
doSkip = true;
}
}
if (doSkip) {
accept(x.getRhs());
return false;
}
}
return true;
}
@Override
public boolean visit(JClassType type, Context ctx) {
assert (referencedTypes.contains(type));
boolean isInstantiated = instantiatedTypes.contains(type);
/*
* SPECIAL: Some classes contain methods used by code generation later.
* Unless those transforms have already been performed, we must rescue all
* contained methods for later user.
*/
if (saveCodeGenTypes && program.codeGenTypes.contains(type)) {
for (int i = 0; i < type.methods.size(); ++i) {
JMethod it = type.methods.get(i);
rescue(it);
}
}
// Rescue my super type
rescue(type.extnds, true, isInstantiated);
// Rescue my clinit (it won't ever be explicitly referenced
rescue(type.methods.get(0));
// JLS 12.4.1: don't rescue my super interfaces just because I'm rescued.
// However, if I'm instantiated, let's mark them as instantiated.
for (int i = 0; i < type.implments.size(); ++i) {
JInterfaceType intfType = type.implments.get(i);
rescue(intfType, false, isInstantiated);
}
return false;
}
@Override
public boolean visit(JFieldRef ref, Context ctx) {
JField target = ref.getField();
// JLS 12.4.1: references to static, non-final, or
// non-compile-time-constant fields rescue the enclosing class.
// JDT already folds in compile-time constants as literals, so we must
// rescue the enclosing types for any static fields that make it here.
if (target.isStatic()) {
rescue(target.getEnclosingType(), true, false);
}
rescue(target);
return true;
}
@Override
public boolean visit(JInterfaceType type, Context ctx) {
boolean isReferenced = referencedTypes.contains(type);
boolean isInstantiated = instantiatedTypes.contains(type);
assert (isReferenced || isInstantiated);
// Rescue my clinit (it won't ever be explicitly referenced
rescue(type.methods.get(0));
// JLS 12.4.1: don't rescue my super interfaces just because I'm rescued.
// However, if I'm instantiated, let's mark them as instantiated.
if (isInstantiated) {
for (int i = 0; i < type.implments.size(); ++i) {
JInterfaceType intfType = type.implments.get(i);
rescue(intfType, false, true);
}
}
// visit any field initializers
for (int i = 0; i < type.fields.size(); ++i) {
JField it = type.fields.get(i);
accept(it);
}
return false;
}
@Override
public boolean visit(JLocalRef ref, Context ctx) {
JLocal target = ref.getLocal();
rescue(target);
return true;
}
@Override
public boolean visit(final JMethod x, Context ctx) {
if (x.isNative()) {
// Manually rescue native parameter references
final JsniMethodBody body = (JsniMethodBody) x.getBody();
final JsFunction func = body.getFunc();
new JsVisitor() {
@Override
public void endVisit(JsNameRef nameRef, JsContext<JsExpression> ctx) {
JsName ident = nameRef.getName();
if (ident != null) {
// If we're referencing a parameter, rescue the associated
// JParameter
int index = func.getParameters().indexOf(ident.getStaticRef());
if (index != -1) {
rescue(x.params.get(index));
}
}
}
}.accept(func);
}
return true;
}
@Override
public boolean visit(JMethodCall call, Context ctx) {
JMethod target = call.getTarget();
// JLS 12.4.1: references to static methods rescue the enclosing class
if (target.isStatic()) {
rescue(target.getEnclosingType(), true, false);
}
rescue(target);
return true;
}
@Override
public boolean visit(JNewArray newArray, Context ctx) {
// rescue and instantiate the array type
JArrayType arrayType = newArray.getArrayType();
if (newArray.dims != null) {
// rescue my type and all the implicitly nested types (with fewer dims)
int nDims = arrayType.getDims();
JType leafType = arrayType.getLeafType();
assert (newArray.dims.size() == nDims);
for (int i = 0; i < nDims; ++i) {
if (newArray.dims.get(i) instanceof JAbsentArrayDimension) {
break;
}
rescue(program.getTypeArray(leafType, nDims - i), true, true);
}
} else {
// just rescue my own specific type
rescue(arrayType, true, true);
}
return true;
}
@Override
public boolean visit(JNewInstance newInstance, Context ctx) {
// rescue and instantiate the target class!
rescue(newInstance.getClassType(), true, true);
return true;
}
@Override
public boolean visit(JParameterRef x, Context ctx) {
// rescue the parameter for future pruning purposes
rescue(x.getParameter());
return true;
}
@Override
public boolean visit(JsniFieldRef x, Context ctx) {
/*
* SPECIAL: this could be an assignment that passes a value from
* JavaScript into Java.
*
* TODO(later): technically we only need to do this if the field is being
* assigned to.
*/
maybeRescueJavaScriptObjectPassingIntoJava(x.getField().getType());
// JsniFieldRef rescues as JFieldRef
return visit((JFieldRef) x, ctx);
}
@Override
public boolean visit(JsniMethodRef x, Context ctx) {
/*
* SPECIAL: each argument of the call passes a value from JavaScript into
* Java.
*/
ArrayList<JParameter> params = x.getTarget().params;
for (int i = 0, c = params.size(); i < c; ++i) {
JParameter param = params.get(i);
maybeRescueJavaScriptObjectPassingIntoJava(param.getType());
/*
* Because we're not currently tracking methods through JSNI, we need to
* assume that it's not safe to prune parameters of a method referenced
* as such.
*
* A better solution would be to perform basic escape analysis to ensure
* that the function reference never escapes, or at minimum, ensure that
* the method is immediately called after retrieving the method
* reference.
*/
rescue(param);
}
// JsniMethodRef rescues as JMethodCall
return visit((JMethodCall) x, ctx);
}
@Override
public boolean visit(JStringLiteral literal, Context ctx) {
// rescue and instantiate java.lang.String
rescue(program.getTypeJavaLangString(), true, true);
return true;
}
/**
* Subclasses of JavaScriptObject are never instantiated directly. They are
* created "magically" when a JSNI method passes a reference to an existing
* JS object into Java code. The point at which a subclass of JSO is passed
* into Java code constitutes "instantiation". We must identify these points
* and trigger a rescue and instantiation of that particular JSO subclass.
*
* @param type The type of the value passing from Java to JavaScript.
* @see com.google.gwt.core.client.JavaScriptObject
*/
private void maybeRescueJavaScriptObjectPassingIntoJava(JType type) {
if (type instanceof JReferenceType) {
JReferenceType refType = (JReferenceType) type;
if (program.typeOracle.canTriviallyCast(refType,
program.getJavaScriptObject())) {
rescue(refType, true, true);
}
}
}
private boolean rescue(JMethod method) {
if (method != null) {
if (!referencedNonTypes.contains(method)) {
referencedNonTypes.add(method);
accept(method);
if (method.isNative()) {
/*
* SPECIAL: returning from this method passes a value from
* JavaScript into Java.
*/
maybeRescueJavaScriptObjectPassingIntoJava(method.getType());
}
return true;
}
}
return false;
}
private void rescue(JReferenceType type, boolean isReferenced,
boolean isInstantiated) {
if (type != null) {
boolean doVisit = false;
if (isInstantiated && !instantiatedTypes.contains(type)) {
instantiatedTypes.add(type);
doVisit = true;
}
if (isReferenced && !referencedTypes.contains(type)) {
referencedTypes.add(type);
doVisit = true;
}
if (doVisit) {
accept(type);
}
}
}
private void rescue(JVariable var) {
if (var != null) {
if (!referencedNonTypes.contains(var)) {
referencedNonTypes.add(var);
}
}
}
/**
* Handle special rescues needed implicitly to support concat.
*/
private void rescueByConcat(JType type) {
JClassType stringType = program.getTypeJavaLangString();
JPrimitiveType charType = program.getTypePrimitiveChar();
if (type instanceof JReferenceType && type != stringType) {
/*
* Any reference types (except String, which works by default) that take
* part in a concat must rescue java.lang.Object.toString().
*
* TODO: can we narrow the focus by walking up the type heirarchy or
* doing explicit toString calls?
*/
JMethod toStringMethod = program.getIndexedMethod("Object.toString");
rescue(toStringMethod);
} else if (type == charType) {
/*
* Characters must rescue String.valueOf(char)
*/
if (stringValueOfChar == null) {
for (int i = 0; i < stringType.methods.size(); ++i) {
JMethod meth = stringType.methods.get(i);
if (meth.getName().equals("valueOf")) {
List<JType> params = meth.getOriginalParamTypes();
if (params.size() == 1) {
if (params.get(0) == charType) {
stringValueOfChar = meth;
break;
}
}
}
}
assert (stringValueOfChar != null);
}
rescue(stringValueOfChar);
}
}
}
/**
* A method that isn't called directly can still be needed, if it overrides or
* implements any methods that are called.
*/
private class UpRefVisitor extends JVisitor {
private boolean didRescue = false;
private final RescueVisitor rescuer;
public UpRefVisitor(RescueVisitor rescuer) {
this.rescuer = rescuer;
}
public boolean didRescue() {
return didRescue;
}
@Override
public boolean visit(JMethod x, Context ctx) {
if (referencedNonTypes.contains(x)) {
return false;
}
for (int i = 0; i < x.overrides.size(); ++i) {
JMethod ref = x.overrides.get(i);
if (referencedNonTypes.contains(ref)) {
rescuer.rescue(x);
didRescue = true;
return false;
}
}
JMethod[] virtualOverrides = program.typeOracle.getAllVirtualOverrides(x);
for (int i = 0; i < virtualOverrides.length; ++i) {
JMethod ref = virtualOverrides[i];
if (referencedNonTypes.contains(ref)) {
rescuer.rescue(x);
didRescue = true;
return false;
}
}
return false;
}
@Override
public boolean visit(JProgram x, Context ctx) {
didRescue = false;
return true;
}
}
public static boolean exec(JProgram program, boolean noSpecialTypes) {
return new Pruner(program, noSpecialTypes).execImpl();
}
private final JProgram program;
private final Set<JNode> referencedNonTypes = new HashSet<JNode>();
private final Set<JReferenceType> referencedTypes = new HashSet<JReferenceType>();
private final Map<JMethod, ArrayList<JParameter>> removedMethodParamsMap = new HashMap<JMethod, ArrayList<JParameter>>();
private final boolean saveCodeGenTypes;
private JMethod stringValueOfChar = null;
private Pruner(JProgram program, boolean saveCodeGenTypes) {
this.program = program;
this.saveCodeGenTypes = saveCodeGenTypes;
}
private boolean execImpl() {
boolean madeChanges = false;
while (true) {
RescueVisitor rescuer = new RescueVisitor();
// Always rescue and instantiate the "base" array type
rescuer.rescue(program.getIndexedType("Array"), true, true);
for (JReferenceType type : program.codeGenTypes) {
rescuer.rescue(type, true, saveCodeGenTypes);
}
for (JMethod method : program.entryMethods) {
rescuer.rescue(method);
}
UpRefVisitor upRefer = new UpRefVisitor(rescuer);
do {
rescuer.commitInstantiatedTypes();
upRefer.accept(program);
} while (upRefer.didRescue());
PruneVisitor pruner = new PruneVisitor();
pruner.accept(program);
if (!pruner.didChange()) {
break;
}
CleanupRefsVisitor cleaner = new CleanupRefsVisitor();
cleaner.accept(program);
referencedTypes.clear();
referencedNonTypes.clear();
removedMethodParamsMap.clear();
madeChanges = true;
}
return madeChanges;
}
}
| false | true | public void endVisit(JMethodCall x, Context ctx) {
JMethod method = x.getTarget();
// Did we prune the parameters of the method we're calling?
if (removedMethodParamsMap.containsKey(method)) {
// This must be a static method
assert method.isStatic();
assert x.getInstance() == null;
JMethodCall newCall = new JMethodCall(program, x.getSourceInfo(), null,
method);
JMultiExpression currentMulti = null;
ArrayList<JParameter> removedParams = removedMethodParamsMap.get(method);
for (int i = 0; i < x.getArgs().size(); i++) {
JParameter param = removedParams.get(i);
JExpression arg = x.getArgs().get(i);
if (referencedNonTypes.contains(param)) {
// We rescued this parameter
// Do we need to add the multi we've been building?
if (currentMulti == null) {
newCall.getArgs().add(arg);
} else {
currentMulti.exprs.add(arg);
newCall.getArgs().add(currentMulti);
currentMulti = null;
}
} else if (arg.hasSideEffects()) {
// We didn't rescue this parameter and it has side-effects. Add it
// to a new multi
if (currentMulti == null) {
currentMulti = new JMultiExpression(program, x.getSourceInfo());
}
currentMulti.exprs.add(arg);
}
}
// We have orphaned parameters - add them on the end, wrapped in the
// multi (JS ignores extra parameters)
if (currentMulti != null) {
newCall.getArgs().add(currentMulti);
}
ctx.replaceMe(newCall);
}
}
| public void endVisit(JMethodCall x, Context ctx) {
JMethod method = x.getTarget();
// Did we prune the parameters of the method we're calling?
if (removedMethodParamsMap.containsKey(method)) {
// This must be a static method
assert method.isStatic();
JMethodCall newCall = new JMethodCall(program, x.getSourceInfo(),
x.getInstance(), method);
JMultiExpression currentMulti = null;
ArrayList<JParameter> removedParams = removedMethodParamsMap.get(method);
for (int i = 0; i < x.getArgs().size(); i++) {
JParameter param = removedParams.get(i);
JExpression arg = x.getArgs().get(i);
if (referencedNonTypes.contains(param)) {
// We rescued this parameter
// Do we need to add the multi we've been building?
if (currentMulti == null) {
newCall.getArgs().add(arg);
} else {
currentMulti.exprs.add(arg);
newCall.getArgs().add(currentMulti);
currentMulti = null;
}
} else if (arg.hasSideEffects()) {
// We didn't rescue this parameter and it has side-effects. Add it
// to a new multi
if (currentMulti == null) {
currentMulti = new JMultiExpression(program, x.getSourceInfo());
}
currentMulti.exprs.add(arg);
}
}
// We have orphaned parameters - add them on the end, wrapped in the
// multi (JS ignores extra parameters)
if (currentMulti != null) {
newCall.getArgs().add(currentMulti);
}
ctx.replaceMe(newCall);
}
}
|
diff --git a/src/main/java/org/n52/sos/sir/xml/SirStreamWriter.java b/src/main/java/org/n52/sos/sir/xml/SirStreamWriter.java
index 6af7209..9edadd0 100644
--- a/src/main/java/org/n52/sos/sir/xml/SirStreamWriter.java
+++ b/src/main/java/org/n52/sos/sir/xml/SirStreamWriter.java
@@ -1,38 +1,38 @@
/**
* Copyright (C) 2013
* by 52 North Initiative for Geospatial Open Source Software GmbH
*
* Contact: Andreas Wytzisk
* 52 North Initiative for Geospatial Open Source Software GmbH
* Martin-Luther-King-Weg 24
* 48155 Muenster, Germany
* [email protected]
*
* This program is free software; you can redistribute 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 WITHOUT ANY WARRANTY; even without 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 (see gnu-gpl v2.txt). If not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA or
* visit the Free Software Foundation web page, http://www.fsf.org.
*/
package org.n52.sos.sir.xml;
import org.n52.sos.sir.SirConstants;
/**
* @author Christian Autermann <[email protected]>
*/
public abstract class SirStreamWriter extends StreamWriter implements SirConstants {
public SirStreamWriter() {
- super(NS_SIR_PREFIX, NS_SIR);
+ super(NS_SIR, NS_SIR_PREFIX);
}
}
| true | true | public SirStreamWriter() {
super(NS_SIR_PREFIX, NS_SIR);
}
| public SirStreamWriter() {
super(NS_SIR, NS_SIR_PREFIX);
}
|
diff --git a/engine/src/blender/com/jme3/scene/plugins/blender/meshes/MeshHelper.java b/engine/src/blender/com/jme3/scene/plugins/blender/meshes/MeshHelper.java
index c484b4b4a..6584fa6f8 100644
--- a/engine/src/blender/com/jme3/scene/plugins/blender/meshes/MeshHelper.java
+++ b/engine/src/blender/com/jme3/scene/plugins/blender/meshes/MeshHelper.java
@@ -1,510 +1,512 @@
/*
* Copyright (c) 2009-2010 jMonkeyEngine
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'jMonkeyEngine' nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.jme3.scene.plugins.blender.meshes;
import java.nio.FloatBuffer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import com.jme3.asset.BlenderKey.FeaturesToLoad;
import com.jme3.material.Material;
import com.jme3.math.FastMath;
import com.jme3.math.Vector2f;
import com.jme3.math.Vector3f;
import com.jme3.renderer.queue.RenderQueue.Bucket;
import com.jme3.scene.Geometry;
import com.jme3.scene.Mesh;
import com.jme3.scene.VertexBuffer;
import com.jme3.scene.VertexBuffer.Format;
import com.jme3.scene.VertexBuffer.Type;
import com.jme3.scene.VertexBuffer.Usage;
import com.jme3.scene.plugins.blender.AbstractBlenderHelper;
import com.jme3.scene.plugins.blender.BlenderContext;
import com.jme3.scene.plugins.blender.BlenderContext.LoadedFeatureDataType;
import com.jme3.scene.plugins.blender.exceptions.BlenderFileException;
import com.jme3.scene.plugins.blender.file.DynamicArray;
import com.jme3.scene.plugins.blender.file.Pointer;
import com.jme3.scene.plugins.blender.file.Structure;
import com.jme3.scene.plugins.blender.materials.MaterialContext;
import com.jme3.scene.plugins.blender.materials.MaterialHelper;
import com.jme3.scene.plugins.blender.objects.Properties;
import com.jme3.scene.plugins.blender.textures.TextureHelper;
import com.jme3.scene.plugins.blender.textures.UVCoordinatesGenerator;
import com.jme3.texture.Texture;
import com.jme3.util.BufferUtils;
/**
* A class that is used in mesh calculations.
*
* @author Marcin Roguski (Kaelthas)
*/
public class MeshHelper extends AbstractBlenderHelper {
/**
* This constructor parses the given blender version and stores the result. Some functionalities may differ in different blender
* versions.
*
* @param blenderVersion
* the version read from the blend file
*/
public MeshHelper(String blenderVersion) {
super(blenderVersion);
}
/**
* This method reads converts the given structure into mesh. The given structure needs to be filled with the appropriate data.
*
* @param structure
* the structure we read the mesh from
* @return the mesh feature
* @throws BlenderFileException
*/
@SuppressWarnings("unchecked")
public List<Geometry> toMesh(Structure structure, BlenderContext blenderContext) throws BlenderFileException {
List<Geometry> geometries = (List<Geometry>) blenderContext.getLoadedFeature(structure.getOldMemoryAddress(),
LoadedFeatureDataType.LOADED_FEATURE);
if (geometries != null) {
List<Geometry> copiedGeometries = new ArrayList<Geometry>(geometries.size());
for (Geometry geometry : geometries) {
copiedGeometries.add(geometry.clone());
}
return copiedGeometries;
}
// helpers
TextureHelper textureHelper = blenderContext.getHelper(TextureHelper.class);
// reading mesh data
String name = structure.getName();
MeshContext meshContext = new MeshContext();
// reading vertices
Vector3f[] vertices = this.getVertices(structure, blenderContext);
int verticesAmount = vertices.length;
// vertices Colors
List<float[]> verticesColors = this.getVerticesColors(structure, blenderContext);
// reading faces
// the following map sorts faces by material number (because in jme Mesh can have only one material)
Map<Integer, List<Integer>> meshesMap = new HashMap<Integer, List<Integer>>();
Pointer pMFace = (Pointer) structure.getFieldValue("mface");
List<Structure> mFaces = null;
if (pMFace.isNotNull()) {
mFaces = pMFace.fetchData(blenderContext.getInputStream());
if (mFaces == null || mFaces.size() == 0) {
return new ArrayList<Geometry>(0);
}
+ } else{
+ mFaces = new ArrayList<Structure>(0);
}
Pointer pMTFace = (Pointer) structure.getFieldValue("mtface");
List<Vector2f> uvCoordinates = null;
List<Structure> mtFaces = null;
if (pMTFace.isNotNull()) {
mtFaces = pMTFace.fetchData(blenderContext.getInputStream());
int facesAmount = ((Number) structure.getFieldValue("totface")).intValue();
if (mtFaces.size() != facesAmount) {
throw new BlenderFileException("The amount of faces uv coordinates is not equal to faces amount!");
}
uvCoordinates = new ArrayList<Vector2f>();
}
// normalMap merges normals of faces that will be rendered smooth
Map<Vector3f, Vector3f> normalMap = new HashMap<Vector3f, Vector3f>(verticesAmount);
List<Vector3f> normalList = new ArrayList<Vector3f>();
List<Vector3f> vertexList = new ArrayList<Vector3f>();
// indicates if the material with the specified number should have a texture attached
Map<Integer, Texture> materialNumberToTexture = new HashMap<Integer, Texture>();
// this map's key is the vertex index from 'vertices 'table and the value are indices from 'vertexList'
// positions (it simply tells which vertex is referenced where in the result list)
Map<Integer, List<Integer>> vertexReferenceMap = new HashMap<Integer, List<Integer>>(verticesAmount);
int vertexColorIndex = 0;
for (int i = 0; i < mFaces.size(); ++i) {
Structure mFace = mFaces.get(i);
boolean smooth = (((Number) mFace.getFieldValue("flag")).byteValue() & 0x01) != 0x00;
DynamicArray<Number> uvs = null;
boolean materialWithoutTextures = false;
Pointer pImage = null;
if (mtFaces != null) {
Structure mtFace = mtFaces.get(i);
pImage = (Pointer) mtFace.getFieldValue("tpage");
materialWithoutTextures = pImage.isNull();
// uvs always must be added wheater we have texture or not
uvs = (DynamicArray<Number>) mtFace.getFieldValue("uv");
uvCoordinates.add(new Vector2f(uvs.get(0, 0).floatValue(), uvs.get(0, 1).floatValue()));
uvCoordinates.add(new Vector2f(uvs.get(1, 0).floatValue(), uvs.get(1, 1).floatValue()));
uvCoordinates.add(new Vector2f(uvs.get(2, 0).floatValue(), uvs.get(2, 1).floatValue()));
}
int matNr = ((Number) mFace.getFieldValue("mat_nr")).intValue();
Integer materialNumber = Integer.valueOf(materialWithoutTextures ? -1 * matNr - 1 : matNr);
List<Integer> indexList = meshesMap.get(materialNumber);
if (indexList == null) {
indexList = new ArrayList<Integer>();
meshesMap.put(materialNumber, indexList);
}
// attaching image to texture (face can have UV's and image whlie its material may have no texture attached)
if (pImage != null && pImage.isNotNull() && !materialNumberToTexture.containsKey(materialNumber)) {
Texture texture = textureHelper.getTextureFromImage(pImage.fetchData(blenderContext.getInputStream()).get(0),
blenderContext);
if (texture != null) {
materialNumberToTexture.put(materialNumber, texture);
}
}
int v1 = ((Number) mFace.getFieldValue("v1")).intValue();
int v2 = ((Number) mFace.getFieldValue("v2")).intValue();
int v3 = ((Number) mFace.getFieldValue("v3")).intValue();
int v4 = ((Number) mFace.getFieldValue("v4")).intValue();
Vector3f n = FastMath.computeNormal(vertices[v1], vertices[v2], vertices[v3]);
this.addNormal(n, normalMap, smooth, vertices[v1], vertices[v2], vertices[v3]);
normalList.add(normalMap.get(vertices[v1]));
normalList.add(normalMap.get(vertices[v2]));
normalList.add(normalMap.get(vertices[v3]));
this.appendVertexReference(v1, vertexList.size(), vertexReferenceMap);
indexList.add(vertexList.size());
vertexList.add(vertices[v1]);
this.appendVertexReference(v2, vertexList.size(), vertexReferenceMap);
indexList.add(vertexList.size());
vertexList.add(vertices[v2]);
this.appendVertexReference(v3, vertexList.size(), vertexReferenceMap);
indexList.add(vertexList.size());
vertexList.add(vertices[v3]);
if (v4 > 0) {
if (uvs != null) {
uvCoordinates.add(new Vector2f(uvs.get(0, 0).floatValue(), uvs.get(0, 1).floatValue()));
uvCoordinates.add(new Vector2f(uvs.get(2, 0).floatValue(), uvs.get(2, 1).floatValue()));
uvCoordinates.add(new Vector2f(uvs.get(3, 0).floatValue(), uvs.get(3, 1).floatValue()));
}
this.appendVertexReference(v1, vertexList.size(), vertexReferenceMap);
indexList.add(vertexList.size());
vertexList.add(vertices[v1]);
this.appendVertexReference(v3, vertexList.size(), vertexReferenceMap);
indexList.add(vertexList.size());
vertexList.add(vertices[v3]);
this.appendVertexReference(v4, vertexList.size(), vertexReferenceMap);
indexList.add(vertexList.size());
vertexList.add(vertices[v4]);
this.addNormal(n, normalMap, smooth, vertices[v4]);
normalList.add(normalMap.get(vertices[v1]));
normalList.add(normalMap.get(vertices[v3]));
normalList.add(normalMap.get(vertices[v4]));
if (verticesColors != null) {
verticesColors.add(vertexColorIndex + 3, verticesColors.get(vertexColorIndex));
verticesColors.add(vertexColorIndex + 4, verticesColors.get(vertexColorIndex + 2));
}
vertexColorIndex += 6;
} else {
if (verticesColors != null) {
verticesColors.remove(vertexColorIndex + 3);
vertexColorIndex += 3;
}
}
}
meshContext.setVertexList(vertexList);
meshContext.setVertexReferenceMap(vertexReferenceMap);
Vector3f[] normals = normalList.toArray(new Vector3f[normalList.size()]);
// reading vertices groups (from the parent)
Structure parent = blenderContext.peekParent();
Structure defbase = (Structure) parent.getFieldValue("defbase");
List<Structure> defs = defbase.evaluateListBase(blenderContext);
String[] verticesGroups = new String[defs.size()];
int defIndex = 0;
for (Structure def : defs) {
verticesGroups[defIndex++] = def.getFieldValue("name").toString();
}
// reading materials
MaterialHelper materialHelper = blenderContext.getHelper(MaterialHelper.class);
Material[] materials = null;
Material[] nonTexturedMaterials = null;
if ((blenderContext.getBlenderKey().getFeaturesToLoad() & FeaturesToLoad.MATERIALS) != 0) {
materials = materialHelper.getMaterials(structure, blenderContext);
nonTexturedMaterials = materials == null ? null : new Material[materials.length];// fill it when needed
}
// creating the result meshes
geometries = new ArrayList<Geometry>(meshesMap.size());
VertexBuffer verticesBuffer = new VertexBuffer(Type.Position);
verticesBuffer.setupData(Usage.Stream, 3, Format.Float,
BufferUtils.createFloatBuffer(vertexList.toArray(new Vector3f[vertexList.size()])));
// initial vertex position (used with animation)
VertexBuffer verticesBind = new VertexBuffer(Type.BindPosePosition);
verticesBind.setupData(Usage.CpuOnly, 3, Format.Float, BufferUtils.clone(verticesBuffer.getData()));
VertexBuffer normalsBuffer = new VertexBuffer(Type.Normal);
normalsBuffer.setupData(Usage.Stream, 3, Format.Float, BufferUtils.createFloatBuffer(normals));
// initial normals position (used with animation)
VertexBuffer normalsBind = new VertexBuffer(Type.BindPoseNormal);
normalsBind.setupData(Usage.CpuOnly, 3, Format.Float, BufferUtils.clone(normalsBuffer.getData()));
VertexBuffer uvCoordsBuffer = null;
if (uvCoordinates != null) {
uvCoordsBuffer = new VertexBuffer(Type.TexCoord);
uvCoordsBuffer.setupData(Usage.Static, 2, Format.Float,
BufferUtils.createFloatBuffer(uvCoordinates.toArray(new Vector2f[uvCoordinates.size()])));
}
//reading custom properties
Properties properties = this.loadProperties(structure, blenderContext);
// generating meshes
FloatBuffer verticesColorsBuffer = this.createFloatBuffer(verticesColors);
for (Entry<Integer, List<Integer>> meshEntry : meshesMap.entrySet()) {
Mesh mesh = new Mesh();
// creating vertices indices for this mesh
List<Integer> indexList = meshEntry.getValue();
int[] indices = new int[indexList.size()];
for (int i = 0; i < indexList.size(); ++i) {
indices[i] = indexList.get(i).intValue();
}
// setting vertices
mesh.setBuffer(Type.Index, 1, indices);
mesh.setBuffer(verticesBuffer);
mesh.setBuffer(verticesBind);
// setting vertices colors
if (verticesColorsBuffer != null) {
mesh.setBuffer(Type.Color, 4, verticesColorsBuffer);
}
// setting faces' normals
mesh.setBuffer(normalsBuffer);
mesh.setBuffer(normalsBind);
// creating the result
Geometry geometry = new Geometry(name + (geometries.size() + 1), mesh);
if (materials != null) {
int materialNumber = meshEntry.getKey().intValue();
Material material;
if (materialNumber >= 0) {
material = materials[materialNumber];
if (materialNumberToTexture.containsKey(Integer.valueOf(materialNumber))) {
if (material.getMaterialDef().getAssetName().contains("Lighting")) {
if (!materialHelper.hasTexture(material, MaterialHelper.TEXTURE_TYPE_DIFFUSE)) {
material = material.clone();
material.setTexture(MaterialHelper.TEXTURE_TYPE_DIFFUSE,
materialNumberToTexture.get(Integer.valueOf(materialNumber)));
}
} else {
if (!materialHelper.hasTexture(material, MaterialHelper.TEXTURE_TYPE_COLOR)) {
material = material.clone();
material.setTexture(MaterialHelper.TEXTURE_TYPE_COLOR,
materialNumberToTexture.get(Integer.valueOf(materialNumber)));
}
}
}
} else {
materialNumber = -1 * (materialNumber + 1);
if (nonTexturedMaterials[materialNumber] == null) {
nonTexturedMaterials[materialNumber] = materialHelper.getNonTexturedMaterial(materials[materialNumber],
TextureHelper.TEX_IMAGE);
}
material = nonTexturedMaterials[materialNumber];
}
geometry.setMaterial(material);
if (material.isTransparent()) {
geometry.setQueueBucket(Bucket.Transparent);
}
} else {
geometry.setMaterial(blenderContext.getDefaultMaterial());
}
if (properties != null && properties.getValue() != null) {
geometry.setUserData("properties", properties);
}
geometries.add(geometry);
}
//applying uvCoordinates for all the meshes
if (uvCoordsBuffer != null) {
for (Geometry geom : geometries) {
geom.getMesh().setBuffer(uvCoordsBuffer);
}
} else {
Map<Material, List<Geometry>> materialMap = new HashMap<Material, List<Geometry>>();
for (Geometry geom : geometries) {
Material material = geom.getMaterial();
List<Geometry> geomsWithCommonMaterial = materialMap.get(material);
if (geomsWithCommonMaterial == null) {
geomsWithCommonMaterial = new ArrayList<Geometry>();
materialMap.put(material, geomsWithCommonMaterial);
}
geomsWithCommonMaterial.add(geom);
}
for (Entry<Material, List<Geometry>> entry : materialMap.entrySet()) {
MaterialContext materialContext = blenderContext.getMaterialContext(entry.getKey());
if (materialContext != null && materialContext.getTexturesCount() > 0) {
VertexBuffer coords = UVCoordinatesGenerator.generateUVCoordinates(materialContext.getUvCoordinatesType(),
materialContext.getProjectionType(), materialContext.getTextureDimension(),
materialContext.getProjection(0), entry.getValue());
//setting the coordinates inside the mesh context
for (Geometry geometry : entry.getValue()) {
meshContext.addUVCoordinates(geometry, coords);
}
}
}
}
blenderContext.addLoadedFeatures(structure.getOldMemoryAddress(), structure.getName(), structure, geometries);
blenderContext.setMeshContext(structure.getOldMemoryAddress(), meshContext);
return geometries;
}
/**
* This method adds a normal to a normals' map. This map is used to merge normals of a vertor that should be rendered smooth.
*
* @param normalToAdd
* a normal to be added
* @param normalMap
* merges normals of faces that will be rendered smooth; the key is the vertex and the value - its normal vector
* @param smooth
* the variable that indicates wheather to merge normals (creating the smooth mesh) or not
* @param vertices
* a list of vertices read from the blender file
*/
public void addNormal(Vector3f normalToAdd, Map<Vector3f, Vector3f> normalMap, boolean smooth, Vector3f... vertices) {
for (Vector3f v : vertices) {
Vector3f n = normalMap.get(v);
if (!smooth || n == null) {
normalMap.put(v, normalToAdd.clone());
} else {
n.addLocal(normalToAdd).normalizeLocal();
}
}
}
/**
* This method fills the vertex reference map. The vertices are loaded once and referenced many times in the model. This map is created
* to tell where the basic vertices are referenced in the result vertex lists. The key of the map is the basic vertex index, and its key
* - the reference indices list.
*
* @param basicVertexIndex
* the index of the vertex from its basic table
* @param resultIndex
* the index of the vertex in its result vertex list
* @param vertexReferenceMap
* the reference map
*/
protected void appendVertexReference(int basicVertexIndex, int resultIndex, Map<Integer, List<Integer>> vertexReferenceMap) {
List<Integer> referenceList = vertexReferenceMap.get(Integer.valueOf(basicVertexIndex));
if (referenceList == null) {
referenceList = new ArrayList<Integer>();
vertexReferenceMap.put(Integer.valueOf(basicVertexIndex), referenceList);
}
referenceList.add(Integer.valueOf(resultIndex));
}
/**
* This method returns the vertices colors. Each vertex is stored in float[4] array.
*
* @param meshStructure
* the structure containing the mesh data
* @param blenderContext
* the blender context
* @return a list of vertices colors, each color belongs to a single vertex
* @throws BlenderFileException
* this exception is thrown when the blend file structure is somehow invalid or corrupted
*/
public List<float[]> getVerticesColors(Structure meshStructure, BlenderContext blenderContext) throws BlenderFileException {
Pointer pMCol = (Pointer) meshStructure.getFieldValue("mcol");
List<float[]> verticesColors = null;
List<Structure> mCol = null;
if (pMCol.isNotNull()) {
verticesColors = new LinkedList<float[]>();
mCol = pMCol.fetchData(blenderContext.getInputStream());
for (Structure color : mCol) {
float r = ((Number) color.getFieldValue("r")).byteValue() / 256.0f;
float g = ((Number) color.getFieldValue("g")).byteValue() / 256.0f;
float b = ((Number) color.getFieldValue("b")).byteValue() / 256.0f;
float a = ((Number) color.getFieldValue("a")).byteValue() / 256.0f;
verticesColors.add(new float[]{b, g, r, a});
}
}
return verticesColors;
}
/**
* This method returns the vertices.
*
* @param meshStructure
* the structure containing the mesh data
* @param blenderContext
* the blender context
* @return a list of vertices colors, each color belongs to a single vertex
* @throws BlenderFileException
* this exception is thrown when the blend file structure is somehow invalid or corrupted
*/
@SuppressWarnings("unchecked")
public Vector3f[] getVertices(Structure meshStructure, BlenderContext blenderContext) throws BlenderFileException {
int verticesAmount = ((Number) meshStructure.getFieldValue("totvert")).intValue();
Vector3f[] vertices = new Vector3f[verticesAmount];
if (verticesAmount == 0) {
return vertices;
}
Pointer pMVert = (Pointer) meshStructure.getFieldValue("mvert");
List<Structure> mVerts = pMVert.fetchData(blenderContext.getInputStream());
for (int i = 0; i < verticesAmount; ++i) {
DynamicArray<Number> coordinates = (DynamicArray<Number>) mVerts.get(i).getFieldValue("co");
vertices[i] = new Vector3f(coordinates.get(0).floatValue(), coordinates.get(1).floatValue(), coordinates.get(2).floatValue());
}
return vertices;
}
@Override
public boolean shouldBeLoaded(Structure structure, BlenderContext blenderContext) {
return true;
}
}
| true | true | public List<Geometry> toMesh(Structure structure, BlenderContext blenderContext) throws BlenderFileException {
List<Geometry> geometries = (List<Geometry>) blenderContext.getLoadedFeature(structure.getOldMemoryAddress(),
LoadedFeatureDataType.LOADED_FEATURE);
if (geometries != null) {
List<Geometry> copiedGeometries = new ArrayList<Geometry>(geometries.size());
for (Geometry geometry : geometries) {
copiedGeometries.add(geometry.clone());
}
return copiedGeometries;
}
// helpers
TextureHelper textureHelper = blenderContext.getHelper(TextureHelper.class);
// reading mesh data
String name = structure.getName();
MeshContext meshContext = new MeshContext();
// reading vertices
Vector3f[] vertices = this.getVertices(structure, blenderContext);
int verticesAmount = vertices.length;
// vertices Colors
List<float[]> verticesColors = this.getVerticesColors(structure, blenderContext);
// reading faces
// the following map sorts faces by material number (because in jme Mesh can have only one material)
Map<Integer, List<Integer>> meshesMap = new HashMap<Integer, List<Integer>>();
Pointer pMFace = (Pointer) structure.getFieldValue("mface");
List<Structure> mFaces = null;
if (pMFace.isNotNull()) {
mFaces = pMFace.fetchData(blenderContext.getInputStream());
if (mFaces == null || mFaces.size() == 0) {
return new ArrayList<Geometry>(0);
}
}
Pointer pMTFace = (Pointer) structure.getFieldValue("mtface");
List<Vector2f> uvCoordinates = null;
List<Structure> mtFaces = null;
if (pMTFace.isNotNull()) {
mtFaces = pMTFace.fetchData(blenderContext.getInputStream());
int facesAmount = ((Number) structure.getFieldValue("totface")).intValue();
if (mtFaces.size() != facesAmount) {
throw new BlenderFileException("The amount of faces uv coordinates is not equal to faces amount!");
}
uvCoordinates = new ArrayList<Vector2f>();
}
// normalMap merges normals of faces that will be rendered smooth
Map<Vector3f, Vector3f> normalMap = new HashMap<Vector3f, Vector3f>(verticesAmount);
List<Vector3f> normalList = new ArrayList<Vector3f>();
List<Vector3f> vertexList = new ArrayList<Vector3f>();
// indicates if the material with the specified number should have a texture attached
Map<Integer, Texture> materialNumberToTexture = new HashMap<Integer, Texture>();
// this map's key is the vertex index from 'vertices 'table and the value are indices from 'vertexList'
// positions (it simply tells which vertex is referenced where in the result list)
Map<Integer, List<Integer>> vertexReferenceMap = new HashMap<Integer, List<Integer>>(verticesAmount);
int vertexColorIndex = 0;
for (int i = 0; i < mFaces.size(); ++i) {
Structure mFace = mFaces.get(i);
boolean smooth = (((Number) mFace.getFieldValue("flag")).byteValue() & 0x01) != 0x00;
DynamicArray<Number> uvs = null;
boolean materialWithoutTextures = false;
Pointer pImage = null;
if (mtFaces != null) {
Structure mtFace = mtFaces.get(i);
pImage = (Pointer) mtFace.getFieldValue("tpage");
materialWithoutTextures = pImage.isNull();
// uvs always must be added wheater we have texture or not
uvs = (DynamicArray<Number>) mtFace.getFieldValue("uv");
uvCoordinates.add(new Vector2f(uvs.get(0, 0).floatValue(), uvs.get(0, 1).floatValue()));
uvCoordinates.add(new Vector2f(uvs.get(1, 0).floatValue(), uvs.get(1, 1).floatValue()));
uvCoordinates.add(new Vector2f(uvs.get(2, 0).floatValue(), uvs.get(2, 1).floatValue()));
}
int matNr = ((Number) mFace.getFieldValue("mat_nr")).intValue();
Integer materialNumber = Integer.valueOf(materialWithoutTextures ? -1 * matNr - 1 : matNr);
List<Integer> indexList = meshesMap.get(materialNumber);
if (indexList == null) {
indexList = new ArrayList<Integer>();
meshesMap.put(materialNumber, indexList);
}
// attaching image to texture (face can have UV's and image whlie its material may have no texture attached)
if (pImage != null && pImage.isNotNull() && !materialNumberToTexture.containsKey(materialNumber)) {
Texture texture = textureHelper.getTextureFromImage(pImage.fetchData(blenderContext.getInputStream()).get(0),
blenderContext);
if (texture != null) {
materialNumberToTexture.put(materialNumber, texture);
}
}
int v1 = ((Number) mFace.getFieldValue("v1")).intValue();
int v2 = ((Number) mFace.getFieldValue("v2")).intValue();
int v3 = ((Number) mFace.getFieldValue("v3")).intValue();
int v4 = ((Number) mFace.getFieldValue("v4")).intValue();
Vector3f n = FastMath.computeNormal(vertices[v1], vertices[v2], vertices[v3]);
this.addNormal(n, normalMap, smooth, vertices[v1], vertices[v2], vertices[v3]);
normalList.add(normalMap.get(vertices[v1]));
normalList.add(normalMap.get(vertices[v2]));
normalList.add(normalMap.get(vertices[v3]));
this.appendVertexReference(v1, vertexList.size(), vertexReferenceMap);
indexList.add(vertexList.size());
vertexList.add(vertices[v1]);
this.appendVertexReference(v2, vertexList.size(), vertexReferenceMap);
indexList.add(vertexList.size());
vertexList.add(vertices[v2]);
this.appendVertexReference(v3, vertexList.size(), vertexReferenceMap);
indexList.add(vertexList.size());
vertexList.add(vertices[v3]);
if (v4 > 0) {
if (uvs != null) {
uvCoordinates.add(new Vector2f(uvs.get(0, 0).floatValue(), uvs.get(0, 1).floatValue()));
uvCoordinates.add(new Vector2f(uvs.get(2, 0).floatValue(), uvs.get(2, 1).floatValue()));
uvCoordinates.add(new Vector2f(uvs.get(3, 0).floatValue(), uvs.get(3, 1).floatValue()));
}
this.appendVertexReference(v1, vertexList.size(), vertexReferenceMap);
indexList.add(vertexList.size());
vertexList.add(vertices[v1]);
this.appendVertexReference(v3, vertexList.size(), vertexReferenceMap);
indexList.add(vertexList.size());
vertexList.add(vertices[v3]);
this.appendVertexReference(v4, vertexList.size(), vertexReferenceMap);
indexList.add(vertexList.size());
vertexList.add(vertices[v4]);
this.addNormal(n, normalMap, smooth, vertices[v4]);
normalList.add(normalMap.get(vertices[v1]));
normalList.add(normalMap.get(vertices[v3]));
normalList.add(normalMap.get(vertices[v4]));
if (verticesColors != null) {
verticesColors.add(vertexColorIndex + 3, verticesColors.get(vertexColorIndex));
verticesColors.add(vertexColorIndex + 4, verticesColors.get(vertexColorIndex + 2));
}
vertexColorIndex += 6;
} else {
if (verticesColors != null) {
verticesColors.remove(vertexColorIndex + 3);
vertexColorIndex += 3;
}
}
}
meshContext.setVertexList(vertexList);
meshContext.setVertexReferenceMap(vertexReferenceMap);
Vector3f[] normals = normalList.toArray(new Vector3f[normalList.size()]);
// reading vertices groups (from the parent)
Structure parent = blenderContext.peekParent();
Structure defbase = (Structure) parent.getFieldValue("defbase");
List<Structure> defs = defbase.evaluateListBase(blenderContext);
String[] verticesGroups = new String[defs.size()];
int defIndex = 0;
for (Structure def : defs) {
verticesGroups[defIndex++] = def.getFieldValue("name").toString();
}
// reading materials
MaterialHelper materialHelper = blenderContext.getHelper(MaterialHelper.class);
Material[] materials = null;
Material[] nonTexturedMaterials = null;
if ((blenderContext.getBlenderKey().getFeaturesToLoad() & FeaturesToLoad.MATERIALS) != 0) {
materials = materialHelper.getMaterials(structure, blenderContext);
nonTexturedMaterials = materials == null ? null : new Material[materials.length];// fill it when needed
}
// creating the result meshes
geometries = new ArrayList<Geometry>(meshesMap.size());
VertexBuffer verticesBuffer = new VertexBuffer(Type.Position);
verticesBuffer.setupData(Usage.Stream, 3, Format.Float,
BufferUtils.createFloatBuffer(vertexList.toArray(new Vector3f[vertexList.size()])));
// initial vertex position (used with animation)
VertexBuffer verticesBind = new VertexBuffer(Type.BindPosePosition);
verticesBind.setupData(Usage.CpuOnly, 3, Format.Float, BufferUtils.clone(verticesBuffer.getData()));
VertexBuffer normalsBuffer = new VertexBuffer(Type.Normal);
normalsBuffer.setupData(Usage.Stream, 3, Format.Float, BufferUtils.createFloatBuffer(normals));
// initial normals position (used with animation)
VertexBuffer normalsBind = new VertexBuffer(Type.BindPoseNormal);
normalsBind.setupData(Usage.CpuOnly, 3, Format.Float, BufferUtils.clone(normalsBuffer.getData()));
VertexBuffer uvCoordsBuffer = null;
if (uvCoordinates != null) {
uvCoordsBuffer = new VertexBuffer(Type.TexCoord);
uvCoordsBuffer.setupData(Usage.Static, 2, Format.Float,
BufferUtils.createFloatBuffer(uvCoordinates.toArray(new Vector2f[uvCoordinates.size()])));
}
//reading custom properties
Properties properties = this.loadProperties(structure, blenderContext);
// generating meshes
FloatBuffer verticesColorsBuffer = this.createFloatBuffer(verticesColors);
for (Entry<Integer, List<Integer>> meshEntry : meshesMap.entrySet()) {
Mesh mesh = new Mesh();
// creating vertices indices for this mesh
List<Integer> indexList = meshEntry.getValue();
int[] indices = new int[indexList.size()];
for (int i = 0; i < indexList.size(); ++i) {
indices[i] = indexList.get(i).intValue();
}
// setting vertices
mesh.setBuffer(Type.Index, 1, indices);
mesh.setBuffer(verticesBuffer);
mesh.setBuffer(verticesBind);
// setting vertices colors
if (verticesColorsBuffer != null) {
mesh.setBuffer(Type.Color, 4, verticesColorsBuffer);
}
// setting faces' normals
mesh.setBuffer(normalsBuffer);
mesh.setBuffer(normalsBind);
// creating the result
Geometry geometry = new Geometry(name + (geometries.size() + 1), mesh);
if (materials != null) {
int materialNumber = meshEntry.getKey().intValue();
Material material;
if (materialNumber >= 0) {
material = materials[materialNumber];
if (materialNumberToTexture.containsKey(Integer.valueOf(materialNumber))) {
if (material.getMaterialDef().getAssetName().contains("Lighting")) {
if (!materialHelper.hasTexture(material, MaterialHelper.TEXTURE_TYPE_DIFFUSE)) {
material = material.clone();
material.setTexture(MaterialHelper.TEXTURE_TYPE_DIFFUSE,
materialNumberToTexture.get(Integer.valueOf(materialNumber)));
}
} else {
if (!materialHelper.hasTexture(material, MaterialHelper.TEXTURE_TYPE_COLOR)) {
material = material.clone();
material.setTexture(MaterialHelper.TEXTURE_TYPE_COLOR,
materialNumberToTexture.get(Integer.valueOf(materialNumber)));
}
}
}
} else {
materialNumber = -1 * (materialNumber + 1);
if (nonTexturedMaterials[materialNumber] == null) {
nonTexturedMaterials[materialNumber] = materialHelper.getNonTexturedMaterial(materials[materialNumber],
TextureHelper.TEX_IMAGE);
}
material = nonTexturedMaterials[materialNumber];
}
geometry.setMaterial(material);
if (material.isTransparent()) {
geometry.setQueueBucket(Bucket.Transparent);
}
} else {
geometry.setMaterial(blenderContext.getDefaultMaterial());
}
if (properties != null && properties.getValue() != null) {
geometry.setUserData("properties", properties);
}
geometries.add(geometry);
}
//applying uvCoordinates for all the meshes
if (uvCoordsBuffer != null) {
for (Geometry geom : geometries) {
geom.getMesh().setBuffer(uvCoordsBuffer);
}
} else {
Map<Material, List<Geometry>> materialMap = new HashMap<Material, List<Geometry>>();
for (Geometry geom : geometries) {
Material material = geom.getMaterial();
List<Geometry> geomsWithCommonMaterial = materialMap.get(material);
if (geomsWithCommonMaterial == null) {
geomsWithCommonMaterial = new ArrayList<Geometry>();
materialMap.put(material, geomsWithCommonMaterial);
}
geomsWithCommonMaterial.add(geom);
}
for (Entry<Material, List<Geometry>> entry : materialMap.entrySet()) {
MaterialContext materialContext = blenderContext.getMaterialContext(entry.getKey());
if (materialContext != null && materialContext.getTexturesCount() > 0) {
VertexBuffer coords = UVCoordinatesGenerator.generateUVCoordinates(materialContext.getUvCoordinatesType(),
materialContext.getProjectionType(), materialContext.getTextureDimension(),
materialContext.getProjection(0), entry.getValue());
//setting the coordinates inside the mesh context
for (Geometry geometry : entry.getValue()) {
meshContext.addUVCoordinates(geometry, coords);
}
}
}
}
blenderContext.addLoadedFeatures(structure.getOldMemoryAddress(), structure.getName(), structure, geometries);
blenderContext.setMeshContext(structure.getOldMemoryAddress(), meshContext);
return geometries;
}
| public List<Geometry> toMesh(Structure structure, BlenderContext blenderContext) throws BlenderFileException {
List<Geometry> geometries = (List<Geometry>) blenderContext.getLoadedFeature(structure.getOldMemoryAddress(),
LoadedFeatureDataType.LOADED_FEATURE);
if (geometries != null) {
List<Geometry> copiedGeometries = new ArrayList<Geometry>(geometries.size());
for (Geometry geometry : geometries) {
copiedGeometries.add(geometry.clone());
}
return copiedGeometries;
}
// helpers
TextureHelper textureHelper = blenderContext.getHelper(TextureHelper.class);
// reading mesh data
String name = structure.getName();
MeshContext meshContext = new MeshContext();
// reading vertices
Vector3f[] vertices = this.getVertices(structure, blenderContext);
int verticesAmount = vertices.length;
// vertices Colors
List<float[]> verticesColors = this.getVerticesColors(structure, blenderContext);
// reading faces
// the following map sorts faces by material number (because in jme Mesh can have only one material)
Map<Integer, List<Integer>> meshesMap = new HashMap<Integer, List<Integer>>();
Pointer pMFace = (Pointer) structure.getFieldValue("mface");
List<Structure> mFaces = null;
if (pMFace.isNotNull()) {
mFaces = pMFace.fetchData(blenderContext.getInputStream());
if (mFaces == null || mFaces.size() == 0) {
return new ArrayList<Geometry>(0);
}
} else{
mFaces = new ArrayList<Structure>(0);
}
Pointer pMTFace = (Pointer) structure.getFieldValue("mtface");
List<Vector2f> uvCoordinates = null;
List<Structure> mtFaces = null;
if (pMTFace.isNotNull()) {
mtFaces = pMTFace.fetchData(blenderContext.getInputStream());
int facesAmount = ((Number) structure.getFieldValue("totface")).intValue();
if (mtFaces.size() != facesAmount) {
throw new BlenderFileException("The amount of faces uv coordinates is not equal to faces amount!");
}
uvCoordinates = new ArrayList<Vector2f>();
}
// normalMap merges normals of faces that will be rendered smooth
Map<Vector3f, Vector3f> normalMap = new HashMap<Vector3f, Vector3f>(verticesAmount);
List<Vector3f> normalList = new ArrayList<Vector3f>();
List<Vector3f> vertexList = new ArrayList<Vector3f>();
// indicates if the material with the specified number should have a texture attached
Map<Integer, Texture> materialNumberToTexture = new HashMap<Integer, Texture>();
// this map's key is the vertex index from 'vertices 'table and the value are indices from 'vertexList'
// positions (it simply tells which vertex is referenced where in the result list)
Map<Integer, List<Integer>> vertexReferenceMap = new HashMap<Integer, List<Integer>>(verticesAmount);
int vertexColorIndex = 0;
for (int i = 0; i < mFaces.size(); ++i) {
Structure mFace = mFaces.get(i);
boolean smooth = (((Number) mFace.getFieldValue("flag")).byteValue() & 0x01) != 0x00;
DynamicArray<Number> uvs = null;
boolean materialWithoutTextures = false;
Pointer pImage = null;
if (mtFaces != null) {
Structure mtFace = mtFaces.get(i);
pImage = (Pointer) mtFace.getFieldValue("tpage");
materialWithoutTextures = pImage.isNull();
// uvs always must be added wheater we have texture or not
uvs = (DynamicArray<Number>) mtFace.getFieldValue("uv");
uvCoordinates.add(new Vector2f(uvs.get(0, 0).floatValue(), uvs.get(0, 1).floatValue()));
uvCoordinates.add(new Vector2f(uvs.get(1, 0).floatValue(), uvs.get(1, 1).floatValue()));
uvCoordinates.add(new Vector2f(uvs.get(2, 0).floatValue(), uvs.get(2, 1).floatValue()));
}
int matNr = ((Number) mFace.getFieldValue("mat_nr")).intValue();
Integer materialNumber = Integer.valueOf(materialWithoutTextures ? -1 * matNr - 1 : matNr);
List<Integer> indexList = meshesMap.get(materialNumber);
if (indexList == null) {
indexList = new ArrayList<Integer>();
meshesMap.put(materialNumber, indexList);
}
// attaching image to texture (face can have UV's and image whlie its material may have no texture attached)
if (pImage != null && pImage.isNotNull() && !materialNumberToTexture.containsKey(materialNumber)) {
Texture texture = textureHelper.getTextureFromImage(pImage.fetchData(blenderContext.getInputStream()).get(0),
blenderContext);
if (texture != null) {
materialNumberToTexture.put(materialNumber, texture);
}
}
int v1 = ((Number) mFace.getFieldValue("v1")).intValue();
int v2 = ((Number) mFace.getFieldValue("v2")).intValue();
int v3 = ((Number) mFace.getFieldValue("v3")).intValue();
int v4 = ((Number) mFace.getFieldValue("v4")).intValue();
Vector3f n = FastMath.computeNormal(vertices[v1], vertices[v2], vertices[v3]);
this.addNormal(n, normalMap, smooth, vertices[v1], vertices[v2], vertices[v3]);
normalList.add(normalMap.get(vertices[v1]));
normalList.add(normalMap.get(vertices[v2]));
normalList.add(normalMap.get(vertices[v3]));
this.appendVertexReference(v1, vertexList.size(), vertexReferenceMap);
indexList.add(vertexList.size());
vertexList.add(vertices[v1]);
this.appendVertexReference(v2, vertexList.size(), vertexReferenceMap);
indexList.add(vertexList.size());
vertexList.add(vertices[v2]);
this.appendVertexReference(v3, vertexList.size(), vertexReferenceMap);
indexList.add(vertexList.size());
vertexList.add(vertices[v3]);
if (v4 > 0) {
if (uvs != null) {
uvCoordinates.add(new Vector2f(uvs.get(0, 0).floatValue(), uvs.get(0, 1).floatValue()));
uvCoordinates.add(new Vector2f(uvs.get(2, 0).floatValue(), uvs.get(2, 1).floatValue()));
uvCoordinates.add(new Vector2f(uvs.get(3, 0).floatValue(), uvs.get(3, 1).floatValue()));
}
this.appendVertexReference(v1, vertexList.size(), vertexReferenceMap);
indexList.add(vertexList.size());
vertexList.add(vertices[v1]);
this.appendVertexReference(v3, vertexList.size(), vertexReferenceMap);
indexList.add(vertexList.size());
vertexList.add(vertices[v3]);
this.appendVertexReference(v4, vertexList.size(), vertexReferenceMap);
indexList.add(vertexList.size());
vertexList.add(vertices[v4]);
this.addNormal(n, normalMap, smooth, vertices[v4]);
normalList.add(normalMap.get(vertices[v1]));
normalList.add(normalMap.get(vertices[v3]));
normalList.add(normalMap.get(vertices[v4]));
if (verticesColors != null) {
verticesColors.add(vertexColorIndex + 3, verticesColors.get(vertexColorIndex));
verticesColors.add(vertexColorIndex + 4, verticesColors.get(vertexColorIndex + 2));
}
vertexColorIndex += 6;
} else {
if (verticesColors != null) {
verticesColors.remove(vertexColorIndex + 3);
vertexColorIndex += 3;
}
}
}
meshContext.setVertexList(vertexList);
meshContext.setVertexReferenceMap(vertexReferenceMap);
Vector3f[] normals = normalList.toArray(new Vector3f[normalList.size()]);
// reading vertices groups (from the parent)
Structure parent = blenderContext.peekParent();
Structure defbase = (Structure) parent.getFieldValue("defbase");
List<Structure> defs = defbase.evaluateListBase(blenderContext);
String[] verticesGroups = new String[defs.size()];
int defIndex = 0;
for (Structure def : defs) {
verticesGroups[defIndex++] = def.getFieldValue("name").toString();
}
// reading materials
MaterialHelper materialHelper = blenderContext.getHelper(MaterialHelper.class);
Material[] materials = null;
Material[] nonTexturedMaterials = null;
if ((blenderContext.getBlenderKey().getFeaturesToLoad() & FeaturesToLoad.MATERIALS) != 0) {
materials = materialHelper.getMaterials(structure, blenderContext);
nonTexturedMaterials = materials == null ? null : new Material[materials.length];// fill it when needed
}
// creating the result meshes
geometries = new ArrayList<Geometry>(meshesMap.size());
VertexBuffer verticesBuffer = new VertexBuffer(Type.Position);
verticesBuffer.setupData(Usage.Stream, 3, Format.Float,
BufferUtils.createFloatBuffer(vertexList.toArray(new Vector3f[vertexList.size()])));
// initial vertex position (used with animation)
VertexBuffer verticesBind = new VertexBuffer(Type.BindPosePosition);
verticesBind.setupData(Usage.CpuOnly, 3, Format.Float, BufferUtils.clone(verticesBuffer.getData()));
VertexBuffer normalsBuffer = new VertexBuffer(Type.Normal);
normalsBuffer.setupData(Usage.Stream, 3, Format.Float, BufferUtils.createFloatBuffer(normals));
// initial normals position (used with animation)
VertexBuffer normalsBind = new VertexBuffer(Type.BindPoseNormal);
normalsBind.setupData(Usage.CpuOnly, 3, Format.Float, BufferUtils.clone(normalsBuffer.getData()));
VertexBuffer uvCoordsBuffer = null;
if (uvCoordinates != null) {
uvCoordsBuffer = new VertexBuffer(Type.TexCoord);
uvCoordsBuffer.setupData(Usage.Static, 2, Format.Float,
BufferUtils.createFloatBuffer(uvCoordinates.toArray(new Vector2f[uvCoordinates.size()])));
}
//reading custom properties
Properties properties = this.loadProperties(structure, blenderContext);
// generating meshes
FloatBuffer verticesColorsBuffer = this.createFloatBuffer(verticesColors);
for (Entry<Integer, List<Integer>> meshEntry : meshesMap.entrySet()) {
Mesh mesh = new Mesh();
// creating vertices indices for this mesh
List<Integer> indexList = meshEntry.getValue();
int[] indices = new int[indexList.size()];
for (int i = 0; i < indexList.size(); ++i) {
indices[i] = indexList.get(i).intValue();
}
// setting vertices
mesh.setBuffer(Type.Index, 1, indices);
mesh.setBuffer(verticesBuffer);
mesh.setBuffer(verticesBind);
// setting vertices colors
if (verticesColorsBuffer != null) {
mesh.setBuffer(Type.Color, 4, verticesColorsBuffer);
}
// setting faces' normals
mesh.setBuffer(normalsBuffer);
mesh.setBuffer(normalsBind);
// creating the result
Geometry geometry = new Geometry(name + (geometries.size() + 1), mesh);
if (materials != null) {
int materialNumber = meshEntry.getKey().intValue();
Material material;
if (materialNumber >= 0) {
material = materials[materialNumber];
if (materialNumberToTexture.containsKey(Integer.valueOf(materialNumber))) {
if (material.getMaterialDef().getAssetName().contains("Lighting")) {
if (!materialHelper.hasTexture(material, MaterialHelper.TEXTURE_TYPE_DIFFUSE)) {
material = material.clone();
material.setTexture(MaterialHelper.TEXTURE_TYPE_DIFFUSE,
materialNumberToTexture.get(Integer.valueOf(materialNumber)));
}
} else {
if (!materialHelper.hasTexture(material, MaterialHelper.TEXTURE_TYPE_COLOR)) {
material = material.clone();
material.setTexture(MaterialHelper.TEXTURE_TYPE_COLOR,
materialNumberToTexture.get(Integer.valueOf(materialNumber)));
}
}
}
} else {
materialNumber = -1 * (materialNumber + 1);
if (nonTexturedMaterials[materialNumber] == null) {
nonTexturedMaterials[materialNumber] = materialHelper.getNonTexturedMaterial(materials[materialNumber],
TextureHelper.TEX_IMAGE);
}
material = nonTexturedMaterials[materialNumber];
}
geometry.setMaterial(material);
if (material.isTransparent()) {
geometry.setQueueBucket(Bucket.Transparent);
}
} else {
geometry.setMaterial(blenderContext.getDefaultMaterial());
}
if (properties != null && properties.getValue() != null) {
geometry.setUserData("properties", properties);
}
geometries.add(geometry);
}
//applying uvCoordinates for all the meshes
if (uvCoordsBuffer != null) {
for (Geometry geom : geometries) {
geom.getMesh().setBuffer(uvCoordsBuffer);
}
} else {
Map<Material, List<Geometry>> materialMap = new HashMap<Material, List<Geometry>>();
for (Geometry geom : geometries) {
Material material = geom.getMaterial();
List<Geometry> geomsWithCommonMaterial = materialMap.get(material);
if (geomsWithCommonMaterial == null) {
geomsWithCommonMaterial = new ArrayList<Geometry>();
materialMap.put(material, geomsWithCommonMaterial);
}
geomsWithCommonMaterial.add(geom);
}
for (Entry<Material, List<Geometry>> entry : materialMap.entrySet()) {
MaterialContext materialContext = blenderContext.getMaterialContext(entry.getKey());
if (materialContext != null && materialContext.getTexturesCount() > 0) {
VertexBuffer coords = UVCoordinatesGenerator.generateUVCoordinates(materialContext.getUvCoordinatesType(),
materialContext.getProjectionType(), materialContext.getTextureDimension(),
materialContext.getProjection(0), entry.getValue());
//setting the coordinates inside the mesh context
for (Geometry geometry : entry.getValue()) {
meshContext.addUVCoordinates(geometry, coords);
}
}
}
}
blenderContext.addLoadedFeatures(structure.getOldMemoryAddress(), structure.getName(), structure, geometries);
blenderContext.setMeshContext(structure.getOldMemoryAddress(), meshContext);
return geometries;
}
|
diff --git a/src/com/android/contacts/datepicker/DatePickerDialog.java b/src/com/android/contacts/datepicker/DatePickerDialog.java
index dbf1e25fa..112b96e1a 100644
--- a/src/com/android/contacts/datepicker/DatePickerDialog.java
+++ b/src/com/android/contacts/datepicker/DatePickerDialog.java
@@ -1,233 +1,232 @@
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.contacts.datepicker;
// This is a fork of the standard Android DatePicker that additionally allows toggling the year
// on/off. It uses some private API so that not everything has to be copied.
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils.TruncateAt;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import com.android.contacts.R;
import com.android.contacts.datepicker.DatePicker.OnDateChangedListener;
import java.text.DateFormatSymbols;
import java.util.Calendar;
/**
* A simple dialog containing an {@link DatePicker}.
*
* <p>See the <a href="{@docRoot}resources/tutorials/views/hello-datepicker.html">Date Picker
* tutorial</a>.</p>
*/
public class DatePickerDialog extends AlertDialog implements OnClickListener,
OnDateChangedListener {
private static final String YEAR = "year";
private static final String MONTH = "month";
private static final String DAY = "day";
private static final String YEAR_OPTIONAL = "year_optional";
private final DatePicker mDatePicker;
private final OnDateSetListener mCallBack;
private final Calendar mCalendar;
private final java.text.DateFormat mTitleDateFormat;
private final String[] mWeekDays;
private int mInitialYear;
private int mInitialMonth;
private int mInitialDay;
/**
* The callback used to indicate the user is done filling in the date.
*/
public interface OnDateSetListener {
/**
* @param view The view associated with this listener.
* @param year The year that was set or 0 if the user has not specified a year
* @param monthOfYear The month that was set (0-11) for compatibility
* with {@link java.util.Calendar}.
* @param dayOfMonth The day of the month that was set.
*/
void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth);
}
/**
* @param context The context the dialog is to run in.
* @param callBack How the parent is notified that the date is set.
* @param year The initial year of the dialog
* @param monthOfYear The initial month of the dialog.
* @param dayOfMonth The initial day of the dialog.
*/
public DatePickerDialog(Context context,
OnDateSetListener callBack,
int year,
int monthOfYear,
int dayOfMonth) {
this(context, callBack, year, monthOfYear, dayOfMonth, false);
}
/**
* @param context The context the dialog is to run in.
* @param callBack How the parent is notified that the date is set.
* @param year The initial year of the dialog or 0 if no year has been specified
* @param monthOfYear The initial month of the dialog.
* @param dayOfMonth The initial day of the dialog.
* @param yearOptional Whether the year can be toggled by the user
*/
public DatePickerDialog(Context context,
OnDateSetListener callBack,
int year,
int monthOfYear,
int dayOfMonth,
boolean yearOptional) {
this(context, context.getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.HONEYCOMB
? com.android.internal.R.style.Theme_Holo_Light_Dialog_Alert
: com.android.internal.R.style.Theme_Dialog_Alert,
callBack, year, monthOfYear, dayOfMonth, yearOptional);
}
/**
* @param context The context the dialog is to run in.
* @param theme the theme to apply to this dialog
* @param callBack How the parent is notified that the date is set.
* @param year The initial year of the dialog or 0 if no year has been specified
* @param monthOfYear The initial month of the dialog.
* @param dayOfMonth The initial day of the dialog.
*/
public DatePickerDialog(Context context,
int theme,
OnDateSetListener callBack,
int year,
int monthOfYear,
int dayOfMonth) {
this(context, theme, callBack, year, monthOfYear, dayOfMonth, false);
}
/**
* @param context The context the dialog is to run in.
* @param theme the theme to apply to this dialog
* @param callBack How the parent is notified that the date is set.
* @param year The initial year of the dialog.
* @param monthOfYear The initial month of the dialog.
* @param dayOfMonth The initial day of the dialog.
* @param yearOptional Whether the year can be toggled by the user
*/
public DatePickerDialog(Context context,
int theme,
OnDateSetListener callBack,
int year,
int monthOfYear,
int dayOfMonth,
boolean yearOptional) {
super(context, theme);
mCallBack = callBack;
mInitialYear = year;
mInitialMonth = monthOfYear;
mInitialDay = dayOfMonth;
DateFormatSymbols symbols = new DateFormatSymbols();
mWeekDays = symbols.getShortWeekdays();
mTitleDateFormat = java.text.DateFormat.
getDateInstance(java.text.DateFormat.FULL);
mCalendar = Calendar.getInstance();
updateTitle(mInitialYear, mInitialMonth, mInitialDay);
setButton(BUTTON_POSITIVE, context.getText(com.android.internal.R.string.date_time_set),
this);
setButton(BUTTON_NEGATIVE, context.getText(android.R.string.cancel),
(OnClickListener) null);
- setIcon(com.android.internal.R.drawable.ic_dialog_time);
LayoutInflater inflater =
(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.date_picker_dialog, null);
setView(view);
mDatePicker = (DatePicker) view.findViewById(R.id.datePicker);
mDatePicker.init(mInitialYear, mInitialMonth, mInitialDay, yearOptional, this);
}
@Override
public void show() {
super.show();
/* Sometimes the full month is displayed causing the title
* to be very long, in those cases ensure it doesn't wrap to
* 2 lines (as that looks jumpy) and ensure we ellipsize the end.
*/
TextView title = (TextView) findViewById(com.android.internal.R.id.alertTitle);
title.setSingleLine();
title.setEllipsize(TruncateAt.END);
}
public void onClick(DialogInterface dialog, int which) {
if (mCallBack != null) {
mDatePicker.clearFocus();
mCallBack.onDateSet(mDatePicker, mDatePicker.getYear(),
mDatePicker.getMonth(), mDatePicker.getDayOfMonth());
}
}
public void onDateChanged(DatePicker view, int year,
int month, int day) {
updateTitle(year, month, day);
}
public void updateDate(int year, int monthOfYear, int dayOfMonth) {
mInitialYear = year;
mInitialMonth = monthOfYear;
mInitialDay = dayOfMonth;
mDatePicker.updateDate(year, monthOfYear, dayOfMonth);
}
private void updateTitle(int year, int month, int day) {
mCalendar.set(Calendar.YEAR, year);
mCalendar.set(Calendar.MONTH, month);
mCalendar.set(Calendar.DAY_OF_MONTH, day);
setTitle(mTitleDateFormat.format(mCalendar.getTime()));
}
@Override
public Bundle onSaveInstanceState() {
Bundle state = super.onSaveInstanceState();
state.putInt(YEAR, mDatePicker.getYear());
state.putInt(MONTH, mDatePicker.getMonth());
state.putInt(DAY, mDatePicker.getDayOfMonth());
state.putBoolean(YEAR_OPTIONAL, mDatePicker.isYearOptional());
return state;
}
@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
int year = savedInstanceState.getInt(YEAR);
int month = savedInstanceState.getInt(MONTH);
int day = savedInstanceState.getInt(DAY);
boolean yearOptional = savedInstanceState.getBoolean(YEAR_OPTIONAL);
mDatePicker.init(year, month, day, yearOptional, this);
updateTitle(year, month, day);
}
}
| true | true | public DatePickerDialog(Context context,
int theme,
OnDateSetListener callBack,
int year,
int monthOfYear,
int dayOfMonth,
boolean yearOptional) {
super(context, theme);
mCallBack = callBack;
mInitialYear = year;
mInitialMonth = monthOfYear;
mInitialDay = dayOfMonth;
DateFormatSymbols symbols = new DateFormatSymbols();
mWeekDays = symbols.getShortWeekdays();
mTitleDateFormat = java.text.DateFormat.
getDateInstance(java.text.DateFormat.FULL);
mCalendar = Calendar.getInstance();
updateTitle(mInitialYear, mInitialMonth, mInitialDay);
setButton(BUTTON_POSITIVE, context.getText(com.android.internal.R.string.date_time_set),
this);
setButton(BUTTON_NEGATIVE, context.getText(android.R.string.cancel),
(OnClickListener) null);
setIcon(com.android.internal.R.drawable.ic_dialog_time);
LayoutInflater inflater =
(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.date_picker_dialog, null);
setView(view);
mDatePicker = (DatePicker) view.findViewById(R.id.datePicker);
mDatePicker.init(mInitialYear, mInitialMonth, mInitialDay, yearOptional, this);
}
| public DatePickerDialog(Context context,
int theme,
OnDateSetListener callBack,
int year,
int monthOfYear,
int dayOfMonth,
boolean yearOptional) {
super(context, theme);
mCallBack = callBack;
mInitialYear = year;
mInitialMonth = monthOfYear;
mInitialDay = dayOfMonth;
DateFormatSymbols symbols = new DateFormatSymbols();
mWeekDays = symbols.getShortWeekdays();
mTitleDateFormat = java.text.DateFormat.
getDateInstance(java.text.DateFormat.FULL);
mCalendar = Calendar.getInstance();
updateTitle(mInitialYear, mInitialMonth, mInitialDay);
setButton(BUTTON_POSITIVE, context.getText(com.android.internal.R.string.date_time_set),
this);
setButton(BUTTON_NEGATIVE, context.getText(android.R.string.cancel),
(OnClickListener) null);
LayoutInflater inflater =
(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.date_picker_dialog, null);
setView(view);
mDatePicker = (DatePicker) view.findViewById(R.id.datePicker);
mDatePicker.init(mInitialYear, mInitialMonth, mInitialDay, yearOptional, this);
}
|
diff --git a/src/dcpu16/Dcpu16ToolMain.java b/src/dcpu16/Dcpu16ToolMain.java
index c7db9fb..2813533 100644
--- a/src/dcpu16/Dcpu16ToolMain.java
+++ b/src/dcpu16/Dcpu16ToolMain.java
@@ -1,99 +1,99 @@
package dcpu16;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import dcpu16.assembler.Dcpu16Assembler;
import dcpu16.disassembler.Dcpu16Disassembler;
public class Dcpu16ToolMain {
private static final String EXTENTION_ASSEMBLY = ".dasm";
private static final String EXTENTION_BINARY = ".bin";
private static final String EXTENTION_DISASSEMBLY = ".disassembled.dasm";
/**
* @param args
*/
public static void main(String[] args) {
if(args.length != 1) {
System.err.println("Invalid number of arguments expected 1, got "+ args.length +".");
printHelp();
return;
}
String inputFilename = args[0];
- File inputFile = new File(inputFilename, "r");
+ File inputFile = new File(inputFilename);
if(! inputFile.exists()) {
System.err.println("Input file '"+ inputFilename +"' not found.");
printHelp();
return;
}
if(inputFilename.endsWith(EXTENTION_ASSEMBLY)) {
String outputFilename = inputFilename.substring(0, inputFilename.length() - EXTENTION_ASSEMBLY.length());
outputFilename += EXTENTION_BINARY;
assembleFile(inputFilename, outputFilename);
}
else if(inputFilename.endsWith(EXTENTION_BINARY)) {
String outputFilename = inputFilename.substring(0, inputFilename.length() - EXTENTION_BINARY.length());
outputFilename += EXTENTION_DISASSEMBLY;
disassembleFile(inputFilename, outputFilename);
}
else {
System.err.println("Unknown file extenstion");
printHelp();
}
}
private static void assembleFile(String inputFilename, String outputFilename) {
Dcpu16Assembler assembler = new Dcpu16Assembler();
FileOutputStream outputStream = null;;
try {
byte[] outputBytes = assembler.assembleFile(inputFilename);
File outputFile = new File(outputFilename);
outputStream = new FileOutputStream(outputFile);
outputStream.write(outputBytes);
}
catch(Exception e) {
e.printStackTrace(System.err);
}
finally {
try {
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
private static void disassembleFile(String inputFilename, String outputFilename) {
Dcpu16Disassembler disassembler = new Dcpu16Disassembler();
FileWriter outputStream = null;
try {
String disassembledData = disassembler.disassembleFile(inputFilename);
File outputFile = new File(outputFilename);
outputStream = new FileWriter(outputFile);
outputStream.write(disassembledData);
}
catch(Exception e) {
e.printStackTrace(System.err);
}
finally {
try {
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
private static void printHelp() {
System.err.println();
System.err.println("Usage: java -jar Dcpu16Tool.jar <filename>");
System.err.println(" - files with '"+ EXTENTION_ASSEMBLY +"' extension will be assembled.");
System.err.println(" - files with '"+ EXTENTION_BINARY +"' extension will be disassembled (not implemented).");
}
}
| true | true | public static void main(String[] args) {
if(args.length != 1) {
System.err.println("Invalid number of arguments expected 1, got "+ args.length +".");
printHelp();
return;
}
String inputFilename = args[0];
File inputFile = new File(inputFilename, "r");
if(! inputFile.exists()) {
System.err.println("Input file '"+ inputFilename +"' not found.");
printHelp();
return;
}
if(inputFilename.endsWith(EXTENTION_ASSEMBLY)) {
String outputFilename = inputFilename.substring(0, inputFilename.length() - EXTENTION_ASSEMBLY.length());
outputFilename += EXTENTION_BINARY;
assembleFile(inputFilename, outputFilename);
}
else if(inputFilename.endsWith(EXTENTION_BINARY)) {
String outputFilename = inputFilename.substring(0, inputFilename.length() - EXTENTION_BINARY.length());
outputFilename += EXTENTION_DISASSEMBLY;
disassembleFile(inputFilename, outputFilename);
}
else {
System.err.println("Unknown file extenstion");
printHelp();
}
}
| public static void main(String[] args) {
if(args.length != 1) {
System.err.println("Invalid number of arguments expected 1, got "+ args.length +".");
printHelp();
return;
}
String inputFilename = args[0];
File inputFile = new File(inputFilename);
if(! inputFile.exists()) {
System.err.println("Input file '"+ inputFilename +"' not found.");
printHelp();
return;
}
if(inputFilename.endsWith(EXTENTION_ASSEMBLY)) {
String outputFilename = inputFilename.substring(0, inputFilename.length() - EXTENTION_ASSEMBLY.length());
outputFilename += EXTENTION_BINARY;
assembleFile(inputFilename, outputFilename);
}
else if(inputFilename.endsWith(EXTENTION_BINARY)) {
String outputFilename = inputFilename.substring(0, inputFilename.length() - EXTENTION_BINARY.length());
outputFilename += EXTENTION_DISASSEMBLY;
disassembleFile(inputFilename, outputFilename);
}
else {
System.err.println("Unknown file extenstion");
printHelp();
}
}
|
diff --git a/src/org/jruby/ext/socket/RubyTCPSocket.java b/src/org/jruby/ext/socket/RubyTCPSocket.java
index db9c8a1e5..7d58bb3b6 100644
--- a/src/org/jruby/ext/socket/RubyTCPSocket.java
+++ b/src/org/jruby/ext/socket/RubyTCPSocket.java
@@ -1,147 +1,147 @@
/*
***** BEGIN LICENSE BLOCK *****
* Version: CPL 1.0/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Common 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://www.eclipse.org/legal/cpl-v10.html
*
* 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) 2007 Ola Bini <[email protected]>
* Copyright (C) 2007 Thomas E Enebo <[email protected]>
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the CPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the CPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****/
package org.jruby.ext.socket;
import java.io.IOException;
import java.net.ConnectException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.nio.channels.SocketChannel;
import org.jruby.Ruby;
import org.jruby.RubyClass;
import org.jruby.RubyNumeric;
import org.jruby.RubyString;
import org.jruby.runtime.Arity;
import org.jruby.runtime.CallbackFactory;
import org.jruby.runtime.Block;
import org.jruby.runtime.ObjectAllocator;
import org.jruby.runtime.builtin.IRubyObject;
public class RubyTCPSocket extends RubyIPSocket {
static void createTCPSocket(Ruby runtime) {
RubyClass rb_cTCPSocket = runtime.defineClass("TCPSocket", runtime.getClass("IPSocket"), TCPSOCKET_ALLOCATOR);
CallbackFactory cfact = runtime.callbackFactory(RubyTCPSocket.class);
rb_cTCPSocket.includeModule(runtime.getClass("Socket").getConstant("Constants"));
rb_cTCPSocket.defineFastMethod("initialize", cfact.getFastOptMethod("initialize"));
rb_cTCPSocket.defineFastMethod("setsockopt", cfact.getFastOptMethod("setsockopt"));
rb_cTCPSocket.getMetaClass().defineFastMethod("gethostbyname", cfact.getFastSingletonMethod("gethostbyname", IRubyObject.class));
rb_cTCPSocket.getMetaClass().defineMethod("open", cfact.getOptSingletonMethod("open"));
runtime.getObject().setConstant("TCPsocket",rb_cTCPSocket);
}
private static ObjectAllocator TCPSOCKET_ALLOCATOR = new ObjectAllocator() {
public IRubyObject allocate(Ruby runtime, RubyClass klass) {
return new RubyTCPSocket(runtime, klass);
}
};
public RubyTCPSocket(Ruby runtime, RubyClass type) {
super(runtime, type);
}
private int getPortFrom(IRubyObject arg) {
return RubyNumeric.fix2int(arg instanceof RubyString ?
RubyNumeric.str2inum(getRuntime(), (RubyString) arg, 0, true) : arg);
}
private InetAddress getAddress(String address) throws UnknownHostException {
return "localhost".equals(address) ? InetAddress.getLocalHost() : InetAddress.getByName(address);
}
public IRubyObject initialize(IRubyObject[] args) {
Arity.checkArgumentCount(getRuntime(), args, 2, 4);
String remoteHost = args[0].convertToString().toString();
int remotePort = getPortFrom(args[1]);
String localHost = args.length >= 3 ? args[2].convertToString().toString() : null;
int localPort = args.length == 4 ? getPortFrom(args[3]) : 0;
try {
Socket socket;
if (localHost != null) {
// We do not getAddress of localhost because for some reason TCP libs seem to not
// like 'localhost' for local host field in MRI.
socket = new Socket(getAddress(remoteHost), remotePort,
InetAddress.getByName(localHost), localPort);
} else {
- socket = new Socket(getAddress(remoteHost), remotePort);
+ socket = new Socket(InetAddress.getByName(remoteHost), remotePort);
}
SocketChannel channel = SocketChannel.open(socket.getRemoteSocketAddress());
channel.finishConnect();
setChannel(channel);
} catch(ConnectException e) {
throw getRuntime().newErrnoECONNREFUSEDError();
} catch(UnknownHostException e) {
throw sockerr(this, "initialize: name or service not known");
} catch(IOException e) {
throw sockerr(this, "initialize: name or service not known");
}
return this;
}
public IRubyObject setsockopt(IRubyObject[] args) {
// Stubbed out
return getRuntime().getNil();
}
public static IRubyObject open(IRubyObject recv, IRubyObject[] args, Block block) {
RubyTCPSocket sock = (RubyTCPSocket)recv.callMethod(recv.getRuntime().getCurrentContext(),"new",args);
if (!block.isGiven()) return sock;
try {
return block.yield(recv.getRuntime().getCurrentContext(), sock);
} finally {
if (sock.isOpen()) sock.close();
}
}
public static IRubyObject gethostbyname(IRubyObject recv, IRubyObject hostname) {
try {
IRubyObject[] ret = new IRubyObject[4];
Ruby r = recv.getRuntime();
InetAddress addr = InetAddress.getByName(hostname.convertToString().toString());
ret[0] = r.newString(addr.getCanonicalHostName());
ret[1] = r.newArray();
ret[2] = r.newFixnum(2); //AF_INET
ret[3] = r.newString(addr.getHostAddress());
return r.newArrayNoCopy(ret);
} catch(UnknownHostException e) {
throw sockerr(recv, "gethostbyname: name or service not known");
}
}
}
| true | true | public IRubyObject initialize(IRubyObject[] args) {
Arity.checkArgumentCount(getRuntime(), args, 2, 4);
String remoteHost = args[0].convertToString().toString();
int remotePort = getPortFrom(args[1]);
String localHost = args.length >= 3 ? args[2].convertToString().toString() : null;
int localPort = args.length == 4 ? getPortFrom(args[3]) : 0;
try {
Socket socket;
if (localHost != null) {
// We do not getAddress of localhost because for some reason TCP libs seem to not
// like 'localhost' for local host field in MRI.
socket = new Socket(getAddress(remoteHost), remotePort,
InetAddress.getByName(localHost), localPort);
} else {
socket = new Socket(getAddress(remoteHost), remotePort);
}
SocketChannel channel = SocketChannel.open(socket.getRemoteSocketAddress());
channel.finishConnect();
setChannel(channel);
} catch(ConnectException e) {
throw getRuntime().newErrnoECONNREFUSEDError();
} catch(UnknownHostException e) {
throw sockerr(this, "initialize: name or service not known");
} catch(IOException e) {
throw sockerr(this, "initialize: name or service not known");
}
return this;
}
| public IRubyObject initialize(IRubyObject[] args) {
Arity.checkArgumentCount(getRuntime(), args, 2, 4);
String remoteHost = args[0].convertToString().toString();
int remotePort = getPortFrom(args[1]);
String localHost = args.length >= 3 ? args[2].convertToString().toString() : null;
int localPort = args.length == 4 ? getPortFrom(args[3]) : 0;
try {
Socket socket;
if (localHost != null) {
// We do not getAddress of localhost because for some reason TCP libs seem to not
// like 'localhost' for local host field in MRI.
socket = new Socket(getAddress(remoteHost), remotePort,
InetAddress.getByName(localHost), localPort);
} else {
socket = new Socket(InetAddress.getByName(remoteHost), remotePort);
}
SocketChannel channel = SocketChannel.open(socket.getRemoteSocketAddress());
channel.finishConnect();
setChannel(channel);
} catch(ConnectException e) {
throw getRuntime().newErrnoECONNREFUSEDError();
} catch(UnknownHostException e) {
throw sockerr(this, "initialize: name or service not known");
} catch(IOException e) {
throw sockerr(this, "initialize: name or service not known");
}
return this;
}
|
diff --git a/src/uk/me/parabola/mkgmap/general/MapLine.java b/src/uk/me/parabola/mkgmap/general/MapLine.java
index 4d1114d3..1d376bf9 100644
--- a/src/uk/me/parabola/mkgmap/general/MapLine.java
+++ b/src/uk/me/parabola/mkgmap/general/MapLine.java
@@ -1,138 +1,138 @@
/*
* Copyright (C) 2006 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: 18-Dec-2006
*/
package uk.me.parabola.mkgmap.general;
import java.util.List;
import uk.me.parabola.imgfmt.app.Area;
import uk.me.parabola.imgfmt.app.Coord;
import uk.me.parabola.log.Logger;
/**
* Represent a line on a Garmin map. Lines are a list of points. They have
* a type (major highway, stream etc) and a name. And that is just about it.
*
* @author Steve Ratcliffe
*/
public class MapLine extends MapElement {
private static final Logger log = Logger.getLogger(MapLine.class);
private List<Coord> points;
private boolean direction; // set if direction is important.
private int minLat = Integer.MAX_VALUE;
private int minLong = Integer.MAX_VALUE;
private int maxLat = Integer.MIN_VALUE;
private int maxLong = Integer.MIN_VALUE;
private String ref;
public MapLine() {
}
public MapLine(MapLine orig) {
super(orig);
direction = orig.direction;
//roadDef = orig.roadDef;
}
public MapLine copy() {
return new MapLine(this);
}
public List<Coord> getPoints() {
return points;
}
public void setPoints(List<Coord> points) {
if (this.points != null)
log.warn("overwriting points");
assert points != null : "trying to set null points";
this.points = points;
Coord last = null;
for (Coord co : points) {
if (last != null && last.equals(co))
- log.warn("Line " + getName() + " has consecutive identical points at ", co.toDegreeString());
+ log.info("Line " + getName() + " has consecutive identical points at ", co.toDegreeString());
addToBounds(co);
last = co;
}
}
public boolean isDirection() {
return direction;
}
public void setDirection(boolean direction) {
this.direction = direction;
}
public boolean isRoad() {
return false;
}
public boolean isHighway() {
return false;
}
public String getRef() {
return ref;
}
public void setRef(String ref) {
this.ref = ref;
}
/**
* Get the mid-point of the bounding box for this element. This is as good
* an indication of 'where the element is' as any. Previously we just
* used the location of the first point which would lead to biases in
* allocating elements to subdivisions.
*
* @return The mid-point of the bounding box.
*/
public Coord getLocation() {
return new Coord((minLat + maxLat) / 2, (minLong + maxLong) / 2);
}
/**
* We build up the bounding box of this element by calling this routine.
*
* @param co The coordinate to add.
*/
private void addToBounds(Coord co) {
int lat = co.getLatitude();
if (lat < minLat)
minLat = lat;
if (lat > maxLat)
maxLat = lat;
int lon = co.getLongitude();
if (lon < minLong)
minLong = lon;
if (lon > maxLong)
maxLong = lon;
}
/**
* Get the region that this element covers.
*
* @return The area that bounds this element.
*/
public Area getBounds() {
return new Area(minLat, minLong, maxLat, maxLong);
}
}
| true | true | public void setPoints(List<Coord> points) {
if (this.points != null)
log.warn("overwriting points");
assert points != null : "trying to set null points";
this.points = points;
Coord last = null;
for (Coord co : points) {
if (last != null && last.equals(co))
log.warn("Line " + getName() + " has consecutive identical points at ", co.toDegreeString());
addToBounds(co);
last = co;
}
}
| public void setPoints(List<Coord> points) {
if (this.points != null)
log.warn("overwriting points");
assert points != null : "trying to set null points";
this.points = points;
Coord last = null;
for (Coord co : points) {
if (last != null && last.equals(co))
log.info("Line " + getName() + " has consecutive identical points at ", co.toDegreeString());
addToBounds(co);
last = co;
}
}
|
diff --git a/plugins/org.eclipse.emf.codegen.ecore/src/org/eclipse/emf/codegen/ecore/templates/editor/ModelWizard.java b/plugins/org.eclipse.emf.codegen.ecore/src/org/eclipse/emf/codegen/ecore/templates/editor/ModelWizard.java
index b5b617b81..8045656ee 100644
--- a/plugins/org.eclipse.emf.codegen.ecore/src/org/eclipse/emf/codegen/ecore/templates/editor/ModelWizard.java
+++ b/plugins/org.eclipse.emf.codegen.ecore/src/org/eclipse/emf/codegen/ecore/templates/editor/ModelWizard.java
@@ -1,313 +1,313 @@
package org.eclipse.emf.codegen.ecore.templates.editor;
import org.eclipse.emf.codegen.ecore.genmodel.*;
public class ModelWizard
{
protected final String NL = System.getProperties().getProperty("line.separator");
protected final String TEXT_1 = "";
protected final String TEXT_2 = "/**" + NL + " * <copyright>" + NL + " * </copyright>" + NL + " *" + NL + " * ";
protected final String TEXT_3 = "Id";
protected final String TEXT_4 = NL + " */" + NL + "package ";
protected final String TEXT_5 = ";" + NL + "" + NL + "" + NL + "import java.util.ArrayList;" + NL + "import java.util.Collections;" + NL + "import java.util.HashMap;" + NL + "import java.util.Iterator;" + NL + "import java.util.List;" + NL + "import java.util.Map;" + NL + "import java.util.StringTokenizer;" + NL + "" + NL + "import org.eclipse.emf.common.util.URI;" + NL + "" + NL + "import org.eclipse.emf.ecore.EClass;" + NL + "import org.eclipse.emf.ecore.EClassifier;" + NL + "" + NL + "import org.eclipse.emf.ecore.resource.Resource;" + NL + "import org.eclipse.emf.ecore.resource.ResourceSet;" + NL + "" + NL + "import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;" + NL + "" + NL + "import org.eclipse.emf.ecore.EObject;" + NL + "" + NL + "import org.eclipse.emf.ecore.xmi.XMLResource;" + NL + "" + NL + "import org.eclipse.emf.edit.ui.provider.ExtendedImageRegistry;" + NL + "" + NL + "import org.eclipse.core.resources.IContainer;" + NL + "import org.eclipse.core.resources.IFile;" + NL + "import org.eclipse.core.resources.IFolder;" + NL + "import org.eclipse.core.resources.IProject;" + NL + "import org.eclipse.core.resources.IResource;" + NL + "import org.eclipse.core.resources.ResourcesPlugin;" + NL + "" + NL + "import org.eclipse.core.runtime.IProgressMonitor;" + NL + "import org.eclipse.core.runtime.Path;" + NL + "" + NL + "import org.eclipse.jface.dialogs.MessageDialog;" + NL + "" + NL + "import org.eclipse.jface.viewers.ISelection;" + NL + "import org.eclipse.jface.viewers.IStructuredSelection;" + NL + "import org.eclipse.jface.viewers.StructuredSelection;" + NL + "" + NL + "import org.eclipse.jface.wizard.Wizard;" + NL + "import org.eclipse.jface.wizard.WizardPage;" + NL + "" + NL + "import org.eclipse.swt.SWT;" + NL + "" + NL + "import org.eclipse.swt.events.SelectionAdapter;" + NL + "import org.eclipse.swt.events.SelectionEvent;" + NL + "" + NL + "import org.eclipse.swt.layout.GridData;" + NL + "import org.eclipse.swt.layout.GridLayout;" + NL + "" + NL + "import org.eclipse.swt.widgets.Composite;" + NL + "import org.eclipse.swt.widgets.Label;" + NL + "" + NL + "import org.eclipse.swt.custom.CCombo;" + NL + "" + NL + "import org.eclipse.ui.INewWizard;" + NL + "import org.eclipse.ui.IWorkbench;" + NL + "import org.eclipse.ui.IWorkbenchPage;" + NL + "import org.eclipse.ui.IWorkbenchPart;" + NL + "import org.eclipse.ui.IWorkbenchWindow;" + NL + "import org.eclipse.ui.PartInitException;" + NL + "" + NL + "import org.eclipse.ui.actions.WorkspaceModifyOperation;" + NL + "" + NL + "import org.eclipse.ui.dialogs.WizardNewFileCreationPage;" + NL + "" + NL + "import org.eclipse.ui.part.FileEditorInput;" + NL + "import org.eclipse.ui.part.ISetSelectionTarget;" + NL + "" + NL + "import ";
protected final String TEXT_6 = ";" + NL + "import ";
protected final String TEXT_7 = ";" + NL + NL;
protected final String TEXT_8 = NL + NL + NL + "/**" + NL + " * This is a simple wizard for creating a new model file." + NL + " * <!-- begin-user-doc -->" + NL + " * <!-- end-user-doc -->" + NL + " * @generated" + NL + " */" + NL + "public class ";
protected final String TEXT_9 = " extends Wizard implements INewWizard" + NL + "{";
protected final String TEXT_10 = NL + "\t/**" + NL + "\t * <!-- begin-user-doc -->" + NL + "\t * <!-- end-user-doc -->" + NL + "\t * @generated" + NL + "\t */" + NL + "\tpublic static final ";
protected final String TEXT_11 = " copyright = \"";
protected final String TEXT_12 = "\";";
protected final String TEXT_13 = NL;
protected final String TEXT_14 = NL + "\t/**" + NL + "\t * This caches an instance of the model package." + NL + "\t * <!-- begin-user-doc -->" + NL + "\t * <!-- end-user-doc -->" + NL + "\t * @generated" + NL + "\t */" + NL + "\tprotected ";
protected final String TEXT_15 = " ";
protected final String TEXT_16 = " = ";
protected final String TEXT_17 = ".eINSTANCE;" + NL + "" + NL + "\t/**" + NL + "\t * This caches an instance of the model factory." + NL + "\t * <!-- begin-user-doc -->" + NL + "\t * <!-- end-user-doc -->" + NL + "\t * @generated" + NL + "\t */" + NL + "\tprotected ";
protected final String TEXT_18 = " ";
protected final String TEXT_19 = " = ";
protected final String TEXT_20 = ".get";
protected final String TEXT_21 = "();" + NL + "" + NL + "\t/**" + NL + "\t * This is the file creation page." + NL + "\t * <!-- begin-user-doc -->" + NL + "\t * <!-- end-user-doc -->" + NL + "\t * @generated" + NL + "\t */" + NL + "\tprotected ";
protected final String TEXT_22 = "NewFileCreationPage newFileCreationPage;" + NL + "" + NL + "\t/**" + NL + "\t * This is the file creation page." + NL + "\t * <!-- begin-user-doc -->" + NL + "\t * <!-- end-user-doc -->" + NL + "\t * @generated" + NL + "\t */" + NL + "\tprotected ";
protected final String TEXT_23 = "InitialObjectCreationPage initialObjectCreationPage;" + NL + "" + NL + "\t/**" + NL + "\t * Remember the selection during initialization for populating the default container." + NL + "\t * <!-- begin-user-doc -->" + NL + "\t * <!-- end-user-doc -->" + NL + "\t * @generated" + NL + "\t */" + NL + "\tprotected IStructuredSelection selection;" + NL + "" + NL + "\t/**" + NL + "\t * Remember the workbench during initialization." + NL + "\t * <!-- begin-user-doc -->" + NL + "\t * <!-- end-user-doc -->" + NL + "\t * @generated" + NL + "\t */" + NL + "\tprotected IWorkbench workbench;" + NL + "" + NL + "\t/**" + NL + "\t * This just records the information." + NL + "\t * <!-- begin-user-doc -->" + NL + "\t * <!-- end-user-doc -->" + NL + "\t * @generated" + NL + "\t */" + NL + "\tpublic void init(IWorkbench workbench, IStructuredSelection selection)" + NL + "\t{" + NL + "\t\tthis.workbench = workbench;" + NL + "\t\tthis.selection = selection;" + NL + "\t\tsetWindowTitle(";
protected final String TEXT_24 = ".INSTANCE.getString(\"_UI_Wizard_label\"));";
protected final String TEXT_25 = NL + "\t\tsetDefaultPageImageDescriptor(ExtendedImageRegistry.INSTANCE.getImageDescriptor(";
protected final String TEXT_26 = ".INSTANCE.getImage(\"full/wizban/New";
protected final String TEXT_27 = "\")));";
protected final String TEXT_28 = NL + "\t}" + NL + "" + NL + "\t/**" + NL + "\t * Create a new model." + NL + "\t * <!-- begin-user-doc -->" + NL + "\t * <!-- end-user-doc -->" + NL + "\t * @generated" + NL + "\t */" + NL + "\tEObject createInitialModel()" + NL + "\t{";
protected final String TEXT_29 = NL + "\t\tEClass eClass = (EClass)";
protected final String TEXT_30 = ".getEClassifier(initialObjectCreationPage.getInitialObjectName());" + NL + "\t\tEObject rootObject = ";
protected final String TEXT_31 = ".create(eClass);";
protected final String TEXT_32 = NL + "\t\tEClass eClass = ";
protected final String TEXT_33 = ".INSTANCE.getDocumentRoot(";
protected final String TEXT_34 = ");" + NL + "\t\tEStructuralFeature eStructuralFeature = eClass.getEStructuralFeature(initialObjectCreationPage.getInitialObjectName());" + NL + "\t\tEObject rootObject = ";
protected final String TEXT_35 = ".create(eClass);" + NL + "\t\trootObject.eSet(eStructuralFeature, ";
protected final String TEXT_36 = ".create((EClass)eStructuralFeature.getEType()));";
protected final String TEXT_37 = NL + "\t\treturn rootObject;" + NL + "\t}" + NL + "" + NL + "\t/**" + NL + "\t * Do the work after everything is specified." + NL + "\t * <!-- begin-user-doc -->" + NL + "\t * <!-- end-user-doc -->" + NL + "\t * @generated" + NL + "\t */" + NL + "\tpublic boolean performFinish()" + NL + "\t{" + NL + "\t\ttry" + NL + "\t\t{" + NL + "\t\t\t// Remember the file." + NL + "\t\t\t//" + NL + "\t\t\tfinal IFile modelFile = getModelFile();" + NL + "" + NL + "\t\t\t// Do the work within an operation." + NL + "\t\t\t//" + NL + "\t\t\tWorkspaceModifyOperation operation =" + NL + "\t\t\t\tnew WorkspaceModifyOperation()" + NL + "\t\t\t\t{" + NL + "\t\t\t\t\tprotected void execute(IProgressMonitor progressMonitor)" + NL + "\t\t\t\t\t{" + NL + "\t\t\t\t\t\ttry" + NL + "\t\t\t\t\t\t{" + NL + "\t\t\t\t\t\t\t// Create a resource set" + NL + "\t\t\t\t\t\t\t//" + NL + "\t\t\t\t\t\t\tResourceSet resourceSet = new ResourceSetImpl();" + NL + "" + NL + "\t\t\t\t\t\t\t// Get the URI of the model file." + NL + "\t\t\t\t\t\t\t//" + NL + "\t\t\t\t\t\t\tURI fileURI = URI.createPlatformResourceURI(modelFile.getFullPath().toString());" + NL + "" + NL + "\t\t\t\t\t\t\t// Create a resource for this file." + NL + "\t\t\t\t\t\t\t//" + NL + "\t\t\t\t\t\t\tResource resource = resourceSet.createResource(fileURI);" + NL + "" + NL + "\t\t\t\t\t\t\t// Add the initial model object to the contents." + NL + "\t\t\t\t\t\t\t//" + NL + "\t\t\t\t\t\t\tEObject rootObject = createInitialModel();" + NL + "\t\t\t\t\t\t\tif (rootObject != null)" + NL + "\t\t\t\t\t\t\t{" + NL + "\t\t\t\t\t\t\t\tresource.getContents().add(rootObject);" + NL + "\t\t\t\t\t\t\t}" + NL + "" + NL + "\t\t\t\t\t\t\t// Save the contents of the resource to the file system." + NL + "\t\t\t\t\t\t\t//" + NL + "\t\t\t\t\t\t\tMap options = new HashMap();" + NL + "\t\t\t\t\t\t\toptions.put(XMLResource.OPTION_ENCODING, initialObjectCreationPage.getEncoding());" + NL + "\t\t\t\t\t\t\tresource.save(options);" + NL + "\t\t\t\t\t\t}" + NL + "\t\t\t\t\t\tcatch (Exception exception)" + NL + "\t\t\t\t\t\t{" + NL + "\t\t\t\t\t\t\t";
protected final String TEXT_38 = ".INSTANCE.log(exception);" + NL + "\t\t\t\t\t\t}" + NL + "\t\t\t\t\t\tfinally" + NL + "\t\t\t\t\t\t{" + NL + "\t\t\t\t\t\t\tprogressMonitor.done();" + NL + "\t\t\t\t\t\t}" + NL + "\t\t\t\t\t}" + NL + "\t\t\t\t};" + NL + "" + NL + "\t\t\tgetContainer().run(false, false, operation);" + NL + "" + NL + "\t\t\t// Select the new file resource in the current view." + NL + "\t\t\t//" + NL + "\t\t\tIWorkbenchWindow workbenchWindow = workbench.getActiveWorkbenchWindow();" + NL + "\t\t\tIWorkbenchPage page = workbenchWindow.getActivePage();" + NL + "\t\t\tfinal IWorkbenchPart activePart = page.getActivePart();" + NL + "\t\t\tif (activePart instanceof ISetSelectionTarget)" + NL + "\t\t\t{" + NL + "\t\t\t\tfinal ISelection targetSelection = new StructuredSelection(modelFile);" + NL + "\t\t\t\tgetShell().getDisplay().asyncExec" + NL + "\t\t\t\t\t(new Runnable()" + NL + "\t\t\t\t\t {" + NL + "\t\t\t\t\t\t public void run()" + NL + "\t\t\t\t\t\t {" + NL + "\t\t\t\t\t\t\t ((ISetSelectionTarget)activePart).selectReveal(targetSelection);" + NL + "\t\t\t\t\t\t }" + NL + "\t\t\t\t\t });" + NL + "\t\t\t}" + NL + "" + NL + "\t\t\t// Open an editor on the new file." + NL + "\t\t\t//" + NL + "\t\t\ttry" + NL + "\t\t\t{" + NL + "\t\t\t\tpage.openEditor" + NL + "\t\t\t\t\t(new FileEditorInput(modelFile)," + NL + "\t\t\t\t\t workbench.getEditorRegistry().getDefaultEditor(modelFile.getFullPath().toString()).getId());" + NL + "\t\t\t}" + NL + "\t\t\tcatch (PartInitException exception)" + NL + "\t\t\t{" + NL + "\t\t\t\tMessageDialog.openError(workbenchWindow.getShell(), ";
protected final String TEXT_39 = ".INSTANCE.getString(\"_UI_OpenEditorError_label\"), exception.getMessage());";
protected final String TEXT_40 = NL + "\t\t\t\treturn false;" + NL + "\t\t\t}" + NL + "" + NL + "\t\t\treturn true;" + NL + "\t\t}" + NL + "\t\tcatch (Exception exception)" + NL + "\t\t{" + NL + "\t\t\t";
protected final String TEXT_41 = ".INSTANCE.log(exception);" + NL + "\t\t\treturn false;" + NL + "\t\t}" + NL + "\t}" + NL + "" + NL + "\t/**" + NL + "\t * This is the one page of the wizard." + NL + "\t * <!-- begin-user-doc -->" + NL + "\t * <!-- end-user-doc -->" + NL + "\t * @generated" + NL + "\t */" + NL + "\tpublic class ";
protected final String TEXT_42 = "NewFileCreationPage extends WizardNewFileCreationPage" + NL + "\t{" + NL + "\t\t/**" + NL + "\t\t * Remember the model file." + NL + "\t\t * <!-- begin-user-doc -->" + NL + "\t\t * <!-- end-user-doc -->" + NL + "\t\t * @generated" + NL + "\t\t */" + NL + "\t\tprotected IFile modelFile;" + NL + "" + NL + "\t\t/**" + NL + "\t\t * Pass in the selection." + NL + "\t\t * <!-- begin-user-doc -->" + NL + "\t\t * <!-- end-user-doc -->" + NL + "\t\t * @generated" + NL + "\t\t */" + NL + "\t\tpublic ";
protected final String TEXT_43 = "NewFileCreationPage(String pageId, IStructuredSelection selection)" + NL + "\t\t{" + NL + "\t\t\tsuper(pageId, selection);" + NL + "\t\t}" + NL + "" + NL + "\t\t/**" + NL + "\t\t * The framework calls this to see if the file is correct." + NL + "\t\t * <!-- begin-user-doc -->" + NL + "\t\t * <!-- end-user-doc -->" + NL + "\t\t * @generated" + NL + "\t\t */" + NL + "\t\tprotected boolean validatePage()" + NL + "\t\t{" + NL + "\t\t\tif (super.validatePage())" + NL + "\t\t\t{" + NL + "\t\t\t\t// Make sure the file ends in \".";
protected final String TEXT_44 = "\"." + NL + "\t\t\t\t//" + NL + "\t\t\t\tString requiredExt = ";
protected final String TEXT_45 = ".INSTANCE.getString(\"_UI_";
protected final String TEXT_46 = "FilenameExtension\");";
protected final String TEXT_47 = NL + "\t\t\t\tString enteredExt = new Path(getFileName()).getFileExtension();" + NL + "\t\t\t\tif (enteredExt == null || !enteredExt.equals(requiredExt))" + NL + "\t\t\t\t{" + NL + "\t\t\t\t\tsetErrorMessage(";
protected final String TEXT_48 = ".INSTANCE.getString(\"_WARN_FilenameExtension\", new Object [] { requiredExt }));";
protected final String TEXT_49 = NL + "\t\t\t\t\treturn false;" + NL + "\t\t\t\t}" + NL + "\t\t\t\telse" + NL + "\t\t\t\t{" + NL + "\t\t\t\t\treturn true;" + NL + "\t\t\t\t}" + NL + "\t\t\t}" + NL + "\t\t\telse" + NL + "\t\t\t{" + NL + "\t\t\t\treturn false;" + NL + "\t\t\t}" + NL + "\t\t}" + NL + "" + NL + "\t\t/**" + NL + "\t\t * Store the dialog field settings upon completion." + NL + "\t\t * <!-- begin-user-doc -->" + NL + "\t\t * <!-- end-user-doc -->" + NL + "\t\t * @generated" + NL + "\t\t */" + NL + "\t\tpublic boolean performFinish()" + NL + "\t\t{" + NL + "\t\t\tmodelFile = getModelFile();" + NL + "\t\t\treturn true;" + NL + "\t\t}" + NL + "" + NL + "\t\t/**" + NL + "\t\t * <!-- begin-user-doc -->" + NL + "\t\t * <!-- end-user-doc -->" + NL + "\t\t * @generated" + NL + "\t\t */" + NL + "\t\tpublic IFile getModelFile()" + NL + "\t\t{" + NL + "\t\t\treturn" + NL + "\t\t\t\tmodelFile == null ?" + NL + "\t\t\t\t\tResourcesPlugin.getWorkspace().getRoot().getFile(getContainerFullPath().append(getFileName())) :" + NL + "\t\t\t\t\tmodelFile;" + NL + "\t\t}" + NL + "\t}" + NL + "" + NL + "\t/**" + NL + "\t * This is the page where the type of object to create is selected." + NL + "\t * <!-- begin-user-doc -->" + NL + "\t * <!-- end-user-doc -->" + NL + "\t * @generated" + NL + "\t */" + NL + "\tpublic class ";
protected final String TEXT_50 = "InitialObjectCreationPage extends WizardPage" + NL + "\t{" + NL + "\t\t/**" + NL + "\t\t * @generated" + NL + "\t\t * <!-- begin-user-doc -->" + NL + "\t\t * <!-- end-user-doc -->" + NL + "\t\t */" + NL + "\t\tprotected String initialObjectName;" + NL + "" + NL + "\t\t/**" + NL + "\t\t * <!-- begin-user-doc -->" + NL + "\t\t * <!-- end-user-doc -->" + NL + "\t\t * @generated" + NL + "\t\t */" + NL + "\t\tprotected CCombo initialObjectField;" + NL + "" + NL + "\t\t/**" + NL + "\t\t * @generated" + NL + "\t\t * <!-- begin-user-doc -->" + NL + "\t\t * <!-- end-user-doc -->" + NL + "\t\t */" + NL + "\t\tprotected String encoding;" + NL + "" + NL + "\t\t/**" + NL + "\t\t * <!-- begin-user-doc -->" + NL + "\t\t * <!-- end-user-doc -->" + NL + "\t\t * @generated" + NL + "\t\t */" + NL + "\t\tprotected CCombo encodingField;" + NL + "" + NL + "\t\t/**" + NL + "\t\t * Pass in the selection." + NL + "\t\t * <!-- begin-user-doc -->" + NL + "\t\t * <!-- end-user-doc -->" + NL + "\t\t * @generated" + NL + "\t\t */" + NL + "\t\tpublic ";
protected final String TEXT_51 = "InitialObjectCreationPage(String pageId)" + NL + "\t\t{" + NL + "\t\t\tsuper(pageId);" + NL + "\t\t}" + NL + "" + NL + "\t\t/**" + NL + "\t\t * <!-- begin-user-doc -->" + NL + "\t\t * <!-- end-user-doc -->" + NL + "\t\t * @generated" + NL + "\t\t */" + NL + "\t\tpublic void createControl(Composite parent)" + NL + "\t\t{" + NL + "\t\t\tComposite composite = new Composite(parent, SWT.NONE);" + NL + "\t\t\t{" + NL + "\t\t\t\tGridLayout layout = new GridLayout();" + NL + "\t\t\t\tlayout.numColumns = 1;" + NL + "\t\t\t\tlayout.verticalSpacing = 12;" + NL + "\t\t\t\tcomposite.setLayout(layout);" + NL + "" + NL + "\t\t\t\tGridData data = new GridData();" + NL + "\t\t\t\tdata.verticalAlignment = GridData.FILL;" + NL + "\t\t\t\tdata.grabExcessVerticalSpace = true;" + NL + "\t\t\t\tdata.horizontalAlignment = GridData.FILL;" + NL + "\t\t\t\tcomposite.setLayoutData(data);" + NL + "\t\t\t}" + NL + "" + NL + "\t\t\tLabel containerLabel = new Label(composite, SWT.LEFT);" + NL + "\t\t\t{" + NL + "\t\t\t\tcontainerLabel.setText(";
protected final String TEXT_52 = ".INSTANCE.getString(\"_UI_ModelObject\"));";
protected final String TEXT_53 = NL + NL + "\t\t\t\tGridData data = new GridData();" + NL + "\t\t\t\tdata.horizontalAlignment = GridData.FILL;" + NL + "\t\t\t\tcontainerLabel.setLayoutData(data);" + NL + "\t\t\t}" + NL + "" + NL + "\t\t\tinitialObjectField = new CCombo(composite, SWT.BORDER);" + NL + "\t\t\t{" + NL + "\t\t\t\tGridData data = new GridData();" + NL + "\t\t\t\tdata.horizontalAlignment = GridData.FILL;" + NL + "\t\t\t\tdata.grabExcessHorizontalSpace = true;" + NL + "\t\t\t\tinitialObjectField.setLayoutData(data);" + NL + "\t\t\t}" + NL + "" + NL + "\t\t\tList objectNames = new ArrayList();";
protected final String TEXT_54 = NL + "\t\t\tfor (Iterator classifier = ";
protected final String TEXT_55 = ".getEClassifiers().iterator(); classifier.hasNext(); )" + NL + "\t\t\t{" + NL + "\t\t\t\tEClassifier eClassifier = (EClassifier)classifier.next();" + NL + "\t\t\t\tif (eClassifier instanceof EClass)" + NL + "\t\t\t\t{" + NL + "\t\t\t\t\tEClass eClass = (EClass)eClassifier;" + NL + "\t\t\t\t\tif (!eClass.isAbstract())" + NL + "\t\t\t\t\t{" + NL + "\t\t\t\t\t\tobjectNames.add(eClass.getName());" + NL + "\t\t\t\t\t}" + NL + "\t\t\t\t}" + NL + "\t\t\t}";
protected final String TEXT_56 = NL + "\t\t\tfor (Iterator elements = ";
protected final String TEXT_57 = ".INSTANCE.getAllElements(";
protected final String TEXT_58 = ".INSTANCE.getDocumentRoot(";
protected final String TEXT_59 = ")).iterator(); elements.hasNext(); )" + NL + "\t\t\t{" + NL + "\t\t\t\t";
protected final String TEXT_60 = " eStructuralFeature = (";
protected final String TEXT_61 = ")elements.next();" + NL + "\t\t\t\tEClassifier eClassifier = eStructuralFeature.getEType();" + NL + "\t\t\t\tif (eClassifier instanceof EClass)" + NL + "\t\t\t\t{" + NL + "\t\t\t\t\tEClass eClass = (EClass)eClassifier;" + NL + "\t\t\t\t\tif (!eClass.isAbstract())" + NL + "\t\t\t\t\t{" + NL + "\t\t\t\t\t\t// objectNames.add(eClass.getName());" + NL + "\t\t\t\t\t\tobjectNames.add(eStructuralFeature.getName());" + NL + "\t\t\t\t\t}" + NL + "\t\t\t\t}" + NL + "\t\t\t}";
protected final String TEXT_62 = NL + NL + "\t\t\tCollections.sort(objectNames, java.text.Collator.getInstance());" + NL + "\t\t\tfor (Iterator i = objectNames.iterator(); i.hasNext(); )" + NL + "\t\t\t{" + NL + "\t\t\t\tString objectName = (String)i.next();" + NL + "\t\t\t\tinitialObjectField.add(objectName);" + NL + "\t\t\t}" + NL + "" + NL + "\t\t\tinitialObjectField.addSelectionListener" + NL + "\t\t\t\t(new SelectionAdapter()" + NL + "\t\t\t\t {" + NL + "\t\t\t\t\t public void widgetSelected(SelectionEvent e)" + NL + "\t\t\t\t\t {" + NL + "\t\t\t\t\t\t setPageComplete(isPageComplete());" + NL + "\t\t\t\t\t }" + NL + "\t\t\t\t });" + NL + "" + NL + "\t\t\tLabel encodingLabel = new Label(composite, SWT.LEFT);" + NL + "\t\t\t{" + NL + "\t\t\t\tencodingLabel.setText(";
protected final String TEXT_63 = ".INSTANCE.getString(\"_UI_XMLEncoding\"));";
protected final String TEXT_64 = NL + NL + "\t\t\t\tGridData data = new GridData();" + NL + "\t\t\t\tdata.horizontalAlignment = GridData.FILL;" + NL + "\t\t\t\tencodingLabel.setLayoutData(data);" + NL + "\t\t\t}" + NL + "\t\t\tencodingField = new CCombo(composite, SWT.BORDER);" + NL + "\t\t\t{" + NL + "\t\t\t\tGridData data = new GridData();" + NL + "\t\t\t\tdata.horizontalAlignment = GridData.FILL;" + NL + "\t\t\t\tdata.grabExcessHorizontalSpace = true;" + NL + "\t\t\t\tencodingField.setLayoutData(data);" + NL + "\t\t\t}" + NL + "" + NL + "\t\t\tfor (StringTokenizer stringTokenizer = new StringTokenizer(";
protected final String TEXT_65 = ".INSTANCE.getString(\"_UI_XMLEncodingChoices\")); stringTokenizer.hasMoreTokens(); )" + NL + "\t\t\t{" + NL + "\t\t\t\tencodingField.add(stringTokenizer.nextToken());" + NL + "\t\t\t}" + NL + "\t\t\tencodingField.select(0);" + NL + "" + NL + "\t\t\tsetControl(composite);" + NL + "\t\t}" + NL + "" + NL + "\t\t/**" + NL + "\t\t * The framework calls this to see if the file is correct." + NL + "\t\t * <!-- begin-user-doc -->" + NL + "\t\t * <!-- end-user-doc -->" + NL + "\t\t * @generated" + NL + "\t\t */" + NL + "\t\tpublic boolean isPageComplete()" + NL + "\t\t{" + NL + "\t\t\tif (super.isPageComplete())" + NL + "\t\t\t{" + NL + "\t\t\t\treturn initialObjectField.getSelectionIndex() != -1;" + NL + "\t\t\t}" + NL + "\t\t\telse" + NL + "\t\t\t{" + NL + "\t\t\t\treturn false;" + NL + "\t\t\t}" + NL + "\t\t}" + NL + "" + NL + "\t\t/**" + NL + "\t\t * Store the dialog field settings upon completion." + NL + "\t\t * <!-- begin-user-doc -->" + NL + "\t\t * <!-- end-user-doc -->" + NL + "\t\t * @generated" + NL + "\t\t */" + NL + "\t\tpublic boolean performFinish()" + NL + "\t\t{" + NL + "\t\t\tinitialObjectName = getInitialObjectName();" + NL + "\t\t\tencoding = getEncoding();" + NL + "\t\t\treturn true;" + NL + "\t\t}" + NL + "" + NL + "\t\t/**" + NL + "\t\t * <!-- begin-user-doc -->" + NL + "\t\t * <!-- end-user-doc -->" + NL + "\t\t * @generated" + NL + "\t\t */" + NL + "\t\tpublic String getInitialObjectName()" + NL + "\t\t{" + NL + "\t\t\treturn" + NL + "\t\t\t\tinitialObjectName == null ?" + NL + "\t\t\t\t\tinitialObjectField.getText() :" + NL + "\t\t\t\t\tinitialObjectName;" + NL + "\t\t}" + NL + "" + NL + "\t\t/**" + NL + "\t\t * <!-- begin-user-doc -->" + NL + "\t\t * <!-- end-user-doc -->" + NL + "\t\t * @generated" + NL + "\t\t */" + NL + "\t\tpublic String getEncoding()" + NL + "\t\t{" + NL + "\t\t\treturn" + NL + "\t\t\t\tencoding == null ?" + NL + "\t\t\t\t\tencodingField.getText() :" + NL + "\t\t\t\t\tencoding;" + NL + "\t\t}" + NL + "\t}" + NL + "" + NL + "\t/**" + NL + "\t * The framework calls this to create the contents of the wizard." + NL + "\t * <!-- begin-user-doc -->" + NL + "\t * <!-- end-user-doc -->" + NL + "\t * @generated" + NL + "\t */" + NL + "\tpublic void addPages()" + NL + "\t{" + NL + "\t\t// Create a page, set the title, and the initial model file name." + NL + "\t\t//" + NL + "\t\tnewFileCreationPage = new ";
protected final String TEXT_66 = "NewFileCreationPage(\"Whatever\", selection);";
protected final String TEXT_67 = NL + "\t\tnewFileCreationPage.setTitle(";
protected final String TEXT_68 = ".INSTANCE.getString(\"_UI_";
protected final String TEXT_69 = "_label\"));";
protected final String TEXT_70 = NL + "\t\tnewFileCreationPage.setDescription(";
protected final String TEXT_71 = ".INSTANCE.getString(\"_UI_";
protected final String TEXT_72 = "_description\"));";
protected final String TEXT_73 = NL + "\t\tnewFileCreationPage.setFileName(";
protected final String TEXT_74 = ".INSTANCE.getString(\"_UI_";
protected final String TEXT_75 = "FilenameDefaultBase\") + \".\" + ";
protected final String TEXT_76 = ".INSTANCE.getString(\"_UI_";
protected final String TEXT_77 = "FilenameExtension\"));";
protected final String TEXT_78 = NL + "\t\taddPage(newFileCreationPage);" + NL + "" + NL + "\t\t// Try and get the resource selection to determine a current directory for the file dialog." + NL + "\t\t//" + NL + "\t\tif (selection != null && !selection.isEmpty())" + NL + "\t\t{" + NL + "\t\t\t// Get the resource..." + NL + "\t\t\t//" + NL + "\t\t\tObject selectedElement = selection.iterator().next();" + NL + "\t\t\tif (selectedElement instanceof IResource)" + NL + "\t\t\t{" + NL + "\t\t\t\t// Get the resource parent, if its a file." + NL + "\t\t\t\t//" + NL + "\t\t\t\tIResource selectedResource = (IResource)selectedElement;" + NL + "\t\t\t\tif (selectedResource.getType() == IResource.FILE)" + NL + "\t\t\t\t{" + NL + "\t\t\t\t\tselectedResource = selectedResource.getParent();" + NL + "\t\t\t\t}" + NL + "" + NL + "\t\t\t\t// This gives us a directory..." + NL + "\t\t\t\t//" + NL + "\t\t\t\tif (selectedResource instanceof IFolder || selectedResource instanceof IProject)" + NL + "\t\t\t\t{" + NL + "\t\t\t\t\t// Set this for the container." + NL + "\t\t\t\t\t//" + NL + "\t\t\t\t\tString currentDirectory = selectedResource.getLocation().toOSString();" + NL + "\t\t\t\t\tnewFileCreationPage.setContainerFullPath(selectedResource.getFullPath());" + NL + "" + NL + "\t\t\t\t\t// Make up a unique new name here." + NL + "\t\t\t\t\t//" + NL + "\t\t\t\t\tString defaultModelBaseFilename = ";
protected final String TEXT_79 = ".INSTANCE.getString(\"_UI_";
protected final String TEXT_80 = "FilenameDefaultBase\");";
protected final String TEXT_81 = NL + "\t\t\t\t\tString defaultModelFilenameExtension = ";
protected final String TEXT_82 = ".INSTANCE.getString(\"_UI_";
protected final String TEXT_83 = "FilenameExtension\");";
protected final String TEXT_84 = NL + "\t\t\t\t\tString modelFilename = defaultModelBaseFilename + \".\" + defaultModelFilenameExtension;";
protected final String TEXT_85 = NL + "\t\t\t\t\tfor (int i = 1; ((IContainer)selectedResource).findMember(modelFilename) != null; ++i)" + NL + "\t\t\t\t\t{" + NL + "\t\t\t\t\t\tmodelFilename = defaultModelBaseFilename + i + \".\" + defaultModelFilenameExtension;";
protected final String TEXT_86 = NL + "\t\t\t\t\t}" + NL + "\t\t\t\t\tnewFileCreationPage.setFileName(modelFilename);" + NL + "\t\t\t\t}" + NL + "\t\t\t}" + NL + "\t\t}" + NL + "\t\tinitialObjectCreationPage = new ";
protected final String TEXT_87 = "InitialObjectCreationPage(\"Whatever2\");";
protected final String TEXT_88 = NL + "\t\tinitialObjectCreationPage.setTitle(";
protected final String TEXT_89 = ".INSTANCE.getString(\"_UI_";
protected final String TEXT_90 = "_label\"));";
protected final String TEXT_91 = NL + "\t\tinitialObjectCreationPage.setDescription(";
protected final String TEXT_92 = ".INSTANCE.getString(\"_UI_Wizard_initial_object_description\"));";
protected final String TEXT_93 = NL + "\t\taddPage(initialObjectCreationPage);" + NL + "\t}" + NL + "" + NL + "\t/**" + NL + "\t * Get the file from the page." + NL + "\t * <!-- begin-user-doc -->" + NL + "\t * <!-- end-user-doc -->" + NL + "\t * @generated" + NL + "\t */" + NL + "\tpublic IFile getModelFile()" + NL + "\t{" + NL + "\t\treturn newFileCreationPage.getModelFile();" + NL + "\t}" + NL + "" + NL + "}";
protected final String TEXT_94 = NL;
public String generate(Object argument)
{
StringBuffer stringBuffer = new StringBuffer();
/**
* <copyright>
*
* Copyright (c) 2002-2004 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 - Initial API and implementation
*
* </copyright>
*/
GenPackage genPackage = (GenPackage)argument; GenModel genModel=genPackage.getGenModel();
stringBuffer.append(TEXT_1);
stringBuffer.append(TEXT_2);
stringBuffer.append("$");
stringBuffer.append(TEXT_3);
stringBuffer.append("$");
stringBuffer.append(TEXT_4);
stringBuffer.append(genPackage.getPresentationPackageName());
stringBuffer.append(TEXT_5);
stringBuffer.append(genPackage.getQualifiedFactoryInterfaceName());
stringBuffer.append(TEXT_6);
stringBuffer.append(genPackage.getQualifiedPackageInterfaceName());
stringBuffer.append(TEXT_7);
genModel.markImportLocation(stringBuffer);
stringBuffer.append(TEXT_8);
stringBuffer.append(genPackage.getModelWizardClassName());
stringBuffer.append(TEXT_9);
if (genModel.getCopyrightText() != null) {
stringBuffer.append(TEXT_10);
stringBuffer.append(genModel.getImportedName("java.lang.String"));
stringBuffer.append(TEXT_11);
stringBuffer.append(genModel.getCopyrightText());
stringBuffer.append(TEXT_12);
stringBuffer.append(genModel.getNonNLS());
stringBuffer.append(TEXT_13);
}
stringBuffer.append(TEXT_14);
stringBuffer.append(genPackage.getPackageInterfaceName());
stringBuffer.append(TEXT_15);
stringBuffer.append(genPackage.getUncapPackageInterfaceName());
stringBuffer.append(TEXT_16);
stringBuffer.append(genPackage.getPackageInterfaceName());
stringBuffer.append(TEXT_17);
stringBuffer.append(genPackage.getFactoryInterfaceName());
stringBuffer.append(TEXT_18);
stringBuffer.append(genPackage.getUncapFactoryInterfaceName());
stringBuffer.append(TEXT_19);
stringBuffer.append(genPackage.getUncapPackageInterfaceName());
stringBuffer.append(TEXT_20);
stringBuffer.append(genPackage.getFactoryInterfaceName());
stringBuffer.append(TEXT_21);
stringBuffer.append(genPackage.getModelWizardClassName());
stringBuffer.append(TEXT_22);
stringBuffer.append(genPackage.getModelWizardClassName());
stringBuffer.append(TEXT_23);
stringBuffer.append(genPackage.getImportedEditorPluginClassName());
stringBuffer.append(TEXT_24);
stringBuffer.append(genModel.getNonNLS());
stringBuffer.append(TEXT_25);
stringBuffer.append(genPackage.getImportedEditorPluginClassName());
stringBuffer.append(TEXT_26);
stringBuffer.append(genPackage.getPrefix());
stringBuffer.append(TEXT_27);
stringBuffer.append(genModel.getNonNLS());
stringBuffer.append(TEXT_28);
if (!genPackage.hasDocumentRoot()) {
stringBuffer.append(TEXT_29);
stringBuffer.append(genPackage.getUncapPackageInterfaceName());
stringBuffer.append(TEXT_30);
stringBuffer.append(genPackage.getUncapFactoryInterfaceName());
stringBuffer.append(TEXT_31);
} else {
stringBuffer.append(TEXT_32);
stringBuffer.append(genModel.getImportedName("org.eclipse.emf.ecore.util.ExtendedMetaData"));
stringBuffer.append(TEXT_33);
stringBuffer.append(genPackage.getUncapPackageInterfaceName());
stringBuffer.append(TEXT_34);
stringBuffer.append(genPackage.getUncapFactoryInterfaceName());
stringBuffer.append(TEXT_35);
- stringBuffer.append(genPackage.getUncapFactoryInterfaceName());
+ stringBuffer.append(genModel.getImportedName("org.eclipse.emf.ecore.util.EcoreUtil"));
stringBuffer.append(TEXT_36);
}
stringBuffer.append(TEXT_37);
stringBuffer.append(genPackage.getImportedEditorPluginClassName());
stringBuffer.append(TEXT_38);
stringBuffer.append(genPackage.getImportedEditorPluginClassName());
stringBuffer.append(TEXT_39);
stringBuffer.append(genModel.getNonNLS());
stringBuffer.append(TEXT_40);
stringBuffer.append(genPackage.getImportedEditorPluginClassName());
stringBuffer.append(TEXT_41);
stringBuffer.append(genPackage.getModelWizardClassName());
stringBuffer.append(TEXT_42);
stringBuffer.append(genPackage.getModelWizardClassName());
stringBuffer.append(TEXT_43);
stringBuffer.append(genPackage.getPrefix().toLowerCase());
stringBuffer.append(TEXT_44);
stringBuffer.append(genPackage.getImportedEditorPluginClassName());
stringBuffer.append(TEXT_45);
stringBuffer.append(genPackage.getEditorClassName());
stringBuffer.append(TEXT_46);
stringBuffer.append(genModel.getNonNLS());
stringBuffer.append(TEXT_47);
stringBuffer.append(genPackage.getImportedEditorPluginClassName());
stringBuffer.append(TEXT_48);
stringBuffer.append(genModel.getNonNLS());
stringBuffer.append(TEXT_49);
stringBuffer.append(genPackage.getModelWizardClassName());
stringBuffer.append(TEXT_50);
stringBuffer.append(genPackage.getModelWizardClassName());
stringBuffer.append(TEXT_51);
stringBuffer.append(genPackage.getImportedEditorPluginClassName());
stringBuffer.append(TEXT_52);
stringBuffer.append(genModel.getNonNLS());
stringBuffer.append(TEXT_53);
if (!genPackage.hasDocumentRoot()) {
stringBuffer.append(TEXT_54);
stringBuffer.append(genPackage.getUncapPackageInterfaceName());
stringBuffer.append(TEXT_55);
} else {
stringBuffer.append(TEXT_56);
stringBuffer.append(genModel.getImportedName("org.eclipse.emf.ecore.util.ExtendedMetaData"));
stringBuffer.append(TEXT_57);
stringBuffer.append(genModel.getImportedName("org.eclipse.emf.ecore.util.ExtendedMetaData"));
stringBuffer.append(TEXT_58);
stringBuffer.append(genPackage.getUncapPackageInterfaceName());
stringBuffer.append(TEXT_59);
stringBuffer.append(genModel.getImportedName("org.eclipse.emf.ecore.EStructuralFeature"));
stringBuffer.append(TEXT_60);
stringBuffer.append(genModel.getImportedName("org.eclipse.emf.ecore.EStructuralFeature"));
stringBuffer.append(TEXT_61);
}
stringBuffer.append(TEXT_62);
stringBuffer.append(genPackage.getImportedEditorPluginClassName());
stringBuffer.append(TEXT_63);
stringBuffer.append(genModel.getNonNLS());
stringBuffer.append(TEXT_64);
stringBuffer.append(genPackage.getImportedEditorPluginClassName());
stringBuffer.append(TEXT_65);
stringBuffer.append(genPackage.getModelWizardClassName());
stringBuffer.append(TEXT_66);
stringBuffer.append(genModel.getNonNLS());
stringBuffer.append(TEXT_67);
stringBuffer.append(genPackage.getImportedEditorPluginClassName());
stringBuffer.append(TEXT_68);
stringBuffer.append(genPackage.getModelWizardClassName());
stringBuffer.append(TEXT_69);
stringBuffer.append(genModel.getNonNLS());
stringBuffer.append(TEXT_70);
stringBuffer.append(genPackage.getImportedEditorPluginClassName());
stringBuffer.append(TEXT_71);
stringBuffer.append(genPackage.getModelWizardClassName());
stringBuffer.append(TEXT_72);
stringBuffer.append(genModel.getNonNLS());
stringBuffer.append(TEXT_73);
stringBuffer.append(genPackage.getImportedEditorPluginClassName());
stringBuffer.append(TEXT_74);
stringBuffer.append(genPackage.getEditorClassName());
stringBuffer.append(TEXT_75);
stringBuffer.append(genPackage.getImportedEditorPluginClassName());
stringBuffer.append(TEXT_76);
stringBuffer.append(genPackage.getEditorClassName());
stringBuffer.append(TEXT_77);
stringBuffer.append(genModel.getNonNLS());
stringBuffer.append(genModel.getNonNLS(2));
stringBuffer.append(genModel.getNonNLS(3));
stringBuffer.append(TEXT_78);
stringBuffer.append(genPackage.getImportedEditorPluginClassName());
stringBuffer.append(TEXT_79);
stringBuffer.append(genPackage.getEditorClassName());
stringBuffer.append(TEXT_80);
stringBuffer.append(genModel.getNonNLS());
stringBuffer.append(TEXT_81);
stringBuffer.append(genPackage.getImportedEditorPluginClassName());
stringBuffer.append(TEXT_82);
stringBuffer.append(genPackage.getEditorClassName());
stringBuffer.append(TEXT_83);
stringBuffer.append(genModel.getNonNLS());
stringBuffer.append(TEXT_84);
stringBuffer.append(genModel.getNonNLS());
stringBuffer.append(TEXT_85);
stringBuffer.append(genModel.getNonNLS());
stringBuffer.append(TEXT_86);
stringBuffer.append(genPackage.getModelWizardClassName());
stringBuffer.append(TEXT_87);
stringBuffer.append(genModel.getNonNLS());
stringBuffer.append(TEXT_88);
stringBuffer.append(genPackage.getImportedEditorPluginClassName());
stringBuffer.append(TEXT_89);
stringBuffer.append(genPackage.getModelWizardClassName());
stringBuffer.append(TEXT_90);
stringBuffer.append(genModel.getNonNLS());
stringBuffer.append(TEXT_91);
stringBuffer.append(genPackage.getImportedEditorPluginClassName());
stringBuffer.append(TEXT_92);
stringBuffer.append(genModel.getNonNLS());
stringBuffer.append(TEXT_93);
genModel.emitSortedImports();
stringBuffer.append(TEXT_94);
return stringBuffer.toString();
}
}
| true | true | public String generate(Object argument)
{
StringBuffer stringBuffer = new StringBuffer();
/**
* <copyright>
*
* Copyright (c) 2002-2004 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 - Initial API and implementation
*
* </copyright>
*/
GenPackage genPackage = (GenPackage)argument; GenModel genModel=genPackage.getGenModel();
stringBuffer.append(TEXT_1);
stringBuffer.append(TEXT_2);
stringBuffer.append("$");
stringBuffer.append(TEXT_3);
stringBuffer.append("$");
stringBuffer.append(TEXT_4);
stringBuffer.append(genPackage.getPresentationPackageName());
stringBuffer.append(TEXT_5);
stringBuffer.append(genPackage.getQualifiedFactoryInterfaceName());
stringBuffer.append(TEXT_6);
stringBuffer.append(genPackage.getQualifiedPackageInterfaceName());
stringBuffer.append(TEXT_7);
genModel.markImportLocation(stringBuffer);
stringBuffer.append(TEXT_8);
stringBuffer.append(genPackage.getModelWizardClassName());
stringBuffer.append(TEXT_9);
if (genModel.getCopyrightText() != null) {
stringBuffer.append(TEXT_10);
stringBuffer.append(genModel.getImportedName("java.lang.String"));
stringBuffer.append(TEXT_11);
stringBuffer.append(genModel.getCopyrightText());
stringBuffer.append(TEXT_12);
stringBuffer.append(genModel.getNonNLS());
stringBuffer.append(TEXT_13);
}
stringBuffer.append(TEXT_14);
stringBuffer.append(genPackage.getPackageInterfaceName());
stringBuffer.append(TEXT_15);
stringBuffer.append(genPackage.getUncapPackageInterfaceName());
stringBuffer.append(TEXT_16);
stringBuffer.append(genPackage.getPackageInterfaceName());
stringBuffer.append(TEXT_17);
stringBuffer.append(genPackage.getFactoryInterfaceName());
stringBuffer.append(TEXT_18);
stringBuffer.append(genPackage.getUncapFactoryInterfaceName());
stringBuffer.append(TEXT_19);
stringBuffer.append(genPackage.getUncapPackageInterfaceName());
stringBuffer.append(TEXT_20);
stringBuffer.append(genPackage.getFactoryInterfaceName());
stringBuffer.append(TEXT_21);
stringBuffer.append(genPackage.getModelWizardClassName());
stringBuffer.append(TEXT_22);
stringBuffer.append(genPackage.getModelWizardClassName());
stringBuffer.append(TEXT_23);
stringBuffer.append(genPackage.getImportedEditorPluginClassName());
stringBuffer.append(TEXT_24);
stringBuffer.append(genModel.getNonNLS());
stringBuffer.append(TEXT_25);
stringBuffer.append(genPackage.getImportedEditorPluginClassName());
stringBuffer.append(TEXT_26);
stringBuffer.append(genPackage.getPrefix());
stringBuffer.append(TEXT_27);
stringBuffer.append(genModel.getNonNLS());
stringBuffer.append(TEXT_28);
if (!genPackage.hasDocumentRoot()) {
stringBuffer.append(TEXT_29);
stringBuffer.append(genPackage.getUncapPackageInterfaceName());
stringBuffer.append(TEXT_30);
stringBuffer.append(genPackage.getUncapFactoryInterfaceName());
stringBuffer.append(TEXT_31);
} else {
stringBuffer.append(TEXT_32);
stringBuffer.append(genModel.getImportedName("org.eclipse.emf.ecore.util.ExtendedMetaData"));
stringBuffer.append(TEXT_33);
stringBuffer.append(genPackage.getUncapPackageInterfaceName());
stringBuffer.append(TEXT_34);
stringBuffer.append(genPackage.getUncapFactoryInterfaceName());
stringBuffer.append(TEXT_35);
stringBuffer.append(genPackage.getUncapFactoryInterfaceName());
stringBuffer.append(TEXT_36);
}
stringBuffer.append(TEXT_37);
stringBuffer.append(genPackage.getImportedEditorPluginClassName());
stringBuffer.append(TEXT_38);
stringBuffer.append(genPackage.getImportedEditorPluginClassName());
stringBuffer.append(TEXT_39);
stringBuffer.append(genModel.getNonNLS());
stringBuffer.append(TEXT_40);
stringBuffer.append(genPackage.getImportedEditorPluginClassName());
stringBuffer.append(TEXT_41);
stringBuffer.append(genPackage.getModelWizardClassName());
stringBuffer.append(TEXT_42);
stringBuffer.append(genPackage.getModelWizardClassName());
stringBuffer.append(TEXT_43);
stringBuffer.append(genPackage.getPrefix().toLowerCase());
stringBuffer.append(TEXT_44);
stringBuffer.append(genPackage.getImportedEditorPluginClassName());
stringBuffer.append(TEXT_45);
stringBuffer.append(genPackage.getEditorClassName());
stringBuffer.append(TEXT_46);
stringBuffer.append(genModel.getNonNLS());
stringBuffer.append(TEXT_47);
stringBuffer.append(genPackage.getImportedEditorPluginClassName());
stringBuffer.append(TEXT_48);
stringBuffer.append(genModel.getNonNLS());
stringBuffer.append(TEXT_49);
stringBuffer.append(genPackage.getModelWizardClassName());
stringBuffer.append(TEXT_50);
stringBuffer.append(genPackage.getModelWizardClassName());
stringBuffer.append(TEXT_51);
stringBuffer.append(genPackage.getImportedEditorPluginClassName());
stringBuffer.append(TEXT_52);
stringBuffer.append(genModel.getNonNLS());
stringBuffer.append(TEXT_53);
if (!genPackage.hasDocumentRoot()) {
stringBuffer.append(TEXT_54);
stringBuffer.append(genPackage.getUncapPackageInterfaceName());
stringBuffer.append(TEXT_55);
} else {
stringBuffer.append(TEXT_56);
stringBuffer.append(genModel.getImportedName("org.eclipse.emf.ecore.util.ExtendedMetaData"));
stringBuffer.append(TEXT_57);
stringBuffer.append(genModel.getImportedName("org.eclipse.emf.ecore.util.ExtendedMetaData"));
stringBuffer.append(TEXT_58);
stringBuffer.append(genPackage.getUncapPackageInterfaceName());
stringBuffer.append(TEXT_59);
stringBuffer.append(genModel.getImportedName("org.eclipse.emf.ecore.EStructuralFeature"));
stringBuffer.append(TEXT_60);
stringBuffer.append(genModel.getImportedName("org.eclipse.emf.ecore.EStructuralFeature"));
stringBuffer.append(TEXT_61);
}
stringBuffer.append(TEXT_62);
stringBuffer.append(genPackage.getImportedEditorPluginClassName());
stringBuffer.append(TEXT_63);
stringBuffer.append(genModel.getNonNLS());
stringBuffer.append(TEXT_64);
stringBuffer.append(genPackage.getImportedEditorPluginClassName());
stringBuffer.append(TEXT_65);
stringBuffer.append(genPackage.getModelWizardClassName());
stringBuffer.append(TEXT_66);
stringBuffer.append(genModel.getNonNLS());
stringBuffer.append(TEXT_67);
stringBuffer.append(genPackage.getImportedEditorPluginClassName());
stringBuffer.append(TEXT_68);
stringBuffer.append(genPackage.getModelWizardClassName());
stringBuffer.append(TEXT_69);
stringBuffer.append(genModel.getNonNLS());
stringBuffer.append(TEXT_70);
stringBuffer.append(genPackage.getImportedEditorPluginClassName());
stringBuffer.append(TEXT_71);
stringBuffer.append(genPackage.getModelWizardClassName());
stringBuffer.append(TEXT_72);
stringBuffer.append(genModel.getNonNLS());
stringBuffer.append(TEXT_73);
stringBuffer.append(genPackage.getImportedEditorPluginClassName());
stringBuffer.append(TEXT_74);
stringBuffer.append(genPackage.getEditorClassName());
stringBuffer.append(TEXT_75);
stringBuffer.append(genPackage.getImportedEditorPluginClassName());
stringBuffer.append(TEXT_76);
stringBuffer.append(genPackage.getEditorClassName());
stringBuffer.append(TEXT_77);
stringBuffer.append(genModel.getNonNLS());
stringBuffer.append(genModel.getNonNLS(2));
stringBuffer.append(genModel.getNonNLS(3));
stringBuffer.append(TEXT_78);
stringBuffer.append(genPackage.getImportedEditorPluginClassName());
stringBuffer.append(TEXT_79);
stringBuffer.append(genPackage.getEditorClassName());
stringBuffer.append(TEXT_80);
stringBuffer.append(genModel.getNonNLS());
stringBuffer.append(TEXT_81);
stringBuffer.append(genPackage.getImportedEditorPluginClassName());
stringBuffer.append(TEXT_82);
stringBuffer.append(genPackage.getEditorClassName());
stringBuffer.append(TEXT_83);
stringBuffer.append(genModel.getNonNLS());
stringBuffer.append(TEXT_84);
stringBuffer.append(genModel.getNonNLS());
stringBuffer.append(TEXT_85);
stringBuffer.append(genModel.getNonNLS());
stringBuffer.append(TEXT_86);
stringBuffer.append(genPackage.getModelWizardClassName());
stringBuffer.append(TEXT_87);
stringBuffer.append(genModel.getNonNLS());
stringBuffer.append(TEXT_88);
stringBuffer.append(genPackage.getImportedEditorPluginClassName());
stringBuffer.append(TEXT_89);
stringBuffer.append(genPackage.getModelWizardClassName());
stringBuffer.append(TEXT_90);
stringBuffer.append(genModel.getNonNLS());
stringBuffer.append(TEXT_91);
stringBuffer.append(genPackage.getImportedEditorPluginClassName());
stringBuffer.append(TEXT_92);
stringBuffer.append(genModel.getNonNLS());
stringBuffer.append(TEXT_93);
genModel.emitSortedImports();
stringBuffer.append(TEXT_94);
return stringBuffer.toString();
}
| public String generate(Object argument)
{
StringBuffer stringBuffer = new StringBuffer();
/**
* <copyright>
*
* Copyright (c) 2002-2004 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 - Initial API and implementation
*
* </copyright>
*/
GenPackage genPackage = (GenPackage)argument; GenModel genModel=genPackage.getGenModel();
stringBuffer.append(TEXT_1);
stringBuffer.append(TEXT_2);
stringBuffer.append("$");
stringBuffer.append(TEXT_3);
stringBuffer.append("$");
stringBuffer.append(TEXT_4);
stringBuffer.append(genPackage.getPresentationPackageName());
stringBuffer.append(TEXT_5);
stringBuffer.append(genPackage.getQualifiedFactoryInterfaceName());
stringBuffer.append(TEXT_6);
stringBuffer.append(genPackage.getQualifiedPackageInterfaceName());
stringBuffer.append(TEXT_7);
genModel.markImportLocation(stringBuffer);
stringBuffer.append(TEXT_8);
stringBuffer.append(genPackage.getModelWizardClassName());
stringBuffer.append(TEXT_9);
if (genModel.getCopyrightText() != null) {
stringBuffer.append(TEXT_10);
stringBuffer.append(genModel.getImportedName("java.lang.String"));
stringBuffer.append(TEXT_11);
stringBuffer.append(genModel.getCopyrightText());
stringBuffer.append(TEXT_12);
stringBuffer.append(genModel.getNonNLS());
stringBuffer.append(TEXT_13);
}
stringBuffer.append(TEXT_14);
stringBuffer.append(genPackage.getPackageInterfaceName());
stringBuffer.append(TEXT_15);
stringBuffer.append(genPackage.getUncapPackageInterfaceName());
stringBuffer.append(TEXT_16);
stringBuffer.append(genPackage.getPackageInterfaceName());
stringBuffer.append(TEXT_17);
stringBuffer.append(genPackage.getFactoryInterfaceName());
stringBuffer.append(TEXT_18);
stringBuffer.append(genPackage.getUncapFactoryInterfaceName());
stringBuffer.append(TEXT_19);
stringBuffer.append(genPackage.getUncapPackageInterfaceName());
stringBuffer.append(TEXT_20);
stringBuffer.append(genPackage.getFactoryInterfaceName());
stringBuffer.append(TEXT_21);
stringBuffer.append(genPackage.getModelWizardClassName());
stringBuffer.append(TEXT_22);
stringBuffer.append(genPackage.getModelWizardClassName());
stringBuffer.append(TEXT_23);
stringBuffer.append(genPackage.getImportedEditorPluginClassName());
stringBuffer.append(TEXT_24);
stringBuffer.append(genModel.getNonNLS());
stringBuffer.append(TEXT_25);
stringBuffer.append(genPackage.getImportedEditorPluginClassName());
stringBuffer.append(TEXT_26);
stringBuffer.append(genPackage.getPrefix());
stringBuffer.append(TEXT_27);
stringBuffer.append(genModel.getNonNLS());
stringBuffer.append(TEXT_28);
if (!genPackage.hasDocumentRoot()) {
stringBuffer.append(TEXT_29);
stringBuffer.append(genPackage.getUncapPackageInterfaceName());
stringBuffer.append(TEXT_30);
stringBuffer.append(genPackage.getUncapFactoryInterfaceName());
stringBuffer.append(TEXT_31);
} else {
stringBuffer.append(TEXT_32);
stringBuffer.append(genModel.getImportedName("org.eclipse.emf.ecore.util.ExtendedMetaData"));
stringBuffer.append(TEXT_33);
stringBuffer.append(genPackage.getUncapPackageInterfaceName());
stringBuffer.append(TEXT_34);
stringBuffer.append(genPackage.getUncapFactoryInterfaceName());
stringBuffer.append(TEXT_35);
stringBuffer.append(genModel.getImportedName("org.eclipse.emf.ecore.util.EcoreUtil"));
stringBuffer.append(TEXT_36);
}
stringBuffer.append(TEXT_37);
stringBuffer.append(genPackage.getImportedEditorPluginClassName());
stringBuffer.append(TEXT_38);
stringBuffer.append(genPackage.getImportedEditorPluginClassName());
stringBuffer.append(TEXT_39);
stringBuffer.append(genModel.getNonNLS());
stringBuffer.append(TEXT_40);
stringBuffer.append(genPackage.getImportedEditorPluginClassName());
stringBuffer.append(TEXT_41);
stringBuffer.append(genPackage.getModelWizardClassName());
stringBuffer.append(TEXT_42);
stringBuffer.append(genPackage.getModelWizardClassName());
stringBuffer.append(TEXT_43);
stringBuffer.append(genPackage.getPrefix().toLowerCase());
stringBuffer.append(TEXT_44);
stringBuffer.append(genPackage.getImportedEditorPluginClassName());
stringBuffer.append(TEXT_45);
stringBuffer.append(genPackage.getEditorClassName());
stringBuffer.append(TEXT_46);
stringBuffer.append(genModel.getNonNLS());
stringBuffer.append(TEXT_47);
stringBuffer.append(genPackage.getImportedEditorPluginClassName());
stringBuffer.append(TEXT_48);
stringBuffer.append(genModel.getNonNLS());
stringBuffer.append(TEXT_49);
stringBuffer.append(genPackage.getModelWizardClassName());
stringBuffer.append(TEXT_50);
stringBuffer.append(genPackage.getModelWizardClassName());
stringBuffer.append(TEXT_51);
stringBuffer.append(genPackage.getImportedEditorPluginClassName());
stringBuffer.append(TEXT_52);
stringBuffer.append(genModel.getNonNLS());
stringBuffer.append(TEXT_53);
if (!genPackage.hasDocumentRoot()) {
stringBuffer.append(TEXT_54);
stringBuffer.append(genPackage.getUncapPackageInterfaceName());
stringBuffer.append(TEXT_55);
} else {
stringBuffer.append(TEXT_56);
stringBuffer.append(genModel.getImportedName("org.eclipse.emf.ecore.util.ExtendedMetaData"));
stringBuffer.append(TEXT_57);
stringBuffer.append(genModel.getImportedName("org.eclipse.emf.ecore.util.ExtendedMetaData"));
stringBuffer.append(TEXT_58);
stringBuffer.append(genPackage.getUncapPackageInterfaceName());
stringBuffer.append(TEXT_59);
stringBuffer.append(genModel.getImportedName("org.eclipse.emf.ecore.EStructuralFeature"));
stringBuffer.append(TEXT_60);
stringBuffer.append(genModel.getImportedName("org.eclipse.emf.ecore.EStructuralFeature"));
stringBuffer.append(TEXT_61);
}
stringBuffer.append(TEXT_62);
stringBuffer.append(genPackage.getImportedEditorPluginClassName());
stringBuffer.append(TEXT_63);
stringBuffer.append(genModel.getNonNLS());
stringBuffer.append(TEXT_64);
stringBuffer.append(genPackage.getImportedEditorPluginClassName());
stringBuffer.append(TEXT_65);
stringBuffer.append(genPackage.getModelWizardClassName());
stringBuffer.append(TEXT_66);
stringBuffer.append(genModel.getNonNLS());
stringBuffer.append(TEXT_67);
stringBuffer.append(genPackage.getImportedEditorPluginClassName());
stringBuffer.append(TEXT_68);
stringBuffer.append(genPackage.getModelWizardClassName());
stringBuffer.append(TEXT_69);
stringBuffer.append(genModel.getNonNLS());
stringBuffer.append(TEXT_70);
stringBuffer.append(genPackage.getImportedEditorPluginClassName());
stringBuffer.append(TEXT_71);
stringBuffer.append(genPackage.getModelWizardClassName());
stringBuffer.append(TEXT_72);
stringBuffer.append(genModel.getNonNLS());
stringBuffer.append(TEXT_73);
stringBuffer.append(genPackage.getImportedEditorPluginClassName());
stringBuffer.append(TEXT_74);
stringBuffer.append(genPackage.getEditorClassName());
stringBuffer.append(TEXT_75);
stringBuffer.append(genPackage.getImportedEditorPluginClassName());
stringBuffer.append(TEXT_76);
stringBuffer.append(genPackage.getEditorClassName());
stringBuffer.append(TEXT_77);
stringBuffer.append(genModel.getNonNLS());
stringBuffer.append(genModel.getNonNLS(2));
stringBuffer.append(genModel.getNonNLS(3));
stringBuffer.append(TEXT_78);
stringBuffer.append(genPackage.getImportedEditorPluginClassName());
stringBuffer.append(TEXT_79);
stringBuffer.append(genPackage.getEditorClassName());
stringBuffer.append(TEXT_80);
stringBuffer.append(genModel.getNonNLS());
stringBuffer.append(TEXT_81);
stringBuffer.append(genPackage.getImportedEditorPluginClassName());
stringBuffer.append(TEXT_82);
stringBuffer.append(genPackage.getEditorClassName());
stringBuffer.append(TEXT_83);
stringBuffer.append(genModel.getNonNLS());
stringBuffer.append(TEXT_84);
stringBuffer.append(genModel.getNonNLS());
stringBuffer.append(TEXT_85);
stringBuffer.append(genModel.getNonNLS());
stringBuffer.append(TEXT_86);
stringBuffer.append(genPackage.getModelWizardClassName());
stringBuffer.append(TEXT_87);
stringBuffer.append(genModel.getNonNLS());
stringBuffer.append(TEXT_88);
stringBuffer.append(genPackage.getImportedEditorPluginClassName());
stringBuffer.append(TEXT_89);
stringBuffer.append(genPackage.getModelWizardClassName());
stringBuffer.append(TEXT_90);
stringBuffer.append(genModel.getNonNLS());
stringBuffer.append(TEXT_91);
stringBuffer.append(genPackage.getImportedEditorPluginClassName());
stringBuffer.append(TEXT_92);
stringBuffer.append(genModel.getNonNLS());
stringBuffer.append(TEXT_93);
genModel.emitSortedImports();
stringBuffer.append(TEXT_94);
return stringBuffer.toString();
}
|
diff --git a/src/main/java/br/com/wobr/reports/config/JasperReportModule.java b/src/main/java/br/com/wobr/reports/config/JasperReportModule.java
index 3370d03..c252d03 100644
--- a/src/main/java/br/com/wobr/reports/config/JasperReportModule.java
+++ b/src/main/java/br/com/wobr/reports/config/JasperReportModule.java
@@ -1,35 +1,35 @@
package br.com.wobr.reports.config;
import net.sf.jasperreports.engine.JasperPrint;
import br.com.wobr.reports.AbstractReportProcessor;
import br.com.wobr.reports.ReportExporter;
import br.com.wobr.reports.ReportProcessor;
import br.com.wobr.reports.ReportProcessorFacade;
import br.com.wobr.reports.jasper.JasperReportExporter;
import br.com.wobr.reports.jasper.JasperReportProcessorForJava;
import br.com.wobr.reports.jasper.JasperReportProcessorForModel;
import br.com.wobr.reports.jasper.JasperReportProcessorForTemplate;
import com.google.inject.AbstractModule;
import com.google.inject.TypeLiteral;
import com.google.inject.multibindings.Multibinder;
import com.google.inject.name.Names;
public class JasperReportModule extends AbstractModule
{
@Override
protected void configure()
{
- Multibinder<AbstractReportProcessor> uriBinder = Multibinder.newSetBinder( binder(), AbstractReportProcessor.class, Names.named( "ForFacade" ) );
+ Multibinder<ReportProcessor> uriBinder = Multibinder.newSetBinder( binder(), ReportProcessor.class, Names.named( "ForFacade" ) );
uriBinder.addBinding().to( JasperReportProcessorForTemplate.class );
uriBinder.addBinding().to( JasperReportProcessorForJava.class );
uriBinder.addBinding().to( JasperReportProcessorForModel.class );
bind( ReportProcessor.class ).to( ReportProcessorFacade.class );
bind( new TypeLiteral<ReportExporter<JasperPrint>>()
{
} ).to( JasperReportExporter.class );
}
}
| true | true | protected void configure()
{
Multibinder<AbstractReportProcessor> uriBinder = Multibinder.newSetBinder( binder(), AbstractReportProcessor.class, Names.named( "ForFacade" ) );
uriBinder.addBinding().to( JasperReportProcessorForTemplate.class );
uriBinder.addBinding().to( JasperReportProcessorForJava.class );
uriBinder.addBinding().to( JasperReportProcessorForModel.class );
bind( ReportProcessor.class ).to( ReportProcessorFacade.class );
bind( new TypeLiteral<ReportExporter<JasperPrint>>()
{
} ).to( JasperReportExporter.class );
}
| protected void configure()
{
Multibinder<ReportProcessor> uriBinder = Multibinder.newSetBinder( binder(), ReportProcessor.class, Names.named( "ForFacade" ) );
uriBinder.addBinding().to( JasperReportProcessorForTemplate.class );
uriBinder.addBinding().to( JasperReportProcessorForJava.class );
uriBinder.addBinding().to( JasperReportProcessorForModel.class );
bind( ReportProcessor.class ).to( ReportProcessorFacade.class );
bind( new TypeLiteral<ReportExporter<JasperPrint>>()
{
} ).to( JasperReportExporter.class );
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.