input
stringlengths 20
285k
| output
stringlengths 20
285k
|
---|---|
public void onInteract(PlayerInteractEvent event) {
ItemStack item = event.getItem();
if (item != null && item.hasItemMeta() && event.getAction().name().contains("RIGHT")) {
if (isSpecialItem(item, flashItemName)) {
event.setCancelled(true);
event.getPlayer().updateInventory();
if (item.getTypeId() == flashOffItemId) {
event.getPlayer()
.sendMessage(
String.format(cooldownMessage,
(-(HungergamesApi.getHungergames().currentTime - cooldown.get(item)))));
} else if (item.getType() == Material.REDSTONE_TORCH_ON) {
List<Block> b = event.getPlayer().getLastTwoTargetBlocks(ignoreBlockTypes, maxTeleportDistance);
if (b.size() > 1 && b.get(1).getType() != Material.AIR) {
double dist = event.getPlayer().getLocation().distance(b.get(0).getLocation());
if (dist > 2) {
Location loc = b.get(0).getLocation().clone().add(0.5, 0.5, 0.5);
item.setTypeId(flashOnItemId);
int hisCooldown = normalCooldown;
if (addMoreCooldownForLargeDistances && (dist / 2) > 30)
hisCooldown = (int) (dist / 2);
cooldown.put(item, hisCooldown + HungergamesApi.getHungergames().currentTime);
Location pLoc = event.getPlayer().getLocation();
loc.setPitch(pLoc.getPitch());
loc.setYaw(pLoc.getYaw());
event.getPlayer().teleport(loc);
pLoc.getWorld().playSound(pLoc, Sound.ENDERMAN_TELEPORT, 1, 1.2F);
pLoc.getWorld().playSound(loc, Sound.ENDERMAN_TELEPORT, 1, 1.2F);
((CraftWorld) pLoc.getWorld()).getHandle().addParticle("portal", pLoc.getX(), pLoc.getY(),
pLoc.getZ(), loc.getX(), loc.getY(), loc.getZ());
((CraftWorld) pLoc.getWorld()).getHandle().addParticle("portal", loc.getX(), loc.getY(), loc.getZ(),
pLoc.getX(), pLoc.getY(), pLoc.getZ());
if (giveWeakness)
event.getPlayer().addPotionEffect(
new PotionEffect(PotionEffectType.WEAKNESS, (int) ((dist / 2) * 20), 1), true);
pLoc.getWorld().strikeLightningEffect(loc);
}
}
}
}
}
}
| public void onInteract(PlayerInteractEvent event) {
ItemStack item = event.getItem();
if (item != null && item.hasItemMeta() && event.getAction().name().contains("RIGHT")) {
if (isSpecialItem(item, flashItemName)) {
event.setCancelled(true);
event.getPlayer().updateInventory();
if (item.getTypeId() == flashOffItemId) {
event.getPlayer()
.sendMessage(
String.format(cooldownMessage,
(-(HungergamesApi.getHungergames().currentTime - cooldown.get(item)))));
} else if (item.getType() == Material.REDSTONE_TORCH_ON) {
List<Block> b = event.getPlayer().getLastTwoTargetBlocks(ignoreBlockTypes, maxTeleportDistance);
if (b.size() > 1 && b.get(1).getType() != Material.AIR) {
double dist = event.getPlayer().getLocation().distance(b.get(0).getLocation());
if (dist > 2) {
Location loc = b.get(0).getLocation().clone().add(0.5, 0.5, 0.5);
item.setTypeId(flashOffItemId);
int hisCooldown = normalCooldown;
if (addMoreCooldownForLargeDistances && (dist / 2) > 30)
hisCooldown = (int) (dist / 2);
cooldown.put(item, hisCooldown + HungergamesApi.getHungergames().currentTime);
Location pLoc = event.getPlayer().getLocation();
loc.setPitch(pLoc.getPitch());
loc.setYaw(pLoc.getYaw());
event.getPlayer().teleport(loc);
pLoc.getWorld().playSound(pLoc, Sound.ENDERMAN_TELEPORT, 1, 1.2F);
pLoc.getWorld().playSound(loc, Sound.ENDERMAN_TELEPORT, 1, 1.2F);
((CraftWorld) pLoc.getWorld()).getHandle().addParticle("portal", pLoc.getX(), pLoc.getY(),
pLoc.getZ(), loc.getX(), loc.getY(), loc.getZ());
((CraftWorld) pLoc.getWorld()).getHandle().addParticle("portal", loc.getX(), loc.getY(), loc.getZ(),
pLoc.getX(), pLoc.getY(), pLoc.getZ());
if (giveWeakness)
event.getPlayer().addPotionEffect(
new PotionEffect(PotionEffectType.WEAKNESS, (int) ((dist / 2) * 20), 1), true);
pLoc.getWorld().strikeLightningEffect(loc);
}
}
}
}
}
}
|
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.layout.updater_fragment);
PreferenceScreen root = this.getPreferenceScreen();
final Preference backup_kernel = root.findPreference("backup_kernel");
final Preference updater_kernel = root.findPreference("updater_kernel");
final ListPreference restore_kernel = (ListPreference) root.findPreference("restore_kernel");
updater_kernel.setEnabled(false);
try {
backup_kernel.setSummary(getText(R.string.last_backup_from)+ " " + shell.getDirInfo("/sdcard/com.aero.control/", false)[0]);
restore_kernel.setEnabled(true);
} catch (ArrayIndexOutOfBoundsException e) {
backup_kernel.setSummary(getText(R.string.last_backup_from)+ " " + getText(R.string.unavailable));
restore_kernel.setEnabled(false);
}
restore_kernel.setEntries(shell.getDirInfo("/sdcard/com.aero.control/", false));
restore_kernel.setEntryValues(shell.getDirInfo("/sdcard/com.aero.control/", false));
restore_kernel.setDialogIcon(R.drawable.restore_dark);
restore_kernel.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object o) {
final String s = (String) o;
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
View layout = inflater.inflate(R.layout.about_screen, null);
TextView aboutText = (TextView) layout.findViewById(R.id.aboutScreen);
builder.setTitle(getText(R.string.backup_from) + " " + s);
aboutText.setText(getText(R.string.restore_from_backup) + " " + s + " ?");
shell.remountSystem();
builder.setView(layout)
.setPositiveButton(R.string.save, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
String[] commands = new String[]
{
"rm -f " + zImage,
"cp " + "/sdcard/com.aero.control/" + s + "/zImage" + " " + zImage,
};
shell.setRootInfo(commands);
Toast.makeText(getActivity(), R.string.need_reboot, Toast.LENGTH_LONG).show();
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
builder.show();
return true;
};
});
backup_kernel.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
View layout = inflater.inflate(R.layout.about_screen, null);
TextView aboutText = (TextView) layout.findViewById(R.id.aboutScreen);
builder.setTitle("Backup");
builder.setIcon(R.drawable.backup_dark);
aboutText.setText(R.string.proceed_backup);
builder.setView(layout)
.setPositiveButton(R.string.save, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
try {
update.copyFile(IMAGE, BACKUP_PATH, false);
Toast.makeText(getActivity(), "Backup was successful!", Toast.LENGTH_LONG).show();
backup_kernel.setSummary(getText(R.string.last_backup_from) + " " + timeStamp);
restore_kernel.setEnabled(true);
} catch (IOException e) {
Log.e("Aero", "A problem occured while saving a backup.", e);
}
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
builder.show();
return true;
}
;
});
}
| public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.layout.updater_fragment);
PreferenceScreen root = this.getPreferenceScreen();
final Preference backup_kernel = root.findPreference("backup_kernel");
final Preference updater_kernel = root.findPreference("updater_kernel");
final ListPreference restore_kernel = (ListPreference) root.findPreference("restore_kernel");
updater_kernel.setEnabled(false);
if (shell.getInfo(zImage).equals("Unavailable"))
backup_kernel.setEnabled(false);
if (shell.getInfo(zImage).equals("Unavailable"))
restore_kernel.setEnabled(false);
try {
backup_kernel.setSummary(getText(R.string.last_backup_from)+ " " + shell.getDirInfo("/sdcard/com.aero.control/", false)[0]);
restore_kernel.setEnabled(true);
} catch (ArrayIndexOutOfBoundsException e) {
backup_kernel.setSummary(getText(R.string.last_backup_from)+ " " + getText(R.string.unavailable));
restore_kernel.setEnabled(false);
}
restore_kernel.setEntries(shell.getDirInfo("/sdcard/com.aero.control/", false));
restore_kernel.setEntryValues(shell.getDirInfo("/sdcard/com.aero.control/", false));
restore_kernel.setDialogIcon(R.drawable.restore_dark);
restore_kernel.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object o) {
final String s = (String) o;
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
View layout = inflater.inflate(R.layout.about_screen, null);
TextView aboutText = (TextView) layout.findViewById(R.id.aboutScreen);
builder.setTitle(getText(R.string.backup_from) + " " + s);
aboutText.setText(getText(R.string.restore_from_backup) + " " + s + " ?");
shell.remountSystem();
builder.setView(layout)
.setPositiveButton(R.string.save, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
String[] commands = new String[]
{
"rm -f " + zImage,
"cp " + "/sdcard/com.aero.control/" + s + "/zImage" + " " + zImage,
};
shell.setRootInfo(commands);
Toast.makeText(getActivity(), R.string.need_reboot, Toast.LENGTH_LONG).show();
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
builder.show();
return true;
};
});
backup_kernel.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
View layout = inflater.inflate(R.layout.about_screen, null);
TextView aboutText = (TextView) layout.findViewById(R.id.aboutScreen);
builder.setTitle("Backup");
builder.setIcon(R.drawable.backup_dark);
aboutText.setText(R.string.proceed_backup);
builder.setView(layout)
.setPositiveButton(R.string.save, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
try {
update.copyFile(IMAGE, BACKUP_PATH, false);
Toast.makeText(getActivity(), "Backup was successful!", Toast.LENGTH_LONG).show();
backup_kernel.setSummary(getText(R.string.last_backup_from) + " " + timeStamp);
restore_kernel.setEnabled(true);
} catch (IOException e) {
Log.e("Aero", "A problem occured while saving a backup.", e);
}
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
builder.show();
return true;
}
;
});
}
|
public void addType(TypeDefinition type) {
index.put(type.getFeatureType().getName(), type);
}
| public void addType(TypeDefinition type) {
FeatureType ft = type.getFeatureType();
if (ft != null) {
index.put(ft.getName(), type);
}
}
|
public float getL1cInterpolatedBtDataFloat(int gridPointIndex, int btDataIndex, int polMode, float noDataValue) throws IOException {
final SequenceData btDataList = getBtDataList(gridPointIndex);
final int btDataListCount = btDataList.getElementCount();
int flags;
int delta, deltaAbs;
int deltaMin1 = Integer.MAX_VALUE;
int deltaMin2 = Integer.MAX_VALUE;
int incidenceAngle;
float incidenceAngle1 = 0;
float incidenceAngle2 = 0;
float btValue;
float btValue1 = 0;
float btValue2 = 0;
for (int i = 0; i < btDataListCount; i++) {
CompoundData btData = btDataList.getCompound(i);
flags = btData.getInt(flagsIndex);
if ((flags & POL_MASK) == polMode) {
incidenceAngle = btData.getInt(incidenceAngleIndex);
delta = CENTER_INCIDENCE_ANGLE - incidenceAngle;
deltaAbs = Math.abs(delta);
if (deltaAbs < INCIDENCE_ANGLE_RANGE) {
btValue = btData.getFloat(btDataIndex);
if (delta < 0) {
if (deltaAbs < deltaMin1) {
deltaMin1 = deltaAbs;
incidenceAngle1 = incidenceAngle;
btValue1 = btValue;
}
} else if (delta > 0) {
if (deltaAbs < deltaMin2) {
deltaMin2 = deltaAbs;
incidenceAngle2 = incidenceAngle;
btValue2 = btValue;
}
} else {
return btValue;
}
}
}
}
final boolean hasValue1 = deltaMin1 < Integer.MAX_VALUE;
final boolean hasValue2 = deltaMin2 < Integer.MAX_VALUE;
if (hasValue1 && hasValue2) {
return btValue1 + CENTER_INCIDENCE_ANGLE * (btValue2 - btValue1) / (incidenceAngle2 - incidenceAngle1);
} else {
return noDataValue;
}
}
| public float getL1cInterpolatedBtDataFloat(int gridPointIndex, int btDataIndex, int polMode, float noDataValue) throws IOException {
final SequenceData btDataList = getBtDataList(gridPointIndex);
final int btDataListCount = btDataList.getElementCount();
int flags;
int delta, deltaAbs;
int deltaMin1 = Integer.MAX_VALUE;
int deltaMin2 = Integer.MAX_VALUE;
int incidenceAngle;
float incidenceAngle1 = 0;
float incidenceAngle2 = 0;
float btValue;
float btValue1 = 0;
float btValue2 = 0;
for (int i = 0; i < btDataListCount; i++) {
CompoundData btData = btDataList.getCompound(i);
flags = btData.getInt(flagsIndex);
if ((flags & POL_MASK) == polMode) {
incidenceAngle = btData.getInt(incidenceAngleIndex);
delta = CENTER_INCIDENCE_ANGLE - incidenceAngle;
deltaAbs = Math.abs(delta);
if (deltaAbs < INCIDENCE_ANGLE_RANGE) {
btValue = btData.getFloat(btDataIndex);
if (delta < 0) {
if (deltaAbs < deltaMin1) {
deltaMin1 = deltaAbs;
incidenceAngle1 = incidenceAngle;
btValue1 = btValue;
}
} else if (delta > 0) {
if (deltaAbs < deltaMin2) {
deltaMin2 = deltaAbs;
incidenceAngle2 = incidenceAngle;
btValue2 = btValue;
}
} else {
return btValue;
}
}
}
}
final boolean hasValue1 = deltaMin1 < Integer.MAX_VALUE;
final boolean hasValue2 = deltaMin2 < Integer.MAX_VALUE;
if (hasValue1 && hasValue2) {
return btValue1 + (CENTER_INCIDENCE_ANGLE - incidenceAngle1) * (btValue2 - btValue1) / (incidenceAngle2 - incidenceAngle1);
} else {
return noDataValue;
}
}
|
public void startElement(
String ns, String localName, String name, Attributes atts)
throws org.xml.sax.SAXException
{
Element elem;
if ((null == ns) || (ns.length() == 0))
elem = m_doc.createElement(name);
else
elem = m_doc.createElementNS(ns, name);
append(elem);
try
{
int nAtts = atts.getLength();
if (0 != nAtts)
{
for (int i = 0; i < nAtts; i++)
{
if (atts.getType(i).equalsIgnoreCase("ID"))
setIDAttribute(atts.getValue(i), elem);
String attrNS = atts.getURI(i);
if(attrNS == null)
attrNS = "";
String attrQName = atts.getQName(i);
if ((attrNS.length() == 0) || attrQName.startsWith("xmlns:") || attrQName.equals("xmlns"))
elem.setAttribute(attrQName, atts.getValue(i));
else
{
elem.setAttributeNS(attrNS, attrQName, atts.getValue(i));
}
}
}
m_elemStack.push(elem);
m_currentNode = elem;
}
catch(java.lang.Exception de)
{
throw new org.xml.sax.SAXException(de);
}
}
| public void startElement(
String ns, String localName, String name, Attributes atts)
throws org.xml.sax.SAXException
{
Element elem;
if ((null == ns) || (ns.length() == 0))
elem = m_doc.createElement(name);
else
elem = m_doc.createElementNS(ns, name);
append(elem);
try
{
int nAtts = atts.getLength();
if (0 != nAtts)
{
for (int i = 0; i < nAtts; i++)
{
if (atts.getType(i).equalsIgnoreCase("ID"))
setIDAttribute(atts.getValue(i), elem);
String attrNS = atts.getURI(i);
if(attrNS == null)
attrNS = "";
String attrQName = atts.getQName(i);
if ((attrNS.length() == 0) )
elem.setAttribute(attrQName, atts.getValue(i));
else
{
elem.setAttributeNS(attrNS, attrQName, atts.getValue(i));
}
}
}
m_elemStack.push(elem);
m_currentNode = elem;
}
catch(java.lang.Exception de)
{
throw new org.xml.sax.SAXException(de);
}
}
|
public void doGet(final HttpServletRequest request,
final HttpServletResponse response) throws ServletException,
IOException {
response.setContentType("text/html");
response.setCharacterEncoding("UTF-8");
final PrintWriter p = response.getWriter();
final String accessToken = request.getParameter("access_token");
if (accessToken == null) {
response.sendRedirect(Config.getValue("LOGIN_URL"));
return;
} else {
HttpSession session = request.getSession();
session.setAttribute(Config.getValue("ACCESS_TOKEN_SESSION"),
accessToken);
}
final DefaultFacebookClient client = new DefaultFacebookClient(
accessToken);
try {
final URL url = new URL(
"https://api.facebook.com/method/fql.query?access_token="
+ accessToken
+ "&query="
+ URLEncoder
.encode("SELECT name,uid,pic_square FROM user WHERE uid IN ( SELECT uid2 FROM friend WHERE uid1=me() )",
"UTF-8"));
final DocumentBuilderFactory factory = DocumentBuilderFactory
.newInstance();
final DocumentBuilder builder = factory.newDocumentBuilder();
final Document doc = builder.parse(url.openStream());
final StreamSource source = new StreamSource(new File(this
.getServletContext().getRealPath(
Config.getValue("XSL_FILE"))));
OutputGenerator.transformWithStyle(new DOMSource(doc), source,
new StreamResult(p));
} catch (final Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
p.flush();
p.close();
}
| public void doGet(final HttpServletRequest request,
final HttpServletResponse response) throws ServletException,
IOException {
response.setContentType("text/html");
response.setCharacterEncoding("UTF-8");
final PrintWriter p = response.getWriter();
final String accessToken = request.getParameter("access_token");
if (accessToken == null) {
response.sendRedirect(Config.getValue("LOGIN_URL"));
return;
} else {
HttpSession session = request.getSession();
session.setAttribute(Config.getValue("ACCESS_TOKEN_SESSION"),
accessToken);
}
final DefaultFacebookClient client = new DefaultFacebookClient(
accessToken);
try {
final URL url = new URL(
"https://api.facebook.com/method/fql.query?access_token="
+ accessToken
+ "&query="
+ URLEncoder
.encode("SELECT name,uid,pic_square FROM user WHERE uid IN ( SELECT uid2 FROM friend WHERE uid1=me() )",
"UTF-8"));
final DocumentBuilderFactory factory = DocumentBuilderFactory
.newInstance();
final DocumentBuilder builder = factory.newDocumentBuilder();
final Document doc = builder.parse(url.openStream());
String xslFile = File.separator + "xsl" + File.separator + "facebook.xsl";
final StreamSource source = new StreamSource(new File(this
.getServletContext().getRealPath(
xslFile)));
OutputGenerator.transformWithStyle(new DOMSource(doc), source,
new StreamResult(p));
} catch (final Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
p.flush();
p.close();
}
|
public static void main(String[] args) throws Exception {
print_header();
NumberFormat pf = NumberFormat.getPercentInstance();
NumberFormat df = NumberFormat.getInstance();
NumberFormat inf = NumberFormat.getIntegerInstance();
pf.setMaximumFractionDigits(2);
df.setMaximumFractionDigits(4);
df.setMinimumFractionDigits(4);
final long ms = 1000000L;
final long ns = 1000000000L;
int threads = Runtime.getRuntime().availableProcessors();
double percent_variation = 0.0001;
long prime_time = 60 * ns;
if ( args.length > 0 && args[0].equals("i") ) {
Scanner scanner = new Scanner(System.in);
int temp;
System.out.println( " --- Interactive Mode" );
System.out.print( " -- Enter number of threads\n (enter 0 for " + threads + " threads): " );
temp = scanner.nextInt();
if ( 0 != temp ) threads = temp;
System.out.print( " -- Enter confidence threshold [10^-n]\n (enter 0 for " + Math.abs(Math.log10(percent_variation)) + "): " );
temp = scanner.nextInt();
if ( 0 != temp ) {
percent_variation = (double)(Math.pow(10, -1 * temp));
if (temp > 4) pf.setMaximumFractionDigits( temp + 1 );
}
System.out.print( " -- Enter priming time\n (enter 0 for " + inf.format(prime_time / ns) + " seconds): " );
temp = scanner.nextInt();
if ( 0 != temp ) prime_time = ns * (long)temp;
} else if ( args.length > 0 && args[0].equals("s") ) {
System.out.println( " --- Short Run Mode" );
percent_variation = (double)(Math.pow(10, -1 * 2));
prime_time = ns * (long)10;
} else if ( args.length > 0 && (args[0].equals("h") || args[0].equals("help")) ) {
print_help();
System.exit(1);
}
System.out.println();
System.out.println( " Using " + threads + " for number of threads." );
System.out.println( " Using " + Math.abs(Math.log10(percent_variation)) + " [" + pf.format(percent_variation) + "] for confidence threshold." );
System.out.println( " Using " + inf.format(prime_time / ns) + " seconds for prime time." );
System.out.println();
WarGameThread[] wgts = new WarGameThread[ threads ];
String display_tail = "";
long print_last = getTime();
int tests = 1;
double completed = 0;
double speed = 0;
double rate = 0;
double rate_low = 0, rate_high = 0, prime_speed = 0;
double percent_speed = 0;
boolean test_started = false;
long elapsed_time = 0;
long current_time = 0;
long test_initial = 0;
long test_duration = 0;
long start = getTime();
for (int i = 0; i < threads; i++) {
wgts[i] = new WarGameThread();
}
while ( isAlive(wgts) ) {
completed = getCompleted(wgts);
current_time = getTime();
elapsed_time = current_time - start;
rate = (elapsed_time / completed);
speed = 1 / rate;
if ( !test_started && elapsed_time >= prime_time ) {
test_started = true;
test_duration = (long)(1 + Math.ceil( (speed * ms) ));
test_initial = elapsed_time + ( test_duration * ns );
percent_speed = rate * percent_variation;
rate_low = rate - percent_speed;
rate_high = rate + percent_speed;
prime_speed = speed;
System.out.println();
} else if ( test_started && elapsed_time >= test_initial ) {
if ( rate_low < rate && rate < rate_high ) {
terminateThreads(wgts);
} else if ( tests >= 100 ) {
terminateThreads(wgts);
} else {
test_duration = (long)(1 + Math.ceil( (speed * ms) ));
test_initial = elapsed_time + ( test_duration * ns );
percent_speed = rate * percent_variation;
rate_low = rate - percent_speed;
rate_high = rate + percent_speed;
tests++;
}
}
if ( ( current_time - print_last) > (1000 * ms) ) {
if ( test_started ) display_tail = "Test #" + tests + " at " + inf.format( (test_initial - elapsed_time) / ns ) + " seconds";
else display_tail = inf.format( (prime_time - elapsed_time) / ns ) + " seconds left...";
print_last = current_time;
System.out.print("\r " + " Speed: " + df.format( (speed * ms) ) + " (g/ms) - " + display_tail );
}
}
long end = getTime();
System.out.print("\r " + " Speed: " + df.format( (speed * ms) ) + " (g/ms) - " + display_tail );
System.out.println();
System.out.println();
System.out.println( " Elasped time: " + inf.format((end - start) / ns) + " seconds or about " + df.format((end - start) / ms / 1000.0 / 60.0) + " minutes ");
System.out.println( " Games completed: " + inf.format( getCompleted(wgts) ) + " " );
System.out.println( " Tests completed: " + inf.format( tests ) + " " );
System.out.println( " Threads used: " + threads + " ");
System.out.println( " Confidence: " + pf.format( percent_variation ) + " " );
System.out.println();
System.out.println( " " + inf.format(tests) + " tests improved speed by " + pf.format( 1 - (prime_speed / speed) ) + "");
System.out.println( " from " + df.format(prime_speed * ms) + " (g/ms) to " + df.format(speed * ms) + " (g/ms)");
System.out.println( " Final confidence range:\n " + df.format(1/rate_high * ms) + " (g/ms) < " + df.format(speed * ms) + " (g/ms) < " + df.format(1/rate_low * ms) + " (g/ms)" );
System.out.println();
System.out.println( " Final speed: " + df.format( (speed * ms) ) + " (g/ms)" );
System.out.println();
}
| public static void main(String[] args) throws Exception {
print_header();
NumberFormat pf = NumberFormat.getPercentInstance();
NumberFormat df = NumberFormat.getInstance();
NumberFormat inf = NumberFormat.getIntegerInstance();
pf.setMaximumFractionDigits(2);
df.setMaximumFractionDigits(4);
df.setMinimumFractionDigits(4);
final long ms = 1000000L;
final long ns = 1000000000L;
int threads = Runtime.getRuntime().availableProcessors();
double percent_variation = 0.0001;
long prime_time = 60 * ns;
if ( args.length > 0 && args[0].equals("i") ) {
Scanner scanner = new Scanner(System.in);
int temp;
System.out.println( " --- Interactive Mode" );
System.out.print( " -- Enter number of threads\n (enter 0 for " + threads + " threads): " );
temp = scanner.nextInt();
if ( 0 != temp ) threads = temp;
System.out.print( " -- Enter confidence threshold [10^-n]\n (enter 0 for " + Math.abs(Math.log10(percent_variation)) + "): " );
temp = scanner.nextInt();
if ( 0 != temp ) {
percent_variation = (double)(Math.pow(10, -1 * temp));
if (temp > 4) pf.setMaximumFractionDigits( temp + 1 );
}
System.out.print( " -- Enter priming time\n (enter 0 for " + inf.format(prime_time / ns) + " seconds): " );
temp = scanner.nextInt();
if ( 0 != temp ) prime_time = ns * (long)temp;
} else if ( args.length > 0 && args[0].equals("s") ) {
System.out.println( " --- Short Run Mode" );
percent_variation = (double)(Math.pow(10, -1 * 2));
prime_time = ns * (long)10;
} else if ( args.length > 0 && (args[0].equals("h") || args[0].equals("help")) ) {
print_help();
System.exit(1);
}
System.out.println();
System.out.println( " Using " + threads + " for number of threads." );
System.out.println( " Using " + Math.abs(Math.log10(percent_variation)) + " [" + pf.format(percent_variation) + "] for confidence threshold." );
System.out.println( " Using " + inf.format(prime_time / ns) + " seconds for prime time." );
System.out.println();
WarGameThread[] wgts = new WarGameThread[ threads ];
String display_tail = "";
long print_last = getTime();
int tests = 1;
double completed = 0;
double speed = 0;
double rate = 0;
double rate_low = 0, rate_high = 0, prime_speed = 0;
double percent_speed = 0;
boolean test_started = false;
long elapsed_time = 0;
long current_time = 0;
long test_initial = 0;
long test_duration = 0;
long start = getTime();
for (int i = 0; i < threads; i++) {
wgts[i] = new WarGameThread();
}
while ( isAlive(wgts) ) {
completed = getCompleted(wgts);
current_time = getTime();
elapsed_time = current_time - start;
rate = (elapsed_time / completed);
speed = 1 / rate;
if ( !test_started && elapsed_time >= prime_time ) {
test_started = true;
test_duration = (long)(1 + Math.ceil( (speed * ms) ));
test_initial = elapsed_time + ( test_duration * ns );
percent_speed = rate * percent_variation;
rate_low = rate - percent_speed;
rate_high = rate + percent_speed;
prime_speed = speed;
System.out.println();
} else if ( test_started && elapsed_time >= test_initial ) {
if ( rate_low < rate && rate < rate_high ) {
terminateThreads(wgts);
} else if ( tests >= 100 ) {
terminateThreads(wgts);
} else {
test_duration = (long)(1 + Math.ceil( (speed * ms) ));
test_initial = elapsed_time + ( test_duration * ns );
percent_speed = rate * percent_variation;
rate_low = rate - percent_speed;
rate_high = rate + percent_speed;
tests++;
}
}
if ( ( current_time - print_last) > (1000 * ms) ) {
if ( test_started ) display_tail = "Test #" + tests + " at " + inf.format( (test_initial - elapsed_time) / ns ) + " seconds";
else display_tail = inf.format( (prime_time - elapsed_time) / ns ) + " seconds left...";
print_last = current_time;
System.out.print("\r " + " Speed: " + df.format( (speed * ms) ) + " (g/ms) - " + display_tail );
}
}
long end = getTime();
System.out.print("\r " + " Speed: " + df.format( (speed * ms) ) + " (g/ms) - " + display_tail );
System.out.println();
System.out.println();
System.out.println( " Elapsed time: " + inf.format((end - start) / ns) + " seconds or ~" + df.format((end - start) / ms / 1000.0 / 60.0) + " minutes.");
System.out.println( " Games completed: " + inf.format( getCompleted(wgts) ) + "." );
System.out.println( " Tests completed: " + inf.format( tests ) + "." );
System.out.println( " Threads used: " + threads + ".");
System.out.println( " Confidence: " + pf.format( percent_variation ) + "." );
System.out.println();
System.out.println( " " + inf.format(tests) + " tests improved speed by " + pf.format( 1 - (prime_speed / speed) ) + "");
System.out.println( " from " + df.format(prime_speed * ms) + " (g/ms) to " + df.format(speed * ms) + " (g/ms)");
System.out.println( " Final confidence range:\n " + df.format(1/rate_low * ms) + " (g/ms) > " + df.format(speed * ms) + " (g/ms) > " + df.format(1/rate_high * ms) + " (g/ms)" );
System.out.println();
System.out.println( " Final rate: \t" + df.format( (rate / ms) ) + " (ms/g)" );
System.out.println( " Final speed: \t" + df.format( (speed * ms) ) + " (g/ms)" );
System.out.println();
System.out.println( " Final speed: \t" + inf.format( Math.round((speed * ms) * 1000)) + " (g/s)" );
System.out.println();
}
|
public static void main(String[] args) throws IOException, PrologException, TermInstantiationException, ExecutionContextException {
PrologProxy p = new PrologProxy(new File("service.pl"));
p.getSolution(new Compound(p, "loadFile", "procedure.ced", "cedalion"));
ExecutionContext exe = new ExecutionContext(p);
exe.runProcedure(new Compound(p, "cpi#openFile", "grammer-example.ced", "grammar", "gram"));
Variable model = new Variable("Model");
Variable x = new Variable("X");
Variable y = new Variable("Y");
Variable z = new Variable("Z");
Iterator<Map<Variable, Object>> results = p.getSolutions(p.createCompound("cedalion#loadedFile", "grammar", z, model));
while(results.hasNext()) {
Map<Variable, Object> result = results.next();
System.out.println(result.get(model));
}
Compound list = p.createCompound("[]");
list = p.createCompound(".", 1, list);
list = p.createCompound(".", 2, list);
list = p.createCompound(".", 2, list);
Compound path = p.createCompound("cpi#path", "grammar", list);
Map<Variable, Object> result = p.getSolution(p.createCompound("cpi#termAtPath", path, x, y));
System.out.println(result.get(x));
System.out.println(result.get(y));
exe.runProcedure(p.createCompound("cpi#saveFile", "grammar", "g1.ced"));
exe.runProcedure(p.createCompound("cpi#edit", path, p.createCompound("::", p.createCompound("[]"), new Variable()), p.createCompound("[]")));
exe.runProcedure(p.createCompound("cpi#saveFile", "grammar", "g2.ced"));
exe.runProcedure(p.createCompound("cpi#undo", "grammar"));
exe.runProcedure(p.createCompound("cpi#saveFile", "grammar", "g3.ced"));
String oldContent = (String)exe.evaluate(p.createCompound("cpi#termAsString", path, p.createCompound("cpi#constExpr", 3)), new Variable());
System.out.println(oldContent);
exe.runProcedure(p.createCompound("cpi#redo", "grammar"));
exe.runProcedure(p.createCompound("cpi#saveFile", "grammar", "g4.ced"));
exe.runProcedure(p.createCompound("cpi#editFromString", path, p.createCompound("cpi#constExpr", "!(hello)")));
exe.runProcedure(p.createCompound("cpi#saveFile", "grammar", "g5.ced"));
Variable vis = new Variable();
result = p.getSolution(p.createCompound("cpi#visualizePath", path, vis));
System.out.println(result.get(vis));
p.terminate();
}
| public static void main(String[] args) throws IOException, PrologException, TermInstantiationException, ExecutionContextException {
PrologProxy p = new PrologProxy(new File("service.pl"));
p.getSolution(new Compound(p, "loadFile", "procedure.ced", "cedalion"));
ExecutionContext exe = new ExecutionContext(p);
exe.runProcedure(new Compound(p, "cpi#openFile", "grammer-example.ced", "grammar", "gram"));
Variable model = new Variable("Model");
Variable x = new Variable("X");
Variable y = new Variable("Y");
Variable z = new Variable("Z");
Iterator<Map<Variable, Object>> results = p.getSolutions(p.createCompound("cedalion#loadedFile", "grammar", z, model));
while(results.hasNext()) {
Map<Variable, Object> result = results.next();
System.out.println(result.get(model));
}
Compound list = p.createCompound("[]");
list = p.createCompound(".", 1, list);
list = p.createCompound(".", 2, list);
list = p.createCompound(".", 2, list);
Compound path = p.createCompound("cpi#path", "grammar", list);
Map<Variable, Object> result = p.getSolution(p.createCompound("cpi#termAtPath", path, x, y));
System.out.println(result.get(x));
System.out.println(result.get(y));
exe.runProcedure(p.createCompound("cpi#saveFile", "grammar", "g1.ced"));
exe.runProcedure(p.createCompound("cpi#edit", path, p.createCompound("::", p.createCompound("[]"), new Variable()), p.createCompound("[]")));
exe.runProcedure(p.createCompound("cpi#saveFile", "grammar", "g2.ced"));
exe.runProcedure(p.createCompound("cpi#undo", "grammar"));
exe.runProcedure(p.createCompound("cpi#saveFile", "grammar", "g3.ced"));
String oldContent = (String)exe.evaluate(p.createCompound("cpi#termAsString", path, p.createCompound("cpi#constExpr", 3)), new Variable());
System.out.println(oldContent);
exe.runProcedure(p.createCompound("cpi#redo", "grammar"));
exe.runProcedure(p.createCompound("cpi#saveFile", "grammar", "g4.ced"));
exe.runProcedure(p.createCompound("cpi#editFromString", path, p.createCompound("cpi#constExpr", "hello")));
exe.runProcedure(p.createCompound("cpi#saveFile", "grammar", "g5.ced"));
Variable vis = new Variable();
result = p.getSolution(p.createCompound("cpi#visualizePath", path, vis));
System.out.println(result.get(vis));
p.terminate();
}
|
public RevCommit call() throws RuntimeException {
final String committer = resolveCommitter();
final String committerEmail = resolveCommitterEmail();
final String author = resolveAuthor();
final String authorEmail = resolveAuthorEmail();
final Long authorTime = getAuthorTimeStamp();
final Long committerTime = getCommitterTimeStamp();
final Integer authorTimeZoneOffset = getAuthorTimeZoneOffset();
final Integer committerTimeZoneOffset = getCommitterTimeZoneOffset();
getProgressListener().started();
float writeTreeProgress = 99f;
if (all) {
writeTreeProgress = 50f;
command(AddOp.class).setUpdateOnly(true).setProgressListener(subProgress(49f)).call();
}
if (getProgressListener().isCanceled()) {
return null;
}
List<Conflict> conflicts = command(ConflictsReadOp.class).call();
if (!conflicts.isEmpty()) {
throw new IllegalStateException("Cannot run operation while merge conflicts exist.");
}
final Optional<Ref> currHead = command(RefParse.class).setName(Ref.HEAD).call();
checkState(currHead.isPresent(), "Repository has no HEAD, can't commit");
final Ref headRef = currHead.get();
checkState(headRef instanceof SymRef,
"HEAD is in a dettached state, cannot commit. Create a branch from it before committing");
final String currentBranch = ((SymRef) headRef).getTarget();
final ObjectId currHeadCommitId = headRef.getObjectId();
if (!currHeadCommitId.isNull()) {
parents.add(0, currHeadCommitId);
}
final Optional<Ref> mergeHead = command(RefParse.class).setName(Ref.MERGE_HEAD).call();
if (mergeHead.isPresent()) {
ObjectId mergeCommitId = mergeHead.get().getObjectId();
if (!mergeCommitId.isNull()) {
parents.add(mergeCommitId);
}
if (message == null) {
message = command(ReadMergeCommitMessageOp.class).call();
}
}
for (String st : pathFilters) {
command(AddOp.class).addPattern(st).call();
}
ObjectId newTreeId;
{
WriteTree2 writeTree = command(WriteTree2.class);
Supplier<RevTree> oldRoot = resolveOldRoot();
writeTree.setOldRoot(oldRoot).setProgressListener(subProgress(writeTreeProgress));
if (!pathFilters.isEmpty()) {
writeTree.setPathFilter(pathFilters);
}
newTreeId = writeTree.call();
}
if (getProgressListener().isCanceled()) {
return null;
}
final ObjectId currentRootTreeId = command(ResolveTreeish.class)
.setTreeish(currHeadCommitId).call().or(ObjectId.NULL);
if (currentRootTreeId.equals(newTreeId)) {
if (!allowEmpty) {
throw new NothingToCommitException("Nothing to commit after " + currHeadCommitId);
}
}
final RevCommit commit;
if (this.commit == null) {
CommitBuilder cb = new CommitBuilder();
cb.setAuthor(author);
cb.setAuthorEmail(authorEmail);
cb.setCommitter(committer);
cb.setCommitterEmail(committerEmail);
cb.setMessage(message);
cb.setParentIds(parents);
cb.setTreeId(newTreeId);
cb.setCommitterTimestamp(committerTime);
cb.setAuthorTimestamp(authorTime);
cb.setCommitterTimeZoneOffset(committerTimeZoneOffset);
cb.setAuthorTimeZoneOffset(authorTimeZoneOffset);
commit = cb.build();
} else {
CommitBuilder cb = new CommitBuilder(this.commit);
cb.setParentIds(parents);
cb.setTreeId(newTreeId);
cb.setCommitterTimestamp(committerTime);
cb.setCommitterTimeZoneOffset(committerTimeZoneOffset);
if (message != null) {
cb.setMessage(message);
}
commit = cb.build();
}
if (getProgressListener().isCanceled()) {
return null;
}
objectDb.put(commit);
final Optional<Ref> branchHead = command(UpdateRef.class).setName(currentBranch)
.setNewValue(commit.getId()).call();
checkState(commit.getId().equals(branchHead.get().getObjectId()));
final Optional<Ref> newHead = command(UpdateSymRef.class).setName(Ref.HEAD)
.setNewValue(currentBranch).call();
checkState(currentBranch.equals(((SymRef) newHead.get()).getTarget()));
Optional<ObjectId> treeId = command(ResolveTreeish.class).setTreeish(
branchHead.get().getObjectId()).call();
checkState(treeId.isPresent());
checkState(newTreeId.equals(treeId.get()));
getProgressListener().progress(100f);
getProgressListener().complete();
if (mergeHead.isPresent()) {
command(UpdateRef.class).setDelete(true).setName(Ref.MERGE_HEAD).call();
command(UpdateRef.class).setDelete(true).setName(Ref.ORIG_HEAD).call();
}
final Optional<Ref> cherrypickHead = command(RefParse.class).setName(Ref.CHERRY_PICK_HEAD)
.call();
if (cherrypickHead.isPresent()) {
command(UpdateRef.class).setDelete(true).setName(Ref.CHERRY_PICK_HEAD).call();
command(UpdateRef.class).setDelete(true).setName(Ref.ORIG_HEAD).call();
}
return commit;
}
| public RevCommit call() throws RuntimeException {
final String committer = resolveCommitter();
final String committerEmail = resolveCommitterEmail();
final String author = resolveAuthor();
final String authorEmail = resolveAuthorEmail();
final Long authorTime = getAuthorTimeStamp();
final Long committerTime = getCommitterTimeStamp();
final Integer authorTimeZoneOffset = getAuthorTimeZoneOffset();
final Integer committerTimeZoneOffset = getCommitterTimeZoneOffset();
getProgressListener().started();
float writeTreeProgress = 99f;
if (all) {
writeTreeProgress = 50f;
AddOp op = command(AddOp.class);
for (String st : pathFilters) {
op.addPattern(st);
}
op.setUpdateOnly(true).setProgressListener(subProgress(49f)).call();
}
if (getProgressListener().isCanceled()) {
return null;
}
List<Conflict> conflicts = command(ConflictsReadOp.class).call();
if (!conflicts.isEmpty()) {
throw new IllegalStateException("Cannot run operation while merge conflicts exist.");
}
final Optional<Ref> currHead = command(RefParse.class).setName(Ref.HEAD).call();
checkState(currHead.isPresent(), "Repository has no HEAD, can't commit");
final Ref headRef = currHead.get();
checkState(headRef instanceof SymRef,
"HEAD is in a dettached state, cannot commit. Create a branch from it before committing");
final String currentBranch = ((SymRef) headRef).getTarget();
final ObjectId currHeadCommitId = headRef.getObjectId();
if (!currHeadCommitId.isNull()) {
parents.add(0, currHeadCommitId);
}
final Optional<Ref> mergeHead = command(RefParse.class).setName(Ref.MERGE_HEAD).call();
if (mergeHead.isPresent()) {
ObjectId mergeCommitId = mergeHead.get().getObjectId();
if (!mergeCommitId.isNull()) {
parents.add(mergeCommitId);
}
if (message == null) {
message = command(ReadMergeCommitMessageOp.class).call();
}
}
ObjectId newTreeId;
{
WriteTree2 writeTree = command(WriteTree2.class);
Supplier<RevTree> oldRoot = resolveOldRoot();
writeTree.setOldRoot(oldRoot).setProgressListener(subProgress(writeTreeProgress));
if (!pathFilters.isEmpty()) {
writeTree.setPathFilter(pathFilters);
}
newTreeId = writeTree.call();
}
if (getProgressListener().isCanceled()) {
return null;
}
final ObjectId currentRootTreeId = command(ResolveTreeish.class)
.setTreeish(currHeadCommitId).call().or(ObjectId.NULL);
if (currentRootTreeId.equals(newTreeId)) {
if (!allowEmpty) {
throw new NothingToCommitException("Nothing to commit after " + currHeadCommitId);
}
}
final RevCommit commit;
if (this.commit == null) {
CommitBuilder cb = new CommitBuilder();
cb.setAuthor(author);
cb.setAuthorEmail(authorEmail);
cb.setCommitter(committer);
cb.setCommitterEmail(committerEmail);
cb.setMessage(message);
cb.setParentIds(parents);
cb.setTreeId(newTreeId);
cb.setCommitterTimestamp(committerTime);
cb.setAuthorTimestamp(authorTime);
cb.setCommitterTimeZoneOffset(committerTimeZoneOffset);
cb.setAuthorTimeZoneOffset(authorTimeZoneOffset);
commit = cb.build();
} else {
CommitBuilder cb = new CommitBuilder(this.commit);
cb.setParentIds(parents);
cb.setTreeId(newTreeId);
cb.setCommitterTimestamp(committerTime);
cb.setCommitterTimeZoneOffset(committerTimeZoneOffset);
if (message != null) {
cb.setMessage(message);
}
commit = cb.build();
}
if (getProgressListener().isCanceled()) {
return null;
}
objectDb.put(commit);
final Optional<Ref> branchHead = command(UpdateRef.class).setName(currentBranch)
.setNewValue(commit.getId()).call();
checkState(commit.getId().equals(branchHead.get().getObjectId()));
final Optional<Ref> newHead = command(UpdateSymRef.class).setName(Ref.HEAD)
.setNewValue(currentBranch).call();
checkState(currentBranch.equals(((SymRef) newHead.get()).getTarget()));
Optional<ObjectId> treeId = command(ResolveTreeish.class).setTreeish(
branchHead.get().getObjectId()).call();
checkState(treeId.isPresent());
checkState(newTreeId.equals(treeId.get()));
getProgressListener().progress(100f);
getProgressListener().complete();
if (mergeHead.isPresent()) {
command(UpdateRef.class).setDelete(true).setName(Ref.MERGE_HEAD).call();
command(UpdateRef.class).setDelete(true).setName(Ref.ORIG_HEAD).call();
}
final Optional<Ref> cherrypickHead = command(RefParse.class).setName(Ref.CHERRY_PICK_HEAD)
.call();
if (cherrypickHead.isPresent()) {
command(UpdateRef.class).setDelete(true).setName(Ref.CHERRY_PICK_HEAD).call();
command(UpdateRef.class).setDelete(true).setName(Ref.ORIG_HEAD).call();
}
return commit;
}
|
public void publish(A asset, Model rdf) throws Exception {
System.out.println("publishing to " + configuration.publishURI());
rdf.write(System.out);
StmtIterator stmts = rdf.listStatements();
String triples = "";
while (stmts.hasNext()) {
Statement s = stmts.next();
triples = FmtUtils.stringForTriple(s.asTriple()) + ".";
}
UpdateExecutionFactory.createRemote(UpdateFactory.create("insert data {" + triples + "}"), configuration.publishURI().toString()).execute();
System.out.println(QueryExecutionFactory.sparqlService("http://168.202.3.223:3030/ds/query", "ask {" + triples + "}").execAsk());
}
| public void publish(A asset, Model rdf) throws Exception {
System.out.println("publishing to " + configuration.publishURI());
rdf.write(System.out);
StmtIterator stmts = rdf.listStatements();
String triples = "";
while (stmts.hasNext()) {
Statement s = stmts.next();
triples+= FmtUtils.stringForTriple(s.asTriple()) + " . ";
}
UpdateExecutionFactory.createRemote(UpdateFactory.create("insert data {" + triples + "}"), configuration.publishURI().toString()).execute();
System.out.println(QueryExecutionFactory.sparqlService("http://168.202.3.223:3030/sr_staging/query", "ask {" + triples + "}").execAsk());
}
|
public boolean onCommand(CommandSender sender, Command command, String commandLabel, String args[]) {
if (args.length < 2)
return false;
Player player = null;
String playerName = plugin.banMessages.get("consoleName");
if (sender instanceof Player) {
player = (Player) sender;
playerName = player.getName();
if (!player.hasPermission("bm.warn")) {
Util.sendMessage(player, plugin.banMessages.get("commandPermissionError"));
return true;
}
}
if (!Util.isValidPlayerName(args[0])) {
Util.sendMessage(sender, plugin.banMessages.get("invalidPlayer"));
return true;
}
List<Player> list = plugin.getServer().matchPlayer(args[0]);
if (list.size() == 1) {
Player target = list.get(0);
if (target.getName().equals(playerName)) {
Util.sendMessage(sender, plugin.banMessages.get("warnSelfError"));
} else if (target.hasPermission("bm.exempt.warn")) {
Util.sendMessage(sender, plugin.banMessages.get("warnExemptError"));
} else {
String reason = Util.getReason(args, 1);
String viewReason = Util.viewReason(reason);
plugin.dbLogger.logWarning(playerName, target.getName(), reason);
String infoMessage = plugin.banMessages.get("playerWarned").replace("[name]", target.getName()).replace("[displayName]", target.getDisplayName());
plugin.logger.info(infoMessage);
if (!sender.hasPermission("bm.notify"))
Util.sendMessage(sender, infoMessage);
String message = plugin.banMessages.get("playerWarned").replace("[displayName]", target.getDisplayName()).replace("[name]", target.getName()).replace("[reason]", viewReason).replace("[by]", playerName);
Util.sendMessageWithPerm(message, "bm.notify");
Util.sendMessage(target, plugin.banMessages.get("warned").replace("[displayName]", target.getDisplayName()).replace("[name]", target.getName()).replace("[reason]", viewReason).replace("[by]", playerName));
}
} else if (list.size() > 1) {
Util.sendMessage(sender, plugin.banMessages.get("multiplePlayersFoundError"));
return false;
} else {
Util.sendMessage(sender, plugin.banMessages.get("playerNotOnline"));
return false;
}
return true;
}
| public boolean onCommand(CommandSender sender, Command command, String commandLabel, String args[]) {
if (args.length < 2)
return false;
Player player = null;
String playerName = plugin.banMessages.get("consoleName");
if (sender instanceof Player) {
player = (Player) sender;
playerName = player.getName();
if (!player.hasPermission("bm.warn")) {
Util.sendMessage(player, plugin.banMessages.get("commandPermissionError"));
return true;
}
}
if (!Util.isValidPlayerName(args[0])) {
Util.sendMessage(sender, plugin.banMessages.get("invalidPlayer"));
return true;
}
List<Player> list = plugin.getServer().matchPlayer(args[0]);
if (list.size() == 1) {
Player target = list.get(0);
if (target.getName().equals(playerName)) {
Util.sendMessage(sender, plugin.banMessages.get("warnSelfError"));
} else if (target.hasPermission("bm.exempt.warn")) {
Util.sendMessage(sender, plugin.banMessages.get("warnExemptError"));
} else {
String reason = Util.getReason(args, 1);
String viewReason = Util.viewReason(reason);
plugin.dbLogger.logWarning(target.getName(), playerName, reason);
String infoMessage = plugin.banMessages.get("playerWarned").replace("[name]", target.getName()).replace("[displayName]", target.getDisplayName());
plugin.logger.info(infoMessage);
if (!sender.hasPermission("bm.notify"))
Util.sendMessage(sender, infoMessage);
String message = plugin.banMessages.get("playerWarned").replace("[displayName]", target.getDisplayName()).replace("[name]", target.getName()).replace("[reason]", viewReason).replace("[by]", playerName);
Util.sendMessageWithPerm(message, "bm.notify");
Util.sendMessage(target, plugin.banMessages.get("warned").replace("[displayName]", target.getDisplayName()).replace("[name]", target.getName()).replace("[reason]", viewReason).replace("[by]", playerName));
}
} else if (list.size() > 1) {
Util.sendMessage(sender, plugin.banMessages.get("multiplePlayersFoundError"));
return false;
} else {
Util.sendMessage(sender, plugin.banMessages.get("playerNotOnline"));
return false;
}
return true;
}
|
public void teleportTransformUpdatesPosition () {
Player teleported = this.player.apply(new Player.TeleportTransform("another-room", 5, 1));
assertEquals("another-room", teleported.getRoomId());
assertEquals(5, teleported.getPosition().getX());
assertEquals(1, teleported.getPosition().getY());
}
| public void teleportTransformUpdatesPosition () {
Player teleported = this.player.apply(new Player.TeleportTransform("another-room", new Position(5, 1)));
assertEquals("another-room", teleported.getRoomId());
assertEquals(5, teleported.getPosition().getX());
assertEquals(1, teleported.getPosition().getY());
}
|
protected BrowserScope getBrowserScopeForRequest(Context context, HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException, SQLException, AuthorizeException
{
try
{
String type = request.getParameter("type");
String order = request.getParameter("order");
String value = request.getParameter("value");
String valueLang = request.getParameter("value_lang");
String month = request.getParameter("month");
String year = request.getParameter("year");
String startsWith = request.getParameter("starts_with");
String valueFocus = request.getParameter("vfocus");
String valueFocusLang = request.getParameter("vfocus_lang");
int focus = UIUtil.getIntParameter(request, "focus");
int resultsperpage = UIUtil.getIntParameter(request, "rpp");
int sortBy = UIUtil.getIntParameter(request, "sort_by");
int etAl = UIUtil.getIntParameter(request, "etal");
Collection collection = null;
Community community = null;
collection = UIUtil.getCollectionLocation(request);
if (collection == null)
{
community = UIUtil.getCommunityLocation(request);
}
BrowseIndex bi = null;
if (type != null && !"".equals(type))
{
bi = BrowseIndex.getBrowseIndex(type);
}
if (bi == null)
{
if (sortBy > 0)
bi = BrowseIndex.getBrowseIndex(SortOption.getSortOption(sortBy));
else
bi = BrowseIndex.getBrowseIndex(SortOption.getDefaultSortOption());
}
if (bi != null && sortBy == -1)
{
SortOption so = bi.getSortOption();
if (so != null)
{
sortBy = so.getNumber();
}
}
else if (bi != null && bi.isItemIndex() && !bi.isInternalIndex())
{
SortOption bso = bi.getSortOption();
SortOption so = SortOption.getSortOption(sortBy);
if ( bso != null && bso != so)
{
BrowseIndex newBi = BrowseIndex.getBrowseIndex(so);
if (newBi != null)
{
bi = newBi;
type = bi.getName();
}
}
}
if (order == null && bi != null)
{
order = bi.getDefaultOrder();
}
if (resultsperpage == -1)
{
resultsperpage = 20;
}
if (year != null && !"".equals(year) && !"-1".equals(year))
{
startsWith = year;
if ((month != null) && !"-1".equals(month) && !"".equals(month))
{
if ("ASC".equals(order))
{
month = Integer.toString((Integer.parseInt(month) - 1));
}
if (month.length() == 1)
{
month = "0" + month;
}
startsWith = year + "-" + month;
}
}
int level = 0;
if (value != null)
{
level = 1;
}
if (sortBy == -1)
{
sortBy = 0;
}
if (etAl == -1)
{
int limitLine = ConfigurationManager.getIntProperty("webui.browse.author-limit");
if (limitLine != 0)
{
etAl = limitLine;
}
}
else
{
if (etAl == 0)
{
etAl = -1;
}
}
String comHandle = "n/a";
if (community != null)
{
comHandle = community.getIdentifier().getCanonicalForm();
}
String colHandle = "n/a";
if (collection != null)
{
colHandle = collection.getIdentifier().getCanonicalForm();
}
String arguments = "type=" + type + ",order=" + order + ",value=" + value +
",month=" + month + ",year=" + year + ",starts_with=" + startsWith +
",vfocus=" + valueFocus + ",focus=" + focus + ",rpp=" + resultsperpage +
",sort_by=" + sortBy + ",community=" + comHandle + ",collection=" + colHandle +
",level=" + level + ",etal=" + etAl;
log.info(LogManager.getHeader(context, "browse", arguments));
BrowserScope scope = new BrowserScope(context);
scope.setBrowseIndex(bi);
scope.setOrder(order);
scope.setFilterValue(value);
scope.setFilterValueLang(valueLang);
scope.setJumpToItem(focus);
scope.setJumpToValue(valueFocus);
scope.setJumpToValueLang(valueFocusLang);
scope.setStartsWith(startsWith);
scope.setResultsPerPage(resultsperpage);
scope.setSortBy(sortBy);
scope.setBrowseLevel(level);
scope.setEtAl(etAl);
if (community != null)
{
scope.setBrowseContainer(community);
}
else if (collection != null)
{
scope.setBrowseContainer(collection);
}
if (bi.isMetadataIndex() && scope.isSecondLevel() && scope.getSortBy() <= 0)
{
scope.setSortBy(1);
}
return scope;
}
catch (SortException se)
{
log.error("caught exception: ", se);
throw new ServletException(se);
}
catch (BrowseException e)
{
log.error("caught exception: ", e);
throw new ServletException(e);
}
}
| protected BrowserScope getBrowserScopeForRequest(Context context, HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException, SQLException, AuthorizeException
{
try
{
String type = request.getParameter("type");
String order = request.getParameter("order");
String value = request.getParameter("value");
String valueLang = request.getParameter("value_lang");
String month = request.getParameter("month");
String year = request.getParameter("year");
String startsWith = request.getParameter("starts_with");
String valueFocus = request.getParameter("vfocus");
String valueFocusLang = request.getParameter("vfocus_lang");
int focus = UIUtil.getIntParameter(request, "focus");
int resultsperpage = UIUtil.getIntParameter(request, "rpp");
int sortBy = UIUtil.getIntParameter(request, "sort_by");
int etAl = UIUtil.getIntParameter(request, "etal");
Collection collection = null;
Community community = null;
collection = UIUtil.getCollectionLocation(request);
if (collection == null)
{
community = UIUtil.getCommunityLocation(request);
}
BrowseIndex bi = null;
if (type != null && !"".equals(type))
{
bi = BrowseIndex.getBrowseIndex(type);
}
if (bi == null)
{
if (sortBy > 0)
bi = BrowseIndex.getBrowseIndex(SortOption.getSortOption(sortBy));
else
bi = BrowseIndex.getBrowseIndex(SortOption.getDefaultSortOption());
}
if (bi != null && sortBy == -1)
{
SortOption so = bi.getSortOption();
if (so != null)
{
sortBy = so.getNumber();
}
}
else if (bi != null && bi.isItemIndex() && !bi.isInternalIndex())
{
SortOption bso = bi.getSortOption();
SortOption so = SortOption.getSortOption(sortBy);
if ( bso != null && bso != so)
{
BrowseIndex newBi = BrowseIndex.getBrowseIndex(so);
if (newBi != null)
{
bi = newBi;
type = bi.getName();
}
}
}
if (order == null && bi != null)
{
order = bi.getDefaultOrder();
}
if (resultsperpage == -1)
{
resultsperpage = 20;
}
if (year != null && !"".equals(year) && !"-1".equals(year))
{
startsWith = year;
if ((month != null) && !"-1".equals(month) && !"".equals(month))
{
if ("ASC".equals(order))
{
month = Integer.toString((Integer.parseInt(month) - 1));
}
if (month.length() == 1)
{
month = "0" + month;
}
startsWith = year + "-" + month;
}
}
int level = 0;
if (value != null)
{
level = 1;
}
if (sortBy == -1)
{
sortBy = 0;
}
if (etAl == -1)
{
int limitLine = ConfigurationManager.getIntProperty("webui.browse.author-limit");
if (limitLine != 0)
{
etAl = limitLine;
}
}
else
{
if (etAl == 0)
{
etAl = -1;
}
}
String comHandle = "n/a";
if (community != null)
{
comHandle = community.getIdentifier().getCanonicalForm();
}
String colHandle = "n/a";
if (collection != null)
{
colHandle = collection.getIdentifier().getCanonicalForm();
}
String arguments = "type=" + type + ",order=" + order + ",value=" + value +
",month=" + month + ",year=" + year + ",starts_with=" + startsWith +
",vfocus=" + valueFocus + ",focus=" + focus + ",rpp=" + resultsperpage +
",sort_by=" + sortBy + ",community=" + comHandle + ",collection=" + colHandle +
",level=" + level + ",etal=" + etAl;
log.info(LogManager.getHeader(context, "browse", arguments));
BrowserScope scope = new BrowserScope(context);
scope.setBrowseIndex(bi);
scope.setOrder(order);
scope.setFilterValue(value);
scope.setFilterValueLang(valueLang);
scope.setJumpToItem(focus);
scope.setJumpToValue(valueFocus);
scope.setJumpToValueLang(valueFocusLang);
scope.setStartsWith(startsWith);
scope.setResultsPerPage(resultsperpage);
scope.setSortBy(sortBy);
scope.setBrowseLevel(level);
scope.setEtAl(etAl);
if (community != null)
{
scope.setBrowseContainer(community);
}
else if (collection != null)
{
scope.setBrowseContainer(collection);
}
if (bi != null && bi.isMetadataIndex() && scope.isSecondLevel() && scope.getSortBy() <= 0)
{
scope.setSortBy(1);
}
return scope;
}
catch (SortException se)
{
log.error("caught exception: ", se);
throw new ServletException(se);
}
catch (BrowseException e)
{
log.error("caught exception: ", e);
throw new ServletException(e);
}
}
|
public Set<IProject> build(int kind, IProgressMonitor monitor) throws Exception {
final IProject project = getMavenProjectFacade().getProject();
if(IncrementalProjectBuilder.AUTO_BUILD == kind || IncrementalProjectBuilder.CLEAN_BUILD == kind || IncrementalProjectBuilder.FULL_BUILD == kind) {
try{
MavenPlugin plugin = MavenPlugin.getDefault();
MavenProjectManager projectManager = plugin.getMavenProjectManager();
IMaven maven = plugin.getMaven();
IFile pom = project.getFile(new Path(IMavenConstants.POM_FILE_NAME));
IMavenProjectFacade projectFacade = projectManager.create(pom, false, monitor);
ResolverConfiguration resolverConfiguration = projectFacade.getResolverConfiguration();
MavenExecutionRequest request = projectManager.createExecutionRequest(pom, resolverConfiguration, monitor);
List<String> goals = new ArrayList<String>();
goals.add("package");
request.setGoals(goals);
Properties properties = request.getUserProperties();
properties.setProperty("maven.test.skip", "true");
request.setUserProperties(properties);
MavenExecutionResult executionResult = maven.execute(request, monitor);
if (executionResult.hasExceptions()){
List<Throwable> exceptions = executionResult.getExceptions();
for (Throwable throwable : exceptions) {
throwable.printStackTrace();
}
}else{
Artifact apkArtifact = executionResult.getProject().getArtifact();
if ("apk".equals(apkArtifact.getType())){
File apkFile = apkArtifact.getFile();
IJavaProject javaProject = JavaCore.create(project);
IPath outputLocation = javaProject.getOutputLocation();
File realOutputFolder = project.getWorkspace().getRoot().getFolder(outputLocation).getLocation().toFile();
String newApkFilename = project.getName() + ".apk";
File newApkFile = new File(realOutputFolder, newApkFilename);
FileUtils.copyFile(apkFile, newApkFile);
ApkInstallManager.getInstance().resetInstallationFor(project);
}
}
}catch(Exception e){
e.printStackTrace();
throw e;
}finally{
project.refreshLocal(IProject.DEPTH_INFINITE, monitor);
}
}else{
ApkInstallManager.getInstance().resetInstallationFor(project);
}
return null;
}
| public Set<IProject> build(int kind, IProgressMonitor monitor) throws Exception {
final IProject project = getMavenProjectFacade().getProject();
if(IncrementalProjectBuilder.AUTO_BUILD == kind || IncrementalProjectBuilder.CLEAN_BUILD == kind || IncrementalProjectBuilder.FULL_BUILD == kind) {
try{
MavenPlugin plugin = MavenPlugin.getDefault();
MavenProjectManager projectManager = plugin.getMavenProjectManager();
IMaven maven = plugin.getMaven();
IFile pom = project.getFile(new Path(IMavenConstants.POM_FILE_NAME));
IMavenProjectFacade projectFacade = projectManager.create(pom, false, monitor);
ResolverConfiguration resolverConfiguration = projectFacade.getResolverConfiguration();
resolverConfiguration.setResolveWorkspaceProjects(false);
MavenExecutionRequest request = projectManager.createExecutionRequest(pom, resolverConfiguration, monitor);
List<String> goals = new ArrayList<String>();
goals.add("install");
request.setGoals(goals);
Properties properties = request.getUserProperties();
properties.setProperty("maven.test.skip", "true");
request.setUserProperties(properties);
MavenExecutionResult executionResult = maven.execute(request, monitor);
if (executionResult.hasExceptions()){
List<Throwable> exceptions = executionResult.getExceptions();
for (Throwable throwable : exceptions) {
throwable.printStackTrace();
}
}else{
Artifact apkArtifact = executionResult.getProject().getArtifact();
if ("apk".equals(apkArtifact.getType())){
File apkFile = apkArtifact.getFile();
IJavaProject javaProject = JavaCore.create(project);
IPath outputLocation = javaProject.getOutputLocation();
File realOutputFolder = project.getWorkspace().getRoot().getFolder(outputLocation).getLocation().toFile();
String newApkFilename = project.getName() + ".apk";
File newApkFile = new File(realOutputFolder, newApkFilename);
FileUtils.copyFile(apkFile, newApkFile);
ApkInstallManager.getInstance().resetInstallationFor(project);
}
}
}catch(Exception e){
e.printStackTrace();
throw e;
}finally{
project.refreshLocal(IProject.DEPTH_INFINITE, monitor);
}
}else{
ApkInstallManager.getInstance().resetInstallationFor(project);
}
return null;
}
|
public static void test() {
User32.INSTANCE.EnumWindows(new WinUser.WNDENUMPROC() {
@Override
public boolean callback(HWND hWnd, Pointer pntr) {
if (!User32.INSTANCE.IsWindowVisible(hWnd))
return true;
char lpString[] = new char[32768];
User32.INSTANCE.GetWindowText(hWnd, lpString, lpString.length);
String windowTitle = Native.toString(lpString);
System.out.println("window: \"" + windowTitle + "\"");
return true;
}
}, null);
}
| public static void test() {
User32.INSTANCE.EnumWindows(new WinUser.WNDENUMPROC() {
public boolean callback(HWND hWnd, Pointer pntr) {
if (!User32.INSTANCE.IsWindowVisible(hWnd))
return true;
char lpString[] = new char[32768];
User32.INSTANCE.GetWindowText(hWnd, lpString, lpString.length);
String windowTitle = Native.toString(lpString);
System.out.println("window: \"" + windowTitle + "\"");
return true;
}
}, null);
}
|
protected void startToolL(final IProgressMonitor monitor) throws CoreException {
fRjsId = RjsComConfig.registerClientComHandler(fRjs);
fRjs.initClient(getTool(), this, fRjsProperties, fRjsId);
try {
final Map<String, Object> data = new HashMap<String, Object>();
final IToolEventHandler loginHandler = getEventHandler(IToolEventHandler.LOGIN_REQUEST_EVENT_ID);
String msg = null;
boolean connected = false;
while (!connected) {
final Map<String, Object> initData = getInitData();
final ServerLogin login = fRjsConnection.getServer().createLogin(Server.C_CONSOLE_CONNECT);
try {
final Callback[] callbacks = login.getCallbacks();
if (callbacks != null) {
final List<Callback> checked = new ArrayList<Callback>();
FxCallback fx = null;
for (final Callback callback : callbacks) {
if (callback instanceof FxCallback) {
fx = (FxCallback) callback;
}
else {
checked.add(callback);
}
}
if (initData != null) {
data.putAll(initData);
}
data.put(LOGIN_ADDRESS_DATA_KEY, (fx != null) ? fAddress.getHost() : fAddress.getAddress());
data.put(LOGIN_MESSAGE_DATA_KEY, msg);
data.put(LOGIN_CALLBACKS_DATA_KEY, checked.toArray(new Callback[checked.size()]));
if (loginHandler == null) {
throw new CoreException(new Status(IStatus.ERROR, RConsoleCorePlugin.PLUGIN_ID,
ICommonStatusConstants.LAUNCHING,
"Login requested but not supported by this configuration.", null ));
}
if (!loginHandler.handle(IToolEventHandler.LOGIN_REQUEST_EVENT_ID, this, data, monitor).isOK()) {
throw new CoreException(Status.CANCEL_STATUS);
}
if (fx != null) {
RjsUtil.handleFxCallback(RjsUtil.getSession(data, new SubProgressMonitor(monitor, 1)), fx, new SubProgressMonitor(monitor, 1));
}
}
msg = null;
if (monitor.isCanceled()) {
throw new CoreException(Status.CANCEL_STATUS);
}
final Map<String, Object> args = new HashMap<String, Object>();
args.putAll(fRjsProperties);
ConsoleEngine rjServer;
if (fStartup) {
args.put("args", fRArgs);
rjServer = (ConsoleEngine) fRjsConnection.getServer().execute(Server.C_CONSOLE_START, args, login.createAnswer());
}
else {
rjServer = (ConsoleEngine) fRjsConnection.getServer().execute(Server.C_CONSOLE_CONNECT, args, login.createAnswer());
}
fRjs.setServer(rjServer, 0);
connected = true;
if (callbacks != null) {
loginHandler.handle(IToolEventHandler.LOGIN_OK_EVENT_ID, this, data, monitor);
if (initData != null) {
initData.put(LOGIN_USERNAME_DATA_KEY, data.get(LOGIN_USERNAME_DATA_KEY));
}
}
}
catch (final LoginException e) {
msg = e.getLocalizedMessage();
}
finally {
if (login != null) {
login.clearData();
}
}
}
final ServerInfo info = fRjsConnection.getServer().getInfo();
if (fWorkspaceData.isRemote()) {
try {
final String wd = FileUtil.toString(fWorkspaceData.toFileStore(info.getDirectory()));
if (wd != null) {
setStartupWD(wd);
}
}
catch (final CoreException e) {}
}
else {
setStartupWD(info.getDirectory());
}
final long timestamp = info.getTimestamp();
if (timestamp != 0) {
setStartupTimestamp(timestamp);
}
final List<IStatus> warnings = new ArrayList<IStatus>();
initTracks(info.getDirectory(), monitor, warnings);
if (fStartup && !fStartupsRunnables.isEmpty()) {
fQueue.add(fStartupsRunnables.toArray(new IToolRunnable[fStartupsRunnables.size()]));
fStartupsRunnables.clear();
}
if (!fStartup) {
handleStatus(new Status(IStatus.INFO, RConsoleCorePlugin.PLUGIN_ID,
addTimestampToMessage(RNicoMessages.R_Info_Reconnected_message, fProcess.getConnectionTimestamp()) ),
monitor);
}
fRjs.runMainLoop(null, null, monitor);
fRjs.activateConsole();
scheduleControllerRunnable(new ControllerSystemRunnable(
"r/rj/start2", "Finish Initialization / Read Output") {
public void run(final IToolService s,
final IProgressMonitor monitor) throws CoreException {
if (!fRjs.isConsoleReady()) {
fRjs.runMainLoop(null, null, monitor);
}
for (final IStatus status : warnings) {
handleStatus(status, monitor);
}
}
});
}
catch (final RemoteException e) {
throw new CoreException(new Status(IStatus.ERROR, RConsoleCorePlugin.PLUGIN_ID,
ICommonStatusConstants.LAUNCHING,
"The R engine could not be started.", e ));
}
catch (final RjException e) {
throw new CoreException(new Status(IStatus.ERROR, RConsoleCorePlugin.PLUGIN_ID,
ICommonStatusConstants.LAUNCHING,
"An error occured when creating login data.", e ));
}
}
| protected void startToolL(final IProgressMonitor monitor) throws CoreException {
fRjsId = RjsComConfig.registerClientComHandler(fRjs);
fRjs.initClient(getTool(), this, fRjsProperties, fRjsId);
try {
final Map<String, Object> data = new HashMap<String, Object>();
final IToolEventHandler loginHandler = getEventHandler(IToolEventHandler.LOGIN_REQUEST_EVENT_ID);
String msg = null;
boolean connected = false;
while (!connected) {
final Map<String, Object> initData = getInitData();
final ServerLogin login = fRjsConnection.getServer().createLogin(Server.C_CONSOLE_CONNECT);
try {
final Callback[] callbacks = login.getCallbacks();
if (callbacks != null) {
final List<Callback> checked = new ArrayList<Callback>();
FxCallback fx = null;
for (final Callback callback : callbacks) {
if (callback instanceof FxCallback) {
fx = (FxCallback) callback;
}
else {
checked.add(callback);
}
}
if (initData != null) {
data.putAll(initData);
}
data.put(LOGIN_ADDRESS_DATA_KEY, (fx != null) ? fAddress.getHost() : fAddress.getAddress());
data.put(LOGIN_MESSAGE_DATA_KEY, msg);
data.put(LOGIN_CALLBACKS_DATA_KEY, checked.toArray(new Callback[checked.size()]));
if (loginHandler == null) {
throw new CoreException(new Status(IStatus.ERROR, RConsoleCorePlugin.PLUGIN_ID,
ICommonStatusConstants.LAUNCHING,
"Login requested but not supported by this configuration.", null ));
}
if (!loginHandler.handle(IToolEventHandler.LOGIN_REQUEST_EVENT_ID, this, data, monitor).isOK()) {
throw new CoreException(Status.CANCEL_STATUS);
}
if (fx != null) {
RjsUtil.handleFxCallback(RjsUtil.getSession(data, new SubProgressMonitor(monitor, 1)), fx, new SubProgressMonitor(monitor, 1));
}
}
msg = null;
if (monitor.isCanceled()) {
throw new CoreException(Status.CANCEL_STATUS);
}
final Map<String, Object> args = new HashMap<String, Object>();
args.putAll(fRjsProperties);
ConsoleEngine rjServer;
if (fStartup) {
args.put("args", fRArgs);
rjServer = (ConsoleEngine) fRjsConnection.getServer().execute(Server.C_CONSOLE_START, args, login.createAnswer());
}
else {
rjServer = (ConsoleEngine) fRjsConnection.getServer().execute(Server.C_CONSOLE_CONNECT, args, login.createAnswer());
}
fRjs.setServer(rjServer, 0);
connected = true;
if (callbacks != null) {
loginHandler.handle(IToolEventHandler.LOGIN_OK_EVENT_ID, this, data, monitor);
if (initData != null) {
initData.put(LOGIN_USERNAME_DATA_KEY, data.get(LOGIN_USERNAME_DATA_KEY));
}
}
}
catch (final LoginException e) {
msg = e.getLocalizedMessage();
}
finally {
if (login != null) {
login.clearData();
}
}
}
final ServerInfo info = fRjsConnection.getServer().getInfo();
if (fWorkspaceData.isRemote()) {
try {
final String wd = FileUtil.toString(fWorkspaceData.toFileStore(info.getDirectory()));
if (wd != null) {
setStartupWD(wd);
}
}
catch (final CoreException e) {}
}
else {
setStartupWD(info.getDirectory());
}
final long timestamp = info.getTimestamp();
if (timestamp != 0) {
setStartupTimestamp(timestamp);
}
final List<IStatus> warnings = new ArrayList<IStatus>();
initTracks(info.getDirectory(), monitor, warnings);
if (fStartup && !fStartupsRunnables.isEmpty()) {
fQueue.add(fStartupsRunnables.toArray(new IToolRunnable[fStartupsRunnables.size()]));
fStartupsRunnables.clear();
}
if (!fStartup) {
handleStatus(new Status(IStatus.INFO, RConsoleCorePlugin.PLUGIN_ID,
addTimestampToMessage(RNicoMessages.R_Info_Reconnected_message, fProcess.getConnectionTimestamp()) ),
monitor);
}
fRjs.activateConsole();
scheduleControllerRunnable(new ControllerSystemRunnable(
"r/rj/start2", "Finish Initialization / Read Output") {
public void run(final IToolService s,
final IProgressMonitor monitor) throws CoreException {
if (!fRjs.isConsoleReady()) {
fRjs.runMainLoop(null, null, monitor);
}
for (final IStatus status : warnings) {
handleStatus(status, monitor);
}
}
});
}
catch (final RemoteException e) {
throw new CoreException(new Status(IStatus.ERROR, RConsoleCorePlugin.PLUGIN_ID,
ICommonStatusConstants.LAUNCHING,
"The R engine could not be started.", e ));
}
catch (final RjException e) {
throw new CoreException(new Status(IStatus.ERROR, RConsoleCorePlugin.PLUGIN_ID,
ICommonStatusConstants.LAUNCHING,
"An error occured when creating login data.", e ));
}
}
|
public void putUpdatedTaskData(final ITask itask, final TaskData taskData, final boolean user, Object token)
throws CoreException {
final AbstractTask task = (AbstractTask) itask;
Assert.isNotNull(task);
Assert.isNotNull(taskData);
final AbstractRepositoryConnector connector = repositoryManager.getRepositoryConnector(task.getConnectorKind());
final TaskRepository repository = repositoryManager.getRepository(task.getConnectorKind(),
task.getRepositoryUrl());
final boolean taskDataChanged = connector.hasTaskChanged(repository, task, taskData);
final TaskDataManagerEvent event = new TaskDataManagerEvent(this, itask, taskData, null);
event.setTaskDataChanged(taskDataChanged);
final boolean[] synchronizationStateChanged = new boolean[1];
if (taskDataChanged || user) {
taskList.run(new ITaskListRunnable() {
public void execute(IProgressMonitor monitor) throws CoreException {
boolean newTask = false;
if (!taskData.isPartial()) {
File file = getMigratedFile(task, task.getConnectorKind());
newTask = !file.exists();
taskDataStore.putTaskData(ensurePathExists(file), taskData, task.isMarkReadPending(), user);
task.setMarkReadPending(false);
event.setTaskDataUpdated(true);
}
boolean taskChanged = updateTaskFromTaskData(taskData, task, connector, repository);
event.setTaskChanged(taskChanged);
if (taskDataChanged) {
switch (task.getSynchronizationState()) {
case OUTGOING:
task.setSynchronizationState(SynchronizationState.CONFLICT);
break;
case SYNCHRONIZED:
if (newTask) {
task.setSynchronizationState(SynchronizationState.INCOMING_NEW);
task.setLastReadTimeStamp(null);
} else {
task.setSynchronizationState(SynchronizationState.INCOMING);
}
break;
}
}
if (task.isSynchronizing()) {
task.setSynchronizing(false);
synchronizationStateChanged[0] = true;
}
}
});
} else {
taskList.run(new ITaskListRunnable() {
public void execute(IProgressMonitor monitor) throws CoreException {
if (task.isSynchronizing()) {
task.setSynchronizing(false);
synchronizationStateChanged[0] = true;
}
}
});
}
if (event.getTaskChanged() || event.getTaskDataChanged()) {
taskList.notifyElementChanged(task);
fireTaskDataUpdated(event);
} else if (synchronizationStateChanged[0]) {
taskList.notifySynchronizationStateChanged(task);
}
}
| public void putUpdatedTaskData(final ITask itask, final TaskData taskData, final boolean user, Object token)
throws CoreException {
final AbstractTask task = (AbstractTask) itask;
Assert.isNotNull(task);
Assert.isNotNull(taskData);
final AbstractRepositoryConnector connector = repositoryManager.getRepositoryConnector(task.getConnectorKind());
final TaskRepository repository = repositoryManager.getRepository(task.getConnectorKind(),
task.getRepositoryUrl());
final boolean taskDataChanged = connector.hasTaskChanged(repository, task, taskData);
final TaskDataManagerEvent event = new TaskDataManagerEvent(this, itask, taskData, null);
event.setTaskDataChanged(taskDataChanged);
final boolean[] synchronizationStateChanged = new boolean[1];
if (taskDataChanged || user) {
taskList.run(new ITaskListRunnable() {
public void execute(IProgressMonitor monitor) throws CoreException {
boolean newTask = false;
if (!taskData.isPartial()) {
File file = getMigratedFile(task, task.getConnectorKind());
newTask = !file.exists();
taskDataStore.putTaskData(ensurePathExists(file), taskData, task.isMarkReadPending(), user);
task.setMarkReadPending(false);
event.setTaskDataUpdated(true);
}
boolean taskChanged = updateTaskFromTaskData(taskData, task, connector, repository);
event.setTaskChanged(taskChanged);
if (taskDataChanged) {
switch (task.getSynchronizationState()) {
case OUTGOING:
task.setSynchronizationState(SynchronizationState.CONFLICT);
break;
case SYNCHRONIZED:
if (newTask) {
task.setSynchronizationState(SynchronizationState.INCOMING_NEW);
task.setLastReadTimeStamp(null);
} else {
task.setSynchronizationState(SynchronizationState.INCOMING);
}
break;
}
}
if (task.isSynchronizing()) {
task.setSynchronizing(false);
synchronizationStateChanged[0] = true;
}
}
});
} else {
taskList.run(new ITaskListRunnable() {
public void execute(IProgressMonitor monitor) throws CoreException {
if (task.isSynchronizing()) {
task.setSynchronizing(false);
synchronizationStateChanged[0] = true;
}
}
});
}
if (event.getTaskChanged() || event.getTaskDataChanged()) {
taskList.notifyElementChanged(task);
fireTaskDataUpdated(event);
} else {
if (synchronizationStateChanged[0]) {
taskList.notifySynchronizationStateChanged(task);
}
if (event.getTaskDataUpdated()) {
fireTaskDataUpdated(event);
}
}
}
|
public void test() {
List<String> names = asList("Tom Waits", "Johnny Cash", "Stefan Sundström");
List<String> surNames = names.stream().map((String s) -> s.substring(0, s.indexOf(' '))).collect(Collectors.<String>toList());
assertEquals(asList("Tom", "Johnny", "Stefan"), surNames);
}
| public void test() {
List<String> names = asList("Tom Waits", "Johnny Cash", "Stefan Sundström");
List<String> foreNames = names.stream().map((String s) -> s.substring(0, s.indexOf(' '))).collect(Collectors.<String>toList());
assertEquals(asList("Tom", "Johnny", "Stefan"), foreNames);
}
|
public static Query makeQuery(String text) throws ClientException {
if (text.startsWith("<?xml"))
return new QPQuery(text);
else if (text.toUpperCase().indexOf("WHERE") != -1)
return new XMLQLQuery(text);
else {
throw new ClientException("Invalid query: " + text);
}
}
| public static Query makeQuery(String text) throws ClientException {
if (text.startsWith("<?xml"))
return new QPQuery(text);
else
throw new ClientException("Invalid Query: " + text);
}
|
public boolean render(InternalContextAdapter internalContextAdapter,
Writer writer,
Node node) throws IOException, ResourceNotFoundException, ParseErrorException, MethodInvocationException {
String trimAfter = "/";
if (node.jjtGetNumChildren() == 2) {
final Object nodeTwo = node.jjtGetChild(1).value(internalContextAdapter);
if(nodeTwo != null) {
trimAfter = nodeTwo.toString();
}
}else if (node.jjtGetNumChildren() != 1) {
rsvc.error("#" + getName() + " - Wrong number of arguments");
return false;
}
final Object nodeValue = node.jjtGetChild(0).value(internalContextAdapter);
if(nodeValue == null) {
writer.write("");
return true;
}
final String originalString = nodeValue.toString();
final int index = originalString.lastIndexOf(trimAfter);
if(index == -1)
{
writer.write(originalString);
}
else{
writer.write(originalString.substring(index+trimAfter.length(),originalString.length()));
}
return true;
}
| public boolean render(InternalContextAdapter internalContextAdapter,
Writer writer,
Node node) throws IOException, ResourceNotFoundException, ParseErrorException, MethodInvocationException {
String trimAfter = "/";
if (node.jjtGetNumChildren() == 2) {
final Object nodeTwo = node.jjtGetChild(1).value(internalContextAdapter);
if(nodeTwo != null) {
trimAfter = nodeTwo.toString();
}
}else if (node.jjtGetNumChildren() != 1) {
rsvc.error("#" + getName() + " - Wrong number of arguments");
return false;
}
final Object nodeValue = node.jjtGetChild(0).value(internalContextAdapter);
if(nodeValue == null) {
writer.write("");
return true;
}
String originalString = nodeValue.toString();
int index = originalString.lastIndexOf(trimAfter);
if(index == originalString.length() -1)
{
originalString = originalString.substring(0,originalString.length() -1);
index = originalString.lastIndexOf(trimAfter);
}
if(index == -1)
{
writer.write(originalString);
}
else{
writer.write(originalString.substring(index+trimAfter.length(),originalString.length()));
}
return true;
}
|
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws Exception
{
String limit = request.getParameter("limit");
String query = request.getParameter("query");
String start = request.getParameter("start");
String controlIdStr = request.getParameter(CONTROL_ID);
Map<String, String> keyMap = extractRequestParameter(controlIdStr);
String controlId = keyMap.get("controlId");;
String containerId = keyMap.get("containerIdentifier");
String formContextId = "";
if(keyMap.get(WebUIManagerConstants.FORM_CONTEXT_IDENTIFIER)!= null &&
!"null".equals(keyMap.get(WebUIManagerConstants.FORM_CONTEXT_IDENTIFIER)))
{
formContextId = keyMap.get(WebUIManagerConstants.FORM_CONTEXT_IDENTIFIER);
}
String[] sourceValues = {};
String[] sourceHtmlComponentValues = null;
if (sourceValues.length > 1)
{
sourceHtmlComponentValues = sourceValues[1].split("~");
}
List<String> sourceControlValues = new ArrayList<String>();
if (sourceHtmlComponentValues != null)
{
for (String sourceValue : sourceHtmlComponentValues)
{
if (sourceValue != null && sourceValue.length() > 0)
{
sourceControlValues.add(sourceValue);
}
}
}
Integer limitFetch = Integer.parseInt(limit);
Integer startFetch = Integer.parseInt(start);
JSONArray jsonArray = new JSONArray();
JSONObject mainJsonObject = new JSONObject();
ContainerInterface container = getContainerFromUserSession(request, containerId,
formContextId);
if (container == null)
{
container = EntityCache.getInstance().getContainerById(Long.valueOf(containerId));
}
List<NameValueBean> nameValueBeans = null;
for (ControlInterface control : container.getControlCollection())
{
if (Long.parseLong(controlId) == control.getId())
{
if (control.getIsSkipLogicTargetControl())
{
Map<BaseAbstractAttributeInterface, Object> valueMap = ((Stack<Map<BaseAbstractAttributeInterface, Object>>) CacheManager
.getObjectFromCache(request, DEConstants.CONTAINER_STACK+formContextId)).peek();
skipLogicEvaluationForAddMore(container, control, valueMap, request
.getParameter(DEConstants.COMBOBOX_IDENTIFER));
}
nameValueBeans = ControlsUtility.populateListOfValues(control, sourceControlValues,
ControlsUtility.getFormattedDate(keyMap.get(Constants.ENCOUNTER_DATE)));
}
}
Integer total = limitFetch + startFetch;
List<NameValueBean> querySpecificNVBeans = new ArrayList<NameValueBean>();
populateQuerySpecificNameValueBeansList(querySpecificNVBeans, nameValueBeans, query);
mainJsonObject.put("totalCount", querySpecificNVBeans.size());
for (int i = startFetch; i < total && i < querySpecificNVBeans.size(); i++)
{
JSONObject jsonObject = new JSONObject();
jsonObject.put("id", querySpecificNVBeans.get(i).getValue());
jsonObject.put("field", querySpecificNVBeans.get(i).getName());
jsonArray.put(jsonObject);
}
mainJsonObject.put("row", jsonArray);
response.flushBuffer();
PrintWriter out = response.getWriter();
out.write(mainJsonObject.toString());
return null;
}
| public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws Exception
{
String limit = request.getParameter("limit");
String query = request.getParameter("query");
String start = request.getParameter("start");
String controlIdStr = request.getParameter(CONTROL_ID);
Map<String, String> keyMap = extractRequestParameter(controlIdStr);
String controlId = keyMap.get("controlId");;
String containerId = keyMap.get("containerIdentifier");
String formContextId = "";
if(keyMap.get(WebUIManagerConstants.FORM_CONTEXT_IDENTIFIER)!= null &&
!"null".equals(keyMap.get(WebUIManagerConstants.FORM_CONTEXT_IDENTIFIER)))
{
formContextId = keyMap.get(WebUIManagerConstants.FORM_CONTEXT_IDENTIFIER);
}
String[] sourceValues = {};
String[] sourceHtmlComponentValues = null;
if (sourceValues.length > 1)
{
sourceHtmlComponentValues = sourceValues[1].split("~");
}
List<String> sourceControlValues = new ArrayList<String>();
if (sourceHtmlComponentValues != null)
{
for (String sourceValue : sourceHtmlComponentValues)
{
if (sourceValue != null && sourceValue.length() > 0)
{
sourceControlValues.add(sourceValue);
}
}
}
Integer limitFetch = Integer.parseInt(limit);
Integer startFetch = Integer.parseInt(start);
JSONArray jsonArray = new JSONArray();
JSONObject mainJsonObject = new JSONObject();
ContainerInterface container = getContainerFromUserSession(request, containerId,
formContextId);
if (container == null)
{
container = EntityCache.getInstance().getContainerById(Long.valueOf(containerId));
}
List<NameValueBean> nameValueBeans = null;
for (ControlInterface control : container.getAllControls())
{
if (Long.parseLong(controlId) == control.getId())
{
if (control.getIsSkipLogicTargetControl())
{
Map<BaseAbstractAttributeInterface, Object> valueMap = ((Stack<Map<BaseAbstractAttributeInterface, Object>>) CacheManager
.getObjectFromCache(request, DEConstants.CONTAINER_STACK+formContextId)).peek();
skipLogicEvaluationForAddMore(container, control, valueMap, request
.getParameter(DEConstants.COMBOBOX_IDENTIFER));
}
nameValueBeans = ControlsUtility.populateListOfValues(control, sourceControlValues,
ControlsUtility.getFormattedDate(keyMap.get(Constants.ENCOUNTER_DATE)));
}
}
Integer total = limitFetch + startFetch;
List<NameValueBean> querySpecificNVBeans = new ArrayList<NameValueBean>();
populateQuerySpecificNameValueBeansList(querySpecificNVBeans, nameValueBeans, query);
mainJsonObject.put("totalCount", querySpecificNVBeans.size());
for (int i = startFetch; i < total && i < querySpecificNVBeans.size(); i++)
{
JSONObject jsonObject = new JSONObject();
jsonObject.put("id", querySpecificNVBeans.get(i).getValue());
jsonObject.put("field", querySpecificNVBeans.get(i).getName());
jsonArray.put(jsonObject);
}
mainJsonObject.put("row", jsonArray);
response.flushBuffer();
PrintWriter out = response.getWriter();
out.write(mainJsonObject.toString());
return null;
}
|
public String readLine() throws IOException {
StringBuffer s = null;
int startChar;
synchronized(lock) {
ensureOpen();
bufferLoop:
for(; ; ) {
if(nextChar >= nChars) fill();
if(nextChar >= nChars) {
if(s != null && s.length() > 0) return s.toString();
return null;
}
boolean eol = false;
char c = 0;
int i;
skipLF = false;
charLoop:
for(i = nextChar; i < nChars; i++) {
c = cb[i];
if(c == '\n' || c == '\r') {
eol = true;
break charLoop;
}
}
startChar = nextChar;
nextChar = i;
if(eol) {
String str;
if(s == null) {
str = new String(cb, startChar, i - startChar);
} else {
s.append(cb, startChar, i - startChar);
str = s.toString();
}
nextChar++;
if(c == '\r') {
skipLF = true;
}
while(cb[nextChar] == '\n' || cb[nextChar] == '\r') {
nextChar++;
}
return str;
}
if(s == null) s = new StringBuffer(defaultExpectedLineLength);
s.append(cb, startChar, i - startChar);
}
}
}
| public String readLine() throws IOException {
StringBuffer s = null;
int startChar;
synchronized(lock) {
ensureOpen();
bufferLoop:
for(; ; ) {
if(nextChar >= nChars) fill();
if(nextChar >= nChars) {
if(s != null && s.length() > 0) return s.toString();
return null;
}
boolean eol = false;
char c = 0;
int i;
skipLF = false;
charLoop:
for(i = nextChar; i < nChars; i++) {
c = cb[i];
if(c == '\n' || c == '\r') {
eol = true;
break charLoop;
}
}
startChar = nextChar;
nextChar = i;
if(eol) {
String str;
if(s == null) {
str = new String(cb, startChar, i - startChar);
} else {
s.append(cb, startChar, i - startChar);
str = s.toString();
}
nextChar++;
if(c == '\r') {
skipLF = true;
}
while(nextChar < cb.length && (cb[nextChar] == '\n' || cb[nextChar] == '\r')) {
nextChar++;
}
return str;
}
if(s == null) s = new StringBuffer(defaultExpectedLineLength);
s.append(cb, startChar, i - startChar);
}
}
}
|
public void execute() throws BuildException {
checkParameters();
AntClassLoader taskloader = setClassLoader();
registerResourceFactories();
try {
log("loading syntax file...");
ICsTextResource csResource = CsResourceUtil.getResource(syntaxFile);
EList<EObject> contents = csResource.getContents();
if (contents.size() < 1) {
if (!csResource.getErrors().isEmpty()) {
log("Resource has the following errors:");
for (Resource.Diagnostic diagnostic : csResource.getErrors()) {
log(diagnostic.getMessage() + " (line " + diagnostic.getLine() + ", column " + diagnostic.getColumn() + ")");
}
}
throw new BuildException("Generation failed, because the syntax file could not be loaded. Probably it contains syntactical errors.");
}
ResourceSet resourceSet = csResource.getResourceSet();
EcoreUtil.resolveAll(resourceSet);
Set<EObject> unresolvedProxies = CsResourceUtil.findUnresolvedProxies(resourceSet);
for (EObject unresolvedProxy : unresolvedProxies) {
log("Found unresolved proxy: " + unresolvedProxy);
}
if (unresolvedProxies.size() > 0) {
throw new BuildException("Generation failed, because the syntax file contains unresolved proxy objects.");
}
ConcreteSyntax syntax = (ConcreteSyntax) contents.get(0);
performPreprocessing(syntax);
IFileSystemConnector folderConnector = new IFileSystemConnector() {
public File getProjectFolder(IPluginDescriptor plugin) {
return new File(rootFolder.getAbsolutePath() + File.separator + plugin.getName());
}
};
Result result = null;
boolean useUIJob = false;
if (Platform.isRunning()) {
File wsFolder = new File(ResourcesPlugin.getWorkspace().getRoot().getLocationURI());
if(rootFolder.equals(wsFolder))
useUIJob = true;
}
AntProblemCollector problemCollector = new AntProblemCollector(this);
if (useUIJob) {
UIGenerationContext context = new UIGenerationContext(folderConnector, problemCollector, syntax);
UICreateResourcePluginsJob job = new UICreateResourcePluginsJob();
result = job.run(
context,
new AntLogMarker(this),
new AntDelegateProgressMonitor(this)
);
} else {
AntGenerationContext context = new AntGenerationContext(folderConnector, problemCollector, syntax, rootFolder, syntaxProjectName, generateANTLRPlugin, generateModelCode);
AntResourcePluginGenerator generator = new AntResourcePluginGenerator();
result = generator.run(
context,
new AntLogMarker(this),
new AntDelegateProgressMonitor(this)
);
}
if (result != Result.SUCCESS) {
if (result == Result.ERROR_FOUND_UNRESOLVED_PROXIES) {
for (EObject unresolvedProxy : result.getUnresolvedProxies()) {
log("Found unresolved proxy \"" + ((InternalEObject) unresolvedProxy).eProxyURI() + "\" in " + unresolvedProxy.eResource());
}
resetClassLoader(taskloader);
throw new BuildException("Generation failed " + result);
} else {
resetClassLoader(taskloader);
throw new BuildException("Generation failed " + result);
}
}
Collection<GenerationProblem> errors = problemCollector.getErrors();
if (!errors.isEmpty()) {
for (GenerationProblem error : errors) {
log("Found problem: " + error.getMessage(), Project.MSG_ERR);
}
throw new BuildException("Generation failed. Found " + errors.size() + " problem(s) while generating text resource plug-ins.");
}
} catch (Exception e) {
resetClassLoader(taskloader);
log("Exception while generation text resource: " + e.getMessage(), Project.MSG_ERR);
e.printStackTrace();
throw new BuildException(e);
}
resetClassLoader(taskloader);
}
| public void execute() throws BuildException {
checkParameters();
AntClassLoader taskloader = setClassLoader();
registerResourceFactories();
try {
log("loading syntax file...");
ICsTextResource csResource = CsResourceUtil.getResource(syntaxFile);
EList<EObject> contents = csResource.getContents();
if (contents.size() < 1) {
if (!csResource.getErrors().isEmpty()) {
log("Resource has the following errors:");
for (Resource.Diagnostic diagnostic : csResource.getErrors()) {
log(diagnostic.getMessage() + " (line " + diagnostic.getLine() + ", column " + diagnostic.getColumn() + ")");
}
}
throw new BuildException("Generation failed, because the syntax file could not be loaded. Probably it contains syntactical errors.");
}
ResourceSet resourceSet = csResource.getResourceSet();
EcoreUtil.resolveAll(resourceSet);
Set<EObject> unresolvedProxies = CsResourceUtil.findUnresolvedProxies(resourceSet);
for (EObject unresolvedProxy : unresolvedProxies) {
log("Found unresolved proxy: " + unresolvedProxy, Project.MSG_ERR);
}
if (unresolvedProxies.size() > 0) {
throw new BuildException("Generation failed, because the syntax file contains unresolved proxy objects.");
}
ConcreteSyntax syntax = (ConcreteSyntax) contents.get(0);
performPreprocessing(syntax);
IFileSystemConnector folderConnector = new IFileSystemConnector() {
public File getProjectFolder(IPluginDescriptor plugin) {
return new File(rootFolder.getAbsolutePath() + File.separator + plugin.getName());
}
};
Result result = null;
boolean useUIJob = false;
if (Platform.isRunning()) {
File wsFolder = new File(ResourcesPlugin.getWorkspace().getRoot().getLocationURI());
if(rootFolder.equals(wsFolder))
useUIJob = true;
}
AntProblemCollector problemCollector = new AntProblemCollector(this);
if (useUIJob) {
UIGenerationContext context = new UIGenerationContext(folderConnector, problemCollector, syntax);
UICreateResourcePluginsJob job = new UICreateResourcePluginsJob();
result = job.run(
context,
new AntLogMarker(this),
new AntDelegateProgressMonitor(this)
);
} else {
AntGenerationContext context = new AntGenerationContext(folderConnector, problemCollector, syntax, rootFolder, syntaxProjectName, generateANTLRPlugin, generateModelCode);
AntResourcePluginGenerator generator = new AntResourcePluginGenerator();
result = generator.run(
context,
new AntLogMarker(this),
new AntDelegateProgressMonitor(this)
);
}
if (result != Result.SUCCESS) {
if (result == Result.ERROR_FOUND_UNRESOLVED_PROXIES) {
for (EObject unresolvedProxy : result.getUnresolvedProxies()) {
log("Found unresolved proxy \"" + ((InternalEObject) unresolvedProxy).eProxyURI() + "\" in " + unresolvedProxy.eResource());
}
resetClassLoader(taskloader);
throw new BuildException("Generation failed " + result);
} else {
resetClassLoader(taskloader);
throw new BuildException("Generation failed " + result);
}
}
Collection<GenerationProblem> errors = problemCollector.getErrors();
if (!errors.isEmpty()) {
for (GenerationProblem error : errors) {
log("Found problem: " + error.getMessage(), Project.MSG_ERR);
}
throw new BuildException("Generation failed. Found " + errors.size() + " problem(s) while generating text resource plug-ins.");
}
} catch (Exception e) {
resetClassLoader(taskloader);
log("Exception while generation text resource: " + e.getMessage(), Project.MSG_ERR);
e.printStackTrace();
throw new BuildException(e);
}
resetClassLoader(taskloader);
}
|
public Player getPlayer(String target, Player searcher) throws BadPlayerMatchException {
final List<Player> players = new ArrayList<Player>();
final boolean hidingVanished = (searcher != null) && VanishPerms.canSeeAll(searcher);
for (final Player p : J2MC_Manager.getCore().getServer().getOnlinePlayers()) {
try {
if (!hidingVanished || !VanishNoPacket.isVanished(p.getName())) {
if (p.getName().toLowerCase().contains(target.toLowerCase())) {
players.add(p);
}
}
} catch (final VanishNotLoadedException e) {
J2MC_Manager.getCore().buggerAll("VanishNoPacket DIED");
}
}
if (players.size() > 1) {
throw new TooManyPlayersException(players.size());
}
if (players.size() == 0) {
throw new NoPlayersException();
}
return players.get(0);
}
| public Player getPlayer(String target, Player searcher) throws BadPlayerMatchException {
final List<Player> players = new ArrayList<Player>();
final boolean hidingVanished = (searcher != null) && VanishPerms.canSeeAll(searcher);
for (final Player player : J2MC_Manager.getCore().getServer().getOnlinePlayers()) {
try {
if (!hidingVanished || !VanishNoPacket.isVanished(player.getName())) {
if (player.getName().toLowerCase().contains(target.toLowerCase())) {
players.add(player);
}
if(player.getName().equalsIgnoreCase(target)){
return player;
}
}
} catch (final VanishNotLoadedException e) {
J2MC_Manager.getCore().buggerAll("VanishNoPacket DIED");
}
}
if (players.size() > 1) {
throw new TooManyPlayersException(players.size());
}
if (players.size() == 0) {
throw new NoPlayersException();
}
return players.get(0);
}
|
public void addHeaderLine(String line)
{
if (line != null && !"".equals(line))
{
int pos = line.indexOf(": ");
int termPos = line.indexOf(' ');
if (pos > 0 && (termPos == -1 || pos < termPos))
{
line = line.trim();
String name = line.substring(0, pos);
List<String> vals = new ArrayList<String>();
if (line.length() >= pos + 2)
{
line = line.substring(pos + 2);
if (name.equals(lastHeaderName))
{
SmtpHeader h = (SmtpHeader) headers.get(name);
if (h != null)
{
h.getValues().add(line);
return;
}
else
vals.add(line);
}
else
{
lastHeaderName = name;
if (lastHeaderName.startsWith("X-"))
vals.add(line);
else
parseMultipleValues(line, vals);
}
}
headers.put(name, new SmtpHeader(name, vals));
}
else
{
SmtpHeader h = headers.get(lastHeaderName);
if (lastHeaderName.startsWith("X-"))
h.getValues().add(line);
else if (SmtpHeadersInterface.SUBJECT.equals(lastHeaderName))
h.getValues().add(line);
else
parseMultipleValues(line, h.getValues());
}
}
}
| public void addHeaderLine(String line)
{
if (line != null && !"".equals(line))
{
int pos = line.indexOf(": ");
int termPos = line.indexOf(' ');
if (pos > 0 && (termPos == -1 || pos < termPos))
{
line = line.trim();
String name = line.substring(0, pos);
List<String> vals = new ArrayList<String>();
if (line.length() >= pos + 2)
{
line = line.substring(pos + 2);
if (name.equals(lastHeaderName))
{
SmtpHeader h = (SmtpHeader) headers.get(name);
if (h != null)
{
h.getValues().add(line);
return;
}
else
vals.add(line);
}
else
{
lastHeaderName = name;
if (lastHeaderName.startsWith("X-"))
vals.add(line);
else
parseMultipleValues(line, vals);
}
}
headers.put(name, new SmtpHeader(name, vals));
}
else
{
SmtpHeader h = headers.get(lastHeaderName);
if (lastHeaderName.startsWith("X-"))
h.getValues().add(line);
else if (SmtpHeadersInterface.SUBJECT.equals(lastHeaderName))
h.getValues().set(0, h.getValues().get(0)+'\n'+line);
else
parseMultipleValues(line, h.getValues());
}
}
}
|
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
elementPath += "/"+qName;
if (elementPath.equalsIgnoreCase("/database/databaseVersions/databaseVersion")) {
databaseVersion = new DatabaseVersion();
}
else if (elementPath.equalsIgnoreCase("/database/databaseVersions/databaseVersion/header/time")) {
Date timeValue = new Date(Long.parseLong(attributes.getValue("value")));
databaseVersion.setTimestamp(timeValue);
}
else if (elementPath.equalsIgnoreCase("/database/databaseVersions/databaseVersion/header/client")) {
String clientName = attributes.getValue("name");
databaseVersion.setClient(clientName);
}
else if (elementPath.equalsIgnoreCase("/database/databaseVersions/databaseVersion/header/vectorClock")) {
vectorClock = new VectorClock();
}
else if (elementPath.equalsIgnoreCase("/database/databaseVersions/databaseVersion/header/vectorClock/client")) {
String clientName = attributes.getValue("name");
Long clientValue = Long.parseLong(attributes.getValue("value"));
vectorClock.setClock(clientName, clientValue);
}
else if (elementPath.equalsIgnoreCase("/database/databaseVersions/databaseVersion/chunks/chunk")) {
String chunkChecksumStr = attributes.getValue("checksum");
byte[] chunkChecksum = StringUtil.fromHex(chunkChecksumStr);
int chunkSize = Integer.parseInt(attributes.getValue("size"));
ChunkEntry chunkEntry = new ChunkEntry(chunkChecksum, chunkSize);
databaseVersion.addChunk(chunkEntry);
}
else if (elementPath.equalsIgnoreCase("/database/databaseVersions/databaseVersion/fileContents/fileContent")) {
String checksumStr = attributes.getValue("checksum");
byte[] checksum = StringUtil.fromHex(checksumStr);
int size = Integer.parseInt(attributes.getValue("size"));
fileContent = new FileContent();
fileContent.setChecksum(checksum);
fileContent.setSize(size);
}
else if (elementPath.equalsIgnoreCase("/database/databaseVersions/databaseVersion/fileContents/fileContent/chunkRefs/chunkRef")) {
String chunkChecksumStr = attributes.getValue("ref");
byte[] chunkChecksum = StringUtil.fromHex(chunkChecksumStr);
fileContent.addChunk(new ChunkEntryId(chunkChecksum));
}
else if (elementPath.equalsIgnoreCase("/database/databaseVersions/databaseVersion/multiChunks/multiChunk")) {
String multChunkIdStr = attributes.getValue("id");
byte[] multiChunkId = StringUtil.fromHex(multChunkIdStr);
if (multiChunkId == null) {
throw new SAXException("Cannot read ID from multichunk " + multChunkIdStr);
}
multiChunk = new MultiChunkEntry(multiChunkId);
}
else if (elementPath.equalsIgnoreCase("/database/databaseVersions/databaseVersion/multiChunks/multiChunk/chunkRefs/chunkRef")) {
String chunkChecksumStr = attributes.getValue("ref");
byte[] chunkChecksum = StringUtil.fromHex(chunkChecksumStr);
multiChunk.addChunk(new ChunkEntryId(chunkChecksum));
}
else if (elementPath.equalsIgnoreCase("/database/databaseVersions/databaseVersion/fileHistories/fileHistory")) {
String fileHistoryIdStr = attributes.getValue("id");
Long fileHistoryId = Long.parseLong(fileHistoryIdStr);
fileHistory = new PartialFileHistory();
fileHistory.setFileId(fileHistoryId);
}
else if (elementPath.equalsIgnoreCase("/database/databaseVersions/databaseVersion/fileHistories/fileHistory/fileVersions/fileVersion")) {
String fileVersionStr = attributes.getValue("version");
String path = attributes.getValue("path");
String sizeStr = attributes.getValue("size");
String typeStr = attributes.getValue("type");
String statusStr = attributes.getValue("status");
String lastModifiedStr = attributes.getValue("lastModified");
String updatedStr = attributes.getValue("updated");
String createdBy = attributes.getValue("createdBy");
String checksumStr = attributes.getValue("checksum");
String linkTarget = attributes.getValue("linkTarget");
String dosAttributes = attributes.getValue("dosattrs");
String posixPermissions = attributes.getValue("posixperms");
if (fileVersionStr == null || path == null || typeStr == null || statusStr == null || sizeStr == null || lastModifiedStr == null) {
throw new SAXException("FileVersion: Attributes missing: version, path, type, status, size and last modified are mandatory");
}
FileVersion fileVersion = new FileVersion();
fileVersion.setVersion(Long.parseLong(fileVersionStr));
fileVersion.setPath(path);
fileVersion.setType(FileType.valueOf(typeStr));
fileVersion.setStatus(FileStatus.valueOf(statusStr));
fileVersion.setSize(Long.parseLong(sizeStr));
fileVersion.setLastModified(new Date(Long.parseLong(lastModifiedStr)));
if (updatedStr != null) {
fileVersion.setUpdated(new Date(Long.parseLong(updatedStr)));
}
if (createdBy != null) {
fileVersion.setCreatedBy(createdBy);
}
if (checksumStr != null) {
fileVersion.setChecksum(StringUtil.fromHex(checksumStr));
}
if (linkTarget != null) {
fileVersion.setLinkTarget(linkTarget);
}
if (dosAttributes != null) {
fileVersion.setDosAttributes(dosAttributes);
}
if (posixPermissions != null) {
fileVersion.setPosixPermissions(posixPermissions);
}
fileHistory.addFileVersion(fileVersion);
}
else {
}
}
| public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
elementPath += "/"+qName;
if (elementPath.equalsIgnoreCase("/database/databaseVersions/databaseVersion")) {
databaseVersion = new DatabaseVersion();
}
else if (elementPath.equalsIgnoreCase("/database/databaseVersions/databaseVersion/header/time")) {
Date timeValue = new Date(Long.parseLong(attributes.getValue("value")));
databaseVersion.setTimestamp(timeValue);
}
else if (elementPath.equalsIgnoreCase("/database/databaseVersions/databaseVersion/header/client")) {
String clientName = attributes.getValue("name");
databaseVersion.setClient(clientName);
}
else if (elementPath.equalsIgnoreCase("/database/databaseVersions/databaseVersion/header/vectorClock")) {
vectorClock = new VectorClock();
}
else if (elementPath.equalsIgnoreCase("/database/databaseVersions/databaseVersion/header/vectorClock/client")) {
String clientName = attributes.getValue("name");
Long clientValue = Long.parseLong(attributes.getValue("value"));
vectorClock.setClock(clientName, clientValue);
}
else if (elementPath.equalsIgnoreCase("/database/databaseVersions/databaseVersion/chunks/chunk")) {
String chunkChecksumStr = attributes.getValue("checksum");
byte[] chunkChecksum = StringUtil.fromHex(chunkChecksumStr);
int chunkSize = Integer.parseInt(attributes.getValue("size"));
ChunkEntry chunkEntry = new ChunkEntry(chunkChecksum, chunkSize);
databaseVersion.addChunk(chunkEntry);
}
else if (elementPath.equalsIgnoreCase("/database/databaseVersions/databaseVersion/fileContents/fileContent")) {
String checksumStr = attributes.getValue("checksum");
byte[] checksum = StringUtil.fromHex(checksumStr);
long size = Long.parseLong(attributes.getValue("size"));
fileContent = new FileContent();
fileContent.setChecksum(checksum);
fileContent.setSize(size);
}
else if (elementPath.equalsIgnoreCase("/database/databaseVersions/databaseVersion/fileContents/fileContent/chunkRefs/chunkRef")) {
String chunkChecksumStr = attributes.getValue("ref");
byte[] chunkChecksum = StringUtil.fromHex(chunkChecksumStr);
fileContent.addChunk(new ChunkEntryId(chunkChecksum));
}
else if (elementPath.equalsIgnoreCase("/database/databaseVersions/databaseVersion/multiChunks/multiChunk")) {
String multChunkIdStr = attributes.getValue("id");
byte[] multiChunkId = StringUtil.fromHex(multChunkIdStr);
if (multiChunkId == null) {
throw new SAXException("Cannot read ID from multichunk " + multChunkIdStr);
}
multiChunk = new MultiChunkEntry(multiChunkId);
}
else if (elementPath.equalsIgnoreCase("/database/databaseVersions/databaseVersion/multiChunks/multiChunk/chunkRefs/chunkRef")) {
String chunkChecksumStr = attributes.getValue("ref");
byte[] chunkChecksum = StringUtil.fromHex(chunkChecksumStr);
multiChunk.addChunk(new ChunkEntryId(chunkChecksum));
}
else if (elementPath.equalsIgnoreCase("/database/databaseVersions/databaseVersion/fileHistories/fileHistory")) {
String fileHistoryIdStr = attributes.getValue("id");
Long fileHistoryId = Long.parseLong(fileHistoryIdStr);
fileHistory = new PartialFileHistory();
fileHistory.setFileId(fileHistoryId);
}
else if (elementPath.equalsIgnoreCase("/database/databaseVersions/databaseVersion/fileHistories/fileHistory/fileVersions/fileVersion")) {
String fileVersionStr = attributes.getValue("version");
String path = attributes.getValue("path");
String sizeStr = attributes.getValue("size");
String typeStr = attributes.getValue("type");
String statusStr = attributes.getValue("status");
String lastModifiedStr = attributes.getValue("lastModified");
String updatedStr = attributes.getValue("updated");
String createdBy = attributes.getValue("createdBy");
String checksumStr = attributes.getValue("checksum");
String linkTarget = attributes.getValue("linkTarget");
String dosAttributes = attributes.getValue("dosattrs");
String posixPermissions = attributes.getValue("posixperms");
if (fileVersionStr == null || path == null || typeStr == null || statusStr == null || sizeStr == null || lastModifiedStr == null) {
throw new SAXException("FileVersion: Attributes missing: version, path, type, status, size and last modified are mandatory");
}
FileVersion fileVersion = new FileVersion();
fileVersion.setVersion(Long.parseLong(fileVersionStr));
fileVersion.setPath(path);
fileVersion.setType(FileType.valueOf(typeStr));
fileVersion.setStatus(FileStatus.valueOf(statusStr));
fileVersion.setSize(Long.parseLong(sizeStr));
fileVersion.setLastModified(new Date(Long.parseLong(lastModifiedStr)));
if (updatedStr != null) {
fileVersion.setUpdated(new Date(Long.parseLong(updatedStr)));
}
if (createdBy != null) {
fileVersion.setCreatedBy(createdBy);
}
if (checksumStr != null) {
fileVersion.setChecksum(StringUtil.fromHex(checksumStr));
}
if (linkTarget != null) {
fileVersion.setLinkTarget(linkTarget);
}
if (dosAttributes != null) {
fileVersion.setDosAttributes(dosAttributes);
}
if (posixPermissions != null) {
fileVersion.setPosixPermissions(posixPermissions);
}
fileHistory.addFileVersion(fileVersion);
}
else {
}
}
|
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mViewPager = new ViewPager(this);
mViewPager.setId(R.id.root_view);
setContentView(mViewPager);
ActionBar ab = getActionBar();
ab.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
ab.setDisplayShowHomeEnabled(false);
ab.setDisplayShowTitleEnabled(false);
mTabsAdapter = new TabsAdapter(this, mViewPager);
mTabsAdapter.addTab(ab.newTab().setText(R.string.tab_photos),
PhotoSetFragment.class, null);
mTabsAdapter.addTab(ab.newTab().setText(R.string.tab_albums),
AlbumSetFragment.class, null);
if (savedInstanceState != null) {
ab.setSelectedNavigationItem(savedInstanceState.getInt("tab", 0));
}
}
| protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mViewPager = new ViewPager(this);
mViewPager.setId(R.id.viewpager);
setContentView(mViewPager);
ActionBar ab = getActionBar();
ab.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
ab.setDisplayShowHomeEnabled(false);
ab.setDisplayShowTitleEnabled(false);
mTabsAdapter = new TabsAdapter(this, mViewPager);
mTabsAdapter.addTab(ab.newTab().setText(R.string.tab_photos),
PhotoSetFragment.class, null);
mTabsAdapter.addTab(ab.newTab().setText(R.string.tab_albums),
AlbumSetFragment.class, null);
if (savedInstanceState != null) {
ab.setSelectedNavigationItem(savedInstanceState.getInt("tab", 0));
}
}
|
public static void soapNotifEndPoint(String topicId) {
String eventTitle;
String eventText;
String notifyMessage;
try {
notifyMessage = new java.util.Scanner(request.body).useDelimiter("\\A").next();
} catch (java.util.NoSuchElementException e) {
notifyMessage = "";
}
if (ModelManager.get().getTopicById(topicId).getId().equals("s_FacebookCepResults")) {
Logger.info(notifyMessage);
}
Model rdf;
try {
rdf = receiver.parseRdf(notifyMessage);
Iterator<Statement> it = rdf.findStatements(Variable.ANY, RDF.type,
Variable.ANY);
if (it.hasNext()) {
Statement stat = it.next();
eventTitle = stat.getObject().asURI().asJavaURI().getPath();
eventTitle = eventTitle.substring(eventTitle.lastIndexOf("/") + 1);
} else {
eventTitle = "RDF Event";
}
eventText = HTML.htmlEscape(rdf.serialize(Syntax.Turtle)).replaceAll("\n", "<br />").replaceAll("\\s{4}", " ");
ModelManager
.get()
.getTopicById(topicId)
.multicast(new models.eventstream.Event(eventTitle, eventText));
} catch (Exception e) {
eventTitle = "Event";
eventText = HTML.htmlEscape(EventFormatHelpers.unwrapFromNativeMessageElement(notifyMessage)).replaceAll("\n", "<br />").replaceAll("\\s{4}", " ");
ModelManager
.get()
.getTopicById(topicId)
.multicast(
new models.eventstream.Event(eventTitle,
eventText));
}
}
| public static void soapNotifEndPoint(String topicId) {
String eventTitle;
String eventText;
String notifyMessage;
try {
notifyMessage = new java.util.Scanner(request.body).useDelimiter("\\A").next();
} catch (java.util.NoSuchElementException e) {
notifyMessage = "";
}
Model rdf;
try {
rdf = receiver.parseRdf(notifyMessage);
Iterator<Statement> it = rdf.findStatements(Variable.ANY, RDF.type,
Variable.ANY);
if (it.hasNext()) {
Statement stat = it.next();
eventTitle = stat.getObject().asURI().asJavaURI().getPath();
eventTitle = eventTitle.substring(eventTitle.lastIndexOf("/") + 1);
} else {
eventTitle = "RDF Event";
}
eventText = HTML.htmlEscape(rdf.serialize(Syntax.Turtle)).replaceAll("\n", "<br />").replaceAll("\\s{4}", " ");
ModelManager
.get()
.getTopicById(topicId)
.multicast(new models.eventstream.Event(eventTitle, eventText));
} catch (Exception e) {
eventTitle = "Event";
eventText = HTML.htmlEscape(EventFormatHelpers.unwrapFromNativeMessageElement(notifyMessage)).replaceAll("\n", "<br />").replaceAll("\\s{4}", " ");
ModelManager
.get()
.getTopicById(topicId)
.multicast(
new models.eventstream.Event(eventTitle,
eventText));
}
}
|
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
mDisplayImageOptions = new DisplayImageOptions.Builder()
.showStubImage(android.R.color.transparent)
.showImageForEmptyUri(R.drawable.placeholder_photo)
.showImageOnFail(R.drawable.placeholder_photo)
.cacheInMemory()
.cacheOnDisc()
.displayer(new SimpleBitmapDisplayer())
.build();
mImageLoadingListener = new OnAnimateImageLoadingListener();
}
| public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
mDisplayImageOptions = new DisplayImageOptions.Builder()
.showStubImage(android.R.color.transparent)
.showImageForEmptyUri(R.drawable.placeholder_photo)
.showImageOnFail(R.drawable.placeholder_photo)
.cacheInMemory(true)
.cacheOnDisc(true)
.displayer(new SimpleBitmapDisplayer())
.build();
mImageLoadingListener = new OnAnimateImageLoadingListener();
}
|
public void launch(ILaunchConfiguration configuration, String mode,
ILaunch launch, IProgressMonitor monitor) throws CoreException {
System.out.println("launching");
IDbgpService dbgpService = null;
try {
int port = 2300;
dbgpService = DLTKDebugPlugin.getDefault().createDbgpService(port,
port + 1);
IScriptDebugTarget target = new ScriptDebugTarget("org.eclipse.dltk.debug.javascriptModel", dbgpService,
"hello", launch,null);
IOConsole cs=new IOConsole("aa",null);
ConsoleScriptDebugTargetStreamManager manager = new ConsoleScriptDebugTargetStreamManager(
cs);
target.setStreamManager(manager);
launch.addDebugTarget(target);
final ISourceLocator sourceLocator = launch.getSourceLocator();
final JavaScriptSourceLookupDirector l=new JavaScriptSourceLookupDirector();
launch.setSourceLocator(new ISourceLocator(){
public Object getSourceElement(IStackFrame stackFrame) {
Object sourceElement = sourceLocator.getSourceElement(stackFrame);
if (sourceElement!=null) return sourceElement;
return l.getSourceElement(stackFrame);
}
});
} catch (Exception e) {
}
super.launch(configuration, mode, launch, monitor);
}
| public void launch(ILaunchConfiguration configuration, String mode,
ILaunch launch, IProgressMonitor monitor) throws CoreException {
System.out.println("launching");
IDbgpService dbgpService = null;
try {
dbgpService = DLTKDebugPlugin.getDefault().getDbgpService();
IScriptDebugTarget target = new ScriptDebugTarget("org.eclipse.dltk.debug.javascriptModel", dbgpService,
"hello", launch,null);
IOConsole cs=new IOConsole("aa",null);
ConsoleScriptDebugTargetStreamManager manager = new ConsoleScriptDebugTargetStreamManager(
cs);
target.setStreamManager(manager);
launch.addDebugTarget(target);
final ISourceLocator sourceLocator = launch.getSourceLocator();
final JavaScriptSourceLookupDirector l=new JavaScriptSourceLookupDirector();
launch.setSourceLocator(new ISourceLocator(){
public Object getSourceElement(IStackFrame stackFrame) {
Object sourceElement = sourceLocator.getSourceElement(stackFrame);
if (sourceElement!=null) return sourceElement;
return l.getSourceElement(stackFrame);
}
});
} catch (Exception e) {
}
super.launch(configuration, mode, launch, monitor);
}
|
public void testApplication(@Drone WebDriver driver, @ArquillianResource URL contextPath) {
driver.get(contextPath + "../tasklist");
Assert.assertTrue(driver.getCurrentUrl().endsWith("tasklist/signin.jsf"));
driver.findElement(By.id("signin:username")).sendKeys("kermit");
driver.findElement(By.id("signin:password")).sendKeys("kermit");
driver.findElement(By.id("signin:submit_button")).submit();
Assert.assertTrue(driver.getCurrentUrl().endsWith("tasklist/app/taskList.jsf"));
driver.findElement(By.linkText("Start Process...")).click();
driver.findElement(By.xpath("//*[@id=\"j_idt21:0:j_idt23\"]/a")).click();
Assert.assertTrue(driver.getCurrentUrl().contains("test-process-application/app/start.jsf"));
driver.findElement(By.id("startForm:someVariable")).sendKeys("some text");
driver.findElement(By.id("startForm:submit_button")).submit();
Assert.assertTrue(driver.getCurrentUrl().endsWith("tasklist/app/taskList.jsf"));
Assert.assertTrue(driver.findElement(By.xpath("//*[@id=\"taskListView\"]/table/tbody/tr/td[1]")).getText().equals("User Task"));
driver.findElement(By.xpath("//*[@id=\"taskListView\"]/table/tbody/tr/td[4]/a")).click();
Assert.assertTrue(driver.getCurrentUrl().contains("test-process-application/app/userTask.jsf"));
driver.findElement(By.id("userTaskForm:submit_button")).submit();
Assert.assertTrue(driver.getCurrentUrl().endsWith("tasklist/app/taskList.jsf"));
Assert.assertTrue(driver.findElement(By.xpath("//*[@id=\"taskListView\"]/table/tbody/tr/td[1]")).getText().equals("-"));
}
| public void testApplication(@Drone WebDriver driver, @ArquillianResource URL contextPath) {
driver.get(contextPath + "../tasklist");
Assert.assertTrue(driver.getCurrentUrl().contains("tasklist/signin.jsf"));
driver.findElement(By.id("signin:username")).sendKeys("kermit");
driver.findElement(By.id("signin:password")).sendKeys("kermit");
driver.findElement(By.id("signin:submit_button")).submit();
Assert.assertTrue(driver.getCurrentUrl().endsWith("tasklist/app/taskList.jsf"));
driver.findElement(By.linkText("Start Process...")).click();
driver.findElement(By.xpath("//*[@id=\"j_idt21:0:j_idt23\"]/a")).click();
Assert.assertTrue(driver.getCurrentUrl().contains("test-process-application/app/start.jsf"));
driver.findElement(By.id("startForm:someVariable")).sendKeys("some text");
driver.findElement(By.id("startForm:submit_button")).submit();
Assert.assertTrue(driver.getCurrentUrl().endsWith("tasklist/app/taskList.jsf"));
Assert.assertTrue(driver.findElement(By.xpath("//*[@id=\"taskListView\"]/table/tbody/tr/td[1]")).getText().equals("User Task"));
driver.findElement(By.xpath("//*[@id=\"taskListView\"]/table/tbody/tr/td[4]/a")).click();
Assert.assertTrue(driver.getCurrentUrl().contains("test-process-application/app/userTask.jsf"));
driver.findElement(By.id("userTaskForm:submit_button")).submit();
Assert.assertTrue(driver.getCurrentUrl().endsWith("tasklist/app/taskList.jsf"));
Assert.assertTrue(driver.findElement(By.xpath("//*[@id=\"taskListView\"]/table/tbody/tr/td[1]")).getText().equals("-"));
}
|
public PhiPlacement(Cfg graph) throws Exception {
finder = new GlobalsAndDefsFinder(graph);
domInfo = new DomFront(new DomMethod(graph)).run();
for (String name : finder.globals()) {
Collection<BasicBlock> definingLocations = finder
.definingLocations(name);
if (definingLocations == null)
continue;
Queue<BasicBlock> worklist = new LinkedList<BasicBlock>(
definingLocations);
Set<BasicBlock> doneList = new HashSet<BasicBlock>();
while (!worklist.isEmpty()) {
BasicBlock workItem = worklist.remove();
doneList.add(workItem);
for (BasicBlock frontierBlock : domInfo.get(workItem).dominanceFrontiers) {
Set<String> phiTargetsAtLocation = phis.get(frontierBlock);
if (phiTargetsAtLocation == null) {
phiTargetsAtLocation = new HashSet<String>();
phis.put(frontierBlock, phiTargetsAtLocation);
}
phiTargetsAtLocation.add(name);
if (doneList.contains(frontierBlock))
worklist.add(frontierBlock);
}
}
}
}
| public PhiPlacement(Cfg graph) throws Exception {
finder = new GlobalsAndDefsFinder(graph);
domInfo = new DomFront(new DomMethod(graph)).run();
for (String name : finder.globals()) {
Collection<BasicBlock> definingLocations = finder
.definingLocations(name);
if (definingLocations == null)
continue;
Queue<BasicBlock> worklist = new LinkedList<BasicBlock>(
definingLocations);
Set<BasicBlock> doneList = new HashSet<BasicBlock>();
while (!worklist.isEmpty()) {
BasicBlock workItem = worklist.remove();
doneList.add(workItem);
for (BasicBlock frontierBlock : domInfo.get(workItem).dominanceFrontiers) {
Set<String> phiTargetsAtLocation = phis.get(frontierBlock);
if (phiTargetsAtLocation == null) {
phiTargetsAtLocation = new HashSet<String>();
phis.put(frontierBlock, phiTargetsAtLocation);
}
phiTargetsAtLocation.add(name);
if (!doneList.contains(frontierBlock))
worklist.add(frontierBlock);
}
}
}
}
|
public SynapseConfiguration getConfiguration(OMElement definitions) {
if (!definitions.getQName().equals(XMLConfigConstants.DEFINITIONS_ELT)) {
throw new SynapseException(
"Wrong QName for this config factory " + definitions.getQName());
}
SynapseConfiguration config = new SynapseConfiguration();
config.setDefaultQName(definitions.getQName());
SequenceMediator rootSequence = new SequenceMediator();
rootSequence.setName(org.apache.synapse.SynapseConstants.MAIN_SEQUENCE_KEY);
Iterator iter = definitions.getChildren();
while (iter.hasNext()) {
Object o = iter.next();
if (o instanceof OMElement) {
OMElement elt = (OMElement) o;
if (XMLConfigConstants.SEQUENCE_ELT.equals(elt.getQName())) {
String key = elt.getAttributeValue(
new QName(XMLConfigConstants.NULL_NAMESPACE, "key"));
if (key != null) {
Mediator m = MediatorFactoryFinder.getInstance().getMediator(elt);
rootSequence.addChild(m);
} else {
defineSequence(config, elt);
}
} else if (XMLConfigConstants.ENDPOINT_ELT.equals(elt.getQName())) {
defineEndpoint(config, elt);
} else if (XMLConfigConstants.ENTRY_ELT.equals(elt.getQName())) {
defineEntry(config, elt);
} else if (XMLConfigConstants.PROXY_ELT.equals(elt.getQName())) {
defineProxy(config, elt);
} else if (XMLConfigConstants.REGISTRY_ELT.equals(elt.getQName())) {
defineRegistry(config, elt);
} else if (XMLConfigConstants.STARTUP_ELT.equals(elt.getQName())) {
defineStartup(config, elt);
} else {
Mediator m = MediatorFactoryFinder.getInstance().getMediator(elt);
rootSequence.addChild(m);
}
}
}
if (config.getLocalRegistry().isEmpty() && config.getProxyServices().isEmpty() &&
rootSequence.getList().isEmpty() && config.getRegistry() != null) {
OMNode remoteConfigNode = config.getRegistry().lookup("synapse.xml");
try {
config = XMLConfigurationBuilder.getConfiguration(SynapseConfigUtils
.getStreamSource(remoteConfigNode).getInputStream());
} catch (XMLStreamException xse) {
throw new SynapseException("Problem loading remote synapse.xml ", xse);
}
}
if (!config.getLocalRegistry().containsKey(SynapseConstants.MAIN_SEQUENCE_KEY)) {
if (rootSequence.getList().isEmpty()) {
setDefaultMainSequence(config);
} else {
config.addSequence(rootSequence.getName(), rootSequence);
}
} else if (!rootSequence.getList().isEmpty()) {
handleException("Invalid Synapse Configuration : Conflict in resolving the \"main\" " +
"mediator\n\tSynapse Configuration cannot have sequence named \"main\" and " +
"toplevel mediators simultaniously");
}
if (config.getFaultSequence() == null) {
setDefaultFaultSequence(config);
}
return config;
}
| public SynapseConfiguration getConfiguration(OMElement definitions) {
if (!definitions.getQName().equals(XMLConfigConstants.DEFINITIONS_ELT)) {
throw new SynapseException(
"Wrong QName for this config factory " + definitions.getQName());
}
SynapseConfiguration config = new SynapseConfiguration();
config.setDefaultQName(definitions.getQName());
SequenceMediator rootSequence = new SequenceMediator();
rootSequence.setName(org.apache.synapse.SynapseConstants.MAIN_SEQUENCE_KEY);
Iterator iter = definitions.getChildren();
while (iter.hasNext()) {
Object o = iter.next();
if (o instanceof OMElement) {
OMElement elt = (OMElement) o;
if (XMLConfigConstants.SEQUENCE_ELT.equals(elt.getQName())) {
String key = elt.getAttributeValue(
new QName(XMLConfigConstants.NULL_NAMESPACE, "key"));
if (key != null) {
Mediator m = MediatorFactoryFinder.getInstance().getMediator(elt);
rootSequence.addChild(m);
} else {
defineSequence(config, elt);
}
} else if (XMLConfigConstants.ENDPOINT_ELT.equals(elt.getQName())) {
defineEndpoint(config, elt);
} else if (XMLConfigConstants.ENTRY_ELT.equals(elt.getQName())) {
defineEntry(config, elt);
} else if (XMLConfigConstants.PROXY_ELT.equals(elt.getQName())) {
defineProxy(config, elt);
} else if (XMLConfigConstants.REGISTRY_ELT.equals(elt.getQName())) {
defineRegistry(config, elt);
} else if (XMLConfigConstants.STARTUP_ELT.equals(elt.getQName())) {
defineStartup(config, elt);
} else {
Mediator m = MediatorFactoryFinder.getInstance().getMediator(elt);
rootSequence.addChild(m);
}
}
}
if (config.getLocalRegistry().isEmpty() && config.getProxyServices().isEmpty() &&
rootSequence.getList().isEmpty() && config.getRegistry() != null) {
OMNode remoteConfigNode = config.getRegistry().lookup("synapse.xml");
try {
config = XMLConfigurationBuilder.getConfiguration(SynapseConfigUtils
.getStreamSource(remoteConfigNode).getInputStream());
} catch (XMLStreamException xse) {
throw new SynapseException("Problem loading remote synapse.xml ", xse);
}
}
if (!config.getLocalRegistry().containsKey(SynapseConstants.MAIN_SEQUENCE_KEY)) {
if (rootSequence.getList().isEmpty() && config.getMainSequence() == null) {
setDefaultMainSequence(config);
} else {
config.addSequence(rootSequence.getName(), rootSequence);
}
} else if (!rootSequence.getList().isEmpty()) {
handleException("Invalid Synapse Configuration : Conflict in resolving the \"main\" " +
"mediator\n\tSynapse Configuration cannot have sequence named \"main\" and " +
"toplevel mediators simultaniously");
}
if (config.getFaultSequence() == null) {
setDefaultFaultSequence(config);
}
return config;
}
|
private Object convertObject(Object toConvert, int maxDepth) throws Exception {
if (toConvert == null)
return JSONObject.NULL;
if (toConvert instanceof Boolean ||
toConvert instanceof CharSequence ||
toConvert instanceof Number) {
return toConvert;
}
if (toConvert.getClass().isEnum() || toConvert instanceof Enum) {
return toConvert.toString();
}
if (toConvert instanceof LoggingPreferences) {
LoggingPreferences prefs = (LoggingPreferences) toConvert;
JSONObject converted = new JSONObject();
for (String logType : prefs.getEnabledLogTypes()) {
converted.put(logType, prefs.getLevel(logType));
}
return converted;
}
if (toConvert instanceof LogEntries) {
LogEntries entries = (LogEntries) toConvert;
JSONArray converted = new JSONArray();
for (LogEntry entry : entries) {
converted.put(mapObject(entry, 1, false));
}
return converted;
}
if (toConvert instanceof Map) {
JSONObject converted = new JSONObject();
for (Object objectEntry : ((Map) toConvert).entrySet()) {
Map.Entry<String, Object> entry = (Map.Entry) objectEntry;
converted.put(entry.getKey(), convertObject(entry.getValue(), maxDepth - 1));
}
return converted;
}
if (toConvert instanceof JSONObject) {
return toConvert;
}
if (toConvert instanceof Collection) {
JSONArray array = new JSONArray();
for (Object o : (Collection) toConvert) {
array.put(convertObject(o, maxDepth - 1));
}
return array;
}
if (toConvert.getClass().isArray()) {
JSONArray converted = new JSONArray();
int length = Array.getLength(toConvert);
for (int i = 0; i < length; i++) {
converted.put(convertObject(Array.get(toConvert, i), maxDepth - 1));
}
return converted;
}
if (toConvert instanceof SessionId) {
JSONObject converted = new JSONObject();
converted.put("value", toConvert.toString());
return converted;
}
if (toConvert instanceof Capabilities) {
return convertObject(((Capabilities) toConvert).asMap(), maxDepth - 1);
}
if (toConvert instanceof DoNotUseProxyPac) {
return convertObject(((DoNotUseProxyPac) toConvert).asMap(), maxDepth - 1);
}
if (toConvert instanceof Date) {
return TimeUnit.MILLISECONDS.toSeconds(((Date) toConvert).getTime());
}
Method toJson = getToJsonMethod(toConvert);
if (toJson != null) {
try {
return toJson.invoke(toConvert);
} catch (IllegalArgumentException e) {
throw new WebDriverException(e);
} catch (IllegalAccessException e) {
throw new WebDriverException(e);
} catch (InvocationTargetException e) {
throw new WebDriverException(e);
}
}
try {
return mapObject(toConvert, maxDepth - 1, toConvert instanceof Cookie);
} catch (Exception e) {
throw new WebDriverException(e);
}
}
| private Object convertObject(Object toConvert, int maxDepth) throws Exception {
if (toConvert == null || maxDepth == 0)
return JSONObject.NULL;
if (toConvert instanceof Boolean ||
toConvert instanceof CharSequence ||
toConvert instanceof Number) {
return toConvert;
}
if (toConvert.getClass().isEnum() || toConvert instanceof Enum) {
return toConvert.toString();
}
if (toConvert instanceof LoggingPreferences) {
LoggingPreferences prefs = (LoggingPreferences) toConvert;
JSONObject converted = new JSONObject();
for (String logType : prefs.getEnabledLogTypes()) {
converted.put(logType, prefs.getLevel(logType));
}
return converted;
}
if (toConvert instanceof LogEntries) {
LogEntries entries = (LogEntries) toConvert;
JSONArray converted = new JSONArray();
for (LogEntry entry : entries) {
converted.put(mapObject(entry, 1, false));
}
return converted;
}
if (toConvert instanceof Map) {
JSONObject converted = new JSONObject();
for (Object objectEntry : ((Map) toConvert).entrySet()) {
Map.Entry<String, Object> entry = (Map.Entry) objectEntry;
converted.put(entry.getKey(), convertObject(entry.getValue(), maxDepth - 1));
}
return converted;
}
if (toConvert instanceof JSONObject) {
return toConvert;
}
if (toConvert instanceof Collection) {
JSONArray array = new JSONArray();
for (Object o : (Collection) toConvert) {
array.put(convertObject(o, maxDepth - 1));
}
return array;
}
if (toConvert.getClass().isArray()) {
JSONArray converted = new JSONArray();
int length = Array.getLength(toConvert);
for (int i = 0; i < length; i++) {
converted.put(convertObject(Array.get(toConvert, i), maxDepth - 1));
}
return converted;
}
if (toConvert instanceof SessionId) {
JSONObject converted = new JSONObject();
converted.put("value", toConvert.toString());
return converted;
}
if (toConvert instanceof Capabilities) {
return convertObject(((Capabilities) toConvert).asMap(), maxDepth - 1);
}
if (toConvert instanceof DoNotUseProxyPac) {
return convertObject(((DoNotUseProxyPac) toConvert).asMap(), maxDepth - 1);
}
if (toConvert instanceof Date) {
return TimeUnit.MILLISECONDS.toSeconds(((Date) toConvert).getTime());
}
Method toJson = getToJsonMethod(toConvert);
if (toJson != null) {
try {
return toJson.invoke(toConvert);
} catch (IllegalArgumentException e) {
throw new WebDriverException(e);
} catch (IllegalAccessException e) {
throw new WebDriverException(e);
} catch (InvocationTargetException e) {
throw new WebDriverException(e);
}
}
try {
return mapObject(toConvert, maxDepth - 1, toConvert instanceof Cookie);
} catch (Exception e) {
throw new WebDriverException(e);
}
}
|
protected Widget createQueryPanel() {
queryBox = new TextArea();
queryBox.setStylePrimaryName("my-QueryBox");
queryBox.setTitle("Goal category");
HorizontalPanel boxPanel = new HorizontalPanel();
boxPanel.setVerticalAlignment(HorizontalPanel.ALIGN_MIDDLE);
boxPanel.setSpacing(5);
final TextBox limitBox = new TextBox();
limitBox.setTitle("Upper limit of the number of examples generated");
limitBox.setWidth("5em");
limitBox.setText("10");
boxPanel.add(new Label("limit:"));
boxPanel.add(limitBox);
boxPanel.add(new HTML(""));
final TextBox depthBox = new TextBox();
depthBox.setTitle("Maximal depth for every example");
depthBox.setWidth("5em");
depthBox.setText("4");
boxPanel.add(new Label("depth:"));
boxPanel.add(depthBox);
boxPanel.add(new HTML(""));
final CheckBox randomBox = new CheckBox();
randomBox.setTitle("random/exhaustive generation");
randomBox.setText("random");
boxPanel.add(randomBox);
outputPanel = new VerticalPanel();
outputPanel.addStyleName("my-translations");
outputPanel.addStyleDependentName("working");
Button execButton = new Button("Execute");
DecoratorPanel queryDecorator = new DecoratorPanel();
VerticalPanel vPanel = new VerticalPanel();
vPanel.add(new Label("Query"));
HorizontalPanel hPanel = new HorizontalPanel();
hPanel.add(queryBox);
hPanel.add(execButton);
vPanel.add(hPanel);
vPanel.add(boxPanel);
queryDecorator.add(vPanel);
VerticalPanel queryPanel = new VerticalPanel();
queryPanel.setHorizontalAlignment(VerticalPanel.ALIGN_CENTER);
queryPanel.add(queryDecorator);
queryPanel.add(outputPanel);
execButton.addClickListener(new ClickListener() {
public void onClick(Widget sender) {
if (executeRequest != null) {
executeRequest.cancel();
}
PGF.GenerationCallback callback = new PGF.GenerationCallback() {
public void onResult(IterableJsArray<PGF.Linearizations> result) {
executeRequest = null;
outputPanel.clear();
outputPanel.removeStyleDependentName("working");
for (PGF.Linearizations lins : result.iterable()) {
LinearizationsPanel lin = new LinearizationsPanel(pgf, lins);
lin.setWidth("100%");
outputPanel.add(lin);
}
}
public void onError(Throwable e) {
executeRequest = null;
statusPopup.showError("The execution failed", e);
}
};
int depth, limit;
try {
depth = Integer.parseInt(depthBox.getText());
limit = Integer.parseInt(limitBox.getText());
} catch (NumberFormatException e) {
return;
}
if (randomBox.getValue())
executeRequest = pgf.generateRandom(queryBox.getText(), depth, limit, callback);
else
executeRequest = pgf.generateAll(queryBox.getText(), depth, limit, callback);
}
});
return queryPanel;
}
| protected Widget createQueryPanel() {
queryBox = new TextArea();
queryBox.setStylePrimaryName("my-QueryBox");
queryBox.setTitle("Goal category");
HorizontalPanel boxPanel = new HorizontalPanel();
boxPanel.setVerticalAlignment(HorizontalPanel.ALIGN_MIDDLE);
boxPanel.setSpacing(5);
final TextBox limitBox = new TextBox();
limitBox.setTitle("Upper limit of the number of examples generated");
limitBox.setWidth("5em");
limitBox.setText("10");
boxPanel.add(new Label("limit:"));
boxPanel.add(limitBox);
boxPanel.add(new HTML(""));
final TextBox depthBox = new TextBox();
depthBox.setTitle("Maximal depth for every example");
depthBox.setWidth("5em");
depthBox.setText("4");
boxPanel.add(new Label("depth:"));
boxPanel.add(depthBox);
boxPanel.add(new HTML(""));
final CheckBox randomBox = new CheckBox();
randomBox.setTitle("random/exhaustive generation");
randomBox.setText("random");
boxPanel.add(randomBox);
outputPanel = new VerticalPanel();
outputPanel.addStyleName("my-translations");
outputPanel.addStyleDependentName("working");
Button execButton = new Button("Execute");
DecoratorPanel queryDecorator = new DecoratorPanel();
VerticalPanel vPanel = new VerticalPanel();
vPanel.add(new Label("Query"));
HorizontalPanel hPanel = new HorizontalPanel();
hPanel.add(queryBox);
hPanel.add(execButton);
vPanel.add(hPanel);
vPanel.add(boxPanel);
queryDecorator.add(vPanel);
VerticalPanel queryPanel = new VerticalPanel();
queryPanel.setHorizontalAlignment(VerticalPanel.ALIGN_CENTER);
queryPanel.add(queryDecorator);
queryPanel.add(outputPanel);
execButton.addClickListener(new ClickListener() {
public void onClick(Widget sender) {
if (executeRequest != null) {
executeRequest.cancel();
}
PGF.GenerationCallback callback = new PGF.GenerationCallback() {
public void onResult(IterableJsArray<PGF.Linearizations> result) {
executeRequest = null;
outputPanel.clear();
outputPanel.removeStyleDependentName("working");
for (PGF.Linearizations lins : result.iterable()) {
LinearizationsPanel lin = new LinearizationsPanel(pgf, lins);
lin.setWidth("100%");
outputPanel.add(lin);
}
}
public void onError(Throwable e) {
executeRequest = null;
statusPopup.showError("The execution failed", e);
}
};
int depth, limit;
try {
depth = Integer.parseInt(depthBox.getText());
limit = Integer.parseInt(limitBox.getText());
} catch (NumberFormatException e) {
statusPopup.showError("Invalid depth/limit parameter", e);
return;
}
if (randomBox.getValue())
executeRequest = pgf.generateRandom(queryBox.getText(), depth, limit, callback);
else
executeRequest = pgf.generateAll(queryBox.getText(), depth, limit, callback);
}
});
return queryPanel;
}
|
public void testChannelAwareMessageListenerDontExpose() throws Exception {
ConnectionFactory mockConnectionFactory = mock(ConnectionFactory.class);
Connection mockConnection = mock(Connection.class);
final Channel firstChannel = mock(Channel.class);
when(firstChannel.isOpen()).thenReturn(true);
final Channel secondChannel = mock(Channel.class);
when(secondChannel.isOpen()).thenReturn(true);
final SingleConnectionFactory singleConnectionFactory = new SingleConnectionFactory(mockConnectionFactory);
when(mockConnectionFactory.newConnection((ExecutorService) null)).thenReturn(mockConnection);
when(mockConnection.isOpen()).thenReturn(true);
final AtomicReference<Exception> tooManyChannels = new AtomicReference<Exception>();
doAnswer(new Answer<Channel>(){
boolean done;
@Override
public Channel answer(InvocationOnMock invocation) throws Throwable {
if (!done) {
done = true;
return firstChannel;
}
return secondChannel;
}
}).when(mockConnection).createChannel();
final AtomicReference<Consumer> consumer = new AtomicReference<Consumer>();
doAnswer(new Answer<String>() {
@Override
public String answer(InvocationOnMock invocation) throws Throwable {
consumer.set((Consumer) invocation.getArguments()[2]);
return null;
}
}).when(firstChannel)
.basicConsume(Mockito.anyString(), Mockito.anyBoolean(), Mockito.any(Consumer.class));
final CountDownLatch commitLatch = new CountDownLatch(1);
doAnswer(new Answer<String>() {
@Override
public String answer(InvocationOnMock invocation) throws Throwable {
commitLatch.countDown();
return null;
}
}).when(firstChannel).txCommit();
final CountDownLatch latch = new CountDownLatch(1);
final AtomicReference<Channel> exposed = new AtomicReference<Channel>();
SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(singleConnectionFactory);
container.setMessageListener(new ChannelAwareMessageListener() {
public void onMessage(Message message, Channel channel) {
exposed.set(channel);
RabbitTemplate rabbitTemplate = new RabbitTemplate(singleConnectionFactory);
rabbitTemplate.setChannelTransacted(true);
rabbitTemplate.convertAndSend("foo", "bar", "baz");
latch.countDown();
}
});
container.setQueueNames("queue");
container.setChannelTransacted(true);
container.setExposeListenerChannel(false);
container.setShutdownTimeout(100);
container.afterPropertiesSet();
container.start();
consumer.get().handleDelivery("qux", new Envelope(1, false, "foo", "bar"), new BasicProperties(), new byte[] {0});
assertTrue(latch.await(10, TimeUnit.SECONDS));
Exception e = tooManyChannels.get();
if (e != null) {
throw e;
}
verify(mockConnection, Mockito.times(2)).createChannel();
assertTrue(commitLatch.await(10, TimeUnit.SECONDS));
verify(firstChannel).txCommit();
verify(secondChannel).txCommit();
verify(secondChannel).basicPublish(Mockito.anyString(), Mockito.anyString(), Mockito.anyBoolean(),
Mockito.anyBoolean(), Mockito.any(BasicProperties.class), Mockito.any(byte[].class));
container.stop();
assertSame(secondChannel, exposed.get());
verify(firstChannel, Mockito.never()).close();
verify(secondChannel, Mockito.times(1)).close();
}
| public void testChannelAwareMessageListenerDontExpose() throws Exception {
ConnectionFactory mockConnectionFactory = mock(ConnectionFactory.class);
Connection mockConnection = mock(Connection.class);
final Channel firstChannel = mock(Channel.class);
when(firstChannel.isOpen()).thenReturn(true);
final Channel secondChannel = mock(Channel.class);
when(secondChannel.isOpen()).thenReturn(true);
final SingleConnectionFactory singleConnectionFactory = new SingleConnectionFactory(mockConnectionFactory);
when(mockConnectionFactory.newConnection((ExecutorService) null)).thenReturn(mockConnection);
when(mockConnection.isOpen()).thenReturn(true);
final AtomicReference<Exception> tooManyChannels = new AtomicReference<Exception>();
doAnswer(new Answer<Channel>(){
boolean done;
@Override
public Channel answer(InvocationOnMock invocation) throws Throwable {
if (!done) {
done = true;
return firstChannel;
}
return secondChannel;
}
}).when(mockConnection).createChannel();
final AtomicReference<Consumer> consumer = new AtomicReference<Consumer>();
doAnswer(new Answer<String>() {
@Override
public String answer(InvocationOnMock invocation) throws Throwable {
consumer.set((Consumer) invocation.getArguments()[2]);
return null;
}
}).when(firstChannel)
.basicConsume(Mockito.anyString(), Mockito.anyBoolean(), Mockito.any(Consumer.class));
final CountDownLatch commitLatch = new CountDownLatch(1);
doAnswer(new Answer<String>() {
@Override
public String answer(InvocationOnMock invocation) throws Throwable {
commitLatch.countDown();
return null;
}
}).when(firstChannel).txCommit();
final CountDownLatch latch = new CountDownLatch(1);
final AtomicReference<Channel> exposed = new AtomicReference<Channel>();
SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(singleConnectionFactory);
container.setMessageListener(new ChannelAwareMessageListener() {
public void onMessage(Message message, Channel channel) {
exposed.set(channel);
RabbitTemplate rabbitTemplate = new RabbitTemplate(singleConnectionFactory);
rabbitTemplate.setChannelTransacted(true);
rabbitTemplate.convertAndSend("foo", "bar", "baz");
latch.countDown();
}
});
container.setQueueNames("queue");
container.setChannelTransacted(true);
container.setExposeListenerChannel(false);
container.setShutdownTimeout(100);
container.afterPropertiesSet();
container.start();
consumer.get().handleDelivery("qux", new Envelope(1, false, "foo", "bar"), new BasicProperties(), new byte[] {0});
assertTrue(latch.await(10, TimeUnit.SECONDS));
Exception e = tooManyChannels.get();
if (e != null) {
throw e;
}
verify(mockConnection, Mockito.times(2)).createChannel();
assertTrue(commitLatch.await(10, TimeUnit.SECONDS));
verify(firstChannel).txCommit();
verify(secondChannel).txCommit();
verify(secondChannel).basicPublish(Mockito.anyString(), Mockito.anyString(), Mockito.anyBoolean(),
Mockito.anyBoolean(), Mockito.any(BasicProperties.class), Mockito.any(byte[].class));
assertSame(secondChannel, exposed.get());
verify(firstChannel, Mockito.never()).close();
verify(secondChannel, Mockito.times(1)).close();
container.stop();
}
|
protected void sortArray(DataSourceRecord<E>[] array, final String columnName, final boolean ascending, final boolean caseSensitive)
{
if (!definitions.getColumn(columnName).isSortable())
{
throw new DataSourceExcpetion(messages.dataSourceErrorColumnNotComparable(columnName));
}
final boolean isStringColumn = getValue(columnName, array[0]) instanceof String;
Arrays.sort(array, new Comparator<DataSourceRecord<E>>(){
public int compare(DataSourceRecord<E> o1, DataSourceRecord<E> o2)
{
if (ascending)
{
if (o1==null) return (o2==null?0:-1);
if (o2==null) return 1;
}
else
{
if (o1==null) return (o2==null?0:1);
if (o2==null) return -1;
}
Object value1 = getValue(columnName, o1);
Object value2 = getValue(columnName, o2);
if (ascending)
{
if (value1==null) return (value2==null?0:-1);
if (value2==null) return 1;
}
else
{
if (value1==null) return (value2==null?0:1);
if (value2==null) return -1;
}
return compareNonNullValuesByType(value1,value2,ascending,caseSensitive, isStringColumn);
}
@SuppressWarnings({ "rawtypes", "unchecked" })
private int compareNonNullValuesByType(Object value1, Object value2, boolean ascending, boolean caseSensitive, boolean isStringColumns)
{
if(isStringColumns)
{
if (ascending)
{
return StringUtils.localeCompare((String)value1, (String)value2, caseSensitive);
} else
{
return StringUtils.localeCompare((String)value2, (String)value1, caseSensitive);
}
}
if (ascending)
{
return ((Comparable)value1).compareTo(value2);
}
else
{
return ((Comparable)value2).compareTo(value1);
}
}
});
firstRecord();
}
| protected void sortArray(DataSourceRecord<E>[] array, final String columnName, final boolean ascending, final boolean caseSensitive)
{
if (!definitions.getColumn(columnName).isSortable())
{
throw new DataSourceExcpetion(messages.dataSourceErrorColumnNotComparable(columnName));
}
if(array == null || array[0] == null)
{
return;
}
final boolean isStringColumn = getValue(columnName, array[0]) instanceof String;
Arrays.sort(array, new Comparator<DataSourceRecord<E>>(){
public int compare(DataSourceRecord<E> o1, DataSourceRecord<E> o2)
{
if (ascending)
{
if (o1==null) return (o2==null?0:-1);
if (o2==null) return 1;
}
else
{
if (o1==null) return (o2==null?0:1);
if (o2==null) return -1;
}
Object value1 = getValue(columnName, o1);
Object value2 = getValue(columnName, o2);
if (ascending)
{
if (value1==null) return (value2==null?0:-1);
if (value2==null) return 1;
}
else
{
if (value1==null) return (value2==null?0:1);
if (value2==null) return -1;
}
return compareNonNullValuesByType(value1,value2,ascending,caseSensitive, isStringColumn);
}
@SuppressWarnings({ "rawtypes", "unchecked" })
private int compareNonNullValuesByType(Object value1, Object value2, boolean ascending, boolean caseSensitive, boolean isStringColumns)
{
if(isStringColumns)
{
if (ascending)
{
return StringUtils.localeCompare((String)value1, (String)value2, caseSensitive);
} else
{
return StringUtils.localeCompare((String)value2, (String)value1, caseSensitive);
}
}
if (ascending)
{
return ((Comparable)value1).compareTo(value2);
}
else
{
return ((Comparable)value2).compareTo(value1);
}
}
});
firstRecord();
}
|
FSImageStorageInspector readAndInspectDirs()
throws IOException {
Integer layoutVersion = null;
boolean multipleLV = false;
StringBuilder layoutVersions = new StringBuilder();
for (Iterator<StorageDirectory> it = dirIterator();
it.hasNext();) {
StorageDirectory sd = it.next();
if (!sd.getVersionFile().exists()) {
FSImage.LOG.warn("Storage directory " + sd + " contains no VERSION file. Skipping...");
continue;
}
readProperties(sd);
int lv = getLayoutVersion();
if (layoutVersion == null) {
layoutVersion = Integer.valueOf(lv);
} else if (!layoutVersion.equals(lv)) {
multipleLV = true;
}
layoutVersions.append("(").append(sd.getRoot()).append(", ").append(lv).append(") ");
}
if (layoutVersion == null) {
throw new IOException("No storage directories contained VERSION information");
}
if (multipleLV) {
throw new IOException(
"Storage directories containe multiple layout versions: "
+ layoutVersions);
}
FSImageStorageInspector inspector;
if (LayoutVersion.supports(Feature.TXID_BASED_LAYOUT, getLayoutVersion())) {
inspector = new FSImageTransactionalStorageInspector();
} else {
inspector = new FSImagePreTransactionalStorageInspector();
}
inspectStorageDirs(inspector);
return inspector;
}
| FSImageStorageInspector readAndInspectDirs()
throws IOException {
Integer layoutVersion = null;
boolean multipleLV = false;
StringBuilder layoutVersions = new StringBuilder();
for (Iterator<StorageDirectory> it = dirIterator();
it.hasNext();) {
StorageDirectory sd = it.next();
if (!sd.getVersionFile().exists()) {
FSImage.LOG.warn("Storage directory " + sd + " contains no VERSION file. Skipping...");
continue;
}
readProperties(sd);
int lv = getLayoutVersion();
if (layoutVersion == null) {
layoutVersion = Integer.valueOf(lv);
} else if (!layoutVersion.equals(lv)) {
multipleLV = true;
}
layoutVersions.append("(").append(sd.getRoot()).append(", ").append(lv).append(") ");
}
if (layoutVersion == null) {
throw new IOException("No storage directories contained VERSION information");
}
if (multipleLV) {
throw new IOException(
"Storage directories contain multiple layout versions: "
+ layoutVersions);
}
FSImageStorageInspector inspector;
if (LayoutVersion.supports(Feature.TXID_BASED_LAYOUT, getLayoutVersion())) {
inspector = new FSImageTransactionalStorageInspector();
} else {
inspector = new FSImagePreTransactionalStorageInspector();
}
inspectStorageDirs(inspector);
return inspector;
}
|
public void testWorkspaces() throws Exception {
Collection workspaces = gwtRegistry.getWorkspaces();
assertEquals(1, workspaces.size());
Collection artifactTypes = gwtRegistry.getArtifactTypes();
assertEquals(5, artifactTypes.size());
}
| public void testWorkspaces() throws Exception {
Collection workspaces = gwtRegistry.getWorkspaces();
assertEquals(1, workspaces.size());
Collection artifactTypes = gwtRegistry.getArtifactTypes();
assertTrue(artifactTypes.size() > 0);
}
|
protected Result doRun(final BuildListener listener) throws Exception {
PrintStream logger = listener.getLogger();
Result r = null;
try {
EnvVars envVars = getEnvironment(listener);
MavenInstallation mvn = project.getMaven();
if(mvn==null)
throw new AbortException("A Maven installation needs to be available for this project to be built.\n"+
"Either your server has no Maven installations defined, or the requested Maven version does not exist.");
mvn = mvn.forEnvironment(envVars).forNode(Computer.currentComputer().getNode(), listener);
if(!project.isAggregatorStyleBuild()) {
parsePoms(listener, logger, envVars, mvn);
logger.println("Triggering "+project.getRootModule().getModuleName());
project.getRootModule().scheduleBuild(new UpstreamCause((Run<?,?>)MavenModuleSetBuild.this));
} else {
try {
List<BuildWrapper> wrappers = new ArrayList<BuildWrapper>();
for (BuildWrapper w : project.getBuildWrappersList())
wrappers.add(w);
ParametersAction parameters = getAction(ParametersAction.class);
if (parameters != null)
parameters.createBuildWrappers(MavenModuleSetBuild.this,wrappers);
for( BuildWrapper w : wrappers) {
Environment e = w.setUp(MavenModuleSetBuild.this, launcher, listener);
if(e==null)
return (r = Result.FAILURE);
buildEnvironments.add(e);
e.buildEnvVars(envVars);
}
if(!preBuild(listener, project.getPublishers()))
return Result.FAILURE;
parsePoms(listener, logger, envVars, mvn);
SplittableBuildListener slistener = new SplittableBuildListener(listener);
proxies = new HashMap<ModuleName, ProxyImpl2>();
List<String> changedModules = new ArrayList<String>();
for (MavenModule m : project.sortedActiveModules) {
MavenBuild mb = m.newBuild();
if (!MavenModuleSetBuild.this.getChangeSet().isEmptySet()
&& project.isIncrementalBuild()) {
if ((mb.getPreviousBuiltBuild() == null) ||
(!getChangeSetFor(m).isEmpty())
|| (mb.getPreviousBuiltBuild().getResult().isWorseThan(Result.SUCCESS))) {
changedModules.add(m.getModuleName().toString());
}
}
mb.setWorkspace(getModuleRoot().child(m.getRelativePath()));
proxies.put(m.getModuleName(), mb.new ProxyImpl2(MavenModuleSetBuild.this,slistener));
}
String rootPOM = project.getRootPOM();
FilePath pom = getModuleRoot().child(rootPOM);
FilePath parentLoc = getWorkspace().child(rootPOM);
if(!pom.exists() && parentLoc.exists())
pom = parentLoc;
ProcessCache.MavenProcess process = MavenBuild.mavenProcessCache.get(launcher.getChannel(), slistener,
new MavenProcessFactory(project,launcher,envVars,pom.getParent()));
ArgumentListBuilder margs = new ArgumentListBuilder().add("-B").add("-f", pom.getRemote());
if(project.usesPrivateRepository())
margs.add("-Dmaven.repo.local="+getWorkspace().child(".repository"));
if (project.isIncrementalBuild() && mvn.isMaven2_1(launcher) && !changedModules.isEmpty()) {
margs.add("-amd");
margs.add("-pl", Util.join(changedModules, ","));
}
if (project.getAlternateSettings() != null) {
if (IOUtils.isAbsolute(project.getAlternateSettings())) {
margs.add("-s").add(project.getAlternateSettings());
} else {
FilePath mrSettings = getModuleRoot().child(project.getAlternateSettings());
FilePath wsSettings = getWorkspace().child(project.getAlternateSettings());
if (!wsSettings.exists() && mrSettings.exists())
wsSettings = mrSettings;
margs.add("-s").add(wsSettings.getRemote());
}
}
margs.addTokenized(envVars.expand(project.getGoals()));
Builder builder = new Builder(slistener, proxies, project.sortedActiveModules, margs.toList(), envVars);
MavenProbeAction mpa=null;
try {
mpa = new MavenProbeAction(project,process.channel);
addAction(mpa);
r = process.call(builder);
return r;
} finally {
builder.end(launcher);
getActions().remove(mpa);
process.discard();
}
} finally {
if (r != null) {
setResult(r);
}
boolean failed=false;
for( int i=buildEnvironments.size()-1; i>=0; i-- ) {
if (!buildEnvironments.get(i).tearDown(MavenModuleSetBuild.this,listener)) {
failed=true;
}
}
if (failed) return Result.FAILURE;
}
}
return r;
} catch (AbortException e) {
if(e.getMessage()!=null)
listener.error(e.getMessage());
return Result.FAILURE;
} catch (InterruptedIOException e) {
e.printStackTrace(listener.error("Aborted Maven execution for InterruptedIOException"));
return Result.ABORTED;
} catch (IOException e) {
e.printStackTrace(listener.error(Messages.MavenModuleSetBuild_FailedToParsePom()));
return Result.FAILURE;
} catch (RunnerAbortedException e) {
return Result.FAILURE;
} catch (RuntimeException e) {
e.printStackTrace(listener.error("Processing failed due to a bug in the code. Please report this to users@hudson.dev.java.net"));
logger.println("project="+project);
logger.println("project.getModules()="+project.getModules());
logger.println("project.getRootModule()="+project.getRootModule());
throw e;
}
}
| protected Result doRun(final BuildListener listener) throws Exception {
PrintStream logger = listener.getLogger();
Result r = null;
try {
EnvVars envVars = getEnvironment(listener);
MavenInstallation mvn = project.getMaven();
if(mvn==null)
throw new AbortException("A Maven installation needs to be available for this project to be built.\n"+
"Either your server has no Maven installations defined, or the requested Maven version does not exist.");
mvn = mvn.forEnvironment(envVars).forNode(Computer.currentComputer().getNode(), listener);
if(!project.isAggregatorStyleBuild()) {
parsePoms(listener, logger, envVars, mvn);
logger.println("Triggering "+project.getRootModule().getModuleName());
project.getRootModule().scheduleBuild(new UpstreamCause((Run<?,?>)MavenModuleSetBuild.this));
} else {
try {
List<BuildWrapper> wrappers = new ArrayList<BuildWrapper>();
for (BuildWrapper w : project.getBuildWrappersList())
wrappers.add(w);
ParametersAction parameters = getAction(ParametersAction.class);
if (parameters != null)
parameters.createBuildWrappers(MavenModuleSetBuild.this,wrappers);
for( BuildWrapper w : wrappers) {
Environment e = w.setUp(MavenModuleSetBuild.this, launcher, listener);
if(e==null)
return (r = Result.FAILURE);
buildEnvironments.add(e);
e.buildEnvVars(envVars);
}
if(!preBuild(listener, project.getPublishers()))
return Result.FAILURE;
parsePoms(listener, logger, envVars, mvn);
SplittableBuildListener slistener = new SplittableBuildListener(listener);
proxies = new HashMap<ModuleName, ProxyImpl2>();
List<String> changedModules = new ArrayList<String>();
for (MavenModule m : project.sortedActiveModules) {
MavenBuild mb = m.newBuild();
if (!MavenModuleSetBuild.this.getChangeSet().isEmptySet()
&& project.isIncrementalBuild()) {
if ((mb.getPreviousBuiltBuild() == null) ||
(!getChangeSetFor(m).isEmpty())
|| (mb.getPreviousBuiltBuild().getResult().isWorseThan(Result.SUCCESS))) {
changedModules.add(m.getModuleName().toString());
}
}
mb.setWorkspace(getModuleRoot().child(m.getRelativePath()));
proxies.put(m.getModuleName(), mb.new ProxyImpl2(MavenModuleSetBuild.this,slistener));
}
String rootPOM = project.getRootPOM();
FilePath pom = getModuleRoot().child(rootPOM);
FilePath parentLoc = getWorkspace().child(rootPOM);
if(!pom.exists() && parentLoc.exists())
pom = parentLoc;
ProcessCache.MavenProcess process = MavenBuild.mavenProcessCache.get(launcher.getChannel(), slistener,
new MavenProcessFactory(project,launcher,envVars,pom.getParent()));
ArgumentListBuilder margs = new ArgumentListBuilder().add("-B").add("-f", pom.getRemote());
if(project.usesPrivateRepository())
margs.add("-Dmaven.repo.local="+getWorkspace().child(".repository"));
if (project.isIncrementalBuild() && mvn.isMaven2_1(launcher) && !changedModules.isEmpty()) {
margs.add("-amd");
margs.add("-pl", Util.join(changedModules, ","));
}
if (project.getAlternateSettings() != null) {
if (IOUtils.isAbsolute(project.getAlternateSettings())) {
margs.add("-s").add(project.getAlternateSettings());
} else {
FilePath mrSettings = getModuleRoot().child(project.getAlternateSettings());
FilePath wsSettings = getWorkspace().child(project.getAlternateSettings());
if (!wsSettings.exists() && mrSettings.exists())
wsSettings = mrSettings;
margs.add("-s").add(wsSettings.getRemote());
}
}
margs.addTokenized(envVars.expand(project.getGoals()));
Builder builder = new Builder(slistener, proxies, project.sortedActiveModules, margs.toList(), envVars);
MavenProbeAction mpa=null;
try {
mpa = new MavenProbeAction(project,process.channel);
addAction(mpa);
r = process.call(builder);
return r;
} finally {
builder.end(launcher);
getActions().remove(mpa);
process.discard();
}
} finally {
if (r != null) {
setResult(r);
}
boolean failed=false;
for( int i=buildEnvironments.size()-1; i>=0; i-- ) {
if (!buildEnvironments.get(i).tearDown(MavenModuleSetBuild.this,listener)) {
failed=true;
}
}
if (failed) return Result.FAILURE;
}
}
return r;
} catch (AbortException e) {
if(e.getMessage()!=null)
listener.error(e.getMessage());
return Result.FAILURE;
} catch (InterruptedIOException e) {
e.printStackTrace(listener.error("Aborted Maven execution for InterruptedIOException"));
return Result.ABORTED;
} catch (IOException e) {
e.printStackTrace(listener.error(Messages.MavenModuleSetBuild_FailedToParsePom()));
return Result.FAILURE;
} catch (RunnerAbortedException e) {
return Result.FAILURE;
} catch (RuntimeException e) {
e.printStackTrace(listener.error("Processing failed due to a bug in the code. Please report this to hudson-users@googlegroups.com"));
logger.println("project="+project);
logger.println("project.getModules()="+project.getModules());
logger.println("project.getRootModule()="+project.getRootModule());
throw e;
}
}
|
public void execute( JobExecutionContext context )
throws JobExecutionException
{
logger.info(
" --- Testing Scheduler Component\n --- " + context.getJobDetail().getDescription() + " executed.["
+ new Date() + "]" );
}
| public void execute( JobExecutionContext context )
throws JobExecutionException
{
logger.info(
" --- Testing Scheduler Component --- {} executed.[{}]", context.getJobDetail().getDescription(), new Date() );
}
|
public SpreadSheet(int sWidth, int sHeight, int cols, int rows,
String server, String clone, String sTitle, FormulaManager fm,
boolean chooseOptions)
{
super(true);
bTitle = sTitle;
NumVisX = cols;
NumVisY = rows;
this.fm = fm;
Possible3D = BasicSSCell.possible3D();
CanDo3D = BasicSSCell.canDo3D();
MappingDialog.initDialog();
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
quitProgram();
}
});
setBackground(Color.white);
boolean slave = clone != null && clone.startsWith("slave:");
if (slave) clone = clone.substring(6);
if (clone != null) {
int slash = clone.lastIndexOf("/");
if (slash < 0) slash = clone.lastIndexOf(":");
server = clone.substring(slash + 1);
clone = clone.substring(0, slash);
}
serverName = server;
cloneAddress = clone;
IsSlave = slave;
CanDoHDF5 = false;
if (!CanDoHDF5 && BasicSSCell.DEBUG) {
System.err.println("Warning: HDF-5 library not found");
}
CanDoJPEG = Util.canDoJPEG();
if (!CanDoJPEG && BasicSSCell.DEBUG) {
System.err.println("Warning: JPEG codec not found");
}
CanDoPython = Util.canDoPython();
if (!CanDoPython && BasicSSCell.DEBUG) {
System.err.println("Warning: JPython not found");
}
SSFileDialog = new JFileChooser(System.getProperty("user.dir"));
SSFileDialog.addChoosableFileFilter(
new ExtensionFileFilter("ss", "SpreadSheet files"));
if (chooseOptions) {
getOptions(NumVisX, NumVisY, serverName, cloneAddress, IsSlave);
}
clone = cloneAddress == null ? null : cloneAddress + "/" + serverName;
server = cloneAddress == null ? serverName : null;
RemoteServer rs = null;
String[][] cellNames = null;
if (clone != null) {
boolean success = true;
if (SHOW_CONNECT_MESSAGES) {
System.out.print("Connecting to " + clone + " ");
}
while (cellNames == null && success) {
snooze(1000);
if (SHOW_CONNECT_MESSAGES) System.out.print(".");
try {
rs = (RemoteServer) Naming.lookup("//" + clone);
RemoteCanDo3D = rs.getDataReference("CanDo3D");
Real bit = (Real) RemoteCanDo3D.getData();
if (bit.getValue() == 0) {
CanDo3D = false;
BasicSSCell.disable3D();
}
RemoteColRow = rs.getDataReference("ColRow");
cellNames = getNewCellNames();
}
catch (UnmarshalException exc) {
if (BasicSSCell.DEBUG) exc.printStackTrace();
displayErrorMessage("Unable to clone the spreadsheet at " + clone +
". The server is using an incompatible version of Java", null,
"Failed to clone spreadsheet");
success = false;
}
catch (MalformedURLException exc) {
if (BasicSSCell.DEBUG) exc.printStackTrace();
displayErrorMessage("Unable to clone the spreadsheet at " + clone +
". The server name is not valid", null,
"Failed to clone spreadsheet");
success = false;
}
catch (VisADException exc) {
if (BasicSSCell.DEBUG) exc.printStackTrace();
displayErrorMessage("Unable to clone the spreadsheet at " + clone +
". An error occurred while downloading the necessary data", exc,
"Failed to clone spreadsheet");
success = false;
}
catch (NotBoundException exc) {
if (BasicSSCell.DEBUG) exc.printStackTrace();
}
catch (NullPointerException exc) {
if (BasicSSCell.DEBUG) exc.printStackTrace();
}
catch (RemoteException exc) {
if (BasicSSCell.DEBUG) exc.printStackTrace();
}
}
if (success) {
if (SHOW_CONNECT_MESSAGES) System.out.println(" done");
bTitle = bTitle + " [" + (IsSlave ? "slaved" : "collaborative") +
" mode: " + clone + "]";
IsRemote = true;
}
else {
if (SHOW_CONNECT_MESSAGES) System.out.println(" failed");
IsSlave = false;
rs = null;
}
}
JPanel pane = new JPanel();
pane.setBackground(Color.white);
pane.setLayout(new BoxLayout(pane, BoxLayout.Y_AXIS));
setContentPane(pane);
addMenuItem("File", "Import data...", "loadDataSet", 'i');
FileSave1 = addMenuItem("File", "Export data to netCDF...",
"exportDataSetNetcdf", 'n', false);
FileSave2 = addMenuItem("File", "Export serialized data...",
"exportDataSetSerial", 's', false);
FileSave3 = addMenuItem("File", "Export data to HDF-5...",
"exportDataSetHDF5", 'h', false);
addMenuSeparator("File");
FileSnap = addMenuItem("File", "Take JPEG snapshot...",
"captureImageJPEG", 'j', false);
addMenuSeparator("File");
addMenuItem("File", "Exit", "quitProgram", 'x');
addMenuItem("Edit", "Cut", "cutCell", 't', !IsRemote);
addMenuItem("Edit", "Copy", "copyCell", 'c', !IsRemote);
EditPaste = addMenuItem("Edit", "Paste", "pasteCell", 'p', false);
EditClear = addMenuItem("Edit", "Clear", "clearCell", 'l', false);
addMenuItem("Setup", "New spreadsheet file", "newFile", 'n');
addMenuItem("Setup", "Open spreadsheet file...", "openFile", 'o',
!IsRemote);
addMenuItem("Setup", "Save spreadsheet file", "saveFile", 's', !IsRemote);
addMenuItem("Setup", "Save spreadsheet file as...", "saveAsFile", 'a',
!IsRemote);
CellDim3D3D = new JCheckBoxMenuItem("3-D (Java3D)", CanDo3D);
addMenuItem("Cell", CellDim3D3D, "setDim3D", '3', CanDo3D);
CellDim2D2D = new JCheckBoxMenuItem("2-D (Java2D)", !CanDo3D);
addMenuItem("Cell", CellDim2D2D, "setDimJ2D", 'j', true);
CellDim2D3D = new JCheckBoxMenuItem("2-D (Java3D)", false);
addMenuItem("Cell", CellDim2D3D, "setDim2D", '2', CanDo3D);
addMenuSeparator("Cell");
addMenuItem("Cell", "Add data object", "formulaAdd", 'a');
CellDel = addMenuItem("Cell", "Delete data object",
"formulaDel", 'd', false);
addMenuSeparator("Cell");
CellPrint = addMenuItem("Cell", "Print cell...",
"printCurrentCell", 'p', false);
addMenuSeparator("Cell");
CellEdit = addMenuItem("Cell", "Edit mappings...",
"createMappings", 'e', false);
CellReset = addMenuItem("Cell", "Reset orientation",
"resetOrientation", 'r', false);
CellShow = addMenuItem("Cell", "Show controls",
"showControls", 's', false);
LayAddCol = addMenuItem("Layout", "Add column", "addColumn", 'c');
addMenuItem("Layout", "Add row", "addRow", 'r');
LayDelCol = addMenuItem("Layout", "Delete column",
"deleteColumn", 'l', NumVisX > 1);
LayDelRow = addMenuItem("Layout", "Delete row",
"deleteRow", 'w', NumVisY > 1);
addMenuSeparator("Layout");
addMenuItem("Layout", "Tile cells", "tileCells", 't');
if (!CanDo3D) AutoSwitch = false;
AutoSwitchBox = new JCheckBoxMenuItem("Auto-switch to 3-D",
AutoSwitch && !IsRemote);
addMenuItem("Options", AutoSwitchBox,
"optionsSwitch", '3', CanDo3D && !IsRemote);
AutoDetectBox = new JCheckBoxMenuItem("Auto-detect mappings",
AutoDetect && !IsRemote);
addMenuItem("Options", AutoDetectBox, "optionsDetect", 'm', !IsRemote);
AutoShowBox = new JCheckBoxMenuItem("Auto-display controls",
AutoShowControls && !IsSlave);
addMenuItem("Options", AutoShowBox, "optionsDisplay", 'c', !IsSlave);
if (!BugFix) {
Toolbar = new JToolBar();
Toolbar.setBackground(Color.lightGray);
Toolbar.setBorder(new EtchedBorder());
Toolbar.setFloatable(false);
pane.add(Toolbar);
addToolbarButton("open", "Import data", "loadDataSet", true, Toolbar);
ToolSave = addToolbarButton("save", "Export data to netCDF",
"exportDataSetNetcdf", false, Toolbar);
Toolbar.addSeparator();
addToolbarButton("cut", "Cut", "cutCell", !IsRemote, Toolbar);
addToolbarButton("copy", "Copy", "copyCell", !IsRemote, Toolbar);
ToolPaste = addToolbarButton("paste", "Paste",
"pasteCell", false, Toolbar);
Toolbar.addSeparator();
Tool3D = addToolbarButton("3d", "3-D (Java3D)",
"setDim3D", false, Toolbar);
ToolJ2D = addToolbarButton("j2d", "2-D (Java2D)",
"setDimJ2D", CanDo3D, Toolbar);
Tool2D = addToolbarButton("2d", "2-D (Java3D)",
"setDim2D", CanDo3D, Toolbar);
Toolbar.addSeparator();
ToolMap = addToolbarButton("mappings", "Edit mappings",
"createMappings", false, Toolbar);
ToolReset = addToolbarButton("reset", "Reset orientation",
"resetOrientation", false, Toolbar);
ToolShow = addToolbarButton("show", "Show controls",
"showControls", false, Toolbar);
Toolbar.addSeparator();
addToolbarButton("tile", "Tile cells", "tileCells", true, Toolbar);
Toolbar.add(Box.createHorizontalGlue());
}
JPanel formulaPanel = new JPanel();
formulaPanel.setPreferredSize(new Dimension(Integer.MAX_VALUE, 25));
formulaPanel.setBackground(Color.lightGray);
formulaPanel.setLayout(new BoxLayout(formulaPanel, BoxLayout.X_AXIS));
formulaPanel.setBorder(new EtchedBorder());
pane.add(formulaPanel);
pane.add(Box.createRigidArea(new Dimension(0, 6)));
if (!BugFix) {
FormulaAdd = addToolbarButton("add", "Add data",
"formulaAdd", true, formulaPanel);
FormulaDel = addToolbarButton("del", "Remove data",
"formulaDel", true, formulaPanel);
}
FormulaBox = new JComboBox();
formulaPanel.add(FormulaBox);
FormulaBox.setLightWeightPopupEnabled(false);
FormulaBox.setEditable(true);
FormulaEditor = FormulaBox.getEditor();
FormulaEditor.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String newItem = (String) FormulaEditor.getItem();
try {
int id = 0;
int type = BasicSSCell.UNKNOWN_SOURCE;
boolean notify = true;
int index1 = newItem.indexOf("d");
int index2 = newItem.indexOf(":");
if (index1 > 0 && index2 > 0 && index1 < index2) {
String cellName = newItem.substring(0, index1);
BasicSSCell ssCell = BasicSSCell.getSSCellByName(cellName);
int dataId = 0;
try {
dataId = Integer.parseInt(newItem.substring(index1 + 1, index2));
}
catch (NumberFormatException exc) {
if (BasicSSCell.DEBUG && BasicSSCell.DEBUG_LEVEL >= 3) {
exc.printStackTrace();
}
}
if (ssCell == DisplayCells[CurX][CurY] && dataId > 0) {
String varName = newItem.substring(0, index2);
String source = ssCell.getDataSource(varName);
if (source != null) {
ssCell.removeData(varName);
String oldItem = null;
for (int i=0; i<FormulaBox.getItemCount(); i++) {
String item = (String) FormulaBox.getItemAt(i);
if (item.startsWith(varName + ":")) {
oldItem = item;
break;
}
}
if (oldItem != null) {
FormulaBox.removeItem(oldItem);
}
}
id = dataId;
newItem = newItem.substring(index2 + 1).trim();
}
}
String varName = DisplayCells[CurX][CurY].addDataSource(
id, newItem, type, notify);
String itemString = varName + ": " + newItem;
FormulaBox.addItem(itemString);
FormulaBox.setSelectedItem(itemString);
if (!BugFix) FormulaAdd.requestFocus();
}
catch (VisADException exc) {
if (BasicSSCell.DEBUG) exc.printStackTrace();
}
catch (RemoteException exc) {
if (BasicSSCell.DEBUG) exc.printStackTrace();
}
}
});
JPanel horizShell = new JPanel();
horizShell.setBackground(Color.white);
horizShell.setLayout(new BoxLayout(horizShell, BoxLayout.X_AXIS));
horizShell.add(Box.createRigidArea(new Dimension(LABEL_WIDTH+6, 0)));
pane.add(horizShell);
HorizPanel = new JPanel() {
public Dimension getPreferredSize() {
Dimension d = super.getPreferredSize();
return new Dimension(d.width, LABEL_HEIGHT);
}
};
HorizPanel.setBackground(Color.white);
constructHorizontalLabels();
JViewport hl = new JViewport() {
public Dimension getMinimumSize() {
return new Dimension(0, LABEL_HEIGHT);
}
public Dimension getPreferredSize() {
return new Dimension(0, LABEL_HEIGHT);
}
public Dimension getMaximumSize() {
return new Dimension(Integer.MAX_VALUE, LABEL_HEIGHT);
}
};
HorizLabels = hl;
HorizLabels.setView(HorizPanel);
horizShell.add(HorizLabels);
horizShell.add(new JComponent() {
public Dimension getMinimumSize() {
return new Dimension(6 + SCPane.getVScrollbarWidth(), 0);
}
public Dimension getPreferredSize() {
return new Dimension(6 + SCPane.getVScrollbarWidth(), 0);
}
public Dimension getMaximumSize() {
return new Dimension(6 + SCPane.getVScrollbarWidth(), 0);
}
});
JPanel mainPanel = new JPanel();
mainPanel.setBackground(Color.white);
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.X_AXIS));
pane.add(mainPanel);
pane.add(Box.createRigidArea(new Dimension(0, 6)));
JPanel vertShell = new JPanel();
vertShell.setBackground(Color.white);
vertShell.setLayout(new BoxLayout(vertShell, BoxLayout.Y_AXIS));
mainPanel.add(Box.createRigidArea(new Dimension(6, 0)));
mainPanel.add(vertShell);
VertPanel = new JPanel() {
public Dimension getPreferredSize() {
Dimension d = super.getPreferredSize();
return new Dimension(LABEL_WIDTH, d.height);
}
};
VertPanel.setBackground(Color.white);
constructVerticalLabels();
JViewport vl = new JViewport() {
public Dimension getMinimumSize() {
return new Dimension(LABEL_WIDTH, 0);
}
public Dimension getPreferredSize() {
return new Dimension(LABEL_WIDTH, 0);
}
public Dimension getMaximumSize() {
return new Dimension(LABEL_WIDTH, Integer.MAX_VALUE);
}
};
VertLabels = vl;
VertLabels.setView(VertPanel);
vertShell.add(VertLabels);
vertShell.add(new JComponent() {
public Dimension getMinimumSize() {
return new Dimension(0, SCPane.getHScrollbarHeight());
}
public Dimension getPreferredSize() {
return new Dimension(0, SCPane.getHScrollbarHeight());
}
public Dimension getMaximumSize() {
return new Dimension(0, SCPane.getHScrollbarHeight());
}
});
ScrollPanel = new JPanel();
ScrollPanel.setBackground(Color.white);
ScrollPanel.setLayout(new BoxLayout(ScrollPanel, BoxLayout.X_AXIS));
mainPanel.add(ScrollPanel);
mainPanel.add(Box.createRigidArea(new Dimension(6, 0)));
SCPane = new ScrollPane(ScrollPane.SCROLLBARS_ALWAYS) {
public Dimension getPreferredSize() {
return new Dimension(0, 0);
}
};
Adjustable hadj = SCPane.getHAdjustable();
Adjustable vadj = SCPane.getVAdjustable();
hadj.setBlockIncrement(MIN_VIS_WIDTH);
hadj.setUnitIncrement(MIN_VIS_WIDTH/4);
hadj.addAdjustmentListener(this);
vadj.setBlockIncrement(MIN_VIS_HEIGHT);
vadj.setUnitIncrement(MIN_VIS_HEIGHT/4);
vadj.addAdjustmentListener(this);
ScrollPanel.add(SCPane);
DisplayPanel = new Panel();
DisplayPanel.setBackground(Color.darkGray);
SCPane.add(DisplayPanel);
addKeyListener(this);
SCPane.addKeyListener(this);
ScrollPanel.addKeyListener(this);
DisplayPanel.addKeyListener(this);
DataReferenceImpl lColRow = null;
if (server != null) {
boolean success = true;
boolean registryStarted = false;
while (true) {
try {
rsi = new RemoteServerImpl();
Naming.rebind("///" + server, rsi);
break;
}
catch (java.rmi.ConnectException exc) {
if (!registryStarted) {
try {
LocateRegistry.createRegistry(Registry.REGISTRY_PORT);
registryStarted = true;
}
catch (RemoteException rexc) {
if (BasicSSCell.DEBUG) exc.printStackTrace();
displayErrorMessage("Unable to autostart rmiregistry. " +
"Please start rmiregistry before launching the " +
"SpreadSheet in server mode", null,
"Failed to initialize RemoteServer");
success = false;
}
}
else {
displayErrorMessage("Unable to export cells as RMI addresses. " +
"Make sure you are running rmiregistry before launching the " +
"SpreadSheet in server mode", null,
"Failed to initialize RemoteServer");
success = false;
}
}
catch (MalformedURLException exc) {
if (BasicSSCell.DEBUG) exc.printStackTrace();
displayErrorMessage("Unable to export cells as RMI addresses. " +
"The name \"" + server + "\" is not valid", null,
"Failed to initialize RemoteServer");
success = false;
}
catch (RemoteException exc) {
if (BasicSSCell.DEBUG) exc.printStackTrace();
displayErrorMessage("Unable to export cells as RMI addresses", exc,
"Failed to initialize RemoteServer");
success = false;
}
if (!success) break;
}
try {
DataReferenceImpl lCanDo3D = new DataReferenceImpl("CanDo3D");
RemoteCanDo3D = new RemoteDataReferenceImpl(lCanDo3D);
RemoteCanDo3D.setData(new Real(CanDo3D ? 1 : 0));
rsi.addDataReference((RemoteDataReferenceImpl) RemoteCanDo3D);
lColRow = new DataReferenceImpl("ColRow");
RemoteColRow = new RemoteDataReferenceImpl(lColRow);
rsi.addDataReference((RemoteDataReferenceImpl) RemoteColRow);
}
catch (VisADException exc) {
if (BasicSSCell.DEBUG) exc.printStackTrace();
displayErrorMessage("Unable to export cells as RMI addresses. " +
"An error occurred setting up the necessary data", exc,
"Failed to initialize RemoteServer");
success = false;
}
catch (RemoteException exc) {
if (BasicSSCell.DEBUG) exc.printStackTrace();
displayErrorMessage("Unable to export cells as RMI addresses. " +
"A remote error occurred setting up the necessary data", exc,
"Failed to initialize RemoteServer");
success = false;
}
if (success) bTitle = bTitle + " (" + server + ")";
else rsi = null;
}
if (rs == null) constructSpreadsheetCells(null);
else {
NumVisX = cellNames.length;
NumVisY = cellNames[0].length;
reconstructLabels(cellNames, null, null);
constructSpreadsheetCells(cellNames, rs);
}
if (rsi != null) synchColRow();
CollabID = DisplayCells[0][0].getRemoteId();
if (rsi != null || IsRemote) {
final RemoteServer frs = rs;
CellImpl lColRowCell = new CellImpl() {
public void doAction() {
if (getColRowID() != CollabID) {
BasicSSCell.invoke(true, new Runnable() {
public void run() {
String[][] cellNamesx = getNewCellNames();
if (cellNamesx == null) {
if (BasicSSCell.DEBUG) System.out.println("Warning: " +
"could not obtain new spreadsheet dimensions!");
return;
}
int oldNVX = NumVisX;
int oldNVY = NumVisY;
NumVisX = cellNamesx.length;
NumVisY = cellNamesx[0].length;
if (NumVisX != oldNVX || NumVisY != oldNVY) {
reconstructSpreadsheet(cellNamesx, null, null, frs);
if (!IsRemote) synchColRow();
}
}
});
}
}
};
try {
RemoteCellImpl rColRowCell = new RemoteCellImpl(lColRowCell);
rColRowCell.addReference(RemoteColRow);
}
catch (VisADException exc) {
if (BasicSSCell.DEBUG) exc.printStackTrace();
}
catch (RemoteException exc) {
try {
lColRowCell.addReference(lColRow);
}
catch (VisADException exc2) {
if (BasicSSCell.DEBUG) exc2.printStackTrace();
}
catch (RemoteException exc2) {
if (BasicSSCell.DEBUG) exc2.printStackTrace();
}
}
}
setTitle(bTitle);
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
int appWidth = (int) (0.01 * sWidth * screenSize.width);
int appHeight = (int) (0.01 * sHeight * screenSize.height);
setSize(appWidth, appHeight);
Util.centerWindow(this);
setVisible(true);
snooze(500);
if (!BugFix) FormulaAdd.requestFocus();
tileCells();
}
| public SpreadSheet(int sWidth, int sHeight, int cols, int rows,
String server, String clone, String sTitle, FormulaManager fm,
boolean chooseOptions)
{
super(true);
bTitle = sTitle;
NumVisX = cols;
NumVisY = rows;
this.fm = fm;
Possible3D = BasicSSCell.possible3D();
CanDo3D = BasicSSCell.canDo3D();
MappingDialog.initDialog();
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
quitProgram();
}
});
setBackground(Color.white);
boolean slave = clone != null && clone.startsWith("slave:");
if (slave) clone = clone.substring(6);
if (clone != null) {
int slash = clone.lastIndexOf("/");
if (slash < 0) slash = clone.lastIndexOf(":");
server = clone.substring(slash + 1);
clone = clone.substring(0, slash);
}
serverName = server;
cloneAddress = clone;
IsSlave = slave;
CanDoHDF5 = false;
if (!CanDoHDF5 && BasicSSCell.DEBUG) {
System.err.println("Warning: HDF-5 library not found");
}
CanDoJPEG = Util.canDoJPEG();
if (!CanDoJPEG && BasicSSCell.DEBUG) {
System.err.println("Warning: JPEG codec not found");
}
CanDoPython = Util.canDoPython();
if (!CanDoPython && BasicSSCell.DEBUG) {
System.err.println("Warning: JPython not found");
}
SSFileDialog = new JFileChooser(System.getProperty("user.dir"));
SSFileDialog.addChoosableFileFilter(
new ExtensionFileFilter("ss", "SpreadSheet files"));
if (chooseOptions) {
getOptions(NumVisX, NumVisY, serverName, cloneAddress, IsSlave);
}
clone = cloneAddress == null ? null : cloneAddress + "/" + serverName;
server = cloneAddress == null ? serverName : null;
RemoteServer rs = null;
String[][] cellNames = null;
if (clone != null) {
boolean success = true;
if (SHOW_CONNECT_MESSAGES) {
System.out.print("Connecting to " + clone + " ");
}
while (cellNames == null && success) {
snooze(1000);
if (SHOW_CONNECT_MESSAGES) System.out.print(".");
try {
rs = (RemoteServer) Naming.lookup("//" + clone);
RemoteCanDo3D = rs.getDataReference("CanDo3D");
Real bit = (Real) RemoteCanDo3D.getData();
if (bit.getValue() == 0) {
CanDo3D = false;
BasicSSCell.disable3D();
}
RemoteColRow = rs.getDataReference("ColRow");
cellNames = getNewCellNames();
}
catch (UnmarshalException exc) {
if (BasicSSCell.DEBUG) exc.printStackTrace();
displayErrorMessage("Unable to clone the spreadsheet at " + clone +
". The server is using an incompatible version of Java", null,
"Failed to clone spreadsheet");
success = false;
}
catch (MalformedURLException exc) {
if (BasicSSCell.DEBUG) exc.printStackTrace();
displayErrorMessage("Unable to clone the spreadsheet at " + clone +
". The server name is not valid", null,
"Failed to clone spreadsheet");
success = false;
}
catch (VisADException exc) {
if (BasicSSCell.DEBUG) exc.printStackTrace();
displayErrorMessage("Unable to clone the spreadsheet at " + clone +
". An error occurred while downloading the necessary data", exc,
"Failed to clone spreadsheet");
success = false;
}
catch (NotBoundException exc) {
if (BasicSSCell.DEBUG) exc.printStackTrace();
}
catch (NullPointerException exc) {
if (BasicSSCell.DEBUG) exc.printStackTrace();
}
catch (RemoteException exc) {
if (BasicSSCell.DEBUG) exc.printStackTrace();
}
}
if (success) {
if (SHOW_CONNECT_MESSAGES) System.out.println(" done");
bTitle = bTitle + " [" + (IsSlave ? "slaved" : "collaborative") +
" mode: " + clone + "]";
IsRemote = true;
}
else {
if (SHOW_CONNECT_MESSAGES) System.out.println(" failed");
IsSlave = false;
rs = null;
}
}
JPanel pane = new JPanel();
pane.setBackground(Color.white);
pane.setLayout(new BoxLayout(pane, BoxLayout.Y_AXIS));
setContentPane(pane);
addMenuItem("File", "Import data...", "loadDataSet", 'i');
FileSave1 = addMenuItem("File", "Export data to netCDF...",
"exportDataSetNetcdf", 'n', false);
FileSave2 = addMenuItem("File", "Export serialized data...",
"exportDataSetSerial", 's', false);
FileSave3 = addMenuItem("File", "Export data to HDF-5...",
"exportDataSetHDF5", 'h', false);
addMenuSeparator("File");
FileSnap = addMenuItem("File", "Take JPEG snapshot...",
"captureImageJPEG", 'j', false);
addMenuSeparator("File");
addMenuItem("File", "Exit", "quitProgram", 'x');
addMenuItem("Edit", "Cut", "cutCell", 't', !IsRemote);
addMenuItem("Edit", "Copy", "copyCell", 'c', !IsRemote);
EditPaste = addMenuItem("Edit", "Paste", "pasteCell", 'p', false);
EditClear = addMenuItem("Edit", "Clear", "clearCell", 'l', false);
addMenuItem("Setup", "New spreadsheet file", "newFile", 'n');
addMenuItem("Setup", "Open spreadsheet file...", "openFile", 'o',
!IsRemote);
addMenuItem("Setup", "Save spreadsheet file", "saveFile", 's', !IsRemote);
addMenuItem("Setup", "Save spreadsheet file as...", "saveAsFile", 'a',
!IsRemote);
CellDim3D3D = new JCheckBoxMenuItem("3-D (Java3D)", CanDo3D);
addMenuItem("Cell", CellDim3D3D, "setDim3D", '3', CanDo3D);
CellDim2D2D = new JCheckBoxMenuItem("2-D (Java2D)", !CanDo3D);
addMenuItem("Cell", CellDim2D2D, "setDimJ2D", 'j', true);
CellDim2D3D = new JCheckBoxMenuItem("2-D (Java3D)", false);
addMenuItem("Cell", CellDim2D3D, "setDim2D", '2', CanDo3D);
addMenuSeparator("Cell");
addMenuItem("Cell", "Add data object", "formulaAdd", 'a');
CellDel = addMenuItem("Cell", "Delete data object",
"formulaDel", 'd', false);
addMenuSeparator("Cell");
CellPrint = addMenuItem("Cell", "Print cell...",
"printCurrentCell", 'p', false);
addMenuSeparator("Cell");
CellEdit = addMenuItem("Cell", "Edit mappings...",
"createMappings", 'e', false);
CellReset = addMenuItem("Cell", "Reset orientation",
"resetOrientation", 'r', false);
CellShow = addMenuItem("Cell", "Show controls",
"showControls", 's', false);
LayAddCol = addMenuItem("Layout", "Add column", "addColumn", 'c');
addMenuItem("Layout", "Add row", "addRow", 'r');
LayDelCol = addMenuItem("Layout", "Delete column",
"deleteColumn", 'l', NumVisX > 1);
LayDelRow = addMenuItem("Layout", "Delete row",
"deleteRow", 'w', NumVisY > 1);
addMenuSeparator("Layout");
addMenuItem("Layout", "Tile cells", "tileCells", 't');
if (!CanDo3D) AutoSwitch = false;
AutoSwitchBox = new JCheckBoxMenuItem("Auto-switch to 3-D",
AutoSwitch && !IsRemote);
addMenuItem("Options", AutoSwitchBox,
"optionsSwitch", '3', CanDo3D && !IsRemote);
AutoDetectBox = new JCheckBoxMenuItem("Auto-detect mappings",
AutoDetect && !IsRemote);
addMenuItem("Options", AutoDetectBox, "optionsDetect", 'm', !IsRemote);
AutoShowBox = new JCheckBoxMenuItem("Auto-display controls",
AutoShowControls && !IsSlave);
addMenuItem("Options", AutoShowBox, "optionsDisplay", 'c', !IsSlave);
if (!BugFix) {
Toolbar = new JToolBar();
Toolbar.setBackground(Color.lightGray);
Toolbar.setBorder(new EtchedBorder());
Toolbar.setFloatable(false);
pane.add(Toolbar);
addToolbarButton("open", "Import data", "loadDataSet", true, Toolbar);
ToolSave = addToolbarButton("save", "Export data to netCDF",
"exportDataSetNetcdf", false, Toolbar);
Toolbar.addSeparator();
addToolbarButton("cut", "Cut", "cutCell", !IsRemote, Toolbar);
addToolbarButton("copy", "Copy", "copyCell", !IsRemote, Toolbar);
ToolPaste = addToolbarButton("paste", "Paste",
"pasteCell", false, Toolbar);
Toolbar.addSeparator();
Tool3D = addToolbarButton("3d", "3-D (Java3D)",
"setDim3D", false, Toolbar);
ToolJ2D = addToolbarButton("j2d", "2-D (Java2D)",
"setDimJ2D", CanDo3D, Toolbar);
Tool2D = addToolbarButton("2d", "2-D (Java3D)",
"setDim2D", CanDo3D, Toolbar);
Toolbar.addSeparator();
ToolMap = addToolbarButton("mappings", "Edit mappings",
"createMappings", false, Toolbar);
ToolReset = addToolbarButton("reset", "Reset orientation",
"resetOrientation", false, Toolbar);
ToolShow = addToolbarButton("show", "Show controls",
"showControls", false, Toolbar);
Toolbar.addSeparator();
addToolbarButton("tile", "Tile cells", "tileCells", true, Toolbar);
Toolbar.add(Box.createHorizontalGlue());
}
JPanel formulaPanel = new JPanel();
formulaPanel.setPreferredSize(new Dimension(Integer.MAX_VALUE, 25));
formulaPanel.setBackground(Color.lightGray);
formulaPanel.setLayout(new BoxLayout(formulaPanel, BoxLayout.X_AXIS));
formulaPanel.setBorder(new EtchedBorder());
pane.add(formulaPanel);
pane.add(Box.createRigidArea(new Dimension(0, 6)));
if (!BugFix) {
FormulaAdd = addToolbarButton("add", "Add data",
"formulaAdd", true, formulaPanel);
FormulaDel = addToolbarButton("del", "Remove data",
"formulaDel", true, formulaPanel);
}
FormulaBox = new JComboBox();
formulaPanel.add(FormulaBox);
FormulaBox.setLightWeightPopupEnabled(false);
FormulaBox.setEditable(true);
FormulaEditor = FormulaBox.getEditor();
FormulaEditor.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String newItem = ((String) FormulaEditor.getItem()).trim();
try {
int id = 0;
int type = BasicSSCell.UNKNOWN_SOURCE;
boolean notify = true;
int index1 = newItem.indexOf("d", 2);
int index2 = newItem.indexOf(":");
if (index1 > 0 && index2 > 0 && index1 < index2) {
String cellName = newItem.substring(0, index1);
BasicSSCell ssCell = BasicSSCell.getSSCellByName(cellName);
int dataId = 0;
try {
dataId = Integer.parseInt(newItem.substring(index1 + 1, index2));
}
catch (NumberFormatException exc) {
if (BasicSSCell.DEBUG && BasicSSCell.DEBUG_LEVEL >= 3) {
exc.printStackTrace();
}
}
if (ssCell == DisplayCells[CurX][CurY] && dataId > 0) {
String varName = newItem.substring(0, index2);
String source = ssCell.getDataSource(varName);
if (source != null) {
ssCell.removeData(varName);
String oldItem = null;
for (int i=0; i<FormulaBox.getItemCount(); i++) {
String item = (String) FormulaBox.getItemAt(i);
if (item.startsWith(varName + ":")) {
oldItem = item;
break;
}
}
if (oldItem != null) {
FormulaBox.removeItem(oldItem);
}
}
id = dataId;
newItem = newItem.substring(index2 + 1).trim();
}
}
String varName = DisplayCells[CurX][CurY].addDataSource(
id, newItem, type, notify);
String itemString = varName + ": " + newItem;
FormulaBox.addItem(itemString);
FormulaBox.setSelectedItem(itemString);
if (!BugFix) FormulaAdd.requestFocus();
}
catch (VisADException exc) {
if (BasicSSCell.DEBUG) exc.printStackTrace();
}
catch (RemoteException exc) {
if (BasicSSCell.DEBUG) exc.printStackTrace();
}
}
});
JPanel horizShell = new JPanel();
horizShell.setBackground(Color.white);
horizShell.setLayout(new BoxLayout(horizShell, BoxLayout.X_AXIS));
horizShell.add(Box.createRigidArea(new Dimension(LABEL_WIDTH+6, 0)));
pane.add(horizShell);
HorizPanel = new JPanel() {
public Dimension getPreferredSize() {
Dimension d = super.getPreferredSize();
return new Dimension(d.width, LABEL_HEIGHT);
}
};
HorizPanel.setBackground(Color.white);
constructHorizontalLabels();
JViewport hl = new JViewport() {
public Dimension getMinimumSize() {
return new Dimension(0, LABEL_HEIGHT);
}
public Dimension getPreferredSize() {
return new Dimension(0, LABEL_HEIGHT);
}
public Dimension getMaximumSize() {
return new Dimension(Integer.MAX_VALUE, LABEL_HEIGHT);
}
};
HorizLabels = hl;
HorizLabels.setView(HorizPanel);
horizShell.add(HorizLabels);
horizShell.add(new JComponent() {
public Dimension getMinimumSize() {
return new Dimension(6 + SCPane.getVScrollbarWidth(), 0);
}
public Dimension getPreferredSize() {
return new Dimension(6 + SCPane.getVScrollbarWidth(), 0);
}
public Dimension getMaximumSize() {
return new Dimension(6 + SCPane.getVScrollbarWidth(), 0);
}
});
JPanel mainPanel = new JPanel();
mainPanel.setBackground(Color.white);
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.X_AXIS));
pane.add(mainPanel);
pane.add(Box.createRigidArea(new Dimension(0, 6)));
JPanel vertShell = new JPanel();
vertShell.setBackground(Color.white);
vertShell.setLayout(new BoxLayout(vertShell, BoxLayout.Y_AXIS));
mainPanel.add(Box.createRigidArea(new Dimension(6, 0)));
mainPanel.add(vertShell);
VertPanel = new JPanel() {
public Dimension getPreferredSize() {
Dimension d = super.getPreferredSize();
return new Dimension(LABEL_WIDTH, d.height);
}
};
VertPanel.setBackground(Color.white);
constructVerticalLabels();
JViewport vl = new JViewport() {
public Dimension getMinimumSize() {
return new Dimension(LABEL_WIDTH, 0);
}
public Dimension getPreferredSize() {
return new Dimension(LABEL_WIDTH, 0);
}
public Dimension getMaximumSize() {
return new Dimension(LABEL_WIDTH, Integer.MAX_VALUE);
}
};
VertLabels = vl;
VertLabels.setView(VertPanel);
vertShell.add(VertLabels);
vertShell.add(new JComponent() {
public Dimension getMinimumSize() {
return new Dimension(0, SCPane.getHScrollbarHeight());
}
public Dimension getPreferredSize() {
return new Dimension(0, SCPane.getHScrollbarHeight());
}
public Dimension getMaximumSize() {
return new Dimension(0, SCPane.getHScrollbarHeight());
}
});
ScrollPanel = new JPanel();
ScrollPanel.setBackground(Color.white);
ScrollPanel.setLayout(new BoxLayout(ScrollPanel, BoxLayout.X_AXIS));
mainPanel.add(ScrollPanel);
mainPanel.add(Box.createRigidArea(new Dimension(6, 0)));
SCPane = new ScrollPane(ScrollPane.SCROLLBARS_ALWAYS) {
public Dimension getPreferredSize() {
return new Dimension(0, 0);
}
};
Adjustable hadj = SCPane.getHAdjustable();
Adjustable vadj = SCPane.getVAdjustable();
hadj.setBlockIncrement(MIN_VIS_WIDTH);
hadj.setUnitIncrement(MIN_VIS_WIDTH/4);
hadj.addAdjustmentListener(this);
vadj.setBlockIncrement(MIN_VIS_HEIGHT);
vadj.setUnitIncrement(MIN_VIS_HEIGHT/4);
vadj.addAdjustmentListener(this);
ScrollPanel.add(SCPane);
DisplayPanel = new Panel();
DisplayPanel.setBackground(Color.darkGray);
SCPane.add(DisplayPanel);
addKeyListener(this);
SCPane.addKeyListener(this);
ScrollPanel.addKeyListener(this);
DisplayPanel.addKeyListener(this);
DataReferenceImpl lColRow = null;
if (server != null) {
boolean success = true;
boolean registryStarted = false;
while (true) {
try {
rsi = new RemoteServerImpl();
Naming.rebind("///" + server, rsi);
break;
}
catch (java.rmi.ConnectException exc) {
if (!registryStarted) {
try {
LocateRegistry.createRegistry(Registry.REGISTRY_PORT);
registryStarted = true;
}
catch (RemoteException rexc) {
if (BasicSSCell.DEBUG) exc.printStackTrace();
displayErrorMessage("Unable to autostart rmiregistry. " +
"Please start rmiregistry before launching the " +
"SpreadSheet in server mode", null,
"Failed to initialize RemoteServer");
success = false;
}
}
else {
displayErrorMessage("Unable to export cells as RMI addresses. " +
"Make sure you are running rmiregistry before launching the " +
"SpreadSheet in server mode", null,
"Failed to initialize RemoteServer");
success = false;
}
}
catch (MalformedURLException exc) {
if (BasicSSCell.DEBUG) exc.printStackTrace();
displayErrorMessage("Unable to export cells as RMI addresses. " +
"The name \"" + server + "\" is not valid", null,
"Failed to initialize RemoteServer");
success = false;
}
catch (RemoteException exc) {
if (BasicSSCell.DEBUG) exc.printStackTrace();
displayErrorMessage("Unable to export cells as RMI addresses", exc,
"Failed to initialize RemoteServer");
success = false;
}
if (!success) break;
}
try {
DataReferenceImpl lCanDo3D = new DataReferenceImpl("CanDo3D");
RemoteCanDo3D = new RemoteDataReferenceImpl(lCanDo3D);
RemoteCanDo3D.setData(new Real(CanDo3D ? 1 : 0));
rsi.addDataReference((RemoteDataReferenceImpl) RemoteCanDo3D);
lColRow = new DataReferenceImpl("ColRow");
RemoteColRow = new RemoteDataReferenceImpl(lColRow);
rsi.addDataReference((RemoteDataReferenceImpl) RemoteColRow);
}
catch (VisADException exc) {
if (BasicSSCell.DEBUG) exc.printStackTrace();
displayErrorMessage("Unable to export cells as RMI addresses. " +
"An error occurred setting up the necessary data", exc,
"Failed to initialize RemoteServer");
success = false;
}
catch (RemoteException exc) {
if (BasicSSCell.DEBUG) exc.printStackTrace();
displayErrorMessage("Unable to export cells as RMI addresses. " +
"A remote error occurred setting up the necessary data", exc,
"Failed to initialize RemoteServer");
success = false;
}
if (success) bTitle = bTitle + " (" + server + ")";
else rsi = null;
}
if (rs == null) constructSpreadsheetCells(null);
else {
NumVisX = cellNames.length;
NumVisY = cellNames[0].length;
reconstructLabels(cellNames, null, null);
constructSpreadsheetCells(cellNames, rs);
}
if (rsi != null) synchColRow();
CollabID = DisplayCells[0][0].getRemoteId();
if (rsi != null || IsRemote) {
final RemoteServer frs = rs;
CellImpl lColRowCell = new CellImpl() {
public void doAction() {
if (getColRowID() != CollabID) {
BasicSSCell.invoke(true, new Runnable() {
public void run() {
String[][] cellNamesx = getNewCellNames();
if (cellNamesx == null) {
if (BasicSSCell.DEBUG) System.out.println("Warning: " +
"could not obtain new spreadsheet dimensions!");
return;
}
int oldNVX = NumVisX;
int oldNVY = NumVisY;
NumVisX = cellNamesx.length;
NumVisY = cellNamesx[0].length;
if (NumVisX != oldNVX || NumVisY != oldNVY) {
reconstructSpreadsheet(cellNamesx, null, null, frs);
if (!IsRemote) synchColRow();
}
}
});
}
}
};
try {
RemoteCellImpl rColRowCell = new RemoteCellImpl(lColRowCell);
rColRowCell.addReference(RemoteColRow);
}
catch (VisADException exc) {
if (BasicSSCell.DEBUG) exc.printStackTrace();
}
catch (RemoteException exc) {
try {
lColRowCell.addReference(lColRow);
}
catch (VisADException exc2) {
if (BasicSSCell.DEBUG) exc2.printStackTrace();
}
catch (RemoteException exc2) {
if (BasicSSCell.DEBUG) exc2.printStackTrace();
}
}
}
setTitle(bTitle);
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
int appWidth = (int) (0.01 * sWidth * screenSize.width);
int appHeight = (int) (0.01 * sHeight * screenSize.height);
setSize(appWidth, appHeight);
Util.centerWindow(this);
setVisible(true);
snooze(500);
if (!BugFix) FormulaAdd.requestFocus();
tileCells();
}
|
public void Bid(Player bidder, String[] inputArgs) {
if (floAuction.allowBuyNow && inputArgs.length > 0) {
if (inputArgs[0].equalsIgnoreCase("buy")) {
if (buyNow == 0 || (currentBid != null && currentBid.getBidAmount() >= buyNow)) {
floAuction.sendMessage("bid-fail-buynow-expired", bidder, this, false);
} else {
inputArgs[0] = Long.toString(buyNow);
AuctionBid bid = new AuctionBid(this, bidder, inputArgs);
if (bid.getError() != null) {
failBid(bid, bid.getError());
return;
} else {
bid.raiseOwnBid(currentBid);
setNewBid(bid, null);
end();
}
}
return;
}
}
AuctionBid bid = new AuctionBid(this, bidder, inputArgs);
if (bid.getError() != null) {
failBid(bid, bid.getError());
return;
}
if (currentBid == null) {
if (bid.getBidAmount() < getStartingBid()) {
failBid(bid, "bid-fail-under-starting-bid");
return;
}
setNewBid(bid, "bid-success-no-challenger");
return;
}
long previousBidAmount = currentBid.getBidAmount();
long previousMaxBidAmount = currentBid.getMaxBidAmount();
if (currentBid.getBidder().equals(bidder.getName())) {
if (bid.raiseOwnBid(currentBid)) {
setNewBid(bid, "bid-success-update-own-bid");
} else {
if (previousMaxBidAmount < currentBid.getMaxBidAmount()) {
failBid(bid, "bid-success-update-own-maxbid");
} else {
failBid(bid, "bid-fail-already-current-bidder");
}
}
return;
}
AuctionBid winner = null;
AuctionBid loser = null;
if (floAuction.useOldBidLogic) {
if (bid.getMaxBidAmount() > currentBid.getMaxBidAmount()) {
winner = bid;
loser = currentBid;
} else {
winner = currentBid;
loser = bid;
}
winner.raiseBid(Math.max(winner.getBidAmount(), Math.min(winner.getMaxBidAmount(), loser.getBidAmount() + minBidIncrement)));
} else {
long baseBid = 0;
if (bid.getBidAmount() >= currentBid.getBidAmount() + minBidIncrement) {
baseBid = bid.getBidAmount();
} else {
baseBid = currentBid.getBidAmount() + minBidIncrement;
}
Integer prevSteps = (int) Math.floor((double)(currentBid.getMaxBidAmount() - baseBid + minBidIncrement) / minBidIncrement / 2);
Integer newSteps = (int) Math.floor((double)(bid.getMaxBidAmount() - baseBid) / minBidIncrement / 2);
if (newSteps >= prevSteps) {
winner = bid;
winner.raiseBid(baseBid + (Math.max(0, prevSteps) * minBidIncrement * 2));
loser = currentBid;
} else {
winner = currentBid;
winner.raiseBid(baseBid + (Math.max(0, newSteps + 1) * minBidIncrement * 2) - minBidIncrement);
loser = bid;
}
}
if (previousBidAmount <= winner.getBidAmount()) {
if (winner.equals(bid)) {
setNewBid(bid, "bid-success-outbid");
} else {
if (previousBidAmount < winner.getBidAmount()) {
if (!this.sealed && !floAuction.broadCastBidUpdates) floAuction.sendMessage("bid-auto-outbid", (CommandSender) null, this, true);
failBid(bid, "bid-fail-auto-outbid");
} else {
if (!this.sealed) floAuction.sendMessage("bid-fail-too-low", bid.getBidder(), this);
failBid(bid, null);
}
}
} else {
floAuction.sendMessage("bid-fail-too-low", bid.getBidder(), this);
}
}
| public void Bid(Player bidder, String[] inputArgs) {
if (floAuction.allowBuyNow && inputArgs.length > 0) {
if (inputArgs[0].equalsIgnoreCase("buy")) {
if (buyNow == 0 || (currentBid != null && currentBid.getBidAmount() >= buyNow)) {
floAuction.sendMessage("bid-fail-buynow-expired", bidder, this, false);
} else {
inputArgs[0] = Double.toString(functions.getUnsafeMoney(buyNow));
AuctionBid bid = new AuctionBid(this, bidder, inputArgs);
if (bid.getError() != null) {
failBid(bid, bid.getError());
return;
} else {
bid.raiseOwnBid(currentBid);
setNewBid(bid, null);
end();
}
}
return;
}
}
AuctionBid bid = new AuctionBid(this, bidder, inputArgs);
if (bid.getError() != null) {
failBid(bid, bid.getError());
return;
}
if (currentBid == null) {
if (bid.getBidAmount() < getStartingBid()) {
failBid(bid, "bid-fail-under-starting-bid");
return;
}
setNewBid(bid, "bid-success-no-challenger");
return;
}
long previousBidAmount = currentBid.getBidAmount();
long previousMaxBidAmount = currentBid.getMaxBidAmount();
if (currentBid.getBidder().equals(bidder.getName())) {
if (bid.raiseOwnBid(currentBid)) {
setNewBid(bid, "bid-success-update-own-bid");
} else {
if (previousMaxBidAmount < currentBid.getMaxBidAmount()) {
failBid(bid, "bid-success-update-own-maxbid");
} else {
failBid(bid, "bid-fail-already-current-bidder");
}
}
return;
}
AuctionBid winner = null;
AuctionBid loser = null;
if (floAuction.useOldBidLogic) {
if (bid.getMaxBidAmount() > currentBid.getMaxBidAmount()) {
winner = bid;
loser = currentBid;
} else {
winner = currentBid;
loser = bid;
}
winner.raiseBid(Math.max(winner.getBidAmount(), Math.min(winner.getMaxBidAmount(), loser.getBidAmount() + minBidIncrement)));
} else {
long baseBid = 0;
if (bid.getBidAmount() >= currentBid.getBidAmount() + minBidIncrement) {
baseBid = bid.getBidAmount();
} else {
baseBid = currentBid.getBidAmount() + minBidIncrement;
}
Integer prevSteps = (int) Math.floor((double)(currentBid.getMaxBidAmount() - baseBid + minBidIncrement) / minBidIncrement / 2);
Integer newSteps = (int) Math.floor((double)(bid.getMaxBidAmount() - baseBid) / minBidIncrement / 2);
if (newSteps >= prevSteps) {
winner = bid;
winner.raiseBid(baseBid + (Math.max(0, prevSteps) * minBidIncrement * 2));
loser = currentBid;
} else {
winner = currentBid;
winner.raiseBid(baseBid + (Math.max(0, newSteps + 1) * minBidIncrement * 2) - minBidIncrement);
loser = bid;
}
}
if (previousBidAmount <= winner.getBidAmount()) {
if (winner.equals(bid)) {
setNewBid(bid, "bid-success-outbid");
} else {
if (previousBidAmount < winner.getBidAmount()) {
if (!this.sealed && !floAuction.broadCastBidUpdates) floAuction.sendMessage("bid-auto-outbid", (CommandSender) null, this, true);
failBid(bid, "bid-fail-auto-outbid");
} else {
if (!this.sealed) floAuction.sendMessage("bid-fail-too-low", bid.getBidder(), this);
failBid(bid, null);
}
}
} else {
floAuction.sendMessage("bid-fail-too-low", bid.getBidder(), this);
}
}
|